RankingHelper.java revision 3fb989b1b6a11ee42cb27ecf5c8ea4e520ccb81a
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 static android.app.NotificationManager.IMPORTANCE_NONE;
19
20import com.android.internal.R;
21import com.android.internal.annotations.VisibleForTesting;
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.os.Build;
34import android.os.UserHandle;
35import android.provider.Settings;
36import android.service.notification.NotificationListenerService.Ranking;
37import android.text.TextUtils;
38import android.util.ArrayMap;
39import android.util.Slog;
40
41import org.json.JSONArray;
42import org.json.JSONException;
43import org.json.JSONObject;
44import org.xmlpull.v1.XmlPullParser;
45import org.xmlpull.v1.XmlPullParserException;
46import org.xmlpull.v1.XmlSerializer;
47
48import java.io.IOException;
49import java.io.PrintWriter;
50import java.util.ArrayList;
51import java.util.Collection;
52import java.util.Collections;
53import java.util.List;
54import java.util.Map;
55import java.util.Map.Entry;
56
57public class RankingHelper implements RankingConfig {
58    private static final String TAG = "RankingHelper";
59
60    private static final int XML_VERSION = 1;
61
62    private static final String TAG_RANKING = "ranking";
63    private static final String TAG_PACKAGE = "package";
64    private static final String TAG_CHANNEL = "channel";
65    private static final String TAG_GROUP = "channelGroup";
66
67    private static final String ATT_VERSION = "version";
68    private static final String ATT_NAME = "name";
69    private static final String ATT_NAME_RES_ID = "name_res_id";
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                                int groupNameRes = safeInt(parser, ATT_NAME_RES_ID, 0);
196                                if (!TextUtils.isEmpty(id)) {
197                                    NotificationChannelGroup group = null;
198                                    if (groupName != null) {
199                                        group = new NotificationChannelGroup(id, groupName);
200                                    } else {
201                                        group = new NotificationChannelGroup(id, groupNameRes);
202                                    }
203                                    r.groups.put(id, group);
204                                }
205                            }
206                            // Channels
207                            if (TAG_CHANNEL.equals(tagName)) {
208                                String id = parser.getAttributeValue(null, ATT_ID);
209                                CharSequence channelName = parser.getAttributeValue(null, ATT_NAME);
210                                int channelNameRes = safeInt(parser, ATT_NAME_RES_ID, 0);
211                                int channelImportance =
212                                        safeInt(parser, ATT_IMPORTANCE, DEFAULT_IMPORTANCE);
213
214                                if (!TextUtils.isEmpty(id)) {
215                                    NotificationChannel channel;
216                                    if (channelName != null) {
217                                        channel = new NotificationChannel(id, channelName,
218                                                channelImportance);
219                                    } else {
220                                        channel = new NotificationChannel(id, channelNameRes,
221                                                channelImportance);
222                                    }
223                                    channel.populateFromXml(parser);
224                                    r.channels.put(id, channel);
225                                }
226                            }
227                        }
228
229                        clampDefaultChannel(r);
230                    }
231                }
232            }
233        }
234        throw new IllegalStateException("Failed to reach END_DOCUMENT");
235    }
236
237    private static String recordKey(String pkg, int uid) {
238        return pkg + "|" + uid;
239    }
240
241    private Record getRecord(String pkg, int uid) {
242        final String key = recordKey(pkg, uid);
243        return mRecords.get(key);
244    }
245
246    private Record getOrCreateRecord(String pkg, int uid) {
247        return getOrCreateRecord(pkg, uid,
248                DEFAULT_IMPORTANCE, DEFAULT_PRIORITY, DEFAULT_VISIBILITY, DEFAULT_SHOW_BADGE);
249    }
250
251    private Record getOrCreateRecord(String pkg, int uid, int importance, int priority,
252            int visibility, boolean showBadge) {
253        final String key = recordKey(pkg, uid);
254        Record r = (uid == Record.UNKNOWN_UID) ? mRestoredWithoutUids.get(pkg) : mRecords.get(key);
255        if (r == null) {
256            r = new Record();
257            r.pkg = pkg;
258            r.uid = uid;
259            r.importance = importance;
260            r.priority = priority;
261            r.visibility = visibility;
262            r.showBadge = showBadge;
263            createDefaultChannelIfMissing(r);
264            if (r.uid == Record.UNKNOWN_UID) {
265                mRestoredWithoutUids.put(pkg, r);
266            } else {
267                mRecords.put(key, r);
268            }
269            clampDefaultChannel(r);
270        }
271        return r;
272    }
273
274    // Clamp the importance level of the default channel for apps targeting the new SDK version,
275    // unless the user has already changed the importance.
276    private void clampDefaultChannel(Record r) {
277        try {
278            if (r.uid != Record.UNKNOWN_UID) {
279                int userId = UserHandle.getUserId(r.uid);
280                final ApplicationInfo applicationInfo =
281                        mPm.getApplicationInfoAsUser(r.pkg, 0, userId);
282                if (applicationInfo.targetSdkVersion > Build.VERSION_CODES.N_MR1) {
283                    final NotificationChannel defaultChannel =
284                            r.channels.get(NotificationChannel.DEFAULT_CHANNEL_ID);
285                    if ((defaultChannel.getUserLockedFields()
286                            & NotificationChannel.USER_LOCKED_IMPORTANCE) == 0) {
287                        defaultChannel.setImportance(NotificationManager.IMPORTANCE_LOW);
288                        updateConfig();
289                    }
290                }
291            }
292        } catch (NameNotFoundException e) {
293            // oh well.
294        }
295    }
296
297    private void createDefaultChannelIfMissing(Record r) {
298        if (!r.channels.containsKey(NotificationChannel.DEFAULT_CHANNEL_ID)) {
299            NotificationChannel channel;
300            channel = new NotificationChannel(
301                    NotificationChannel.DEFAULT_CHANNEL_ID,
302                    R.string.default_notification_channel_label,
303                    r.importance);
304            channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX);
305            channel.setLockscreenVisibility(r.visibility);
306            if (r.importance != NotificationManager.IMPORTANCE_UNSPECIFIED) {
307                channel.lockFields(NotificationChannel.USER_LOCKED_IMPORTANCE);
308            }
309            if (r.priority != DEFAULT_PRIORITY) {
310                channel.lockFields(NotificationChannel.USER_LOCKED_PRIORITY);
311            }
312            if (r.visibility != DEFAULT_VISIBILITY) {
313                channel.lockFields(NotificationChannel.USER_LOCKED_VISIBILITY);
314            }
315            r.channels.put(channel.getId(), channel);
316        }
317    }
318
319    public void writeXml(XmlSerializer out, boolean forBackup) throws IOException {
320        out.startTag(null, TAG_RANKING);
321        out.attribute(null, ATT_VERSION, Integer.toString(XML_VERSION));
322
323        final int N = mRecords.size();
324        for (int i = 0; i < N; i++) {
325            final Record r = mRecords.valueAt(i);
326            //TODO: http://b/22388012
327            if (forBackup && UserHandle.getUserId(r.uid) != UserHandle.USER_SYSTEM) {
328                continue;
329            }
330            final boolean hasNonDefaultSettings = r.importance != DEFAULT_IMPORTANCE
331                    || r.priority != DEFAULT_PRIORITY || r.visibility != DEFAULT_VISIBILITY
332                    || r.showBadge != DEFAULT_SHOW_BADGE || r.channels.size() > 0
333                    || r.groups.size() > 0;
334            if (hasNonDefaultSettings) {
335                out.startTag(null, TAG_PACKAGE);
336                out.attribute(null, ATT_NAME, r.pkg);
337                if (r.importance != DEFAULT_IMPORTANCE) {
338                    out.attribute(null, ATT_IMPORTANCE, Integer.toString(r.importance));
339                }
340                if (r.priority != DEFAULT_PRIORITY) {
341                    out.attribute(null, ATT_PRIORITY, Integer.toString(r.priority));
342                }
343                if (r.visibility != DEFAULT_VISIBILITY) {
344                    out.attribute(null, ATT_VISIBILITY, Integer.toString(r.visibility));
345                }
346                out.attribute(null, ATT_SHOW_BADGE, Boolean.toString(r.showBadge));
347
348                if (!forBackup) {
349                    out.attribute(null, ATT_UID, Integer.toString(r.uid));
350                }
351
352                for (NotificationChannelGroup group : r.groups.values()) {
353                    group.writeXml(out);
354                }
355
356                for (NotificationChannel channel : r.channels.values()) {
357                    channel.writeXml(out);
358                }
359
360                out.endTag(null, TAG_PACKAGE);
361            }
362        }
363        out.endTag(null, TAG_RANKING);
364    }
365
366    private void updateConfig() {
367        final int N = mSignalExtractors.length;
368        for (int i = 0; i < N; i++) {
369            mSignalExtractors[i].setConfig(this);
370        }
371        mRankingHandler.requestSort(false);
372    }
373
374    public void sort(ArrayList<NotificationRecord> notificationList) {
375        final int N = notificationList.size();
376        // clear global sort keys
377        for (int i = N - 1; i >= 0; i--) {
378            notificationList.get(i).setGlobalSortKey(null);
379        }
380
381        // rank each record individually
382        Collections.sort(notificationList, mPreliminaryComparator);
383
384        synchronized (mProxyByGroupTmp) {
385            // record individual ranking result and nominate proxies for each group
386            for (int i = N - 1; i >= 0; i--) {
387                final NotificationRecord record = notificationList.get(i);
388                record.setAuthoritativeRank(i);
389                final String groupKey = record.getGroupKey();
390                NotificationRecord existingProxy = mProxyByGroupTmp.get(groupKey);
391                if (existingProxy == null
392                        || record.getImportance() > existingProxy.getImportance()) {
393                    mProxyByGroupTmp.put(groupKey, record);
394                }
395            }
396            // assign global sort key:
397            //   is_recently_intrusive:group_rank:is_group_summary:group_sort_key:rank
398            for (int i = 0; i < N; i++) {
399                final NotificationRecord record = notificationList.get(i);
400                NotificationRecord groupProxy = mProxyByGroupTmp.get(record.getGroupKey());
401                String groupSortKey = record.getNotification().getSortKey();
402
403                // We need to make sure the developer provided group sort key (gsk) is handled
404                // correctly:
405                //   gsk="" < gsk=non-null-string < gsk=null
406                //
407                // We enforce this by using different prefixes for these three cases.
408                String groupSortKeyPortion;
409                if (groupSortKey == null) {
410                    groupSortKeyPortion = "nsk";
411                } else if (groupSortKey.equals("")) {
412                    groupSortKeyPortion = "esk";
413                } else {
414                    groupSortKeyPortion = "gsk=" + groupSortKey;
415                }
416
417                boolean isGroupSummary = record.getNotification().isGroupSummary();
418                record.setGlobalSortKey(
419                        String.format("intrsv=%c:grnk=0x%04x:gsmry=%c:%s:rnk=0x%04x",
420                        record.isRecentlyIntrusive() ? '0' : '1',
421                        groupProxy.getAuthoritativeRank(),
422                        isGroupSummary ? '0' : '1',
423                        groupSortKeyPortion,
424                        record.getAuthoritativeRank()));
425            }
426            mProxyByGroupTmp.clear();
427        }
428
429        // Do a second ranking pass, using group proxies
430        Collections.sort(notificationList, mFinalComparator);
431    }
432
433    public int indexOf(ArrayList<NotificationRecord> notificationList, NotificationRecord target) {
434        return Collections.binarySearch(notificationList, target, mFinalComparator);
435    }
436
437    private static boolean safeBool(XmlPullParser parser, String att, boolean defValue) {
438        final String value = parser.getAttributeValue(null, att);
439        if (TextUtils.isEmpty(value)) return defValue;
440        return Boolean.parseBoolean(value);
441    }
442
443    private static int safeInt(XmlPullParser parser, String att, int defValue) {
444        final String val = parser.getAttributeValue(null, att);
445        return tryParseInt(val, defValue);
446    }
447
448    private static int tryParseInt(String value, int defValue) {
449        if (TextUtils.isEmpty(value)) return defValue;
450        try {
451            return Integer.parseInt(value);
452        } catch (NumberFormatException e) {
453            return defValue;
454        }
455    }
456
457    /**
458     * Gets importance.
459     */
460    @Override
461    public int getImportance(String packageName, int uid) {
462        return getOrCreateRecord(packageName, uid).importance;
463    }
464
465    @Override
466    public boolean canShowBadge(String packageName, int uid) {
467        return getOrCreateRecord(packageName, uid).showBadge;
468    }
469
470    @Override
471    public void setShowBadge(String packageName, int uid, boolean showBadge) {
472        getOrCreateRecord(packageName, uid).showBadge = showBadge;
473        updateConfig();
474    }
475
476    @Override
477    public void createNotificationChannelGroup(String pkg, int uid, NotificationChannelGroup group,
478            boolean fromTargetApp) {
479        Preconditions.checkNotNull(pkg);
480        Preconditions.checkNotNull(group);
481        Preconditions.checkNotNull(group.getId());
482        Preconditions.checkNotNull(!TextUtils.isEmpty(group.getName())
483                || group.getNameResId() != 0);
484        Record r = getOrCreateRecord(pkg, uid);
485        if (r == null) {
486            throw new IllegalArgumentException("Invalid package");
487        }
488        r.groups.put(group.getId(), group);
489        updateConfig();
490    }
491
492    @Override
493    public void createNotificationChannel(String pkg, int uid, NotificationChannel channel,
494            boolean fromTargetApp) {
495        Preconditions.checkNotNull(pkg);
496        Preconditions.checkNotNull(channel);
497        Preconditions.checkNotNull(channel.getId());
498        Preconditions.checkArgument(!TextUtils.isEmpty(channel.getName())
499                || channel.getNameResId() != 0);
500        Record r = getOrCreateRecord(pkg, uid);
501        if (r == null) {
502            throw new IllegalArgumentException("Invalid package");
503        }
504        if (IMPORTANCE_NONE == r.importance) {
505            throw new IllegalArgumentException("Package blocked");
506        }
507        if (channel.getGroup() != null && !r.groups.containsKey(channel.getGroup())) {
508            throw new IllegalArgumentException("NotificationChannelGroup doesn't exist");
509        }
510
511        NotificationChannel existing = r.channels.get(channel.getId());
512        // Keep existing settings
513        if (existing != null) {
514            if (existing.isDeleted()) {
515                existing.setDeleted(false);
516                updateConfig();
517            }
518            return;
519        }
520        if (channel.getImportance() < NotificationManager.IMPORTANCE_NONE
521                || channel.getImportance() > NotificationManager.IMPORTANCE_MAX) {
522            throw new IllegalArgumentException("Invalid importance level");
523        }
524        // Reset fields that apps aren't allowed to set.
525        if (fromTargetApp) {
526            channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX);
527            channel.setLockscreenVisibility(r.visibility);
528        }
529        clearLockedFields(channel);
530        if (channel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) {
531            channel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE);
532        }
533        if (!r.showBadge) {
534            channel.setShowBadge(false);
535        }
536        if (channel.getSound() == null) {
537            channel.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,
538                    Notification.AUDIO_ATTRIBUTES_DEFAULT);
539        }
540        r.channels.put(channel.getId(), channel);
541        updateConfig();
542    }
543
544    private void clearLockedFields(NotificationChannel channel) {
545        int clearMask = 0;
546        for (int i = 0; i < NotificationChannel.LOCKABLE_FIELDS.length; i++) {
547            clearMask |= NotificationChannel.LOCKABLE_FIELDS[i];
548        }
549        channel.lockFields(~clearMask);
550    }
551
552    @Override
553    public void updateNotificationChannel(String pkg, int uid, NotificationChannel updatedChannel) {
554        Preconditions.checkNotNull(updatedChannel);
555        Preconditions.checkNotNull(updatedChannel.getId());
556        Record r = getOrCreateRecord(pkg, uid);
557        if (r == null) {
558            throw new IllegalArgumentException("Invalid package");
559        }
560        NotificationChannel channel = r.channels.get(updatedChannel.getId());
561        if (channel == null || channel.isDeleted()) {
562            throw new IllegalArgumentException("Channel does not exist");
563        }
564        if (updatedChannel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) {
565            updatedChannel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE);
566        }
567        r.channels.put(updatedChannel.getId(), updatedChannel);
568        updateConfig();
569    }
570
571    @Override
572    public void updateNotificationChannelFromAssistant(String pkg, int uid,
573            NotificationChannel updatedChannel) {
574        Record r = getOrCreateRecord(pkg, uid);
575        if (r == null) {
576            throw new IllegalArgumentException("Invalid package");
577        }
578        NotificationChannel channel = r.channels.get(updatedChannel.getId());
579        if (channel == null || channel.isDeleted()) {
580            throw new IllegalArgumentException("Channel does not exist");
581        }
582
583        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_IMPORTANCE) == 0) {
584            channel.setImportance(updatedChannel.getImportance());
585        }
586        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_LIGHTS) == 0) {
587            channel.enableLights(updatedChannel.shouldShowLights());
588            channel.setLightColor(updatedChannel.getLightColor());
589        }
590        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_PRIORITY) == 0) {
591            channel.setBypassDnd(updatedChannel.canBypassDnd());
592        }
593        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_SOUND) == 0) {
594            channel.setSound(updatedChannel.getSound(), updatedChannel.getAudioAttributes());
595        }
596        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_VIBRATION) == 0) {
597            channel.enableVibration(updatedChannel.shouldVibrate());
598            channel.setVibrationPattern(updatedChannel.getVibrationPattern());
599        }
600        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_VISIBILITY) == 0) {
601            if (updatedChannel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) {
602                channel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE);
603            } else {
604                channel.setLockscreenVisibility(updatedChannel.getLockscreenVisibility());
605            }
606        }
607        if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_SHOW_BADGE) == 0) {
608            channel.setShowBadge(updatedChannel.canShowBadge());
609        }
610        if (updatedChannel.isDeleted()) {
611            channel.setDeleted(true);
612        }
613        // Assistant cannot change the group
614
615        r.channels.put(channel.getId(), channel);
616        updateConfig();
617    }
618
619    @Override
620    public NotificationChannel getNotificationChannelWithFallback(String pkg, int uid,
621            String channelId, boolean includeDeleted) {
622        Record r = getOrCreateRecord(pkg, uid);
623        if (channelId == null) {
624            channelId = NotificationChannel.DEFAULT_CHANNEL_ID;
625        }
626        NotificationChannel channel = r.channels.get(channelId);
627        if (channel != null && (includeDeleted || !channel.isDeleted())) {
628            return channel;
629        } else {
630            return r.channels.get(NotificationChannel.DEFAULT_CHANNEL_ID);
631        }
632    }
633
634    @Override
635    public NotificationChannel getNotificationChannel(String pkg, int uid, String channelId,
636            boolean includeDeleted) {
637        Preconditions.checkNotNull(pkg);
638        Record r = getOrCreateRecord(pkg, uid);
639        if (r == null) {
640            return null;
641        }
642        if (channelId == null) {
643            channelId = NotificationChannel.DEFAULT_CHANNEL_ID;
644        }
645        final NotificationChannel nc = r.channels.get(channelId);
646        if (nc != null && (includeDeleted || !nc.isDeleted())) {
647            return nc;
648        }
649        return null;
650    }
651
652    @Override
653    public void deleteNotificationChannel(String pkg, int uid, String channelId) {
654        Preconditions.checkNotNull(pkg);
655        Preconditions.checkNotNull(channelId);
656        Record r = getRecord(pkg, uid);
657        if (r == null) {
658            return;
659        }
660        NotificationChannel channel = r.channels.get(channelId);
661        if (channel != null) {
662            channel.setDeleted(true);
663        }
664    }
665
666    @Override
667    @VisibleForTesting
668    public void permanentlyDeleteNotificationChannel(String pkg, int uid, String channelId) {
669        Preconditions.checkNotNull(pkg);
670        Preconditions.checkNotNull(channelId);
671        Record r = getRecord(pkg, uid);
672        if (r == null) {
673            return;
674        }
675        r.channels.remove(channelId);
676    }
677
678    @Override
679    public void permanentlyDeleteNotificationChannels(String pkg, int uid) {
680        Preconditions.checkNotNull(pkg);
681        Record r = getRecord(pkg, uid);
682        if (r == null) {
683            return;
684        }
685        int N = r.channels.size() - 1;
686        for (int i = N; i >= 0; i--) {
687            String key = r.channels.keyAt(i);
688            if (!NotificationChannel.DEFAULT_CHANNEL_ID.equals(key)) {
689                r.channels.remove(key);
690            }
691        }
692    }
693
694    public NotificationChannelGroup getNotificationChannelGroup(String groupId, String pkg,
695            int uid) {
696        Preconditions.checkNotNull(pkg);
697        Record r = getRecord(pkg, uid);
698        return r.groups.get(groupId);
699    }
700
701    @Override
702    public ParceledListSlice<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
703            int uid, boolean includeDeleted) {
704        Preconditions.checkNotNull(pkg);
705        Map<String, NotificationChannelGroup> groups = new ArrayMap<>();
706        Record r = getRecord(pkg, uid);
707        if (r == null) {
708            return ParceledListSlice.emptyList();
709        }
710        NotificationChannelGroup nonGrouped = new NotificationChannelGroup(null, null);
711        int N = r.channels.size();
712        for (int i = 0; i < N; i++) {
713            final NotificationChannel nc = r.channels.valueAt(i);
714            if (includeDeleted || !nc.isDeleted()) {
715                if (nc.getGroup() != null) {
716                    NotificationChannelGroup ncg = groups.get(nc.getGroup());
717                    if (ncg == null ) {
718                        ncg = r.groups.get(nc.getGroup()).clone();
719                        groups.put(nc.getGroup(), ncg);
720                    }
721                    ncg.addChannel(nc);
722                } else {
723                    nonGrouped.addChannel(nc);
724                }
725            }
726        }
727        if (nonGrouped.getChannels().size() > 0) {
728            groups.put(null, nonGrouped);
729        }
730        return new ParceledListSlice<>(new ArrayList<>(groups.values()));
731    }
732
733    @Override
734    @VisibleForTesting
735    public Collection<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
736            int uid) {
737        Record r = getRecord(pkg, uid);
738        if (r == null) {
739            return new ArrayList<>();
740        }
741        return r.groups.values();
742    }
743
744    @Override
745    public ParceledListSlice<NotificationChannel> getNotificationChannels(String pkg, int uid,
746            boolean includeDeleted) {
747        Preconditions.checkNotNull(pkg);
748        List<NotificationChannel> channels = new ArrayList<>();
749        Record r = getRecord(pkg, uid);
750        if (r == null) {
751            return ParceledListSlice.emptyList();
752        }
753        int N = r.channels.size();
754        for (int i = 0; i < N; i++) {
755            final NotificationChannel nc = r.channels.valueAt(i);
756            if (includeDeleted || !nc.isDeleted()) {
757                channels.add(nc);
758            }
759        }
760        return new ParceledListSlice<>(channels);
761    }
762
763    /**
764     * Sets importance.
765     */
766    @Override
767    public void setImportance(String pkgName, int uid, int importance) {
768        getOrCreateRecord(pkgName, uid).importance = importance;
769        updateConfig();
770    }
771
772    public void setEnabled(String packageName, int uid, boolean enabled) {
773        boolean wasEnabled = getImportance(packageName, uid) != NotificationManager.IMPORTANCE_NONE;
774        if (wasEnabled == enabled) {
775            return;
776        }
777        setImportance(packageName, uid,
778                enabled ? DEFAULT_IMPORTANCE : NotificationManager.IMPORTANCE_NONE);
779    }
780
781    public void dump(PrintWriter pw, String prefix, NotificationManagerService.DumpFilter filter) {
782        if (filter == null) {
783            final int N = mSignalExtractors.length;
784            pw.print(prefix);
785            pw.print("mSignalExtractors.length = ");
786            pw.println(N);
787            for (int i = 0; i < N; i++) {
788                pw.print(prefix);
789                pw.print("  ");
790                pw.println(mSignalExtractors[i]);
791            }
792        }
793        if (filter == null) {
794            pw.print(prefix);
795            pw.println("per-package config:");
796        }
797        pw.println("Records:");
798        dumpRecords(pw, prefix, filter, mRecords);
799        pw.println("Restored without uid:");
800        dumpRecords(pw, prefix, filter, mRestoredWithoutUids);
801    }
802
803    private static void dumpRecords(PrintWriter pw, String prefix,
804            NotificationManagerService.DumpFilter filter, ArrayMap<String, Record> records) {
805        final int N = records.size();
806        for (int i = 0; i < N; i++) {
807            final Record r = records.valueAt(i);
808            if (filter == null || filter.matches(r.pkg)) {
809                pw.print(prefix);
810                pw.print("  AppSettings: ");
811                pw.print(r.pkg);
812                pw.print(" (");
813                pw.print(r.uid == Record.UNKNOWN_UID ? "UNKNOWN_UID" : Integer.toString(r.uid));
814                pw.print(')');
815                if (r.importance != DEFAULT_IMPORTANCE) {
816                    pw.print(" importance=");
817                    pw.print(Ranking.importanceToString(r.importance));
818                }
819                if (r.priority != DEFAULT_PRIORITY) {
820                    pw.print(" priority=");
821                    pw.print(Notification.priorityToString(r.priority));
822                }
823                if (r.visibility != DEFAULT_VISIBILITY) {
824                    pw.print(" visibility=");
825                    pw.print(Notification.visibilityToString(r.visibility));
826                }
827                pw.print(" showBadge=");
828                pw.print(Boolean.toString(r.showBadge));
829                pw.println();
830                for (NotificationChannel channel : r.channels.values()) {
831                    pw.print(prefix);
832                    pw.print("  ");
833                    pw.print("  ");
834                    pw.println(channel);
835                }
836                for (NotificationChannelGroup group : r.groups.values()) {
837                    pw.print(prefix);
838                    pw.print("  ");
839                    pw.print("  ");
840                    pw.println(group);
841                }
842            }
843        }
844    }
845
846    public JSONObject dumpJson(NotificationManagerService.DumpFilter filter) {
847        JSONObject ranking = new JSONObject();
848        JSONArray records = new JSONArray();
849        try {
850            ranking.put("noUid", mRestoredWithoutUids.size());
851        } catch (JSONException e) {
852           // pass
853        }
854        final int N = mRecords.size();
855        for (int i = 0; i < N; i++) {
856            final Record r = mRecords.valueAt(i);
857            if (filter == null || filter.matches(r.pkg)) {
858                JSONObject record = new JSONObject();
859                try {
860                    record.put("userId", UserHandle.getUserId(r.uid));
861                    record.put("packageName", r.pkg);
862                    if (r.importance != DEFAULT_IMPORTANCE) {
863                        record.put("importance", Ranking.importanceToString(r.importance));
864                    }
865                    if (r.priority != DEFAULT_PRIORITY) {
866                        record.put("priority", Notification.priorityToString(r.priority));
867                    }
868                    if (r.visibility != DEFAULT_VISIBILITY) {
869                        record.put("visibility", Notification.visibilityToString(r.visibility));
870                    }
871                    if (r.showBadge != DEFAULT_SHOW_BADGE) {
872                        record.put("showBadge", Boolean.valueOf(r.showBadge));
873                    }
874                    for (NotificationChannel channel : r.channels.values()) {
875                        record.put("channel", channel.toJson());
876                    }
877                    for (NotificationChannelGroup group : r.groups.values()) {
878                        record.put("group", group.toJson());
879                    }
880                } catch (JSONException e) {
881                   // pass
882                }
883                records.put(record);
884            }
885        }
886        try {
887            ranking.put("records", records);
888        } catch (JSONException e) {
889            // pass
890        }
891        return ranking;
892    }
893
894    /**
895     * Dump only the ban information as structured JSON for the stats collector.
896     *
897     * This is intentionally redundant with {#link dumpJson} because the old
898     * scraper will expect this format.
899     *
900     * @param filter
901     * @return
902     */
903    public JSONArray dumpBansJson(NotificationManagerService.DumpFilter filter) {
904        JSONArray bans = new JSONArray();
905        Map<Integer, String> packageBans = getPackageBans();
906        for(Entry<Integer, String> ban : packageBans.entrySet()) {
907            final int userId = UserHandle.getUserId(ban.getKey());
908            final String packageName = ban.getValue();
909            if (filter == null || filter.matches(packageName)) {
910                JSONObject banJson = new JSONObject();
911                try {
912                    banJson.put("userId", userId);
913                    banJson.put("packageName", packageName);
914                } catch (JSONException e) {
915                    e.printStackTrace();
916                }
917                bans.put(banJson);
918            }
919        }
920        return bans;
921    }
922
923    public Map<Integer, String> getPackageBans() {
924        final int N = mRecords.size();
925        ArrayMap<Integer, String> packageBans = new ArrayMap<>(N);
926        for (int i = 0; i < N; i++) {
927            final Record r = mRecords.valueAt(i);
928            if (r.importance == NotificationManager.IMPORTANCE_NONE) {
929                packageBans.put(r.uid, r.pkg);
930            }
931        }
932        return packageBans;
933    }
934
935    public void onPackagesChanged(boolean removingPackage, int changeUserId, String[] pkgList,
936            int[] uidList) {
937        if (pkgList == null || pkgList.length == 0) {
938            return; // nothing to do
939        }
940        boolean updated = false;
941        if (removingPackage) {
942            // Remove notification settings for uninstalled package
943            int size = Math.min(pkgList.length, uidList.length);
944            for (int i = 0; i < size; i++) {
945                final String pkg = pkgList[i];
946                final int uid = uidList[i];
947                mRecords.remove(recordKey(pkg, uid));
948                mRestoredWithoutUids.remove(pkg);
949                updated = true;
950            }
951        } else {
952            for (String pkg : pkgList) {
953                // Package install
954                final Record r = mRestoredWithoutUids.get(pkg);
955                if (r != null) {
956                    try {
957                        r.uid = mPm.getPackageUidAsUser(r.pkg, changeUserId);
958                        mRestoredWithoutUids.remove(pkg);
959                        mRecords.put(recordKey(r.pkg, r.uid), r);
960                        updated = true;
961                    } catch (NameNotFoundException e) {
962                        // noop
963                    }
964                }
965                // Package upgrade
966                try {
967                    Record fullRecord = getRecord(pkg,
968                            mPm.getPackageUidAsUser(pkg, changeUserId));
969                    if (fullRecord != null) {
970                        clampDefaultChannel(fullRecord);
971                    }
972                } catch (NameNotFoundException e) {
973                }
974            }
975        }
976
977        if (updated) {
978            updateConfig();
979        }
980    }
981
982    private static class Record {
983        static int UNKNOWN_UID = UserHandle.USER_NULL;
984
985        String pkg;
986        int uid = UNKNOWN_UID;
987        int importance = DEFAULT_IMPORTANCE;
988        int priority = DEFAULT_PRIORITY;
989        int visibility = DEFAULT_VISIBILITY;
990        boolean showBadge = DEFAULT_SHOW_BADGE;
991
992        ArrayMap<String, NotificationChannel> channels = new ArrayMap<>();
993        ArrayMap<String, NotificationChannelGroup> groups = new ArrayMap<>();
994   }
995}
996