RankingHelper.java revision 8e0eb372c9c5c941609daca554c92a44ee61c063
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                                CharSequence 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() != 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());
550
551            MetricsLogger.action(getChannelLog(channel, pkg));
552            updateConfig();
553            return;
554        }
555        if (channel.getImportance() < NotificationManager.IMPORTANCE_NONE
556                || channel.getImportance() > NotificationManager.IMPORTANCE_MAX) {
557            throw new IllegalArgumentException("Invalid importance level");
558        }
559        // Reset fields that apps aren't allowed to set.
560        if (fromTargetApp) {
561            channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX);
562            channel.setLockscreenVisibility(r.visibility);
563        }
564        clearLockedFields(channel);
565        if (channel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) {
566            channel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE);
567        }
568        if (!r.showBadge) {
569            channel.setShowBadge(false);
570        }
571        if (channel.getSound() == null) {
572            channel.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,
573                    Notification.AUDIO_ATTRIBUTES_DEFAULT);
574        }
575        r.channels.put(channel.getId(), channel);
576        MetricsLogger.action(getChannelLog(channel, pkg).setType(
577                MetricsProto.MetricsEvent.TYPE_OPEN));
578        updateConfig();
579    }
580
581    private void clearLockedFields(NotificationChannel channel) {
582        int clearMask = 0;
583        for (int i = 0; i < NotificationChannel.LOCKABLE_FIELDS.length; i++) {
584            clearMask |= NotificationChannel.LOCKABLE_FIELDS[i];
585        }
586        channel.lockFields(~clearMask);
587    }
588
589    @Override
590    public void updateNotificationChannel(String pkg, int uid, NotificationChannel updatedChannel) {
591        Preconditions.checkNotNull(updatedChannel);
592        Preconditions.checkNotNull(updatedChannel.getId());
593        Record r = getOrCreateRecord(pkg, uid);
594        if (r == null) {
595            throw new IllegalArgumentException("Invalid package");
596        }
597        NotificationChannel channel = r.channels.get(updatedChannel.getId());
598        if (channel == null || channel.isDeleted()) {
599            throw new IllegalArgumentException("Channel does not exist");
600        }
601        if (updatedChannel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) {
602            updatedChannel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE);
603        }
604        r.channels.put(updatedChannel.getId(), updatedChannel);
605
606        MetricsLogger.action(getChannelLog(updatedChannel, pkg));
607        updateConfig();
608    }
609
610    @Override
611    public void updateNotificationChannelFromAssistant(String pkg, int uid,
612            NotificationChannel updatedChannel) {
613        Record r = getOrCreateRecord(pkg, uid);
614        if (r == null) {
615            throw new IllegalArgumentException("Invalid package");
616        }
617        NotificationChannel channel = r.channels.get(updatedChannel.getId());
618        if (channel == null || channel.isDeleted()) {
619            throw new IllegalArgumentException("Channel does not exist");
620        }
621
622        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_IMPORTANCE) == 0) {
623            channel.setImportance(updatedChannel.getImportance());
624        }
625        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_LIGHTS) == 0) {
626            channel.enableLights(updatedChannel.shouldShowLights());
627            channel.setLightColor(updatedChannel.getLightColor());
628        }
629        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_PRIORITY) == 0) {
630            channel.setBypassDnd(updatedChannel.canBypassDnd());
631        }
632        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_SOUND) == 0) {
633            channel.setSound(updatedChannel.getSound(), updatedChannel.getAudioAttributes());
634        }
635        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_VIBRATION) == 0) {
636            channel.enableVibration(updatedChannel.shouldVibrate());
637            channel.setVibrationPattern(updatedChannel.getVibrationPattern());
638        }
639        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_VISIBILITY) == 0) {
640            if (updatedChannel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) {
641                channel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE);
642            } else {
643                channel.setLockscreenVisibility(updatedChannel.getLockscreenVisibility());
644            }
645        }
646        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_SHOW_BADGE) == 0) {
647            channel.setShowBadge(updatedChannel.canShowBadge());
648        }
649        if (updatedChannel.isDeleted()) {
650            channel.setDeleted(true);
651        }
652        // Assistant cannot change the group
653
654        MetricsLogger.action(getChannelLog(channel, pkg));
655        r.channels.put(channel.getId(), channel);
656        updateConfig();
657    }
658
659    @Override
660    public NotificationChannel getNotificationChannel(String pkg, int uid, String channelId,
661            boolean includeDeleted) {
662        Preconditions.checkNotNull(pkg);
663        Record r = getOrCreateRecord(pkg, uid);
664        if (r == null) {
665            return null;
666        }
667        if (channelId == null) {
668            channelId = NotificationChannel.DEFAULT_CHANNEL_ID;
669        }
670        final NotificationChannel nc = r.channels.get(channelId);
671        if (nc != null && (includeDeleted || !nc.isDeleted())) {
672            return nc;
673        }
674        return null;
675    }
676
677    @Override
678    public void deleteNotificationChannel(String pkg, int uid, String channelId) {
679        Record r = getRecord(pkg, uid);
680        if (r == null) {
681            return;
682        }
683        NotificationChannel channel = r.channels.get(channelId);
684        if (channel != null) {
685            channel.setDeleted(true);
686            LogMaker lm = getChannelLog(channel, pkg);
687            lm.setType(MetricsProto.MetricsEvent.TYPE_CLOSE);
688            MetricsLogger.action(lm);
689            updateConfig();
690        }
691    }
692
693    @Override
694    @VisibleForTesting
695    public void permanentlyDeleteNotificationChannel(String pkg, int uid, String channelId) {
696        Preconditions.checkNotNull(pkg);
697        Preconditions.checkNotNull(channelId);
698        Record r = getRecord(pkg, uid);
699        if (r == null) {
700            return;
701        }
702        r.channels.remove(channelId);
703        updateConfig();
704    }
705
706    @Override
707    public void permanentlyDeleteNotificationChannels(String pkg, int uid) {
708        Preconditions.checkNotNull(pkg);
709        Record r = getRecord(pkg, uid);
710        if (r == null) {
711            return;
712        }
713        int N = r.channels.size() - 1;
714        for (int i = N; i >= 0; i--) {
715            String key = r.channels.keyAt(i);
716            if (!NotificationChannel.DEFAULT_CHANNEL_ID.equals(key)) {
717                r.channels.remove(key);
718            }
719        }
720        updateConfig();
721    }
722
723    public NotificationChannelGroup getNotificationChannelGroup(String groupId, String pkg,
724            int uid) {
725        Preconditions.checkNotNull(pkg);
726        Record r = getRecord(pkg, uid);
727        return r.groups.get(groupId);
728    }
729
730    @Override
731    public ParceledListSlice<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
732            int uid, boolean includeDeleted) {
733        Preconditions.checkNotNull(pkg);
734        Map<String, NotificationChannelGroup> groups = new ArrayMap<>();
735        Record r = getRecord(pkg, uid);
736        if (r == null) {
737            return ParceledListSlice.emptyList();
738        }
739        NotificationChannelGroup nonGrouped = new NotificationChannelGroup(null, null);
740        int N = r.channels.size();
741        for (int i = 0; i < N; i++) {
742            final NotificationChannel nc = r.channels.valueAt(i);
743            if (includeDeleted || !nc.isDeleted()) {
744                if (nc.getGroup() != null) {
745                    if (r.groups.get(nc.getGroup()) != null) {
746                        NotificationChannelGroup ncg = groups.get(nc.getGroup());
747                        if (ncg == null) {
748                            ncg = r.groups.get(nc.getGroup()).clone();
749                            groups.put(nc.getGroup(), ncg);
750
751                        }
752                        ncg.addChannel(nc);
753                    }
754                } else {
755                    nonGrouped.addChannel(nc);
756                }
757            }
758        }
759        if (nonGrouped.getChannels().size() > 0) {
760            groups.put(null, nonGrouped);
761        }
762        return new ParceledListSlice<>(new ArrayList<>(groups.values()));
763    }
764
765    public List<String> deleteNotificationChannelGroup(String pkg, int uid,
766            String groupId) {
767        List<String> deletedChannelIds = new ArrayList<>();
768        Record r = getRecord(pkg, uid);
769        if (r == null || TextUtils.isEmpty(groupId)) {
770            return deletedChannelIds;
771        }
772
773        r.groups.remove(groupId);
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 (groupId.equals(nc.getGroup())) {
779                nc.setDeleted(true);
780                deletedChannelIds.add(nc.getId());
781            }
782        }
783        updateConfig();
784        return deletedChannelIds;
785    }
786
787    @Override
788    public Collection<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
789            int uid) {
790        Record r = getRecord(pkg, uid);
791        if (r == null) {
792            return new ArrayList<>();
793        }
794        return r.groups.values();
795    }
796
797    @Override
798    public ParceledListSlice<NotificationChannel> getNotificationChannels(String pkg, int uid,
799            boolean includeDeleted) {
800        Preconditions.checkNotNull(pkg);
801        List<NotificationChannel> channels = new ArrayList<>();
802        Record r = getRecord(pkg, uid);
803        if (r == null) {
804            return ParceledListSlice.emptyList();
805        }
806        int N = r.channels.size();
807        for (int i = 0; i < N; i++) {
808            final NotificationChannel nc = r.channels.valueAt(i);
809            if (includeDeleted || !nc.isDeleted()) {
810                channels.add(nc);
811            }
812        }
813        return new ParceledListSlice<>(channels);
814    }
815
816    public int getDeletedChannelCount(String pkg, int uid) {
817        Preconditions.checkNotNull(pkg);
818        int deletedCount = 0;
819        Record r = getRecord(pkg, uid);
820        if (r == null) {
821            return deletedCount;
822        }
823        int N = r.channels.size();
824        for (int i = 0; i < N; i++) {
825            final NotificationChannel nc = r.channels.valueAt(i);
826            if (nc.isDeleted()) {
827                deletedCount++;
828            }
829        }
830        return deletedCount;
831    }
832
833    /**
834     * Sets importance.
835     */
836    @Override
837    public void setImportance(String pkgName, int uid, int importance) {
838        getOrCreateRecord(pkgName, uid).importance = importance;
839        updateConfig();
840    }
841
842    public void setEnabled(String packageName, int uid, boolean enabled) {
843        boolean wasEnabled = getImportance(packageName, uid) != NotificationManager.IMPORTANCE_NONE;
844        if (wasEnabled == enabled) {
845            return;
846        }
847        setImportance(packageName, uid,
848                enabled ? DEFAULT_IMPORTANCE : NotificationManager.IMPORTANCE_NONE);
849    }
850
851    public void dump(PrintWriter pw, String prefix, NotificationManagerService.DumpFilter filter) {
852        if (filter == null) {
853            final int N = mSignalExtractors.length;
854            pw.print(prefix);
855            pw.print("mSignalExtractors.length = ");
856            pw.println(N);
857            for (int i = 0; i < N; i++) {
858                pw.print(prefix);
859                pw.print("  ");
860                pw.println(mSignalExtractors[i]);
861            }
862        }
863        if (filter == null) {
864            pw.print(prefix);
865            pw.println("per-package config:");
866        }
867        pw.println("Records:");
868        dumpRecords(pw, prefix, filter, mRecords);
869        pw.println("Restored without uid:");
870        dumpRecords(pw, prefix, filter, mRestoredWithoutUids);
871    }
872
873    private static void dumpRecords(PrintWriter pw, String prefix,
874            NotificationManagerService.DumpFilter filter, ArrayMap<String, Record> records) {
875        final int N = records.size();
876        for (int i = 0; i < N; i++) {
877            final Record r = records.valueAt(i);
878            if (filter == null || filter.matches(r.pkg)) {
879                pw.print(prefix);
880                pw.print("  AppSettings: ");
881                pw.print(r.pkg);
882                pw.print(" (");
883                pw.print(r.uid == Record.UNKNOWN_UID ? "UNKNOWN_UID" : Integer.toString(r.uid));
884                pw.print(')');
885                if (r.importance != DEFAULT_IMPORTANCE) {
886                    pw.print(" importance=");
887                    pw.print(Ranking.importanceToString(r.importance));
888                }
889                if (r.priority != DEFAULT_PRIORITY) {
890                    pw.print(" priority=");
891                    pw.print(Notification.priorityToString(r.priority));
892                }
893                if (r.visibility != DEFAULT_VISIBILITY) {
894                    pw.print(" visibility=");
895                    pw.print(Notification.visibilityToString(r.visibility));
896                }
897                pw.print(" showBadge=");
898                pw.print(Boolean.toString(r.showBadge));
899                pw.println();
900                for (NotificationChannel channel : r.channels.values()) {
901                    pw.print(prefix);
902                    pw.print("  ");
903                    pw.print("  ");
904                    pw.println(channel);
905                }
906                for (NotificationChannelGroup group : r.groups.values()) {
907                    pw.print(prefix);
908                    pw.print("  ");
909                    pw.print("  ");
910                    pw.println(group);
911                }
912            }
913        }
914    }
915
916    public JSONObject dumpJson(NotificationManagerService.DumpFilter filter) {
917        JSONObject ranking = new JSONObject();
918        JSONArray records = new JSONArray();
919        try {
920            ranking.put("noUid", mRestoredWithoutUids.size());
921        } catch (JSONException e) {
922           // pass
923        }
924        final int N = mRecords.size();
925        for (int i = 0; i < N; i++) {
926            final Record r = mRecords.valueAt(i);
927            if (filter == null || filter.matches(r.pkg)) {
928                JSONObject record = new JSONObject();
929                try {
930                    record.put("userId", UserHandle.getUserId(r.uid));
931                    record.put("packageName", r.pkg);
932                    if (r.importance != DEFAULT_IMPORTANCE) {
933                        record.put("importance", Ranking.importanceToString(r.importance));
934                    }
935                    if (r.priority != DEFAULT_PRIORITY) {
936                        record.put("priority", Notification.priorityToString(r.priority));
937                    }
938                    if (r.visibility != DEFAULT_VISIBILITY) {
939                        record.put("visibility", Notification.visibilityToString(r.visibility));
940                    }
941                    if (r.showBadge != DEFAULT_SHOW_BADGE) {
942                        record.put("showBadge", Boolean.valueOf(r.showBadge));
943                    }
944                    for (NotificationChannel channel : r.channels.values()) {
945                        record.put("channel", channel.toJson());
946                    }
947                    for (NotificationChannelGroup group : r.groups.values()) {
948                        record.put("group", group.toJson());
949                    }
950                } catch (JSONException e) {
951                   // pass
952                }
953                records.put(record);
954            }
955        }
956        try {
957            ranking.put("records", records);
958        } catch (JSONException e) {
959            // pass
960        }
961        return ranking;
962    }
963
964    /**
965     * Dump only the ban information as structured JSON for the stats collector.
966     *
967     * This is intentionally redundant with {#link dumpJson} because the old
968     * scraper will expect this format.
969     *
970     * @param filter
971     * @return
972     */
973    public JSONArray dumpBansJson(NotificationManagerService.DumpFilter filter) {
974        JSONArray bans = new JSONArray();
975        Map<Integer, String> packageBans = getPackageBans();
976        for(Entry<Integer, String> ban : packageBans.entrySet()) {
977            final int userId = UserHandle.getUserId(ban.getKey());
978            final String packageName = ban.getValue();
979            if (filter == null || filter.matches(packageName)) {
980                JSONObject banJson = new JSONObject();
981                try {
982                    banJson.put("userId", userId);
983                    banJson.put("packageName", packageName);
984                } catch (JSONException e) {
985                    e.printStackTrace();
986                }
987                bans.put(banJson);
988            }
989        }
990        return bans;
991    }
992
993    public Map<Integer, String> getPackageBans() {
994        final int N = mRecords.size();
995        ArrayMap<Integer, String> packageBans = new ArrayMap<>(N);
996        for (int i = 0; i < N; i++) {
997            final Record r = mRecords.valueAt(i);
998            if (r.importance == NotificationManager.IMPORTANCE_NONE) {
999                packageBans.put(r.uid, r.pkg);
1000            }
1001        }
1002        return packageBans;
1003    }
1004
1005    /**
1006     * Dump only the channel information as structured JSON for the stats collector.
1007     *
1008     * This is intentionally redundant with {#link dumpJson} because the old
1009     * scraper will expect this format.
1010     *
1011     * @param filter
1012     * @return
1013     */
1014    public JSONArray dumpChannelsJson(NotificationManagerService.DumpFilter filter) {
1015        JSONArray channels = new JSONArray();
1016        Map<String, Integer> packageChannels = getPackageChannels();
1017        for(Entry<String, Integer> channelCount : packageChannels.entrySet()) {
1018            final String packageName = channelCount.getKey();
1019            if (filter == null || filter.matches(packageName)) {
1020                JSONObject channelCountJson = new JSONObject();
1021                try {
1022                    channelCountJson.put("packageName", packageName);
1023                    channelCountJson.put("channelCount", channelCount.getValue());
1024                } catch (JSONException e) {
1025                    e.printStackTrace();
1026                }
1027                channels.put(channelCountJson);
1028            }
1029        }
1030        return channels;
1031    }
1032
1033    private Map<String, Integer> getPackageChannels() {
1034        ArrayMap<String, Integer> packageChannels = new ArrayMap<>();
1035        for (int i = 0; i < mRecords.size(); i++) {
1036            final Record r = mRecords.valueAt(i);
1037            int channelCount = 0;
1038            for (int j = 0; j < r.channels.size();j++) {
1039                if (!r.channels.valueAt(j).isDeleted()) {
1040                    channelCount++;
1041                }
1042            }
1043            packageChannels.put(r.pkg, channelCount);
1044        }
1045        return packageChannels;
1046    }
1047
1048    public void onPackagesChanged(boolean removingPackage, int changeUserId, String[] pkgList,
1049            int[] uidList) {
1050        if (pkgList == null || pkgList.length == 0) {
1051            return; // nothing to do
1052        }
1053        boolean updated = false;
1054        if (removingPackage) {
1055            // Remove notification settings for uninstalled package
1056            int size = Math.min(pkgList.length, uidList.length);
1057            for (int i = 0; i < size; i++) {
1058                final String pkg = pkgList[i];
1059                final int uid = uidList[i];
1060                mRecords.remove(recordKey(pkg, uid));
1061                mRestoredWithoutUids.remove(pkg);
1062                updated = true;
1063            }
1064        } else {
1065            for (String pkg : pkgList) {
1066                // Package install
1067                final Record r = mRestoredWithoutUids.get(pkg);
1068                if (r != null) {
1069                    try {
1070                        r.uid = mPm.getPackageUidAsUser(r.pkg, changeUserId);
1071                        mRestoredWithoutUids.remove(pkg);
1072                        mRecords.put(recordKey(r.pkg, r.uid), r);
1073                        updated = true;
1074                    } catch (NameNotFoundException e) {
1075                        // noop
1076                    }
1077                }
1078                // Package upgrade
1079                try {
1080                    Record fullRecord = getRecord(pkg,
1081                            mPm.getPackageUidAsUser(pkg, changeUserId));
1082                    if (fullRecord != null) {
1083                        deleteDefaultChannelIfNeeded(fullRecord);
1084                    }
1085                } catch (NameNotFoundException e) {}
1086            }
1087        }
1088
1089        if (updated) {
1090            updateConfig();
1091        }
1092    }
1093
1094    private LogMaker getChannelLog(NotificationChannel channel, String pkg) {
1095        return new LogMaker(MetricsProto.MetricsEvent.ACTION_NOTIFICATION_CHANNEL)
1096                .setType(MetricsProto.MetricsEvent.TYPE_UPDATE)
1097                .setPackageName(pkg)
1098                .addTaggedData(MetricsProto.MetricsEvent.FIELD_NOTIFICATION_CHANNEL_ID,
1099                        channel.getId())
1100                .addTaggedData(MetricsProto.MetricsEvent.FIELD_NOTIFICATION_CHANNEL_IMPORTANCE,
1101                        channel.getImportance());
1102    }
1103
1104    private static class Record {
1105        static int UNKNOWN_UID = UserHandle.USER_NULL;
1106
1107        String pkg;
1108        int uid = UNKNOWN_UID;
1109        int importance = DEFAULT_IMPORTANCE;
1110        int priority = DEFAULT_PRIORITY;
1111        int visibility = DEFAULT_VISIBILITY;
1112        boolean showBadge = DEFAULT_SHOW_BADGE;
1113
1114        ArrayMap<String, NotificationChannel> channels = new ArrayMap<>();
1115        ArrayMap<String, NotificationChannelGroup> groups = new ArrayMap<>();
1116   }
1117}
1118