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