1/*
2 * Copyright (C) 2012 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 com.android.calendar.alerts;
18
19import android.app.AlarmManager;
20import android.app.PendingIntent;
21import android.content.ContentUris;
22import android.content.ContentValues;
23import android.content.Context;
24import android.content.Intent;
25import android.content.SharedPreferences;
26import android.net.Uri;
27import android.provider.CalendarContract;
28import android.provider.CalendarContract.CalendarAlerts;
29import android.text.TextUtils;
30import android.text.format.DateFormat;
31import android.text.format.DateUtils;
32import android.text.format.Time;
33import android.util.Log;
34
35import com.android.calendar.EventInfoActivity;
36import com.android.calendar.R;
37import com.android.calendar.Utils;
38
39import java.util.Locale;
40import java.util.Map;
41import java.util.TimeZone;
42
43public class AlertUtils {
44    private static final String TAG = "AlertUtils";
45    static final boolean DEBUG = true;
46
47    public static final long SNOOZE_DELAY = 5 * 60 * 1000L;
48
49    // We use one notification id for the expired events notification.  All
50    // other notifications (the 'active' future/concurrent ones) use a unique ID.
51    public static final int EXPIRED_GROUP_NOTIFICATION_ID = 0;
52
53    public static final String EVENT_ID_KEY = "eventid";
54    public static final String SHOW_EVENT_KEY = "showevent";
55    public static final String EVENT_START_KEY = "eventstart";
56    public static final String EVENT_END_KEY = "eventend";
57    public static final String NOTIFICATION_ID_KEY = "notificationid";
58    public static final String EVENT_IDS_KEY = "eventids";
59    public static final String EVENT_STARTS_KEY = "starts";
60
61    // A flag for using local storage to save alert state instead of the alerts DB table.
62    // This allows the unbundled app to run alongside other calendar apps without eating
63    // alerts from other apps.
64    static boolean BYPASS_DB = true;
65
66    // SharedPrefs table name for storing fired alerts.  This prevents other installed
67    // Calendar apps from eating the alerts.
68    private static final String ALERTS_SHARED_PREFS_NAME = "calendar_alerts";
69
70    // Keyname prefix for the alerts data in SharedPrefs.  The key will contain a combo
71    // of event ID, begin time, and alarm time.  The value will be the fired time.
72    private static final String KEY_FIRED_ALERT_PREFIX = "preference_alert_";
73
74    // The last time the SharedPrefs was scanned and flushed of old alerts data.
75    private static final String KEY_LAST_FLUSH_TIME_MS = "preference_flushTimeMs";
76
77    // The # of days to save alert states in the shared prefs table, before flushing.  This
78    // can be any value, since AlertService will also check for a recent alertTime before
79    // ringing the alert.
80    private static final int FLUSH_INTERVAL_DAYS = 1;
81    private static final int FLUSH_INTERVAL_MS = FLUSH_INTERVAL_DAYS * 24 * 60 * 60 * 1000;
82
83    /**
84     * Creates an AlarmManagerInterface that wraps a real AlarmManager.  The alarm code
85     * was abstracted to an interface to make it testable.
86     */
87    public static AlarmManagerInterface createAlarmManager(Context context) {
88        final AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
89        return new AlarmManagerInterface() {
90            @Override
91            public void set(int type, long triggerAtMillis, PendingIntent operation) {
92                mgr.set(type, triggerAtMillis, operation);
93            }
94        };
95    }
96
97    /**
98     * Schedules an alarm intent with the system AlarmManager that will notify
99     * listeners when a reminder should be fired. The provider will keep
100     * scheduled reminders up to date but apps may use this to implement snooze
101     * functionality without modifying the reminders table. Scheduled alarms
102     * will generate an intent using AlertReceiver.EVENT_REMINDER_APP_ACTION.
103     *
104     * @param context A context for referencing system resources
105     * @param manager The AlarmManager to use or null
106     * @param alarmTime The time to fire the intent in UTC millis since epoch
107     */
108    public static void scheduleAlarm(Context context, AlarmManagerInterface manager,
109            long alarmTime) {
110        scheduleAlarmHelper(context, manager, alarmTime, false);
111    }
112
113    /**
114     * Schedules the next alarm to silently refresh the notifications.  Note that if there
115     * is a pending silent refresh alarm, it will be replaced with this one.
116     */
117    static void scheduleNextNotificationRefresh(Context context, AlarmManagerInterface manager,
118            long alarmTime) {
119        scheduleAlarmHelper(context, manager, alarmTime, true);
120    }
121
122    private static void scheduleAlarmHelper(Context context, AlarmManagerInterface manager,
123            long alarmTime, boolean quietUpdate) {
124        int alarmType = AlarmManager.RTC_WAKEUP;
125        Intent intent = new Intent(AlertReceiver.EVENT_REMINDER_APP_ACTION);
126        intent.setClass(context, AlertReceiver.class);
127        if (quietUpdate) {
128            alarmType = AlarmManager.RTC;
129        } else {
130            // Set data field so we get a unique PendingIntent instance per alarm or else alarms
131            // may be dropped.
132            Uri.Builder builder = CalendarAlerts.CONTENT_URI.buildUpon();
133            ContentUris.appendId(builder, alarmTime);
134            intent.setData(builder.build());
135        }
136
137        intent.putExtra(CalendarContract.CalendarAlerts.ALARM_TIME, alarmTime);
138        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent,
139                PendingIntent.FLAG_UPDATE_CURRENT);
140        manager.set(alarmType, alarmTime, pi);
141    }
142
143    /**
144     * Format the second line which shows time and location for single alert or the
145     * number of events for multiple alerts
146     *     1) Show time only for non-all day events
147     *     2) No date for today
148     *     3) Show "tomorrow" for tomorrow
149     *     4) Show date for days beyond that
150     */
151    static String formatTimeLocation(Context context, long startMillis, boolean allDay,
152            String location) {
153        String tz = Utils.getTimeZone(context, null);
154        Time time = new Time(tz);
155        time.setToNow();
156        int today = Time.getJulianDay(time.toMillis(false), time.gmtoff);
157        time.set(startMillis);
158        int eventDay = Time.getJulianDay(time.toMillis(false), allDay ? 0 : time.gmtoff);
159
160        int flags = DateUtils.FORMAT_ABBREV_ALL;
161        if (!allDay) {
162            flags |= DateUtils.FORMAT_SHOW_TIME;
163            if (DateFormat.is24HourFormat(context)) {
164                flags |= DateUtils.FORMAT_24HOUR;
165            }
166        } else {
167            flags |= DateUtils.FORMAT_UTC;
168        }
169
170        if (eventDay < today || eventDay > today + 1) {
171            flags |= DateUtils.FORMAT_SHOW_DATE;
172        }
173
174        StringBuilder sb = new StringBuilder(Utils.formatDateRange(context, startMillis,
175                startMillis, flags));
176
177        if (!allDay && tz != Time.getCurrentTimezone()) {
178            // Assumes time was set to the current tz
179            time.set(startMillis);
180            boolean isDST = time.isDst != 0;
181            sb.append(" ").append(TimeZone.getTimeZone(tz).getDisplayName(
182                    isDST, TimeZone.SHORT, Locale.getDefault()));
183        }
184
185        if (eventDay == today + 1) {
186            // Tomorrow
187            sb.append(", ");
188            sb.append(context.getString(R.string.tomorrow));
189        }
190
191        String loc;
192        if (location != null && !TextUtils.isEmpty(loc = location.trim())) {
193            sb.append(", ");
194            sb.append(loc);
195        }
196        return sb.toString();
197    }
198
199    public static ContentValues makeContentValues(long eventId, long begin, long end,
200            long alarmTime, int minutes) {
201        ContentValues values = new ContentValues();
202        values.put(CalendarAlerts.EVENT_ID, eventId);
203        values.put(CalendarAlerts.BEGIN, begin);
204        values.put(CalendarAlerts.END, end);
205        values.put(CalendarAlerts.ALARM_TIME, alarmTime);
206        long currentTime = System.currentTimeMillis();
207        values.put(CalendarAlerts.CREATION_TIME, currentTime);
208        values.put(CalendarAlerts.RECEIVED_TIME, 0);
209        values.put(CalendarAlerts.NOTIFY_TIME, 0);
210        values.put(CalendarAlerts.STATE, CalendarAlerts.STATE_SCHEDULED);
211        values.put(CalendarAlerts.MINUTES, minutes);
212        return values;
213    }
214
215    public static Intent buildEventViewIntent(Context c, long eventId, long begin, long end) {
216        Intent i = new Intent(Intent.ACTION_VIEW);
217        Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
218        builder.appendEncodedPath("events/" + eventId);
219        i.setData(builder.build());
220        i.setClass(c, EventInfoActivity.class);
221        i.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, begin);
222        i.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end);
223        return i;
224    }
225
226    public static SharedPreferences getFiredAlertsTable(Context context) {
227        return context.getSharedPreferences(ALERTS_SHARED_PREFS_NAME, Context.MODE_PRIVATE);
228    }
229
230    private static String getFiredAlertsKey(long eventId, long beginTime,
231            long alarmTime) {
232        StringBuilder sb = new StringBuilder(KEY_FIRED_ALERT_PREFIX);
233        sb.append(eventId);
234        sb.append("_");
235        sb.append(beginTime);
236        sb.append("_");
237        sb.append(alarmTime);
238        return sb.toString();
239    }
240
241    /**
242     * Returns whether the SharedPrefs storage indicates we have fired the alert before.
243     */
244    static boolean hasAlertFiredInSharedPrefs(Context context, long eventId, long beginTime,
245            long alarmTime) {
246        SharedPreferences prefs = getFiredAlertsTable(context);
247        return prefs.contains(getFiredAlertsKey(eventId, beginTime, alarmTime));
248    }
249
250    /**
251     * Store fired alert info in the SharedPrefs.
252     */
253    static void setAlertFiredInSharedPrefs(Context context, long eventId, long beginTime,
254            long alarmTime) {
255        // Store alarm time as the value too so we don't have to parse all the keys to flush
256        // old alarms out of the table later.
257        SharedPreferences prefs = getFiredAlertsTable(context);
258        SharedPreferences.Editor editor = prefs.edit();
259        editor.putLong(getFiredAlertsKey(eventId, beginTime, alarmTime), alarmTime);
260        editor.apply();
261    }
262
263    /**
264     * Scans and flushes the internal storage of old alerts.  Looks up the previous flush
265     * time in SharedPrefs, and performs the flush if overdue.  Otherwise, no-op.
266     */
267    static void flushOldAlertsFromInternalStorage(Context context) {
268        if (BYPASS_DB) {
269            SharedPreferences prefs = getFiredAlertsTable(context);
270
271            // Only flush if it hasn't been done in a while.
272            long nowTime = System.currentTimeMillis();
273            long lastFlushTimeMs = prefs.getLong(KEY_LAST_FLUSH_TIME_MS, 0);
274            if (nowTime - lastFlushTimeMs > FLUSH_INTERVAL_MS) {
275                if (DEBUG) {
276                    Log.d(TAG, "Flushing old alerts from shared prefs table");
277                }
278
279                // Scan through all fired alert entries, removing old ones.
280                SharedPreferences.Editor editor = prefs.edit();
281                Time timeObj = new Time();
282                for (Map.Entry<String, ?> entry : prefs.getAll().entrySet()) {
283                    String key = entry.getKey();
284                    Object value = entry.getValue();
285                    if (key.startsWith(KEY_FIRED_ALERT_PREFIX)) {
286                        long alertTime;
287                        if (value instanceof Long) {
288                            alertTime = (Long) value;
289                        } else {
290                            // Should never occur.
291                            Log.e(TAG,"SharedPrefs key " + key + " did not have Long value: " +
292                                    value);
293                            continue;
294                        }
295
296                        if (nowTime - alertTime >= FLUSH_INTERVAL_MS) {
297                            editor.remove(key);
298                            if (DEBUG) {
299                                int ageInDays = getIntervalInDays(alertTime, nowTime, timeObj);
300                                Log.d(TAG, "SharedPrefs key " + key + ": removed (" + ageInDays +
301                                        " days old)");
302                            }
303                        } else {
304                            if (DEBUG) {
305                                int ageInDays = getIntervalInDays(alertTime, nowTime, timeObj);
306                                Log.d(TAG, "SharedPrefs key " + key + ": keep (" + ageInDays +
307                                        " days old)");
308                            }
309                        }
310                    }
311                }
312                editor.putLong(KEY_LAST_FLUSH_TIME_MS, nowTime);
313                editor.apply();
314            }
315        }
316    }
317
318    private static int getIntervalInDays(long startMillis, long endMillis, Time timeObj) {
319        timeObj.set(startMillis);
320        int startDay = Time.getJulianDay(startMillis, timeObj.gmtoff);
321        timeObj.set(endMillis);
322        return Time.getJulianDay(endMillis, timeObj.gmtoff) - startDay;
323    }
324}
325