RankingHelper.java revision d5286843737e1117d5c6e90567fd7099a32c3a64
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 boolean isGroupSummary = record.getNotification().isGroupSummary(); 391 if (isGroupSummary || !mProxyByGroupTmp.containsKey(groupKey)) { 392 mProxyByGroupTmp.put(groupKey, record); 393 } 394 } 395 // assign global sort key: 396 // is_recently_intrusive:group_rank:is_group_summary:group_sort_key:rank 397 for (int i = 0; i < N; i++) { 398 final NotificationRecord record = notificationList.get(i); 399 NotificationRecord groupProxy = mProxyByGroupTmp.get(record.getGroupKey()); 400 String groupSortKey = record.getNotification().getSortKey(); 401 402 // We need to make sure the developer provided group sort key (gsk) is handled 403 // correctly: 404 // gsk="" < gsk=non-null-string < gsk=null 405 // 406 // We enforce this by using different prefixes for these three cases. 407 String groupSortKeyPortion; 408 if (groupSortKey == null) { 409 groupSortKeyPortion = "nsk"; 410 } else if (groupSortKey.equals("")) { 411 groupSortKeyPortion = "esk"; 412 } else { 413 groupSortKeyPortion = "gsk=" + groupSortKey; 414 } 415 416 boolean isGroupSummary = record.getNotification().isGroupSummary(); 417 record.setGlobalSortKey( 418 String.format("intrsv=%c:grnk=0x%04x:gsmry=%c:%s:rnk=0x%04x", 419 record.isRecentlyIntrusive() ? '0' : '1', 420 groupProxy.getAuthoritativeRank(), 421 isGroupSummary ? '0' : '1', 422 groupSortKeyPortion, 423 record.getAuthoritativeRank())); 424 } 425 mProxyByGroupTmp.clear(); 426 } 427 428 // Do a second ranking pass, using group proxies 429 Collections.sort(notificationList, mFinalComparator); 430 } 431 432 public int indexOf(ArrayList<NotificationRecord> notificationList, NotificationRecord target) { 433 return Collections.binarySearch(notificationList, target, mFinalComparator); 434 } 435 436 private static boolean safeBool(XmlPullParser parser, String att, boolean defValue) { 437 final String value = parser.getAttributeValue(null, att); 438 if (TextUtils.isEmpty(value)) return defValue; 439 return Boolean.parseBoolean(value); 440 } 441 442 private static int safeInt(XmlPullParser parser, String att, int defValue) { 443 final String val = parser.getAttributeValue(null, att); 444 return tryParseInt(val, defValue); 445 } 446 447 private static int tryParseInt(String value, int defValue) { 448 if (TextUtils.isEmpty(value)) return defValue; 449 try { 450 return Integer.parseInt(value); 451 } catch (NumberFormatException e) { 452 return defValue; 453 } 454 } 455 456 /** 457 * Gets importance. 458 */ 459 @Override 460 public int getImportance(String packageName, int uid) { 461 return getOrCreateRecord(packageName, uid).importance; 462 } 463 464 @Override 465 public boolean canShowBadge(String packageName, int uid) { 466 return getOrCreateRecord(packageName, uid).showBadge; 467 } 468 469 @Override 470 public void setShowBadge(String packageName, int uid, boolean showBadge) { 471 getOrCreateRecord(packageName, uid).showBadge = showBadge; 472 updateConfig(); 473 } 474 475 @Override 476 public void createNotificationChannelGroup(String pkg, int uid, NotificationChannelGroup group, 477 boolean fromTargetApp) { 478 Preconditions.checkNotNull(pkg); 479 Preconditions.checkNotNull(group); 480 Preconditions.checkNotNull(group.getId()); 481 Preconditions.checkNotNull(!TextUtils.isEmpty(group.getName()) 482 || group.getNameResId() != 0); 483 Record r = getOrCreateRecord(pkg, uid); 484 if (r == null) { 485 throw new IllegalArgumentException("Invalid package"); 486 } 487 r.groups.put(group.getId(), group); 488 updateConfig(); 489 } 490 491 @Override 492 public void createNotificationChannel(String pkg, int uid, NotificationChannel channel, 493 boolean fromTargetApp) { 494 Preconditions.checkNotNull(pkg); 495 Preconditions.checkNotNull(channel); 496 Preconditions.checkNotNull(channel.getId()); 497 Preconditions.checkArgument(!TextUtils.isEmpty(channel.getName()) 498 || channel.getNameResId() != 0); 499 Record r = getOrCreateRecord(pkg, uid); 500 if (r == null) { 501 throw new IllegalArgumentException("Invalid package"); 502 } 503 if (IMPORTANCE_NONE == r.importance) { 504 throw new IllegalArgumentException("Package blocked"); 505 } 506 if (channel.getGroup() != null && !r.groups.containsKey(channel.getGroup())) { 507 throw new IllegalArgumentException("NotificationChannelGroup doesn't exist"); 508 } 509 510 NotificationChannel existing = r.channels.get(channel.getId()); 511 // Keep existing settings 512 if (existing != null) { 513 if (existing.isDeleted()) { 514 existing.setDeleted(false); 515 updateConfig(); 516 } 517 return; 518 } 519 if (channel.getImportance() < NotificationManager.IMPORTANCE_NONE 520 || channel.getImportance() > NotificationManager.IMPORTANCE_MAX) { 521 throw new IllegalArgumentException("Invalid importance level"); 522 } 523 // Reset fields that apps aren't allowed to set. 524 if (fromTargetApp) { 525 channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX); 526 channel.setLockscreenVisibility(r.visibility); 527 } 528 clearLockedFields(channel); 529 if (channel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) { 530 channel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE); 531 } 532 if (!r.showBadge) { 533 channel.setShowBadge(false); 534 } 535 if (channel.getSound() == null) { 536 channel.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, 537 Notification.AUDIO_ATTRIBUTES_DEFAULT); 538 } 539 r.channels.put(channel.getId(), channel); 540 updateConfig(); 541 } 542 543 private void clearLockedFields(NotificationChannel channel) { 544 int clearMask = 0; 545 for (int i = 0; i < NotificationChannel.LOCKABLE_FIELDS.length; i++) { 546 clearMask |= NotificationChannel.LOCKABLE_FIELDS[i]; 547 } 548 channel.lockFields(~clearMask); 549 } 550 551 @Override 552 public void updateNotificationChannel(String pkg, int uid, NotificationChannel updatedChannel) { 553 Preconditions.checkNotNull(updatedChannel); 554 Preconditions.checkNotNull(updatedChannel.getId()); 555 Record r = getOrCreateRecord(pkg, uid); 556 if (r == null) { 557 throw new IllegalArgumentException("Invalid package"); 558 } 559 NotificationChannel channel = r.channels.get(updatedChannel.getId()); 560 if (channel == null || channel.isDeleted()) { 561 throw new IllegalArgumentException("Channel does not exist"); 562 } 563 if (updatedChannel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) { 564 updatedChannel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE); 565 } 566 r.channels.put(updatedChannel.getId(), updatedChannel); 567 updateConfig(); 568 } 569 570 @Override 571 public void updateNotificationChannelFromAssistant(String pkg, int uid, 572 NotificationChannel updatedChannel) { 573 Record r = getOrCreateRecord(pkg, uid); 574 if (r == null) { 575 throw new IllegalArgumentException("Invalid package"); 576 } 577 NotificationChannel channel = r.channels.get(updatedChannel.getId()); 578 if (channel == null || channel.isDeleted()) { 579 throw new IllegalArgumentException("Channel does not exist"); 580 } 581 582 if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_IMPORTANCE) == 0) { 583 channel.setImportance(updatedChannel.getImportance()); 584 } 585 if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_LIGHTS) == 0) { 586 channel.enableLights(updatedChannel.shouldShowLights()); 587 channel.setLightColor(updatedChannel.getLightColor()); 588 } 589 if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_PRIORITY) == 0) { 590 channel.setBypassDnd(updatedChannel.canBypassDnd()); 591 } 592 if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_SOUND) == 0) { 593 channel.setSound(updatedChannel.getSound(), updatedChannel.getAudioAttributes()); 594 } 595 if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_VIBRATION) == 0) { 596 channel.enableVibration(updatedChannel.shouldVibrate()); 597 channel.setVibrationPattern(updatedChannel.getVibrationPattern()); 598 } 599 if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_VISIBILITY) == 0) { 600 if (updatedChannel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) { 601 channel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE); 602 } else { 603 channel.setLockscreenVisibility(updatedChannel.getLockscreenVisibility()); 604 } 605 } 606 if ((channel.getUserLockedFields() & NotificationChannel.USER_LOCKED_SHOW_BADGE) == 0) { 607 channel.setShowBadge(updatedChannel.canShowBadge()); 608 } 609 if (updatedChannel.isDeleted()) { 610 channel.setDeleted(true); 611 } 612 // Assistant cannot change the group 613 614 r.channels.put(channel.getId(), channel); 615 updateConfig(); 616 } 617 618 @Override 619 public NotificationChannel getNotificationChannelWithFallback(String pkg, int uid, 620 String channelId, boolean includeDeleted) { 621 Record r = getOrCreateRecord(pkg, uid); 622 if (channelId == null) { 623 channelId = NotificationChannel.DEFAULT_CHANNEL_ID; 624 } 625 NotificationChannel channel = r.channels.get(channelId); 626 if (channel != null && (includeDeleted || !channel.isDeleted())) { 627 return channel; 628 } else { 629 return r.channels.get(NotificationChannel.DEFAULT_CHANNEL_ID); 630 } 631 } 632 633 @Override 634 public NotificationChannel getNotificationChannel(String pkg, int uid, String channelId, 635 boolean includeDeleted) { 636 Preconditions.checkNotNull(pkg); 637 Record r = getOrCreateRecord(pkg, uid); 638 if (r == null) { 639 return null; 640 } 641 if (channelId == null) { 642 channelId = NotificationChannel.DEFAULT_CHANNEL_ID; 643 } 644 final NotificationChannel nc = r.channels.get(channelId); 645 if (nc != null && (includeDeleted || !nc.isDeleted())) { 646 return nc; 647 } 648 return null; 649 } 650 651 @Override 652 public void deleteNotificationChannel(String pkg, int uid, String channelId) { 653 Preconditions.checkNotNull(pkg); 654 Preconditions.checkNotNull(channelId); 655 Record r = getRecord(pkg, uid); 656 if (r == null) { 657 return; 658 } 659 NotificationChannel channel = r.channels.get(channelId); 660 if (channel != null) { 661 channel.setDeleted(true); 662 } 663 } 664 665 @Override 666 @VisibleForTesting 667 public void permanentlyDeleteNotificationChannel(String pkg, int uid, String channelId) { 668 Preconditions.checkNotNull(pkg); 669 Preconditions.checkNotNull(channelId); 670 Record r = getRecord(pkg, uid); 671 if (r == null) { 672 return; 673 } 674 r.channels.remove(channelId); 675 } 676 677 @Override 678 public void permanentlyDeleteNotificationChannels(String pkg, int uid) { 679 Preconditions.checkNotNull(pkg); 680 Record r = getRecord(pkg, uid); 681 if (r == null) { 682 return; 683 } 684 int N = r.channels.size() - 1; 685 for (int i = N; i >= 0; i--) { 686 String key = r.channels.keyAt(i); 687 if (!NotificationChannel.DEFAULT_CHANNEL_ID.equals(key)) { 688 r.channels.remove(key); 689 } 690 } 691 } 692 693 public NotificationChannelGroup getNotificationChannelGroup(String groupId, String pkg, 694 int uid) { 695 Preconditions.checkNotNull(pkg); 696 Record r = getRecord(pkg, uid); 697 return r.groups.get(groupId); 698 } 699 700 @Override 701 public ParceledListSlice<NotificationChannelGroup> getNotificationChannelGroups(String pkg, 702 int uid, boolean includeDeleted) { 703 Preconditions.checkNotNull(pkg); 704 Map<String, NotificationChannelGroup> groups = new ArrayMap<>(); 705 Record r = getRecord(pkg, uid); 706 if (r == null) { 707 return ParceledListSlice.emptyList(); 708 } 709 NotificationChannelGroup nonGrouped = new NotificationChannelGroup(null, null); 710 int N = r.channels.size(); 711 for (int i = 0; i < N; i++) { 712 final NotificationChannel nc = r.channels.valueAt(i); 713 if (includeDeleted || !nc.isDeleted()) { 714 if (nc.getGroup() != null) { 715 NotificationChannelGroup ncg = groups.get(nc.getGroup()); 716 if (ncg == null ) { 717 ncg = r.groups.get(nc.getGroup()).clone(); 718 groups.put(nc.getGroup(), ncg); 719 } 720 ncg.addChannel(nc); 721 } else { 722 nonGrouped.addChannel(nc); 723 } 724 } 725 } 726 if (nonGrouped.getChannels().size() > 0) { 727 groups.put(null, nonGrouped); 728 } 729 return new ParceledListSlice<>(new ArrayList<>(groups.values())); 730 } 731 732 @Override 733 @VisibleForTesting 734 public Collection<NotificationChannelGroup> getNotificationChannelGroups(String pkg, 735 int uid) { 736 Record r = getRecord(pkg, uid); 737 if (r == null) { 738 return new ArrayList<>(); 739 } 740 return r.groups.values(); 741 } 742 743 @Override 744 public ParceledListSlice<NotificationChannel> getNotificationChannels(String pkg, int uid, 745 boolean includeDeleted) { 746 Preconditions.checkNotNull(pkg); 747 List<NotificationChannel> channels = new ArrayList<>(); 748 Record r = getRecord(pkg, uid); 749 if (r == null) { 750 return ParceledListSlice.emptyList(); 751 } 752 int N = r.channels.size(); 753 for (int i = 0; i < N; i++) { 754 final NotificationChannel nc = r.channels.valueAt(i); 755 if (includeDeleted || !nc.isDeleted()) { 756 channels.add(nc); 757 } 758 } 759 return new ParceledListSlice<>(channels); 760 } 761 762 /** 763 * Sets importance. 764 */ 765 @Override 766 public void setImportance(String pkgName, int uid, int importance) { 767 getOrCreateRecord(pkgName, uid).importance = importance; 768 updateConfig(); 769 } 770 771 public void setEnabled(String packageName, int uid, boolean enabled) { 772 boolean wasEnabled = getImportance(packageName, uid) != NotificationManager.IMPORTANCE_NONE; 773 if (wasEnabled == enabled) { 774 return; 775 } 776 setImportance(packageName, uid, 777 enabled ? DEFAULT_IMPORTANCE : NotificationManager.IMPORTANCE_NONE); 778 } 779 780 public void dump(PrintWriter pw, String prefix, NotificationManagerService.DumpFilter filter) { 781 if (filter == null) { 782 final int N = mSignalExtractors.length; 783 pw.print(prefix); 784 pw.print("mSignalExtractors.length = "); 785 pw.println(N); 786 for (int i = 0; i < N; i++) { 787 pw.print(prefix); 788 pw.print(" "); 789 pw.println(mSignalExtractors[i]); 790 } 791 } 792 if (filter == null) { 793 pw.print(prefix); 794 pw.println("per-package config:"); 795 } 796 pw.println("Records:"); 797 dumpRecords(pw, prefix, filter, mRecords); 798 pw.println("Restored without uid:"); 799 dumpRecords(pw, prefix, filter, mRestoredWithoutUids); 800 } 801 802 private static void dumpRecords(PrintWriter pw, String prefix, 803 NotificationManagerService.DumpFilter filter, ArrayMap<String, Record> records) { 804 final int N = records.size(); 805 for (int i = 0; i < N; i++) { 806 final Record r = records.valueAt(i); 807 if (filter == null || filter.matches(r.pkg)) { 808 pw.print(prefix); 809 pw.print(" AppSettings: "); 810 pw.print(r.pkg); 811 pw.print(" ("); 812 pw.print(r.uid == Record.UNKNOWN_UID ? "UNKNOWN_UID" : Integer.toString(r.uid)); 813 pw.print(')'); 814 if (r.importance != DEFAULT_IMPORTANCE) { 815 pw.print(" importance="); 816 pw.print(Ranking.importanceToString(r.importance)); 817 } 818 if (r.priority != DEFAULT_PRIORITY) { 819 pw.print(" priority="); 820 pw.print(Notification.priorityToString(r.priority)); 821 } 822 if (r.visibility != DEFAULT_VISIBILITY) { 823 pw.print(" visibility="); 824 pw.print(Notification.visibilityToString(r.visibility)); 825 } 826 pw.print(" showBadge="); 827 pw.print(Boolean.toString(r.showBadge)); 828 pw.println(); 829 for (NotificationChannel channel : r.channels.values()) { 830 pw.print(prefix); 831 pw.print(" "); 832 pw.print(" "); 833 pw.println(channel); 834 } 835 for (NotificationChannelGroup group : r.groups.values()) { 836 pw.print(prefix); 837 pw.print(" "); 838 pw.print(" "); 839 pw.println(group); 840 } 841 } 842 } 843 } 844 845 public JSONObject dumpJson(NotificationManagerService.DumpFilter filter) { 846 JSONObject ranking = new JSONObject(); 847 JSONArray records = new JSONArray(); 848 try { 849 ranking.put("noUid", mRestoredWithoutUids.size()); 850 } catch (JSONException e) { 851 // pass 852 } 853 final int N = mRecords.size(); 854 for (int i = 0; i < N; i++) { 855 final Record r = mRecords.valueAt(i); 856 if (filter == null || filter.matches(r.pkg)) { 857 JSONObject record = new JSONObject(); 858 try { 859 record.put("userId", UserHandle.getUserId(r.uid)); 860 record.put("packageName", r.pkg); 861 if (r.importance != DEFAULT_IMPORTANCE) { 862 record.put("importance", Ranking.importanceToString(r.importance)); 863 } 864 if (r.priority != DEFAULT_PRIORITY) { 865 record.put("priority", Notification.priorityToString(r.priority)); 866 } 867 if (r.visibility != DEFAULT_VISIBILITY) { 868 record.put("visibility", Notification.visibilityToString(r.visibility)); 869 } 870 if (r.showBadge != DEFAULT_SHOW_BADGE) { 871 record.put("showBadge", Boolean.valueOf(r.showBadge)); 872 } 873 for (NotificationChannel channel : r.channels.values()) { 874 record.put("channel", channel.toJson()); 875 } 876 for (NotificationChannelGroup group : r.groups.values()) { 877 record.put("group", group.toJson()); 878 } 879 } catch (JSONException e) { 880 // pass 881 } 882 records.put(record); 883 } 884 } 885 try { 886 ranking.put("records", records); 887 } catch (JSONException e) { 888 // pass 889 } 890 return ranking; 891 } 892 893 /** 894 * Dump only the ban information as structured JSON for the stats collector. 895 * 896 * This is intentionally redundant with {#link dumpJson} because the old 897 * scraper will expect this format. 898 * 899 * @param filter 900 * @return 901 */ 902 public JSONArray dumpBansJson(NotificationManagerService.DumpFilter filter) { 903 JSONArray bans = new JSONArray(); 904 Map<Integer, String> packageBans = getPackageBans(); 905 for(Entry<Integer, String> ban : packageBans.entrySet()) { 906 final int userId = UserHandle.getUserId(ban.getKey()); 907 final String packageName = ban.getValue(); 908 if (filter == null || filter.matches(packageName)) { 909 JSONObject banJson = new JSONObject(); 910 try { 911 banJson.put("userId", userId); 912 banJson.put("packageName", packageName); 913 } catch (JSONException e) { 914 e.printStackTrace(); 915 } 916 bans.put(banJson); 917 } 918 } 919 return bans; 920 } 921 922 public Map<Integer, String> getPackageBans() { 923 final int N = mRecords.size(); 924 ArrayMap<Integer, String> packageBans = new ArrayMap<>(N); 925 for (int i = 0; i < N; i++) { 926 final Record r = mRecords.valueAt(i); 927 if (r.importance == NotificationManager.IMPORTANCE_NONE) { 928 packageBans.put(r.uid, r.pkg); 929 } 930 } 931 return packageBans; 932 } 933 934 public void onPackagesChanged(boolean removingPackage, int changeUserId, String[] pkgList, 935 int[] uidList) { 936 if (pkgList == null || pkgList.length == 0) { 937 return; // nothing to do 938 } 939 boolean updated = false; 940 if (removingPackage) { 941 // Remove notification settings for uninstalled package 942 int size = Math.min(pkgList.length, uidList.length); 943 for (int i = 0; i < size; i++) { 944 final String pkg = pkgList[i]; 945 final int uid = uidList[i]; 946 mRecords.remove(recordKey(pkg, uid)); 947 mRestoredWithoutUids.remove(pkg); 948 updated = true; 949 } 950 } else { 951 for (String pkg : pkgList) { 952 // Package install 953 final Record r = mRestoredWithoutUids.get(pkg); 954 if (r != null) { 955 try { 956 r.uid = mPm.getPackageUidAsUser(r.pkg, changeUserId); 957 mRestoredWithoutUids.remove(pkg); 958 mRecords.put(recordKey(r.pkg, r.uid), r); 959 updated = true; 960 } catch (NameNotFoundException e) { 961 // noop 962 } 963 } 964 // Package upgrade 965 try { 966 Record fullRecord = getRecord(pkg, 967 mPm.getPackageUidAsUser(pkg, changeUserId)); 968 if (fullRecord != null) { 969 clampDefaultChannel(fullRecord); 970 } 971 } catch (NameNotFoundException e) { 972 } 973 } 974 } 975 976 if (updated) { 977 updateConfig(); 978 } 979 } 980 981 private static class Record { 982 static int UNKNOWN_UID = UserHandle.USER_NULL; 983 984 String pkg; 985 int uid = UNKNOWN_UID; 986 int importance = DEFAULT_IMPORTANCE; 987 int priority = DEFAULT_PRIORITY; 988 int visibility = DEFAULT_VISIBILITY; 989 boolean showBadge = DEFAULT_SHOW_BADGE; 990 991 ArrayMap<String, NotificationChannel> channels = new ArrayMap<>(); 992 ArrayMap<String, NotificationChannelGroup> groups = new ArrayMap<>(); 993 } 994} 995