ZenModeConfig.java revision cb9aa20bddbeebc3a052e40ca3b7d0a511fa8358
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 */ 16 17package android.service.notification; 18 19import android.app.NotificationManager.Policy; 20import android.content.ComponentName; 21import android.content.Context; 22import android.content.res.Resources; 23import android.net.Uri; 24import android.os.Parcel; 25import android.os.Parcelable; 26import android.provider.Settings.Global; 27import android.text.TextUtils; 28import android.text.format.DateFormat; 29import android.util.ArrayMap; 30import android.util.ArraySet; 31import android.util.Slog; 32 33import com.android.internal.R; 34 35import org.xmlpull.v1.XmlPullParser; 36import org.xmlpull.v1.XmlPullParserException; 37import org.xmlpull.v1.XmlSerializer; 38 39import java.io.IOException; 40import java.util.ArrayList; 41import java.util.Calendar; 42import java.util.Locale; 43import java.util.Objects; 44import java.util.UUID; 45 46/** 47 * Persisted configuration for zen mode. 48 * 49 * @hide 50 */ 51public class ZenModeConfig implements Parcelable { 52 private static String TAG = "ZenModeConfig"; 53 54 public static final int SOURCE_ANYONE = 0; 55 public static final int SOURCE_CONTACT = 1; 56 public static final int SOURCE_STAR = 2; 57 public static final int MAX_SOURCE = SOURCE_STAR; 58 private static final int DEFAULT_SOURCE = SOURCE_CONTACT; 59 60 public static final int[] ALL_DAYS = { Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY, 61 Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY }; 62 public static final int[] WEEKNIGHT_DAYS = { Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY, 63 Calendar.WEDNESDAY, Calendar.THURSDAY }; 64 public static final int[] WEEKEND_DAYS = { Calendar.FRIDAY, Calendar.SATURDAY }; 65 66 public static final int[] MINUTE_BUCKETS = generateMinuteBuckets(); 67 private static final int SECONDS_MS = 1000; 68 private static final int MINUTES_MS = 60 * SECONDS_MS; 69 private static final int ZERO_VALUE_MS = 10 * SECONDS_MS; 70 71 private static final boolean DEFAULT_ALLOW_CALLS = true; 72 private static final boolean DEFAULT_ALLOW_MESSAGES = false; 73 private static final boolean DEFAULT_ALLOW_REMINDERS = true; 74 private static final boolean DEFAULT_ALLOW_EVENTS = true; 75 private static final boolean DEFAULT_ALLOW_REPEAT_CALLERS = false; 76 77 private static final int XML_VERSION = 2; 78 private static final String ZEN_TAG = "zen"; 79 private static final String ZEN_ATT_VERSION = "version"; 80 private static final String ALLOW_TAG = "allow"; 81 private static final String ALLOW_ATT_CALLS = "calls"; 82 private static final String ALLOW_ATT_REPEAT_CALLERS = "repeatCallers"; 83 private static final String ALLOW_ATT_MESSAGES = "messages"; 84 private static final String ALLOW_ATT_FROM = "from"; 85 private static final String ALLOW_ATT_CALLS_FROM = "callsFrom"; 86 private static final String ALLOW_ATT_MESSAGES_FROM = "messagesFrom"; 87 private static final String ALLOW_ATT_REMINDERS = "reminders"; 88 private static final String ALLOW_ATT_EVENTS = "events"; 89 90 private static final String CONDITION_TAG = "condition"; 91 private static final String CONDITION_ATT_COMPONENT = "component"; 92 private static final String CONDITION_ATT_ID = "id"; 93 private static final String CONDITION_ATT_SUMMARY = "summary"; 94 private static final String CONDITION_ATT_LINE1 = "line1"; 95 private static final String CONDITION_ATT_LINE2 = "line2"; 96 private static final String CONDITION_ATT_ICON = "icon"; 97 private static final String CONDITION_ATT_STATE = "state"; 98 private static final String CONDITION_ATT_FLAGS = "flags"; 99 100 private static final String MANUAL_TAG = "manual"; 101 private static final String AUTOMATIC_TAG = "automatic"; 102 103 private static final String RULE_ATT_ID = "ruleId"; 104 private static final String RULE_ATT_ENABLED = "enabled"; 105 private static final String RULE_ATT_SNOOZING = "snoozing"; 106 private static final String RULE_ATT_NAME = "name"; 107 private static final String RULE_ATT_COMPONENT = "component"; 108 private static final String RULE_ATT_ZEN = "zen"; 109 private static final String RULE_ATT_CONDITION_ID = "conditionId"; 110 111 public boolean allowCalls = DEFAULT_ALLOW_CALLS; 112 public boolean allowRepeatCallers = DEFAULT_ALLOW_REPEAT_CALLERS; 113 public boolean allowMessages = DEFAULT_ALLOW_MESSAGES; 114 public boolean allowReminders = DEFAULT_ALLOW_REMINDERS; 115 public boolean allowEvents = DEFAULT_ALLOW_EVENTS; 116 public int allowCallsFrom = DEFAULT_SOURCE; 117 public int allowMessagesFrom = DEFAULT_SOURCE; 118 119 public ZenRule manualRule; 120 public ArrayMap<String, ZenRule> automaticRules = new ArrayMap<>(); 121 122 public ZenModeConfig() { } 123 124 public ZenModeConfig(Parcel source) { 125 allowCalls = source.readInt() == 1; 126 allowRepeatCallers = source.readInt() == 1; 127 allowMessages = source.readInt() == 1; 128 allowReminders = source.readInt() == 1; 129 allowEvents = source.readInt() == 1; 130 allowCallsFrom = source.readInt(); 131 allowMessagesFrom = source.readInt(); 132 manualRule = source.readParcelable(null); 133 final int len = source.readInt(); 134 if (len > 0) { 135 final String[] ids = new String[len]; 136 final ZenRule[] rules = new ZenRule[len]; 137 source.readStringArray(ids); 138 source.readTypedArray(rules, ZenRule.CREATOR); 139 for (int i = 0; i < len; i++) { 140 automaticRules.put(ids[i], rules[i]); 141 } 142 } 143 } 144 145 @Override 146 public void writeToParcel(Parcel dest, int flags) { 147 dest.writeInt(allowCalls ? 1 : 0); 148 dest.writeInt(allowRepeatCallers ? 1 : 0); 149 dest.writeInt(allowMessages ? 1 : 0); 150 dest.writeInt(allowReminders ? 1 : 0); 151 dest.writeInt(allowEvents ? 1 : 0); 152 dest.writeInt(allowCallsFrom); 153 dest.writeInt(allowMessagesFrom); 154 dest.writeParcelable(manualRule, 0); 155 if (!automaticRules.isEmpty()) { 156 final int len = automaticRules.size(); 157 final String[] ids = new String[len]; 158 final ZenRule[] rules = new ZenRule[len]; 159 for (int i = 0; i < len; i++) { 160 ids[i] = automaticRules.keyAt(i); 161 rules[i] = automaticRules.valueAt(i); 162 } 163 dest.writeInt(len); 164 dest.writeStringArray(ids); 165 dest.writeTypedArray(rules, 0); 166 } else { 167 dest.writeInt(0); 168 } 169 } 170 171 @Override 172 public String toString() { 173 return new StringBuilder(ZenModeConfig.class.getSimpleName()).append('[') 174 .append("allowCalls=").append(allowCalls) 175 .append(",allowRepeatCallers=").append(allowRepeatCallers) 176 .append(",allowMessages=").append(allowMessages) 177 .append(",allowCallsFrom=").append(sourceToString(allowCallsFrom)) 178 .append(",allowMessagesFrom=").append(sourceToString(allowMessagesFrom)) 179 .append(",allowReminders=").append(allowReminders) 180 .append(",allowEvents=").append(allowEvents) 181 .append(",automaticRules=").append(automaticRules) 182 .append(",manualRule=").append(manualRule) 183 .append(']').toString(); 184 } 185 186 public boolean isValid() { 187 if (!isValidManualRule(manualRule)) return false; 188 final int N = automaticRules.size(); 189 for (int i = 0; i < N; i++) { 190 if (!isValidAutomaticRule(automaticRules.valueAt(i))) return false; 191 } 192 return true; 193 } 194 195 private static boolean isValidManualRule(ZenRule rule) { 196 return rule == null || Global.isValidZenMode(rule.zenMode) && sameCondition(rule); 197 } 198 199 private static boolean isValidAutomaticRule(ZenRule rule) { 200 return rule != null && !TextUtils.isEmpty(rule.name) && Global.isValidZenMode(rule.zenMode) 201 && rule.conditionId != null && sameCondition(rule); 202 } 203 204 private static boolean sameCondition(ZenRule rule) { 205 if (rule == null) return false; 206 if (rule.conditionId == null) { 207 return rule.condition == null; 208 } else { 209 return rule.condition == null || rule.conditionId.equals(rule.condition.id); 210 } 211 } 212 213 private static int[] generateMinuteBuckets() { 214 final int maxHrs = 12; 215 final int[] buckets = new int[maxHrs + 3]; 216 buckets[0] = 15; 217 buckets[1] = 30; 218 buckets[2] = 45; 219 for (int i = 1; i <= maxHrs; i++) { 220 buckets[2 + i] = 60 * i; 221 } 222 return buckets; 223 } 224 225 public static String sourceToString(int source) { 226 switch (source) { 227 case SOURCE_ANYONE: 228 return "anyone"; 229 case SOURCE_CONTACT: 230 return "contacts"; 231 case SOURCE_STAR: 232 return "stars"; 233 default: 234 return "UNKNOWN"; 235 } 236 } 237 238 @Override 239 public boolean equals(Object o) { 240 if (!(o instanceof ZenModeConfig)) return false; 241 if (o == this) return true; 242 final ZenModeConfig other = (ZenModeConfig) o; 243 return other.allowCalls == allowCalls 244 && other.allowRepeatCallers == allowRepeatCallers 245 && other.allowMessages == allowMessages 246 && other.allowCallsFrom == allowCallsFrom 247 && other.allowMessagesFrom == allowMessagesFrom 248 && other.allowReminders == allowReminders 249 && other.allowEvents == allowEvents 250 && Objects.equals(other.automaticRules, automaticRules) 251 && Objects.equals(other.manualRule, manualRule); 252 } 253 254 @Override 255 public int hashCode() { 256 return Objects.hash(allowCalls, allowRepeatCallers, allowMessages, allowCallsFrom, 257 allowMessagesFrom, allowReminders, allowEvents, automaticRules, manualRule); 258 } 259 260 private static String toDayList(int[] days) { 261 if (days == null || days.length == 0) return ""; 262 final StringBuilder sb = new StringBuilder(); 263 for (int i = 0; i < days.length; i++) { 264 if (i > 0) sb.append('.'); 265 sb.append(days[i]); 266 } 267 return sb.toString(); 268 } 269 270 private static int[] tryParseDayList(String dayList, String sep) { 271 if (dayList == null) return null; 272 final String[] tokens = dayList.split(sep); 273 if (tokens.length == 0) return null; 274 final int[] rt = new int[tokens.length]; 275 for (int i = 0; i < tokens.length; i++) { 276 final int day = tryParseInt(tokens[i], -1); 277 if (day == -1) return null; 278 rt[i] = day; 279 } 280 return rt; 281 } 282 283 private static int tryParseInt(String value, int defValue) { 284 if (TextUtils.isEmpty(value)) return defValue; 285 try { 286 return Integer.valueOf(value); 287 } catch (NumberFormatException e) { 288 return defValue; 289 } 290 } 291 292 private static long tryParseLong(String value, long defValue) { 293 if (TextUtils.isEmpty(value)) return defValue; 294 try { 295 return Long.valueOf(value); 296 } catch (NumberFormatException e) { 297 return defValue; 298 } 299 } 300 301 public static ZenModeConfig readXml(XmlPullParser parser, Migration migration) 302 throws XmlPullParserException, IOException { 303 int type = parser.getEventType(); 304 if (type != XmlPullParser.START_TAG) return null; 305 String tag = parser.getName(); 306 if (!ZEN_TAG.equals(tag)) return null; 307 final ZenModeConfig rt = new ZenModeConfig(); 308 final int version = safeInt(parser, ZEN_ATT_VERSION, XML_VERSION); 309 if (version == 1) { 310 final XmlV1 v1 = XmlV1.readXml(parser); 311 return migration.migrate(v1); 312 } 313 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { 314 tag = parser.getName(); 315 if (type == XmlPullParser.END_TAG && ZEN_TAG.equals(tag)) { 316 return rt; 317 } 318 if (type == XmlPullParser.START_TAG) { 319 if (ALLOW_TAG.equals(tag)) { 320 rt.allowCalls = safeBoolean(parser, ALLOW_ATT_CALLS, false); 321 rt.allowRepeatCallers = safeBoolean(parser, ALLOW_ATT_REPEAT_CALLERS, 322 DEFAULT_ALLOW_REPEAT_CALLERS); 323 rt.allowMessages = safeBoolean(parser, ALLOW_ATT_MESSAGES, false); 324 rt.allowReminders = safeBoolean(parser, ALLOW_ATT_REMINDERS, 325 DEFAULT_ALLOW_REMINDERS); 326 rt.allowEvents = safeBoolean(parser, ALLOW_ATT_EVENTS, DEFAULT_ALLOW_EVENTS); 327 final int from = safeInt(parser, ALLOW_ATT_FROM, -1); 328 final int callsFrom = safeInt(parser, ALLOW_ATT_CALLS_FROM, -1); 329 final int messagesFrom = safeInt(parser, ALLOW_ATT_MESSAGES_FROM, -1); 330 if (isValidSource(callsFrom) && isValidSource(messagesFrom)) { 331 rt.allowCallsFrom = callsFrom; 332 rt.allowMessagesFrom = messagesFrom; 333 } else if (isValidSource(from)) { 334 Slog.i(TAG, "Migrating existing shared 'from': " + sourceToString(from)); 335 rt.allowCallsFrom = from; 336 rt.allowMessagesFrom = from; 337 } else { 338 rt.allowCallsFrom = DEFAULT_SOURCE; 339 rt.allowMessagesFrom = DEFAULT_SOURCE; 340 } 341 } else if (MANUAL_TAG.equals(tag)) { 342 rt.manualRule = readRuleXml(parser, false /*conditionRequired*/); 343 } else if (AUTOMATIC_TAG.equals(tag)) { 344 final String id = parser.getAttributeValue(null, RULE_ATT_ID); 345 final ZenRule automaticRule = readRuleXml(parser, true /*conditionRequired*/); 346 if (id != null && automaticRule != null) { 347 rt.automaticRules.put(id, automaticRule); 348 } 349 } 350 } 351 } 352 throw new IllegalStateException("Failed to reach END_DOCUMENT"); 353 } 354 355 public void writeXml(XmlSerializer out) throws IOException { 356 out.startTag(null, ZEN_TAG); 357 out.attribute(null, ZEN_ATT_VERSION, Integer.toString(XML_VERSION)); 358 359 out.startTag(null, ALLOW_TAG); 360 out.attribute(null, ALLOW_ATT_CALLS, Boolean.toString(allowCalls)); 361 out.attribute(null, ALLOW_ATT_REPEAT_CALLERS, Boolean.toString(allowRepeatCallers)); 362 out.attribute(null, ALLOW_ATT_MESSAGES, Boolean.toString(allowMessages)); 363 out.attribute(null, ALLOW_ATT_REMINDERS, Boolean.toString(allowReminders)); 364 out.attribute(null, ALLOW_ATT_EVENTS, Boolean.toString(allowEvents)); 365 out.attribute(null, ALLOW_ATT_CALLS_FROM, Integer.toString(allowCallsFrom)); 366 out.attribute(null, ALLOW_ATT_MESSAGES_FROM, Integer.toString(allowMessagesFrom)); 367 out.endTag(null, ALLOW_TAG); 368 369 if (manualRule != null) { 370 out.startTag(null, MANUAL_TAG); 371 writeRuleXml(manualRule, out); 372 out.endTag(null, MANUAL_TAG); 373 } 374 final int N = automaticRules.size(); 375 for (int i = 0; i < N; i++) { 376 final String id = automaticRules.keyAt(i); 377 final ZenRule automaticRule = automaticRules.valueAt(i); 378 out.startTag(null, AUTOMATIC_TAG); 379 out.attribute(null, RULE_ATT_ID, id); 380 writeRuleXml(automaticRule, out); 381 out.endTag(null, AUTOMATIC_TAG); 382 } 383 out.endTag(null, ZEN_TAG); 384 } 385 386 public static ZenRule readRuleXml(XmlPullParser parser, boolean conditionRequired) { 387 final ZenRule rt = new ZenRule(); 388 rt.enabled = safeBoolean(parser, RULE_ATT_ENABLED, true); 389 rt.snoozing = safeBoolean(parser, RULE_ATT_SNOOZING, false); 390 rt.name = parser.getAttributeValue(null, RULE_ATT_NAME); 391 final String zen = parser.getAttributeValue(null, RULE_ATT_ZEN); 392 rt.zenMode = tryParseZenMode(zen, -1); 393 if (rt.zenMode == -1) { 394 Slog.w(TAG, "Bad zen mode in rule xml:" + zen); 395 return null; 396 } 397 rt.conditionId = safeUri(parser, RULE_ATT_CONDITION_ID); 398 rt.component = safeComponentName(parser, RULE_ATT_COMPONENT); 399 rt.condition = readConditionXml(parser); 400 return rt; 401 } 402 403 public static void writeRuleXml(ZenRule rule, XmlSerializer out) throws IOException { 404 out.attribute(null, RULE_ATT_ENABLED, Boolean.toString(rule.enabled)); 405 out.attribute(null, RULE_ATT_SNOOZING, Boolean.toString(rule.snoozing)); 406 if (rule.name != null) { 407 out.attribute(null, RULE_ATT_NAME, rule.name); 408 } 409 out.attribute(null, RULE_ATT_ZEN, Integer.toString(rule.zenMode)); 410 if (rule.component != null) { 411 out.attribute(null, RULE_ATT_COMPONENT, rule.component.flattenToString()); 412 } 413 if (rule.conditionId != null) { 414 out.attribute(null, RULE_ATT_CONDITION_ID, rule.conditionId.toString()); 415 } 416 if (rule.condition != null) { 417 writeConditionXml(rule.condition, out); 418 } 419 } 420 421 public static Condition readConditionXml(XmlPullParser parser) { 422 final Uri id = safeUri(parser, CONDITION_ATT_ID); 423 if (id == null) return null; 424 final String summary = parser.getAttributeValue(null, CONDITION_ATT_SUMMARY); 425 final String line1 = parser.getAttributeValue(null, CONDITION_ATT_LINE1); 426 final String line2 = parser.getAttributeValue(null, CONDITION_ATT_LINE2); 427 final int icon = safeInt(parser, CONDITION_ATT_ICON, -1); 428 final int state = safeInt(parser, CONDITION_ATT_STATE, -1); 429 final int flags = safeInt(parser, CONDITION_ATT_FLAGS, -1); 430 try { 431 return new Condition(id, summary, line1, line2, icon, state, flags); 432 } catch (IllegalArgumentException e) { 433 Slog.w(TAG, "Unable to read condition xml", e); 434 return null; 435 } 436 } 437 438 public static void writeConditionXml(Condition c, XmlSerializer out) throws IOException { 439 out.attribute(null, CONDITION_ATT_ID, c.id.toString()); 440 out.attribute(null, CONDITION_ATT_SUMMARY, c.summary); 441 out.attribute(null, CONDITION_ATT_LINE1, c.line1); 442 out.attribute(null, CONDITION_ATT_LINE2, c.line2); 443 out.attribute(null, CONDITION_ATT_ICON, Integer.toString(c.icon)); 444 out.attribute(null, CONDITION_ATT_STATE, Integer.toString(c.state)); 445 out.attribute(null, CONDITION_ATT_FLAGS, Integer.toString(c.flags)); 446 } 447 448 public static boolean isValidHour(int val) { 449 return val >= 0 && val < 24; 450 } 451 452 public static boolean isValidMinute(int val) { 453 return val >= 0 && val < 60; 454 } 455 456 private static boolean isValidSource(int source) { 457 return source >= SOURCE_ANYONE && source <= MAX_SOURCE; 458 } 459 460 private static boolean safeBoolean(XmlPullParser parser, String att, boolean defValue) { 461 final String val = parser.getAttributeValue(null, att); 462 if (TextUtils.isEmpty(val)) return defValue; 463 return Boolean.valueOf(val); 464 } 465 466 private static int safeInt(XmlPullParser parser, String att, int defValue) { 467 final String val = parser.getAttributeValue(null, att); 468 return tryParseInt(val, defValue); 469 } 470 471 private static ComponentName safeComponentName(XmlPullParser parser, String att) { 472 final String val = parser.getAttributeValue(null, att); 473 if (TextUtils.isEmpty(val)) return null; 474 return ComponentName.unflattenFromString(val); 475 } 476 477 private static Uri safeUri(XmlPullParser parser, String att) { 478 final String val = parser.getAttributeValue(null, att); 479 if (TextUtils.isEmpty(val)) return null; 480 return Uri.parse(val); 481 } 482 483 public ArraySet<String> getAutomaticRuleNames() { 484 final ArraySet<String> rt = new ArraySet<String>(); 485 for (int i = 0; i < automaticRules.size(); i++) { 486 rt.add(automaticRules.valueAt(i).name); 487 } 488 return rt; 489 } 490 491 @Override 492 public int describeContents() { 493 return 0; 494 } 495 496 public ZenModeConfig copy() { 497 final Parcel parcel = Parcel.obtain(); 498 try { 499 writeToParcel(parcel, 0); 500 parcel.setDataPosition(0); 501 return new ZenModeConfig(parcel); 502 } finally { 503 parcel.recycle(); 504 } 505 } 506 507 public static final Parcelable.Creator<ZenModeConfig> CREATOR 508 = new Parcelable.Creator<ZenModeConfig>() { 509 @Override 510 public ZenModeConfig createFromParcel(Parcel source) { 511 return new ZenModeConfig(source); 512 } 513 514 @Override 515 public ZenModeConfig[] newArray(int size) { 516 return new ZenModeConfig[size]; 517 } 518 }; 519 520 public Policy toNotificationPolicy() { 521 int priorityCategories = 0; 522 int priorityCallSenders = Policy.PRIORITY_SENDERS_CONTACTS; 523 int priorityMessageSenders = Policy.PRIORITY_SENDERS_CONTACTS; 524 if (allowCalls) { 525 priorityCategories |= Policy.PRIORITY_CATEGORY_CALLS; 526 } 527 if (allowMessages) { 528 priorityCategories |= Policy.PRIORITY_CATEGORY_MESSAGES; 529 } 530 if (allowEvents) { 531 priorityCategories |= Policy.PRIORITY_CATEGORY_EVENTS; 532 } 533 if (allowReminders) { 534 priorityCategories |= Policy.PRIORITY_CATEGORY_REMINDERS; 535 } 536 if (allowRepeatCallers) { 537 priorityCategories |= Policy.PRIORITY_CATEGORY_REPEAT_CALLERS; 538 } 539 priorityCallSenders = sourceToPrioritySenders(allowCallsFrom, priorityCallSenders); 540 priorityMessageSenders = sourceToPrioritySenders(allowMessagesFrom, priorityMessageSenders); 541 return new Policy(priorityCategories, priorityCallSenders); 542 } 543 544 private static int sourceToPrioritySenders(int source, int def) { 545 switch (source) { 546 case SOURCE_ANYONE: return Policy.PRIORITY_SENDERS_ANY; 547 case SOURCE_CONTACT: return Policy.PRIORITY_SENDERS_CONTACTS; 548 case SOURCE_STAR: return Policy.PRIORITY_SENDERS_STARRED; 549 default: return def; 550 } 551 } 552 553 private static int prioritySendersToSource(int prioritySenders, int def) { 554 switch (prioritySenders) { 555 case Policy.PRIORITY_SENDERS_CONTACTS: return SOURCE_CONTACT; 556 case Policy.PRIORITY_SENDERS_STARRED: return SOURCE_STAR; 557 case Policy.PRIORITY_SENDERS_ANY: return SOURCE_ANYONE; 558 default: return def; 559 } 560 } 561 562 public void applyNotificationPolicy(Policy policy) { 563 if (policy == null) return; 564 allowCalls = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_CALLS) != 0; 565 allowMessages = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_MESSAGES) != 0; 566 allowEvents = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_EVENTS) != 0; 567 allowReminders = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_REMINDERS) != 0; 568 allowRepeatCallers = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_REPEAT_CALLERS) 569 != 0; 570 allowCallsFrom = prioritySendersToSource(policy.prioritySenders, allowCallsFrom); 571 } 572 573 public static Condition toTimeCondition(Context context, int minutesFromNow, int userHandle) { 574 final long now = System.currentTimeMillis(); 575 final long millis = minutesFromNow == 0 ? ZERO_VALUE_MS : minutesFromNow * MINUTES_MS; 576 return toTimeCondition(context, now + millis, minutesFromNow, now, userHandle); 577 } 578 579 public static Condition toTimeCondition(Context context, long time, int minutes, long now, 580 int userHandle) { 581 final int num, summaryResId, line1ResId; 582 if (minutes < 60) { 583 // display as minutes 584 num = minutes; 585 summaryResId = R.plurals.zen_mode_duration_minutes_summary; 586 line1ResId = R.plurals.zen_mode_duration_minutes; 587 } else { 588 // display as hours 589 num = Math.round(minutes / 60f); 590 summaryResId = com.android.internal.R.plurals.zen_mode_duration_hours_summary; 591 line1ResId = com.android.internal.R.plurals.zen_mode_duration_hours; 592 } 593 final String skeleton = DateFormat.is24HourFormat(context, userHandle) ? "Hm" : "hma"; 594 final String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton); 595 final CharSequence formattedTime = DateFormat.format(pattern, time); 596 final Resources res = context.getResources(); 597 final String summary = res.getQuantityString(summaryResId, num, num, formattedTime); 598 final String line1 = res.getQuantityString(line1ResId, num, num, formattedTime); 599 final String line2 = res.getString(R.string.zen_mode_until, formattedTime); 600 final Uri id = toCountdownConditionId(time); 601 return new Condition(id, summary, line1, line2, 0, Condition.STATE_TRUE, 602 Condition.FLAG_RELEVANT_NOW); 603 } 604 605 // ==== Built-in system conditions ==== 606 607 public static final String SYSTEM_AUTHORITY = "android"; 608 609 // ==== Built-in system condition: countdown ==== 610 611 public static final String COUNTDOWN_PATH = "countdown"; 612 613 public static Uri toCountdownConditionId(long time) { 614 return new Uri.Builder().scheme(Condition.SCHEME) 615 .authority(SYSTEM_AUTHORITY) 616 .appendPath(COUNTDOWN_PATH) 617 .appendPath(Long.toString(time)) 618 .build(); 619 } 620 621 public static long tryParseCountdownConditionId(Uri conditionId) { 622 if (!Condition.isValidId(conditionId, SYSTEM_AUTHORITY)) return 0; 623 if (conditionId.getPathSegments().size() != 2 624 || !COUNTDOWN_PATH.equals(conditionId.getPathSegments().get(0))) return 0; 625 try { 626 return Long.parseLong(conditionId.getPathSegments().get(1)); 627 } catch (RuntimeException e) { 628 Slog.w(TAG, "Error parsing countdown condition: " + conditionId, e); 629 return 0; 630 } 631 } 632 633 public static boolean isValidCountdownConditionId(Uri conditionId) { 634 return tryParseCountdownConditionId(conditionId) != 0; 635 } 636 637 // ==== Built-in system condition: schedule ==== 638 639 public static final String SCHEDULE_PATH = "schedule"; 640 641 public static Uri toScheduleConditionId(ScheduleInfo schedule) { 642 return new Uri.Builder().scheme(Condition.SCHEME) 643 .authority(SYSTEM_AUTHORITY) 644 .appendPath(SCHEDULE_PATH) 645 .appendQueryParameter("days", toDayList(schedule.days)) 646 .appendQueryParameter("start", schedule.startHour + "." + schedule.startMinute) 647 .appendQueryParameter("end", schedule.endHour + "." + schedule.endMinute) 648 .build(); 649 } 650 651 public static boolean isValidScheduleConditionId(Uri conditionId) { 652 return tryParseScheduleConditionId(conditionId) != null; 653 } 654 655 public static ScheduleInfo tryParseScheduleConditionId(Uri conditionId) { 656 final boolean isSchedule = conditionId != null 657 && conditionId.getScheme().equals(Condition.SCHEME) 658 && conditionId.getAuthority().equals(ZenModeConfig.SYSTEM_AUTHORITY) 659 && conditionId.getPathSegments().size() == 1 660 && conditionId.getPathSegments().get(0).equals(ZenModeConfig.SCHEDULE_PATH); 661 if (!isSchedule) return null; 662 final int[] start = tryParseHourAndMinute(conditionId.getQueryParameter("start")); 663 final int[] end = tryParseHourAndMinute(conditionId.getQueryParameter("end")); 664 if (start == null || end == null) return null; 665 final ScheduleInfo rt = new ScheduleInfo(); 666 rt.days = tryParseDayList(conditionId.getQueryParameter("days"), "\\."); 667 rt.startHour = start[0]; 668 rt.startMinute = start[1]; 669 rt.endHour = end[0]; 670 rt.endMinute = end[1]; 671 return rt; 672 } 673 674 public static class ScheduleInfo { 675 public int[] days; 676 public int startHour; 677 public int startMinute; 678 public int endHour; 679 public int endMinute; 680 681 @Override 682 public int hashCode() { 683 return 0; 684 } 685 686 @Override 687 public boolean equals(Object o) { 688 if (!(o instanceof ScheduleInfo)) return false; 689 final ScheduleInfo other = (ScheduleInfo) o; 690 return toDayList(days).equals(toDayList(other.days)) 691 && startHour == other.startHour 692 && startMinute == other.startMinute 693 && endHour == other.endHour 694 && endMinute == other.endMinute; 695 } 696 697 public ScheduleInfo copy() { 698 final ScheduleInfo rt = new ScheduleInfo(); 699 if (days != null) { 700 rt.days = new int[days.length]; 701 System.arraycopy(days, 0, rt.days, 0, days.length); 702 } 703 rt.startHour = startHour; 704 rt.startMinute = startMinute; 705 rt.endHour = endHour; 706 rt.endMinute = endMinute; 707 return rt; 708 } 709 } 710 711 // ==== Built-in system condition: event ==== 712 713 public static final String EVENT_PATH = "event"; 714 715 public static Uri toEventConditionId(EventInfo event) { 716 return new Uri.Builder().scheme(Condition.SCHEME) 717 .authority(SYSTEM_AUTHORITY) 718 .appendPath(EVENT_PATH) 719 .appendQueryParameter("calendar", Long.toString(event.calendar)) 720 .appendQueryParameter("reply", Integer.toString(event.reply)) 721 .build(); 722 } 723 724 public static boolean isValidEventConditionId(Uri conditionId) { 725 return tryParseEventConditionId(conditionId) != null; 726 } 727 728 public static EventInfo tryParseEventConditionId(Uri conditionId) { 729 final boolean isEvent = conditionId != null 730 && conditionId.getScheme().equals(Condition.SCHEME) 731 && conditionId.getAuthority().equals(ZenModeConfig.SYSTEM_AUTHORITY) 732 && conditionId.getPathSegments().size() == 1 733 && conditionId.getPathSegments().get(0).equals(EVENT_PATH); 734 if (!isEvent) return null; 735 final EventInfo rt = new EventInfo(); 736 rt.calendar = tryParseLong(conditionId.getQueryParameter("calendar"), 737 EventInfo.ANY_CALENDAR); 738 rt.reply = tryParseInt(conditionId.getQueryParameter("reply"), 0); 739 return rt; 740 } 741 742 public static class EventInfo { 743 public static final long ANY_CALENDAR = 0; 744 745 public static final int REPLY_ANY_EXCEPT_NO = 0; 746 public static final int REPLY_YES_OR_MAYBE = 1; 747 public static final int REPLY_YES = 2; 748 749 public long calendar = ANY_CALENDAR; // CalendarContract.Calendars._ID, or ANY_CALENDAR 750 public int reply; 751 752 @Override 753 public int hashCode() { 754 return 0; 755 } 756 757 @Override 758 public boolean equals(Object o) { 759 if (!(o instanceof EventInfo)) return false; 760 final EventInfo other = (EventInfo) o; 761 return calendar == other.calendar 762 && reply == other.reply; 763 } 764 765 public EventInfo copy() { 766 final EventInfo rt = new EventInfo(); 767 rt.calendar = calendar; 768 rt.reply = reply; 769 return rt; 770 } 771 } 772 773 // ==== End built-in system conditions ==== 774 775 private static int[] tryParseHourAndMinute(String value) { 776 if (TextUtils.isEmpty(value)) return null; 777 final int i = value.indexOf('.'); 778 if (i < 1 || i >= value.length() - 1) return null; 779 final int hour = tryParseInt(value.substring(0, i), -1); 780 final int minute = tryParseInt(value.substring(i + 1), -1); 781 return isValidHour(hour) && isValidMinute(minute) ? new int[] { hour, minute } : null; 782 } 783 784 private static int tryParseZenMode(String value, int defValue) { 785 final int rt = tryParseInt(value, defValue); 786 return Global.isValidZenMode(rt) ? rt : defValue; 787 } 788 789 public String newRuleId() { 790 return UUID.randomUUID().toString().replace("-", ""); 791 } 792 793 public static String getConditionLine1(Context context, ZenModeConfig config, 794 int userHandle) { 795 return getConditionLine(context, config, userHandle, true /*useLine1*/); 796 } 797 798 public static String getConditionSummary(Context context, ZenModeConfig config, 799 int userHandle) { 800 return getConditionLine(context, config, userHandle, false /*useLine1*/); 801 } 802 803 private static String getConditionLine(Context context, ZenModeConfig config, 804 int userHandle, boolean useLine1) { 805 if (config == null) return ""; 806 if (config.manualRule != null) { 807 final Uri id = config.manualRule.conditionId; 808 if (id == null) { 809 return context.getString(com.android.internal.R.string.zen_mode_forever); 810 } 811 final long time = tryParseCountdownConditionId(id); 812 Condition c = config.manualRule.condition; 813 if (time > 0) { 814 final long now = System.currentTimeMillis(); 815 final long span = time - now; 816 c = toTimeCondition(context, 817 time, Math.round(span / (float) MINUTES_MS), now, userHandle); 818 } 819 final String rt = c == null ? "" : useLine1 ? c.line1 : c.summary; 820 return TextUtils.isEmpty(rt) ? "" : rt; 821 } 822 String summary = ""; 823 for (ZenRule automaticRule : config.automaticRules.values()) { 824 if (automaticRule.isAutomaticActive()) { 825 if (summary.isEmpty()) { 826 summary = automaticRule.name; 827 } else { 828 summary = context.getResources() 829 .getString(R.string.zen_mode_rule_name_combination, summary, 830 automaticRule.name); 831 } 832 } 833 } 834 return summary; 835 } 836 837 public static class ZenRule implements Parcelable { 838 public boolean enabled; 839 public boolean snoozing; // user manually disabled this instance 840 public String name; // required for automatic (unique) 841 public int zenMode; 842 public Uri conditionId; // required for automatic 843 public Condition condition; // optional 844 public ComponentName component; // optional 845 846 public ZenRule() { } 847 848 public ZenRule(Parcel source) { 849 enabled = source.readInt() == 1; 850 snoozing = source.readInt() == 1; 851 if (source.readInt() == 1) { 852 name = source.readString(); 853 } 854 zenMode = source.readInt(); 855 conditionId = source.readParcelable(null); 856 condition = source.readParcelable(null); 857 component = source.readParcelable(null); 858 } 859 860 @Override 861 public int describeContents() { 862 return 0; 863 } 864 865 @Override 866 public void writeToParcel(Parcel dest, int flags) { 867 dest.writeInt(enabled ? 1 : 0); 868 dest.writeInt(snoozing ? 1 : 0); 869 if (name != null) { 870 dest.writeInt(1); 871 dest.writeString(name); 872 } else { 873 dest.writeInt(0); 874 } 875 dest.writeInt(zenMode); 876 dest.writeParcelable(conditionId, 0); 877 dest.writeParcelable(condition, 0); 878 dest.writeParcelable(component, 0); 879 } 880 881 @Override 882 public String toString() { 883 return new StringBuilder(ZenRule.class.getSimpleName()).append('[') 884 .append("enabled=").append(enabled) 885 .append(",snoozing=").append(snoozing) 886 .append(",name=").append(name) 887 .append(",zenMode=").append(Global.zenModeToString(zenMode)) 888 .append(",conditionId=").append(conditionId) 889 .append(",condition=").append(condition) 890 .append(",component=").append(component) 891 .append(']').toString(); 892 } 893 894 @Override 895 public boolean equals(Object o) { 896 if (!(o instanceof ZenRule)) return false; 897 if (o == this) return true; 898 final ZenRule other = (ZenRule) o; 899 return other.enabled == enabled 900 && other.snoozing == snoozing 901 && Objects.equals(other.name, name) 902 && other.zenMode == zenMode 903 && Objects.equals(other.conditionId, conditionId) 904 && Objects.equals(other.condition, condition) 905 && Objects.equals(other.component, component); 906 } 907 908 @Override 909 public int hashCode() { 910 return Objects.hash(enabled, snoozing, name, zenMode, conditionId, condition, 911 component); 912 } 913 914 public boolean isAutomaticActive() { 915 return enabled && !snoozing && component != null && isTrueOrUnknown(); 916 } 917 918 public boolean isTrueOrUnknown() { 919 return condition != null && (condition.state == Condition.STATE_TRUE 920 || condition.state == Condition.STATE_UNKNOWN); 921 } 922 923 public static final Parcelable.Creator<ZenRule> CREATOR 924 = new Parcelable.Creator<ZenRule>() { 925 @Override 926 public ZenRule createFromParcel(Parcel source) { 927 return new ZenRule(source); 928 } 929 @Override 930 public ZenRule[] newArray(int size) { 931 return new ZenRule[size]; 932 } 933 }; 934 } 935 936 // Legacy config 937 public static final class XmlV1 { 938 public static final String SLEEP_MODE_NIGHTS = "nights"; 939 public static final String SLEEP_MODE_WEEKNIGHTS = "weeknights"; 940 public static final String SLEEP_MODE_DAYS_PREFIX = "days:"; 941 942 private static final String EXIT_CONDITION_TAG = "exitCondition"; 943 private static final String EXIT_CONDITION_ATT_COMPONENT = "component"; 944 private static final String SLEEP_TAG = "sleep"; 945 private static final String SLEEP_ATT_MODE = "mode"; 946 private static final String SLEEP_ATT_NONE = "none"; 947 948 private static final String SLEEP_ATT_START_HR = "startHour"; 949 private static final String SLEEP_ATT_START_MIN = "startMin"; 950 private static final String SLEEP_ATT_END_HR = "endHour"; 951 private static final String SLEEP_ATT_END_MIN = "endMin"; 952 953 public boolean allowCalls; 954 public boolean allowMessages; 955 public boolean allowReminders = DEFAULT_ALLOW_REMINDERS; 956 public boolean allowEvents = DEFAULT_ALLOW_EVENTS; 957 public int allowFrom = SOURCE_ANYONE; 958 959 public String sleepMode; // nights, weeknights, days:1,2,3 Calendar.days 960 public int sleepStartHour; // 0-23 961 public int sleepStartMinute; // 0-59 962 public int sleepEndHour; 963 public int sleepEndMinute; 964 public boolean sleepNone; // false = priority, true = none 965 public ComponentName[] conditionComponents; 966 public Uri[] conditionIds; 967 public Condition exitCondition; // manual exit condition 968 public ComponentName exitConditionComponent; // manual exit condition component 969 970 private static boolean isValidSleepMode(String sleepMode) { 971 return sleepMode == null || sleepMode.equals(SLEEP_MODE_NIGHTS) 972 || sleepMode.equals(SLEEP_MODE_WEEKNIGHTS) || tryParseDays(sleepMode) != null; 973 } 974 975 public static int[] tryParseDays(String sleepMode) { 976 if (sleepMode == null) return null; 977 sleepMode = sleepMode.trim(); 978 if (SLEEP_MODE_NIGHTS.equals(sleepMode)) return ALL_DAYS; 979 if (SLEEP_MODE_WEEKNIGHTS.equals(sleepMode)) return WEEKNIGHT_DAYS; 980 if (!sleepMode.startsWith(SLEEP_MODE_DAYS_PREFIX)) return null; 981 if (sleepMode.equals(SLEEP_MODE_DAYS_PREFIX)) return null; 982 return tryParseDayList(sleepMode.substring(SLEEP_MODE_DAYS_PREFIX.length()), ","); 983 } 984 985 public static XmlV1 readXml(XmlPullParser parser) 986 throws XmlPullParserException, IOException { 987 int type; 988 String tag; 989 XmlV1 rt = new XmlV1(); 990 final ArrayList<ComponentName> conditionComponents = new ArrayList<ComponentName>(); 991 final ArrayList<Uri> conditionIds = new ArrayList<Uri>(); 992 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { 993 tag = parser.getName(); 994 if (type == XmlPullParser.END_TAG && ZEN_TAG.equals(tag)) { 995 if (!conditionComponents.isEmpty()) { 996 rt.conditionComponents = conditionComponents 997 .toArray(new ComponentName[conditionComponents.size()]); 998 rt.conditionIds = conditionIds.toArray(new Uri[conditionIds.size()]); 999 } 1000 return rt; 1001 } 1002 if (type == XmlPullParser.START_TAG) { 1003 if (ALLOW_TAG.equals(tag)) { 1004 rt.allowCalls = safeBoolean(parser, ALLOW_ATT_CALLS, false); 1005 rt.allowMessages = safeBoolean(parser, ALLOW_ATT_MESSAGES, false); 1006 rt.allowReminders = safeBoolean(parser, ALLOW_ATT_REMINDERS, 1007 DEFAULT_ALLOW_REMINDERS); 1008 rt.allowEvents = safeBoolean(parser, ALLOW_ATT_EVENTS, 1009 DEFAULT_ALLOW_EVENTS); 1010 rt.allowFrom = safeInt(parser, ALLOW_ATT_FROM, SOURCE_ANYONE); 1011 if (rt.allowFrom < SOURCE_ANYONE || rt.allowFrom > MAX_SOURCE) { 1012 throw new IndexOutOfBoundsException("bad source in config:" 1013 + rt.allowFrom); 1014 } 1015 } else if (SLEEP_TAG.equals(tag)) { 1016 final String mode = parser.getAttributeValue(null, SLEEP_ATT_MODE); 1017 rt.sleepMode = isValidSleepMode(mode)? mode : null; 1018 rt.sleepNone = safeBoolean(parser, SLEEP_ATT_NONE, false); 1019 final int startHour = safeInt(parser, SLEEP_ATT_START_HR, 0); 1020 final int startMinute = safeInt(parser, SLEEP_ATT_START_MIN, 0); 1021 final int endHour = safeInt(parser, SLEEP_ATT_END_HR, 0); 1022 final int endMinute = safeInt(parser, SLEEP_ATT_END_MIN, 0); 1023 rt.sleepStartHour = isValidHour(startHour) ? startHour : 0; 1024 rt.sleepStartMinute = isValidMinute(startMinute) ? startMinute : 0; 1025 rt.sleepEndHour = isValidHour(endHour) ? endHour : 0; 1026 rt.sleepEndMinute = isValidMinute(endMinute) ? endMinute : 0; 1027 } else if (CONDITION_TAG.equals(tag)) { 1028 final ComponentName component = 1029 safeComponentName(parser, CONDITION_ATT_COMPONENT); 1030 final Uri conditionId = safeUri(parser, CONDITION_ATT_ID); 1031 if (component != null && conditionId != null) { 1032 conditionComponents.add(component); 1033 conditionIds.add(conditionId); 1034 } 1035 } else if (EXIT_CONDITION_TAG.equals(tag)) { 1036 rt.exitCondition = readConditionXml(parser); 1037 if (rt.exitCondition != null) { 1038 rt.exitConditionComponent = 1039 safeComponentName(parser, EXIT_CONDITION_ATT_COMPONENT); 1040 } 1041 } 1042 } 1043 } 1044 throw new IllegalStateException("Failed to reach END_DOCUMENT"); 1045 } 1046 } 1047 1048 public interface Migration { 1049 ZenModeConfig migrate(XmlV1 v1); 1050 } 1051 1052} 1053