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