CalendarProvider2.java revision 192b1807d4b6265a4f7581580bd6172dae3fc1b1
19f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff/*
29f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff**
39f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff** Copyright 2006, The Android Open Source Project
49f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff**
59f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff** Licensed under the Apache License, Version 2.0 (the "License");
69f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff** you may not use this file except in compliance with the License.
79f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff** You may obtain a copy of the License at
89f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff**
99f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff**     http://www.apache.org/licenses/LICENSE-2.0
109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff**
119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff** Unless required by applicable law or agreed to in writing, software
129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff** distributed under the License is distributed on an "AS IS" BASIS,
139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff** See the License for the specific language governing permissions and
149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff** limitations under the License.
169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff*/
179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffpackage com.android.providers.calendar;
199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.accounts.Account;
219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.accounts.AccountManager;
229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.accounts.OnAccountsUpdateListener;
239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.app.AlarmManager;
249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.app.PendingIntent;
259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.content.BroadcastReceiver;
269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.content.ContentResolver;
279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.content.ContentUris;
289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.content.ContentValues;
299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.content.Context;
309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.content.Intent;
319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.content.IntentFilter;
329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.content.UriMatcher;
339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.database.Cursor;
349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.database.DatabaseUtils;
359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.database.SQLException;
369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.database.sqlite.SQLiteDatabase;
379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.database.sqlite.SQLiteQueryBuilder;
389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.net.Uri;
399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.os.Debug;
409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.os.Process;
419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.pim.DateException;
42f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglioimport android.pim.EventRecurrence;
439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.pim.RecurrenceSet;
449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.provider.BaseColumns;
459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.provider.Calendar;
469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.provider.Calendar.Attendees;
479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.provider.Calendar.CalendarAlerts;
489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.provider.Calendar.Calendars;
499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.provider.Calendar.Events;
509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.provider.Calendar.Instances;
519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.provider.Calendar.Reminders;
529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.text.TextUtils;
531edaf77a7ef2fbad6b6116dd75591e0aeaff3a16Ken Shirriffimport android.text.format.DateUtils;
54192b1807d4b6265a4f7581580bd6172dae3fc1b1Marc Blankimport android.text.format.Time;
559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.util.Config;
569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.util.Log;
579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport android.util.TimeFormatException;
58ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglioimport android.util.TimeUtils;
599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport java.util.ArrayList;
619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport java.util.HashMap;
629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport java.util.HashSet;
639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport java.util.Set;
649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffimport java.util.TimeZone;
659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff/**
679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff * Calendar content provider. The contract between this provider and applications
689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff * is defined in {@link android.provider.Calendar}.
699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff */
709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriffpublic class CalendarProvider2 extends SQLiteContentProvider implements OnAccountsUpdateListener {
719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final String TAG = "CalendarProvider2";
739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final boolean PROFILE = false;
759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final boolean MULTIPLE_ATTENDEES_PER_EVENT = true;
768f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff
778f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff    private static final String INVALID_CALENDARALERTS_SELECTOR =
788f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff            "_id IN (SELECT ca._id FROM CalendarAlerts AS ca"
798f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                    + " LEFT OUTER JOIN Instances USING (event_id, begin, end)"
808f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                    + " LEFT OUTER JOIN Reminders AS r ON"
818f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                    + " (ca.event_id=r.event_id AND ca.minutes=r.minutes)"
828f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                    + " WHERE Instances.begin ISNULL OR ca.alarmTime<?"
838f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                    + "   OR (r.minutes ISNULL AND ca.minutes<>0))";
848f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff
851ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff    private static final String[] ID_ONLY_PROJECTION =
861ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff            new String[] {Events._ID};
879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final String[] EVENTS_PROJECTION = new String[] {
899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events._SYNC_ID,
909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.RRULE,
919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.RDATE,
929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.ORIGINAL_EVENT,
939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    };
949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int EVENTS_SYNC_ID_INDEX = 0;
957e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    private static final int EVENTS_RRULE_INDEX = 1;
967e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    private static final int EVENTS_RDATE_INDEX = 2;
977e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    private static final int EVENTS_ORIGINAL_EVENT_INDEX = 3;
987e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff
997e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    private static final String[] ID_PROJECTION = new String[] {
1007e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff            Attendees._ID,
1017e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff            Attendees.EVENT_ID, // Assume these are the same for each table
1027e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    };
1037e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    private static final int ID_INDEX = 0;
1047e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    private static final int EVENT_ID_INDEX = 1;
1059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
1079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * The cached copy of the CalendarMetaData database table.
1089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Make this "package private" instead of "private" so that test code
1099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * can access it.
1109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
1119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    MetaData mMetaData;
112ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    CalendarCache mCalendarCache;
1139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private CalendarDatabaseHelper mDbHelper;
1159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final Uri SYNCSTATE_CONTENT_URI =
1179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Uri.parse("content://syncstate/state");
11883512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff    //
11983512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff    // SCHEDULE_ALARM_URI runs scheduleNextAlarm(false)
12083512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff    // SCHEDULE_ALARM_REMOVE_URI runs scheduleNextAlarm(true)
12183512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff    // TODO: use a service to schedule alarms rather than private URI
12283512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff    /* package */ static final String SCHEDULE_ALARM_PATH = "schedule_alarms";
12383512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff    /* package */ static final String SCHEDULE_ALARM_REMOVE_PATH = "schedule_alarms_remove";
12483512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff    /* package */ static final Uri SCHEDULE_ALARM_URI =
12583512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff            Uri.withAppendedPath(Calendar.CONTENT_URI, SCHEDULE_ALARM_PATH);
12683512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff    /* package */ static final Uri SCHEDULE_ALARM_REMOVE_URI =
12783512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff            Uri.withAppendedPath(Calendar.CONTENT_URI, SCHEDULE_ALARM_REMOVE_PATH);
1289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    // To determine if a recurrence exception originally overlapped the
1309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    // window, we need to assume a maximum duration, since we only know
1319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    // the original start time.
1329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int MAX_ASSUMED_DURATION = 7*24*60*60*1000;
1339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    public static final class TimeRange {
1359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        public long begin;
1369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        public long end;
1379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        public boolean allDay;
1389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
1399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    public static final class InstancesRange {
1419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        public long begin;
1429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        public long end;
1439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        public InstancesRange(long begin, long end) {
1459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            this.begin = begin;
1469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            this.end = end;
1479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
1489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
1499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    public static final class InstancesList
1519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            extends ArrayList<ContentValues> {
1529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
1539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    public static final class EventInstancesMap
1559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            extends HashMap<String, InstancesList> {
1569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        public void add(String syncId, ContentValues values) {
1579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            InstancesList instances = get(syncId);
1589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (instances == null) {
1599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                instances = new InstancesList();
1609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                put(syncId, instances);
1619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
1629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            instances.add(values);
1639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
1649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
1659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    // A thread that runs in the background and schedules the next
1679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    // calendar event alarm.
1689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private class AlarmScheduler extends Thread {
1699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        boolean mRemoveAlarms;
1709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        public AlarmScheduler(boolean removeAlarms) {
1729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            mRemoveAlarms = removeAlarms;
1739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
1749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
175192b1807d4b6265a4f7581580bd6172dae3fc1b1Marc Blank        @Override
1769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        public void run() {
1779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            try {
1789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                runScheduleNextAlarm(mRemoveAlarms);
1809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            } catch (SQLException e) {
1819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Log.e(TAG, "runScheduleNextAlarm() failed", e);
1829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
1839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
1849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
1859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
1879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * We search backward in time for event reminders that we may have missed
1889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * and schedule them if the event has not yet expired.  The amount in
1899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * the past to search backwards is controlled by this constant.  It
1909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * should be at least a few minutes to allow for an event that was
1919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * recently created on the web to make its way to the phone.  Two hours
1929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * might seem like overkill, but it is useful in the case where the user
1939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * just crossed into a new timezone and might have just missed an alarm.
1949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
1951edaf77a7ef2fbad6b6116dd75591e0aeaff3a16Ken Shirriff    private static final long SCHEDULE_ALARM_SLACK = 2 * DateUtils.HOUR_IN_MILLIS;
1969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
1989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Alarms older than this threshold will be deleted from the CalendarAlerts
1999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * table.  This should be at least a day because if the timezone is
2009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * wrong and the user corrects it we might delete good alarms that
2019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * appear to be old because the device time was incorrectly in the future.
2029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * This threshold must also be larger than SCHEDULE_ALARM_SLACK.  We add
2039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * the SCHEDULE_ALARM_SLACK to ensure this.
2049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
2059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * To make it easier to find and debug problems with missed reminders,
2069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * set this to something greater than a day.
2079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
2089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final long CLEAR_OLD_ALARM_THRESHOLD =
2091edaf77a7ef2fbad6b6116dd75591e0aeaff3a16Ken Shirriff            7 * DateUtils.DAY_IN_MILLIS + SCHEDULE_ALARM_SLACK;
2109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    // A lock for synchronizing access to fields that are shared
2129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    // with the AlarmScheduler thread.
2139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private Object mAlarmLock = new Object();
2149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    // Make sure we load at least two months worth of data.
2169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    // Client apps can load more data in a background thread.
2179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final long MINIMUM_EXPANSION_SPAN =
2189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            2L * 31 * 24 * 60 * 60 * 1000;
2199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final String[] sCalendarsIdProjection = new String[] { Calendars._ID };
2219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int CALENDARS_INDEX_ID = 0;
2229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    // Allocate the string constant once here instead of on the heap
2249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final String CALENDAR_ID_SELECTION = "calendar_id=?";
2259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final String[] sInstancesProjection =
2279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            new String[] { Instances.START_DAY, Instances.END_DAY,
2289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    Instances.START_MINUTE, Instances.END_MINUTE, Instances.ALL_DAY };
2299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int INSTANCES_INDEX_START_DAY = 0;
2319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int INSTANCES_INDEX_END_DAY = 1;
2329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int INSTANCES_INDEX_START_MINUTE = 2;
2339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int INSTANCES_INDEX_END_MINUTE = 3;
2349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int INSTANCES_INDEX_ALL_DAY = 4;
2359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private AlarmManager mAlarmManager;
2379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private CalendarAppWidgetProvider mAppWidgetProvider = CalendarAppWidgetProvider.getInstance();
2399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
2419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Listens for timezone changes and disk-no-longer-full events
2429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
2439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
2449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        @Override
2459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        public void onReceive(Context context, Intent intent) {
2469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String action = intent.getAction();
2479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (Log.isLoggable(TAG, Log.DEBUG)) {
2489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Log.d(TAG, "onReceive() " + action);
2499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
2509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (Intent.ACTION_TIMEZONE_CHANGED.equals(action)) {
2519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                updateTimezoneDependentFields();
2529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                scheduleNextAlarm(false /* do not remove alarms */);
2539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            } else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action)) {
2549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Try to clean up if things were screwy due to a full disk
2559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                updateTimezoneDependentFields();
2569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                scheduleNextAlarm(false /* do not remove alarms */);
2579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            } else if (Intent.ACTION_TIME_CHANGED.equals(action)) {
2589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                scheduleNextAlarm(false /* do not remove alarms */);
2599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
2609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
2619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    };
2629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
263ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    /**
264ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio     * Columns from the EventsRawTimes table
265ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio     */
266ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    public interface EventsRawTimesColumns
267ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    {
268ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        /**
269ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         * The corresponding event id
270ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         * <P>Type: INTEGER (long)</P>
271ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         */
272ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        public static final String EVENT_ID = "event_id";
273ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
274ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        /**
275ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         * The RFC2445 compliant time the event starts
276ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         * <P>Type: TEXT</P>
277ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         */
278ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        public static final String DTSTART_2445 = "dtstart2445";
279ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
280ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        /**
281ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         * The RFC2445 compliant time the event ends
282ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         * <P>Type: TEXT</P>
283ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         */
284ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        public static final String DTEND_2445 = "dtend2445";
285ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
286ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        /**
287ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         * The RFC2445 compliant original instance time of the recurring event for which this
288ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         * event is an exception.
289ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         * <P>Type: TEXT</P>
290ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         */
291ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        public static final String ORIGINAL_INSTANCE_TIME_2445 = "originalInstanceTime2445";
292ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
293ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        /**
294ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         * The RFC2445 compliant last date this event repeats on, or NULL if it never ends
295ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         * <P>Type: TEXT</P>
296ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio         */
297ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        public static final String LAST_DATE_2445 = "lastDate2445";
298ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    }
299ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
3009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    protected void verifyAccounts() {
3019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        AccountManager.get(getContext()).addOnAccountsUpdatedListener(this, null, false);
3029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        onAccountsUpdated(AccountManager.get(getContext()).getAccounts());
3039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
3049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /* Visible for testing */
3069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    @Override
3079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    protected CalendarDatabaseHelper getDatabaseHelper(final Context context) {
3089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        return CalendarDatabaseHelper.getInstance(context);
3099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
3109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    @Override
3129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    public boolean onCreate() {
3139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        super.onCreate();
3149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        mDbHelper = (CalendarDatabaseHelper)getDatabaseHelper();
3159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        verifyAccounts();
3179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Register for Intent broadcasts
3199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        IntentFilter filter = new IntentFilter();
3209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
3229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
3239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        filter.addAction(Intent.ACTION_TIME_CHANGED);
3249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final Context c = getContext();
3259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // We don't ever unregister this because this thread always wants
3279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // to receive notifications, even in the background.  And if this
3289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // thread is killed then the whole process will be killed and the
3299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // memory resources will be reclaimed.
3309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        c.registerReceiver(mIntentReceiver, filter);
3319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        mMetaData = new MetaData(mDbHelper);
333ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        mCalendarCache = new CalendarCache(mDbHelper);
334ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
3359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        updateTimezoneDependentFields();
3369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        return true;
3389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
3399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
3419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * This creates a background thread to check the timezone and update
3429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * the timezone dependent fields in the Instances table if the timezone
3439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * has changes.
3449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
3459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    protected void updateTimezoneDependentFields() {
3469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Thread thread = new TimezoneCheckerThread();
3479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        thread.start();
3489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
3499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private class TimezoneCheckerThread extends Thread {
3519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        @Override
3529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        public void run() {
3539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
3549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            try {
3559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                doUpdateTimezoneDependentFields();
3569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            } catch (SQLException e) {
3579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Log.e(TAG, "doUpdateTimezoneDependentFields() failed", e);
3589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                try {
3599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // Clear at least the in-memory data (and if possible the
3609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // database fields) to force a re-computation of Instances.
3619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    mMetaData.clearInstanceRange();
3629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                } catch (SQLException e2) {
3639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    Log.e(TAG, "clearInstanceRange() also failed: " + e2);
3649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
3659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
3669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
3679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
3689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
3709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * This method runs in a background thread.  If the timezone has changed
3719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * then the Instances table will be regenerated.
3729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
3739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void doUpdateTimezoneDependentFields() {
374ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        if (! isSameTimezoneDatabaseVersion()) {
375ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            doProcessEventRawTimes(null  /* default current timezone*/,
376ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            TimeUtils.getTimeZoneDatabaseVersion());
377ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        }
378ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        if (isSameTimezone()) {
3799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Even if the timezone hasn't changed, check for missed alarms.
3809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // This code executes when the CalendarProvider2 is created and
3819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // helps to catch missed alarms when the Calendar process is
3829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // killed (because of low-memory conditions) and then restarted.
3839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            rescheduleMissedAlarms();
3849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return;
3859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
386ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        regenerateInstancesTable();
387ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    }
388ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
389ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    protected void doProcessEventRawTimes(String timezone, String timeZoneDatabaseVersion) {
390ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        mDb = mDbHelper.getWritableDatabase();
391ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        if (mDb == null) {
392ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            if (Log.isLoggable(TAG, Log.VERBOSE)) {
393ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                Log.v(TAG, "Cannot update Events table from EventsRawTimes table");
394ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            }
395ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            return;
396ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        }
397ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        mDb.beginTransaction();
398ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        try {
399ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            updateEventsStartEndFromEventRawTimesLocked(timezone);
400ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            updateTimezoneDatabaseVersion(timeZoneDatabaseVersion);
401ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            cleanInstancesTable();
402ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            regenerateInstancesTable();
403ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
404ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            mDb.setTransactionSuccessful();
405ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        } finally {
406ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            mDb.endTransaction();
407ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        }
408ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    }
409ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
410ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    private void updateEventsStartEndFromEventRawTimesLocked(String timezone) {
411ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        Cursor cursor = mDb.query("EventsRawTimes",
412ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                            new String[] { EventsRawTimesColumns.EVENT_ID,
413ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                                    EventsRawTimesColumns.DTSTART_2445,
414ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                                    EventsRawTimesColumns.DTEND_2445} /* projection */,
415ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                            null /* selection */,
416ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                            null /* selection args */,
417ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                            null /* group by */,
418ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                            null /* having */,
419ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                            null /* order by */
420ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                );
421ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        try {
422ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            while (cursor.moveToNext()) {
423ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                long eventId = cursor.getLong(0);
424ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                String dtStart2445 = cursor.getString(1);
425ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                String dtEnd2445 = cursor.getString(2);
426ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                updateEventsStartEndLocked(eventId,
427ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                        timezone,
428ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                        dtStart2445,
429ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                        dtEnd2445);
430ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            }
431ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        } finally {
432ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            cursor.close();
433ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            cursor = null;
434ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        }
435ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    }
436ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
437ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    private long get2445ToMillis(String timezone, String dt2445) {
438ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        if (null == dt2445) {
439ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            Log.v( TAG, "Cannot parse null RFC2445 date");
440ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            return 0;
441ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        }
442ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        Time time = (timezone != null) ? new Time(timezone) : new Time();
443ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        try {
444ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            time.parse(dt2445);
445ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        } catch (TimeFormatException e) {
446ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            Log.v( TAG, "Cannot parse RFC2445 date " + dt2445);
447ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            return 0;
448ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        }
449ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        return time.toMillis(true /* ignore DST */);
450ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    }
451ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
452ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    private void updateEventsStartEndLocked(long eventId,
453ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            String timezone, String dtStart2445, String dtEnd2445) {
454ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
455ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        ContentValues values = new ContentValues();
456ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        values.put("dtstart", get2445ToMillis(timezone, dtStart2445));
457ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        values.put("dtend", get2445ToMillis(timezone, dtEnd2445));
458ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
459dc538177512191886cc40bc5e5125aae9bb197aaKen Shirriff        int result = mDb.update("Events", values, "_id=?",
460dc538177512191886cc40bc5e5125aae9bb197aaKen Shirriff                new String[] {String.valueOf(eventId)});
461ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        if (0 == result) {
462ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            if (Log.isLoggable(TAG, Log.VERBOSE)) {
463ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio                Log.v(TAG, "Could not update Events table with values " + values);
464ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            }
465ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        }
466ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    }
467ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
468ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    private void cleanInstancesTable() {
469ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        mDb.delete("Instances", null /* where clause */, null /* where args */);
470ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    }
471ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
472ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    private void updateTimezoneDatabaseVersion(String timeZoneDatabaseVersion) {
473ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        try {
474ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            mCalendarCache.writeTimezoneDatabaseVersion(timeZoneDatabaseVersion);
475ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        } catch (CalendarCache.CacheException e) {
476ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            Log.e(TAG, "Could not write timezone database version in the cache");
477ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        }
478ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    }
4799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
480ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    /**
481ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio     * Check if we are in the same time zone
482ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio     */
483ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    private boolean isSameTimezone() {
484ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        MetaData.Fields fields = mMetaData.getFields();
485ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        String localTimezone = TimeZone.getDefault().getID();
486ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        return TextUtils.equals(fields.timezone, localTimezone);
487ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    }
488ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
489ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    /**
490ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio     * Check if the time zone database version is the same as the cached one
491ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio     */
492ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    protected boolean isSameTimezoneDatabaseVersion() {
493ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        String timezoneDatabaseVersion = null;
494ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        try {
495ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            timezoneDatabaseVersion = mCalendarCache.readTimezoneDatabaseVersion();
496ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        } catch (CalendarCache.CacheException e) {
497ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            Log.e(TAG, "Could not read timezone database version from the cache");
498ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            return false;
499ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        }
500ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        return TextUtils.equals(timezoneDatabaseVersion, TimeUtils.getTimeZoneDatabaseVersion());
501ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    }
502ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
503ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    protected String getTimezoneDatabaseVersion() {
504ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        String timezoneDatabaseVersion = null;
505ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        try {
506ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            timezoneDatabaseVersion = mCalendarCache.readTimezoneDatabaseVersion();
507ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        } catch (CalendarCache.CacheException e) {
508ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            Log.e(TAG, "Could not read timezone database version from the cache");
509ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio            return "";
510ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        }
511ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        Log.i(TAG, "timezoneDatabaseVersion = " + timezoneDatabaseVersion);
512ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        return timezoneDatabaseVersion;
513ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    }
514ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio
515ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio    private void regenerateInstancesTable() {
5169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // The database timezone is different from the current timezone.
5179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Regenerate the Instances table for this month.  Include events
5189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // starting at the beginning of this month.
5199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        long now = System.currentTimeMillis();
5209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Time time = new Time();
5219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        time.set(now);
5229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        time.monthDay = 1;
5239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        time.hour = 0;
5249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        time.minute = 0;
5259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        time.second = 0;
5269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        long begin = time.normalize(true);
5279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        long end = begin + MINIMUM_EXPANSION_SPAN;
5289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
5299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        handleInstanceQuery(qb, begin, end, new String[] { Instances._ID },
5309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                null /* selection */, null /* sort */, false /* searchByDayInsteadOfMillis */);
5319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
5329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        rescheduleMissedAlarms();
5339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
5349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
5359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void rescheduleMissedAlarms() {
5369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        AlarmManager manager = getAlarmManager();
5379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (manager != null) {
5389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Context context = getContext();
5399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            ContentResolver cr = context.getContentResolver();
5409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            CalendarAlerts.rescheduleMissedAlarms(cr, context, manager);
5419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
5429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
5439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
5449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
5459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Appends comma separated ids.
5469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param ids Should not be empty
5479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
5489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void appendIds(StringBuilder sb, HashSet<Long> ids) {
5499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        for (long id : ids) {
5509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            sb.append(id).append(',');
5519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
5529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
5539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sb.setLength(sb.length() - 1); // Yank the last comma
5549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
5559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
5569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    @Override
5579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    protected void notifyChange() {
5589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Note that semantics are changed: notification is for CONTENT_URI, not the specific
5599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Uri that was modified.
5609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        getContext().getContentResolver().notifyChange(Calendar.CONTENT_URI, null,
5619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                true /* syncToNetwork */);
5629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
5639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
5649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    @Override
5659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
5669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String sortOrder) {
567ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        if (Log.isLoggable(TAG, Log.VERBOSE)) {
5689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.v(TAG, "query: " + uri);
5699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
5709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
5719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final SQLiteDatabase db = mDbHelper.getReadableDatabase();
5729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
5739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
5749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        String groupBy = null;
5759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        String limit = null; // Not currently implemented
5769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
5779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final int match = sUriMatcher.match(uri);
5789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        switch (match) {
5799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case SYNCSTATE:
5809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return mDbHelper.getSyncState().query(db, projection, selection,  selectionArgs,
5819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        sortOrder);
5829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
5839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case EVENTS:
5841ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                qb.setTables(CalendarDatabaseHelper.Views.EVENTS);
5859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                qb.setProjectionMap(sEventsProjectionMap);
586595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff                appendAccountFromParameter(qb, uri);
5879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
5889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case EVENTS_ID:
5891ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                qb.setTables(CalendarDatabaseHelper.Views.EVENTS);
5909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                qb.setProjectionMap(sEventsProjectionMap);
591636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                selectionArgs = insertSelectionArg(selectionArgs, uri.getPathSegments().get(1));
592636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                qb.appendWhere("_id=?");
5939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
59419fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana
59519fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana            case EVENT_ENTITIES:
59619fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana                qb.setTables(CalendarDatabaseHelper.Views.EVENTS);
59719fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana                qb.setProjectionMap(sEventEntitiesProjectionMap);
598595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff                appendAccountFromParameter(qb, uri);
59919fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana                break;
60019fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana            case EVENT_ENTITIES_ID:
60119fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana                qb.setTables(CalendarDatabaseHelper.Views.EVENTS);
60219fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana                qb.setProjectionMap(sEventEntitiesProjectionMap);
603636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                selectionArgs = insertSelectionArg(selectionArgs, uri.getPathSegments().get(1));
604636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                qb.appendWhere("_id=?");
60519fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana                break;
60619fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana
6079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDARS:
6089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                qb.setTables("Calendars");
609595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff                appendAccountFromParameter(qb, uri);
6109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
6119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDARS_ID:
6129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                qb.setTables("Calendars");
613636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                selectionArgs = insertSelectionArg(selectionArgs, uri.getPathSegments().get(1));
614636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                qb.appendWhere("_id=?");
6159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
6169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case INSTANCES:
6179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case INSTANCES_BY_DAY:
6189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                long begin;
6199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                long end;
6209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                try {
6219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    begin = Long.valueOf(uri.getPathSegments().get(2));
6229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                } catch (NumberFormatException nfe) {
6239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    throw new IllegalArgumentException("Cannot parse begin "
6249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            + uri.getPathSegments().get(2));
6259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
6269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                try {
6279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    end = Long.valueOf(uri.getPathSegments().get(3));
6289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                } catch (NumberFormatException nfe) {
6299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    throw new IllegalArgumentException("Cannot parse end "
6309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            + uri.getPathSegments().get(3));
6319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
6329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return handleInstanceQuery(qb, begin, end, projection,
6339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        selection, sortOrder, match == INSTANCES_BY_DAY);
6346db535b458146a279bebd4a51d56c1bdfc204528Erik            case EVENT_DAYS:
6359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                int startDay;
6369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                int endDay;
6379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                try {
6389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    startDay = Integer.valueOf(uri.getPathSegments().get(2));
6399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                } catch (NumberFormatException nfe) {
6409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    throw new IllegalArgumentException("Cannot parse start day "
6419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            + uri.getPathSegments().get(2));
6429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
6439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                try {
6449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    endDay = Integer.valueOf(uri.getPathSegments().get(3));
6459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                } catch (NumberFormatException nfe) {
6469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    throw new IllegalArgumentException("Cannot parse end day "
6479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            + uri.getPathSegments().get(3));
6489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
6496db535b458146a279bebd4a51d56c1bdfc204528Erik                return handleEventDayQuery(qb, startDay, endDay, projection, selection);
6509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case ATTENDEES:
6511ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                qb.setTables("Attendees, Events");
6529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                qb.setProjectionMap(sAttendeesProjectionMap);
6531ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                qb.appendWhere("Events._id=Attendees.event_id");
6549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
6559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case ATTENDEES_ID:
6561ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                qb.setTables("Attendees, Events");
6579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                qb.setProjectionMap(sAttendeesProjectionMap);
658636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                selectionArgs = insertSelectionArg(selectionArgs, uri.getPathSegments().get(1));
659636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                qb.appendWhere("Attendees._id=?  AND Events._id=Attendees.event_id");
6609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
6619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case REMINDERS:
6629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                qb.setTables("Reminders");
6639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
6649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case REMINDERS_ID:
6651ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                qb.setTables("Reminders, Events");
6669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                qb.setProjectionMap(sRemindersProjectionMap);
667636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
668636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                qb.appendWhere("Reminders._id=? AND Events._id=Reminders.event_id");
6699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
6709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDAR_ALERTS:
671e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff                qb.setTables("CalendarAlerts, " + CalendarDatabaseHelper.Views.EVENTS);
6729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                qb.setProjectionMap(sCalendarAlertsProjectionMap);
673e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff                qb.appendWhere(CalendarDatabaseHelper.Views.EVENTS +
674e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff                        "._id=CalendarAlerts.event_id");
6759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
6769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDAR_ALERTS_BY_INSTANCE:
677e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff                qb.setTables("CalendarAlerts, " + CalendarDatabaseHelper.Views.EVENTS);
6789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                qb.setProjectionMap(sCalendarAlertsProjectionMap);
679e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff                qb.appendWhere(CalendarDatabaseHelper.Views.EVENTS +
680e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff                        "._id=CalendarAlerts.event_id");
6819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                groupBy = CalendarAlerts.EVENT_ID + "," + CalendarAlerts.BEGIN;
6829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
6839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDAR_ALERTS_ID:
684e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff                qb.setTables("CalendarAlerts, " + CalendarDatabaseHelper.Views.EVENTS);
6859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                qb.setProjectionMap(sCalendarAlertsProjectionMap);
686636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
687e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff                qb.appendWhere(CalendarDatabaseHelper.Views.EVENTS +
688e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff                        "._id=CalendarAlerts.event_id AND CalendarAlerts._id=?");
6899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
6909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case EXTENDED_PROPERTIES:
6919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                qb.setTables("ExtendedProperties");
6929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
6939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case EXTENDED_PROPERTIES_ID:
6947e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                qb.setTables("ExtendedProperties");
695636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                selectionArgs = insertSelectionArg(selectionArgs, uri.getPathSegments().get(1));
696636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                qb.appendWhere("ExtendedProperties._id=?");
6979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
6989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            default:
6999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                throw new IllegalArgumentException("Unknown URL " + uri);
7009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
7019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
7029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // run the query
7039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        return query(db, qb, projection, selection, selectionArgs, sortOrder, groupBy, limit);
7049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
7059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
7069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private Cursor query(final SQLiteDatabase db, SQLiteQueryBuilder qb, String[] projection,
7079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String selection, String[] selectionArgs, String sortOrder, String groupBy,
7089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String limit) {
7099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null,
7109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                sortOrder, limit);
7119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (c != null) {
7129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // TODO: is this the right notification Uri?
7139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            c.setNotificationUri(getContext().getContentResolver(), Calendar.Events.CONTENT_URI);
7149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
7159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        return c;
7169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
7179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
7189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /*
7199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Fills the Instances table, if necessary, for the given range and then
7209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * queries the Instances table.
7219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
7229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param qb The query
7239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param rangeBegin start of range (Julian days or ms)
7249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param rangeEnd end of range (Julian days or ms)
7259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param projection The projection
7269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param selection The selection
7279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param sort How to sort
7289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param searchByDay if true, range is in Julian days, if false, range is in ms
7299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @return
7309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
7319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private Cursor handleInstanceQuery(SQLiteQueryBuilder qb, long rangeBegin,
7329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            long rangeEnd, String[] projection,
7339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String selection, String sort, boolean searchByDay) {
7349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
7359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        qb.setTables("Instances INNER JOIN Events ON (Instances.event_id=Events._id) " +
7369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                "INNER JOIN Calendars ON (Events.calendar_id = Calendars._id)");
7379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        qb.setProjectionMap(sInstancesProjectionMap);
7389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (searchByDay) {
7399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Convert the first and last Julian day range to a range that uses
7409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // UTC milliseconds.
7419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Time time = new Time();
7429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            long beginMs = time.setJulianDay((int) rangeBegin);
7439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // We add one to lastDay because the time is set to 12am on the given
7449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Julian day and we want to include all the events on the last day.
7459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            long endMs = time.setJulianDay((int) rangeEnd + 1);
7469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // will lock the database.
7479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            acquireInstanceRange(beginMs, endMs, true /* use minimum expansion window */);
7488335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff            qb.appendWhere("startDay<=? AND endDay>=?");
7499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } else {
7509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // will lock the database.
7519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            acquireInstanceRange(rangeBegin, rangeEnd, true /* use minimum expansion window */);
7528335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff            qb.appendWhere("begin<=? AND end>=?");
7539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
7548335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff        String selectionArgs[] = new String[] {String.valueOf(rangeEnd),
7558335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff                String.valueOf(rangeBegin)};
7568335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff        return qb.query(mDb, projection, selection, selectionArgs, null /* groupBy */,
7577e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                null /* having */, sort);
7589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
7599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
7606db535b458146a279bebd4a51d56c1bdfc204528Erik    private Cursor handleEventDayQuery(SQLiteQueryBuilder qb, int begin, int end,
7616db535b458146a279bebd4a51d56c1bdfc204528Erik            String[] projection, String selection) {
7626db535b458146a279bebd4a51d56c1bdfc204528Erik        qb.setTables("Instances INNER JOIN Events ON (Instances.event_id=Events._id) " +
7636db535b458146a279bebd4a51d56c1bdfc204528Erik                "INNER JOIN Calendars ON (Events.calendar_id = Calendars._id)");
7646db535b458146a279bebd4a51d56c1bdfc204528Erik        qb.setProjectionMap(sInstancesProjectionMap);
76543556fa5610bd302cb80aa5ddc98af1e2f2d8b18Ken Shirriff        // Convert the first and last Julian day range to a range that uses
76643556fa5610bd302cb80aa5ddc98af1e2f2d8b18Ken Shirriff        // UTC milliseconds.
76743556fa5610bd302cb80aa5ddc98af1e2f2d8b18Ken Shirriff        Time time = new Time();
768192b1807d4b6265a4f7581580bd6172dae3fc1b1Marc Blank        long beginMs = time.setJulianDay(begin);
76943556fa5610bd302cb80aa5ddc98af1e2f2d8b18Ken Shirriff        // We add one to lastDay because the time is set to 12am on the given
77043556fa5610bd302cb80aa5ddc98af1e2f2d8b18Ken Shirriff        // Julian day and we want to include all the events on the last day.
771192b1807d4b6265a4f7581580bd6172dae3fc1b1Marc Blank        long endMs = time.setJulianDay(end + 1);
77243556fa5610bd302cb80aa5ddc98af1e2f2d8b18Ken Shirriff
77343556fa5610bd302cb80aa5ddc98af1e2f2d8b18Ken Shirriff        acquireInstanceRange(beginMs, endMs, true);
7748335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff        qb.appendWhere("startDay<=? AND endDay>=?");
7758335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff        String selectionArgs[] = new String[] {String.valueOf(end), String.valueOf(begin)};
7768335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff
7778335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff        return qb.query(mDb, projection, selection, selectionArgs,
7786db535b458146a279bebd4a51d56c1bdfc204528Erik                Instances.START_DAY /* groupBy */, null /* having */, null);
7799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
7809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
7819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
7829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Ensure that the date range given has all elements in the instance
7839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * table.  Acquires the database lock and calls {@link #acquireInstanceRangeLocked}.
7849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
7859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param begin start of range (ms)
7869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param end end of range (ms)
7879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param useMinimumExpansionWindow expand by at least MINIMUM_EXPANSION_SPAN
7889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
7899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void acquireInstanceRange(final long begin,
7909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            final long end,
7919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            final boolean useMinimumExpansionWindow) {
7929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        mDb.beginTransaction();
7939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        try {
7949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            acquireInstanceRangeLocked(begin, end, useMinimumExpansionWindow);
7959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            mDb.setTransactionSuccessful();
7969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } finally {
7979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            mDb.endTransaction();
7989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
7999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
8009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
8019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
8029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Ensure that the date range given has all elements in the instance
8039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * table.  The database lock must be held when calling this method.
8049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
8059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param begin start of range (ms)
8069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param end end of range (ms)
8079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param useMinimumExpansionWindow expand by at least MINIMUM_EXPANSION_SPAN
8089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
8099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void acquireInstanceRangeLocked(long begin, long end,
8109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            boolean useMinimumExpansionWindow) {
8119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        long expandBegin = begin;
8129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        long expandEnd = end;
8139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
8149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (useMinimumExpansionWindow) {
8159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // if we end up having to expand events into the instances table, expand
8169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // events for a minimal amount of time, so we do not have to perform
8179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // expansions frequently.
8189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            long span = end - begin;
8199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (span < MINIMUM_EXPANSION_SPAN) {
8209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                long additionalRange = (MINIMUM_EXPANSION_SPAN - span) / 2;
8219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                expandBegin -= additionalRange;
8229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                expandEnd += additionalRange;
8239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
8249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
8259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
8269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Check if the timezone has changed.
8279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // We do this check here because the database is locked and we can
8289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // safely delete all the entries in the Instances table.
8299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        MetaData.Fields fields = mMetaData.getFieldsLocked();
8309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        String dbTimezone = fields.timezone;
8319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        long maxInstance = fields.maxInstance;
8329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        long minInstance = fields.minInstance;
8339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        String localTimezone = TimeZone.getDefault().getID();
8349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        boolean timezoneChanged = (dbTimezone == null) || !dbTimezone.equals(localTimezone);
8359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
8369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (maxInstance == 0 || timezoneChanged) {
8379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Empty the Instances table and expand from scratch.
8389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            mDb.execSQL("DELETE FROM Instances;");
8399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (Config.LOGV) {
8406db535b458146a279bebd4a51d56c1bdfc204528Erik                Log.v(TAG, "acquireInstanceRangeLocked() deleted Instances,"
8419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        + " timezone changed: " + timezoneChanged);
8429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
8439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            expandInstanceRangeLocked(expandBegin, expandEnd, localTimezone);
8449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
845dbd797d59294d72d7ea9226d10128674b634aaadErik            mMetaData.writeLocked(localTimezone, expandBegin, expandEnd);
8469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return;
8479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
8489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
8499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // If the desired range [begin, end] has already been
8509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // expanded, then simply return.  The range is inclusive, that is,
8519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // events that touch either endpoint are included in the expansion.
8529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // This means that a zero-duration event that starts and ends at
8539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // the endpoint will be included.
8549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // We use [begin, end] here and not [expandBegin, expandEnd] for
8559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // checking the range because a common case is for the client to
8569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // request successive days or weeks, for example.  If we checked
8579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // that the expanded range [expandBegin, expandEnd] then we would
8589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // always be expanding because there would always be one more day
8599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // or week that hasn't been expanded.
8609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if ((begin >= minInstance) && (end <= maxInstance)) {
8619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (Config.LOGV) {
8629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Log.v(TAG, "Canceled instance query (" + expandBegin + ", " + expandEnd
8639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        + ") falls within previously expanded range.");
8649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
8659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return;
8669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
8679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
8689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // If the requested begin point has not been expanded, then include
8699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // more events than requested in the expansion (use "expandBegin").
8709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (begin < minInstance) {
8719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            expandInstanceRangeLocked(expandBegin, minInstance, localTimezone);
8729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            minInstance = expandBegin;
8739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
8749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
8759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // If the requested end point has not been expanded, then include
8769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // more events than requested in the expansion (use "expandEnd").
8779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (end > maxInstance) {
8789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            expandInstanceRangeLocked(maxInstance, expandEnd, localTimezone);
8799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            maxInstance = expandEnd;
8809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
8819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
8829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Update the bounds on the Instances table.
883dbd797d59294d72d7ea9226d10128674b634aaadErik        mMetaData.writeLocked(localTimezone, minInstance, maxInstance);
8849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
8859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
8869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final String[] EXPAND_COLUMNS = new String[] {
8879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events._ID,
8889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events._SYNC_ID,
8899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.STATUS,
8909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.DTSTART,
8919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.DTEND,
8929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.EVENT_TIMEZONE,
8939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.RRULE,
8949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.RDATE,
8959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.EXRULE,
8969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.EXDATE,
8979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.DURATION,
8989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.ALL_DAY,
8999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.ORIGINAL_EVENT,
9009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Events.ORIGINAL_INSTANCE_TIME
9019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    };
9029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
9049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Make instances for the given range.
9059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
9069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void expandInstanceRangeLocked(long begin, long end, String localTimezone) {
9079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (PROFILE) {
9099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Debug.startMethodTracing("expandInstanceRangeLocked");
9109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
9119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (Log.isLoggable(TAG, Log.VERBOSE)) {
9139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.v(TAG, "Expanding events between " + begin + " and " + end);
9149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
9159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Cursor entries = getEntries(begin, end);
9179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        try {
9189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            performInstanceExpansion(begin, end, localTimezone, entries);
9199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } finally {
9209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (entries != null) {
9219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                entries.close();
9229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
9239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
9249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (PROFILE) {
9259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Debug.stopMethodTracing();
9269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
9279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
9289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
9309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Get all entries affecting the given window.
9319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param begin Window start (ms).
9329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param end Window end (ms).
9339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @return Cursor for the entries; caller must close it.
9349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
9359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private Cursor getEntries(long begin, long end) {
9369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
9371ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        qb.setTables(CalendarDatabaseHelper.Views.EVENTS);
9389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        qb.setProjectionMap(sEventsProjectionMap);
9399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        String beginString = String.valueOf(begin);
9419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        String endString = String.valueOf(end);
9429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // grab recurrence exceptions that fall outside our expansion window but modify
9449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // recurrences that do fall within our window.  we won't insert these into the output
9459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // set of instances, but instead will just add them to our cancellations list, so we
9469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // can cancel the correct recurrence expansion instances.
9479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // we don't have originalInstanceDuration or end time.  for now, assume the original
9489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // instance lasts no longer than 1 week.
9492d1b3d70a6ebce8194932f8a8355d97a89da113fFabrice Di Meglio        // also filter with syncable state (we dont want the entries from a non syncable account)
9509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // TODO: compute the originalInstanceEndTime or get this from the server.
9512d1b3d70a6ebce8194932f8a8355d97a89da113fFabrice Di Meglio        qb.appendWhere("((dtstart <= ? AND (lastDate IS NULL OR lastDate >= ?)) OR " +
9528335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff                "(originalInstanceTime IS NOT NULL AND originalInstanceTime <= ? AND " +
9532d1b3d70a6ebce8194932f8a8355d97a89da113fFabrice Di Meglio                "originalInstanceTime >= ?)) AND (sync_events != 0)");
9548335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff        String selectionArgs[] = new String[] {endString, beginString, endString,
9558335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff                String.valueOf(begin - MAX_ASSUMED_DURATION)};
9569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (Log.isLoggable(TAG, Log.VERBOSE)) {
9579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.v(TAG, "Retrieving events to expand: " + qb.toString());
9589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
9599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9607e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        return qb.query(mDb, EXPAND_COLUMNS, null /* selection */,
9618335a18ac6024f302b50e6f473ad4058cc355c85Ken Shirriff                selectionArgs, null /* groupBy */,
9627e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                null /* having */, null /* sortOrder */);
9639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
9649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
9669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Perform instance expansion on the given entries.
9679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param begin Window start (ms).
9689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param end Window end (ms).
9699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param localTimezone
9709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param entries The entries to process.
9719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
9729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void performInstanceExpansion(long begin, long end, String localTimezone,
9739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                          Cursor entries) {
9749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        RecurrenceProcessor rp = new RecurrenceProcessor();
9759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int statusColumn = entries.getColumnIndex(Events.STATUS);
9779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int dtstartColumn = entries.getColumnIndex(Events.DTSTART);
9789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int dtendColumn = entries.getColumnIndex(Events.DTEND);
9799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int eventTimezoneColumn = entries.getColumnIndex(Events.EVENT_TIMEZONE);
9809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int durationColumn = entries.getColumnIndex(Events.DURATION);
9819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int rruleColumn = entries.getColumnIndex(Events.RRULE);
9829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int rdateColumn = entries.getColumnIndex(Events.RDATE);
9839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int exruleColumn = entries.getColumnIndex(Events.EXRULE);
9849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int exdateColumn = entries.getColumnIndex(Events.EXDATE);
9859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int allDayColumn = entries.getColumnIndex(Events.ALL_DAY);
9869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int idColumn = entries.getColumnIndex(Events._ID);
9879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int syncIdColumn = entries.getColumnIndex(Events._SYNC_ID);
9889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int originalEventColumn = entries.getColumnIndex(Events.ORIGINAL_EVENT);
9899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int originalInstanceTimeColumn = entries.getColumnIndex(Events.ORIGINAL_INSTANCE_TIME);
9909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        ContentValues initialValues;
9929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        EventInstancesMap instancesMap = new EventInstancesMap();
9939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Duration duration = new Duration();
9959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Time eventTime = new Time();
9969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
9979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Invariant: entries contains all events that affect the current
9989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // window.  It consists of:
9999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // a) Individual events that fall in the window.  These will be
10009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //    displayed.
10019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // b) Recurrences that included the window.  These will be displayed
10029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //    if not canceled.
10039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // c) Recurrence exceptions that fall in the window.  These will be
10049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //    displayed if not cancellations.
10059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // d) Recurrence exceptions that modify an instance inside the
10069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //    window (subject to 1 week assumption above), but are outside
10079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //    the window.  These will not be displayed.  Cases c and d are
10089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //    distingushed by the start / end time.
10099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
10109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        while (entries.moveToNext()) {
10119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            try {
10129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                initialValues = null;
10139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
10149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                boolean allDay = entries.getInt(allDayColumn) != 0;
10159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
10169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String eventTimezone = entries.getString(eventTimezoneColumn);
10179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (allDay || TextUtils.isEmpty(eventTimezone)) {
10189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // in the events table, allDay events start at midnight.
10199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // this forces them to stay at midnight for all day events
10209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // TODO: check that this actually does the right thing.
10219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    eventTimezone = Time.TIMEZONE_UTC;
10229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
10239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
10249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                long dtstartMillis = entries.getLong(dtstartColumn);
10259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Long eventId = Long.valueOf(entries.getLong(idColumn));
10269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
10279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String durationStr = entries.getString(durationColumn);
10289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (durationStr != null) {
10299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    try {
10309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        duration.parse(durationStr);
10319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
10329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    catch (DateException e) {
10339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        Log.w(TAG, "error parsing duration for event "
10349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                + eventId + "'" + durationStr + "'", e);
10359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        duration.sign = 1;
10369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        duration.weeks = 0;
10379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        duration.days = 0;
10389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        duration.hours = 0;
10399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        duration.minutes = 0;
10409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        duration.seconds = 0;
10419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        durationStr = "+P0S";
10429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
10439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
10449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
10459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String syncId = entries.getString(syncIdColumn);
10469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String originalEvent = entries.getString(originalEventColumn);
10479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
10489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                long originalInstanceTimeMillis = -1;
10499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (!entries.isNull(originalInstanceTimeColumn)) {
10509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    originalInstanceTimeMillis= entries.getLong(originalInstanceTimeColumn);
10519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
10529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                int status = entries.getInt(statusColumn);
10539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
10549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String rruleStr = entries.getString(rruleColumn);
10559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String rdateStr = entries.getString(rdateColumn);
10569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String exruleStr = entries.getString(exruleColumn);
10579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String exdateStr = entries.getString(exdateColumn);
10589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1059f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio                RecurrenceSet recur = null;
1060f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio                try {
1061f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio                    recur = new RecurrenceSet(rruleStr, rdateStr, exruleStr, exdateStr);
1062f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio                } catch (EventRecurrence.InvalidFormatException e) {
1063f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio                    Log.w(TAG, "Could not parse RRULE recurrence string: " + rruleStr, e);
1064f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio                    continue;
1065f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio                }
10669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1067f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio                if (null != recur && recur.hasRecurrence()) {
10689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // the event is repeating
10699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
10709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if (status == Events.STATUS_CANCELED) {
10719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        // should not happen!
10729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        Log.e(TAG, "Found canceled recurring event in "
10739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                + "Events table.  Ignoring.");
10749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        continue;
10759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
10769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
10779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // need to parse the event into a local calendar.
10789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    eventTime.timezone = eventTimezone;
10799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    eventTime.set(dtstartMillis);
10809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    eventTime.allDay = allDay;
10819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
10829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if (durationStr == null) {
10839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        // should not happen.
10849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        Log.e(TAG, "Repeating event has no duration -- "
10859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                + "should not happen.");
10869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        if (allDay) {
10879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            // set to one day.
10889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            duration.sign = 1;
10899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            duration.weeks = 0;
10909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            duration.days = 1;
10919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            duration.hours = 0;
10929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            duration.minutes = 0;
10939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            duration.seconds = 0;
10949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            durationStr = "+P1D";
10959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        } else {
10969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            // compute the duration from dtend, if we can.
10979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            // otherwise, use 0s.
10989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            duration.sign = 1;
10999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            duration.weeks = 0;
11009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            duration.days = 0;
11019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            duration.hours = 0;
11029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            duration.minutes = 0;
11039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            if (!entries.isNull(dtendColumn)) {
11049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                long dtendMillis = entries.getLong(dtendColumn);
11059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                duration.seconds = (int) ((dtendMillis - dtstartMillis) / 1000);
11069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                durationStr = "+P" + duration.seconds + "S";
11079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            } else {
11089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                duration.seconds = 0;
11099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                durationStr = "+P0S";
11109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            }
11119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        }
11129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
11139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    long[] dates;
11159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    dates = rp.expand(eventTime, recur, begin, end);
11169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // Initialize the "eventTime" timezone outside the loop.
11189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // This is used in computeTimezoneDependentFields().
11199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if (allDay) {
11209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        eventTime.timezone = Time.TIMEZONE_UTC;
11219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    } else {
11229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        eventTime.timezone = localTimezone;
11239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
11249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    long durationMillis = duration.getMillis();
11269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    for (long date : dates) {
11279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        initialValues = new ContentValues();
11289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        initialValues.put(Instances.EVENT_ID, eventId);
11299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        initialValues.put(Instances.BEGIN, date);
11319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        long dtendMillis = date + durationMillis;
11329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        initialValues.put(Instances.END, dtendMillis);
11339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        computeTimezoneDependentFields(date, dtendMillis,
11359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                eventTime, initialValues);
11369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        instancesMap.add(syncId, initialValues);
11379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
11389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                } else {
11399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // the event is not repeating
11409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    initialValues = new ContentValues();
11419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // if this event has an "original" field, then record
11439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // that we need to cancel the original event (we can't
11449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // do that here because the order of this loop isn't
11459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // defined)
11469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if (originalEvent != null && originalInstanceTimeMillis != -1) {
11479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        initialValues.put(Events.ORIGINAL_EVENT, originalEvent);
11489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        initialValues.put(Events.ORIGINAL_INSTANCE_TIME,
11499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                originalInstanceTimeMillis);
11509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        initialValues.put(Events.STATUS, status);
11519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
11529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    long dtendMillis = dtstartMillis;
11549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if (durationStr == null) {
11559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        if (!entries.isNull(dtendColumn)) {
11569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            dtendMillis = entries.getLong(dtendColumn);
11579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        }
11589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    } else {
11599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        dtendMillis = duration.addTo(dtstartMillis);
11609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
11619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // this non-recurring event might be a recurrence exception that doesn't
11639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // actually fall within our expansion window, but instead was selected
11649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // so we can correctly cancel expanded recurrence instances below.  do not
11659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // add events to the instances map if they don't actually fall within our
11669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // expansion window.
11679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if ((dtendMillis < begin) || (dtstartMillis > end)) {
11689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        if (originalEvent != null && originalInstanceTimeMillis != -1) {
11699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            initialValues.put(Events.STATUS, Events.STATUS_CANCELED);
11709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        } else {
11719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            Log.w(TAG, "Unexpected event outside window: " + syncId);
11729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            continue;
11739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        }
11749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
11759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    initialValues.put(Instances.EVENT_ID, eventId);
11779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    initialValues.put(Instances.BEGIN, dtstartMillis);
11789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    initialValues.put(Instances.END, dtendMillis);
11809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if (allDay) {
11829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        eventTime.timezone = Time.TIMEZONE_UTC;
11839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    } else {
11849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        eventTime.timezone = localTimezone;
11859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
11869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    computeTimezoneDependentFields(dtstartMillis, dtendMillis,
11879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            eventTime, initialValues);
11889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    instancesMap.add(syncId, initialValues);
11909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
11919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            } catch (DateException e) {
11929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Log.w(TAG, "RecurrenceProcessor error ", e);
11939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            } catch (TimeFormatException e) {
11949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Log.w(TAG, "RecurrenceProcessor error ", e);
11959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
11969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
11979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
11989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Invariant: instancesMap contains all instances that affect the
11999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // window, indexed by original sync id.  It consists of:
12009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // a) Individual events that fall in the window.  They have:
12019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //   EVENT_ID, BEGIN, END
12029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // b) Instances of recurrences that fall in the window.  They may
12039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //   be subject to exceptions.  They have:
12049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //   EVENT_ID, BEGIN, END
12059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // c) Exceptions that fall in the window.  They have:
12069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //   ORIGINAL_EVENT, ORIGINAL_INSTANCE_TIME, STATUS (since they can
12079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //   be a modification or cancellation), EVENT_ID, BEGIN, END
12089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // d) Recurrence exceptions that modify an instance inside the
12099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //   window but fall outside the window.  They have:
12109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //   ORIGINAL_EVENT, ORIGINAL_INSTANCE_TIME, STATUS =
12119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //   STATUS_CANCELED, EVENT_ID, BEGIN, END
12129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
12139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // First, delete the original instances corresponding to recurrence
12149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // exceptions.  We do this by iterating over the list and for each
12159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // recurrence exception, we search the list for an instance with a
12169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // matching "original instance time".  If we find such an instance,
12179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // we remove it from the list.  If we don't find such an instance
12189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // then we cancel the recurrence exception.
12199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Set<String> keys = instancesMap.keySet();
12209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        for (String syncId : keys) {
12219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            InstancesList list = instancesMap.get(syncId);
12229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            for (ContentValues values : list) {
12239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
12249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // If this instance is not a recurrence exception, then
12259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // skip it.
12269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (!values.containsKey(Events.ORIGINAL_EVENT)) {
12279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    continue;
12289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
12299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
12309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String originalEvent = values.getAsString(Events.ORIGINAL_EVENT);
12319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                long originalTime = values.getAsLong(Events.ORIGINAL_INSTANCE_TIME);
12329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                InstancesList originalList = instancesMap.get(originalEvent);
12339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (originalList == null) {
12349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // The original recurrence is not present, so don't try canceling it.
12359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    continue;
12369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
12379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
12389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Search the original event for a matching original
12399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // instance time.  If there is a matching one, then remove
12409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // the original one.  We do this both for exceptions that
12419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // change the original instance as well as for exceptions
12429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // that delete the original instance.
12439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                for (int num = originalList.size() - 1; num >= 0; num--) {
12449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    ContentValues originalValues = originalList.get(num);
12459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    long beginTime = originalValues.getAsLong(Instances.BEGIN);
12469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if (beginTime == originalTime) {
12479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        // We found the original instance, so remove it.
12489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        originalList.remove(num);
12499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
12509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
12519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
12529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
12539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
12549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Invariant: instancesMap contains filtered instances.
12559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // It consists of:
12569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // a) Individual events that fall in the window.
12579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // b) Instances of recurrences that fall in the window and have not
12589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //   been subject to exceptions.
12599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // c) Exceptions that fall in the window.  They will have
12609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //   STATUS_CANCELED if they are cancellations.
12619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // d) Recurrence exceptions that modify an instance inside the
12629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //   window but fall outside the window.  These are STATUS_CANCELED.
12639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
12649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Now do the inserts.  Since the db lock is held when this method is executed,
12659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // this will be done in a transaction.
12669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // NOTE: if there is lock contention (e.g., a sync is trying to merge into the db
12679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // while the calendar app is trying to query the db (expanding instances)), we will
12689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // not be "polite" and yield the lock until we're done.  This will favor local query
12699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // operations over sync/write operations.
12709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        for (String syncId : keys) {
12719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            InstancesList list = instancesMap.get(syncId);
12729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            for (ContentValues values : list) {
12739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
12749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // If this instance was cancelled then don't create a new
12759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // instance.
12769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Integer status = values.getAsInteger(Events.STATUS);
12779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (status != null && status == Events.STATUS_CANCELED) {
12789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    continue;
12799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
12809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
12819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Remove these fields before inserting a new instance
12829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                values.remove(Events.ORIGINAL_EVENT);
12839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                values.remove(Events.ORIGINAL_INSTANCE_TIME);
12849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                values.remove(Events.STATUS);
12859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1286c874ed5c6cc0fcc6ac06ae7d20db0eab7d749608Ken Shirriff                mDbHelper.instancesReplace(values);
12879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
12889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
12899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
12909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
12919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
12929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Computes the timezone-dependent fields of an instance of an event and
12939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * updates the "values" map to contain those fields.
12949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
12959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param begin the start time of the instance (in UTC milliseconds)
12969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param end the end time of the instance (in UTC milliseconds)
12979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param local a Time object with the timezone set to the local timezone
12989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param values a map that will contain the timezone-dependent fields
12999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
13009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void computeTimezoneDependentFields(long begin, long end,
13019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Time local, ContentValues values) {
13029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        local.set(begin);
13039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int startDay = Time.getJulianDay(begin, local.gmtoff);
13049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int startMinute = local.hour * 60 + local.minute;
13059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
13069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        local.set(end);
13079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int endDay = Time.getJulianDay(end, local.gmtoff);
13089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int endMinute = local.hour * 60 + local.minute;
13099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
13109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Special case for midnight, which has endMinute == 0.  Change
13119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // that to +24 hours on the previous day to make everything simpler.
13129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Exception: if start and end minute are both 0 on the same day,
13139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // then leave endMinute alone.
13149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (endMinute == 0 && endDay > startDay) {
13159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            endMinute = 24 * 60;
13169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            endDay -= 1;
13179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
13189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
13199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        values.put(Instances.START_DAY, startDay);
13209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        values.put(Instances.END_DAY, endDay);
13219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        values.put(Instances.START_MINUTE, startMinute);
13229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        values.put(Instances.END_MINUTE, endMinute);
13239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
13249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
13259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    @Override
13269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    public String getType(Uri url) {
13279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int match = sUriMatcher.match(url);
13289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        switch (match) {
13299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case EVENTS:
13309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return "vnd.android.cursor.dir/event";
13319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case EVENTS_ID:
13329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return "vnd.android.cursor.item/event";
13339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case REMINDERS:
13349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return "vnd.android.cursor.dir/reminder";
13359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case REMINDERS_ID:
13369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return "vnd.android.cursor.item/reminder";
13379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDAR_ALERTS:
13389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return "vnd.android.cursor.dir/calendar-alert";
13399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDAR_ALERTS_BY_INSTANCE:
13409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return "vnd.android.cursor.dir/calendar-alert-by-instance";
13419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDAR_ALERTS_ID:
13429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return "vnd.android.cursor.item/calendar-alert";
13439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case INSTANCES:
13449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case INSTANCES_BY_DAY:
13456db535b458146a279bebd4a51d56c1bdfc204528Erik            case EVENT_DAYS:
13469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return "vnd.android.cursor.dir/event-instance";
134748587d3291c4db7f0942e1bff55b88cfa7764ba0Erik            case TIME:
134848587d3291c4db7f0942e1bff55b88cfa7764ba0Erik                return "time/epoch";
13499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            default:
13509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                throw new IllegalArgumentException("Unknown URL " + url);
13519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
13529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
13539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
13549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    public static boolean isRecurrenceEvent(ContentValues values) {
13559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        return (!TextUtils.isEmpty(values.getAsString(Events.RRULE))||
13569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                !TextUtils.isEmpty(values.getAsString(Events.RDATE))||
13579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                !TextUtils.isEmpty(values.getAsString(Events.ORIGINAL_EVENT)));
13589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
13599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
13609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    @Override
13619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    protected Uri insertInTransaction(Uri uri, ContentValues values) {
1362ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        if (Log.isLoggable(TAG, Log.VERBOSE)) {
13639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.v(TAG, "insertInTransaction: " + uri);
13649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
13659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
13669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final boolean callerIsSyncAdapter =
13679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                readBooleanQueryParameter(uri, Calendar.CALLER_IS_SYNCADAPTER, false);
13689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
13699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final int match = sUriMatcher.match(uri);
13709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        long id = 0;
13719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
13729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        switch (match) {
13739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff              case SYNCSTATE:
13749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                id = mDbHelper.getSyncState().insert(mDb, values);
13759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
13769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case EVENTS:
13777e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (!callerIsSyncAdapter) {
13787e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    values.put(Events._SYNC_DIRTY, 1);
13797e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
13809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (!values.containsKey(Events.DTSTART)) {
13819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    throw new RuntimeException("DTSTART field missing from event");
13829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
13839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // TODO: avoid the call to updateBundleFromEvent if this is just finding local
13847e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                // changes.
13859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // TODO: do we really need to make a copy?
13869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                ContentValues updatedValues = updateContentValuesFromEvent(values);
13879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (updatedValues == null) {
13889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    throw new RuntimeException("Could not insert event.");
13899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // return null;
13909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
13919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String owner = null;
13929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (updatedValues.containsKey(Events.CALENDAR_ID) &&
13939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        !updatedValues.containsKey(Events.ORGANIZER)) {
13949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    owner = getOwner(updatedValues.getAsLong(Events.CALENDAR_ID));
13959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // TODO: This isn't entirely correct.  If a guest is adding a recurrence
13969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // exception to an event, the organizer should stay the original organizer.
13979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // This value doesn't go to the server and it will get fixed on sync,
13989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // so it shouldn't really matter.
13999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if (owner != null) {
14009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        updatedValues.put(Events.ORGANIZER, owner);
14019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
14029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
14039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
14049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                id = mDbHelper.eventsInsert(updatedValues);
14059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (id != -1) {
14069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    updateEventRawTimesLocked(id, updatedValues);
14079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    updateInstancesLocked(updatedValues, id, true /* new event */, mDb);
14089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
14099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // If we inserted a new event that specified the self-attendee
14109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // status, then we need to add an entry to the attendees table.
14119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if (values.containsKey(Events.SELF_ATTENDEE_STATUS)) {
14129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        int status = values.getAsInteger(Events.SELF_ATTENDEE_STATUS);
14139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        if (owner == null) {
14149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            owner = getOwner(updatedValues.getAsLong(Events.CALENDAR_ID));
14159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        }
14169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        createAttendeeEntry(id, status, owner);
14179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
14189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    triggerAppWidgetUpdate(id);
14199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
14209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
14219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDARS:
14229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Integer syncEvents = values.getAsInteger(Calendars.SYNC_EVENTS);
14239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (syncEvents != null && syncEvents == 1) {
14249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    String accountName = values.getAsString(Calendars._SYNC_ACCOUNT);
14259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    String accountType = values.getAsString(
14269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            Calendars._SYNC_ACCOUNT_TYPE);
14279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    final Account account = new Account(accountName, accountType);
14289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    String calendarUrl = values.getAsString(Calendars.URL);
14299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    mDbHelper.scheduleSync(account, false /* two-way sync */, calendarUrl);
14309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
14319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                id = mDbHelper.calendarsInsert(values);
14329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
14339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case ATTENDEES:
14349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (!values.containsKey(Attendees.EVENT_ID)) {
14359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    throw new IllegalArgumentException("Attendees values must "
14369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            + "contain an event_id");
14379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
14389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                id = mDbHelper.attendeesInsert(values);
14397e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (!callerIsSyncAdapter) {
14407e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    setEventDirty(values.getAsInteger(Attendees.EVENT_ID));
14417e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
14429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
14439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Copy the attendee status value to the Events table.
14449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                updateEventAttendeeStatus(mDb, values);
14459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
14469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case REMINDERS:
14479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (!values.containsKey(Reminders.EVENT_ID)) {
14489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    throw new IllegalArgumentException("Reminders values must "
14499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            + "contain an event_id");
14509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
14519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                id = mDbHelper.remindersInsert(values);
14527e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (!callerIsSyncAdapter) {
14537e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    setEventDirty(values.getAsInteger(Reminders.EVENT_ID));
14547e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
14559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
14569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Schedule another event alarm, if necessary
14579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (Log.isLoggable(TAG, Log.DEBUG)) {
14589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    Log.d(TAG, "insertInternal() changing reminder");
14599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
14609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                scheduleNextAlarm(false /* do not remove alarms */);
14619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
14629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDAR_ALERTS:
14639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (!values.containsKey(CalendarAlerts.EVENT_ID)) {
14649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    throw new IllegalArgumentException("CalendarAlerts values must "
14659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            + "contain an event_id");
14669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
14679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                id = mDbHelper.calendarAlertsInsert(values);
14682fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                // Note: dirty bit is not set for Alerts because it is not synced.
14692fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                // It is generated from Reminders, which is synced.
14709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
14719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case EXTENDED_PROPERTIES:
14729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (!values.containsKey(Calendar.ExtendedProperties.EVENT_ID)) {
14739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    throw new IllegalArgumentException("ExtendedProperties values must "
14749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            + "contain an event_id");
14759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
14769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                id = mDbHelper.extendedPropertiesInsert(values);
14777e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (!callerIsSyncAdapter) {
14787e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    setEventDirty(values.getAsInteger(Calendar.ExtendedProperties.EVENT_ID));
14797e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
14809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                break;
14819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case DELETED_EVENTS:
14829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case EVENTS_ID:
14839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case REMINDERS_ID:
14849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDAR_ALERTS_ID:
14859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case EXTENDED_PROPERTIES_ID:
14869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case INSTANCES:
14879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case INSTANCES_BY_DAY:
14886db535b458146a279bebd4a51d56c1bdfc204528Erik            case EVENT_DAYS:
14897e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                throw new UnsupportedOperationException("Cannot insert into that URL: " + uri);
14909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            default:
14919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                throw new IllegalArgumentException("Unknown URL " + uri);
14929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
14939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
14949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (id < 0) {
14959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return null;
14969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
14979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
14989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        return ContentUris.withAppendedId(uri, id);
14999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
15009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
15017e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    private void setEventDirty(int eventId) {
1502636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff        mDb.execSQL("UPDATE Events SET _sync_dirty=1 where _id=?", new Integer[] {eventId});
15037e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    }
15047e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff
15059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
15069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Gets the calendar's owner for an event.
15079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param calId
15089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @return email of owner or null
15099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
15109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private String getOwner(long calId) {
1511f09652d7327e45711f0e5b210e4df9c4c4c78ac4Fabrice Di Meglio        if (calId < 0) {
1512f09652d7327e45711f0e5b210e4df9c4c4c78ac4Fabrice Di Meglio            Log.e(TAG, "Calendar Id is not valid: " + calId);
1513f09652d7327e45711f0e5b210e4df9c4c4c78ac4Fabrice Di Meglio            return null;
1514f09652d7327e45711f0e5b210e4df9c4c4c78ac4Fabrice Di Meglio        }
15159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Get the email address of this user from this Calendar
15169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        String emailAddress = null;
15179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Cursor cursor = null;
15189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        try {
15199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            cursor = query(ContentUris.withAppendedId(Calendars.CONTENT_URI, calId),
15209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    new String[] { Calendars.OWNER_ACCOUNT },
15219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    null /* selection */,
15229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    null /* selectionArgs */,
15239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    null /* sort */);
15249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (cursor == null || !cursor.moveToFirst()) {
15259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Log.d(TAG, "Couldn't find " + calId + " in Calendars table");
15269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return null;
15279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
15289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            emailAddress = cursor.getString(0);
15299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } finally {
15309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (cursor != null) {
15319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                cursor.close();
15329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
15339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
15349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        return emailAddress;
15359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
15369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
15379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
15389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Creates an entry in the Attendees table that refers to the given event
15399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * and that has the given response status.
15409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
15419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param eventId the event id that the new entry in the Attendees table
15429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * should refer to
15439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param status the response status
15449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param emailAddress the email of the attendee
15459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
15469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void createAttendeeEntry(long eventId, int status, String emailAddress) {
15479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        ContentValues values = new ContentValues();
15489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        values.put(Attendees.EVENT_ID, eventId);
15499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        values.put(Attendees.ATTENDEE_STATUS, status);
15509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_NONE);
15519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // TODO: The relationship could actually be ORGANIZER, but it will get straightened out
15529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // on sync.
15539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        values.put(Attendees.ATTENDEE_RELATIONSHIP,
15549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Attendees.RELATIONSHIP_ATTENDEE);
15559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        values.put(Attendees.ATTENDEE_EMAIL, emailAddress);
15569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
15579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // We don't know the ATTENDEE_NAME but that will be filled in by the
15589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // server and sent back to us.
15599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        mDbHelper.attendeesInsert(values);
15609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
15619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
15629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
15639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Updates the attendee status in the Events table to be consistent with
15649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * the value in the Attendees table.
15659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
15669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param db the database
15679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param attendeeValues the column values for one row in the Attendees
15689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * table.
15699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
15709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void updateEventAttendeeStatus(SQLiteDatabase db, ContentValues attendeeValues) {
15719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Get the event id for this attendee
15729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        long eventId = attendeeValues.getAsLong(Attendees.EVENT_ID);
15739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
15749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (MULTIPLE_ATTENDEES_PER_EVENT) {
15759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Get the calendar id for this event
15769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Cursor cursor = null;
15779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            long calId;
15789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            try {
15799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                cursor = query(ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
15809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        new String[] { Events.CALENDAR_ID },
15819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        null /* selection */,
15829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        null /* selectionArgs */,
15839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        null /* sort */);
15849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (cursor == null || !cursor.moveToFirst()) {
15859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    Log.d(TAG, "Couldn't find " + eventId + " in Events table");
15869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    return;
15879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
15889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                calId = cursor.getLong(0);
15899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            } finally {
15909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (cursor != null) {
15919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    cursor.close();
15929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
15939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
15949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
15959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Get the owner email for this Calendar
15969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String calendarEmail = null;
15979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            cursor = null;
15989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            try {
15999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                cursor = query(ContentUris.withAppendedId(Calendars.CONTENT_URI, calId),
16009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        new String[] { Calendars.OWNER_ACCOUNT },
16019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        null /* selection */,
16029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        null /* selectionArgs */,
16039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        null /* sort */);
16049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (cursor == null || !cursor.moveToFirst()) {
16059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    Log.d(TAG, "Couldn't find " + calId + " in Calendars table");
16069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    return;
16079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
16089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                calendarEmail = cursor.getString(0);
16099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            } finally {
16109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (cursor != null) {
16119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    cursor.close();
16129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
16139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
16149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
16159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (calendarEmail == null) {
16169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return;
16179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
16189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
16199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Get the email address for this attendee
16209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String attendeeEmail = null;
16219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (attendeeValues.containsKey(Attendees.ATTENDEE_EMAIL)) {
16229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                attendeeEmail = attendeeValues.getAsString(Attendees.ATTENDEE_EMAIL);
16239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
16249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
16259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // If the attendee email does not match the calendar email, then this
16269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // attendee is not the owner of this calendar so we don't update the
16279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // selfAttendeeStatus in the event.
16289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (!calendarEmail.equals(attendeeEmail)) {
16299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return;
16309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
16319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
16329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
16339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int status = Attendees.ATTENDEE_STATUS_NONE;
16349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (attendeeValues.containsKey(Attendees.ATTENDEE_RELATIONSHIP)) {
16359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            int rel = attendeeValues.getAsInteger(Attendees.ATTENDEE_RELATIONSHIP);
16369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (rel == Attendees.RELATIONSHIP_ORGANIZER) {
16379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                status = Attendees.ATTENDEE_STATUS_ACCEPTED;
16389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
16399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
16409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
16419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (attendeeValues.containsKey(Attendees.ATTENDEE_STATUS)) {
16429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            status = attendeeValues.getAsInteger(Attendees.ATTENDEE_STATUS);
16439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
16449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
16459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        ContentValues values = new ContentValues();
16469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        values.put(Events.SELF_ATTENDEE_STATUS, status);
1647636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff        db.update("Events", values, "_id=?", new String[] {String.valueOf(eventId)});
16489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
16499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
16509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
16519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Updates the instances table when an event is added or updated.
16529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param values The new values of the event.
16539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param rowId The database row id of the event.
16549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param newEvent true if the event is new.
16559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param db The database
16569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
16579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void updateInstancesLocked(ContentValues values,
16589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            long rowId,
16599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            boolean newEvent,
16609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            SQLiteDatabase db) {
16619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
16629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // If there are no expanded Instances, then return.
16639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        MetaData.Fields fields = mMetaData.getFieldsLocked();
16649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (fields.maxInstance == 0) {
16659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return;
16669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
16679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
16689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Long dtstartMillis = values.getAsLong(Events.DTSTART);
16699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (dtstartMillis == null) {
16709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (newEvent) {
16719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // must be present for a new event.
16729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                throw new RuntimeException("DTSTART missing.");
16739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
16749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (Config.LOGV) Log.v(TAG, "Missing DTSTART.  "
16759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    + "No need to update instance.");
16769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return;
16779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
16789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
16799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Long lastDateMillis = values.getAsLong(Events.LAST_DATE);
16809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Long originalInstanceTime = values.getAsLong(Events.ORIGINAL_INSTANCE_TIME);
16819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
16829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (!newEvent) {
16839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Want to do this for regular event, recurrence, or exception.
16849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // For recurrence or exception, more deletion may happen below if we
16859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // do an instance expansion.  This deletion will suffice if the exception
16869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // is moved outside the window, for instance.
1687636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff            db.delete("Instances", "event_id=?", new String[] {String.valueOf(rowId)});
16889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
16899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
16909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (isRecurrenceEvent(values))  {
16919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // The recurrence or exception needs to be (re-)expanded if:
16929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // a) Exception or recurrence that falls inside window
16939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            boolean insideWindow = dtstartMillis <= fields.maxInstance &&
16949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    (lastDateMillis == null || lastDateMillis >= fields.minInstance);
16959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // b) Exception that affects instance inside window
16969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // These conditions match the query in getEntries
16979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            //  See getEntries comment for explanation of subtracting 1 week.
16989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            boolean affectsWindow = originalInstanceTime != null &&
16999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    originalInstanceTime <= fields.maxInstance &&
17009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    originalInstanceTime >= fields.minInstance - MAX_ASSUMED_DURATION;
17019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (insideWindow || affectsWindow) {
17029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                updateRecurrenceInstancesLocked(values, rowId, db);
17039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
17049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // TODO: an exception creation or update could be optimized by
17059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // updating just the affected instances, instead of regenerating
17069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // the recurrence.
17079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return;
17089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
17099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
17109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Long dtendMillis = values.getAsLong(Events.DTEND);
17119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (dtendMillis == null) {
17129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            dtendMillis = dtstartMillis;
17139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
17149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
17159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // if the event is in the expanded range, insert
17169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // into the instances table.
17179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // TODO: deal with durations.  currently, durations are only used in
17189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // recurrences.
17199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
17209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (dtstartMillis <= fields.maxInstance && dtendMillis >= fields.minInstance) {
17219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            ContentValues instanceValues = new ContentValues();
17229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            instanceValues.put(Instances.EVENT_ID, rowId);
17239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            instanceValues.put(Instances.BEGIN, dtstartMillis);
17249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            instanceValues.put(Instances.END, dtendMillis);
17259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
17269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            boolean allDay = false;
17279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Integer allDayInteger = values.getAsInteger(Events.ALL_DAY);
17289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (allDayInteger != null) {
17299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                allDay = allDayInteger != 0;
17309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
17319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
17329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Update the timezone-dependent fields.
17339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Time local = new Time();
17349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (allDay) {
17359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                local.timezone = Time.TIMEZONE_UTC;
17369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            } else {
17379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                local.timezone = fields.timezone;
17389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
17399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
17409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            computeTimezoneDependentFields(dtstartMillis, dtendMillis, local, instanceValues);
17419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            mDbHelper.instancesInsert(instanceValues);
17429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
17439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
17449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
17459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
17469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Determines the recurrence entries associated with a particular recurrence.
17479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * This set is the base recurrence and any exception.
17489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
17499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Normally the entries are indicated by the sync id of the base recurrence
17509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * (which is the originalEvent in the exceptions).
17519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * However, a complication is that a recurrence may not yet have a sync id.
17529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * In that case, the recurrence is specified by the rowId.
17539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
17549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param recurrenceSyncId The sync id of the base recurrence, or null.
17559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param rowId The row id of the base recurrence.
17569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @return the relevant entries.
17579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
17589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private Cursor getRelevantRecurrenceEntries(String recurrenceSyncId, long rowId) {
17599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
17609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
17611ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        qb.setTables(CalendarDatabaseHelper.Views.EVENTS);
17629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        qb.setProjectionMap(sEventsProjectionMap);
1763636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff        String selectionArgs[];
17649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (recurrenceSyncId == null) {
1765636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff            String where = "_id =?";
17669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            qb.appendWhere(where);
1767636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff            selectionArgs = new String[] {String.valueOf(rowId)};
17689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } else {
1769636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff            String where = "_sync_id = ? OR originalEvent = ?";
17709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            qb.appendWhere(where);
1771636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff            selectionArgs = new String[] {recurrenceSyncId, recurrenceSyncId};
17729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
17739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (Log.isLoggable(TAG, Log.VERBOSE)) {
17749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.v(TAG, "Retrieving events to expand: " + qb.toString());
17759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
17769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1777636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff        return qb.query(mDb, EXPAND_COLUMNS, null /* selection */, selectionArgs,
17787e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                null /* groupBy */, null /* having */, null /* sortOrder */);
17799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
17809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
17819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
17829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Do incremental Instances update of a recurrence or recurrence exception.
17839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
17849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * This method does performInstanceExpansion on just the modified recurrence,
17859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * to avoid the overhead of recomputing the entire instance table.
17869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
17879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param values The new values of the event.
17889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param rowId The database row id of the event.
17899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param db The database
17909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
17919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void updateRecurrenceInstancesLocked(ContentValues values,
17929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            long rowId,
17939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            SQLiteDatabase db) {
17949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        MetaData.Fields fields = mMetaData.getFieldsLocked();
17959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        String originalEvent = values.getAsString(Events.ORIGINAL_EVENT);
17969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        String recurrenceSyncId = null;
17979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (originalEvent != null) {
17989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            recurrenceSyncId = originalEvent;
17999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } else {
18009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Get the recurrence's sync id from the database
18019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            recurrenceSyncId = DatabaseUtils.stringForQuery(db, "SELECT _sync_id FROM Events"
1802636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                    + " WHERE _id=?", new String[] {String.valueOf(rowId)});
18039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
18049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // recurrenceSyncId is the _sync_id of the underlying recurrence
18059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // If the recurrence hasn't gone to the server, it will be null.
18069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
18079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Need to clear out old instances
18089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (recurrenceSyncId == null) {
18099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Creating updating a recurrence that hasn't gone to the server.
18109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Need to delete based on row id
18119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String where = "_id IN (SELECT Instances._id as _id"
18129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    + " FROM Instances INNER JOIN Events"
18139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    + " ON (Events._id = Instances.event_id)"
18149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    + " WHERE Events._id =?)";
18159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            db.delete("Instances", where, new String[]{"" + rowId});
18169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } else {
18179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Creating or modifying a recurrence or exception.
18189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Delete instances for recurrence (_sync_id = recurrenceSyncId)
18199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // and all exceptions (originalEvent = recurrenceSyncId)
18209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String where = "_id IN (SELECT Instances._id as _id"
18219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    + " FROM Instances INNER JOIN Events"
18229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    + " ON (Events._id = Instances.event_id)"
18239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    + " WHERE Events._sync_id =?"
18249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    + " OR Events.originalEvent =?)";
18259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            db.delete("Instances", where, new String[]{recurrenceSyncId, recurrenceSyncId});
18269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
18279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
18289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Now do instance expansion
18299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Cursor entries = getRelevantRecurrenceEntries(recurrenceSyncId, rowId);
18309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        try {
18319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            performInstanceExpansion(fields.minInstance, fields.maxInstance, fields.timezone,
18329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                     entries);
18339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } finally {
18349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (entries != null) {
18359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                entries.close();
18369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
18379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
18389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1839dbd797d59294d72d7ea9226d10128674b634aaadErik        // Clear busy bits (is this still needed?)
1840dbd797d59294d72d7ea9226d10128674b634aaadErik        mMetaData.writeLocked(fields.timezone, fields.minInstance, fields.maxInstance);
18419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
18429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
18439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    long calculateLastDate(ContentValues values)
18449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            throws DateException {
18459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Allow updates to some event fields like the title or hasAlarm
18469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // without requiring DTSTART.
18479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (!values.containsKey(Events.DTSTART)) {
18489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (values.containsKey(Events.DTEND) || values.containsKey(Events.RRULE)
18499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    || values.containsKey(Events.DURATION)
18509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    || values.containsKey(Events.EVENT_TIMEZONE)
18519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    || values.containsKey(Events.RDATE)
18529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    || values.containsKey(Events.EXRULE)
18539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    || values.containsKey(Events.EXDATE)) {
18549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                throw new RuntimeException("DTSTART field missing from event");
18559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
18569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return -1;
18579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
18589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        long dtstartMillis = values.getAsLong(Events.DTSTART);
18599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        long lastMillis = -1;
18609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
18619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Can we use dtend with a repeating event?  What does that even
18629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // mean?
18639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // NOTE: if the repeating event has a dtend, we convert it to a
18649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // duration during event processing, so this situation should not
18659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // occur.
18669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Long dtEnd = values.getAsLong(Events.DTEND);
18679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (dtEnd != null) {
18689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            lastMillis = dtEnd;
18699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } else {
18709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // find out how long it is
18719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Duration duration = new Duration();
18729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String durationStr = values.getAsString(Events.DURATION);
18739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (durationStr != null) {
18749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                duration.parse(durationStr);
18759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
18769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1877f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio            RecurrenceSet recur = null;
1878f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio            try {
1879f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio                recur = new RecurrenceSet(values);
1880f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio            } catch (EventRecurrence.InvalidFormatException e) {
1881f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio                Log.w(TAG, "Could not parse RRULE recurrence string: " +
1882f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio                        values.get(Calendar.Events.RRULE), e);
1883f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio                return lastMillis; // -1
1884f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio            }
18859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
1886f8de1a9391de5d8b6a6a0ae7c55e1a2c318d6c05Fabrice Di Meglio            if (null != recur && recur.hasRecurrence()) {
18879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // the event is repeating, so find the last date it
18889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // could appear on
18899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
18909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String tz = values.getAsString(Events.EVENT_TIMEZONE);
18919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
18929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (TextUtils.isEmpty(tz)) {
18939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // floating timezone
18949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    tz = Time.TIMEZONE_UTC;
18959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
18969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Time dtstartLocal = new Time(tz);
18979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
18989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                dtstartLocal.set(dtstartMillis);
18999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                RecurrenceProcessor rp = new RecurrenceProcessor();
19019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                lastMillis = rp.getLastOccurence(dtstartLocal, recur);
19029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (lastMillis == -1) {
19039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    return lastMillis;  // -1
19049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
19059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            } else {
19069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // the event is not repeating, just use dtstartMillis
19079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                lastMillis = dtstartMillis;
19089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
19099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // that was the beginning of the event.  this is the end.
19119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            lastMillis = duration.addTo(lastMillis);
19129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
19139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        return lastMillis;
19149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
19159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private ContentValues updateContentValuesFromEvent(ContentValues initialValues) {
19179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        try {
19189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            ContentValues values = new ContentValues(initialValues);
19199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            long last = calculateLastDate(values);
19219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (last != -1) {
19229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                values.put(Events.LAST_DATE, last);
19239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
19249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return values;
19269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } catch (DateException e) {
19279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // don't add it if there was an error
19289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.w(TAG, "Could not calculate last date.", e);
19299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return null;
19309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
19319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
19329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void updateEventRawTimesLocked(long eventId, ContentValues values) {
19349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        ContentValues rawValues = new ContentValues();
19359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        rawValues.put("event_id", eventId);
19379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        String timezone = values.getAsString(Events.EVENT_TIMEZONE);
19399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        boolean allDay = false;
19419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Integer allDayInteger = values.getAsInteger(Events.ALL_DAY);
19429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (allDayInteger != null) {
19439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            allDay = allDayInteger != 0;
19449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
19459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (allDay || TextUtils.isEmpty(timezone)) {
19479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // floating timezone
19489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            timezone = Time.TIMEZONE_UTC;
19499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
19509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Time time = new Time(timezone);
19529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        time.allDay = allDay;
19539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Long dtstartMillis = values.getAsLong(Events.DTSTART);
19549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (dtstartMillis != null) {
19559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            time.set(dtstartMillis);
19569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            rawValues.put("dtstart2445", time.format2445());
19579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
19589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Long dtendMillis = values.getAsLong(Events.DTEND);
19609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (dtendMillis != null) {
19619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            time.set(dtendMillis);
19629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            rawValues.put("dtend2445", time.format2445());
19639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
19649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Long originalInstanceMillis = values.getAsLong(Events.ORIGINAL_INSTANCE_TIME);
19669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (originalInstanceMillis != null) {
19679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // This is a recurrence exception so we need to get the all-day
19689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // status of the original recurring event in order to format the
19699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // date correctly.
19709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            allDayInteger = values.getAsInteger(Events.ORIGINAL_ALL_DAY);
19719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (allDayInteger != null) {
19729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                time.allDay = allDayInteger != 0;
19739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
19749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            time.set(originalInstanceMillis);
19759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            rawValues.put("originalInstanceTime2445", time.format2445());
19769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
19779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Long lastDateMillis = values.getAsLong(Events.LAST_DATE);
19799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (lastDateMillis != null) {
19809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            time.allDay = allDay;
19819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            time.set(lastDateMillis);
19829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            rawValues.put("lastDate2445", time.format2445());
19839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
19849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        mDbHelper.eventsRawTimesReplace(rawValues);
19869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
19879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
19889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    @Override
19899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    protected int deleteInTransaction(Uri uri, String selection, String[] selectionArgs) {
1990ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        if (Log.isLoggable(TAG, Log.VERBOSE)) {
19919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.v(TAG, "deleteInTransaction: " + uri);
19929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
19939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final boolean callerIsSyncAdapter =
19949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                readBooleanQueryParameter(uri, Calendar.CALLER_IS_SYNCADAPTER, false);
19959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final int match = sUriMatcher.match(uri);
19969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        switch (match) {
19979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case SYNCSTATE:
19989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return mDbHelper.getSyncState().delete(mDb, selection, selectionArgs);
19999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
20009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case SYNCSTATE_ID:
2001dc538177512191886cc40bc5e5125aae9bb197aaKen Shirriff                String selectionWithId = (BaseColumns._ID + "=?")
20029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        + (selection == null ? "" : " AND (" + selection + ")");
20039323bb1bbb247bac4871595a3de387ec7568897eKen Shirriff                // Prepend id to selectionArgs
2004dc538177512191886cc40bc5e5125aae9bb197aaKen Shirriff                selectionArgs = insertSelectionArg(selectionArgs,
2005dc538177512191886cc40bc5e5125aae9bb197aaKen Shirriff                        String.valueOf(ContentUris.parseId(uri)));
2006dc538177512191886cc40bc5e5125aae9bb197aaKen Shirriff                return mDbHelper.getSyncState().delete(mDb, selectionWithId,
2007dc538177512191886cc40bc5e5125aae9bb197aaKen Shirriff                        selectionArgs);
20089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
20091ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff            case EVENTS:
20109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            {
20117e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                int result = 0;
20121ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                selection = appendAccountToSelection(uri, selection);
20137e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff
20141ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                // Query this event to get the ids to delete.
20151ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                Cursor cursor = mDb.query("Events", ID_ONLY_PROJECTION,
20161ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                        selection, selectionArgs, null /* groupBy */,
20177e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                        null /* having */, null /* sortOrder */);
20189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                try {
20191ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                    while (cursor.moveToNext()) {
20201ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                        long id = cursor.getLong(0);
20211ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                        result += deleteEventInternal(id, callerIsSyncAdapter);
20229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
20239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                } finally {
20249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    cursor.close();
20259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    cursor = null;
20269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
20279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return result;
20289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
20291ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff            case EVENTS_ID:
20301ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff            {
20311ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                long id = ContentUris.parseId(uri);
20321ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                if (selection != null) {
20331ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                    throw new UnsupportedOperationException("CalendarProvider2 "
20341ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                            + "doesn't support selection based deletion for type "
20351ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                            + match);
20361ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                }
20371ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                return deleteEventInternal(id, callerIsSyncAdapter);
20381ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff            }
20399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case ATTENDEES:
20409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            {
20417e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (callerIsSyncAdapter) {
20427e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    return mDb.delete("Attendees", selection, selectionArgs);
20437e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                } else {
20447e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    return deleteFromTable("Attendees", uri, selection, selectionArgs);
20457e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
20469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
20479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case ATTENDEES_ID:
20489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            {
20492fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                if (selection != null) {
20502fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    throw new UnsupportedOperationException("Selection not permitted for " + uri);
20512fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                }
20527e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (callerIsSyncAdapter) {
20537e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    long id = ContentUris.parseId(uri);
2054636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                    return mDb.delete("Attendees", "_id=?", new String[] {String.valueOf(id)});
20557e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                } else {
20562fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    return deleteFromTable("Attendees", uri, null /* selection */,
20572fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                                           null /* selectionArgs */);
20587e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
20599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
20609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case REMINDERS:
20619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            {
20627e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (callerIsSyncAdapter) {
20637e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    return mDb.delete("Reminders", selection, selectionArgs);
20647e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                } else {
20657e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    return deleteFromTable("Reminders", uri, selection, selectionArgs);
20667e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
20679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
20689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case REMINDERS_ID:
20699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            {
20702fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                if (selection != null) {
20712fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    throw new UnsupportedOperationException("Selection not permitted for " + uri);
20722fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                }
20737e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (callerIsSyncAdapter) {
20747e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    long id = ContentUris.parseId(uri);
2075636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                    return mDb.delete("Reminders", "_id=?", new String[] {String.valueOf(id)});
20767e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                } else {
20772fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    return deleteFromTable("Reminders", uri, null /* selection */,
20782fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                                           null /* selectionArgs */);
20792fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                }
20802fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff            }
20812fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff            case EXTENDED_PROPERTIES:
20822fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff            {
20832fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                if (callerIsSyncAdapter) {
20842fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    return mDb.delete("ExtendedProperties", selection, selectionArgs);
20852fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                } else {
20862fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    return deleteFromTable("ExtendedProperties", uri, selection, selectionArgs);
20872fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                }
20882fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff            }
20892fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff            case EXTENDED_PROPERTIES_ID:
20902fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff            {
20912fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                if (selection != null) {
20922fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    throw new UnsupportedOperationException("Selection not permitted for " + uri);
20932fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                }
20942fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                if (callerIsSyncAdapter) {
20952fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    long id = ContentUris.parseId(uri);
2096636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                    return mDb.delete("ExtendedProperties", "_id=?",
2097636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                            new String[] {String.valueOf(id)});
20982fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                } else {
20992fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    return deleteFromTable("ExtendedProperties", uri, null /* selection */,
21002fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                                           null /* selectionArgs */);
21017e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
21029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
21039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDAR_ALERTS:
21049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            {
21057e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (callerIsSyncAdapter) {
21067e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    return mDb.delete("CalendarAlerts", selection, selectionArgs);
21077e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                } else {
21087e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    return deleteFromTable("CalendarAlerts", uri, selection, selectionArgs);
21097e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
21109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
21119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDAR_ALERTS_ID:
21129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            {
21132fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                if (selection != null) {
21142fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    throw new UnsupportedOperationException("Selection not permitted for " + uri);
21152fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                }
21162fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                // Note: dirty bit is not set for Alerts because it is not synced.
21172fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                // It is generated from Reminders, which is synced.
21189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                long id = ContentUris.parseId(uri);
2119636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                return mDb.delete("CalendarAlerts", "_id=?", new String[] {String.valueOf(id)});
21209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
21219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case DELETED_EVENTS:
21227e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                throw new UnsupportedOperationException("Cannot delete that URL: " + uri);
21239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDARS_ID:
21249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                StringBuilder selectionSb = new StringBuilder("_id=");
21259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                selectionSb.append(uri.getPathSegments().get(1));
21269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (!TextUtils.isEmpty(selection)) {
21279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    selectionSb.append(" AND (");
21289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    selectionSb.append(selection);
21299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    selectionSb.append(')');
21309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
21319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                selection = selectionSb.toString();
21329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // fall through to CALENDARS for the actual delete
21339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDARS:
2134595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff                selection = appendAccountToSelection(uri, selection);
21357e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                return deleteMatchingCalendars(selection); // TODO: handle in sync adapter
21369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case INSTANCES:
21379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case INSTANCES_BY_DAY:
21386db535b458146a279bebd4a51d56c1bdfc204528Erik            case EVENT_DAYS:
21399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                throw new UnsupportedOperationException("Cannot delete that URL");
21409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            default:
21419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                throw new IllegalArgumentException("Unknown URL " + uri);
21429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
21439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
21449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
21451ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff    private int deleteEventInternal(long id, boolean callerIsSyncAdapter) {
21461ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        int result = 0;
2147192b1807d4b6265a4f7581580bd6172dae3fc1b1Marc Blank        String selectionArgs[] = new String[] {String.valueOf(id)};
21481ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff
21491ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        // Query this event to get the fields needed for deleting.
21501ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        Cursor cursor = mDb.query("Events", EVENTS_PROJECTION,
2151192b1807d4b6265a4f7581580bd6172dae3fc1b1Marc Blank                "_id=?", selectionArgs,
2152636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                null /* groupBy */,
21531ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                null /* having */, null /* sortOrder */);
21541ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        try {
21551ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff            if (cursor.moveToNext()) {
21561ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                result = 1;
21571ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                String syncId = cursor.getString(EVENTS_SYNC_ID_INDEX);
21581ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                if (!TextUtils.isEmpty(syncId)) {
21591ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff
21601ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                    // TODO: we may also want to delete exception
21611ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                    // events for this event (in case this was a
21621ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                    // recurring event).  We can do that with the
21631ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                    // following code:
21641ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                    // mDb.delete("Events", "originalEvent=?", new String[] {syncId});
21651ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                }
21661ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff
21671ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                // If this was a recurring event or a recurrence
21681ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                // exception, then force a recalculation of the
21691ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                // instances.
21701ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                String rrule = cursor.getString(EVENTS_RRULE_INDEX);
21711ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                String rdate = cursor.getString(EVENTS_RDATE_INDEX);
21721ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                String origEvent = cursor.getString(EVENTS_ORIGINAL_EVENT_INDEX);
21731ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                if (!TextUtils.isEmpty(rrule) || !TextUtils.isEmpty(rdate)
21741ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                        || !TextUtils.isEmpty(origEvent)) {
21751ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                    mMetaData.clearInstanceRange();
21761ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                }
21771ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff
21781ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                if (callerIsSyncAdapter) {
2179192b1807d4b6265a4f7581580bd6172dae3fc1b1Marc Blank                    mDb.delete("Events", "_id=?", selectionArgs);
2180192b1807d4b6265a4f7581580bd6172dae3fc1b1Marc Blank                    mDb.delete("Attendees", "event_id=?", selectionArgs);
21811ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                } else {
21821ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                    ContentValues values = new ContentValues();
21831ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                    values.put(Events.DELETED, 1);
21841ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                    values.put(Events._SYNC_DIRTY, 1);
2185192b1807d4b6265a4f7581580bd6172dae3fc1b1Marc Blank                    mDb.update("Events", values, "_id=?", selectionArgs);
21861ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                }
21871ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff            }
21881ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        } finally {
21891ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff            cursor.close();
21901ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff            cursor = null;
21911ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        }
21928f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff
21938f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff        scheduleNextAlarm(false /* do not remove alarms */);
21941ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        triggerAppWidgetUpdate(-1);
21951ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff
2196192b1807d4b6265a4f7581580bd6172dae3fc1b1Marc Blank        // Delete associated data; attendees, however, are deleted with the actual event so
2197192b1807d4b6265a4f7581580bd6172dae3fc1b1Marc Blank        // that the sync adapter is able to notify attendees of the cancellation.
2198636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff        mDb.delete("Instances", "event_id=?", selectionArgs);
2199636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff        mDb.delete("EventsRawTimes", "event_id=?", selectionArgs);
2200636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff        mDb.delete("Reminders", "event_id=?", selectionArgs);
2201636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff        mDb.delete("CalendarAlerts", "event_id=?", selectionArgs);
2202636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff        mDb.delete("ExtendedProperties", "event_id=?", selectionArgs);
22031ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        return result;
22041ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff    }
22051ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff
22067e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    /**
22077e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * Delete rows from a table and mark corresponding events as dirty.
22087e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * @param table The table to delete from
22097e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * @param uri The URI specifying the rows
22107e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * @param selection for the query
22117e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * @param selectionArgs for the query
22127e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     */
22137e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    private int deleteFromTable(String table, Uri uri, String selection, String[] selectionArgs) {
22147e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        // Note that the query will return data according to the access restrictions,
22157e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        // so we don't need to worry about deleting data we don't have permission to read.
22167e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        Cursor c = query(uri, ID_PROJECTION, selection, selectionArgs, null);
22177e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        ContentValues values = new ContentValues();
22187e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        values.put(Events._SYNC_DIRTY, "1");
22197e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        int count = 0;
22207e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        try {
22217e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff            while(c.moveToNext()) {
22227e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                long id = c.getLong(ID_INDEX);
22237e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                long event_id = c.getLong(EVENT_ID_INDEX);
2224636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                mDb.delete(table, "_id=?", new String[] {String.valueOf(id)});
2225636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                mDb.update("Events", values, "_id=?", new String[] {String.valueOf(event_id)});
22267e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                count++;
22277e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff            }
22287e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        } finally {
22297e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff            c.close();
22307e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        }
22317e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        return count;
22327e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    }
22337e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff
22347e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    /**
22357e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * Update rows in a table and mark corresponding events as dirty.
22367e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * @param table The table to delete from
22377e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * @param values The values to update
22387e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * @param uri The URI specifying the rows
22397e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * @param selection for the query
22407e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * @param selectionArgs for the query
22417e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     */
22427e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    private int updateInTable(String table, ContentValues values, Uri uri, String selection,
22437e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff            String[] selectionArgs) {
22447e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        // Note that the query will return data according to the access restrictions,
22457e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        // so we don't need to worry about deleting data we don't have permission to read.
22467e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        Cursor c = query(uri, ID_PROJECTION, selection, selectionArgs, null);
22477e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        ContentValues dirtyValues = new ContentValues();
22487e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        dirtyValues.put(Events._SYNC_DIRTY, "1");
22497e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        int count = 0;
22507e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        try {
22517e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff            while(c.moveToNext()) {
22527e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                long id = c.getLong(ID_INDEX);
22537e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                long event_id = c.getLong(EVENT_ID_INDEX);
2254636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                mDb.update(table, values, "_id=?", new String[] {String.valueOf(id)});
2255636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                mDb.update("Events", dirtyValues, "_id=?", new String[] {String.valueOf(event_id)});
22567e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                count++;
22577e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff            }
22587e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        } finally {
22597e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff            c.close();
22607e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        }
22617e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        return count;
22627e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff    }
22637e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff
22649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private int deleteMatchingCalendars(String where) {
22659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // query to find all the calendars that match, for each
22669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // - delete calendar subscription
22679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // - delete calendar
22689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
22697e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        Cursor c = mDb.query("Calendars", sCalendarsIdProjection, where,
22707e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                null /* selectionArgs */, null /* groupBy */,
22717e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                null /* having */, null /* sortOrder */);
22729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (c == null) {
22739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return 0;
22749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
22759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        try {
22769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            while (c.moveToNext()) {
22779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                long id = c.getLong(CALENDARS_INDEX_ID);
22789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                modifyCalendarSubscription(id, false /* not selected */);
22799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
22809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } finally {
22819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            c.close();
22829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
22832cc859cab85391a240b9c3f28c935d919c8ceb8cKen Shirriff        return mDb.delete("Calendars", where, null /* whereArgs */);
22849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
22859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
22869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    // TODO: call calculateLastDate()!
22879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    @Override
22889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    protected int updateInTransaction(Uri uri, ContentValues values, String selection,
22899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String[] selectionArgs) {
2290ae270e35e14b5c7a756050cb8dcccf5771743850Fabrice Di Meglio        if (Log.isLoggable(TAG, Log.VERBOSE)) {
22919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.v(TAG, "updateInTransaction: " + uri);
22929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
22939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
22949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        int count = 0;
22959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
22969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final int match = sUriMatcher.match(uri);
22979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
22989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final boolean callerIsSyncAdapter =
22999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                readBooleanQueryParameter(uri, Calendar.CALLER_IS_SYNCADAPTER, false);
23009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
23019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // TODO: remove this restriction
23027e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        if (!TextUtils.isEmpty(selection) && match != CALENDAR_ALERTS && match != EVENTS) {
23039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            throw new IllegalArgumentException(
23049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    "WHERE based updates not supported");
23059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
23069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        switch (match) {
23079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case SYNCSTATE:
23089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return mDbHelper.getSyncState().update(mDb, values,
23099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        appendAccountToSelection(uri, selection), selectionArgs);
23109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
23119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case SYNCSTATE_ID: {
23129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                selection = appendAccountToSelection(uri, selection);
2313dc538177512191886cc40bc5e5125aae9bb197aaKen Shirriff                String selectionWithId = (BaseColumns._ID + "=?")
2314dc538177512191886cc40bc5e5125aae9bb197aaKen Shirriff                        + (selection == null ? "" : " AND (" + selection + ")");
23159323bb1bbb247bac4871595a3de387ec7568897eKen Shirriff                // Prepend id to selectionArgs
2316dc538177512191886cc40bc5e5125aae9bb197aaKen Shirriff                selectionArgs = insertSelectionArg(selectionArgs,
2317dc538177512191886cc40bc5e5125aae9bb197aaKen Shirriff                        String.valueOf(ContentUris.parseId(uri)));
2318dc538177512191886cc40bc5e5125aae9bb197aaKen Shirriff                return mDbHelper.getSyncState().update(mDb, values, selectionWithId, selectionArgs);
23199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
23209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
23219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case CALENDARS_ID:
23229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            {
23232fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                if (selection != null) {
23242fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    throw new UnsupportedOperationException("Selection not permitted for " + uri);
23252fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                }
23269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                long id = ContentUris.parseId(uri);
23279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Integer syncEvents = values.getAsInteger(Calendars.SYNC_EVENTS);
23289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (syncEvents != null) {
23299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    modifyCalendarSubscription(id, syncEvents == 1);
23309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
23319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2332636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                int result = mDb.update("Calendars", values, "_id=?",
2333636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                        new String[] {String.valueOf(id)});
23349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
23359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return result;
23369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
23377e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff            case EVENTS:
23389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            case EVENTS_ID:
23399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            {
23407e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                long id = 0;
23417e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (match == EVENTS_ID) {
23427e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    id = ContentUris.parseId(uri);
2343a7f687007ff4d0c30726bf86f717fde88f51b453Ken Shirriff                } else if (callerIsSyncAdapter) {
2344a7f687007ff4d0c30726bf86f717fde88f51b453Ken Shirriff                    if (selection != null && selection.startsWith("_id=")) {
23457e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                        // The ContentProviderOperation generates an _id=n string instead of
23467e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                        // adding the id to the URL, so parse that out here.
23477e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                        id = Long.parseLong(selection.substring(4));
2348a7f687007ff4d0c30726bf86f717fde88f51b453Ken Shirriff                    } else {
2349a7f687007ff4d0c30726bf86f717fde88f51b453Ken Shirriff                        // Sync adapter Events operation affects just Events table, not associated
2350a7f687007ff4d0c30726bf86f717fde88f51b453Ken Shirriff                        // tables.
2351a7f687007ff4d0c30726bf86f717fde88f51b453Ken Shirriff                        return mDb.update("Events", values, selection, selectionArgs);
2352a7f687007ff4d0c30726bf86f717fde88f51b453Ken Shirriff                    }
23537e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                } else {
2354a7f687007ff4d0c30726bf86f717fde88f51b453Ken Shirriff                    throw new IllegalArgumentException("Unknown URL " + uri);
23557e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
23567e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (!callerIsSyncAdapter) {
23577e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    values.put(Events._SYNC_DIRTY, 1);
23587e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
23599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Disallow updating the attendee status in the Events
23609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // table.  In the future, we could support this but we
23619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // would have to query and update the attendees table
23629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // to keep the values consistent.
23639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (values.containsKey(Events.SELF_ATTENDEE_STATUS)) {
23649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    throw new IllegalArgumentException("Updating "
23659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            + Events.SELF_ATTENDEE_STATUS
23669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            + " in Events table is not allowed.");
23679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
23689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
23697e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                // TODO: should we allow this?
23707e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (values.containsKey(Events.HTML_URI) && !callerIsSyncAdapter) {
23719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    throw new IllegalArgumentException("Updating "
23729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            + Events.HTML_URI
23739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            + " in Events table is not allowed.");
23749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
23759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
23769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                ContentValues updatedValues = updateContentValuesFromEvent(values);
23779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (updatedValues == null) {
23789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    Log.w(TAG, "Could not update event.");
23799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    return 0;
23809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
23819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2382636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                int result = mDb.update("Events", updatedValues, "_id=?",
2383636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                        new String[] {String.valueOf(id)});
23849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (result > 0) {
23859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    updateEventRawTimesLocked(id, updatedValues);
23869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    updateInstancesLocked(updatedValues, id, false /* not a new event */, mDb);
23879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
23889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if (values.containsKey(Events.DTSTART)) {
23899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        // The start time of the event changed, so run the
23909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        // event alarm scheduler.
23919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        if (Log.isLoggable(TAG, Log.DEBUG)) {
23929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            Log.d(TAG, "updateInternal() changing event");
23939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        }
23949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        scheduleNextAlarm(false /* do not remove alarms */);
23959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        triggerAppWidgetUpdate(id);
23969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
23979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
23989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return result;
23999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
24002fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff            case ATTENDEES_ID: {
24012fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                if (selection != null) {
24022fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    throw new UnsupportedOperationException("Selection not permitted for " + uri);
24032fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                }
24049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Copy the attendee status value to the Events table.
24059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                updateEventAttendeeStatus(mDb, values);
24069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
24077e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (callerIsSyncAdapter) {
24087e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    long id = ContentUris.parseId(uri);
2409636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                    return mDb.update("Attendees", values, "_id=?",
241083512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff                            new String[] {String.valueOf(id)});
24117e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                } else {
24122fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    return updateInTable("Attendees", values, uri, null /* selection */,
24132fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                            null /* selectionArgs */);
24147e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
24159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
24162fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff            case CALENDAR_ALERTS_ID: {
24172fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                if (selection != null) {
24182fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    throw new UnsupportedOperationException("Selection not permitted for " + uri);
24192fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                }
24202fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                // Note: dirty bit is not set for Alerts because it is not synced.
24212fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                // It is generated from Reminders, which is synced.
24229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                long id = ContentUris.parseId(uri);
2423636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                return mDb.update("CalendarAlerts", values, "_id=?",
2424636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                        new String[] {String.valueOf(id)});
24259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
24262fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff            case CALENDAR_ALERTS: {
24272fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                // Note: dirty bit is not set for Alerts because it is not synced.
24282fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                // It is generated from Reminders, which is synced.
24299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                return mDb.update("CalendarAlerts", values, selection, selectionArgs);
24309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
24312fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff            case REMINDERS_ID: {
24322fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                if (selection != null) {
24332fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    throw new UnsupportedOperationException("Selection not permitted for " + uri);
24342fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                }
24357e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (callerIsSyncAdapter) {
24367e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    long id = ContentUris.parseId(uri);
2437636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                    count = mDb.update("Reminders", values, "_id=?",
243883512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff                            new String[] {String.valueOf(id)});
24397e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                } else {
24402fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    count = updateInTable("Reminders", values, uri, null /* selection */,
24412fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                            null /* selectionArgs */);
24427e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
24437e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff
24449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Reschedule the event alarms because the
24459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // "minutes" field may have changed.
24469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (Log.isLoggable(TAG, Log.DEBUG)) {
24479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    Log.d(TAG, "updateInternal() changing reminder");
24489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
24499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                scheduleNextAlarm(false /* do not remove alarms */);
24507e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                return count;
24519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
24522fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff            case EXTENDED_PROPERTIES_ID: {
24532fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                if (selection != null) {
24542fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    throw new UnsupportedOperationException("Selection not permitted for " + uri);
24552fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                }
24567e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                if (callerIsSyncAdapter) {
24577e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                    long id = ContentUris.parseId(uri);
2458636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                    return mDb.update("ExtendedProperties", values, "_id=?",
2459636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff                            new String[] {String.valueOf(id)});
24607e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                } else {
24612fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                    return updateInTable("ExtendedProperties", values, uri, null /* selection */,
24622fb3bc8f9ded55c0e379e1eaed2e036a5670b63aKen Shirriff                            null /* selectionArgs */);
24637e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff                }
24649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
246583512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff            // TODO: replace the SCHEDULE_ALARM private URIs with a
246683512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff            // service
246783512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff            case SCHEDULE_ALARM: {
246883512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff                scheduleNextAlarm(false);
246983512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff                return 0;
247083512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff            }
247183512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff            case SCHEDULE_ALARM_REMOVE: {
247283512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff                scheduleNextAlarm(true);
247383512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff                return 0;
247483512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff            }
24759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
24769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            default:
24779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                throw new IllegalArgumentException("Unknown URL " + uri);
24789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
24799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
24809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2481595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff    private void appendAccountFromParameter(SQLiteQueryBuilder qb, Uri uri) {
2482595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        final String accountName = getQueryParameter(uri, Calendar.EventsEntity.ACCOUNT_NAME);
2483595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        final String accountType = getQueryParameter(uri, Calendar.EventsEntity.ACCOUNT_TYPE);
2484595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        if (!TextUtils.isEmpty(accountName)) {
2485595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            qb.appendWhere(Calendar.Calendars._SYNC_ACCOUNT + "="
2486595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff                    + DatabaseUtils.sqlEscapeString(accountName) + " AND "
2487595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff                    + Calendar.Calendars._SYNC_ACCOUNT_TYPE + "="
2488595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff                    + DatabaseUtils.sqlEscapeString(accountType));
2489595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        } else {
2490595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            qb.appendWhere("1"); // I.e. always true
2491595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        }
2492595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff    }
2493595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff
24949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private String appendAccountToSelection(Uri uri, String selection) {
2495595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        final String accountName = getQueryParameter(uri, Calendar.EventsEntity.ACCOUNT_NAME);
2496595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        final String accountType = getQueryParameter(uri, Calendar.EventsEntity.ACCOUNT_TYPE);
24979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (!TextUtils.isEmpty(accountName)) {
24989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            StringBuilder selectionSb = new StringBuilder(Calendar.Calendars._SYNC_ACCOUNT + "="
24999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    + DatabaseUtils.sqlEscapeString(accountName) + " AND "
25009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    + Calendar.Calendars._SYNC_ACCOUNT_TYPE + "="
25019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    + DatabaseUtils.sqlEscapeString(accountType));
25029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (!TextUtils.isEmpty(selection)) {
25039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                selectionSb.append(" AND (");
25049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                selectionSb.append(selection);
25059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                selectionSb.append(')');
25069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
25079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return selectionSb.toString();
25089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } else {
25099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return selection;
25109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
25119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
25129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
25139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void modifyCalendarSubscription(long id, boolean syncEvents) {
25149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // get the account, url, and current selected state
25159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // for this calendar.
25169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Cursor cursor = query(ContentUris.withAppendedId(Calendars.CONTENT_URI, id),
25179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                new String[] {Calendars._SYNC_ACCOUNT, Calendars._SYNC_ACCOUNT_TYPE,
25189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        Calendars.URL, Calendars.SYNC_EVENTS},
25199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                null /* selection */,
25209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                null /* selectionArgs */,
25219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                null /* sort */);
25229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
25239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Account account = null;
25249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        String calendarUrl = null;
25259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        boolean oldSyncEvents = false;
25269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (cursor != null && cursor.moveToFirst()) {
25279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            try {
25289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                final String accountName = cursor.getString(0);
25299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                final String accountType = cursor.getString(1);
25309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                account = new Account(accountName, accountType);
25319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                calendarUrl = cursor.getString(2);
25329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                oldSyncEvents = (cursor.getInt(3) != 0);
25339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            } finally {
25349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                cursor.close();
25359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
25369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
25379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
25389535627bf6295cd94447beb83e1aac41f50c3600Erik        if (account == null) {
25399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // should not happen?
25409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.w(TAG, "Cannot update subscription because account "
25419535627bf6295cd94447beb83e1aac41f50c3600Erik                    + "is empty -- should not happen.");
25429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return;
25439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
25449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
25459535627bf6295cd94447beb83e1aac41f50c3600Erik        if (TextUtils.isEmpty(calendarUrl)) {
25469535627bf6295cd94447beb83e1aac41f50c3600Erik            // Passing in a null Url will cause it to not add any extras
25479535627bf6295cd94447beb83e1aac41f50c3600Erik            // Should only happen for non-google calendars.
25489535627bf6295cd94447beb83e1aac41f50c3600Erik            calendarUrl = null;
25499535627bf6295cd94447beb83e1aac41f50c3600Erik        }
25509535627bf6295cd94447beb83e1aac41f50c3600Erik
25519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (oldSyncEvents == syncEvents) {
25529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // nothing to do
25539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return;
25549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
25559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
25569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // If the calendar is not selected for syncing, then don't download
25579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // events.
25589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        mDbHelper.scheduleSync(account, !syncEvents, calendarUrl);
25599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
25609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
25619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    // TODO: is this needed
25629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff//    @Override
25639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff//    public void onSyncStop(SyncContext context, boolean success) {
25649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff//        super.onSyncStop(context, success);
25659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff//        if (Log.isLoggable(TAG, Log.DEBUG)) {
25669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff//            Log.d(TAG, "onSyncStop() success: " + success);
25679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff//        }
25689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff//        scheduleNextAlarm(false /* do not remove alarms */);
25699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff//        triggerAppWidgetUpdate(-1);
25709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff//    }
25719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
25729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
25739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Update any existing widgets with the changed events.
25749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
25759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param changedEventId Specific event known to be changed, otherwise -1.
25769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *            If present, we use it to decide if an update is necessary.
25779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
25789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private synchronized void triggerAppWidgetUpdate(long changedEventId) {
25799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Context context = getContext();
25809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (context != null) {
25819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            mAppWidgetProvider.providerUpdated(context, changedEventId);
25829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
25839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
25849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
25859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /* Retrieve and cache the alarm manager */
25869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private AlarmManager getAlarmManager() {
25879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        synchronized(mAlarmLock) {
25889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (mAlarmManager == null) {
25899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Context context = getContext();
25909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (context == null) {
25919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    Log.e(TAG, "getAlarmManager() cannot get Context");
25929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    return null;
25939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
25949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Object service = context.getSystemService(Context.ALARM_SERVICE);
25959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                mAlarmManager = (AlarmManager) service;
25969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
25979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return mAlarmManager;
25989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
25999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
26009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
26019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    void scheduleNextAlarmCheck(long triggerTime) {
26029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        AlarmManager manager = getAlarmManager();
26039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (manager == null) {
26049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.e(TAG, "scheduleNextAlarmCheck() cannot get AlarmManager");
26059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return;
26069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
26079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Context context = getContext();
26089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Intent intent = new Intent(CalendarReceiver.SCHEDULE);
26099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        intent.setClass(context, CalendarReceiver.class);
26109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        PendingIntent pending = PendingIntent.getBroadcast(context,
26119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                0, intent, PendingIntent.FLAG_NO_CREATE);
26129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (pending != null) {
26139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            // Cancel any previous alarms that do the same thing.
26149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            manager.cancel(pending);
26159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
26169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        pending = PendingIntent.getBroadcast(context,
26179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
26189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
26199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (Log.isLoggable(TAG, Log.DEBUG)) {
26209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Time time = new Time();
26219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            time.set(triggerTime);
26229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String timeStr = time.format(" %a, %b %d, %Y %I:%M%P");
26239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.d(TAG, "scheduleNextAlarmCheck at: " + triggerTime + timeStr);
26249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
26259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
26269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        manager.set(AlarmManager.RTC_WAKEUP, triggerTime, pending);
26279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
26289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
26299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /*
26309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * This method runs the alarm scheduler in a background thread.
26319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
26329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    void scheduleNextAlarm(boolean removeAlarms) {
26339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Thread thread = new AlarmScheduler(removeAlarms);
26349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        thread.start();
26359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
26369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
26379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
26389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * This method runs in a background thread and schedules an alarm for
26399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * the next calendar event, if necessary.
26409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
26419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void runScheduleNextAlarm(boolean removeAlarms) {
26429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final SQLiteDatabase db = mDbHelper.getWritableDatabase();
26439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        db.beginTransaction();
26449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        try {
26459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (removeAlarms) {
26469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                removeScheduledAlarmsLocked(db);
26479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
26489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            scheduleNextAlarmLocked(db);
26499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            db.setTransactionSuccessful();
26509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } finally {
26519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            db.endTransaction();
26529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
26539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
26549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
26559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
26569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * This method looks at the 24-hour window from now for any events that it
26579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * needs to schedule.  This method runs within a database transaction. It
26589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * also runs in a background thread.
26599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
26609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * The CalendarProvider2 keeps track of which alarms it has already scheduled
26619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * to avoid scheduling them more than once and for debugging problems with
26629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * alarms.  It stores this knowledge in a database table called CalendarAlerts
26639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * which persists across reboots.  But the actual alarm list is in memory
26649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * and disappears if the phone loses power.  To avoid missing an alarm, we
26659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * clear the entries in the CalendarAlerts table when we start up the
26669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * CalendarProvider2.
26679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
26689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Scheduling an alarm multiple times is not tragic -- we filter out the
26699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * extra ones when we receive them. But we still need to keep track of the
26709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * scheduled alarms. The main reason is that we need to prevent multiple
26719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * notifications for the same alarm (on the receive side) in case we
26729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * accidentally schedule the same alarm multiple times.  We don't have
26739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * visibility into the system's alarm list so we can never know for sure if
26749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * we have already scheduled an alarm and it's better to err on scheduling
26759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * an alarm twice rather than missing an alarm.  Another reason we keep
26769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * track of scheduled alarms in a database table is that it makes it easy to
26779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * run an SQL query to find the next reminder that we haven't scheduled.
26789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
26799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * @param db the database
26809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
26819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void scheduleNextAlarmLocked(SQLiteDatabase db) {
26829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        AlarmManager alarmManager = getAlarmManager();
26839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (alarmManager == null) {
26849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.e(TAG, "Failed to find the AlarmManager. Could not schedule the next alarm!");
26859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            return;
26869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
26879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
26889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final long currentMillis = System.currentTimeMillis();
26899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final long start = currentMillis - SCHEDULE_ALARM_SLACK;
26909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        final long end = start + (24 * 60 * 60 * 1000);
26919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        ContentResolver cr = getContext().getContentResolver();
26929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (Log.isLoggable(TAG, Log.DEBUG)) {
26939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Time time = new Time();
26949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            time.set(start);
26959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            String startTimeStr = time.format(" %a, %b %d, %Y %I:%M%P");
26969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.d(TAG, "runScheduleNextAlarm() start search: " + startTimeStr);
26979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
26989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
26998f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff        // Delete rows in CalendarAlert where the corresponding Instance or
27008f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff        // Reminder no longer exist.
27018f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff        // Also clear old alarms but keep alarms around for a while to prevent
27029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // multiple alerts for the same reminder.  The "clearUpToTime'
27039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // should be further in the past than the point in time where
27049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // we start searching for events (the "start" variable defined above).
27058f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff        String selectArg[] = new String[] {
27068f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff            Long.toString(currentMillis - CLEAR_OLD_ALARM_THRESHOLD)
27078f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff        };
27088f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff
27098f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff        int rowsDeleted =
27108f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff            db.delete(CalendarAlerts.TABLE_NAME, INVALID_CALENDARALERTS_SELECTOR, selectArg);
27119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
27129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        long nextAlarmTime = end;
27138f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff        final long tmpAlarmTime = CalendarAlerts.findNextAlarmTime(cr, currentMillis);
27148f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff        if (tmpAlarmTime != -1 && tmpAlarmTime < nextAlarmTime) {
27158f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff            nextAlarmTime = tmpAlarmTime;
27169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
27179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
27189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Extract events from the database sorted by alarm time.  The
27199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // alarm times are computed from Instances.begin (whose units
27209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // are milliseconds) and Reminders.minutes (whose units are
27219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // minutes).
27229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //
27239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Also, ignore events whose end time is already in the past.
27249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Also, ignore events alarms that we have already scheduled.
27259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //
27269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Note 1: we can add support for the case where Reminders.minutes
27279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // equals -1 to mean use Calendars.minutes by adding a UNION for
27289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // that case where the two halves restrict the WHERE clause on
27299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Reminders.minutes != -1 and Reminders.minutes = 1, respectively.
27309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        //
27319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Note 2: we have to name "myAlarmTime" different from the
27329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // "alarmTime" column in CalendarAlerts because otherwise the
27339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // query won't find multiple alarms for the same event.
2734156ad29fe71eaae73cddad9b17690d1cc8225136Ken Shirriff        //
2735156ad29fe71eaae73cddad9b17690d1cc8225136Ken Shirriff        // The CAST is needed in the query because otherwise the expression
2736156ad29fe71eaae73cddad9b17690d1cc8225136Ken Shirriff        // will be untyped and sqlite3's manifest typing will not convert the
2737156ad29fe71eaae73cddad9b17690d1cc8225136Ken Shirriff        // string query parameter to an int in myAlarmtime>=?, so the comparison
2738156ad29fe71eaae73cddad9b17690d1cc8225136Ken Shirriff        // will fail.  This could be simplified if bug 2464440 is resolved.
27399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        String query = "SELECT begin-(minutes*60000) AS myAlarmTime,"
27409f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                + " Instances.event_id AS eventId, begin, end,"
27419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                + " title, allDay, method, minutes"
27429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                + " FROM Instances INNER JOIN Events"
27439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                + " ON (Events._id = Instances.event_id)"
27449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                + " INNER JOIN Reminders"
27459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                + " ON (Instances.event_id = Reminders.event_id)"
27469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                + " WHERE method=" + Reminders.METHOD_ALERT
2747156ad29fe71eaae73cddad9b17690d1cc8225136Ken Shirriff                + " AND myAlarmTime>=CAST(? AS INT)"
2748156ad29fe71eaae73cddad9b17690d1cc8225136Ken Shirriff                + " AND myAlarmTime<=CAST(? AS INT)"
2749156ad29fe71eaae73cddad9b17690d1cc8225136Ken Shirriff                + " AND end>=?"
27509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                + " AND 0=(SELECT count(*) from CalendarAlerts CA"
27519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                + " where CA.event_id=Instances.event_id AND CA.begin=Instances.begin"
27529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                + " AND CA.alarmTime=myAlarmTime)"
27539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                + " ORDER BY myAlarmTime,begin,title";
2754156ad29fe71eaae73cddad9b17690d1cc8225136Ken Shirriff        String queryParams[] = new String[] {String.valueOf(start), String.valueOf(nextAlarmTime),
2755156ad29fe71eaae73cddad9b17690d1cc8225136Ken Shirriff                String.valueOf(currentMillis)};
27569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
27579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        acquireInstanceRangeLocked(start, end, false /* don't use minimum expansion windows */);
27589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        Cursor cursor = null;
27599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        try {
2760156ad29fe71eaae73cddad9b17690d1cc8225136Ken Shirriff            cursor = db.rawQuery(query, queryParams);
27619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
27628f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff            final int beginIndex = cursor.getColumnIndex(Instances.BEGIN);
27638f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff            final int endIndex = cursor.getColumnIndex(Instances.END);
27648f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff            final int eventIdIndex = cursor.getColumnIndex("eventId");
27658f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff            final int alarmTimeIndex = cursor.getColumnIndex("myAlarmTime");
27668f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff            final int minutesIndex = cursor.getColumnIndex(Reminders.MINUTES);
27679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
27689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (Log.isLoggable(TAG, Log.DEBUG)) {
27699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Time time = new Time();
27709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                time.set(nextAlarmTime);
27719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String alarmTimeStr = time.format(" %a, %b %d, %Y %I:%M%P");
27728f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                Log.d(TAG, "cursor results: " + cursor.getCount() + " nextAlarmTime: "
27738f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                        + alarmTimeStr);
27749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
27759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
27769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            while (cursor.moveToNext()) {
27779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Schedule all alarms whose alarm time is as early as any
27789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // scheduled alarm.  For example, if the earliest alarm is at
27799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // 1pm, then we will schedule all alarms that occur at 1pm
27809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // but no alarms that occur later than 1pm.
27819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Actually, we allow alarms up to a minute later to also
27829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // be scheduled so that we don't have to check immediately
27839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // again after an event alarm goes off.
27848f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                final long alarmTime = cursor.getLong(alarmTimeIndex);
27858f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                final long eventId = cursor.getLong(eventIdIndex);
27868f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                final int minutes = cursor.getInt(minutesIndex);
27878f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                final long startTime = cursor.getLong(beginIndex);
27888f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                final long endTime = cursor.getLong(endIndex);
27899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
27909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (Log.isLoggable(TAG, Log.DEBUG)) {
27919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    Time time = new Time();
27929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    time.set(alarmTime);
27939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    String schedTime = time.format(" %a, %b %d, %Y %I:%M%P");
27949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    time.set(startTime);
27959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    String startTimeStr = time.format(" %a, %b %d, %Y %I:%M%P");
27968f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff
27978f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                    Log.d(TAG, "  looking at id: " + eventId + " " + startTime + startTimeStr
27988f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                            + " alarm: " + alarmTime + schedTime);
27999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
28009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
28019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (alarmTime < nextAlarmTime) {
28029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    nextAlarmTime = alarmTime;
28039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                } else if (alarmTime >
28041edaf77a7ef2fbad6b6116dd75591e0aeaff3a16Ken Shirriff                           nextAlarmTime + DateUtils.MINUTE_IN_MILLIS) {
28059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // This event alarm (and all later ones) will be scheduled
28069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    // later.
28078f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                    if (Log.isLoggable(TAG, Log.DEBUG)) {
28088f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                        Log.d(TAG, "This event alarm (and all later ones) will be scheduled later");
28098f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                    }
28109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    break;
28119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
28129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
28139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Avoid an SQLiteContraintException by checking if this alarm
28149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // already exists in the table.
28159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (CalendarAlerts.alarmExists(cr, eventId, startTime, alarmTime)) {
28169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if (Log.isLoggable(TAG, Log.DEBUG)) {
28179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        int titleIndex = cursor.getColumnIndex(Events.TITLE);
28189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        String title = cursor.getString(titleIndex);
28199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        Log.d(TAG, "  alarm exists for id: " + eventId + " " + title);
28209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
28219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    continue;
28229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
28239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
28249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Insert this alarm into the CalendarAlerts table
28259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Uri uri = CalendarAlerts.insert(cr, eventId, startTime,
28269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        endTime, alarmTime, minutes);
28279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                if (uri == null) {
28289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    Log.e(TAG, "runScheduleNextAlarm() insert into CalendarAlerts table failed");
28299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    continue;
28309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
28319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
28328f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff                CalendarAlerts.scheduleAlarm(getContext(), alarmManager, alarmTime);
28339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
28349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } finally {
28359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            if (cursor != null) {
28369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                cursor.close();
28379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
28389f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
28399f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
28408f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff        // Refresh notification bar
28418f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff        if (rowsDeleted > 0) {
28428f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff            CalendarAlerts.scheduleAlarm(getContext(), alarmManager, currentMillis);
28438f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff        }
28448f4ccb20cce4cd09bd9e0c777d2d5cd92a2c9b78Ken Shirriff
28459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // If we scheduled an event alarm, then schedule the next alarm check
28469f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // for one minute past that alarm.  Otherwise, if there were no
28479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // event alarms scheduled, then check again in 24 hours.  If a new
28489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // event is inserted before the next alarm check, then this method
28499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // will be run again when the new event is inserted.
28509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (nextAlarmTime != Long.MAX_VALUE) {
28511edaf77a7ef2fbad6b6116dd75591e0aeaff3a16Ken Shirriff            scheduleNextAlarmCheck(nextAlarmTime + DateUtils.MINUTE_IN_MILLIS);
28529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } else {
28531edaf77a7ef2fbad6b6116dd75591e0aeaff3a16Ken Shirriff            scheduleNextAlarmCheck(currentMillis + DateUtils.DAY_IN_MILLIS);
28549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
28559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
28569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
28579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
28589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Removes the entries in the CalendarAlerts table for alarms that we have
28599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * scheduled but that have not fired yet. We do this to ensure that we
28609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * don't miss an alarm.  The CalendarAlerts table keeps track of the
28619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * alarms that we have scheduled but the actual alarm list is in memory
28629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * and will be cleared if the phone reboots.
28639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
28649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * We don't need to remove entries that have already fired, and in fact
28659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * we should not remove them because we need to display the notifications
28669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * until the user dismisses them.
28679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     *
28689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * We could remove entries that have fired and been dismissed, but we leave
28699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * them around for a while because it makes it easier to debug problems.
28709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Entries that are old enough will be cleaned up later when we schedule
28719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * new alarms.
28729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
28739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private void removeScheduledAlarmsLocked(SQLiteDatabase db) {
28749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (Log.isLoggable(TAG, Log.DEBUG)) {
28759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            Log.d(TAG, "removing scheduled alarms");
28769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
28779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        db.delete(CalendarAlerts.TABLE_NAME,
28789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                CalendarAlerts.STATE + "=" + CalendarAlerts.SCHEDULED, null /* whereArgs */);
28799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
28809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
28819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static String sEventsTable = "Events";
28829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static String sAttendeesTable = "Attendees";
28839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static String sRemindersTable = "Reminders";
28849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static String sCalendarAlertsTable = "CalendarAlerts";
28859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static String sExtendedPropertiesTable = "ExtendedProperties";
28869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
28879f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int EVENTS = 1;
28889f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int EVENTS_ID = 2;
28899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int INSTANCES = 3;
28909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int DELETED_EVENTS = 4;
28919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int CALENDARS = 5;
28929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int CALENDARS_ID = 6;
28939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int ATTENDEES = 7;
28949f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int ATTENDEES_ID = 8;
28959f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int REMINDERS = 9;
28969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int REMINDERS_ID = 10;
28979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int EXTENDED_PROPERTIES = 11;
28989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int EXTENDED_PROPERTIES_ID = 12;
28999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int CALENDAR_ALERTS = 13;
29009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int CALENDAR_ALERTS_ID = 14;
29019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final int CALENDAR_ALERTS_BY_INSTANCE = 15;
29026db535b458146a279bebd4a51d56c1bdfc204528Erik    private static final int INSTANCES_BY_DAY = 16;
29036db535b458146a279bebd4a51d56c1bdfc204528Erik    private static final int SYNCSTATE = 17;
29046db535b458146a279bebd4a51d56c1bdfc204528Erik    private static final int SYNCSTATE_ID = 18;
29056db535b458146a279bebd4a51d56c1bdfc204528Erik    private static final int EVENT_ENTITIES = 19;
29066db535b458146a279bebd4a51d56c1bdfc204528Erik    private static final int EVENT_ENTITIES_ID = 20;
29076db535b458146a279bebd4a51d56c1bdfc204528Erik    private static final int EVENT_DAYS = 21;
290883512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff    private static final int SCHEDULE_ALARM = 22;
290983512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff    private static final int SCHEDULE_ALARM_REMOVE = 23;
291048587d3291c4db7f0942e1bff55b88cfa7764ba0Erik    private static final int TIME = 24;
29119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
29129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
29139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final HashMap<String, String> sInstancesProjectionMap;
29149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final HashMap<String, String> sEventsProjectionMap;
291519fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana    private static final HashMap<String, String> sEventEntitiesProjectionMap;
29169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final HashMap<String, String> sAttendeesProjectionMap;
29179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final HashMap<String, String> sRemindersProjectionMap;
29189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    private static final HashMap<String, String> sCalendarAlertsProjectionMap;
29199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
29209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    static {
2921b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "instances/when/*/*", INSTANCES);
2922b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "instances/whenbyday/*/*", INSTANCES_BY_DAY);
2923b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "instances/groupbyday/*/*", EVENT_DAYS);
2924b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "events", EVENTS);
2925b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "events/#", EVENTS_ID);
2926b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "event_entities", EVENT_ENTITIES);
2927b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "event_entities/#", EVENT_ENTITIES_ID);
2928b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "calendars", CALENDARS);
2929b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "calendars/#", CALENDARS_ID);
2930b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "deleted_events", DELETED_EVENTS);
2931b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "attendees", ATTENDEES);
2932b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "attendees/#", ATTENDEES_ID);
2933b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "reminders", REMINDERS);
2934b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "reminders/#", REMINDERS_ID);
2935b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "extendedproperties", EXTENDED_PROPERTIES);
2936b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "extendedproperties/#", EXTENDED_PROPERTIES_ID);
2937b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "calendar_alerts", CALENDAR_ALERTS);
2938b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "calendar_alerts/#", CALENDAR_ALERTS_ID);
2939b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "calendar_alerts/by_instance",
2940b57f228c23d3672c1f08153f3fcc88ced2011714Ken Shirriff                           CALENDAR_ALERTS_BY_INSTANCE);
2941c4e53191b570e09959c5723f4d253977ba48f2d0Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "syncstate", SYNCSTATE);
294283512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, "syncstate/#", SYNCSTATE_ID);
294383512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, SCHEDULE_ALARM_PATH, SCHEDULE_ALARM);
294483512315d187baad2c9dc3ed686cc23676c9f463Ken Shirriff        sUriMatcher.addURI(Calendar.AUTHORITY, SCHEDULE_ALARM_REMOVE_PATH, SCHEDULE_ALARM_REMOVE);
294548587d3291c4db7f0942e1bff55b88cfa7764ba0Erik        sUriMatcher.addURI(Calendar.AUTHORITY, "time/#", TIME);
2946997e2e5cb006682bc1a82441304994b458d9745dErik        sUriMatcher.addURI(Calendar.AUTHORITY, "time", TIME);
29479f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
29489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap = new HashMap<String, String>();
29499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Events columns
29509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.HTML_URI, "htmlUri");
29519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.TITLE, "title");
29529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.EVENT_LOCATION, "eventLocation");
29539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.DESCRIPTION, "description");
29549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.STATUS, "eventStatus");
29559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.SELF_ATTENDEE_STATUS, "selfAttendeeStatus");
29569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.COMMENTS_URI, "commentsUri");
29579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.DTSTART, "dtstart");
29589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.DTEND, "dtend");
29599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.EVENT_TIMEZONE, "eventTimezone");
29609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.DURATION, "duration");
29619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.ALL_DAY, "allDay");
29629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.VISIBILITY, "visibility");
29639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.TRANSPARENCY, "transparency");
29649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.HAS_ALARM, "hasAlarm");
29659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.HAS_EXTENDED_PROPERTIES, "hasExtendedProperties");
29669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.RRULE, "rrule");
29679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.RDATE, "rdate");
29689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.EXRULE, "exrule");
29699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.EXDATE, "exdate");
29709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.ORIGINAL_EVENT, "originalEvent");
29719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.ORIGINAL_INSTANCE_TIME, "originalInstanceTime");
29729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.ORIGINAL_ALL_DAY, "originalAllDay");
29739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.LAST_DATE, "lastDate");
29749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.HAS_ATTENDEE_DATA, "hasAttendeeData");
29759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.CALENDAR_ID, "calendar_id");
29769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.GUESTS_CAN_INVITE_OTHERS, "guestsCanInviteOthers");
29779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.GUESTS_CAN_MODIFY, "guestsCanModify");
29789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.GUESTS_CAN_SEE_GUESTS, "guestsCanSeeGuests");
29799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events.ORGANIZER, "organizer");
29807e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff        sEventsProjectionMap.put(Events.DELETED, "deleted");
29819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2982e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff        // Put the shared items into the Attendees, Reminders projection map
29831ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        sAttendeesProjectionMap = new HashMap<String, String>(sEventsProjectionMap);
29841ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        sRemindersProjectionMap = new HashMap<String, String>(sEventsProjectionMap);
29851ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff
29869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Calendar columns
2987982cbfe8b4e5af45b06fc5c18ff9e0868378ee40Ken Shirriff        sEventsProjectionMap.put(Calendars.COLOR, "color");
2988982cbfe8b4e5af45b06fc5c18ff9e0868378ee40Ken Shirriff        sEventsProjectionMap.put(Calendars.ACCESS_LEVEL, "access_level");
2989982cbfe8b4e5af45b06fc5c18ff9e0868378ee40Ken Shirriff        sEventsProjectionMap.put(Calendars.SELECTED, "selected");
29909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Calendars.URL, "url");
29919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Calendars.TIMEZONE, "timezone");
29929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Calendars.OWNER_ACCOUNT, "ownerAccount");
29939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
2994982cbfe8b4e5af45b06fc5c18ff9e0868378ee40Ken Shirriff        // Put the shared items into the Instances projection map
2995e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff        // The Instances and CalendarAlerts are joined with Calendars, so the projections include
2996e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff        // the above Calendar columns.
2997982cbfe8b4e5af45b06fc5c18ff9e0868378ee40Ken Shirriff        sInstancesProjectionMap = new HashMap<String, String>(sEventsProjectionMap);
2998e74157e34e174c923032a4b93ad298d0f234879cKen Shirriff        sCalendarAlertsProjectionMap = new HashMap<String, String>(sEventsProjectionMap);
2999982cbfe8b4e5af45b06fc5c18ff9e0868378ee40Ken Shirriff
30001ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        sEventsProjectionMap.put(Events._ID, "_id");
30011ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        sEventsProjectionMap.put(Events._SYNC_ID, "_sync_id");
30021ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        sEventsProjectionMap.put(Events._SYNC_VERSION, "_sync_version");
30031ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        sEventsProjectionMap.put(Events._SYNC_TIME, "_sync_time");
30041ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        sEventsProjectionMap.put(Events._SYNC_LOCAL_ID, "_sync_local_id");
30051ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        sEventsProjectionMap.put(Events._SYNC_DIRTY, "_sync_dirty");
30061ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff        sEventsProjectionMap.put(Events._SYNC_ACCOUNT, "_sync_account");
30079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sEventsProjectionMap.put(Events._SYNC_ACCOUNT_TYPE,
30081ae4c22f15c107cd9f9cd8babaa11005e45e4647Ken Shirriff                "_sync_account_type");
30099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
301046f3f01b132f97b51ec1f4670769dda499cd9da5Ken Shirriff        sEventEntitiesProjectionMap = new HashMap<String, String>();
301119fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.HTML_URI, "htmlUri");
301219fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.TITLE, "title");
301319fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.DESCRIPTION, "description");
301419fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.EVENT_LOCATION, "eventLocation");
301519fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.STATUS, "eventStatus");
301619fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.SELF_ATTENDEE_STATUS, "selfAttendeeStatus");
301719fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.COMMENTS_URI, "commentsUri");
301819fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.DTSTART, "dtstart");
301919fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.DTEND, "dtend");
302019fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.DURATION, "duration");
302119fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.EVENT_TIMEZONE, "eventTimezone");
302219fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.ALL_DAY, "allDay");
302319fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.VISIBILITY, "visibility");
302419fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.TRANSPARENCY, "transparency");
302519fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.HAS_ALARM, "hasAlarm");
302619fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.HAS_EXTENDED_PROPERTIES, "hasExtendedProperties");
302719fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.RRULE, "rrule");
302819fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.RDATE, "rdate");
302919fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.EXRULE, "exrule");
303019fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.EXDATE, "exdate");
303119fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.ORIGINAL_EVENT, "originalEvent");
303219fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.ORIGINAL_INSTANCE_TIME, "originalInstanceTime");
303319fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.ORIGINAL_ALL_DAY, "originalAllDay");
303419fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.LAST_DATE, "lastDate");
303519fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.HAS_ATTENDEE_DATA, "hasAttendeeData");
303619fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.CALENDAR_ID, "calendar_id");
303719fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.GUESTS_CAN_INVITE_OTHERS, "guestsCanInviteOthers");
303819fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.GUESTS_CAN_MODIFY, "guestsCanModify");
303919fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.GUESTS_CAN_SEE_GUESTS, "guestsCanSeeGuests");
304019fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.ORGANIZER, "organizer");
304119fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events.DELETED, "deleted");
304219fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events._ID, Events._ID);
304319fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events._SYNC_ID, Events._SYNC_ID);
304419fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events._SYNC_VERSION, Events._SYNC_VERSION);
304519fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Events._SYNC_DIRTY, Events._SYNC_DIRTY);
304619fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana        sEventEntitiesProjectionMap.put(Calendars.URL, "url");
304719fb3af2ec12621bca575f5518c2ba3831cb3600Fred Quintana
30489f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Instances columns
30499f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sInstancesProjectionMap.put(Instances.BEGIN, "begin");
30509f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sInstancesProjectionMap.put(Instances.END, "end");
30519f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sInstancesProjectionMap.put(Instances.EVENT_ID, "Instances.event_id AS event_id");
30529f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sInstancesProjectionMap.put(Instances._ID, "Instances._id AS _id");
30539f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sInstancesProjectionMap.put(Instances.START_DAY, "startDay");
30549f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sInstancesProjectionMap.put(Instances.END_DAY, "endDay");
30559f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sInstancesProjectionMap.put(Instances.START_MINUTE, "startMinute");
30569f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sInstancesProjectionMap.put(Instances.END_MINUTE, "endMinute");
30579f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
30589f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Attendees columns
30599f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sAttendeesProjectionMap.put(Attendees.EVENT_ID, "event_id");
30609f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sAttendeesProjectionMap.put(Attendees._ID, "Attendees._id AS _id");
30619f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sAttendeesProjectionMap.put(Attendees.ATTENDEE_NAME, "attendeeName");
30629f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sAttendeesProjectionMap.put(Attendees.ATTENDEE_EMAIL, "attendeeEmail");
30639f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sAttendeesProjectionMap.put(Attendees.ATTENDEE_STATUS, "attendeeStatus");
30649f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sAttendeesProjectionMap.put(Attendees.ATTENDEE_RELATIONSHIP, "attendeeRelationship");
30659f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sAttendeesProjectionMap.put(Attendees.ATTENDEE_TYPE, "attendeeType");
30669f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
30679f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // Reminders columns
30689f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sRemindersProjectionMap.put(Reminders.EVENT_ID, "event_id");
30699f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sRemindersProjectionMap.put(Reminders._ID, "Reminders._id AS _id");
30709f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sRemindersProjectionMap.put(Reminders.MINUTES, "minutes");
30719f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sRemindersProjectionMap.put(Reminders.METHOD, "method");
30729f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
30739f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        // CalendarAlerts columns
30749f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sCalendarAlertsProjectionMap.put(CalendarAlerts.EVENT_ID, "event_id");
30759f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sCalendarAlertsProjectionMap.put(CalendarAlerts._ID, "CalendarAlerts._id AS _id");
30769f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sCalendarAlertsProjectionMap.put(CalendarAlerts.BEGIN, "begin");
30779f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sCalendarAlertsProjectionMap.put(CalendarAlerts.END, "end");
30789f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sCalendarAlertsProjectionMap.put(CalendarAlerts.ALARM_TIME, "alarmTime");
30799f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sCalendarAlertsProjectionMap.put(CalendarAlerts.STATE, "state");
30809f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        sCalendarAlertsProjectionMap.put(CalendarAlerts.MINUTES, "minutes");
30819f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
30829f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
30839f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    /**
30849f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Make sure that there are no entries for accounts that no longer
30859f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * exist. We are overriding this since we need to delete from the
30869f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     * Calendars table, which is not syncable, which has triggers that
30877e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * will delete from the Events and  tables, which are
30887e3ec5f2025164fca508f81a5a01940bc912e064Ken Shirriff     * syncable.  TODO: update comment, make sure deletes don't get synced.
30899f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff     */
30909f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    public void onAccountsUpdated(Account[] accounts) {
30919f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        mDb = mDbHelper.getWritableDatabase();
30929f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        if (mDb == null) return;
30939f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
309446f3f01b132f97b51ec1f4670769dda499cd9da5Ken Shirriff        HashMap<Account, Boolean> accountHasCalendar = new HashMap<Account, Boolean>();
309546f3f01b132f97b51ec1f4670769dda499cd9da5Ken Shirriff        HashSet<Account> validAccounts = new HashSet<Account>();
30969f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        for (Account account : accounts) {
30979f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            validAccounts.add(new Account(account.name, account.type));
30989f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            accountHasCalendar.put(account, false);
30999f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
31009f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        ArrayList<Account> accountsToDelete = new ArrayList<Account>();
31019f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
31029f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        mDb.beginTransaction();
31039f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        try {
31049f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
31059f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            for (String table : new String[]{"Calendars"}) {
31069f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // Find all the accounts the contacts DB knows about, mark the ones that aren't
31079f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                // in the valid set for deletion.
31089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Cursor c = mDb.rawQuery("SELECT DISTINCT " + CalendarDatabaseHelper.ACCOUNT_NAME
31099f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                        + ","
31109f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                                        + CalendarDatabaseHelper.ACCOUNT_TYPE + " from "
31119f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        + table, null);
31129f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                while (c.moveToNext()) {
31139f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    if (c.getString(0) != null && c.getString(1) != null) {
31149f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        Account currAccount = new Account(c.getString(0), c.getString(1));
31159f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        if (!validAccounts.contains(currAccount)) {
31169f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                            accountsToDelete.add(currAccount);
31179f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        }
31189f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                    }
31199f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                }
31209f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                c.close();
31219f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
31229f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
31239f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            for (Account account : accountsToDelete) {
31249f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                Log.d(TAG, "removing data for removed account " + account);
31259f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                String[] params = new String[]{account.name, account.type};
31269f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                mDb.execSQL("DELETE FROM Calendars"
31279f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        + " WHERE " + CalendarDatabaseHelper.ACCOUNT_NAME + "= ? AND "
31289f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        + CalendarDatabaseHelper.ACCOUNT_TYPE
31299f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                        + "= ?", params);
31309f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            }
31319f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            mDbHelper.getSyncState().onAccountsChanged(mDb, accounts);
31329f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            mDb.setTransactionSuccessful();
31339f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        } finally {
31349f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff            mDb.endTransaction();
31359f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        }
31369f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
31379f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3138595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff    /* package */ static boolean readBooleanQueryParameter(Uri uri, String name,
3139595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            boolean defaultValue) {
3140595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        final String flag = getQueryParameter(uri, name);
31419f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff        return flag == null
31429f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                ? defaultValue
31439f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff                : (!"false".equals(flag.toLowerCase()) && !"0".equals(flag.toLowerCase()));
31449f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff    }
31459f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff
3146595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff    // Duplicated from ContactsProvider2.  TODO: a utility class for shared code
3147595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff    /**
3148595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff     * A fast re-implementation of {@link Uri#getQueryParameter}
3149595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff     */
3150595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff    /* package */ static String getQueryParameter(Uri uri, String parameter) {
3151595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        String query = uri.getEncodedQuery();
3152595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        if (query == null) {
3153595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            return null;
3154595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        }
3155595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff
3156595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        int queryLength = query.length();
3157595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        int parameterLength = parameter.length();
3158595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff
3159595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        String value;
3160595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        int index = 0;
3161595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        while (true) {
3162595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            index = query.indexOf(parameter, index);
3163595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            if (index == -1) {
3164595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff                return null;
3165595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            }
3166595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff
3167595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            index += parameterLength;
3168595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff
3169595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            if (queryLength == index) {
3170595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff                return null;
3171595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            }
3172595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff
3173595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            if (query.charAt(index) == '=') {
3174595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff                index++;
3175595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff                break;
3176595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            }
3177595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        }
3178595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff
3179595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        int ampIndex = query.indexOf('&', index);
3180595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        if (ampIndex == -1) {
3181595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            value = query.substring(index);
3182595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        } else {
3183595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff            value = query.substring(index, ampIndex);
3184595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        }
3185595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff
3186595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff        return Uri.decode(value);
3187595242cb01dc0d2d90b01613ff195b2be7b2559eKen Shirriff    }
3188636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff
3189636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff    /**
3190636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff     * Inserts an argument at the beginning of the selection arg list.
3191636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff     *
3192636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff     * The {@link android.database.sqlite.SQLiteQueryBuilder}'s where clause is
3193636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff     * prepended to the user's where clause (combined with 'AND') to generate
3194636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff     * the final where close, so arguments associated with the QueryBuilder are
3195636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff     * prepended before any user selection args to keep them in the right order.
3196636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff     */
3197636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff    private String[] insertSelectionArg(String[] selectionArgs, String arg) {
3198636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff        if (selectionArgs == null) {
3199636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff            return new String[] {arg};
3200636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff        } else {
3201636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff            int newLength = selectionArgs.length + 1;
3202636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff            String[] newSelectionArgs = new String[newLength];
3203636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff            newSelectionArgs[0] = arg;
3204636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff            System.arraycopy(selectionArgs, 0, newSelectionArgs, 1, selectionArgs.length);
3205636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff            return newSelectionArgs;
3206636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff        }
3207636b4fb283b9d2802afd179b20a24f2f5035ee69Ken Shirriff    }
32089f005e4843925efe4fa8434361c4ad4ad384ed4cKen Shirriff}
3209