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