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