RankingHelper.java revision 3a2ac3e11b336deb272e733dbdfc08317ce78b31
1/**
2 * Copyright (c) 2014, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.server.notification;
17
18import com.android.internal.R;
19import com.android.internal.annotations.VisibleForTesting;
20import com.android.internal.logging.MetricsLogger;
21import com.android.internal.logging.nano.MetricsProto;
22import com.android.internal.util.Preconditions;
23
24import android.app.Notification;
25import android.app.NotificationChannel;
26import android.app.NotificationChannelGroup;
27import android.app.NotificationManager;
28import android.content.Context;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.PackageManager;
31import android.content.pm.PackageManager.NameNotFoundException;
32import android.content.pm.ParceledListSlice;
33import android.metrics.LogMaker;
34import android.os.Build;
35import android.os.UserHandle;
36import android.provider.Settings.Secure;
37import android.service.notification.NotificationListenerService.Ranking;
38import android.text.TextUtils;
39import android.util.ArrayMap;
40import android.util.Slog;
41import android.util.SparseBooleanArray;
42
43import org.json.JSONArray;
44import org.json.JSONException;
45import org.json.JSONObject;
46import org.xmlpull.v1.XmlPullParser;
47import org.xmlpull.v1.XmlPullParserException;
48import org.xmlpull.v1.XmlSerializer;
49
50import java.io.IOException;
51import java.io.PrintWriter;
52import java.util.ArrayList;
53import java.util.Arrays;
54import java.util.Collection;
55import java.util.Collections;
56import java.util.List;
57import java.util.Map;
58import java.util.Map.Entry;
59import java.util.Objects;
60
61public class RankingHelper implements RankingConfig {
62    private static final String TAG = "RankingHelper";
63
64    private static final int XML_VERSION = 1;
65
66    private static final String TAG_RANKING = "ranking";
67    private static final String TAG_PACKAGE = "package";
68    private static final String TAG_CHANNEL = "channel";
69    private static final String TAG_GROUP = "channelGroup";
70
71    private static final String ATT_VERSION = "version";
72    private static final String ATT_NAME = "name";
73    private static final String ATT_UID = "uid";
74    private static final String ATT_ID = "id";
75    private static final String ATT_PRIORITY = "priority";
76    private static final String ATT_VISIBILITY = "visibility";
77    private static final String ATT_IMPORTANCE = "importance";
78    private static final String ATT_SHOW_BADGE = "show_badge";
79
80    private static final int DEFAULT_PRIORITY = Notification.PRIORITY_DEFAULT;
81    private static final int DEFAULT_VISIBILITY = NotificationManager.VISIBILITY_NO_OVERRIDE;
82    private static final int DEFAULT_IMPORTANCE = NotificationManager.IMPORTANCE_UNSPECIFIED;
83    private static final boolean DEFAULT_SHOW_BADGE = true;
84
85    private final NotificationSignalExtractor[] mSignalExtractors;
86    private final NotificationComparator mPreliminaryComparator;
87    private final GlobalSortKeyComparator mFinalComparator = new GlobalSortKeyComparator();
88
89    private final ArrayMap<String, Record> mRecords = new ArrayMap<>(); // pkg|uid => Record
90    private final ArrayMap<String, NotificationRecord> mProxyByGroupTmp = new ArrayMap<>();
91    private final ArrayMap<String, Record> mRestoredWithoutUids = new ArrayMap<>(); // pkg => Record
92
93    private final Context mContext;
94    private final RankingHandler mRankingHandler;
95    private final PackageManager mPm;
96    private SparseBooleanArray mBadgingEnabled;
97
98    public RankingHelper(Context context, PackageManager pm, RankingHandler rankingHandler,
99            NotificationUsageStats usageStats, String[] extractorNames) {
100        mContext = context;
101        mRankingHandler = rankingHandler;
102        mPm = pm;
103
104        mPreliminaryComparator = new NotificationComparator(mContext);
105
106        updateBadgingEnabled();
107
108        final int N = extractorNames.length;
109        mSignalExtractors = new NotificationSignalExtractor[N];
110        for (int i = 0; i < N; i++) {
111            try {
112                Class<?> extractorClass = mContext.getClassLoader().loadClass(extractorNames[i]);
113                NotificationSignalExtractor extractor =
114                        (NotificationSignalExtractor) extractorClass.newInstance();
115                extractor.initialize(mContext, usageStats);
116                extractor.setConfig(this);
117                mSignalExtractors[i] = extractor;
118            } catch (ClassNotFoundException e) {
119                Slog.w(TAG, "Couldn't find extractor " + extractorNames[i] + ".", e);
120            } catch (InstantiationException e) {
121                Slog.w(TAG, "Couldn't instantiate extractor " + extractorNames[i] + ".", e);
122            } catch (IllegalAccessException e) {
123                Slog.w(TAG, "Problem accessing extractor " + extractorNames[i] + ".", e);
124            }
125        }
126    }
127
128    @SuppressWarnings("unchecked")
129    public <T extends NotificationSignalExtractor> T findExtractor(Class<T> extractorClass) {
130        final int N = mSignalExtractors.length;
131        for (int i = 0; i < N; i++) {
132            final NotificationSignalExtractor extractor = mSignalExtractors[i];
133            if (extractorClass.equals(extractor.getClass())) {
134                return (T) extractor;
135            }
136        }
137        return null;
138    }
139
140    public void extractSignals(NotificationRecord r) {
141        final int N = mSignalExtractors.length;
142        for (int i = 0; i < N; i++) {
143            NotificationSignalExtractor extractor = mSignalExtractors[i];
144            try {
145                RankingReconsideration recon = extractor.process(r);
146                if (recon != null) {
147                    mRankingHandler.requestReconsideration(recon);
148                }
149            } catch (Throwable t) {
150                Slog.w(TAG, "NotificationSignalExtractor failed.", t);
151            }
152        }
153    }
154
155    public void readXml(XmlPullParser parser, boolean forRestore)
156            throws XmlPullParserException, IOException {
157        int type = parser.getEventType();
158        if (type != XmlPullParser.START_TAG) return;
159        String tag = parser.getName();
160        if (!TAG_RANKING.equals(tag)) return;
161        // Clobber groups and channels with the xml, but don't delete other data that wasn't present
162        // at the time of serialization.
163        mRestoredWithoutUids.clear();
164        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
165            tag = parser.getName();
166            if (type == XmlPullParser.END_TAG && TAG_RANKING.equals(tag)) {
167                return;
168            }
169            if (type == XmlPullParser.START_TAG) {
170                if (TAG_PACKAGE.equals(tag)) {
171                    int uid = safeInt(parser, ATT_UID, Record.UNKNOWN_UID);
172                    String name = parser.getAttributeValue(null, ATT_NAME);
173                    if (!TextUtils.isEmpty(name)) {
174                        if (forRestore) {
175                            try {
176                                //TODO: http://b/22388012
177                                uid = mPm.getPackageUidAsUser(name, UserHandle.USER_SYSTEM);
178                            } catch (NameNotFoundException e) {
179                                // noop
180                            }
181                        }
182
183                        Record r = getOrCreateRecord(name, uid,
184                                safeInt(parser, ATT_IMPORTANCE, DEFAULT_IMPORTANCE),
185                                safeInt(parser, ATT_PRIORITY, DEFAULT_PRIORITY),
186                                safeInt(parser, ATT_VISIBILITY, DEFAULT_VISIBILITY),
187                                safeBool(parser, ATT_SHOW_BADGE, DEFAULT_SHOW_BADGE));
188                        r.importance = safeInt(parser, ATT_IMPORTANCE, DEFAULT_IMPORTANCE);
189                        r.priority = safeInt(parser, ATT_PRIORITY, DEFAULT_PRIORITY);
190                        r.visibility = safeInt(parser, ATT_VISIBILITY, DEFAULT_VISIBILITY);
191                        r.showBadge = safeBool(parser, ATT_SHOW_BADGE, DEFAULT_SHOW_BADGE);
192
193                        final int innerDepth = parser.getDepth();
194                        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
195                                && (type != XmlPullParser.END_TAG
196                                || parser.getDepth() > innerDepth)) {
197                            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
198                                continue;
199                            }
200
201                            String tagName = parser.getName();
202                            // Channel groups
203                            if (TAG_GROUP.equals(tagName)) {
204                                String id = parser.getAttributeValue(null, ATT_ID);
205                                CharSequence groupName = parser.getAttributeValue(null, ATT_NAME);
206                                if (!TextUtils.isEmpty(id)) {
207                                    NotificationChannelGroup group
208                                            = new NotificationChannelGroup(id, groupName);
209                                    r.groups.put(id, group);
210                                }
211                            }
212                            // Channels
213                            if (TAG_CHANNEL.equals(tagName)) {
214                                String id = parser.getAttributeValue(null, ATT_ID);
215                                String channelName = parser.getAttributeValue(null, ATT_NAME);
216                                int channelImportance =
217                                        safeInt(parser, ATT_IMPORTANCE, DEFAULT_IMPORTANCE);
218                                if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(channelName)) {
219                                    NotificationChannel channel = new NotificationChannel(id,
220                                            channelName, channelImportance);
221                                    channel.populateFromXml(parser);
222                                    r.channels.put(id, channel);
223                                }
224                            }
225                        }
226
227                        try {
228                            deleteDefaultChannelIfNeeded(r);
229                        } catch (NameNotFoundException e) {
230                            Slog.e(TAG, "deleteDefaultChannelIfNeeded - Exception: " + e);
231                        }
232                    }
233                }
234            }
235        }
236        throw new IllegalStateException("Failed to reach END_DOCUMENT");
237    }
238
239    private static String recordKey(String pkg, int uid) {
240        return pkg + "|" + uid;
241    }
242
243    private Record getRecord(String pkg, int uid) {
244        final String key = recordKey(pkg, uid);
245        synchronized (mRecords) {
246            return mRecords.get(key);
247        }
248    }
249
250    private Record getOrCreateRecord(String pkg, int uid) {
251        return getOrCreateRecord(pkg, uid,
252                DEFAULT_IMPORTANCE, DEFAULT_PRIORITY, DEFAULT_VISIBILITY, DEFAULT_SHOW_BADGE);
253    }
254
255    private Record getOrCreateRecord(String pkg, int uid, int importance, int priority,
256            int visibility, boolean showBadge) {
257        final String key = recordKey(pkg, uid);
258        synchronized (mRecords) {
259            Record r = (uid == Record.UNKNOWN_UID) ? mRestoredWithoutUids.get(pkg) : mRecords.get(
260                    key);
261            if (r == null) {
262                r = new Record();
263                r.pkg = pkg;
264                r.uid = uid;
265                r.importance = importance;
266                r.priority = priority;
267                r.visibility = visibility;
268                r.showBadge = showBadge;
269
270                try {
271                    createDefaultChannelIfNeeded(r);
272                } catch (NameNotFoundException e) {
273                    Slog.e(TAG, "createDefaultChannelIfNeeded - Exception: " + e);
274                }
275
276                if (r.uid == Record.UNKNOWN_UID) {
277                    mRestoredWithoutUids.put(pkg, r);
278                } else {
279                    mRecords.put(key, r);
280                }
281            }
282            return r;
283        }
284    }
285
286    private boolean shouldHaveDefaultChannel(Record r) throws NameNotFoundException {
287        final int userId = UserHandle.getUserId(r.uid);
288        final ApplicationInfo applicationInfo = mPm.getApplicationInfoAsUser(r.pkg, 0, userId);
289        if (applicationInfo.targetSdkVersion >= Build.VERSION_CODES.O) {
290            // O apps should not have the default channel.
291            return false;
292        }
293
294        // Otherwise, this app should have the default channel.
295        return true;
296    }
297
298    private void deleteDefaultChannelIfNeeded(Record r) throws NameNotFoundException {
299        if (!r.channels.containsKey(NotificationChannel.DEFAULT_CHANNEL_ID)) {
300            // Not present
301            return;
302        }
303
304        if (shouldHaveDefaultChannel(r)) {
305            // Keep the default channel until upgraded.
306            return;
307        }
308
309        // Remove Default Channel.
310        r.channels.remove(NotificationChannel.DEFAULT_CHANNEL_ID);
311    }
312
313    private void createDefaultChannelIfNeeded(Record r) throws NameNotFoundException {
314        if (r.channels.containsKey(NotificationChannel.DEFAULT_CHANNEL_ID)) {
315            r.channels.get(NotificationChannel.DEFAULT_CHANNEL_ID).setName(
316                    mContext.getString(R.string.default_notification_channel_label));
317            return;
318        }
319
320        if (!shouldHaveDefaultChannel(r)) {
321            // Keep the default channel until upgraded.
322            return;
323        }
324
325        // Create Default Channel
326        NotificationChannel channel;
327        channel = new NotificationChannel(
328                NotificationChannel.DEFAULT_CHANNEL_ID,
329                mContext.getString(R.string.default_notification_channel_label),
330                r.importance);
331        channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX);
332        channel.setLockscreenVisibility(r.visibility);
333        if (r.importance != NotificationManager.IMPORTANCE_UNSPECIFIED) {
334            channel.lockFields(NotificationChannel.USER_LOCKED_IMPORTANCE);
335        }
336        if (r.priority != DEFAULT_PRIORITY) {
337            channel.lockFields(NotificationChannel.USER_LOCKED_PRIORITY);
338        }
339        if (r.visibility != DEFAULT_VISIBILITY) {
340            channel.lockFields(NotificationChannel.USER_LOCKED_VISIBILITY);
341        }
342        r.channels.put(channel.getId(), channel);
343    }
344
345    public void writeXml(XmlSerializer out, boolean forBackup) throws IOException {
346        out.startTag(null, TAG_RANKING);
347        out.attribute(null, ATT_VERSION, Integer.toString(XML_VERSION));
348
349        synchronized (mRecords) {
350            final int N = mRecords.size();
351            for (int i = 0; i < N; i++) {
352                final Record r = mRecords.valueAt(i);
353                //TODO: http://b/22388012
354                if (forBackup && UserHandle.getUserId(r.uid) != UserHandle.USER_SYSTEM) {
355                    continue;
356                }
357                final boolean hasNonDefaultSettings = r.importance != DEFAULT_IMPORTANCE
358                        || r.priority != DEFAULT_PRIORITY || r.visibility != DEFAULT_VISIBILITY
359                        || r.showBadge != DEFAULT_SHOW_BADGE || r.channels.size() > 0
360                        || r.groups.size() > 0;
361                if (hasNonDefaultSettings) {
362                    out.startTag(null, TAG_PACKAGE);
363                    out.attribute(null, ATT_NAME, r.pkg);
364                    if (r.importance != DEFAULT_IMPORTANCE) {
365                        out.attribute(null, ATT_IMPORTANCE, Integer.toString(r.importance));
366                    }
367                    if (r.priority != DEFAULT_PRIORITY) {
368                        out.attribute(null, ATT_PRIORITY, Integer.toString(r.priority));
369                    }
370                    if (r.visibility != DEFAULT_VISIBILITY) {
371                        out.attribute(null, ATT_VISIBILITY, Integer.toString(r.visibility));
372                    }
373                    out.attribute(null, ATT_SHOW_BADGE, Boolean.toString(r.showBadge));
374
375                    if (!forBackup) {
376                        out.attribute(null, ATT_UID, Integer.toString(r.uid));
377                    }
378
379                    for (NotificationChannelGroup group : r.groups.values()) {
380                        group.writeXml(out);
381                    }
382
383                    for (NotificationChannel channel : r.channels.values()) {
384                        if (!forBackup || (forBackup && !channel.isDeleted())) {
385                            channel.writeXml(out);
386                        }
387                    }
388
389                    out.endTag(null, TAG_PACKAGE);
390                }
391            }
392        }
393        out.endTag(null, TAG_RANKING);
394    }
395
396    private void updateConfig() {
397        final int N = mSignalExtractors.length;
398        for (int i = 0; i < N; i++) {
399            mSignalExtractors[i].setConfig(this);
400        }
401        mRankingHandler.requestSort(false);
402    }
403
404    public void sort(ArrayList<NotificationRecord> notificationList) {
405        final int N = notificationList.size();
406        // clear global sort keys
407        for (int i = N - 1; i >= 0; i--) {
408            notificationList.get(i).setGlobalSortKey(null);
409        }
410
411        // rank each record individually
412        Collections.sort(notificationList, mPreliminaryComparator);
413
414        synchronized (mProxyByGroupTmp) {
415            // record individual ranking result and nominate proxies for each group
416            for (int i = N - 1; i >= 0; i--) {
417                final NotificationRecord record = notificationList.get(i);
418                record.setAuthoritativeRank(i);
419                final String groupKey = record.getGroupKey();
420                NotificationRecord existingProxy = mProxyByGroupTmp.get(groupKey);
421                if (existingProxy == null
422                        || record.getImportance() > existingProxy.getImportance()) {
423                    mProxyByGroupTmp.put(groupKey, record);
424                }
425            }
426            // assign global sort key:
427            //   is_recently_intrusive:group_rank:is_group_summary:group_sort_key:rank
428            for (int i = 0; i < N; i++) {
429                final NotificationRecord record = notificationList.get(i);
430                NotificationRecord groupProxy = mProxyByGroupTmp.get(record.getGroupKey());
431                String groupSortKey = record.getNotification().getSortKey();
432
433                // We need to make sure the developer provided group sort key (gsk) is handled
434                // correctly:
435                //   gsk="" < gsk=non-null-string < gsk=null
436                //
437                // We enforce this by using different prefixes for these three cases.
438                String groupSortKeyPortion;
439                if (groupSortKey == null) {
440                    groupSortKeyPortion = "nsk";
441                } else if (groupSortKey.equals("")) {
442                    groupSortKeyPortion = "esk";
443                } else {
444                    groupSortKeyPortion = "gsk=" + groupSortKey;
445                }
446
447                boolean isGroupSummary = record.getNotification().isGroupSummary();
448                record.setGlobalSortKey(
449                        String.format("intrsv=%c:grnk=0x%04x:gsmry=%c:%s:rnk=0x%04x",
450                        record.isRecentlyIntrusive() ? '0' : '1',
451                        groupProxy.getAuthoritativeRank(),
452                        isGroupSummary ? '0' : '1',
453                        groupSortKeyPortion,
454                        record.getAuthoritativeRank()));
455            }
456            mProxyByGroupTmp.clear();
457        }
458
459        // Do a second ranking pass, using group proxies
460        Collections.sort(notificationList, mFinalComparator);
461    }
462
463    public int indexOf(ArrayList<NotificationRecord> notificationList, NotificationRecord target) {
464        return Collections.binarySearch(notificationList, target, mFinalComparator);
465    }
466
467    private static boolean safeBool(XmlPullParser parser, String att, boolean defValue) {
468        final String value = parser.getAttributeValue(null, att);
469        if (TextUtils.isEmpty(value)) return defValue;
470        return Boolean.parseBoolean(value);
471    }
472
473    private static int safeInt(XmlPullParser parser, String att, int defValue) {
474        final String val = parser.getAttributeValue(null, att);
475        return tryParseInt(val, defValue);
476    }
477
478    private static int tryParseInt(String value, int defValue) {
479        if (TextUtils.isEmpty(value)) return defValue;
480        try {
481            return Integer.parseInt(value);
482        } catch (NumberFormatException e) {
483            return defValue;
484        }
485    }
486
487    /**
488     * Gets importance.
489     */
490    @Override
491    public int getImportance(String packageName, int uid) {
492        return getOrCreateRecord(packageName, uid).importance;
493    }
494
495    @Override
496    public boolean canShowBadge(String packageName, int uid) {
497        return getOrCreateRecord(packageName, uid).showBadge;
498    }
499
500    @Override
501    public void setShowBadge(String packageName, int uid, boolean showBadge) {
502        getOrCreateRecord(packageName, uid).showBadge = showBadge;
503        updateConfig();
504    }
505
506    int getPackagePriority(String pkg, int uid) {
507        return getOrCreateRecord(pkg, uid).priority;
508    }
509
510    int getPackageVisibility(String pkg, int uid) {
511        return getOrCreateRecord(pkg, uid).visibility;
512    }
513
514    @Override
515    public void createNotificationChannelGroup(String pkg, int uid, NotificationChannelGroup group,
516            boolean fromTargetApp) {
517        Preconditions.checkNotNull(pkg);
518        Preconditions.checkNotNull(group);
519        Preconditions.checkNotNull(group.getId());
520        Preconditions.checkNotNull(!TextUtils.isEmpty(group.getName()));
521        Record r = getOrCreateRecord(pkg, uid);
522        if (r == null) {
523            throw new IllegalArgumentException("Invalid package");
524        }
525        LogMaker lm = new LogMaker(MetricsProto.MetricsEvent.ACTION_NOTIFICATION_CHANNEL_GROUP)
526                .setType(MetricsProto.MetricsEvent.TYPE_UPDATE)
527                .addTaggedData(MetricsProto.MetricsEvent.FIELD_NOTIFICATION_CHANNEL_GROUP_ID,
528                        group.getId())
529                .setPackageName(pkg);
530        MetricsLogger.action(lm);
531        r.groups.put(group.getId(), group);
532        updateConfig();
533    }
534
535    @Override
536    public void createNotificationChannel(String pkg, int uid, NotificationChannel channel,
537            boolean fromTargetApp) {
538        Preconditions.checkNotNull(pkg);
539        Preconditions.checkNotNull(channel);
540        Preconditions.checkNotNull(channel.getId());
541        Preconditions.checkArgument(!TextUtils.isEmpty(channel.getName()));
542        Record r = getOrCreateRecord(pkg, uid);
543        if (r == null) {
544            throw new IllegalArgumentException("Invalid package");
545        }
546        if (channel.getGroup() != null && !r.groups.containsKey(channel.getGroup())) {
547            throw new IllegalArgumentException("NotificationChannelGroup doesn't exist");
548        }
549        if (NotificationChannel.DEFAULT_CHANNEL_ID.equals(channel.getId())) {
550            throw new IllegalArgumentException("Reserved id");
551        }
552
553        NotificationChannel existing = r.channels.get(channel.getId());
554        // Keep most of the existing settings
555        if (existing != null && fromTargetApp) {
556            if (existing.isDeleted()) {
557                existing.setDeleted(false);
558            }
559
560            existing.setName(channel.getName().toString());
561            existing.setDescription(channel.getDescription());
562            existing.setBlockableSystem(channel.isBlockableSystem());
563
564            MetricsLogger.action(getChannelLog(channel, pkg));
565            updateConfig();
566            return;
567        }
568        if (channel.getImportance() < NotificationManager.IMPORTANCE_NONE
569                || channel.getImportance() > NotificationManager.IMPORTANCE_MAX) {
570            throw new IllegalArgumentException("Invalid importance level");
571        }
572        // Reset fields that apps aren't allowed to set.
573        if (fromTargetApp) {
574            channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX);
575            channel.setLockscreenVisibility(r.visibility);
576        }
577        clearLockedFields(channel);
578        if (channel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) {
579            channel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE);
580        }
581        if (!r.showBadge) {
582            channel.setShowBadge(false);
583        }
584        r.channels.put(channel.getId(), channel);
585        MetricsLogger.action(getChannelLog(channel, pkg).setType(
586                MetricsProto.MetricsEvent.TYPE_OPEN));
587        updateConfig();
588    }
589
590    void clearLockedFields(NotificationChannel channel) {
591        channel.unlockFields(channel.getUserLockedFields());
592    }
593
594    @Override
595    public void updateNotificationChannel(String pkg, int uid, NotificationChannel updatedChannel) {
596        Preconditions.checkNotNull(updatedChannel);
597        Preconditions.checkNotNull(updatedChannel.getId());
598        Record r = getOrCreateRecord(pkg, uid);
599        if (r == null) {
600            throw new IllegalArgumentException("Invalid package");
601        }
602        NotificationChannel channel = r.channels.get(updatedChannel.getId());
603        if (channel == null || channel.isDeleted()) {
604            throw new IllegalArgumentException("Channel does not exist");
605        }
606        if (updatedChannel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) {
607            updatedChannel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE);
608        }
609        lockFieldsForUpdate(channel, updatedChannel);
610        r.channels.put(updatedChannel.getId(), updatedChannel);
611
612        if (NotificationChannel.DEFAULT_CHANNEL_ID.equals(updatedChannel.getId())) {
613            // copy settings to app level so they are inherited by new channels
614            // when the app migrates
615            r.importance = updatedChannel.getImportance();
616            r.priority = updatedChannel.canBypassDnd()
617                    ? Notification.PRIORITY_MAX : Notification.PRIORITY_DEFAULT;
618            r.visibility = updatedChannel.getLockscreenVisibility();
619            r.showBadge = updatedChannel.canShowBadge();
620        }
621
622        MetricsLogger.action(getChannelLog(updatedChannel, pkg));
623        updateConfig();
624    }
625
626    @Override
627    public NotificationChannel getNotificationChannel(String pkg, int uid, String channelId,
628            boolean includeDeleted) {
629        Preconditions.checkNotNull(pkg);
630        Record r = getOrCreateRecord(pkg, uid);
631        if (r == null) {
632            return null;
633        }
634        if (channelId == null) {
635            channelId = NotificationChannel.DEFAULT_CHANNEL_ID;
636        }
637        final NotificationChannel nc = r.channels.get(channelId);
638        if (nc != null && (includeDeleted || !nc.isDeleted())) {
639            return nc;
640        }
641        return null;
642    }
643
644    @Override
645    public void deleteNotificationChannel(String pkg, int uid, String channelId) {
646        Record r = getRecord(pkg, uid);
647        if (r == null) {
648            return;
649        }
650        NotificationChannel channel = r.channels.get(channelId);
651        if (channel != null) {
652            channel.setDeleted(true);
653            LogMaker lm = getChannelLog(channel, pkg);
654            lm.setType(MetricsProto.MetricsEvent.TYPE_CLOSE);
655            MetricsLogger.action(lm);
656            updateConfig();
657        }
658    }
659
660    @Override
661    @VisibleForTesting
662    public void permanentlyDeleteNotificationChannel(String pkg, int uid, String channelId) {
663        Preconditions.checkNotNull(pkg);
664        Preconditions.checkNotNull(channelId);
665        Record r = getRecord(pkg, uid);
666        if (r == null) {
667            return;
668        }
669        r.channels.remove(channelId);
670        updateConfig();
671    }
672
673    @Override
674    public void permanentlyDeleteNotificationChannels(String pkg, int uid) {
675        Preconditions.checkNotNull(pkg);
676        Record r = getRecord(pkg, uid);
677        if (r == null) {
678            return;
679        }
680        int N = r.channels.size() - 1;
681        for (int i = N; i >= 0; i--) {
682            String key = r.channels.keyAt(i);
683            if (!NotificationChannel.DEFAULT_CHANNEL_ID.equals(key)) {
684                r.channels.remove(key);
685            }
686        }
687        updateConfig();
688    }
689
690    public NotificationChannelGroup getNotificationChannelGroup(String groupId, String pkg,
691            int uid) {
692        Preconditions.checkNotNull(pkg);
693        Record r = getRecord(pkg, uid);
694        return r.groups.get(groupId);
695    }
696
697    @Override
698    public ParceledListSlice<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
699            int uid, boolean includeDeleted) {
700        Preconditions.checkNotNull(pkg);
701        Map<String, NotificationChannelGroup> groups = new ArrayMap<>();
702        Record r = getRecord(pkg, uid);
703        if (r == null) {
704            return ParceledListSlice.emptyList();
705        }
706        NotificationChannelGroup nonGrouped = new NotificationChannelGroup(null, null);
707        int N = r.channels.size();
708        for (int i = 0; i < N; i++) {
709            final NotificationChannel nc = r.channels.valueAt(i);
710            if (includeDeleted || !nc.isDeleted()) {
711                if (nc.getGroup() != null) {
712                    if (r.groups.get(nc.getGroup()) != null) {
713                        NotificationChannelGroup ncg = groups.get(nc.getGroup());
714                        if (ncg == null) {
715                            ncg = r.groups.get(nc.getGroup()).clone();
716                            groups.put(nc.getGroup(), ncg);
717
718                        }
719                        ncg.addChannel(nc);
720                    }
721                } else {
722                    nonGrouped.addChannel(nc);
723                }
724            }
725        }
726        if (nonGrouped.getChannels().size() > 0) {
727            groups.put(null, nonGrouped);
728        }
729        return new ParceledListSlice<>(new ArrayList<>(groups.values()));
730    }
731
732    public List<NotificationChannel> deleteNotificationChannelGroup(String pkg, int uid,
733            String groupId) {
734        List<NotificationChannel> deletedChannels = new ArrayList<>();
735        Record r = getRecord(pkg, uid);
736        if (r == null || TextUtils.isEmpty(groupId)) {
737            return deletedChannels;
738        }
739
740        r.groups.remove(groupId);
741
742        int N = r.channels.size();
743        for (int i = 0; i < N; i++) {
744            final NotificationChannel nc = r.channels.valueAt(i);
745            if (groupId.equals(nc.getGroup())) {
746                nc.setDeleted(true);
747                deletedChannels.add(nc);
748            }
749        }
750        updateConfig();
751        return deletedChannels;
752    }
753
754    @Override
755    public Collection<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
756            int uid) {
757        Record r = getRecord(pkg, uid);
758        if (r == null) {
759            return new ArrayList<>();
760        }
761        return r.groups.values();
762    }
763
764    @Override
765    public ParceledListSlice<NotificationChannel> getNotificationChannels(String pkg, int uid,
766            boolean includeDeleted) {
767        Preconditions.checkNotNull(pkg);
768        List<NotificationChannel> channels = new ArrayList<>();
769        Record r = getRecord(pkg, uid);
770        if (r == null) {
771            return ParceledListSlice.emptyList();
772        }
773        int N = r.channels.size();
774        for (int i = 0; i < N; i++) {
775            final NotificationChannel nc = r.channels.valueAt(i);
776            if (includeDeleted || !nc.isDeleted()) {
777                channels.add(nc);
778            }
779        }
780        return new ParceledListSlice<>(channels);
781    }
782
783    /**
784     * True for pre-O apps that only have the default channel, or pre O apps that have no
785     * channels yet. This method will create the default channel for pre-O apps that don't have it.
786     * Should never be true for O+ targeting apps, but that's enforced on boot/when an app
787     * upgrades.
788     */
789    public boolean onlyHasDefaultChannel(String pkg, int uid) {
790        Record r = getOrCreateRecord(pkg, uid);
791        if (r.channels.size() == 1
792                && r.channels.containsKey(NotificationChannel.DEFAULT_CHANNEL_ID)) {
793            return true;
794        }
795        return false;
796    }
797
798    public int getDeletedChannelCount(String pkg, int uid) {
799        Preconditions.checkNotNull(pkg);
800        int deletedCount = 0;
801        Record r = getRecord(pkg, uid);
802        if (r == null) {
803            return deletedCount;
804        }
805        int N = r.channels.size();
806        for (int i = 0; i < N; i++) {
807            final NotificationChannel nc = r.channels.valueAt(i);
808            if (nc.isDeleted()) {
809                deletedCount++;
810            }
811        }
812        return deletedCount;
813    }
814
815    /**
816     * Sets importance.
817     */
818    @Override
819    public void setImportance(String pkgName, int uid, int importance) {
820        getOrCreateRecord(pkgName, uid).importance = importance;
821        updateConfig();
822    }
823
824    public void setEnabled(String packageName, int uid, boolean enabled) {
825        boolean wasEnabled = getImportance(packageName, uid) != NotificationManager.IMPORTANCE_NONE;
826        if (wasEnabled == enabled) {
827            return;
828        }
829        setImportance(packageName, uid,
830                enabled ? DEFAULT_IMPORTANCE : NotificationManager.IMPORTANCE_NONE);
831    }
832
833    @VisibleForTesting
834    void lockFieldsForUpdate(NotificationChannel original, NotificationChannel update) {
835        update.unlockFields(update.getUserLockedFields());
836        update.lockFields(original.getUserLockedFields());
837        if (original.canBypassDnd() != update.canBypassDnd()) {
838            update.lockFields(NotificationChannel.USER_LOCKED_PRIORITY);
839        }
840        if (original.getLockscreenVisibility() != update.getLockscreenVisibility()) {
841            update.lockFields(NotificationChannel.USER_LOCKED_VISIBILITY);
842        }
843        if (original.getImportance() != update.getImportance()) {
844            update.lockFields(NotificationChannel.USER_LOCKED_IMPORTANCE);
845        }
846        if (original.shouldShowLights() != update.shouldShowLights()
847                || original.getLightColor() != update.getLightColor()) {
848            update.lockFields(NotificationChannel.USER_LOCKED_LIGHTS);
849        }
850        if (!Objects.equals(original.getSound(), update.getSound())) {
851            update.lockFields(NotificationChannel.USER_LOCKED_SOUND);
852        }
853        if (!Arrays.equals(original.getVibrationPattern(), update.getVibrationPattern())
854                || original.shouldVibrate() != update.shouldVibrate()) {
855            update.lockFields(NotificationChannel.USER_LOCKED_VIBRATION);
856        }
857        if (original.canShowBadge() != update.canShowBadge()) {
858            update.lockFields(NotificationChannel.USER_LOCKED_SHOW_BADGE);
859        }
860    }
861
862    public void dump(PrintWriter pw, String prefix, NotificationManagerService.DumpFilter filter) {
863        if (filter == null) {
864            final int N = mSignalExtractors.length;
865            pw.print(prefix);
866            pw.print("mSignalExtractors.length = ");
867            pw.println(N);
868            for (int i = 0; i < N; i++) {
869                pw.print(prefix);
870                pw.print("  ");
871                pw.println(mSignalExtractors[i]);
872            }
873        }
874        if (filter == null) {
875            pw.print(prefix);
876            pw.println("per-package config:");
877        }
878        pw.println("Records:");
879        synchronized (mRecords) {
880            dumpRecords(pw, prefix, filter, mRecords);
881        }
882        pw.println("Restored without uid:");
883        dumpRecords(pw, prefix, filter, mRestoredWithoutUids);
884    }
885
886    private static void dumpRecords(PrintWriter pw, String prefix,
887            NotificationManagerService.DumpFilter filter, ArrayMap<String, Record> records) {
888        final int N = records.size();
889        for (int i = 0; i < N; i++) {
890            final Record r = records.valueAt(i);
891            if (filter == null || filter.matches(r.pkg)) {
892                pw.print(prefix);
893                pw.print("  AppSettings: ");
894                pw.print(r.pkg);
895                pw.print(" (");
896                pw.print(r.uid == Record.UNKNOWN_UID ? "UNKNOWN_UID" : Integer.toString(r.uid));
897                pw.print(')');
898                if (r.importance != DEFAULT_IMPORTANCE) {
899                    pw.print(" importance=");
900                    pw.print(Ranking.importanceToString(r.importance));
901                }
902                if (r.priority != DEFAULT_PRIORITY) {
903                    pw.print(" priority=");
904                    pw.print(Notification.priorityToString(r.priority));
905                }
906                if (r.visibility != DEFAULT_VISIBILITY) {
907                    pw.print(" visibility=");
908                    pw.print(Notification.visibilityToString(r.visibility));
909                }
910                pw.print(" showBadge=");
911                pw.print(Boolean.toString(r.showBadge));
912                pw.println();
913                for (NotificationChannel channel : r.channels.values()) {
914                    pw.print(prefix);
915                    pw.print("  ");
916                    pw.print("  ");
917                    pw.println(channel);
918                }
919                for (NotificationChannelGroup group : r.groups.values()) {
920                    pw.print(prefix);
921                    pw.print("  ");
922                    pw.print("  ");
923                    pw.println(group);
924                }
925            }
926        }
927    }
928
929    public JSONObject dumpJson(NotificationManagerService.DumpFilter filter) {
930        JSONObject ranking = new JSONObject();
931        JSONArray records = new JSONArray();
932        try {
933            ranking.put("noUid", mRestoredWithoutUids.size());
934        } catch (JSONException e) {
935           // pass
936        }
937        synchronized (mRecords) {
938            final int N = mRecords.size();
939            for (int i = 0; i < N; i++) {
940                final Record r = mRecords.valueAt(i);
941                if (filter == null || filter.matches(r.pkg)) {
942                    JSONObject record = new JSONObject();
943                    try {
944                        record.put("userId", UserHandle.getUserId(r.uid));
945                        record.put("packageName", r.pkg);
946                        if (r.importance != DEFAULT_IMPORTANCE) {
947                            record.put("importance", Ranking.importanceToString(r.importance));
948                        }
949                        if (r.priority != DEFAULT_PRIORITY) {
950                            record.put("priority", Notification.priorityToString(r.priority));
951                        }
952                        if (r.visibility != DEFAULT_VISIBILITY) {
953                            record.put("visibility", Notification.visibilityToString(r.visibility));
954                        }
955                        if (r.showBadge != DEFAULT_SHOW_BADGE) {
956                            record.put("showBadge", Boolean.valueOf(r.showBadge));
957                        }
958                        for (NotificationChannel channel : r.channels.values()) {
959                            record.put("channel", channel.toJson());
960                        }
961                        for (NotificationChannelGroup group : r.groups.values()) {
962                            record.put("group", group.toJson());
963                        }
964                    } catch (JSONException e) {
965                        // pass
966                    }
967                    records.put(record);
968                }
969            }
970        }
971        try {
972            ranking.put("records", records);
973        } catch (JSONException e) {
974            // pass
975        }
976        return ranking;
977    }
978
979    /**
980     * Dump only the ban information as structured JSON for the stats collector.
981     *
982     * This is intentionally redundant with {#link dumpJson} because the old
983     * scraper will expect this format.
984     *
985     * @param filter
986     * @return
987     */
988    public JSONArray dumpBansJson(NotificationManagerService.DumpFilter filter) {
989        JSONArray bans = new JSONArray();
990        Map<Integer, String> packageBans = getPackageBans();
991        for(Entry<Integer, String> ban : packageBans.entrySet()) {
992            final int userId = UserHandle.getUserId(ban.getKey());
993            final String packageName = ban.getValue();
994            if (filter == null || filter.matches(packageName)) {
995                JSONObject banJson = new JSONObject();
996                try {
997                    banJson.put("userId", userId);
998                    banJson.put("packageName", packageName);
999                } catch (JSONException e) {
1000                    e.printStackTrace();
1001                }
1002                bans.put(banJson);
1003            }
1004        }
1005        return bans;
1006    }
1007
1008    public Map<Integer, String> getPackageBans() {
1009        synchronized (mRecords) {
1010            final int N = mRecords.size();
1011            ArrayMap<Integer, String> packageBans = new ArrayMap<>(N);
1012            for (int i = 0; i < N; i++) {
1013                final Record r = mRecords.valueAt(i);
1014                if (r.importance == NotificationManager.IMPORTANCE_NONE) {
1015                    packageBans.put(r.uid, r.pkg);
1016                }
1017            }
1018
1019            return packageBans;
1020        }
1021    }
1022
1023    /**
1024     * Dump only the channel information as structured JSON for the stats collector.
1025     *
1026     * This is intentionally redundant with {#link dumpJson} because the old
1027     * scraper will expect this format.
1028     *
1029     * @param filter
1030     * @return
1031     */
1032    public JSONArray dumpChannelsJson(NotificationManagerService.DumpFilter filter) {
1033        JSONArray channels = new JSONArray();
1034        Map<String, Integer> packageChannels = getPackageChannels();
1035        for(Entry<String, Integer> channelCount : packageChannels.entrySet()) {
1036            final String packageName = channelCount.getKey();
1037            if (filter == null || filter.matches(packageName)) {
1038                JSONObject channelCountJson = new JSONObject();
1039                try {
1040                    channelCountJson.put("packageName", packageName);
1041                    channelCountJson.put("channelCount", channelCount.getValue());
1042                } catch (JSONException e) {
1043                    e.printStackTrace();
1044                }
1045                channels.put(channelCountJson);
1046            }
1047        }
1048        return channels;
1049    }
1050
1051    private Map<String, Integer> getPackageChannels() {
1052        ArrayMap<String, Integer> packageChannels = new ArrayMap<>();
1053        synchronized (mRecords) {
1054            for (int i = 0; i < mRecords.size(); i++) {
1055                final Record r = mRecords.valueAt(i);
1056                int channelCount = 0;
1057                for (int j = 0; j < r.channels.size(); j++) {
1058                    if (!r.channels.valueAt(j).isDeleted()) {
1059                        channelCount++;
1060                    }
1061                }
1062                packageChannels.put(r.pkg, channelCount);
1063            }
1064        }
1065        return packageChannels;
1066    }
1067
1068    public void onUserRemoved(int userId) {
1069        synchronized (mRecords) {
1070            int N = mRecords.size();
1071            for (int i = N - 1; i >= 0 ; i--) {
1072                Record record = mRecords.valueAt(i);
1073                if (UserHandle.getUserId(record.uid) == userId) {
1074                    mRecords.removeAt(i);
1075                }
1076            }
1077        }
1078    }
1079
1080    public void onPackagesChanged(boolean removingPackage, int changeUserId, String[] pkgList,
1081            int[] uidList) {
1082        if (pkgList == null || pkgList.length == 0) {
1083            return; // nothing to do
1084        }
1085        boolean updated = false;
1086        if (removingPackage) {
1087            // Remove notification settings for uninstalled package
1088            int size = Math.min(pkgList.length, uidList.length);
1089            for (int i = 0; i < size; i++) {
1090                final String pkg = pkgList[i];
1091                final int uid = uidList[i];
1092                synchronized (mRecords) {
1093                    mRecords.remove(recordKey(pkg, uid));
1094                }
1095                mRestoredWithoutUids.remove(pkg);
1096                updated = true;
1097            }
1098        } else {
1099            for (String pkg : pkgList) {
1100                // Package install
1101                final Record r = mRestoredWithoutUids.get(pkg);
1102                if (r != null) {
1103                    try {
1104                        r.uid = mPm.getPackageUidAsUser(r.pkg, changeUserId);
1105                        mRestoredWithoutUids.remove(pkg);
1106                        synchronized (mRecords) {
1107                            mRecords.put(recordKey(r.pkg, r.uid), r);
1108                        }
1109                        updated = true;
1110                    } catch (NameNotFoundException e) {
1111                        // noop
1112                    }
1113                }
1114                // Package upgrade
1115                try {
1116                    Record fullRecord = getRecord(pkg,
1117                            mPm.getPackageUidAsUser(pkg, changeUserId));
1118                    if (fullRecord != null) {
1119                        createDefaultChannelIfNeeded(fullRecord);
1120                        deleteDefaultChannelIfNeeded(fullRecord);
1121                    }
1122                } catch (NameNotFoundException e) {}
1123            }
1124        }
1125
1126        if (updated) {
1127            updateConfig();
1128        }
1129    }
1130
1131    private LogMaker getChannelLog(NotificationChannel channel, String pkg) {
1132        return new LogMaker(MetricsProto.MetricsEvent.ACTION_NOTIFICATION_CHANNEL)
1133                .setType(MetricsProto.MetricsEvent.TYPE_UPDATE)
1134                .setPackageName(pkg)
1135                .addTaggedData(MetricsProto.MetricsEvent.FIELD_NOTIFICATION_CHANNEL_ID,
1136                        channel.getId())
1137                .addTaggedData(MetricsProto.MetricsEvent.FIELD_NOTIFICATION_CHANNEL_IMPORTANCE,
1138                        channel.getImportance());
1139    }
1140
1141    public void updateBadgingEnabled() {
1142        if (mBadgingEnabled == null) {
1143            mBadgingEnabled = new SparseBooleanArray();
1144        }
1145        boolean changed = false;
1146        // update the cached values
1147        for (int index = 0; index < mBadgingEnabled.size(); index++) {
1148            int userId = mBadgingEnabled.keyAt(index);
1149            final boolean oldValue = mBadgingEnabled.get(userId);
1150            final boolean newValue = Secure.getIntForUser(mContext.getContentResolver(),
1151                    Secure.NOTIFICATION_BADGING,
1152                    DEFAULT_SHOW_BADGE ? 1 : 0, userId) != 0;
1153            mBadgingEnabled.put(userId, newValue);
1154            changed |= oldValue != newValue;
1155        }
1156        if (changed) {
1157            mRankingHandler.requestSort(false);
1158        }
1159    }
1160
1161    public boolean badgingEnabled(UserHandle userHandle) {
1162        int userId = userHandle.getIdentifier();
1163        if (userId == UserHandle.USER_ALL) {
1164            return false;
1165        }
1166        if (mBadgingEnabled.indexOfKey(userId) < 0) {
1167            mBadgingEnabled.put(userId,
1168                    Secure.getIntForUser(mContext.getContentResolver(),
1169                            Secure.NOTIFICATION_BADGING,
1170                            DEFAULT_SHOW_BADGE ? 1 : 0, userId) != 0);
1171        }
1172        return mBadgingEnabled.get(userId, DEFAULT_SHOW_BADGE);
1173    }
1174
1175
1176    private static class Record {
1177        static int UNKNOWN_UID = UserHandle.USER_NULL;
1178
1179        String pkg;
1180        int uid = UNKNOWN_UID;
1181        int importance = DEFAULT_IMPORTANCE;
1182        int priority = DEFAULT_PRIORITY;
1183        int visibility = DEFAULT_VISIBILITY;
1184        boolean showBadge = DEFAULT_SHOW_BADGE;
1185
1186        ArrayMap<String, NotificationChannel> channels = new ArrayMap<>();
1187        ArrayMap<String, NotificationChannelGroup> groups = new ArrayMap<>();
1188   }
1189}
1190