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