Debian Codegraph @

core/java/android/service/notification/ZenModeConfig.java

raw symbols SCIP
1 /**
2 * Copyright (c) 2014, The Android Open Source Project
3 *
4 * Licensed under the Apache License, 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
17 package android.service.notification;
18
19 import static android.app.NotificationManager.Policy.CONVERSATION_SENDERS_ANYONE;
20 import static android.app.NotificationManager.Policy.CONVERSATION_SENDERS_IMPORTANT;
21 import static android.app.NotificationManager.Policy.CONVERSATION_SENDERS_NONE;
22 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_AMBIENT;
23 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
24 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_LIGHTS;
25 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_PEEK;
26 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_SCREEN_OFF;
27
28 import android.annotation.Nullable;
29 import android.app.ActivityManager;
30 import android.app.AlarmManager;
31 import android.app.NotificationManager;
32 import android.app.NotificationManager.Policy;
33 import android.compat.annotation.UnsupportedAppUsage;
34 import android.content.ComponentName;
35 import android.content.Context;
36 import android.content.pm.ApplicationInfo;
37 import android.content.pm.PackageManager;
38 import android.content.res.Resources;
39 import android.net.Uri;
40 import android.os.Build;
41 import android.os.Parcel;
42 import android.os.Parcelable;
43 import android.os.UserHandle;
44 import android.provider.Settings.Global;
45 import android.text.TextUtils;
46 import android.text.format.DateFormat;
47 import android.util.ArrayMap;
48 import android.util.ArraySet;
49 import android.util.PluralsMessageFormatter;
50 import android.util.Slog;
51 import android.util.TypedXmlPullParser;
52 import android.util.TypedXmlSerializer;
53 import android.util.proto.ProtoOutputStream;
54
55 import com.android.internal.R;
56 import com.android.internal.util.XmlUtils;
57
58 import org.xmlpull.v1.XmlPullParser;
59 import org.xmlpull.v1.XmlPullParserException;
60
61 import java.io.IOException;
62 import java.util.ArrayList;
63 import java.util.Arrays;
64 import java.util.Calendar;
65 import java.util.Date;
66 import java.util.GregorianCalendar;
67 import java.util.HashMap;
68 import java.util.List;
69 import java.util.Locale;
70 import java.util.Map;
71 import java.util.Objects;
72 import java.util.TimeZone;
73 import java.util.UUID;
74
75 /**
76 * Persisted configuration for zen mode.
77 *
78 * @hide
79 */
80 public class ZenModeConfig implements Parcelable {
81 private static String TAG = "ZenModeConfig";
82
83 public static final int SOURCE_ANYONE = Policy.PRIORITY_SENDERS_ANY;
84 public static final int SOURCE_CONTACT = Policy.PRIORITY_SENDERS_CONTACTS;
85 public static final int SOURCE_STAR = Policy.PRIORITY_SENDERS_STARRED;
86 public static final int MAX_SOURCE = SOURCE_STAR;
87 private static final int DEFAULT_SOURCE = SOURCE_STAR;
88 private static final int DEFAULT_CALLS_SOURCE = SOURCE_STAR;
89
90 public static final String MANUAL_RULE_ID = "MANUAL_RULE";
91 public static final String EVENTS_DEFAULT_RULE_ID = "EVENTS_DEFAULT_RULE";
92 public static final String EVERY_NIGHT_DEFAULT_RULE_ID = "EVERY_NIGHT_DEFAULT_RULE";
93 public static final List<String> DEFAULT_RULE_IDS = Arrays.asList(EVERY_NIGHT_DEFAULT_RULE_ID,
94 EVENTS_DEFAULT_RULE_ID);
95
96 public static final int[] ALL_DAYS = { Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY,
97 Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY };
98
99 public static final int[] MINUTE_BUCKETS = generateMinuteBuckets();
100 private static final int SECONDS_MS = 1000;
101 private static final int MINUTES_MS = 60 * SECONDS_MS;
102 private static final int DAY_MINUTES = 24 * 60;
103 private static final int ZERO_VALUE_MS = 10 * SECONDS_MS;
104
105 // Default allow categories set in readXml() from default_zen_mode_config.xml,
106 // fallback/upgrade values:
107 private static final boolean DEFAULT_ALLOW_ALARMS = true;
108 private static final boolean DEFAULT_ALLOW_MEDIA = true;
109 private static final boolean DEFAULT_ALLOW_SYSTEM = false;
110 private static final boolean DEFAULT_ALLOW_CALLS = true;
111 private static final boolean DEFAULT_ALLOW_MESSAGES = true;
112 private static final boolean DEFAULT_ALLOW_REMINDERS = false;
113 private static final boolean DEFAULT_ALLOW_EVENTS = false;
114 private static final boolean DEFAULT_ALLOW_REPEAT_CALLERS = true;
115 private static final boolean DEFAULT_ALLOW_CONV = true;
116 private static final int DEFAULT_ALLOW_CONV_FROM = ZenPolicy.CONVERSATION_SENDERS_IMPORTANT;
117 private static final boolean DEFAULT_CHANNELS_BYPASSING_DND = false;
118 // Default setting here is 010011101 = 157
119 private static final int DEFAULT_SUPPRESSED_VISUAL_EFFECTS =
120 SUPPRESSED_EFFECT_SCREEN_OFF | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT
121 | SUPPRESSED_EFFECT_LIGHTS | SUPPRESSED_EFFECT_PEEK | SUPPRESSED_EFFECT_AMBIENT;
122
123 public static final int XML_VERSION = 8;
124 public static final String ZEN_TAG = "zen";
125 private static final String ZEN_ATT_VERSION = "version";
126 private static final String ZEN_ATT_USER = "user";
127 private static final String ALLOW_TAG = "allow";
128 private static final String ALLOW_ATT_ALARMS = "alarms";
129 private static final String ALLOW_ATT_MEDIA = "media";
130 private static final String ALLOW_ATT_SYSTEM = "system";
131 private static final String ALLOW_ATT_CALLS = "calls";
132 private static final String ALLOW_ATT_REPEAT_CALLERS = "repeatCallers";
133 private static final String ALLOW_ATT_MESSAGES = "messages";
134 private static final String ALLOW_ATT_FROM = "from";
135 private static final String ALLOW_ATT_CALLS_FROM = "callsFrom";
136 private static final String ALLOW_ATT_MESSAGES_FROM = "messagesFrom";
137 private static final String ALLOW_ATT_REMINDERS = "reminders";
138 private static final String ALLOW_ATT_EVENTS = "events";
139 private static final String ALLOW_ATT_SCREEN_OFF = "visualScreenOff";
140 private static final String ALLOW_ATT_SCREEN_ON = "visualScreenOn";
141 private static final String ALLOW_ATT_CONV = "convos";
142 private static final String ALLOW_ATT_CONV_FROM = "convosFrom";
143 private static final String DISALLOW_TAG = "disallow";
144 private static final String DISALLOW_ATT_VISUAL_EFFECTS = "visualEffects";
145 private static final String STATE_TAG = "state";
146 private static final String STATE_ATT_CHANNELS_BYPASSING_DND = "areChannelsBypassingDnd";
147
148 // zen policy visual effects attributes
149 private static final String SHOW_ATT_FULL_SCREEN_INTENT = "showFullScreenIntent";
150 private static final String SHOW_ATT_LIGHTS = "showLights";
151 private static final String SHOW_ATT_PEEK = "shoePeek";
152 private static final String SHOW_ATT_STATUS_BAR_ICONS = "showStatusBarIcons";
153 private static final String SHOW_ATT_BADGES = "showBadges";
154 private static final String SHOW_ATT_AMBIENT = "showAmbient";
155 private static final String SHOW_ATT_NOTIFICATION_LIST = "showNotificationList";
156
157 private static final String CONDITION_ATT_ID = "id";
158 private static final String CONDITION_ATT_SUMMARY = "summary";
159 private static final String CONDITION_ATT_LINE1 = "line1";
160 private static final String CONDITION_ATT_LINE2 = "line2";
161 private static final String CONDITION_ATT_ICON = "icon";
162 private static final String CONDITION_ATT_STATE = "state";
163 private static final String CONDITION_ATT_FLAGS = "flags";
164
165 private static final String ZEN_POLICY_TAG = "zen_policy";
166
167 private static final String MANUAL_TAG = "manual";
168 private static final String AUTOMATIC_TAG = "automatic";
169
170 private static final String RULE_ATT_ID = "ruleId";
171 private static final String RULE_ATT_ENABLED = "enabled";
172 private static final String RULE_ATT_SNOOZING = "snoozing";
173 private static final String RULE_ATT_NAME = "name";
174 private static final String RULE_ATT_PKG = "pkg";
175 private static final String RULE_ATT_COMPONENT = "component";
176 private static final String RULE_ATT_CONFIG_ACTIVITY = "configActivity";
177 private static final String RULE_ATT_ZEN = "zen";
178 private static final String RULE_ATT_CONDITION_ID = "conditionId";
179 private static final String RULE_ATT_CREATION_TIME = "creationTime";
180 private static final String RULE_ATT_ENABLER = "enabler";
181 private static final String RULE_ATT_MODIFIED = "modified";
182
183 @UnsupportedAppUsage
184 public boolean allowAlarms = DEFAULT_ALLOW_ALARMS;
185 public boolean allowMedia = DEFAULT_ALLOW_MEDIA;
186 public boolean allowSystem = DEFAULT_ALLOW_SYSTEM;
187 public boolean allowCalls = DEFAULT_ALLOW_CALLS;
188 public boolean allowRepeatCallers = DEFAULT_ALLOW_REPEAT_CALLERS;
189 public boolean allowMessages = DEFAULT_ALLOW_MESSAGES;
190 public boolean allowReminders = DEFAULT_ALLOW_REMINDERS;
191 public boolean allowEvents = DEFAULT_ALLOW_EVENTS;
192 public int allowCallsFrom = DEFAULT_CALLS_SOURCE;
193 public int allowMessagesFrom = DEFAULT_SOURCE;
194 public boolean allowConversations = DEFAULT_ALLOW_CONV;
195 public int allowConversationsFrom = DEFAULT_ALLOW_CONV_FROM;
196 public int user = UserHandle.USER_SYSTEM;
197 public int suppressedVisualEffects = DEFAULT_SUPPRESSED_VISUAL_EFFECTS;
198 public boolean areChannelsBypassingDnd = DEFAULT_CHANNELS_BYPASSING_DND;
199 public int version;
200
201 public ZenRule manualRule;
202 @UnsupportedAppUsage
203 public ArrayMap<String, ZenRule> automaticRules = new ArrayMap<>();
204
205 @UnsupportedAppUsage
206 public ZenModeConfig() { }
207
208 public ZenModeConfig(Parcel source) {
209 allowCalls = source.readInt() == 1;
210 allowRepeatCallers = source.readInt() == 1;
211 allowMessages = source.readInt() == 1;
212 allowReminders = source.readInt() == 1;
213 allowEvents = source.readInt() == 1;
214 allowCallsFrom = source.readInt();
215 allowMessagesFrom = source.readInt();
216 user = source.readInt();
217 manualRule = source.readParcelable(null, android.service.notification.ZenModeConfig.ZenRule.class);
218 final int len = source.readInt();
219 if (len > 0) {
220 final String[] ids = new String[len];
221 final ZenRule[] rules = new ZenRule[len];
222 source.readStringArray(ids);
223 source.readTypedArray(rules, ZenRule.CREATOR);
224 for (int i = 0; i < len; i++) {
225 automaticRules.put(ids[i], rules[i]);
226 }
227 }
228 allowAlarms = source.readInt() == 1;
229 allowMedia = source.readInt() == 1;
230 allowSystem = source.readInt() == 1;
231 suppressedVisualEffects = source.readInt();
232 areChannelsBypassingDnd = source.readInt() == 1;
233 allowConversations = source.readBoolean();
234 allowConversationsFrom = source.readInt();
235 }
236
237 @Override
238 public void writeToParcel(Parcel dest, int flags) {
239 dest.writeInt(allowCalls ? 1 : 0);
240 dest.writeInt(allowRepeatCallers ? 1 : 0);
241 dest.writeInt(allowMessages ? 1 : 0);
242 dest.writeInt(allowReminders ? 1 : 0);
243 dest.writeInt(allowEvents ? 1 : 0);
244 dest.writeInt(allowCallsFrom);
245 dest.writeInt(allowMessagesFrom);
246 dest.writeInt(user);
247 dest.writeParcelable(manualRule, 0);
248 if (!automaticRules.isEmpty()) {
249 final int len = automaticRules.size();
250 final String[] ids = new String[len];
251 final ZenRule[] rules = new ZenRule[len];
252 for (int i = 0; i < len; i++) {
253 ids[i] = automaticRules.keyAt(i);
254 rules[i] = automaticRules.valueAt(i);
255 }
256 dest.writeInt(len);
257 dest.writeStringArray(ids);
258 dest.writeTypedArray(rules, 0);
259 } else {
260 dest.writeInt(0);
261 }
262 dest.writeInt(allowAlarms ? 1 : 0);
263 dest.writeInt(allowMedia ? 1 : 0);
264 dest.writeInt(allowSystem ? 1 : 0);
265 dest.writeInt(suppressedVisualEffects);
266 dest.writeInt(areChannelsBypassingDnd ? 1 : 0);
267 dest.writeBoolean(allowConversations);
268 dest.writeInt(allowConversationsFrom);
269 }
270
271 @Override
272 public String toString() {
273 return new StringBuilder(ZenModeConfig.class.getSimpleName()).append('[')
274 .append("user=").append(user)
275 .append(",allowAlarms=").append(allowAlarms)
276 .append(",allowMedia=").append(allowMedia)
277 .append(",allowSystem=").append(allowSystem)
278 .append(",allowReminders=").append(allowReminders)
279 .append(",allowEvents=").append(allowEvents)
280 .append(",allowCalls=").append(allowCalls)
281 .append(",allowRepeatCallers=").append(allowRepeatCallers)
282 .append(",allowMessages=").append(allowMessages)
283 .append(",allowConversations=").append(allowConversations)
284 .append(",allowCallsFrom=").append(sourceToString(allowCallsFrom))
285 .append(",allowMessagesFrom=").append(sourceToString(allowMessagesFrom))
286 .append(",allowConvFrom=").append(ZenPolicy.conversationTypeToString
287 (allowConversationsFrom))
288 .append(",suppressedVisualEffects=").append(suppressedVisualEffects)
289 .append(",areChannelsBypassingDnd=").append(areChannelsBypassingDnd)
290 .append(",\nautomaticRules=").append(rulesToString())
291 .append(",\nmanualRule=").append(manualRule)
292 .append(']').toString();
293 }
294
295 private String rulesToString() {
296 if (automaticRules.isEmpty()) {
297 return "{}";
298 }
299
300 StringBuilder buffer = new StringBuilder(automaticRules.size() * 28);
301 buffer.append("{\n");
302 for (int i = 0; i < automaticRules.size(); i++) {
303 if (i > 0) {
304 buffer.append(",\n");
305 }
306 Object value = automaticRules.valueAt(i);
307 buffer.append(value);
308 }
309 buffer.append('}');
310 return buffer.toString();
311 }
312
313 public Diff diff(ZenModeConfig to) {
314 final Diff d = new Diff();
315 if (to == null) {
316 return d.addLine("config", "delete");
317 }
318 if (user != to.user) {
319 d.addLine("user", user, to.user);
320 }
321 if (allowAlarms != to.allowAlarms) {
322 d.addLine("allowAlarms", allowAlarms, to.allowAlarms);
323 }
324 if (allowMedia != to.allowMedia) {
325 d.addLine("allowMedia", allowMedia, to.allowMedia);
326 }
327 if (allowSystem != to.allowSystem) {
328 d.addLine("allowSystem", allowSystem, to.allowSystem);
329 }
330 if (allowCalls != to.allowCalls) {
331 d.addLine("allowCalls", allowCalls, to.allowCalls);
332 }
333 if (allowReminders != to.allowReminders) {
334 d.addLine("allowReminders", allowReminders, to.allowReminders);
335 }
336 if (allowEvents != to.allowEvents) {
337 d.addLine("allowEvents", allowEvents, to.allowEvents);
338 }
339 if (allowRepeatCallers != to.allowRepeatCallers) {
340 d.addLine("allowRepeatCallers", allowRepeatCallers, to.allowRepeatCallers);
341 }
342 if (allowMessages != to.allowMessages) {
343 d.addLine("allowMessages", allowMessages, to.allowMessages);
344 }
345 if (allowCallsFrom != to.allowCallsFrom) {
346 d.addLine("allowCallsFrom", allowCallsFrom, to.allowCallsFrom);
347 }
348 if (allowMessagesFrom != to.allowMessagesFrom) {
349 d.addLine("allowMessagesFrom", allowMessagesFrom, to.allowMessagesFrom);
350 }
351 if (suppressedVisualEffects != to.suppressedVisualEffects) {
352 d.addLine("suppressedVisualEffects", suppressedVisualEffects,
353 to.suppressedVisualEffects);
354 }
355 final ArraySet<String> allRules = new ArraySet<>();
356 addKeys(allRules, automaticRules);
357 addKeys(allRules, to.automaticRules);
358 final int N = allRules.size();
359 for (int i = 0; i < N; i++) {
360 final String rule = allRules.valueAt(i);
361 final ZenRule fromRule = automaticRules != null ? automaticRules.get(rule) : null;
362 final ZenRule toRule = to.automaticRules != null ? to.automaticRules.get(rule) : null;
363 ZenRule.appendDiff(d, "automaticRule[" + rule + "]", fromRule, toRule);
364 }
365 ZenRule.appendDiff(d, "manualRule", manualRule, to.manualRule);
366
367 if (areChannelsBypassingDnd != to.areChannelsBypassingDnd) {
368 d.addLine("areChannelsBypassingDnd", areChannelsBypassingDnd,
369 to.areChannelsBypassingDnd);
370 }
371 return d;
372 }
373
374 public static Diff diff(ZenModeConfig from, ZenModeConfig to) {
375 if (from == null) {
376 final Diff d = new Diff();
377 if (to != null) {
378 d.addLine("config", "insert");
379 }
380 return d;
381 }
382 return from.diff(to);
383 }
384
385 private static <T> void addKeys(ArraySet<T> set, ArrayMap<T, ?> map) {
386 if (map != null) {
387 for (int i = 0; i < map.size(); i++) {
388 set.add(map.keyAt(i));
389 }
390 }
391 }
392
393 public boolean isValid() {
394 if (!isValidManualRule(manualRule)) return false;
395 final int N = automaticRules.size();
396 for (int i = 0; i < N; i++) {
397 if (!isValidAutomaticRule(automaticRules.valueAt(i))) return false;
398 }
399 return true;
400 }
401
402 private static boolean isValidManualRule(ZenRule rule) {
403 return rule == null || Global.isValidZenMode(rule.zenMode) && sameCondition(rule);
404 }
405
406 private static boolean isValidAutomaticRule(ZenRule rule) {
407 return rule != null && !TextUtils.isEmpty(rule.name) && Global.isValidZenMode(rule.zenMode)
408 && rule.conditionId != null && sameCondition(rule);
409 }
410
411 private static boolean sameCondition(ZenRule rule) {
412 if (rule == null) return false;
413 if (rule.conditionId == null) {
414 return rule.condition == null;
415 } else {
416 return rule.condition == null || rule.conditionId.equals(rule.condition.id);
417 }
418 }
419
420 private static int[] generateMinuteBuckets() {
421 final int maxHrs = 12;
422 final int[] buckets = new int[maxHrs + 3];
423 buckets[0] = 15;
424 buckets[1] = 30;
425 buckets[2] = 45;
426 for (int i = 1; i <= maxHrs; i++) {
427 buckets[2 + i] = 60 * i;
428 }
429 return buckets;
430 }
431
432 public static String sourceToString(int source) {
433 switch (source) {
434 case SOURCE_ANYONE:
435 return "anyone";
436 case SOURCE_CONTACT:
437 return "contacts";
438 case SOURCE_STAR:
439 return "stars";
440 default:
441 return "UNKNOWN";
442 }
443 }
444
445 @Override
446 public boolean equals(@Nullable Object o) {
447 if (!(o instanceof ZenModeConfig)) return false;
448 if (o == this) return true;
449 final ZenModeConfig other = (ZenModeConfig) o;
450 return other.allowAlarms == allowAlarms
451 && other.allowMedia == allowMedia
452 && other.allowSystem == allowSystem
453 && other.allowCalls == allowCalls
454 && other.allowRepeatCallers == allowRepeatCallers
455 && other.allowMessages == allowMessages
456 && other.allowCallsFrom == allowCallsFrom
457 && other.allowMessagesFrom == allowMessagesFrom
458 && other.allowReminders == allowReminders
459 && other.allowEvents == allowEvents
460 && other.user == user
461 && Objects.equals(other.automaticRules, automaticRules)
462 && Objects.equals(other.manualRule, manualRule)
463 && other.suppressedVisualEffects == suppressedVisualEffects
464 && other.areChannelsBypassingDnd == areChannelsBypassingDnd
465 && other.allowConversations == allowConversations
466 && other.allowConversationsFrom == allowConversationsFrom;
467 }
468
469 @Override
470 public int hashCode() {
471 return Objects.hash(allowAlarms, allowMedia, allowSystem, allowCalls,
472 allowRepeatCallers, allowMessages,
473 allowCallsFrom, allowMessagesFrom, allowReminders, allowEvents,
474 user, automaticRules, manualRule,
475 suppressedVisualEffects, areChannelsBypassingDnd, allowConversations,
476 allowConversationsFrom);
477 }
478
479 private static String toDayList(int[] days) {
480 if (days == null || days.length == 0) return "";
481 final StringBuilder sb = new StringBuilder();
482 for (int i = 0; i < days.length; i++) {
483 if (i > 0) sb.append('.');
484 sb.append(days[i]);
485 }
486 return sb.toString();
487 }
488
489 private static int[] tryParseDayList(String dayList, String sep) {
490 if (dayList == null) return null;
491 final String[] tokens = dayList.split(sep);
492 if (tokens.length == 0) return null;
493 final int[] rt = new int[tokens.length];
494 for (int i = 0; i < tokens.length; i++) {
495 final int day = tryParseInt(tokens[i], -1);
496 if (day == -1) return null;
497 rt[i] = day;
498 }
499 return rt;
500 }
501
502 private static int tryParseInt(String value, int defValue) {
503 if (TextUtils.isEmpty(value)) return defValue;
504 try {
505 return Integer.parseInt(value);
506 } catch (NumberFormatException e) {
507 return defValue;
508 }
509 }
510
511 private static long tryParseLong(String value, long defValue) {
512 if (TextUtils.isEmpty(value)) return defValue;
513 try {
514 return Long.parseLong(value);
515 } catch (NumberFormatException e) {
516 return defValue;
517 }
518 }
519
520 private static Long tryParseLong(String value, Long defValue) {
521 if (TextUtils.isEmpty(value)) return defValue;
522 try {
523 return Long.parseLong(value);
524 } catch (NumberFormatException e) {
525 return defValue;
526 }
527 }
528
529 public static ZenModeConfig readXml(TypedXmlPullParser parser)
530 throws XmlPullParserException, IOException {
531 int type = parser.getEventType();
532 if (type != XmlPullParser.START_TAG) return null;
533 String tag = parser.getName();
534 if (!ZEN_TAG.equals(tag)) return null;
535 final ZenModeConfig rt = new ZenModeConfig();
536 rt.version = safeInt(parser, ZEN_ATT_VERSION, XML_VERSION);
537 rt.user = safeInt(parser, ZEN_ATT_USER, rt.user);
538 boolean readSuppressedEffects = false;
539 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
540 tag = parser.getName();
541 if (type == XmlPullParser.END_TAG && ZEN_TAG.equals(tag)) {
542 return rt;
543 }
544 if (type == XmlPullParser.START_TAG) {
545 if (ALLOW_TAG.equals(tag)) {
546 rt.allowCalls = safeBoolean(parser, ALLOW_ATT_CALLS,
547 DEFAULT_ALLOW_CALLS);
548 rt.allowRepeatCallers = safeBoolean(parser, ALLOW_ATT_REPEAT_CALLERS,
549 DEFAULT_ALLOW_REPEAT_CALLERS);
550 rt.allowMessages = safeBoolean(parser, ALLOW_ATT_MESSAGES,
551 DEFAULT_ALLOW_MESSAGES);
552 rt.allowReminders = safeBoolean(parser, ALLOW_ATT_REMINDERS,
553 DEFAULT_ALLOW_REMINDERS);
554 rt.allowConversations = safeBoolean(parser, ALLOW_ATT_CONV, DEFAULT_ALLOW_CONV);
555 rt.allowEvents = safeBoolean(parser, ALLOW_ATT_EVENTS, DEFAULT_ALLOW_EVENTS);
556 final int from = safeInt(parser, ALLOW_ATT_FROM, -1);
557 final int callsFrom = safeInt(parser, ALLOW_ATT_CALLS_FROM, -1);
558 final int messagesFrom = safeInt(parser, ALLOW_ATT_MESSAGES_FROM, -1);
559 rt.allowConversationsFrom = safeInt(parser, ALLOW_ATT_CONV_FROM,
560 DEFAULT_ALLOW_CONV_FROM);
561 if (isValidSource(callsFrom) && isValidSource(messagesFrom)) {
562 rt.allowCallsFrom = callsFrom;
563 rt.allowMessagesFrom = messagesFrom;
564 } else if (isValidSource(from)) {
565 Slog.i(TAG, "Migrating existing shared 'from': " + sourceToString(from));
566 rt.allowCallsFrom = from;
567 rt.allowMessagesFrom = from;
568 } else {
569 rt.allowCallsFrom = DEFAULT_CALLS_SOURCE;
570 rt.allowMessagesFrom = DEFAULT_SOURCE;
571 }
572 rt.allowAlarms = safeBoolean(parser, ALLOW_ATT_ALARMS, DEFAULT_ALLOW_ALARMS);
573 rt.allowMedia = safeBoolean(parser, ALLOW_ATT_MEDIA,
574 DEFAULT_ALLOW_MEDIA);
575 rt.allowSystem = safeBoolean(parser, ALLOW_ATT_SYSTEM, DEFAULT_ALLOW_SYSTEM);
576
577 // migrate old suppressed visual effects fields, if they still exist in the xml
578 Boolean allowWhenScreenOff = unsafeBoolean(parser, ALLOW_ATT_SCREEN_OFF);
579 Boolean allowWhenScreenOn = unsafeBoolean(parser, ALLOW_ATT_SCREEN_ON);
580 if (allowWhenScreenOff != null || allowWhenScreenOn != null) {
581 // If either setting exists, then reset the suppressed visual effects field
582 // to 0 (all allowed) so that only the relevant bits are disallowed by
583 // the migrated settings.
584 readSuppressedEffects = true;
585 rt.suppressedVisualEffects = 0;
586 }
587 if (allowWhenScreenOff != null) {
588 if (!allowWhenScreenOff) {
589 rt.suppressedVisualEffects |= SUPPRESSED_EFFECT_LIGHTS
590 | SUPPRESSED_EFFECT_FULL_SCREEN_INTENT
591 | SUPPRESSED_EFFECT_AMBIENT;
592 }
593 }
594 if (allowWhenScreenOn != null) {
595 if (!allowWhenScreenOn) {
596 rt.suppressedVisualEffects |= SUPPRESSED_EFFECT_PEEK;
597 }
598 }
599 if (readSuppressedEffects) {
600 Slog.d(TAG, "Migrated visual effects to " + rt.suppressedVisualEffects);
601 }
602 } else if (DISALLOW_TAG.equals(tag) && !readSuppressedEffects) {
603 // only read from suppressed visual effects field if we haven't just migrated
604 // the values from allowOn/allowOff, lest we wipe out those settings
605 rt.suppressedVisualEffects = safeInt(parser, DISALLOW_ATT_VISUAL_EFFECTS,
606 DEFAULT_SUPPRESSED_VISUAL_EFFECTS);
607 } else if (MANUAL_TAG.equals(tag)) {
608 rt.manualRule = readRuleXml(parser);
609 } else if (AUTOMATIC_TAG.equals(tag)) {
610 final String id = parser.getAttributeValue(null, RULE_ATT_ID);
611 final ZenRule automaticRule = readRuleXml(parser);
612 if (id != null && automaticRule != null) {
613 automaticRule.id = id;
614 rt.automaticRules.put(id, automaticRule);
615 }
616 } else if (STATE_TAG.equals(tag)) {
617 rt.areChannelsBypassingDnd = safeBoolean(parser,
618 STATE_ATT_CHANNELS_BYPASSING_DND, DEFAULT_CHANNELS_BYPASSING_DND);
619 }
620 }
621 }
622 throw new IllegalStateException("Failed to reach END_DOCUMENT");
623 }
624
625 /**
626 * Writes XML of current ZenModeConfig
627 * @param out serializer
628 * @param version uses XML_VERSION if version is null
629 * @throws IOException
630 */
631 public void writeXml(TypedXmlSerializer out, Integer version) throws IOException {
632 out.startTag(null, ZEN_TAG);
633 out.attribute(null, ZEN_ATT_VERSION, version == null
634 ? Integer.toString(XML_VERSION) : Integer.toString(version));
635 out.attributeInt(null, ZEN_ATT_USER, user);
636 out.startTag(null, ALLOW_TAG);
637 out.attributeBoolean(null, ALLOW_ATT_CALLS, allowCalls);
638 out.attributeBoolean(null, ALLOW_ATT_REPEAT_CALLERS, allowRepeatCallers);
639 out.attributeBoolean(null, ALLOW_ATT_MESSAGES, allowMessages);
640 out.attributeBoolean(null, ALLOW_ATT_REMINDERS, allowReminders);
641 out.attributeBoolean(null, ALLOW_ATT_EVENTS, allowEvents);
642 out.attributeInt(null, ALLOW_ATT_CALLS_FROM, allowCallsFrom);
643 out.attributeInt(null, ALLOW_ATT_MESSAGES_FROM, allowMessagesFrom);
644 out.attributeBoolean(null, ALLOW_ATT_ALARMS, allowAlarms);
645 out.attributeBoolean(null, ALLOW_ATT_MEDIA, allowMedia);
646 out.attributeBoolean(null, ALLOW_ATT_SYSTEM, allowSystem);
647 out.attributeBoolean(null, ALLOW_ATT_CONV, allowConversations);
648 out.attributeInt(null, ALLOW_ATT_CONV_FROM, allowConversationsFrom);
649 out.endTag(null, ALLOW_TAG);
650
651 out.startTag(null, DISALLOW_TAG);
652 out.attributeInt(null, DISALLOW_ATT_VISUAL_EFFECTS, suppressedVisualEffects);
653 out.endTag(null, DISALLOW_TAG);
654
655 if (manualRule != null) {
656 out.startTag(null, MANUAL_TAG);
657 writeRuleXml(manualRule, out);
658 out.endTag(null, MANUAL_TAG);
659 }
660 final int N = automaticRules.size();
661 for (int i = 0; i < N; i++) {
662 final String id = automaticRules.keyAt(i);
663 final ZenRule automaticRule = automaticRules.valueAt(i);
664 out.startTag(null, AUTOMATIC_TAG);
665 out.attribute(null, RULE_ATT_ID, id);
666 writeRuleXml(automaticRule, out);
667 out.endTag(null, AUTOMATIC_TAG);
668 }
669
670 out.startTag(null, STATE_TAG);
671 out.attributeBoolean(null, STATE_ATT_CHANNELS_BYPASSING_DND, areChannelsBypassingDnd);
672 out.endTag(null, STATE_TAG);
673
674 out.endTag(null, ZEN_TAG);
675 }
676
677 public static ZenRule readRuleXml(TypedXmlPullParser parser) {
678 final ZenRule rt = new ZenRule();
679 rt.enabled = safeBoolean(parser, RULE_ATT_ENABLED, true);
680 rt.name = parser.getAttributeValue(null, RULE_ATT_NAME);
681 final String zen = parser.getAttributeValue(null, RULE_ATT_ZEN);
682 rt.zenMode = tryParseZenMode(zen, -1);
683 if (rt.zenMode == -1) {
684 Slog.w(TAG, "Bad zen mode in rule xml:" + zen);
685 return null;
686 }
687 rt.conditionId = safeUri(parser, RULE_ATT_CONDITION_ID);
688 rt.component = safeComponentName(parser, RULE_ATT_COMPONENT);
689 rt.configurationActivity = safeComponentName(parser, RULE_ATT_CONFIG_ACTIVITY);
690 rt.pkg = XmlUtils.readStringAttribute(parser, RULE_ATT_PKG);
691 if (rt.pkg == null) {
692 // backfill from component, if present. configActivity is not safe to backfill from
693 rt.pkg = rt.component != null ? rt.component.getPackageName() : null;
694 }
695 rt.creationTime = safeLong(parser, RULE_ATT_CREATION_TIME, 0);
696 rt.enabler = parser.getAttributeValue(null, RULE_ATT_ENABLER);
697 rt.condition = readConditionXml(parser);
698
699 // all default rules and user created rules updated to zenMode important interruptions
700 if (rt.zenMode != Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS
701 && Condition.isValidId(rt.conditionId, SYSTEM_AUTHORITY)) {
702 Slog.i(TAG, "Updating zenMode of automatic rule " + rt.name);
703 rt.zenMode = Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
704 }
705 rt.modified = safeBoolean(parser, RULE_ATT_MODIFIED, false);
706 rt.zenPolicy = readZenPolicyXml(parser);
707 return rt;
708 }
709
710 public static void writeRuleXml(ZenRule rule, TypedXmlSerializer out) throws IOException {
711 out.attributeBoolean(null, RULE_ATT_ENABLED, rule.enabled);
712 if (rule.name != null) {
713 out.attribute(null, RULE_ATT_NAME, rule.name);
714 }
715 out.attributeInt(null, RULE_ATT_ZEN, rule.zenMode);
716 if (rule.pkg != null) {
717 out.attribute(null, RULE_ATT_PKG, rule.pkg);
718 }
719 if (rule.component != null) {
720 out.attribute(null, RULE_ATT_COMPONENT, rule.component.flattenToString());
721 }
722 if (rule.configurationActivity != null) {
723 out.attribute(null, RULE_ATT_CONFIG_ACTIVITY,
724 rule.configurationActivity.flattenToString());
725 }
726 if (rule.conditionId != null) {
727 out.attribute(null, RULE_ATT_CONDITION_ID, rule.conditionId.toString());
728 }
729 out.attributeLong(null, RULE_ATT_CREATION_TIME, rule.creationTime);
730 if (rule.enabler != null) {
731 out.attribute(null, RULE_ATT_ENABLER, rule.enabler);
732 }
733 if (rule.condition != null) {
734 writeConditionXml(rule.condition, out);
735 }
736 if (rule.zenPolicy != null) {
737 writeZenPolicyXml(rule.zenPolicy, out);
738 }
739 out.attributeBoolean(null, RULE_ATT_MODIFIED, rule.modified);
740 }
741
742 public static Condition readConditionXml(TypedXmlPullParser parser) {
743 final Uri id = safeUri(parser, CONDITION_ATT_ID);
744 if (id == null) return null;
745 final String summary = parser.getAttributeValue(null, CONDITION_ATT_SUMMARY);
746 final String line1 = parser.getAttributeValue(null, CONDITION_ATT_LINE1);
747 final String line2 = parser.getAttributeValue(null, CONDITION_ATT_LINE2);
748 final int icon = safeInt(parser, CONDITION_ATT_ICON, -1);
749 final int state = safeInt(parser, CONDITION_ATT_STATE, -1);
750 final int flags = safeInt(parser, CONDITION_ATT_FLAGS, -1);
751 try {
752 return new Condition(id, summary, line1, line2, icon, state, flags);
753 } catch (IllegalArgumentException e) {
754 Slog.w(TAG, "Unable to read condition xml", e);
755 return null;
756 }
757 }
758
759 public static void writeConditionXml(Condition c, TypedXmlSerializer out) throws IOException {
760 out.attribute(null, CONDITION_ATT_ID, c.id.toString());
761 out.attribute(null, CONDITION_ATT_SUMMARY, c.summary);
762 out.attribute(null, CONDITION_ATT_LINE1, c.line1);
763 out.attribute(null, CONDITION_ATT_LINE2, c.line2);
764 out.attributeInt(null, CONDITION_ATT_ICON, c.icon);
765 out.attributeInt(null, CONDITION_ATT_STATE, c.state);
766 out.attributeInt(null, CONDITION_ATT_FLAGS, c.flags);
767 }
768
769 /**
770 * Read the zen policy from xml
771 * Returns null if no zen policy exists
772 */
773 public static ZenPolicy readZenPolicyXml(TypedXmlPullParser parser) {
774 boolean policySet = false;
775
776 ZenPolicy.Builder builder = new ZenPolicy.Builder();
777 final int calls = safeInt(parser, ALLOW_ATT_CALLS_FROM, ZenPolicy.PEOPLE_TYPE_UNSET);
778 final int messages = safeInt(parser, ALLOW_ATT_MESSAGES_FROM, ZenPolicy.PEOPLE_TYPE_UNSET);
779 final int repeatCallers = safeInt(parser, ALLOW_ATT_REPEAT_CALLERS, ZenPolicy.STATE_UNSET);
780 final int conversations = safeInt(parser, ALLOW_ATT_CONV_FROM,
781 ZenPolicy.CONVERSATION_SENDERS_UNSET);
782 final int alarms = safeInt(parser, ALLOW_ATT_ALARMS, ZenPolicy.STATE_UNSET);
783 final int media = safeInt(parser, ALLOW_ATT_MEDIA, ZenPolicy.STATE_UNSET);
784 final int system = safeInt(parser, ALLOW_ATT_SYSTEM, ZenPolicy.STATE_UNSET);
785 final int events = safeInt(parser, ALLOW_ATT_EVENTS, ZenPolicy.STATE_UNSET);
786 final int reminders = safeInt(parser, ALLOW_ATT_REMINDERS, ZenPolicy.STATE_UNSET);
787
788 if (calls != ZenPolicy.PEOPLE_TYPE_UNSET) {
789 builder.allowCalls(calls);
790 policySet = true;
791 }
792 if (messages != ZenPolicy.PEOPLE_TYPE_UNSET) {
793 builder.allowMessages(messages);
794 policySet = true;
795 }
796 if (repeatCallers != ZenPolicy.STATE_UNSET) {
797 builder.allowRepeatCallers(repeatCallers == ZenPolicy.STATE_ALLOW);
798 policySet = true;
799 }
800 if (conversations != ZenPolicy.CONVERSATION_SENDERS_UNSET) {
801 builder.allowConversations(conversations);
802 policySet = true;
803 }
804 if (alarms != ZenPolicy.STATE_UNSET) {
805 builder.allowAlarms(alarms == ZenPolicy.STATE_ALLOW);
806 policySet = true;
807 }
808 if (media != ZenPolicy.STATE_UNSET) {
809 builder.allowMedia(media == ZenPolicy.STATE_ALLOW);
810 policySet = true;
811 }
812 if (system != ZenPolicy.STATE_UNSET) {
813 builder.allowSystem(system == ZenPolicy.STATE_ALLOW);
814 policySet = true;
815 }
816 if (events != ZenPolicy.STATE_UNSET) {
817 builder.allowEvents(events == ZenPolicy.STATE_ALLOW);
818 policySet = true;
819 }
820 if (reminders != ZenPolicy.STATE_UNSET) {
821 builder.allowReminders(reminders == ZenPolicy.STATE_ALLOW);
822 policySet = true;
823 }
824
825 final int fullScreenIntent = safeInt(parser, SHOW_ATT_FULL_SCREEN_INTENT,
826 ZenPolicy.STATE_UNSET);
827 final int lights = safeInt(parser, SHOW_ATT_LIGHTS, ZenPolicy.STATE_UNSET);
828 final int peek = safeInt(parser, SHOW_ATT_PEEK, ZenPolicy.STATE_UNSET);
829 final int statusBar = safeInt(parser, SHOW_ATT_STATUS_BAR_ICONS, ZenPolicy.STATE_UNSET);
830 final int badges = safeInt(parser, SHOW_ATT_BADGES, ZenPolicy.STATE_UNSET);
831 final int ambient = safeInt(parser, SHOW_ATT_AMBIENT, ZenPolicy.STATE_UNSET);
832 final int notificationList = safeInt(parser, SHOW_ATT_NOTIFICATION_LIST,
833 ZenPolicy.STATE_UNSET);
834
835 if (fullScreenIntent != ZenPolicy.STATE_UNSET) {
836 builder.showFullScreenIntent(fullScreenIntent == ZenPolicy.STATE_ALLOW);
837 policySet = true;
838 }
839 if (lights != ZenPolicy.STATE_UNSET) {
840 builder.showLights(lights == ZenPolicy.STATE_ALLOW);
841 policySet = true;
842 }
843 if (peek != ZenPolicy.STATE_UNSET) {
844 builder.showPeeking(peek == ZenPolicy.STATE_ALLOW);
845 policySet = true;
846 }
847 if (statusBar != ZenPolicy.STATE_UNSET) {
848 builder.showStatusBarIcons(statusBar == ZenPolicy.STATE_ALLOW);
849 policySet = true;
850 }
851 if (badges != ZenPolicy.STATE_UNSET) {
852 builder.showBadges(badges == ZenPolicy.STATE_ALLOW);
853 policySet = true;
854 }
855 if (ambient != ZenPolicy.STATE_UNSET) {
856 builder.showInAmbientDisplay(ambient == ZenPolicy.STATE_ALLOW);
857 policySet = true;
858 }
859 if (notificationList != ZenPolicy.STATE_UNSET) {
860 builder.showInNotificationList(notificationList == ZenPolicy.STATE_ALLOW);
861 policySet = true;
862 }
863
864 if (policySet) {
865 return builder.build();
866 }
867 return null;
868 }
869
870 /**
871 * Writes zen policy to xml
872 */
873 public static void writeZenPolicyXml(ZenPolicy policy, TypedXmlSerializer out)
874 throws IOException {
875 writeZenPolicyState(ALLOW_ATT_CALLS_FROM, policy.getPriorityCallSenders(), out);
876 writeZenPolicyState(ALLOW_ATT_MESSAGES_FROM, policy.getPriorityMessageSenders(), out);
877 writeZenPolicyState(ALLOW_ATT_REPEAT_CALLERS, policy.getPriorityCategoryRepeatCallers(),
878 out);
879 writeZenPolicyState(ALLOW_ATT_CONV_FROM, policy.getPriorityConversationSenders(), out);
880 writeZenPolicyState(ALLOW_ATT_ALARMS, policy.getPriorityCategoryAlarms(), out);
881 writeZenPolicyState(ALLOW_ATT_MEDIA, policy.getPriorityCategoryMedia(), out);
882 writeZenPolicyState(ALLOW_ATT_SYSTEM, policy.getPriorityCategorySystem(), out);
883 writeZenPolicyState(ALLOW_ATT_REMINDERS, policy.getPriorityCategoryReminders(), out);
884 writeZenPolicyState(ALLOW_ATT_EVENTS, policy.getPriorityCategoryEvents(), out);
885
886 writeZenPolicyState(SHOW_ATT_FULL_SCREEN_INTENT, policy.getVisualEffectFullScreenIntent(),
887 out);
888 writeZenPolicyState(SHOW_ATT_LIGHTS, policy.getVisualEffectLights(), out);
889 writeZenPolicyState(SHOW_ATT_PEEK, policy.getVisualEffectPeek(), out);
890 writeZenPolicyState(SHOW_ATT_STATUS_BAR_ICONS, policy.getVisualEffectStatusBar(), out);
891 writeZenPolicyState(SHOW_ATT_BADGES, policy.getVisualEffectBadge(), out);
892 writeZenPolicyState(SHOW_ATT_AMBIENT, policy.getVisualEffectAmbient(), out);
893 writeZenPolicyState(SHOW_ATT_NOTIFICATION_LIST, policy.getVisualEffectNotificationList(),
894 out);
895 }
896
897 private static void writeZenPolicyState(String attr, int val, TypedXmlSerializer out)
898 throws IOException {
899 if (Objects.equals(attr, ALLOW_ATT_CALLS_FROM)
900 || Objects.equals(attr, ALLOW_ATT_MESSAGES_FROM)) {
901 if (val != ZenPolicy.PEOPLE_TYPE_UNSET) {
902 out.attributeInt(null, attr, val);
903 }
904 } else if (Objects.equals(attr, ALLOW_ATT_CONV_FROM)) {
905 if (val != ZenPolicy.CONVERSATION_SENDERS_UNSET) {
906 out.attributeInt(null, attr, val);
907 }
908 } else {
909 if (val != ZenPolicy.STATE_UNSET) {
910 out.attributeInt(null, attr, val);
911 }
912 }
913 }
914
915 public static boolean isValidHour(int val) {
916 return val >= 0 && val < 24;
917 }
918
919 public static boolean isValidMinute(int val) {
920 return val >= 0 && val < 60;
921 }
922
923 private static boolean isValidSource(int source) {
924 return source >= SOURCE_ANYONE && source <= MAX_SOURCE;
925 }
926
927 private static Boolean unsafeBoolean(TypedXmlPullParser parser, String att) {
928 try {
929 return parser.getAttributeBoolean(null, att);
930 } catch (Exception e) {
931 return null;
932 }
933 }
934
935 private static boolean safeBoolean(TypedXmlPullParser parser, String att, boolean defValue) {
936 return parser.getAttributeBoolean(null, att, defValue);
937 }
938
939 private static boolean safeBoolean(String val, boolean defValue) {
940 if (TextUtils.isEmpty(val)) return defValue;
941 return Boolean.parseBoolean(val);
942 }
943
944 private static int safeInt(TypedXmlPullParser parser, String att, int defValue) {
945 return parser.getAttributeInt(null, att, defValue);
946 }
947
948 private static ComponentName safeComponentName(TypedXmlPullParser parser, String att) {
949 final String val = parser.getAttributeValue(null, att);
950 if (TextUtils.isEmpty(val)) return null;
951 return ComponentName.unflattenFromString(val);
952 }
953
954 private static Uri safeUri(TypedXmlPullParser parser, String att) {
955 final String val = parser.getAttributeValue(null, att);
956 if (TextUtils.isEmpty(val)) return null;
957 return Uri.parse(val);
958 }
959
960 private static long safeLong(TypedXmlPullParser parser, String att, long defValue) {
961 final String val = parser.getAttributeValue(null, att);
962 return tryParseLong(val, defValue);
963 }
964
965 @Override
966 public int describeContents() {
967 return 0;
968 }
969
970 public ZenModeConfig copy() {
971 final Parcel parcel = Parcel.obtain();
972 try {
973 writeToParcel(parcel, 0);
974 parcel.setDataPosition(0);
975 return new ZenModeConfig(parcel);
976 } finally {
977 parcel.recycle();
978 }
979 }
980
981 public static final @android.annotation.NonNull Parcelable.Creator<ZenModeConfig> CREATOR
982 = new Parcelable.Creator<ZenModeConfig>() {
983 @Override
984 public ZenModeConfig createFromParcel(Parcel source) {
985 return new ZenModeConfig(source);
986 }
987
988 @Override
989 public ZenModeConfig[] newArray(int size) {
990 return new ZenModeConfig[size];
991 }
992 };
993
994 /**
995 * Converts a ZenModeConfig to a ZenPolicy
996 */
997 public ZenPolicy toZenPolicy() {
998 ZenPolicy.Builder builder = new ZenPolicy.Builder()
999 .allowCalls(allowCalls
1000 ? ZenModeConfig.getZenPolicySenders(allowCallsFrom)
1001 : ZenPolicy.PEOPLE_TYPE_NONE)
1002 .allowRepeatCallers(allowRepeatCallers)
1003 .allowMessages(allowMessages
1004 ? ZenModeConfig.getZenPolicySenders(allowMessagesFrom)
1005 : ZenPolicy.PEOPLE_TYPE_NONE)
1006 .allowReminders(allowReminders)
1007 .allowEvents(allowEvents)
1008 .allowAlarms(allowAlarms)
1009 .allowMedia(allowMedia)
1010 .allowSystem(allowSystem)
1011 .allowConversations(allowConversations
1012 ? ZenModeConfig.getZenPolicySenders(allowConversationsFrom)
1013 : ZenPolicy.PEOPLE_TYPE_NONE);
1014 if (suppressedVisualEffects == 0) {
1015 builder.showAllVisualEffects();
1016 } else {
1017 // configs don't have an unset state: wither true or false.
1018 builder.showFullScreenIntent(
1019 (suppressedVisualEffects & Policy.SUPPRESSED_EFFECT_FULL_SCREEN_INTENT) == 0);
1020 builder.showLights(
1021 (suppressedVisualEffects & SUPPRESSED_EFFECT_LIGHTS) == 0);
1022 builder.showPeeking(
1023 (suppressedVisualEffects & SUPPRESSED_EFFECT_PEEK) == 0);
1024 builder.showStatusBarIcons(
1025 (suppressedVisualEffects & Policy.SUPPRESSED_EFFECT_STATUS_BAR) == 0);
1026 builder.showBadges(
1027 (suppressedVisualEffects & Policy.SUPPRESSED_EFFECT_BADGE) == 0);
1028 builder.showInAmbientDisplay(
1029 (suppressedVisualEffects & SUPPRESSED_EFFECT_AMBIENT) == 0);
1030 builder.showInNotificationList(
1031 (suppressedVisualEffects & Policy.SUPPRESSED_EFFECT_NOTIFICATION_LIST) == 0);
1032 }
1033 return builder.build();
1034 }
1035
1036 /**
1037 * Converts a zenPolicy to a notificationPolicy using this ZenModeConfig's values as its
1038 * defaults for all unset values in zenPolicy
1039 */
1040 public Policy toNotificationPolicy(ZenPolicy zenPolicy) {
1041 NotificationManager.Policy defaultPolicy = toNotificationPolicy();
1042 int priorityCategories = 0;
1043 int suppressedVisualEffects = 0;
1044 int callSenders = defaultPolicy.priorityCallSenders;
1045 int messageSenders = defaultPolicy.priorityMessageSenders;
1046 int conversationSenders = defaultPolicy.priorityConversationSenders;
1047
1048 if (zenPolicy.isCategoryAllowed(ZenPolicy.PRIORITY_CATEGORY_REMINDERS,
1049 isPriorityCategoryEnabled(Policy.PRIORITY_CATEGORY_REMINDERS, defaultPolicy))) {
1050 priorityCategories |= Policy.PRIORITY_CATEGORY_REMINDERS;
1051 }
1052
1053 if (zenPolicy.isCategoryAllowed(ZenPolicy.PRIORITY_CATEGORY_EVENTS,
1054 isPriorityCategoryEnabled(Policy.PRIORITY_CATEGORY_EVENTS, defaultPolicy))) {
1055 priorityCategories |= Policy.PRIORITY_CATEGORY_EVENTS;
1056 }
1057
1058 if (zenPolicy.isCategoryAllowed(ZenPolicy.PRIORITY_CATEGORY_MESSAGES,
1059 isPriorityCategoryEnabled(Policy.PRIORITY_CATEGORY_MESSAGES, defaultPolicy))) {
1060 priorityCategories |= Policy.PRIORITY_CATEGORY_MESSAGES;
1061 messageSenders = getNotificationPolicySenders(zenPolicy.getPriorityMessageSenders(),
1062 messageSenders);
1063 }
1064
1065 if (zenPolicy.isCategoryAllowed(ZenPolicy.PRIORITY_CATEGORY_CONVERSATIONS,
1066 isPriorityCategoryEnabled(Policy.PRIORITY_CATEGORY_CONVERSATIONS, defaultPolicy))) {
1067 priorityCategories |= Policy.PRIORITY_CATEGORY_CONVERSATIONS;
1068 conversationSenders = getConversationSendersWithDefault(
1069 zenPolicy.getPriorityConversationSenders(), conversationSenders);
1070 }
1071
1072 if (zenPolicy.isCategoryAllowed(ZenPolicy.PRIORITY_CATEGORY_CALLS,
1073 isPriorityCategoryEnabled(Policy.PRIORITY_CATEGORY_CALLS, defaultPolicy))) {
1074 priorityCategories |= Policy.PRIORITY_CATEGORY_CALLS;
1075 callSenders = getNotificationPolicySenders(zenPolicy.getPriorityCallSenders(),
1076 callSenders);
1077 }
1078
1079 if (zenPolicy.isCategoryAllowed(ZenPolicy.PRIORITY_CATEGORY_REPEAT_CALLERS,
1080 isPriorityCategoryEnabled(Policy.PRIORITY_CATEGORY_REPEAT_CALLERS,
1081 defaultPolicy))) {
1082 priorityCategories |= Policy.PRIORITY_CATEGORY_REPEAT_CALLERS;
1083 }
1084
1085 if (zenPolicy.isCategoryAllowed(ZenPolicy.PRIORITY_CATEGORY_ALARMS,
1086 isPriorityCategoryEnabled(Policy.PRIORITY_CATEGORY_ALARMS, defaultPolicy))) {
1087 priorityCategories |= Policy.PRIORITY_CATEGORY_ALARMS;
1088 }
1089
1090 if (zenPolicy.isCategoryAllowed(ZenPolicy.PRIORITY_CATEGORY_MEDIA,
1091 isPriorityCategoryEnabled(Policy.PRIORITY_CATEGORY_MEDIA, defaultPolicy))) {
1092 priorityCategories |= Policy.PRIORITY_CATEGORY_MEDIA;
1093 }
1094
1095 if (zenPolicy.isCategoryAllowed(ZenPolicy.PRIORITY_CATEGORY_SYSTEM,
1096 isPriorityCategoryEnabled(Policy.PRIORITY_CATEGORY_SYSTEM, defaultPolicy))) {
1097 priorityCategories |= Policy.PRIORITY_CATEGORY_SYSTEM;
1098 }
1099
1100 boolean suppressFullScreenIntent = !zenPolicy.isVisualEffectAllowed(
1101 ZenPolicy.VISUAL_EFFECT_FULL_SCREEN_INTENT,
1102 isVisualEffectAllowed(Policy.SUPPRESSED_EFFECT_FULL_SCREEN_INTENT,
1103 defaultPolicy));
1104
1105 boolean suppressLights = !zenPolicy.isVisualEffectAllowed(
1106 ZenPolicy.VISUAL_EFFECT_LIGHTS,
1107 isVisualEffectAllowed(Policy.SUPPRESSED_EFFECT_LIGHTS,
1108 defaultPolicy));
1109
1110 boolean suppressAmbient = !zenPolicy.isVisualEffectAllowed(
1111 ZenPolicy.VISUAL_EFFECT_AMBIENT,
1112 isVisualEffectAllowed(SUPPRESSED_EFFECT_AMBIENT,
1113 defaultPolicy));
1114
1115 if (suppressFullScreenIntent && suppressLights && suppressAmbient) {
1116 suppressedVisualEffects |= Policy.SUPPRESSED_EFFECT_SCREEN_OFF;
1117 }
1118
1119 if (suppressFullScreenIntent) {
1120 suppressedVisualEffects |= Policy.SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
1121 }
1122
1123 if (suppressLights) {
1124 suppressedVisualEffects |= Policy.SUPPRESSED_EFFECT_LIGHTS;
1125 }
1126
1127 if (!zenPolicy.isVisualEffectAllowed(ZenPolicy.VISUAL_EFFECT_PEEK,
1128 isVisualEffectAllowed(Policy.SUPPRESSED_EFFECT_PEEK,
1129 defaultPolicy))) {
1130 suppressedVisualEffects |= Policy.SUPPRESSED_EFFECT_PEEK;
1131 suppressedVisualEffects |= Policy.SUPPRESSED_EFFECT_SCREEN_ON;
1132 }
1133
1134 if (!zenPolicy.isVisualEffectAllowed(ZenPolicy.VISUAL_EFFECT_STATUS_BAR,
1135 isVisualEffectAllowed(Policy.SUPPRESSED_EFFECT_STATUS_BAR,
1136 defaultPolicy))) {
1137 suppressedVisualEffects |= Policy.SUPPRESSED_EFFECT_STATUS_BAR;
1138 }
1139
1140 if (!zenPolicy.isVisualEffectAllowed(ZenPolicy.VISUAL_EFFECT_BADGE,
1141 isVisualEffectAllowed(Policy.SUPPRESSED_EFFECT_BADGE,
1142 defaultPolicy))) {
1143 suppressedVisualEffects |= Policy.SUPPRESSED_EFFECT_BADGE;
1144 }
1145
1146 if (suppressAmbient) {
1147 suppressedVisualEffects |= SUPPRESSED_EFFECT_AMBIENT;
1148 }
1149
1150 if (!zenPolicy.isVisualEffectAllowed(ZenPolicy.VISUAL_EFFECT_NOTIFICATION_LIST,
1151 isVisualEffectAllowed(Policy.SUPPRESSED_EFFECT_NOTIFICATION_LIST,
1152 defaultPolicy))) {
1153 suppressedVisualEffects |= Policy.SUPPRESSED_EFFECT_NOTIFICATION_LIST;
1154 }
1155
1156 return new NotificationManager.Policy(priorityCategories, callSenders,
1157 messageSenders, suppressedVisualEffects, defaultPolicy.state, conversationSenders);
1158 }
1159
1160 private boolean isPriorityCategoryEnabled(int categoryType, Policy policy) {
1161 return (policy.priorityCategories & categoryType) != 0;
1162 }
1163
1164 private boolean isVisualEffectAllowed(int visualEffect, Policy policy) {
1165 return (policy.suppressedVisualEffects & visualEffect) == 0;
1166 }
1167
1168 private int getNotificationPolicySenders(@ZenPolicy.PeopleType int senders,
1169 int defaultPolicySender) {
1170 switch (senders) {
1171 case ZenPolicy.PEOPLE_TYPE_ANYONE:
1172 return Policy.PRIORITY_SENDERS_ANY;
1173 case ZenPolicy.PEOPLE_TYPE_CONTACTS:
1174 return Policy.PRIORITY_SENDERS_CONTACTS;
1175 case ZenPolicy.PEOPLE_TYPE_STARRED:
1176 return Policy.PRIORITY_SENDERS_STARRED;
1177 default:
1178 return defaultPolicySender;
1179 }
1180 }
1181
1182 private int getConversationSendersWithDefault(@ZenPolicy.ConversationSenders int senders,
1183 int defaultPolicySender) {
1184 switch (senders) {
1185 case ZenPolicy.CONVERSATION_SENDERS_ANYONE:
1186 case ZenPolicy.CONVERSATION_SENDERS_IMPORTANT:
1187 case ZenPolicy.CONVERSATION_SENDERS_NONE:
1188 return senders;
1189 default:
1190 return defaultPolicySender;
1191 }
1192 }
1193
1194 /**
1195 * Maps NotificationManager.Policy senders type to ZenPolicy.PeopleType
1196 */
1197 public static @ZenPolicy.PeopleType int getZenPolicySenders(int senders) {
1198 switch (senders) {
1199 case Policy.PRIORITY_SENDERS_ANY:
1200 return ZenPolicy.PEOPLE_TYPE_ANYONE;
1201 case Policy.PRIORITY_SENDERS_CONTACTS:
1202 return ZenPolicy.PEOPLE_TYPE_CONTACTS;
1203 case Policy.PRIORITY_SENDERS_STARRED:
1204 default:
1205 return ZenPolicy.PEOPLE_TYPE_STARRED;
1206 }
1207 }
1208
1209 public Policy toNotificationPolicy() {
1210 int priorityCategories = 0;
1211 int priorityCallSenders = Policy.PRIORITY_SENDERS_CONTACTS;
1212 int priorityMessageSenders = Policy.PRIORITY_SENDERS_CONTACTS;
1213 int priorityConversationSenders = Policy.CONVERSATION_SENDERS_IMPORTANT;
1214 if (allowConversations) {
1215 priorityCategories |= Policy.PRIORITY_CATEGORY_CONVERSATIONS;
1216 }
1217 if (allowCalls) {
1218 priorityCategories |= Policy.PRIORITY_CATEGORY_CALLS;
1219 }
1220 if (allowMessages) {
1221 priorityCategories |= Policy.PRIORITY_CATEGORY_MESSAGES;
1222 }
1223 if (allowEvents) {
1224 priorityCategories |= Policy.PRIORITY_CATEGORY_EVENTS;
1225 }
1226 if (allowReminders) {
1227 priorityCategories |= Policy.PRIORITY_CATEGORY_REMINDERS;
1228 }
1229 if (allowRepeatCallers) {
1230 priorityCategories |= Policy.PRIORITY_CATEGORY_REPEAT_CALLERS;
1231 }
1232 if (allowAlarms) {
1233 priorityCategories |= Policy.PRIORITY_CATEGORY_ALARMS;
1234 }
1235 if (allowMedia) {
1236 priorityCategories |= Policy.PRIORITY_CATEGORY_MEDIA;
1237 }
1238 if (allowSystem) {
1239 priorityCategories |= Policy.PRIORITY_CATEGORY_SYSTEM;
1240 }
1241 priorityCallSenders = sourceToPrioritySenders(allowCallsFrom, priorityCallSenders);
1242 priorityMessageSenders = sourceToPrioritySenders(allowMessagesFrom, priorityMessageSenders);
1243 priorityConversationSenders = getConversationSendersWithDefault(
1244 allowConversationsFrom, priorityConversationSenders);
1245
1246 return new Policy(priorityCategories, priorityCallSenders, priorityMessageSenders,
1247 suppressedVisualEffects, areChannelsBypassingDnd
1248 ? Policy.STATE_CHANNELS_BYPASSING_DND : 0,
1249 priorityConversationSenders);
1250 }
1251
1252 /**
1253 * Creates scheduleCalendar from a condition id
1254 * @param conditionId
1255 * @return ScheduleCalendar with info populated with conditionId
1256 */
1257 public static ScheduleCalendar toScheduleCalendar(Uri conditionId) {
1258 final ScheduleInfo schedule = ZenModeConfig.tryParseScheduleConditionId(conditionId);
1259 if (schedule == null || schedule.days == null || schedule.days.length == 0) return null;
1260 final ScheduleCalendar sc = new ScheduleCalendar();
1261 sc.setSchedule(schedule);
1262 sc.setTimeZone(TimeZone.getDefault());
1263 return sc;
1264 }
1265
1266 private static int sourceToPrioritySenders(int source, int def) {
1267 switch (source) {
1268 case SOURCE_ANYONE: return Policy.PRIORITY_SENDERS_ANY;
1269 case SOURCE_CONTACT: return Policy.PRIORITY_SENDERS_CONTACTS;
1270 case SOURCE_STAR: return Policy.PRIORITY_SENDERS_STARRED;
1271 default: return def;
1272 }
1273 }
1274
1275 private static int prioritySendersToSource(int prioritySenders, int def) {
1276 switch (prioritySenders) {
1277 case Policy.PRIORITY_SENDERS_CONTACTS: return SOURCE_CONTACT;
1278 case Policy.PRIORITY_SENDERS_STARRED: return SOURCE_STAR;
1279 case Policy.PRIORITY_SENDERS_ANY: return SOURCE_ANYONE;
1280 default: return def;
1281 }
1282 }
1283
1284 private static int normalizePrioritySenders(int prioritySenders, int def) {
1285 if (!(prioritySenders == Policy.PRIORITY_SENDERS_CONTACTS
1286 || prioritySenders == Policy.PRIORITY_SENDERS_STARRED
1287 || prioritySenders == Policy.PRIORITY_SENDERS_ANY)) {
1288 return def;
1289 }
1290 return prioritySenders;
1291 }
1292
1293 private static int normalizeConversationSenders(boolean allowed, int senders, int def) {
1294 if (!allowed) {
1295 return CONVERSATION_SENDERS_NONE;
1296 }
1297 if (!(senders == CONVERSATION_SENDERS_ANYONE
1298 || senders == CONVERSATION_SENDERS_IMPORTANT
1299 || senders == CONVERSATION_SENDERS_NONE)) {
1300 return def;
1301 }
1302 return senders;
1303 }
1304
1305 public void applyNotificationPolicy(Policy policy) {
1306 if (policy == null) return;
1307 allowAlarms = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_ALARMS) != 0;
1308 allowMedia = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_MEDIA) != 0;
1309 allowSystem = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_SYSTEM) != 0;
1310 allowEvents = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_EVENTS) != 0;
1311 allowReminders = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_REMINDERS) != 0;
1312 allowCalls = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_CALLS) != 0;
1313 allowMessages = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_MESSAGES) != 0;
1314 allowRepeatCallers = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_REPEAT_CALLERS)
1315 != 0;
1316 allowCallsFrom = normalizePrioritySenders(policy.priorityCallSenders, allowCallsFrom);
1317 allowMessagesFrom = normalizePrioritySenders(policy.priorityMessageSenders,
1318 allowMessagesFrom);
1319 if (policy.suppressedVisualEffects != Policy.SUPPRESSED_EFFECTS_UNSET) {
1320 suppressedVisualEffects = policy.suppressedVisualEffects;
1321 }
1322 allowConversations = (policy.priorityCategories
1323 & Policy.PRIORITY_CATEGORY_CONVERSATIONS) != 0;
1324 allowConversationsFrom = normalizeConversationSenders(allowConversations,
1325 policy.priorityConversationSenders,
1326 allowConversationsFrom);
1327 if (policy.state != Policy.STATE_UNSET) {
1328 areChannelsBypassingDnd = (policy.state & Policy.STATE_CHANNELS_BYPASSING_DND) != 0;
1329 }
1330 }
1331
1332 public static Condition toTimeCondition(Context context, int minutesFromNow, int userHandle) {
1333 return toTimeCondition(context, minutesFromNow, userHandle, false /*shortVersion*/);
1334 }
1335
1336 public static Condition toTimeCondition(Context context, int minutesFromNow, int userHandle,
1337 boolean shortVersion) {
1338 final long now = System.currentTimeMillis();
1339 final long millis = minutesFromNow == 0 ? ZERO_VALUE_MS : minutesFromNow * MINUTES_MS;
1340 return toTimeCondition(context, now + millis, minutesFromNow, userHandle, shortVersion);
1341 }
1342
1343 public static Condition toTimeCondition(Context context, long time, int minutes,
1344 int userHandle, boolean shortVersion) {
1345 final int num;
1346 String summary, line1, line2;
1347 final CharSequence formattedTime =
1348 getFormattedTime(context, time, isToday(time), userHandle);
1349 final Resources res = context.getResources();
1350 final Map<String, Object> arguments = new HashMap<>();
1351 if (minutes < 60) {
1352 // display as minutes
1353 num = minutes;
1354 int summaryResId = shortVersion ? R.string.zen_mode_duration_minutes_summary_short
1355 : R.string.zen_mode_duration_minutes_summary;
1356 arguments.put("count", num);
1357 arguments.put("formattedTime", formattedTime);
1358 summary = PluralsMessageFormatter.format(res, arguments, summaryResId);
1359 int line1ResId = shortVersion ? R.string.zen_mode_duration_minutes_short
1360 : R.string.zen_mode_duration_minutes;
1361 line1 = PluralsMessageFormatter.format(res, arguments, line1ResId);
1362 line2 = res.getString(R.string.zen_mode_until, formattedTime);
1363 } else if (minutes < DAY_MINUTES) {
1364 // display as hours
1365 num = Math.round(minutes / 60f);
1366 int summaryResId = shortVersion ? R.string.zen_mode_duration_hours_summary_short
1367 : R.string.zen_mode_duration_hours_summary;
1368 arguments.put("count", num);
1369 arguments.put("formattedTime", formattedTime);
1370 summary = PluralsMessageFormatter.format(res, arguments, summaryResId);
1371 int line1ResId = shortVersion ? R.string.zen_mode_duration_hours_short
1372 : R.string.zen_mode_duration_hours;
1373 line1 = PluralsMessageFormatter.format(res, arguments, line1ResId);
1374 line2 = res.getString(R.string.zen_mode_until, formattedTime);
1375 } else {
1376 // display as day/time
1377 summary = line1 = line2 = res.getString(R.string.zen_mode_until_next_day,
1378 formattedTime);
1379 }
1380 final Uri id = toCountdownConditionId(time, false);
1381 return new Condition(id, summary, line1, line2, 0, Condition.STATE_TRUE,
1382 Condition.FLAG_RELEVANT_NOW);
1383 }
1384
1385 /**
1386 * Converts countdown to alarm parameters into a condition with user facing summary
1387 */
1388 public static Condition toNextAlarmCondition(Context context, long alarm,
1389 int userHandle) {
1390 boolean isSameDay = isToday(alarm);
1391 final CharSequence formattedTime = getFormattedTime(context, alarm, isSameDay, userHandle);
1392 final Resources res = context.getResources();
1393 final String line1 = res.getString(R.string.zen_mode_until, formattedTime);
1394 final Uri id = toCountdownConditionId(alarm, true);
1395 return new Condition(id, "", line1, "", 0, Condition.STATE_TRUE,
1396 Condition.FLAG_RELEVANT_NOW);
1397 }
1398
1399 /**
1400 * Creates readable time from time in milliseconds
1401 */
1402 public static CharSequence getFormattedTime(Context context, long time, boolean isSameDay,
1403 int userHandle) {
1404 String skeleton = (!isSameDay ? "EEE " : "")
1405 + (DateFormat.is24HourFormat(context, userHandle) ? "Hm" : "hma");
1406 final String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1407 return DateFormat.format(pattern, time);
1408 }
1409
1410 /**
1411 * Determines whether a time in milliseconds is today or not
1412 */
1413 public static boolean isToday(long time) {
1414 GregorianCalendar now = new GregorianCalendar();
1415 GregorianCalendar endTime = new GregorianCalendar();
1416 endTime.setTimeInMillis(time);
1417 if (now.get(Calendar.YEAR) == endTime.get(Calendar.YEAR)
1418 && now.get(Calendar.MONTH) == endTime.get(Calendar.MONTH)
1419 && now.get(Calendar.DATE) == endTime.get(Calendar.DATE)) {
1420 return true;
1421 }
1422 return false;
1423 }
1424
1425 // ==== Built-in system conditions ====
1426
1427 public static final String SYSTEM_AUTHORITY = "android";
1428
1429 // ==== Built-in system condition: countdown ====
1430
1431 public static final String COUNTDOWN_PATH = "countdown";
1432
1433 public static final String IS_ALARM_PATH = "alarm";
1434
1435 /**
1436 * Converts countdown condition parameters into a condition id.
1437 */
1438 public static Uri toCountdownConditionId(long time, boolean alarm) {
1439 return new Uri.Builder().scheme(Condition.SCHEME)
1440 .authority(SYSTEM_AUTHORITY)
1441 .appendPath(COUNTDOWN_PATH)
1442 .appendPath(Long.toString(time))
1443 .appendPath(IS_ALARM_PATH)
1444 .appendPath(Boolean.toString(alarm))
1445 .build();
1446 }
1447
1448 public static long tryParseCountdownConditionId(Uri conditionId) {
1449 if (!Condition.isValidId(conditionId, SYSTEM_AUTHORITY)) return 0;
1450 if (conditionId.getPathSegments().size() < 2
1451 || !COUNTDOWN_PATH.equals(conditionId.getPathSegments().get(0))) return 0;
1452 try {
1453 return Long.parseLong(conditionId.getPathSegments().get(1));
1454 } catch (RuntimeException e) {
1455 Slog.w(TAG, "Error parsing countdown condition: " + conditionId, e);
1456 return 0;
1457 }
1458 }
1459
1460 /**
1461 * Returns whether this condition is a countdown condition.
1462 */
1463 public static boolean isValidCountdownConditionId(Uri conditionId) {
1464 return tryParseCountdownConditionId(conditionId) != 0;
1465 }
1466
1467 /**
1468 * Returns whether this condition is a countdown to an alarm.
1469 */
1470 public static boolean isValidCountdownToAlarmConditionId(Uri conditionId) {
1471 if (tryParseCountdownConditionId(conditionId) != 0) {
1472 if (conditionId.getPathSegments().size() < 4
1473 || !IS_ALARM_PATH.equals(conditionId.getPathSegments().get(2))) {
1474 return false;
1475 }
1476 try {
1477 return Boolean.parseBoolean(conditionId.getPathSegments().get(3));
1478 } catch (RuntimeException e) {
1479 Slog.w(TAG, "Error parsing countdown alarm condition: " + conditionId, e);
1480 return false;
1481 }
1482 }
1483 return false;
1484 }
1485
1486 // ==== Built-in system condition: schedule ====
1487
1488 public static final String SCHEDULE_PATH = "schedule";
1489
1490 public static Uri toScheduleConditionId(ScheduleInfo schedule) {
1491 return new Uri.Builder().scheme(Condition.SCHEME)
1492 .authority(SYSTEM_AUTHORITY)
1493 .appendPath(SCHEDULE_PATH)
1494 .appendQueryParameter("days", toDayList(schedule.days))
1495 .appendQueryParameter("start", schedule.startHour + "." + schedule.startMinute)
1496 .appendQueryParameter("end", schedule.endHour + "." + schedule.endMinute)
1497 .appendQueryParameter("exitAtAlarm", String.valueOf(schedule.exitAtAlarm))
1498 .build();
1499 }
1500
1501 public static boolean isValidScheduleConditionId(Uri conditionId) {
1502 ScheduleInfo info;
1503 try {
1504 info = tryParseScheduleConditionId(conditionId);
1505 } catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
1506 return false;
1507 }
1508
1509 if (info == null || info.days == null || info.days.length == 0) {
1510 return false;
1511 }
1512 return true;
1513 }
1514
1515 /**
1516 * Returns whether the conditionId is a valid ScheduleCondition.
1517 * If allowNever is true, this will return true even if the ScheduleCondition never occurs.
1518 */
1519 public static boolean isValidScheduleConditionId(Uri conditionId, boolean allowNever) {
1520 ScheduleInfo info;
1521 try {
1522 info = tryParseScheduleConditionId(conditionId);
1523 } catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
1524 return false;
1525 }
1526
1527 if (info == null || (!allowNever && (info.days == null || info.days.length == 0))) {
1528 return false;
1529 }
1530 return true;
1531 }
1532
1533 @UnsupportedAppUsage
1534 public static ScheduleInfo tryParseScheduleConditionId(Uri conditionId) {
1535 final boolean isSchedule = conditionId != null
1536 && Condition.SCHEME.equals(conditionId.getScheme())
1537 && ZenModeConfig.SYSTEM_AUTHORITY.equals(conditionId.getAuthority())
1538 && conditionId.getPathSegments().size() == 1
1539 && ZenModeConfig.SCHEDULE_PATH.equals(conditionId.getPathSegments().get(0));
1540 if (!isSchedule) return null;
1541 final int[] start = tryParseHourAndMinute(conditionId.getQueryParameter("start"));
1542 final int[] end = tryParseHourAndMinute(conditionId.getQueryParameter("end"));
1543 if (start == null || end == null) return null;
1544 final ScheduleInfo rt = new ScheduleInfo();
1545 rt.days = tryParseDayList(conditionId.getQueryParameter("days"), "\\.");
1546 rt.startHour = start[0];
1547 rt.startMinute = start[1];
1548 rt.endHour = end[0];
1549 rt.endMinute = end[1];
1550 rt.exitAtAlarm = safeBoolean(conditionId.getQueryParameter("exitAtAlarm"), false);
1551 return rt;
1552 }
1553
1554 public static ComponentName getScheduleConditionProvider() {
1555 return new ComponentName(SYSTEM_AUTHORITY, "ScheduleConditionProvider");
1556 }
1557
1558 public static class ScheduleInfo {
1559 @UnsupportedAppUsage
1560 public int[] days;
1561 @UnsupportedAppUsage
1562 public int startHour;
1563 @UnsupportedAppUsage
1564 public int startMinute;
1565 @UnsupportedAppUsage
1566 public int endHour;
1567 @UnsupportedAppUsage
1568 public int endMinute;
1569 public boolean exitAtAlarm;
1570 public long nextAlarm;
1571
1572 @Override
1573 public int hashCode() {
1574 return 0;
1575 }
1576
1577 @Override
1578 public boolean equals(@Nullable Object o) {
1579 if (!(o instanceof ScheduleInfo)) return false;
1580 final ScheduleInfo other = (ScheduleInfo) o;
1581 return toDayList(days).equals(toDayList(other.days))
1582 && startHour == other.startHour
1583 && startMinute == other.startMinute
1584 && endHour == other.endHour
1585 && endMinute == other.endMinute
1586 && exitAtAlarm == other.exitAtAlarm;
1587 }
1588
1589 public ScheduleInfo copy() {
1590 final ScheduleInfo rt = new ScheduleInfo();
1591 if (days != null) {
1592 rt.days = new int[days.length];
1593 System.arraycopy(days, 0, rt.days, 0, days.length);
1594 }
1595 rt.startHour = startHour;
1596 rt.startMinute = startMinute;
1597 rt.endHour = endHour;
1598 rt.endMinute = endMinute;
1599 rt.exitAtAlarm = exitAtAlarm;
1600 rt.nextAlarm = nextAlarm;
1601 return rt;
1602 }
1603
1604 @Override
1605 public String toString() {
1606 return "ScheduleInfo{" +
1607 "days=" + Arrays.toString(days) +
1608 ", startHour=" + startHour +
1609 ", startMinute=" + startMinute +
1610 ", endHour=" + endHour +
1611 ", endMinute=" + endMinute +
1612 ", exitAtAlarm=" + exitAtAlarm +
1613 ", nextAlarm=" + ts(nextAlarm) +
1614 '}';
1615 }
1616
1617 protected static String ts(long time) {
1618 return new Date(time) + " (" + time + ")";
1619 }
1620 }
1621
1622 // ==== Built-in system condition: event ====
1623
1624 public static final String EVENT_PATH = "event";
1625
1626 public static Uri toEventConditionId(EventInfo event) {
1627 return new Uri.Builder().scheme(Condition.SCHEME)
1628 .authority(SYSTEM_AUTHORITY)
1629 .appendPath(EVENT_PATH)
1630 .appendQueryParameter("userId", Long.toString(event.userId))
1631 .appendQueryParameter("calendar", event.calName != null ? event.calName : "")
1632 .appendQueryParameter("calendarId", event.calendarId != null
1633 ? event.calendarId.toString() : "")
1634 .appendQueryParameter("reply", Integer.toString(event.reply))
1635 .build();
1636 }
1637
1638 public static boolean isValidEventConditionId(Uri conditionId) {
1639 return tryParseEventConditionId(conditionId) != null;
1640 }
1641
1642 public static EventInfo tryParseEventConditionId(Uri conditionId) {
1643 final boolean isEvent = conditionId != null
1644 && Condition.SCHEME.equals(conditionId.getScheme())
1645 && ZenModeConfig.SYSTEM_AUTHORITY.equals(conditionId.getAuthority())
1646 && conditionId.getPathSegments().size() == 1
1647 && EVENT_PATH.equals(conditionId.getPathSegments().get(0));
1648 if (!isEvent) return null;
1649 final EventInfo rt = new EventInfo();
1650 rt.userId = tryParseInt(conditionId.getQueryParameter("userId"), UserHandle.USER_NULL);
1651 rt.calName = conditionId.getQueryParameter("calendar");
1652 if (TextUtils.isEmpty(rt.calName)) {
1653 rt.calName = null;
1654 }
1655 rt.calendarId = tryParseLong(conditionId.getQueryParameter("calendarId"), null);
1656 rt.reply = tryParseInt(conditionId.getQueryParameter("reply"), 0);
1657 return rt;
1658 }
1659
1660 public static ComponentName getEventConditionProvider() {
1661 return new ComponentName(SYSTEM_AUTHORITY, "EventConditionProvider");
1662 }
1663
1664 public static class EventInfo {
1665 public static final int REPLY_ANY_EXCEPT_NO = 0;
1666 public static final int REPLY_YES_OR_MAYBE = 1;
1667 public static final int REPLY_YES = 2;
1668
1669 public int userId = UserHandle.USER_NULL; // USER_NULL = unspecified - use current user
1670 public String calName; // CalendarContract.Calendars.DISPLAY_NAME, or null for any
1671 public Long calendarId; // Calendars._ID, or null if restored from < Q calendar
1672 public int reply;
1673
1674 @Override
1675 public int hashCode() {
1676 return Objects.hash(userId, calName, calendarId, reply);
1677 }
1678
1679 @Override
1680 public boolean equals(@Nullable Object o) {
1681 if (!(o instanceof EventInfo)) return false;
1682 final EventInfo other = (EventInfo) o;
1683 return userId == other.userId
1684 && Objects.equals(calName, other.calName)
1685 && reply == other.reply
1686 && Objects.equals(calendarId, other.calendarId);
1687 }
1688
1689 public EventInfo copy() {
1690 final EventInfo rt = new EventInfo();
1691 rt.userId = userId;
1692 rt.calName = calName;
1693 rt.reply = reply;
1694 rt.calendarId = calendarId;
1695 return rt;
1696 }
1697
1698 public static int resolveUserId(int userId) {
1699 return userId == UserHandle.USER_NULL ? ActivityManager.getCurrentUser() : userId;
1700 }
1701 }
1702
1703 // ==== End built-in system conditions ====
1704
1705 private static int[] tryParseHourAndMinute(String value) {
1706 if (TextUtils.isEmpty(value)) return null;
1707 final int i = value.indexOf('.');
1708 if (i < 1 || i >= value.length() - 1) return null;
1709 final int hour = tryParseInt(value.substring(0, i), -1);
1710 final int minute = tryParseInt(value.substring(i + 1), -1);
1711 return isValidHour(hour) && isValidMinute(minute) ? new int[] { hour, minute } : null;
1712 }
1713
1714 private static int tryParseZenMode(String value, int defValue) {
1715 final int rt = tryParseInt(value, defValue);
1716 return Global.isValidZenMode(rt) ? rt : defValue;
1717 }
1718
1719 public static String newRuleId() {
1720 return UUID.randomUUID().toString().replace("-", "");
1721 }
1722
1723 /**
1724 * Gets the name of the app associated with owner
1725 */
1726 public static String getOwnerCaption(Context context, String owner) {
1727 final PackageManager pm = context.getPackageManager();
1728 try {
1729 final ApplicationInfo info = pm.getApplicationInfo(owner, 0);
1730 if (info != null) {
1731 final CharSequence seq = info.loadLabel(pm);
1732 if (seq != null) {
1733 final String str = seq.toString().trim();
1734 if (str.length() > 0) {
1735 return str;
1736 }
1737 }
1738 }
1739 } catch (Throwable e) {
1740 Slog.w(TAG, "Error loading owner caption", e);
1741 }
1742 return "";
1743 }
1744
1745 public static String getConditionSummary(Context context, ZenModeConfig config,
1746 int userHandle, boolean shortVersion) {
1747 return getConditionLine(context, config, userHandle, false /*useLine1*/, shortVersion);
1748 }
1749
1750 private static String getConditionLine(Context context, ZenModeConfig config,
1751 int userHandle, boolean useLine1, boolean shortVersion) {
1752 if (config == null) return "";
1753 String summary = "";
1754 if (config.manualRule != null) {
1755 final Uri id = config.manualRule.conditionId;
1756 if (config.manualRule.enabler != null) {
1757 summary = getOwnerCaption(context, config.manualRule.enabler);
1758 } else {
1759 if (id == null) {
1760 summary = context.getString(com.android.internal.R.string.zen_mode_forever);
1761 } else {
1762 final long time = tryParseCountdownConditionId(id);
1763 Condition c = config.manualRule.condition;
1764 if (time > 0) {
1765 final long now = System.currentTimeMillis();
1766 final long span = time - now;
1767 c = toTimeCondition(context, time, Math.round(span / (float) MINUTES_MS),
1768 userHandle, shortVersion);
1769 }
1770 final String rt = c == null ? "" : useLine1 ? c.line1 : c.summary;
1771 summary = TextUtils.isEmpty(rt) ? "" : rt;
1772 }
1773 }
1774 }
1775 for (ZenRule automaticRule : config.automaticRules.values()) {
1776 if (automaticRule.isAutomaticActive()) {
1777 if (summary.isEmpty()) {
1778 summary = automaticRule.name;
1779 } else {
1780 summary = context.getResources()
1781 .getString(R.string.zen_mode_rule_name_combination, summary,
1782 automaticRule.name);
1783 }
1784
1785 }
1786 }
1787 return summary;
1788 }
1789
1790 public static class ZenRule implements Parcelable {
1791 @UnsupportedAppUsage
1792 public boolean enabled;
1793 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1794 public boolean snoozing; // user manually disabled this instance
1795 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1796 public String name; // required for automatic
1797 @UnsupportedAppUsage
1798 public int zenMode; // ie: Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS
1799 @UnsupportedAppUsage
1800 public Uri conditionId; // required for automatic
1801 public Condition condition; // optional
1802 public ComponentName component; // optional
1803 public ComponentName configurationActivity; // optional
1804 public String id; // required for automatic (unique)
1805 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1806 public long creationTime; // required for automatic
1807 // package name, only used for manual rules when they have turned DND on.
1808 public String enabler;
1809 public ZenPolicy zenPolicy;
1810 public boolean modified; // rule has been modified from initial creation
1811 public String pkg;
1812
1813 public ZenRule() { }
1814
1815 public ZenRule(Parcel source) {
1816 enabled = source.readInt() == 1;
1817 snoozing = source.readInt() == 1;
1818 if (source.readInt() == 1) {
1819 name = source.readString();
1820 }
1821 zenMode = source.readInt();
1822 conditionId = source.readParcelable(null, android.net.Uri.class);
1823 condition = source.readParcelable(null, android.service.notification.Condition.class);
1824 component = source.readParcelable(null, android.content.ComponentName.class);
1825 configurationActivity = source.readParcelable(null, android.content.ComponentName.class);
1826 if (source.readInt() == 1) {
1827 id = source.readString();
1828 }
1829 creationTime = source.readLong();
1830 if (source.readInt() == 1) {
1831 enabler = source.readString();
1832 }
1833 zenPolicy = source.readParcelable(null, android.service.notification.ZenPolicy.class);
1834 modified = source.readInt() == 1;
1835 pkg = source.readString();
1836 }
1837
1838 @Override
1839 public int describeContents() {
1840 return 0;
1841 }
1842
1843 @Override
1844 public void writeToParcel(Parcel dest, int flags) {
1845 dest.writeInt(enabled ? 1 : 0);
1846 dest.writeInt(snoozing ? 1 : 0);
1847 if (name != null) {
1848 dest.writeInt(1);
1849 dest.writeString(name);
1850 } else {
1851 dest.writeInt(0);
1852 }
1853 dest.writeInt(zenMode);
1854 dest.writeParcelable(conditionId, 0);
1855 dest.writeParcelable(condition, 0);
1856 dest.writeParcelable(component, 0);
1857 dest.writeParcelable(configurationActivity, 0);
1858 if (id != null) {
1859 dest.writeInt(1);
1860 dest.writeString(id);
1861 } else {
1862 dest.writeInt(0);
1863 }
1864 dest.writeLong(creationTime);
1865 if (enabler != null) {
1866 dest.writeInt(1);
1867 dest.writeString(enabler);
1868 } else {
1869 dest.writeInt(0);
1870 }
1871 dest.writeParcelable(zenPolicy, 0);
1872 dest.writeInt(modified ? 1 : 0);
1873 dest.writeString(pkg);
1874 }
1875
1876 @Override
1877 public String toString() {
1878 return new StringBuilder(ZenRule.class.getSimpleName()).append('[')
1879 .append("id=").append(id)
1880 .append(",state=").append(condition == null ? "STATE_FALSE"
1881 : Condition.stateToString(condition.state))
1882 .append(",enabled=").append(String.valueOf(enabled).toUpperCase())
1883 .append(",snoozing=").append(snoozing)
1884 .append(",name=").append(name)
1885 .append(",zenMode=").append(Global.zenModeToString(zenMode))
1886 .append(",conditionId=").append(conditionId)
1887 .append(",pkg=").append(pkg)
1888 .append(",component=").append(component)
1889 .append(",configActivity=").append(configurationActivity)
1890 .append(",creationTime=").append(creationTime)
1891 .append(",enabler=").append(enabler)
1892 .append(",zenPolicy=").append(zenPolicy)
1893 .append(",modified=").append(modified)
1894 .append(",condition=").append(condition)
1895 .append(']').toString();
1896 }
1897
1898 /** @hide */
1899 // TODO: add configuration activity
1900 public void dumpDebug(ProtoOutputStream proto, long fieldId) {
1901 final long token = proto.start(fieldId);
1902
1903 proto.write(ZenRuleProto.ID, id);
1904 proto.write(ZenRuleProto.NAME, name);
1905 proto.write(ZenRuleProto.CREATION_TIME_MS, creationTime);
1906 proto.write(ZenRuleProto.ENABLED, enabled);
1907 proto.write(ZenRuleProto.ENABLER, enabler);
1908 proto.write(ZenRuleProto.IS_SNOOZING, snoozing);
1909 proto.write(ZenRuleProto.ZEN_MODE, zenMode);
1910 if (conditionId != null) {
1911 proto.write(ZenRuleProto.CONDITION_ID, conditionId.toString());
1912 }
1913 if (condition != null) {
1914 condition.dumpDebug(proto, ZenRuleProto.CONDITION);
1915 }
1916 if (component != null) {
1917 component.dumpDebug(proto, ZenRuleProto.COMPONENT);
1918 }
1919 if (zenPolicy != null) {
1920 zenPolicy.dumpDebug(proto, ZenRuleProto.ZEN_POLICY);
1921 }
1922 proto.write(ZenRuleProto.MODIFIED, modified);
1923 proto.end(token);
1924 }
1925
1926 private static void appendDiff(Diff d, String item, ZenRule from, ZenRule to) {
1927 if (d == null) return;
1928 if (from == null) {
1929 if (to != null) {
1930 d.addLine(item, "insert");
1931 }
1932 return;
1933 }
1934 from.appendDiff(d, item, to);
1935 }
1936
1937 private void appendDiff(Diff d, String item, ZenRule to) {
1938 if (to == null) {
1939 d.addLine(item, "delete");
1940 return;
1941 }
1942 if (enabled != to.enabled) {
1943 d.addLine(item, "enabled", enabled, to.enabled);
1944 }
1945 if (snoozing != to.snoozing) {
1946 d.addLine(item, "snoozing", snoozing, to.snoozing);
1947 }
1948 if (!Objects.equals(name, to.name)) {
1949 d.addLine(item, "name", name, to.name);
1950 }
1951 if (zenMode != to.zenMode) {
1952 d.addLine(item, "zenMode", zenMode, to.zenMode);
1953 }
1954 if (!Objects.equals(conditionId, to.conditionId)) {
1955 d.addLine(item, "conditionId", conditionId, to.conditionId);
1956 }
1957 if (!Objects.equals(condition, to.condition)) {
1958 d.addLine(item, "condition", condition, to.condition);
1959 }
1960 if (!Objects.equals(component, to.component)) {
1961 d.addLine(item, "component", component, to.component);
1962 }
1963 if (!Objects.equals(configurationActivity, to.configurationActivity)) {
1964 d.addLine(item, "configActivity", configurationActivity, to.configurationActivity);
1965 }
1966 if (!Objects.equals(id, to.id)) {
1967 d.addLine(item, "id", id, to.id);
1968 }
1969 if (creationTime != to.creationTime) {
1970 d.addLine(item, "creationTime", creationTime, to.creationTime);
1971 }
1972 if (!Objects.equals(enabler, to.enabler)) {
1973 d.addLine(item, "enabler", enabler, to.enabler);
1974 }
1975 if (!Objects.equals(zenPolicy, to.zenPolicy)) {
1976 d.addLine(item, "zenPolicy", zenPolicy, to.zenPolicy);
1977 }
1978 if (modified != to.modified) {
1979 d.addLine(item, "modified", modified, to.modified);
1980 }
1981 if (!Objects.equals(pkg, to.pkg)) {
1982 d.addLine(item, "pkg", pkg, to.pkg);
1983 }
1984 }
1985
1986 @Override
1987 public boolean equals(@Nullable Object o) {
1988 if (!(o instanceof ZenRule)) return false;
1989 if (o == this) return true;
1990 final ZenRule other = (ZenRule) o;
1991 return other.enabled == enabled
1992 && other.snoozing == snoozing
1993 && Objects.equals(other.name, name)
1994 && other.zenMode == zenMode
1995 && Objects.equals(other.conditionId, conditionId)
1996 && Objects.equals(other.condition, condition)
1997 && Objects.equals(other.component, component)
1998 && Objects.equals(other.configurationActivity, configurationActivity)
1999 && Objects.equals(other.id, id)
2000 && Objects.equals(other.enabler, enabler)
2001 && Objects.equals(other.zenPolicy, zenPolicy)
2002 && Objects.equals(other.pkg, pkg)
2003 && other.modified == modified;
2004 }
2005
2006 @Override
2007 public int hashCode() {
2008 return Objects.hash(enabled, snoozing, name, zenMode, conditionId, condition,
2009 component, configurationActivity, pkg, id, enabler, zenPolicy, modified);
2010 }
2011
2012 public boolean isAutomaticActive() {
2013 return enabled && !snoozing && getPkg() != null && isTrueOrUnknown();
2014 }
2015
2016 public String getPkg() {
2017 return !TextUtils.isEmpty(pkg)
2018 ? pkg
2019 : (component != null)
2020 ? component.getPackageName()
2021 : (configurationActivity != null)
2022 ? configurationActivity.getPackageName()
2023 : null;
2024 }
2025
2026 public boolean isTrueOrUnknown() {
2027 return condition != null && (condition.state == Condition.STATE_TRUE
2028 || condition.state == Condition.STATE_UNKNOWN);
2029 }
2030
2031 public static final @android.annotation.NonNull Parcelable.Creator<ZenRule> CREATOR
2032 = new Parcelable.Creator<ZenRule>() {
2033 @Override
2034 public ZenRule createFromParcel(Parcel source) {
2035 return new ZenRule(source);
2036 }
2037 @Override
2038 public ZenRule[] newArray(int size) {
2039 return new ZenRule[size];
2040 }
2041 };
2042 }
2043
2044 public static class Diff {
2045 private final ArrayList<String> lines = new ArrayList<>();
2046
2047 @Override
2048 public String toString() {
2049 final StringBuilder sb = new StringBuilder("Diff[");
2050 final int N = lines.size();
2051 for (int i = 0; i < N; i++) {
2052 if (i > 0) {
2053 sb.append(",\n");
2054 }
2055 sb.append(lines.get(i));
2056 }
2057 return sb.append(']').toString();
2058 }
2059
2060 private Diff addLine(String item, String action) {
2061 lines.add(item + ":" + action);
2062 return this;
2063 }
2064
2065 public Diff addLine(String item, String subitem, Object from, Object to) {
2066 return addLine(item + "." + subitem, from, to);
2067 }
2068
2069 public Diff addLine(String item, Object from, Object to) {
2070 return addLine(item, from + "->" + to);
2071 }
2072
2073 public boolean isEmpty() {
2074 return lines.isEmpty();
2075 }
2076 }
2077
2078 /**
2079 * Determines whether dnd behavior should mute all ringer-controlled sounds
2080 * This includes notification, ringer and system sounds
2081 */
2082 public static boolean areAllPriorityOnlyRingerSoundsMuted(NotificationManager.Policy
2083 policy) {
2084 boolean allowReminders = (policy.priorityCategories
2085 & NotificationManager.Policy.PRIORITY_CATEGORY_REMINDERS) != 0;
2086 boolean allowCalls = (policy.priorityCategories
2087 & NotificationManager.Policy.PRIORITY_CATEGORY_CALLS) != 0;
2088 boolean allowMessages = (policy.priorityCategories
2089 & NotificationManager.Policy.PRIORITY_CATEGORY_MESSAGES) != 0;
2090 boolean allowEvents = (policy.priorityCategories
2091 & NotificationManager.Policy.PRIORITY_CATEGORY_EVENTS) != 0;
2092 boolean allowRepeatCallers = (policy.priorityCategories
2093 & NotificationManager.Policy.PRIORITY_CATEGORY_REPEAT_CALLERS) != 0;
2094 boolean allowConversations = (policy.priorityConversationSenders
2095 & Policy.PRIORITY_CATEGORY_CONVERSATIONS) != 0;
2096 boolean areChannelsBypassingDnd = (policy.state & Policy.STATE_CHANNELS_BYPASSING_DND) != 0;
2097 boolean allowSystem = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_SYSTEM) != 0;
2098 return !allowReminders && !allowCalls && !allowMessages && !allowEvents
2099 && !allowRepeatCallers && !areChannelsBypassingDnd && !allowSystem
2100 && !allowConversations;
2101 }
2102
2103 /**
2104 * Determines whether dnd behavior should mute all sounds
2105 */
2106 public static boolean areAllZenBehaviorSoundsMuted(NotificationManager.Policy
2107 policy) {
2108 boolean allowAlarms = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_ALARMS) != 0;
2109 boolean allowMedia = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_MEDIA) != 0;
2110 return !allowAlarms && !allowMedia && areAllPriorityOnlyRingerSoundsMuted(policy);
2111 }
2112
2113 /**
2114 * Determines if DND is currently overriding the ringer
2115 */
2116 public static boolean isZenOverridingRinger(int zen, Policy consolidatedPolicy) {
2117 return zen == Global.ZEN_MODE_NO_INTERRUPTIONS
2118 || zen == Global.ZEN_MODE_ALARMS
2119 || (zen == Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS
2120 && ZenModeConfig.areAllPriorityOnlyRingerSoundsMuted(consolidatedPolicy));
2121 }
2122
2123 /**
2124 * Determines whether dnd behavior should mute all ringer-controlled sounds
2125 * This includes notification, ringer and system sounds
2126 */
2127 public static boolean areAllPriorityOnlyRingerSoundsMuted(ZenModeConfig config) {
2128 return !config.allowReminders && !config.allowCalls && !config.allowMessages
2129 && !config.allowEvents && !config.allowRepeatCallers
2130 && !config.areChannelsBypassingDnd && !config.allowSystem;
2131 }
2132
2133 /**
2134 * Determines whether dnd mutes all sounds
2135 */
2136 public static boolean areAllZenBehaviorSoundsMuted(ZenModeConfig config) {
2137 return !config.allowAlarms && !config.allowMedia
2138 && areAllPriorityOnlyRingerSoundsMuted(config);
2139 }
2140
2141 /**
2142 * Returns a description of the current do not disturb settings from config.
2143 * - If turned on manually and end time is known, returns end time.
2144 * - If turned on manually and end time is on forever until turned off, return null if
2145 * describeForeverCondition is false, else return String describing indefinite behavior
2146 * - If turned on by an automatic rule, returns the automatic rule name.
2147 * - If on due to an app, returns the app name.
2148 * - If there's a combination of rules/apps that trigger, then shows the one that will
2149 * last the longest if applicable.
2150 * @return null if DND is off or describeForeverCondition is false and
2151 * DND is on forever (until turned off)
2152 */
2153 public static String getDescription(Context context, boolean zenOn, ZenModeConfig config,
2154 boolean describeForeverCondition) {
2155 if (!zenOn || config == null) {
2156 return null;
2157 }
2158
2159 String secondaryText = "";
2160 long latestEndTime = -1;
2161
2162 // DND turned on by manual rule
2163 if (config.manualRule != null) {
2164 final Uri id = config.manualRule.conditionId;
2165 if (config.manualRule.enabler != null) {
2166 // app triggered manual rule
2167 String appName = getOwnerCaption(context, config.manualRule.enabler);
2168 if (!appName.isEmpty()) {
2169 secondaryText = appName;
2170 }
2171 } else {
2172 if (id == null) {
2173 // Do not disturb manually triggered to remain on forever until turned off
2174 if (describeForeverCondition) {
2175 return context.getString(R.string.zen_mode_forever);
2176 } else {
2177 return null;
2178 }
2179 } else {
2180 latestEndTime = tryParseCountdownConditionId(id);
2181 if (latestEndTime > 0) {
2182 final CharSequence formattedTime = getFormattedTime(context,
2183 latestEndTime, isToday(latestEndTime),
2184 context.getUserId());
2185 secondaryText = context.getString(R.string.zen_mode_until, formattedTime);
2186 }
2187 }
2188 }
2189 }
2190
2191 // DND turned on by an automatic rule
2192 for (ZenRule automaticRule : config.automaticRules.values()) {
2193 if (automaticRule.isAutomaticActive()) {
2194 if (isValidEventConditionId(automaticRule.conditionId)
2195 || isValidScheduleConditionId(automaticRule.conditionId)) {
2196 // set text if automatic rule end time is the latest active rule end time
2197 long endTime = parseAutomaticRuleEndTime(context, automaticRule.conditionId);
2198 if (endTime > latestEndTime) {
2199 latestEndTime = endTime;
2200 secondaryText = automaticRule.name;
2201 }
2202 } else {
2203 // set text if 3rd party rule
2204 return automaticRule.name;
2205 }
2206 }
2207 }
2208
2209 return !secondaryText.equals("") ? secondaryText : null;
2210 }
2211
2212 private static long parseAutomaticRuleEndTime(Context context, Uri id) {
2213 if (isValidEventConditionId(id)) {
2214 // cannot look up end times for events
2215 return Long.MAX_VALUE;
2216 }
2217
2218 if (isValidScheduleConditionId(id)) {
2219 ScheduleCalendar schedule = toScheduleCalendar(id);
2220 long endTimeMs = schedule.getNextChangeTime(System.currentTimeMillis());
2221
2222 // check if automatic rule will end on next alarm
2223 if (schedule.exitAtAlarm()) {
2224 long nextAlarm = getNextAlarm(context);
2225 schedule.maybeSetNextAlarm(System.currentTimeMillis(), nextAlarm);
2226 if (schedule.shouldExitForAlarm(endTimeMs)) {
2227 return nextAlarm;
2228 }
2229 }
2230
2231 return endTimeMs;
2232 }
2233
2234 return -1;
2235 }
2236
2237 private static long getNextAlarm(Context context) {
2238 final AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
2239 final AlarmManager.AlarmClockInfo info = alarms.getNextAlarmClock(context.getUserId());
2240 return info != null ? info.getTriggerTime() : 0;
2241 }
2242 }