ZenModeConfig.java revision d560729ce3a6f3d51c03d39768815b4c49f7a8f4
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_SCREEN_OFF = true;
81    private static final boolean DEFAULT_ALLOW_SCREEN_ON = 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_SCREEN_OFF = "visualScreenOff";
97    private static final String ALLOW_ATT_SCREEN_ON = "visualScreenOn";
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 allowWhenScreenOff = DEFAULT_ALLOW_SCREEN_OFF;
130    public boolean allowWhenScreenOn = DEFAULT_ALLOW_SCREEN_ON;
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        allowWhenScreenOff = source.readInt() == 1;
158        allowWhenScreenOn = 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(allowWhenScreenOff ? 1 : 0);
187        dest.writeInt(allowWhenScreenOn ? 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(",allowWhenScreenOff=").append(allowWhenScreenOff)
202                .append(",allowWhenScreenOn=").append(allowWhenScreenOn)
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 (allowWhenScreenOff != to.allowWhenScreenOff) {
238            d.addLine("allowWhenScreenOff", allowWhenScreenOff, to.allowWhenScreenOff);
239        }
240        if (allowWhenScreenOn != to.allowWhenScreenOn) {
241            d.addLine("allowWhenScreenOn", allowWhenScreenOn, to.allowWhenScreenOn);
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.allowWhenScreenOff == allowWhenScreenOff
341                && other.allowWhenScreenOn == allowWhenScreenOn
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, allowWhenScreenOff,
351                allowWhenScreenOn,
352                user, automaticRules, manualRule);
353    }
354
355    private static String toDayList(int[] days) {
356        if (days == null || days.length == 0) return "";
357        final StringBuilder sb = new StringBuilder();
358        for (int i = 0; i < days.length; i++) {
359            if (i > 0) sb.append('.');
360            sb.append(days[i]);
361        }
362        return sb.toString();
363    }
364
365    private static int[] tryParseDayList(String dayList, String sep) {
366        if (dayList == null) return null;
367        final String[] tokens = dayList.split(sep);
368        if (tokens.length == 0) return null;
369        final int[] rt = new int[tokens.length];
370        for (int i = 0; i < tokens.length; i++) {
371            final int day = tryParseInt(tokens[i], -1);
372            if (day == -1) return null;
373            rt[i] = day;
374        }
375        return rt;
376    }
377
378    private static int tryParseInt(String value, int defValue) {
379        if (TextUtils.isEmpty(value)) return defValue;
380        try {
381            return Integer.valueOf(value);
382        } catch (NumberFormatException e) {
383            return defValue;
384        }
385    }
386
387    private static long tryParseLong(String value, long defValue) {
388        if (TextUtils.isEmpty(value)) return defValue;
389        try {
390            return Long.valueOf(value);
391        } catch (NumberFormatException e) {
392            return defValue;
393        }
394    }
395
396    public static ZenModeConfig readXml(XmlPullParser parser, Migration migration)
397            throws XmlPullParserException, IOException {
398        int type = parser.getEventType();
399        if (type != XmlPullParser.START_TAG) return null;
400        String tag = parser.getName();
401        if (!ZEN_TAG.equals(tag)) return null;
402        final ZenModeConfig rt = new ZenModeConfig();
403        final int version = safeInt(parser, ZEN_ATT_VERSION, XML_VERSION);
404        if (version == 1) {
405            final XmlV1 v1 = XmlV1.readXml(parser);
406            return migration.migrate(v1);
407        }
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
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
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.condition = readConditionXml(parser);
505        return rt;
506    }
507
508    public static void writeRuleXml(ZenRule rule, XmlSerializer out) throws IOException {
509        out.attribute(null, RULE_ATT_ENABLED, Boolean.toString(rule.enabled));
510        out.attribute(null, RULE_ATT_SNOOZING, Boolean.toString(rule.snoozing));
511        if (rule.name != null) {
512            out.attribute(null, RULE_ATT_NAME, rule.name);
513        }
514        out.attribute(null, RULE_ATT_ZEN, Integer.toString(rule.zenMode));
515        if (rule.component != null) {
516            out.attribute(null, RULE_ATT_COMPONENT, rule.component.flattenToString());
517        }
518        if (rule.conditionId != null) {
519            out.attribute(null, RULE_ATT_CONDITION_ID, rule.conditionId.toString());
520        }
521        out.attribute(null, RULE_ATT_CREATION_TIME, Long.toString(rule.creationTime));
522        if (rule.condition != null) {
523            writeConditionXml(rule.condition, out);
524        }
525    }
526
527    public static Condition readConditionXml(XmlPullParser parser) {
528        final Uri id = safeUri(parser, CONDITION_ATT_ID);
529        if (id == null) return null;
530        final String summary = parser.getAttributeValue(null, CONDITION_ATT_SUMMARY);
531        final String line1 = parser.getAttributeValue(null, CONDITION_ATT_LINE1);
532        final String line2 = parser.getAttributeValue(null, CONDITION_ATT_LINE2);
533        final int icon = safeInt(parser, CONDITION_ATT_ICON, -1);
534        final int state = safeInt(parser, CONDITION_ATT_STATE, -1);
535        final int flags = safeInt(parser, CONDITION_ATT_FLAGS, -1);
536        try {
537            return new Condition(id, summary, line1, line2, icon, state, flags);
538        } catch (IllegalArgumentException e) {
539            Slog.w(TAG, "Unable to read condition xml", e);
540            return null;
541        }
542    }
543
544    public static void writeConditionXml(Condition c, XmlSerializer out) throws IOException {
545        out.attribute(null, CONDITION_ATT_ID, c.id.toString());
546        out.attribute(null, CONDITION_ATT_SUMMARY, c.summary);
547        out.attribute(null, CONDITION_ATT_LINE1, c.line1);
548        out.attribute(null, CONDITION_ATT_LINE2, c.line2);
549        out.attribute(null, CONDITION_ATT_ICON, Integer.toString(c.icon));
550        out.attribute(null, CONDITION_ATT_STATE, Integer.toString(c.state));
551        out.attribute(null, CONDITION_ATT_FLAGS, Integer.toString(c.flags));
552    }
553
554    public static boolean isValidHour(int val) {
555        return val >= 0 && val < 24;
556    }
557
558    public static boolean isValidMinute(int val) {
559        return val >= 0 && val < 60;
560    }
561
562    private static boolean isValidSource(int source) {
563        return source >= SOURCE_ANYONE && source <= MAX_SOURCE;
564    }
565
566    private static boolean safeBoolean(XmlPullParser parser, String att, boolean defValue) {
567        final String val = parser.getAttributeValue(null, att);
568        if (TextUtils.isEmpty(val)) return defValue;
569        return Boolean.valueOf(val);
570    }
571
572    private static int safeInt(XmlPullParser parser, String att, int defValue) {
573        final String val = parser.getAttributeValue(null, att);
574        return tryParseInt(val, defValue);
575    }
576
577    private static ComponentName safeComponentName(XmlPullParser parser, String att) {
578        final String val = parser.getAttributeValue(null, att);
579        if (TextUtils.isEmpty(val)) return null;
580        return ComponentName.unflattenFromString(val);
581    }
582
583    private static Uri safeUri(XmlPullParser parser, String att) {
584        final String val = parser.getAttributeValue(null, att);
585        if (TextUtils.isEmpty(val)) return null;
586        return Uri.parse(val);
587    }
588
589    private static long safeLong(XmlPullParser parser, String att, long defValue) {
590        final String val = parser.getAttributeValue(null, att);
591        return tryParseLong(val, defValue);
592    }
593
594    @Override
595    public int describeContents() {
596        return 0;
597    }
598
599    public ZenModeConfig copy() {
600        final Parcel parcel = Parcel.obtain();
601        try {
602            writeToParcel(parcel, 0);
603            parcel.setDataPosition(0);
604            return new ZenModeConfig(parcel);
605        } finally {
606            parcel.recycle();
607        }
608    }
609
610    public static final Parcelable.Creator<ZenModeConfig> CREATOR
611            = new Parcelable.Creator<ZenModeConfig>() {
612        @Override
613        public ZenModeConfig createFromParcel(Parcel source) {
614            return new ZenModeConfig(source);
615        }
616
617        @Override
618        public ZenModeConfig[] newArray(int size) {
619            return new ZenModeConfig[size];
620        }
621    };
622
623    public Policy toNotificationPolicy() {
624        int priorityCategories = 0;
625        int priorityCallSenders = Policy.PRIORITY_SENDERS_CONTACTS;
626        int priorityMessageSenders = Policy.PRIORITY_SENDERS_CONTACTS;
627        if (allowCalls) {
628            priorityCategories |= Policy.PRIORITY_CATEGORY_CALLS;
629        }
630        if (allowMessages) {
631            priorityCategories |= Policy.PRIORITY_CATEGORY_MESSAGES;
632        }
633        if (allowEvents) {
634            priorityCategories |= Policy.PRIORITY_CATEGORY_EVENTS;
635        }
636        if (allowReminders) {
637            priorityCategories |= Policy.PRIORITY_CATEGORY_REMINDERS;
638        }
639        if (allowRepeatCallers) {
640            priorityCategories |= Policy.PRIORITY_CATEGORY_REPEAT_CALLERS;
641        }
642        int suppressedVisualEffects = 0;
643        if (!allowWhenScreenOff) {
644            suppressedVisualEffects |= Policy.SUPPRESSED_EFFECT_SCREEN_OFF;
645        }
646        if (!allowWhenScreenOn) {
647            suppressedVisualEffects |= Policy.SUPPRESSED_EFFECT_SCREEN_ON;
648        }
649        priorityCallSenders = sourceToPrioritySenders(allowCallsFrom, priorityCallSenders);
650        priorityMessageSenders = sourceToPrioritySenders(allowMessagesFrom, priorityMessageSenders);
651        return new Policy(priorityCategories, priorityCallSenders, priorityMessageSenders,
652                suppressedVisualEffects);
653    }
654
655    private static int sourceToPrioritySenders(int source, int def) {
656        switch (source) {
657            case SOURCE_ANYONE: return Policy.PRIORITY_SENDERS_ANY;
658            case SOURCE_CONTACT: return Policy.PRIORITY_SENDERS_CONTACTS;
659            case SOURCE_STAR: return Policy.PRIORITY_SENDERS_STARRED;
660            default: return def;
661        }
662    }
663
664    private static int prioritySendersToSource(int prioritySenders, int def) {
665        switch (prioritySenders) {
666            case Policy.PRIORITY_SENDERS_CONTACTS: return SOURCE_CONTACT;
667            case Policy.PRIORITY_SENDERS_STARRED: return SOURCE_STAR;
668            case Policy.PRIORITY_SENDERS_ANY: return SOURCE_ANYONE;
669            default: return def;
670        }
671    }
672
673    public void applyNotificationPolicy(Policy policy) {
674        if (policy == null) return;
675        allowCalls = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_CALLS) != 0;
676        allowMessages = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_MESSAGES) != 0;
677        allowEvents = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_EVENTS) != 0;
678        allowReminders = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_REMINDERS) != 0;
679        allowRepeatCallers = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_REPEAT_CALLERS)
680                != 0;
681        allowCallsFrom = prioritySendersToSource(policy.priorityCallSenders, allowCallsFrom);
682        allowMessagesFrom = prioritySendersToSource(policy.priorityMessageSenders,
683                allowMessagesFrom);
684        if (policy.suppressedVisualEffects != Policy.SUPPRESSED_EFFECTS_UNSET) {
685            allowWhenScreenOff =
686                    (policy.suppressedVisualEffects & Policy.SUPPRESSED_EFFECT_SCREEN_OFF) == 0;
687            allowWhenScreenOn =
688                    (policy.suppressedVisualEffects & Policy.SUPPRESSED_EFFECT_SCREEN_ON) == 0;
689        }
690    }
691
692    public static Condition toTimeCondition(Context context, int minutesFromNow, int userHandle) {
693        return toTimeCondition(context, minutesFromNow, userHandle, false /*shortVersion*/);
694    }
695
696    public static Condition toTimeCondition(Context context, int minutesFromNow, int userHandle,
697            boolean shortVersion) {
698        final long now = System.currentTimeMillis();
699        final long millis = minutesFromNow == 0 ? ZERO_VALUE_MS : minutesFromNow * MINUTES_MS;
700        return toTimeCondition(context, now + millis, minutesFromNow, userHandle, shortVersion);
701    }
702
703    public static Condition toTimeCondition(Context context, long time, int minutes,
704            int userHandle, boolean shortVersion) {
705        final int num;
706        String summary, line1, line2;
707        final CharSequence formattedTime = getFormattedTime(context, time, userHandle);
708        final Resources res = context.getResources();
709        if (minutes < 60) {
710            // display as minutes
711            num = minutes;
712            int summaryResId = shortVersion ? R.plurals.zen_mode_duration_minutes_summary_short
713                    : R.plurals.zen_mode_duration_minutes_summary;
714            summary = res.getQuantityString(summaryResId, num, num, formattedTime);
715            int line1ResId = shortVersion ? R.plurals.zen_mode_duration_minutes_short
716                    : R.plurals.zen_mode_duration_minutes;
717            line1 = res.getQuantityString(line1ResId, num, num, formattedTime);
718            line2 = res.getString(R.string.zen_mode_until, formattedTime);
719        } else if (minutes < DAY_MINUTES) {
720            // display as hours
721            num =  Math.round(minutes / 60f);
722            int summaryResId = shortVersion ? R.plurals.zen_mode_duration_hours_summary_short
723                    : R.plurals.zen_mode_duration_hours_summary;
724            summary = res.getQuantityString(summaryResId, num, num, formattedTime);
725            int line1ResId = shortVersion ? R.plurals.zen_mode_duration_hours_short
726                    : R.plurals.zen_mode_duration_hours;
727            line1 = res.getQuantityString(line1ResId, num, num, formattedTime);
728            line2 = res.getString(R.string.zen_mode_until, formattedTime);
729        } else {
730            // display as day/time
731            summary = line1 = line2 = res.getString(R.string.zen_mode_until, formattedTime);
732        }
733        final Uri id = toCountdownConditionId(time);
734        return new Condition(id, summary, line1, line2, 0, Condition.STATE_TRUE,
735                Condition.FLAG_RELEVANT_NOW);
736    }
737
738    public static Condition toNextAlarmCondition(Context context, long now, long alarm,
739            int userHandle) {
740        final CharSequence formattedTime = getFormattedTime(context, alarm, userHandle);
741        final Resources res = context.getResources();
742        final String line1 = res.getString(R.string.zen_mode_alarm, formattedTime);
743        final Uri id = toCountdownConditionId(alarm);
744        return new Condition(id, "", line1, "", 0, Condition.STATE_TRUE,
745                Condition.FLAG_RELEVANT_NOW);
746    }
747
748    private static CharSequence getFormattedTime(Context context, long time, int userHandle) {
749        String skeleton = "EEE " + (DateFormat.is24HourFormat(context, userHandle) ? "Hm" : "hma");
750        GregorianCalendar now = new GregorianCalendar();
751        GregorianCalendar endTime = new GregorianCalendar();
752        endTime.setTimeInMillis(time);
753        if (now.get(Calendar.YEAR) == endTime.get(Calendar.YEAR)
754                && now.get(Calendar.MONTH) == endTime.get(Calendar.MONTH)
755                && now.get(Calendar.DATE) == endTime.get(Calendar.DATE)) {
756            skeleton = DateFormat.is24HourFormat(context, userHandle) ? "Hm" : "hma";
757        }
758        final String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
759        return DateFormat.format(pattern, time);
760    }
761
762    // ==== Built-in system conditions ====
763
764    public static final String SYSTEM_AUTHORITY = "android";
765
766    // ==== Built-in system condition: countdown ====
767
768    public static final String COUNTDOWN_PATH = "countdown";
769
770    public static Uri toCountdownConditionId(long time) {
771        return new Uri.Builder().scheme(Condition.SCHEME)
772                .authority(SYSTEM_AUTHORITY)
773                .appendPath(COUNTDOWN_PATH)
774                .appendPath(Long.toString(time))
775                .build();
776    }
777
778    public static long tryParseCountdownConditionId(Uri conditionId) {
779        if (!Condition.isValidId(conditionId, SYSTEM_AUTHORITY)) return 0;
780        if (conditionId.getPathSegments().size() != 2
781                || !COUNTDOWN_PATH.equals(conditionId.getPathSegments().get(0))) return 0;
782        try {
783            return Long.parseLong(conditionId.getPathSegments().get(1));
784        } catch (RuntimeException e) {
785            Slog.w(TAG, "Error parsing countdown condition: " + conditionId, e);
786            return 0;
787        }
788    }
789
790    public static boolean isValidCountdownConditionId(Uri conditionId) {
791        return tryParseCountdownConditionId(conditionId) != 0;
792    }
793
794    // ==== Built-in system condition: schedule ====
795
796    public static final String SCHEDULE_PATH = "schedule";
797
798    public static Uri toScheduleConditionId(ScheduleInfo schedule) {
799        return new Uri.Builder().scheme(Condition.SCHEME)
800                .authority(SYSTEM_AUTHORITY)
801                .appendPath(SCHEDULE_PATH)
802                .appendQueryParameter("days", toDayList(schedule.days))
803                .appendQueryParameter("start", schedule.startHour + "." + schedule.startMinute)
804                .appendQueryParameter("end", schedule.endHour + "." + schedule.endMinute)
805                .build();
806    }
807
808    public static boolean isValidScheduleConditionId(Uri conditionId) {
809        return tryParseScheduleConditionId(conditionId) != null;
810    }
811
812    public static ScheduleInfo tryParseScheduleConditionId(Uri conditionId) {
813        final boolean isSchedule =  conditionId != null
814                && conditionId.getScheme().equals(Condition.SCHEME)
815                && conditionId.getAuthority().equals(ZenModeConfig.SYSTEM_AUTHORITY)
816                && conditionId.getPathSegments().size() == 1
817                && conditionId.getPathSegments().get(0).equals(ZenModeConfig.SCHEDULE_PATH);
818        if (!isSchedule) return null;
819        final int[] start = tryParseHourAndMinute(conditionId.getQueryParameter("start"));
820        final int[] end = tryParseHourAndMinute(conditionId.getQueryParameter("end"));
821        if (start == null || end == null) return null;
822        final ScheduleInfo rt = new ScheduleInfo();
823        rt.days = tryParseDayList(conditionId.getQueryParameter("days"), "\\.");
824        rt.startHour = start[0];
825        rt.startMinute = start[1];
826        rt.endHour = end[0];
827        rt.endMinute = end[1];
828        return rt;
829    }
830
831    public static ComponentName getScheduleConditionProvider() {
832        return new ComponentName(SYSTEM_AUTHORITY, "ScheduleConditionProvider");
833    }
834
835    public static class ScheduleInfo {
836        public int[] days;
837        public int startHour;
838        public int startMinute;
839        public int endHour;
840        public int endMinute;
841
842        @Override
843        public int hashCode() {
844            return 0;
845        }
846
847        @Override
848        public boolean equals(Object o) {
849            if (!(o instanceof ScheduleInfo)) return false;
850            final ScheduleInfo other = (ScheduleInfo) o;
851            return toDayList(days).equals(toDayList(other.days))
852                    && startHour == other.startHour
853                    && startMinute == other.startMinute
854                    && endHour == other.endHour
855                    && endMinute == other.endMinute;
856        }
857
858        public ScheduleInfo copy() {
859            final ScheduleInfo rt = new ScheduleInfo();
860            if (days != null) {
861                rt.days = new int[days.length];
862                System.arraycopy(days, 0, rt.days, 0, days.length);
863            }
864            rt.startHour = startHour;
865            rt.startMinute = startMinute;
866            rt.endHour = endHour;
867            rt.endMinute = endMinute;
868            return rt;
869        }
870    }
871
872    // ==== Built-in system condition: event ====
873
874    public static final String EVENT_PATH = "event";
875
876    public static Uri toEventConditionId(EventInfo event) {
877        return new Uri.Builder().scheme(Condition.SCHEME)
878                .authority(SYSTEM_AUTHORITY)
879                .appendPath(EVENT_PATH)
880                .appendQueryParameter("userId", Long.toString(event.userId))
881                .appendQueryParameter("calendar", event.calendar != null ? event.calendar : "")
882                .appendQueryParameter("reply", Integer.toString(event.reply))
883                .build();
884    }
885
886    public static boolean isValidEventConditionId(Uri conditionId) {
887        return tryParseEventConditionId(conditionId) != null;
888    }
889
890    public static EventInfo tryParseEventConditionId(Uri conditionId) {
891        final boolean isEvent = conditionId != null
892                && conditionId.getScheme().equals(Condition.SCHEME)
893                && conditionId.getAuthority().equals(ZenModeConfig.SYSTEM_AUTHORITY)
894                && conditionId.getPathSegments().size() == 1
895                && conditionId.getPathSegments().get(0).equals(EVENT_PATH);
896        if (!isEvent) return null;
897        final EventInfo rt = new EventInfo();
898        rt.userId = tryParseInt(conditionId.getQueryParameter("userId"), UserHandle.USER_NULL);
899        rt.calendar = conditionId.getQueryParameter("calendar");
900        if (TextUtils.isEmpty(rt.calendar) || tryParseLong(rt.calendar, -1L) != -1L) {
901            rt.calendar = null;
902        }
903        rt.reply = tryParseInt(conditionId.getQueryParameter("reply"), 0);
904        return rt;
905    }
906
907    public static ComponentName getEventConditionProvider() {
908        return new ComponentName(SYSTEM_AUTHORITY, "EventConditionProvider");
909    }
910
911    public static class EventInfo {
912        public static final int REPLY_ANY_EXCEPT_NO = 0;
913        public static final int REPLY_YES_OR_MAYBE = 1;
914        public static final int REPLY_YES = 2;
915
916        public int userId = UserHandle.USER_NULL;  // USER_NULL = unspecified - use current user
917        public String calendar;  // CalendarContract.Calendars.OWNER_ACCOUNT, or null for any
918        public int reply;
919
920        @Override
921        public int hashCode() {
922            return 0;
923        }
924
925        @Override
926        public boolean equals(Object o) {
927            if (!(o instanceof EventInfo)) return false;
928            final EventInfo other = (EventInfo) o;
929            return userId == other.userId
930                    && Objects.equals(calendar, other.calendar)
931                    && reply == other.reply;
932        }
933
934        public EventInfo copy() {
935            final EventInfo rt = new EventInfo();
936            rt.userId = userId;
937            rt.calendar = calendar;
938            rt.reply = reply;
939            return rt;
940        }
941
942        public static int resolveUserId(int userId) {
943            return userId == UserHandle.USER_NULL ? ActivityManager.getCurrentUser() : userId;
944        }
945    }
946
947    // ==== End built-in system conditions ====
948
949    private static int[] tryParseHourAndMinute(String value) {
950        if (TextUtils.isEmpty(value)) return null;
951        final int i = value.indexOf('.');
952        if (i < 1 || i >= value.length() - 1) return null;
953        final int hour = tryParseInt(value.substring(0, i), -1);
954        final int minute = tryParseInt(value.substring(i + 1), -1);
955        return isValidHour(hour) && isValidMinute(minute) ? new int[] { hour, minute } : null;
956    }
957
958    private static int tryParseZenMode(String value, int defValue) {
959        final int rt = tryParseInt(value, defValue);
960        return Global.isValidZenMode(rt) ? rt : defValue;
961    }
962
963    public static String newRuleId() {
964        return UUID.randomUUID().toString().replace("-", "");
965    }
966
967    public static String getConditionSummary(Context context, ZenModeConfig config,
968            int userHandle, boolean shortVersion) {
969        return getConditionLine(context, config, userHandle, false /*useLine1*/, shortVersion);
970    }
971
972    private static String getConditionLine(Context context, ZenModeConfig config,
973            int userHandle, boolean useLine1, boolean shortVersion) {
974        if (config == null) return "";
975        if (config.manualRule != null) {
976            final Uri id = config.manualRule.conditionId;
977            if (id == null) {
978                return context.getString(com.android.internal.R.string.zen_mode_forever);
979            }
980            final long time = tryParseCountdownConditionId(id);
981            Condition c = config.manualRule.condition;
982            if (time > 0) {
983                final long now = System.currentTimeMillis();
984                final long span = time - now;
985                c = toTimeCondition(context, time, Math.round(span / (float) MINUTES_MS),
986                        userHandle, shortVersion);
987            }
988            final String rt = c == null ? "" : useLine1 ? c.line1 : c.summary;
989            return TextUtils.isEmpty(rt) ? "" : rt;
990        }
991        String summary = "";
992        for (ZenRule automaticRule : config.automaticRules.values()) {
993            if (automaticRule.isAutomaticActive()) {
994                if (summary.isEmpty()) {
995                    summary = automaticRule.name;
996                } else {
997                    summary = context.getResources()
998                            .getString(R.string.zen_mode_rule_name_combination, summary,
999                                    automaticRule.name);
1000                }
1001            }
1002        }
1003        return summary;
1004    }
1005
1006    public static class ZenRule implements Parcelable {
1007        public boolean enabled;
1008        public boolean snoozing;         // user manually disabled this instance
1009        public String name;              // required for automatic (unique)
1010        public int zenMode;
1011        public Uri conditionId;          // required for automatic
1012        public Condition condition;      // optional
1013        public ComponentName component;  // optional
1014        public String id;                // required for automatic (unique)
1015        public long creationTime;        // required for automatic
1016
1017        public ZenRule() { }
1018
1019        public ZenRule(Parcel source) {
1020            enabled = source.readInt() == 1;
1021            snoozing = source.readInt() == 1;
1022            if (source.readInt() == 1) {
1023                name = source.readString();
1024            }
1025            zenMode = source.readInt();
1026            conditionId = source.readParcelable(null);
1027            condition = source.readParcelable(null);
1028            component = source.readParcelable(null);
1029            if (source.readInt() == 1) {
1030                id = source.readString();
1031            }
1032            creationTime = source.readLong();
1033        }
1034
1035        @Override
1036        public int describeContents() {
1037            return 0;
1038        }
1039
1040        @Override
1041        public void writeToParcel(Parcel dest, int flags) {
1042            dest.writeInt(enabled ? 1 : 0);
1043            dest.writeInt(snoozing ? 1 : 0);
1044            if (name != null) {
1045                dest.writeInt(1);
1046                dest.writeString(name);
1047            } else {
1048                dest.writeInt(0);
1049            }
1050            dest.writeInt(zenMode);
1051            dest.writeParcelable(conditionId, 0);
1052            dest.writeParcelable(condition, 0);
1053            dest.writeParcelable(component, 0);
1054            if (id != null) {
1055                dest.writeInt(1);
1056                dest.writeString(id);
1057            } else {
1058                dest.writeInt(0);
1059            }
1060            dest.writeLong(creationTime);
1061        }
1062
1063        @Override
1064        public String toString() {
1065            return new StringBuilder(ZenRule.class.getSimpleName()).append('[')
1066                    .append("enabled=").append(enabled)
1067                    .append(",snoozing=").append(snoozing)
1068                    .append(",name=").append(name)
1069                    .append(",zenMode=").append(Global.zenModeToString(zenMode))
1070                    .append(",conditionId=").append(conditionId)
1071                    .append(",condition=").append(condition)
1072                    .append(",component=").append(component)
1073                    .append(",id=").append(id)
1074                    .append(",creationTime=").append(creationTime)
1075                    .append(']').toString();
1076        }
1077
1078        private static void appendDiff(Diff d, String item, ZenRule from, ZenRule to) {
1079            if (d == null) return;
1080            if (from == null) {
1081                if (to != null) {
1082                    d.addLine(item, "insert");
1083                }
1084                return;
1085            }
1086            from.appendDiff(d, item, to);
1087        }
1088
1089        private void appendDiff(Diff d, String item, ZenRule to) {
1090            if (to == null) {
1091                d.addLine(item, "delete");
1092                return;
1093            }
1094            if (enabled != to.enabled) {
1095                d.addLine(item, "enabled", enabled, to.enabled);
1096            }
1097            if (snoozing != to.snoozing) {
1098                d.addLine(item, "snoozing", snoozing, to.snoozing);
1099            }
1100            if (!Objects.equals(name, to.name)) {
1101                d.addLine(item, "name", name, to.name);
1102            }
1103            if (zenMode != to.zenMode) {
1104                d.addLine(item, "zenMode", zenMode, to.zenMode);
1105            }
1106            if (!Objects.equals(conditionId, to.conditionId)) {
1107                d.addLine(item, "conditionId", conditionId, to.conditionId);
1108            }
1109            if (!Objects.equals(condition, to.condition)) {
1110                d.addLine(item, "condition", condition, to.condition);
1111            }
1112            if (!Objects.equals(component, to.component)) {
1113                d.addLine(item, "component", component, to.component);
1114            }
1115            if (!Objects.equals(id, to.id)) {
1116                d.addLine(item, "id", id, to.id);
1117            }
1118            if (creationTime != to.creationTime) {
1119                d.addLine(item, "creationTime", creationTime, to.creationTime);
1120            }
1121        }
1122
1123        @Override
1124        public boolean equals(Object o) {
1125            if (!(o instanceof ZenRule)) return false;
1126            if (o == this) return true;
1127            final ZenRule other = (ZenRule) o;
1128            return other.enabled == enabled
1129                    && other.snoozing == snoozing
1130                    && Objects.equals(other.name, name)
1131                    && other.zenMode == zenMode
1132                    && Objects.equals(other.conditionId, conditionId)
1133                    && Objects.equals(other.condition, condition)
1134                    && Objects.equals(other.component, component)
1135                    && Objects.equals(other.id, id)
1136                    && other.creationTime == creationTime;
1137        }
1138
1139        @Override
1140        public int hashCode() {
1141            return Objects.hash(enabled, snoozing, name, zenMode, conditionId, condition,
1142                    component, id, creationTime);
1143        }
1144
1145        public boolean isAutomaticActive() {
1146            return enabled && !snoozing && component != null && isTrueOrUnknown();
1147        }
1148
1149        public boolean isTrueOrUnknown() {
1150            return condition != null && (condition.state == Condition.STATE_TRUE
1151                    || condition.state == Condition.STATE_UNKNOWN);
1152        }
1153
1154        public static final Parcelable.Creator<ZenRule> CREATOR
1155                = new Parcelable.Creator<ZenRule>() {
1156            @Override
1157            public ZenRule createFromParcel(Parcel source) {
1158                return new ZenRule(source);
1159            }
1160            @Override
1161            public ZenRule[] newArray(int size) {
1162                return new ZenRule[size];
1163            }
1164        };
1165    }
1166
1167    // Legacy config
1168    public static final class XmlV1 {
1169        public static final String SLEEP_MODE_NIGHTS = "nights";
1170        public static final String SLEEP_MODE_WEEKNIGHTS = "weeknights";
1171        public static final String SLEEP_MODE_DAYS_PREFIX = "days:";
1172
1173        private static final String EXIT_CONDITION_TAG = "exitCondition";
1174        private static final String EXIT_CONDITION_ATT_COMPONENT = "component";
1175        private static final String SLEEP_TAG = "sleep";
1176        private static final String SLEEP_ATT_MODE = "mode";
1177        private static final String SLEEP_ATT_NONE = "none";
1178
1179        private static final String SLEEP_ATT_START_HR = "startHour";
1180        private static final String SLEEP_ATT_START_MIN = "startMin";
1181        private static final String SLEEP_ATT_END_HR = "endHour";
1182        private static final String SLEEP_ATT_END_MIN = "endMin";
1183
1184        public boolean allowCalls;
1185        public boolean allowMessages;
1186        public boolean allowReminders = DEFAULT_ALLOW_REMINDERS;
1187        public boolean allowEvents = DEFAULT_ALLOW_EVENTS;
1188        public int allowFrom = SOURCE_ANYONE;
1189
1190        public String sleepMode;     // nights, weeknights, days:1,2,3  Calendar.days
1191        public int sleepStartHour;   // 0-23
1192        public int sleepStartMinute; // 0-59
1193        public int sleepEndHour;
1194        public int sleepEndMinute;
1195        public boolean sleepNone;    // false = priority, true = none
1196        public ComponentName[] conditionComponents;
1197        public Uri[] conditionIds;
1198        public Condition exitCondition;  // manual exit condition
1199        public ComponentName exitConditionComponent;  // manual exit condition component
1200
1201        private static boolean isValidSleepMode(String sleepMode) {
1202            return sleepMode == null || sleepMode.equals(SLEEP_MODE_NIGHTS)
1203                    || sleepMode.equals(SLEEP_MODE_WEEKNIGHTS) || tryParseDays(sleepMode) != null;
1204        }
1205
1206        public static int[] tryParseDays(String sleepMode) {
1207            if (sleepMode == null) return null;
1208            sleepMode = sleepMode.trim();
1209            if (SLEEP_MODE_NIGHTS.equals(sleepMode)) return ALL_DAYS;
1210            if (SLEEP_MODE_WEEKNIGHTS.equals(sleepMode)) return WEEKNIGHT_DAYS;
1211            if (!sleepMode.startsWith(SLEEP_MODE_DAYS_PREFIX)) return null;
1212            if (sleepMode.equals(SLEEP_MODE_DAYS_PREFIX)) return null;
1213            return tryParseDayList(sleepMode.substring(SLEEP_MODE_DAYS_PREFIX.length()), ",");
1214        }
1215
1216        public static XmlV1 readXml(XmlPullParser parser)
1217                throws XmlPullParserException, IOException {
1218            int type;
1219            String tag;
1220            XmlV1 rt = new XmlV1();
1221            final ArrayList<ComponentName> conditionComponents = new ArrayList<ComponentName>();
1222            final ArrayList<Uri> conditionIds = new ArrayList<Uri>();
1223            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1224                tag = parser.getName();
1225                if (type == XmlPullParser.END_TAG && ZEN_TAG.equals(tag)) {
1226                    if (!conditionComponents.isEmpty()) {
1227                        rt.conditionComponents = conditionComponents
1228                                .toArray(new ComponentName[conditionComponents.size()]);
1229                        rt.conditionIds = conditionIds.toArray(new Uri[conditionIds.size()]);
1230                    }
1231                    return rt;
1232                }
1233                if (type == XmlPullParser.START_TAG) {
1234                    if (ALLOW_TAG.equals(tag)) {
1235                        rt.allowCalls = safeBoolean(parser, ALLOW_ATT_CALLS, false);
1236                        rt.allowMessages = safeBoolean(parser, ALLOW_ATT_MESSAGES, false);
1237                        rt.allowReminders = safeBoolean(parser, ALLOW_ATT_REMINDERS,
1238                                DEFAULT_ALLOW_REMINDERS);
1239                        rt.allowEvents = safeBoolean(parser, ALLOW_ATT_EVENTS,
1240                                DEFAULT_ALLOW_EVENTS);
1241                        rt.allowFrom = safeInt(parser, ALLOW_ATT_FROM, SOURCE_ANYONE);
1242                        if (rt.allowFrom < SOURCE_ANYONE || rt.allowFrom > MAX_SOURCE) {
1243                            throw new IndexOutOfBoundsException("bad source in config:"
1244                                    + rt.allowFrom);
1245                        }
1246                    } else if (SLEEP_TAG.equals(tag)) {
1247                        final String mode = parser.getAttributeValue(null, SLEEP_ATT_MODE);
1248                        rt.sleepMode = isValidSleepMode(mode)? mode : null;
1249                        rt.sleepNone = safeBoolean(parser, SLEEP_ATT_NONE, false);
1250                        final int startHour = safeInt(parser, SLEEP_ATT_START_HR, 0);
1251                        final int startMinute = safeInt(parser, SLEEP_ATT_START_MIN, 0);
1252                        final int endHour = safeInt(parser, SLEEP_ATT_END_HR, 0);
1253                        final int endMinute = safeInt(parser, SLEEP_ATT_END_MIN, 0);
1254                        rt.sleepStartHour = isValidHour(startHour) ? startHour : 0;
1255                        rt.sleepStartMinute = isValidMinute(startMinute) ? startMinute : 0;
1256                        rt.sleepEndHour = isValidHour(endHour) ? endHour : 0;
1257                        rt.sleepEndMinute = isValidMinute(endMinute) ? endMinute : 0;
1258                    } else if (CONDITION_TAG.equals(tag)) {
1259                        final ComponentName component =
1260                                safeComponentName(parser, CONDITION_ATT_COMPONENT);
1261                        final Uri conditionId = safeUri(parser, CONDITION_ATT_ID);
1262                        if (component != null && conditionId != null) {
1263                            conditionComponents.add(component);
1264                            conditionIds.add(conditionId);
1265                        }
1266                    } else if (EXIT_CONDITION_TAG.equals(tag)) {
1267                        rt.exitCondition = readConditionXml(parser);
1268                        if (rt.exitCondition != null) {
1269                            rt.exitConditionComponent =
1270                                    safeComponentName(parser, EXIT_CONDITION_ATT_COMPONENT);
1271                        }
1272                    }
1273                }
1274            }
1275            throw new IllegalStateException("Failed to reach END_DOCUMENT");
1276        }
1277    }
1278
1279    public interface Migration {
1280        ZenModeConfig migrate(XmlV1 v1);
1281    }
1282
1283    public static class Diff {
1284        private final ArrayList<String> lines = new ArrayList<>();
1285
1286        @Override
1287        public String toString() {
1288            final StringBuilder sb = new StringBuilder("Diff[");
1289            final int N = lines.size();
1290            for (int i = 0; i < N; i++) {
1291                if (i > 0) {
1292                    sb.append(',');
1293                }
1294                sb.append(lines.get(i));
1295            }
1296            return sb.append(']').toString();
1297        }
1298
1299        private Diff addLine(String item, String action) {
1300            lines.add(item + ":" + action);
1301            return this;
1302        }
1303
1304        public Diff addLine(String item, String subitem, Object from, Object to) {
1305            return addLine(item + "." + subitem, from, to);
1306        }
1307
1308        public Diff addLine(String item, Object from, Object to) {
1309            return addLine(item, from + "->" + to);
1310        }
1311    }
1312
1313}
1314