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