CalendarContract.java revision 0a35dd5660ea3aac7676054fcdb39afadd639f8c
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.provider;
18
19
20import android.annotation.SdkConstant;
21import android.annotation.SdkConstant.SdkConstantType;
22import android.app.Activity;
23import android.app.AlarmManager;
24import android.app.PendingIntent;
25import android.content.ContentProviderClient;
26import android.content.ContentResolver;
27import android.content.ContentUris;
28import android.content.ContentValues;
29import android.content.Context;
30import android.content.CursorEntityIterator;
31import android.content.Entity;
32import android.content.EntityIterator;
33import android.content.Intent;
34import android.database.Cursor;
35import android.database.DatabaseUtils;
36import android.net.Uri;
37import android.os.RemoteException;
38import android.text.format.DateUtils;
39import android.text.format.Time;
40import android.util.Log;
41
42/**
43 * <p>
44 * The contract between the calendar provider and applications. Contains
45 * definitions for the supported URIs and data columns.
46 * </p>
47 * <h3>Overview</h3>
48 * <p>
49 * CalendarContract defines the data model of calendar and event related
50 * information. This data is stored in a number of tables:
51 * </p>
52 * <ul>
53 * <li>The {@link Calendars} table holds the calendar specific information. Each
54 * row in this table contains the details for a single calendar, such as the
55 * name, color, sync info, etc.</li>
56 * <li>The {@link Events} table holds the event specific information. Each row
57 * in this table has the info for a single event. It contains information such
58 * as event title, location, start time, end time, etc. The event can occur
59 * one-time or can recur multiple times. Attendees, reminders, and extended
60 * properties are stored on separate tables and reference the {@link Events#_ID}
61 * to link them with the event.</li>
62 * <li>The {@link Instances} table holds the start and end time for occurrences
63 * of an event. Each row in this table represents a single occurrence. For
64 * one-time events there will be a 1:1 mapping of instances to events. For
65 * recurring events, multiple rows will automatically be generated which
66 * correspond to multiple occurrences of that event.</li>
67 * <li>The {@link Attendees} table holds the event attendee or guest
68 * information. Each row represents a single guest of an event. It specifies the
69 * type of guest they are and their attendance response for the event.</li>
70 * <li>The {@link Reminders} table holds the alert/notification data. Each row
71 * represents a single alert for an event. An event can have multiple reminders.
72 * The number of reminders per event is specified in
73 * {@link Calendars#MAX_REMINDERS} which is set by the Sync Adapter that owns
74 * the given calendar. Reminders are specified in minutes before the event and
75 * have a type.</li>
76 * <li>The {@link ExtendedProperties} table holds opaque data fields used by the
77 * sync adapter. The provider takes no action with items in this table except to
78 * delete them when their related events are deleted.</li>
79 * </ul>
80 * <p>
81 * Other tables include:
82 * </p>
83 * <ul>
84 * <li>
85 * {@link SyncState}, which contains free-form data maintained by the sync
86 * adapters</li>
87 * </ul>
88 *
89 */
90public final class CalendarContract {
91    private static final String TAG = "Calendar";
92
93    /**
94     * Broadcast Action: This is the intent that gets fired when an alarm
95     * notification needs to be posted for a reminder.
96     *
97     */
98    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
99    public static final String ACTION_EVENT_REMINDER = "android.intent.action.EVENT_REMINDER";
100
101    /**
102     * Activity Action: Display the event to the user in the custom app as
103     * specified in {@link EventsColumns#CUSTOM_APP_PACKAGE}. The custom app
104     * will be started via {@link Activity#startActivityForResult(Intent, int)}
105     * and it should call {@link Activity#setResult(int)} with
106     * {@link Activity#RESULT_OK} or {@link Activity#RESULT_CANCELED} to
107     * acknowledge whether the action was handled or not.
108     *
109     * The custom app should have an intent-filter like the following
110     * <pre>
111     * {@code
112     * <intent-filter>
113     *    <action android:name="android.provider.calendar.action.HANDLE_CUSTOM_EVENT" />
114     *    <category android:name="android.intent.category.DEFAULT" />
115     *    <data android:mimeType="vnd.android.cursor.item/event" />
116     * </intent-filter>
117     * }
118     * </pre>
119     * <p>
120     * Input: {@link Intent#getData} has the event URI. The extra
121     * {@link #EXTRA_EVENT_BEGIN_TIME} has the start time of the instance. The
122     * extra {@link #EXTRA_CUSTOM_APP_URI} will have the
123     * {@link EventsColumns#CUSTOM_APP_URI}.
124     * <p>
125     * Output: {@link Activity#RESULT_OK} if this was handled; otherwise
126     * {@link Activity#RESULT_CANCELED}
127     */
128    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
129    public static final String ACTION_HANDLE_CUSTOM_EVENT =
130        "android.provider.calendar.action.HANDLE_CUSTOM_EVENT";
131
132    /**
133     * Intent Extras key: {@link EventsColumns#CUSTOM_APP_URI} for the event in
134     * the {@link #ACTION_HANDLE_CUSTOM_EVENT} intent
135     */
136    public static final String EXTRA_CUSTOM_APP_URI = "customAppUri";
137
138    /**
139     * Intent Extras key: The start time of an event or an instance of a
140     * recurring event. (milliseconds since epoch)
141     */
142    public static final String EXTRA_EVENT_BEGIN_TIME = "beginTime";
143
144    /**
145     * Intent Extras key: The end time of an event or an instance of a recurring
146     * event. (milliseconds since epoch)
147     */
148    public static final String EXTRA_EVENT_END_TIME = "endTime";
149
150    /**
151     * Intent Extras key: When creating an event, set this to true to create an
152     * all-day event by default
153     */
154    public static final String EXTRA_EVENT_ALL_DAY = "allDay";
155
156    /**
157     * This authority is used for writing to or querying from the calendar
158     * provider. Note: This is set at first run and cannot be changed without
159     * breaking apps that access the provider.
160     */
161    public static final String AUTHORITY = "com.android.calendar";
162
163    /**
164     * The content:// style URL for the top-level calendar authority
165     */
166    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
167
168    /**
169     * An optional insert, update or delete URI parameter that allows the caller
170     * to specify that it is a sync adapter. The default value is false. If set
171     * to true, the modified row is not marked as "dirty" (needs to be synced)
172     * and when the provider calls
173     * {@link ContentResolver#notifyChange(android.net.Uri, android.database.ContentObserver, boolean)}
174     * , the third parameter "syncToNetwork" is set to false. Furthermore, if
175     * set to true, the caller must also include
176     * {@link Calendars#ACCOUNT_NAME} and {@link Calendars#ACCOUNT_TYPE} as
177     * query parameters.
178     *
179     * @see Uri.Builder#appendQueryParameter(java.lang.String, java.lang.String)
180     */
181    public static final String CALLER_IS_SYNCADAPTER = "caller_is_syncadapter";
182
183    /**
184     * A special account type for calendars not associated with any account.
185     * Normally calendars that do not match an account on the device will be
186     * removed. Setting the account_type on a calendar to this will prevent it
187     * from being wiped if it does not match an existing account.
188     *
189     * @see SyncColumns#ACCOUNT_TYPE
190     */
191    public static final String ACCOUNT_TYPE_LOCAL = "LOCAL";
192
193    /**
194     * This utility class cannot be instantiated
195     */
196    private CalendarContract() {}
197
198    /**
199     * Generic columns for use by sync adapters. The specific functions of these
200     * columns are private to the sync adapter. Other clients of the API should
201     * not attempt to either read or write this column. These columns are
202     * editable as part of the Calendars Uri, but can only be read if accessed
203     * through any other Uri.
204     */
205    protected interface CalendarSyncColumns {
206
207
208        /**
209         * Generic column for use by sync adapters. Column name.
210         * <P>Type: TEXT</P>
211         */
212        public static final String CAL_SYNC1 = "cal_sync1";
213
214        /**
215         * Generic column for use by sync adapters. Column name.
216         * <P>Type: TEXT</P>
217         */
218        public static final String CAL_SYNC2 = "cal_sync2";
219
220        /**
221         * Generic column for use by sync adapters. Column name.
222         * <P>Type: TEXT</P>
223         */
224        public static final String CAL_SYNC3 = "cal_sync3";
225
226        /**
227         * Generic column for use by sync adapters. Column name.
228         * <P>Type: TEXT</P>
229         */
230        public static final String CAL_SYNC4 = "cal_sync4";
231
232        /**
233         * Generic column for use by sync adapters. Column name.
234         * <P>Type: TEXT</P>
235         */
236        public static final String CAL_SYNC5 = "cal_sync5";
237
238        /**
239         * Generic column for use by sync adapters. Column name.
240         * <P>Type: TEXT</P>
241         */
242        public static final String CAL_SYNC6 = "cal_sync6";
243
244        /**
245         * Generic column for use by sync adapters. Column name.
246         * <P>Type: TEXT</P>
247         */
248        public static final String CAL_SYNC7 = "cal_sync7";
249
250        /**
251         * Generic column for use by sync adapters. Column name.
252         * <P>Type: TEXT</P>
253         */
254        public static final String CAL_SYNC8 = "cal_sync8";
255
256        /**
257         * Generic column for use by sync adapters. Column name.
258         * <P>Type: TEXT</P>
259         */
260        public static final String CAL_SYNC9 = "cal_sync9";
261
262        /**
263         * Generic column for use by sync adapters. Column name.
264         * <P>Type: TEXT</P>
265         */
266        public static final String CAL_SYNC10 = "cal_sync10";
267    }
268
269    /**
270     * Columns for Sync information used by Calendars and Events tables. These
271     * have specific uses which are expected to be consistent by the app and
272     * sync adapter.
273     *
274     */
275    protected interface SyncColumns extends CalendarSyncColumns {
276        /**
277         * The account that was used to sync the entry to the device. If the
278         * account_type is not {@link #ACCOUNT_TYPE_LOCAL} then the name and
279         * type must match an account on the device or the calendar will be
280         * deleted.
281         * <P>Type: TEXT</P>
282         */
283        public static final String ACCOUNT_NAME = "account_name";
284
285        /**
286         * The type of the account that was used to sync the entry to the
287         * device. A type of {@link #ACCOUNT_TYPE_LOCAL} will keep this event
288         * form being deleted if there are no matching accounts on the device.
289         * <P>Type: TEXT</P>
290         */
291        public static final String ACCOUNT_TYPE = "account_type";
292
293        /**
294         * The unique ID for a row assigned by the sync source. NULL if the row
295         * has never been synced. This is used as a reference id for exceptions
296         * along with {@link BaseColumns#_ID}.
297         * <P>Type: TEXT</P>
298         */
299        public static final String _SYNC_ID = "_sync_id";
300
301        /**
302         * Used to indicate that local, unsynced, changes are present.
303         * <P>Type: INTEGER (long)</P>
304         */
305
306        public static final String DIRTY = "dirty";
307
308        /**
309         * Used in conjunction with {@link #DIRTY} to indicate what packages wrote local changes.
310         * <P>Type: TEXT</P>
311         */
312        public static final String MUTATORS = "mutators";
313
314        /**
315         * Whether the row has been deleted but not synced to the server. A
316         * deleted row should be ignored.
317         * <P>
318         * Type: INTEGER (boolean)
319         * </P>
320         */
321        public static final String DELETED = "deleted";
322
323        /**
324         * If set to 1 this causes events on this calendar to be duplicated with
325         * {@link Events#LAST_SYNCED} set to 1 whenever the event
326         * transitions from non-dirty to dirty. The duplicated event will not be
327         * expanded in the instances table and will only show up in sync adapter
328         * queries of the events table. It will also be deleted when the
329         * originating event has its dirty flag cleared by the sync adapter.
330         * <P>Type: INTEGER (boolean)</P>
331         */
332        public static final String CAN_PARTIALLY_UPDATE = "canPartiallyUpdate";
333    }
334
335    /**
336     * Columns specific to the Calendars Uri that other Uris can query.
337     */
338    protected interface CalendarColumns {
339        /**
340         * The color of the calendar. This should only be updated by the sync
341         * adapter, not other apps, as changing a calendar's color can adversely
342         * affect its display.
343         * <P>Type: INTEGER (color value)</P>
344         */
345        public static final String CALENDAR_COLOR = "calendar_color";
346
347        /**
348         * A key for looking up a color from the {@link Colors} table. NULL or
349         * an empty string are reserved for indicating that the calendar does
350         * not use a key for looking up the color. The provider will update
351         * {@link #CALENDAR_COLOR} automatically when a valid key is written to
352         * this column. The key must reference an existing row of the
353         * {@link Colors} table. @see Colors
354         * <P>
355         * Type: TEXT
356         * </P>
357         */
358        public static final String CALENDAR_COLOR_KEY = "calendar_color_index";
359
360        /**
361         * The display name of the calendar. Column name.
362         * <P>
363         * Type: TEXT
364         * </P>
365         */
366        public static final String CALENDAR_DISPLAY_NAME = "calendar_displayName";
367
368        /**
369         * The level of access that the user has for the calendar
370         * <P>Type: INTEGER (one of the values below)</P>
371         */
372        public static final String CALENDAR_ACCESS_LEVEL = "calendar_access_level";
373
374        /** Cannot access the calendar */
375        public static final int CAL_ACCESS_NONE = 0;
376        /** Can only see free/busy information about the calendar */
377        public static final int CAL_ACCESS_FREEBUSY = 100;
378        /** Can read all event details */
379        public static final int CAL_ACCESS_READ = 200;
380        /** Can reply yes/no/maybe to an event */
381        public static final int CAL_ACCESS_RESPOND = 300;
382        /** not used */
383        public static final int CAL_ACCESS_OVERRIDE = 400;
384        /** Full access to modify the calendar, but not the access control
385         * settings
386         */
387        public static final int CAL_ACCESS_CONTRIBUTOR = 500;
388        /** Full access to modify the calendar, but not the access control
389         * settings
390         */
391        public static final int CAL_ACCESS_EDITOR = 600;
392        /** Full access to the calendar */
393        public static final int CAL_ACCESS_OWNER = 700;
394        /** Domain admin */
395        public static final int CAL_ACCESS_ROOT = 800;
396
397        /**
398         * Is the calendar selected to be displayed?
399         * 0 - do not show events associated with this calendar.
400         * 1 - show events associated with this calendar
401         * <P>Type: INTEGER (boolean)</P>
402         */
403        public static final String VISIBLE = "visible";
404
405        /**
406         * The time zone the calendar is associated with.
407         * <P>Type: TEXT</P>
408         */
409        public static final String CALENDAR_TIME_ZONE = "calendar_timezone";
410
411        /**
412         * Is this calendar synced and are its events stored on the device?
413         * 0 - Do not sync this calendar or store events for this calendar.
414         * 1 - Sync down events for this calendar.
415         * <p>Type: INTEGER (boolean)</p>
416         */
417        public static final String SYNC_EVENTS = "sync_events";
418
419        /**
420         * The owner account for this calendar, based on the calendar feed.
421         * This will be different from the _SYNC_ACCOUNT for delegated calendars.
422         * Column name.
423         * <P>Type: String</P>
424         */
425        public static final String OWNER_ACCOUNT = "ownerAccount";
426
427        /**
428         * Can the organizer respond to the event?  If no, the status of the
429         * organizer should not be shown by the UI.  Defaults to 1. Column name.
430         * <P>Type: INTEGER (boolean)</P>
431         */
432        public static final String CAN_ORGANIZER_RESPOND = "canOrganizerRespond";
433
434        /**
435         * Can the organizer modify the time zone of the event? Column name.
436         * <P>Type: INTEGER (boolean)</P>
437        */
438        public static final String CAN_MODIFY_TIME_ZONE = "canModifyTimeZone";
439
440        /**
441         * The maximum number of reminders allowed for an event. Column name.
442         * <P>Type: INTEGER</P>
443         */
444        public static final String MAX_REMINDERS = "maxReminders";
445
446        /**
447         * A comma separated list of reminder methods supported for this
448         * calendar in the format "#,#,#". Valid types are
449         * {@link Reminders#METHOD_DEFAULT}, {@link Reminders#METHOD_ALERT},
450         * {@link Reminders#METHOD_EMAIL}, {@link Reminders#METHOD_SMS},
451         * {@link Reminders#METHOD_ALARM}. Column name.
452         * <P>Type: TEXT</P>
453         */
454        public static final String ALLOWED_REMINDERS = "allowedReminders";
455
456        /**
457         * A comma separated list of availability types supported for this
458         * calendar in the format "#,#,#". Valid types are
459         * {@link Events#AVAILABILITY_BUSY}, {@link Events#AVAILABILITY_FREE},
460         * {@link Events#AVAILABILITY_TENTATIVE}. Setting this field to only
461         * {@link Events#AVAILABILITY_BUSY} should be used to indicate that
462         * changing the availability is not supported.
463         *
464         */
465        public static final String ALLOWED_AVAILABILITY = "allowedAvailability";
466
467        /**
468         * A comma separated list of attendee types supported for this calendar
469         * in the format "#,#,#". Valid types are {@link Attendees#TYPE_NONE},
470         * {@link Attendees#TYPE_OPTIONAL}, {@link Attendees#TYPE_REQUIRED},
471         * {@link Attendees#TYPE_RESOURCE}. Setting this field to only
472         * {@link Attendees#TYPE_NONE} should be used to indicate that changing
473         * the attendee type is not supported.
474         *
475         */
476        public static final String ALLOWED_ATTENDEE_TYPES = "allowedAttendeeTypes";
477
478        /**
479         * Is this the primary calendar for this account. If this column is not explicitly set, the
480         * provider will return 1 if {@link Calendars#ACCOUNT_NAME} is equal to
481         * {@link Calendars#OWNER_ACCOUNT}.
482         */
483        public static final String IS_PRIMARY = "isPrimary";
484    }
485
486    /**
487     * Class that represents a Calendar Entity. There is one entry per calendar.
488     * This is a helper class to make batch operations easier.
489     */
490    public static final class CalendarEntity implements BaseColumns, SyncColumns, CalendarColumns {
491
492        /**
493         * The default Uri used when creating a new calendar EntityIterator.
494         */
495        @SuppressWarnings("hiding")
496        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY +
497                "/calendar_entities");
498
499        /**
500         * This utility class cannot be instantiated
501         */
502        private CalendarEntity() {}
503
504        /**
505         * Creates an entity iterator for the given cursor. It assumes the
506         * cursor contains a calendars query.
507         *
508         * @param cursor query on {@link #CONTENT_URI}
509         * @return an EntityIterator of calendars
510         */
511        public static EntityIterator newEntityIterator(Cursor cursor) {
512            return new EntityIteratorImpl(cursor);
513        }
514
515        private static class EntityIteratorImpl extends CursorEntityIterator {
516
517            public EntityIteratorImpl(Cursor cursor) {
518                super(cursor);
519            }
520
521            @Override
522            public Entity getEntityAndIncrementCursor(Cursor cursor) throws RemoteException {
523                // we expect the cursor is already at the row we need to read from
524                final long calendarId = cursor.getLong(cursor.getColumnIndexOrThrow(_ID));
525
526                // Create the content value
527                ContentValues cv = new ContentValues();
528                cv.put(_ID, calendarId);
529
530                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, ACCOUNT_NAME);
531                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, ACCOUNT_TYPE);
532
533                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, _SYNC_ID);
534                DatabaseUtils.cursorLongToContentValuesIfPresent(cursor, cv, DIRTY);
535                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, MUTATORS);
536
537                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC1);
538                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC2);
539                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC3);
540                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC4);
541                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC5);
542                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC6);
543                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC7);
544                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC8);
545                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC9);
546                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC10);
547
548                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, Calendars.NAME);
549                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv,
550                        Calendars.CALENDAR_DISPLAY_NAME);
551                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv,
552                        Calendars.CALENDAR_COLOR);
553                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, CALENDAR_ACCESS_LEVEL);
554                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, VISIBLE);
555                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, SYNC_EVENTS);
556                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv,
557                        Calendars.CALENDAR_LOCATION);
558                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CALENDAR_TIME_ZONE);
559                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv,
560                        Calendars.OWNER_ACCOUNT);
561                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv,
562                        Calendars.CAN_ORGANIZER_RESPOND);
563                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv,
564                        Calendars.CAN_MODIFY_TIME_ZONE);
565                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv,
566                        Calendars.MAX_REMINDERS);
567                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv,
568                        Calendars.CAN_PARTIALLY_UPDATE);
569                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv,
570                        Calendars.ALLOWED_REMINDERS);
571
572                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, DELETED);
573
574                // Create the Entity from the ContentValue
575                Entity entity = new Entity(cv);
576
577                // Set cursor to next row
578                cursor.moveToNext();
579
580                // Return the created Entity
581                return entity;
582            }
583        }
584     }
585
586    /**
587     * Constants and helpers for the Calendars table, which contains details for
588     * individual calendars. <h3>Operations</h3> All operations can be done
589     * either as an app or as a sync adapter. To perform an operation as a sync
590     * adapter {@link #CALLER_IS_SYNCADAPTER} should be set to true and
591     * {@link #ACCOUNT_NAME} and {@link #ACCOUNT_TYPE} must be set in the Uri
592     * parameters. See
593     * {@link Uri.Builder#appendQueryParameter(java.lang.String, java.lang.String)}
594     * for details on adding parameters. Sync adapters have write access to more
595     * columns but are restricted to a single account at a time. Calendars are
596     * designed to be primarily managed by a sync adapter and inserting new
597     * calendars should be done as a sync adapter. For the most part, apps
598     * should only update calendars (such as changing the color or display
599     * name). If a local calendar is required an app can do so by inserting as a
600     * sync adapter and using an {@link #ACCOUNT_TYPE} of
601     * {@link #ACCOUNT_TYPE_LOCAL} .
602     * <dl>
603     * <dt><b>Insert</b></dt>
604     * <dd>When inserting a new calendar the following fields must be included:
605     * <ul>
606     * <li>{@link #ACCOUNT_NAME}</li>
607     * <li>{@link #ACCOUNT_TYPE}</li>
608     * <li>{@link #NAME}</li>
609     * <li>{@link #CALENDAR_DISPLAY_NAME}</li>
610     * <li>{@link #CALENDAR_COLOR}</li>
611     * <li>{@link #CALENDAR_ACCESS_LEVEL}</li>
612     * <li>{@link #OWNER_ACCOUNT}</li>
613     * </ul>
614     * The following fields are not required when inserting a Calendar but are
615     * generally a good idea to include:
616     * <ul>
617     * <li>{@link #SYNC_EVENTS} set to 1</li>
618     * <li>{@link #CALENDAR_TIME_ZONE}</li>
619     * <li>{@link #ALLOWED_REMINDERS}</li>
620     * <li>{@link #ALLOWED_AVAILABILITY}</li>
621     * <li>{@link #ALLOWED_ATTENDEE_TYPES}</li>
622     * </ul>
623     * <dt><b>Update</b></dt>
624     * <dd>To perform an update on a calendar the {@link #_ID} of the calendar
625     * should be provided either as an appended id to the Uri (
626     * {@link ContentUris#withAppendedId}) or as the first selection item--the
627     * selection should start with "_id=?" and the first selectionArg should be
628     * the _id of the calendar. Calendars may also be updated using a selection
629     * without the id. In general, the {@link #ACCOUNT_NAME} and
630     * {@link #ACCOUNT_TYPE} should not be changed after a calendar is created
631     * as this can cause issues for sync adapters.
632     * <dt><b>Delete</b></dt>
633     * <dd>Calendars can be deleted either by the {@link #_ID} as an appended id
634     * on the Uri or using any standard selection. Deleting a calendar should
635     * generally be handled by a sync adapter as it will remove the calendar
636     * from the database and all associated data (aka events).</dd>
637     * <dt><b>Query</b></dt>
638     * <dd>Querying the Calendars table will get you all information about a set
639     * of calendars. There will be one row returned for each calendar that
640     * matches the query selection, or at most a single row if the {@link #_ID}
641     * is appended to the Uri.</dd>
642     * </dl>
643     * <h3>Calendar Columns</h3> The following Calendar columns are writable by
644     * both an app and a sync adapter.
645     * <ul>
646     * <li>{@link #NAME}</li>
647     * <li>{@link #CALENDAR_DISPLAY_NAME}</li>
648     * <li>{@link #VISIBLE}</li>
649     * <li>{@link #SYNC_EVENTS}</li>
650     * </ul>
651     * The following Calendars columns are writable only by a sync adapter
652     * <ul>
653     * <li>{@link #ACCOUNT_NAME}</li>
654     * <li>{@link #ACCOUNT_TYPE}</li>
655     * <li>{@link #CALENDAR_COLOR}</li>
656     * <li>{@link #_SYNC_ID}</li>
657     * <li>{@link #DIRTY}</li>
658     * <li>{@link #MUTATORS}</li>
659     * <li>{@link #OWNER_ACCOUNT}</li>
660     * <li>{@link #MAX_REMINDERS}</li>
661     * <li>{@link #ALLOWED_REMINDERS}</li>
662     * <li>{@link #ALLOWED_AVAILABILITY}</li>
663     * <li>{@link #ALLOWED_ATTENDEE_TYPES}</li>
664     * <li>{@link #CAN_MODIFY_TIME_ZONE}</li>
665     * <li>{@link #CAN_ORGANIZER_RESPOND}</li>
666     * <li>{@link #CAN_PARTIALLY_UPDATE}</li>
667     * <li>{@link #CALENDAR_LOCATION}</li>
668     * <li>{@link #CALENDAR_TIME_ZONE}</li>
669     * <li>{@link #CALENDAR_ACCESS_LEVEL}</li>
670     * <li>{@link #DELETED}</li>
671     * <li>{@link #CAL_SYNC1}</li>
672     * <li>{@link #CAL_SYNC2}</li>
673     * <li>{@link #CAL_SYNC3}</li>
674     * <li>{@link #CAL_SYNC4}</li>
675     * <li>{@link #CAL_SYNC5}</li>
676     * <li>{@link #CAL_SYNC6}</li>
677     * <li>{@link #CAL_SYNC7}</li>
678     * <li>{@link #CAL_SYNC8}</li>
679     * <li>{@link #CAL_SYNC9}</li>
680     * <li>{@link #CAL_SYNC10}</li>
681     * </ul>
682     */
683    public static final class Calendars implements BaseColumns, SyncColumns, CalendarColumns {
684
685        /**
686         * This utility class cannot be instantiated
687         */
688        private Calendars() {}
689
690        /**
691         * The content:// style URL for accessing Calendars
692         */
693        @SuppressWarnings("hiding")
694        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/calendars");
695
696        /**
697         * The default sort order for this table
698         */
699        public static final String DEFAULT_SORT_ORDER = CALENDAR_DISPLAY_NAME;
700
701        /**
702         * The name of the calendar. Column name.
703         * <P>Type: TEXT</P>
704         */
705        public static final String NAME = "name";
706
707        /**
708         * The default location for the calendar. Column name.
709         * <P>Type: TEXT</P>
710         */
711        public static final String CALENDAR_LOCATION = "calendar_location";
712
713        /**
714         * These fields are only writable by a sync adapter. To modify them the
715         * caller must include {@link #CALLER_IS_SYNCADAPTER},
716         * {@link #ACCOUNT_NAME}, and {@link #ACCOUNT_TYPE} in the Uri's query
717         * parameters. TODO move to provider
718         *
719         * @hide
720         */
721        public static final String[] SYNC_WRITABLE_COLUMNS = new String[] {
722            ACCOUNT_NAME,
723            ACCOUNT_TYPE,
724            _SYNC_ID,
725            DIRTY,
726            MUTATORS,
727            OWNER_ACCOUNT,
728            MAX_REMINDERS,
729            ALLOWED_REMINDERS,
730            CAN_MODIFY_TIME_ZONE,
731            CAN_ORGANIZER_RESPOND,
732            CAN_PARTIALLY_UPDATE,
733            CALENDAR_LOCATION,
734            CALENDAR_TIME_ZONE,
735            CALENDAR_ACCESS_LEVEL,
736            DELETED,
737            CAL_SYNC1,
738            CAL_SYNC2,
739            CAL_SYNC3,
740            CAL_SYNC4,
741            CAL_SYNC5,
742            CAL_SYNC6,
743            CAL_SYNC7,
744            CAL_SYNC8,
745            CAL_SYNC9,
746            CAL_SYNC10,
747        };
748    }
749
750    /**
751     * Columns from the Attendees table that other tables join into themselves.
752     */
753    protected interface AttendeesColumns {
754
755        /**
756         * The id of the event. Column name.
757         * <P>Type: INTEGER</P>
758         */
759        public static final String EVENT_ID = "event_id";
760
761        /**
762         * The name of the attendee. Column name.
763         * <P>Type: STRING</P>
764         */
765        public static final String ATTENDEE_NAME = "attendeeName";
766
767        /**
768         * The email address of the attendee. Column name.
769         * <P>Type: STRING</P>
770         */
771        public static final String ATTENDEE_EMAIL = "attendeeEmail";
772
773        /**
774         * The relationship of the attendee to the user. Column name.
775         * <P>Type: INTEGER (one of {@link #RELATIONSHIP_ATTENDEE}, ...}.</P>
776         */
777        public static final String ATTENDEE_RELATIONSHIP = "attendeeRelationship";
778
779        public static final int RELATIONSHIP_NONE = 0;
780        public static final int RELATIONSHIP_ATTENDEE = 1;
781        public static final int RELATIONSHIP_ORGANIZER = 2;
782        public static final int RELATIONSHIP_PERFORMER = 3;
783        public static final int RELATIONSHIP_SPEAKER = 4;
784
785        /**
786         * The type of attendee. Column name.
787         * <P>
788         * Type: Integer (one of {@link #TYPE_NONE}, {@link #TYPE_REQUIRED},
789         * {@link #TYPE_OPTIONAL}, {@link #TYPE_RESOURCE})
790         * </P>
791         */
792        public static final String ATTENDEE_TYPE = "attendeeType";
793
794        public static final int TYPE_NONE = 0;
795        public static final int TYPE_REQUIRED = 1;
796        public static final int TYPE_OPTIONAL = 2;
797        /**
798         * This specifies that an attendee is a resource, like a room, a
799         * cabbage, or something and not an actual person.
800         */
801        public static final int TYPE_RESOURCE = 3;
802
803        /**
804         * The attendance status of the attendee. Column name.
805         * <P>Type: Integer (one of {@link #ATTENDEE_STATUS_ACCEPTED}, ...).</P>
806         */
807        public static final String ATTENDEE_STATUS = "attendeeStatus";
808
809        public static final int ATTENDEE_STATUS_NONE = 0;
810        public static final int ATTENDEE_STATUS_ACCEPTED = 1;
811        public static final int ATTENDEE_STATUS_DECLINED = 2;
812        public static final int ATTENDEE_STATUS_INVITED = 3;
813        public static final int ATTENDEE_STATUS_TENTATIVE = 4;
814
815        /**
816         * The identity of the attendee as referenced in
817         * {@link ContactsContract.CommonDataKinds.Identity#IDENTITY}.
818         * This is required only if {@link #ATTENDEE_ID_NAMESPACE} is present. Column name.
819         * <P>Type: STRING</P>
820         */
821        public static final String ATTENDEE_IDENTITY = "attendeeIdentity";
822
823        /**
824         * The identity name space of the attendee as referenced in
825         * {@link ContactsContract.CommonDataKinds.Identity#NAMESPACE}.
826         * This is required only if {@link #ATTENDEE_IDENTITY} is present. Column name.
827         * <P>Type: STRING</P>
828         */
829        public static final String ATTENDEE_ID_NAMESPACE = "attendeeIdNamespace";
830    }
831
832    /**
833     * Fields and helpers for interacting with Attendees. Each row of this table
834     * represents a single attendee or guest of an event. Calling
835     * {@link #query(ContentResolver, long, String[])} will return a list of attendees for
836     * the event with the given eventId. Both apps and sync adapters may write
837     * to this table. There are six writable fields and all of them except
838     * {@link #ATTENDEE_NAME} must be included when inserting a new attendee.
839     * They are:
840     * <ul>
841     * <li>{@link #EVENT_ID}</li>
842     * <li>{@link #ATTENDEE_NAME}</li>
843     * <li>{@link #ATTENDEE_EMAIL}</li>
844     * <li>{@link #ATTENDEE_RELATIONSHIP}</li>
845     * <li>{@link #ATTENDEE_TYPE}</li>
846     * <li>{@link #ATTENDEE_STATUS}</li>
847     * <li>{@link #ATTENDEE_IDENTITY}</li>
848     * <li>{@link #ATTENDEE_ID_NAMESPACE}</li>
849     * </ul>
850     */
851    public static final class Attendees implements BaseColumns, AttendeesColumns, EventsColumns {
852
853        /**
854         * The content:// style URL for accessing Attendees data
855         */
856        @SuppressWarnings("hiding")
857        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/attendees");
858        private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=?";
859
860        /**
861         * This utility class cannot be instantiated
862         */
863        private Attendees() {}
864
865        /**
866         * Queries all attendees associated with the given event. This is a
867         * blocking call and should not be done on the UI thread.
868         *
869         * @param cr The content resolver to use for the query
870         * @param eventId The id of the event to retrieve attendees for
871         * @param projection the columns to return in the cursor
872         * @return A Cursor containing all attendees for the event
873         */
874        public static final Cursor query(ContentResolver cr, long eventId, String[] projection) {
875            String[] attArgs = {Long.toString(eventId)};
876            return cr.query(CONTENT_URI, projection, ATTENDEES_WHERE, attArgs /* selection args */,
877                    null /* sort order */);
878        }
879    }
880
881    /**
882     * Columns from the Events table that other tables join into themselves.
883     */
884    protected interface EventsColumns {
885
886        /**
887         * The {@link Calendars#_ID} of the calendar the event belongs to.
888         * Column name.
889         * <P>Type: INTEGER</P>
890         */
891        public static final String CALENDAR_ID = "calendar_id";
892
893        /**
894         * The title of the event. Column name.
895         * <P>Type: TEXT</P>
896         */
897        public static final String TITLE = "title";
898
899        /**
900         * The description of the event. Column name.
901         * <P>Type: TEXT</P>
902         */
903        public static final String DESCRIPTION = "description";
904
905        /**
906         * Where the event takes place. Column name.
907         * <P>Type: TEXT</P>
908         */
909        public static final String EVENT_LOCATION = "eventLocation";
910
911        /**
912         * A secondary color for the individual event. This should only be
913         * updated by the sync adapter for a given account.
914         * <P>Type: INTEGER</P>
915         */
916        public static final String EVENT_COLOR = "eventColor";
917
918        /**
919         * A secondary color key for the individual event. NULL or an empty
920         * string are reserved for indicating that the event does not use a key
921         * for looking up the color. The provider will update
922         * {@link #EVENT_COLOR} automatically when a valid key is written to
923         * this column. The key must reference an existing row of the
924         * {@link Colors} table. @see Colors
925         * <P>
926         * Type: TEXT
927         * </P>
928         */
929        public static final String EVENT_COLOR_KEY = "eventColor_index";
930
931        /**
932         * This will be {@link #EVENT_COLOR} if it is not null; otherwise, this will be
933         * {@link Calendars#CALENDAR_COLOR}.
934         * Read-only value. To modify, write to {@link #EVENT_COLOR} or
935         * {@link Calendars#CALENDAR_COLOR} directly.
936         *<P>
937         *     Type: INTEGER
938         *</P>
939         */
940        public static final String DISPLAY_COLOR = "displayColor";
941
942        /**
943         * The event status. Column name.
944         * <P>Type: INTEGER (one of {@link #STATUS_TENTATIVE}...)</P>
945         */
946        public static final String STATUS = "eventStatus";
947
948        public static final int STATUS_TENTATIVE = 0;
949        public static final int STATUS_CONFIRMED = 1;
950        public static final int STATUS_CANCELED = 2;
951
952        /**
953         * This is a copy of the attendee status for the owner of this event.
954         * This field is copied here so that we can efficiently filter out
955         * events that are declined without having to look in the Attendees
956         * table. Column name.
957         *
958         * <P>Type: INTEGER (int)</P>
959         */
960        public static final String SELF_ATTENDEE_STATUS = "selfAttendeeStatus";
961
962        /**
963         * This column is available for use by sync adapters. Column name.
964         * <P>Type: TEXT</P>
965         */
966        public static final String SYNC_DATA1 = "sync_data1";
967
968        /**
969         * This column is available for use by sync adapters. Column name.
970         * <P>Type: TEXT</P>
971         */
972        public static final String SYNC_DATA2 = "sync_data2";
973
974        /**
975         * This column is available for use by sync adapters. Column name.
976         * <P>Type: TEXT</P>
977         */
978        public static final String SYNC_DATA3 = "sync_data3";
979
980        /**
981         * This column is available for use by sync adapters. Column name.
982         * <P>Type: TEXT</P>
983         */
984        public static final String SYNC_DATA4 = "sync_data4";
985
986        /**
987         * This column is available for use by sync adapters. Column name.
988         * <P>Type: TEXT</P>
989         */
990        public static final String SYNC_DATA5 = "sync_data5";
991
992        /**
993         * This column is available for use by sync adapters. Column name.
994         * <P>Type: TEXT</P>
995         */
996        public static final String SYNC_DATA6 = "sync_data6";
997
998        /**
999         * This column is available for use by sync adapters. Column name.
1000         * <P>Type: TEXT</P>
1001         */
1002        public static final String SYNC_DATA7 = "sync_data7";
1003
1004        /**
1005         * This column is available for use by sync adapters. Column name.
1006         * <P>Type: TEXT</P>
1007         */
1008        public static final String SYNC_DATA8 = "sync_data8";
1009
1010        /**
1011         * This column is available for use by sync adapters. Column name.
1012         * <P>Type: TEXT</P>
1013         */
1014        public static final String SYNC_DATA9 = "sync_data9";
1015
1016        /**
1017         * This column is available for use by sync adapters. Column name.
1018         * <P>Type: TEXT</P>
1019         */
1020        public static final String SYNC_DATA10 = "sync_data10";
1021
1022        /**
1023         * Used to indicate that a row is not a real event but an original copy of a locally
1024         * modified event. A copy is made when an event changes from non-dirty to dirty and the
1025         * event is on a calendar with {@link Calendars#CAN_PARTIALLY_UPDATE} set to 1. This copy
1026         * does not get expanded in the instances table and is only visible in queries made by a
1027         * sync adapter. The copy gets removed when the event is changed back to non-dirty by a
1028         * sync adapter.
1029         * <P>Type: INTEGER (boolean)</P>
1030         */
1031        public static final String LAST_SYNCED = "lastSynced";
1032
1033        /**
1034         * The time the event starts in UTC millis since epoch. Column name.
1035         * <P>Type: INTEGER (long; millis since epoch)</P>
1036         */
1037        public static final String DTSTART = "dtstart";
1038
1039        /**
1040         * The time the event ends in UTC millis since epoch. Column name.
1041         * <P>Type: INTEGER (long; millis since epoch)</P>
1042         */
1043        public static final String DTEND = "dtend";
1044
1045        /**
1046         * The duration of the event in RFC2445 format. Column name.
1047         * <P>Type: TEXT (duration in RFC2445 format)</P>
1048         */
1049        public static final String DURATION = "duration";
1050
1051        /**
1052         * The timezone for the event. Column name.
1053         * <P>Type: TEXT</P>
1054         */
1055        public static final String EVENT_TIMEZONE = "eventTimezone";
1056
1057        /**
1058         * The timezone for the end time of the event. Column name.
1059         * <P>Type: TEXT</P>
1060         */
1061        public static final String EVENT_END_TIMEZONE = "eventEndTimezone";
1062
1063        /**
1064         * Is the event all day (time zone independent). Column name.
1065         * <P>Type: INTEGER (boolean)</P>
1066         */
1067        public static final String ALL_DAY = "allDay";
1068
1069        /**
1070         * Defines how the event shows up for others when the calendar is
1071         * shared. Column name.
1072         * <P>Type: INTEGER (One of {@link #ACCESS_DEFAULT}, ...)</P>
1073         */
1074        public static final String ACCESS_LEVEL = "accessLevel";
1075
1076        /**
1077         * Default access is controlled by the server and will be treated as
1078         * public on the device.
1079         */
1080        public static final int ACCESS_DEFAULT = 0;
1081        /**
1082         * Confidential is not used by the app.
1083         */
1084        public static final int ACCESS_CONFIDENTIAL = 1;
1085        /**
1086         * Private shares the event as a free/busy slot with no details.
1087         */
1088        public static final int ACCESS_PRIVATE = 2;
1089        /**
1090         * Public makes the contents visible to anyone with access to the
1091         * calendar.
1092         */
1093        public static final int ACCESS_PUBLIC = 3;
1094
1095        /**
1096         * If this event counts as busy time or is still free time that can be
1097         * scheduled over. Column name.
1098         * <P>
1099         * Type: INTEGER (One of {@link #AVAILABILITY_BUSY},
1100         * {@link #AVAILABILITY_FREE}, {@link #AVAILABILITY_TENTATIVE})
1101         * </P>
1102         */
1103        public static final String AVAILABILITY = "availability";
1104
1105        /**
1106         * Indicates that this event takes up time and will conflict with other
1107         * events.
1108         */
1109        public static final int AVAILABILITY_BUSY = 0;
1110        /**
1111         * Indicates that this event is free time and will not conflict with
1112         * other events.
1113         */
1114        public static final int AVAILABILITY_FREE = 1;
1115        /**
1116         * Indicates that the owner's availability may change, but should be
1117         * considered busy time that will conflict.
1118         */
1119        public static final int AVAILABILITY_TENTATIVE = 2;
1120
1121        /**
1122         * Whether the event has an alarm or not. Column name.
1123         * <P>Type: INTEGER (boolean)</P>
1124         */
1125        public static final String HAS_ALARM = "hasAlarm";
1126
1127        /**
1128         * Whether the event has extended properties or not. Column name.
1129         * <P>Type: INTEGER (boolean)</P>
1130         */
1131        public static final String HAS_EXTENDED_PROPERTIES = "hasExtendedProperties";
1132
1133        /**
1134         * The recurrence rule for the event. Column name.
1135         * <P>Type: TEXT</P>
1136         */
1137        public static final String RRULE = "rrule";
1138
1139        /**
1140         * The recurrence dates for the event. Column name.
1141         * <P>Type: TEXT</P>
1142         */
1143        public static final String RDATE = "rdate";
1144
1145        /**
1146         * The recurrence exception rule for the event. Column name.
1147         * <P>Type: TEXT</P>
1148         */
1149        public static final String EXRULE = "exrule";
1150
1151        /**
1152         * The recurrence exception dates for the event. Column name.
1153         * <P>Type: TEXT</P>
1154         */
1155        public static final String EXDATE = "exdate";
1156
1157        /**
1158         * The {@link Events#_ID} of the original recurring event for which this
1159         * event is an exception. Column name.
1160         * <P>Type: TEXT</P>
1161         */
1162        public static final String ORIGINAL_ID = "original_id";
1163
1164        /**
1165         * The _sync_id of the original recurring event for which this event is
1166         * an exception. The provider should keep the original_id in sync when
1167         * this is updated. Column name.
1168         * <P>Type: TEXT</P>
1169         */
1170        public static final String ORIGINAL_SYNC_ID = "original_sync_id";
1171
1172        /**
1173         * The original instance time of the recurring event for which this
1174         * event is an exception. Column name.
1175         * <P>Type: INTEGER (long; millis since epoch)</P>
1176         */
1177        public static final String ORIGINAL_INSTANCE_TIME = "originalInstanceTime";
1178
1179        /**
1180         * The allDay status (true or false) of the original recurring event
1181         * for which this event is an exception. Column name.
1182         * <P>Type: INTEGER (boolean)</P>
1183         */
1184        public static final String ORIGINAL_ALL_DAY = "originalAllDay";
1185
1186        /**
1187         * The last date this event repeats on, or NULL if it never ends. Column
1188         * name.
1189         * <P>Type: INTEGER (long; millis since epoch)</P>
1190         */
1191        public static final String LAST_DATE = "lastDate";
1192
1193        /**
1194         * Whether the event has attendee information.  True if the event
1195         * has full attendee data, false if the event has information about
1196         * self only. Column name.
1197         * <P>Type: INTEGER (boolean)</P>
1198         */
1199        public static final String HAS_ATTENDEE_DATA = "hasAttendeeData";
1200
1201        /**
1202         * Whether guests can modify the event. Column name.
1203         * <P>Type: INTEGER (boolean)</P>
1204         */
1205        public static final String GUESTS_CAN_MODIFY = "guestsCanModify";
1206
1207        /**
1208         * Whether guests can invite other guests. Column name.
1209         * <P>Type: INTEGER (boolean)</P>
1210         */
1211        public static final String GUESTS_CAN_INVITE_OTHERS = "guestsCanInviteOthers";
1212
1213        /**
1214         * Whether guests can see the list of attendees. Column name.
1215         * <P>Type: INTEGER (boolean)</P>
1216         */
1217        public static final String GUESTS_CAN_SEE_GUESTS = "guestsCanSeeGuests";
1218
1219        /**
1220         * Email of the organizer (owner) of the event. Column name.
1221         * <P>Type: STRING</P>
1222         */
1223        public static final String ORGANIZER = "organizer";
1224
1225        /**
1226         * Are we the organizer of this event. If this column is not explicitly set, the provider
1227         * will return 1 if {@link #ORGANIZER} is equal to {@link Calendars#OWNER_ACCOUNT}.
1228         * Column name.
1229         * <P>Type: STRING</P>
1230         */
1231        public static final String IS_ORGANIZER = "isOrganizer";
1232
1233        /**
1234         * Whether the user can invite others to the event. The
1235         * GUESTS_CAN_INVITE_OTHERS is a setting that applies to an arbitrary
1236         * guest, while CAN_INVITE_OTHERS indicates if the user can invite
1237         * others (either through GUESTS_CAN_INVITE_OTHERS or because the user
1238         * has modify access to the event). Column name.
1239         * <P>Type: INTEGER (boolean, readonly)</P>
1240         */
1241        public static final String CAN_INVITE_OTHERS = "canInviteOthers";
1242
1243        /**
1244         * The package name of the custom app that can provide a richer
1245         * experience for the event. See the ACTION TYPE
1246         * {@link CalendarContract#ACTION_HANDLE_CUSTOM_EVENT} for details.
1247         * Column name.
1248         * <P> Type: TEXT </P>
1249         */
1250        public static final String CUSTOM_APP_PACKAGE = "customAppPackage";
1251
1252        /**
1253         * The URI used by the custom app for the event. Column name.
1254         * <P>Type: TEXT</P>
1255         */
1256        public static final String CUSTOM_APP_URI = "customAppUri";
1257
1258        /**
1259         * The UID for events added from the RFC 2445 iCalendar format.
1260         * Column name.
1261         * <P>Type: TEXT</P>
1262         */
1263        public static final String UID_2445 = "uid2445";
1264    }
1265
1266    /**
1267     * Class that represents an Event Entity. There is one entry per event.
1268     * Recurring events show up as a single entry. This is a helper class to
1269     * make batch operations easier. A {@link ContentResolver} or
1270     * {@link ContentProviderClient} is required as the helper does additional
1271     * queries to add reminders and attendees to each entry.
1272     */
1273    public static final class EventsEntity implements BaseColumns, SyncColumns, EventsColumns {
1274        /**
1275         * The content:// style URL for this table
1276         */
1277        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY +
1278                "/event_entities");
1279
1280        /**
1281         * This utility class cannot be instantiated
1282         */
1283        private EventsEntity() {}
1284
1285        /**
1286         * Creates a new iterator for events
1287         *
1288         * @param cursor An event query
1289         * @param resolver For performing additional queries
1290         * @return an EntityIterator containing one entity per event in the
1291         *         cursor
1292         */
1293        public static EntityIterator newEntityIterator(Cursor cursor, ContentResolver resolver) {
1294            return new EntityIteratorImpl(cursor, resolver);
1295        }
1296
1297        /**
1298         * Creates a new iterator for events
1299         *
1300         * @param cursor An event query
1301         * @param provider For performing additional queries
1302         * @return an EntityIterator containing one entity per event in the
1303         *         cursor
1304         */
1305        public static EntityIterator newEntityIterator(Cursor cursor,
1306                ContentProviderClient provider) {
1307            return new EntityIteratorImpl(cursor, provider);
1308        }
1309
1310        private static class EntityIteratorImpl extends CursorEntityIterator {
1311            private final ContentResolver mResolver;
1312            private final ContentProviderClient mProvider;
1313
1314            private static final String[] REMINDERS_PROJECTION = new String[] {
1315                    Reminders.MINUTES,
1316                    Reminders.METHOD,
1317            };
1318            private static final int COLUMN_MINUTES = 0;
1319            private static final int COLUMN_METHOD = 1;
1320
1321            private static final String[] ATTENDEES_PROJECTION = new String[] {
1322                    Attendees.ATTENDEE_NAME,
1323                    Attendees.ATTENDEE_EMAIL,
1324                    Attendees.ATTENDEE_RELATIONSHIP,
1325                    Attendees.ATTENDEE_TYPE,
1326                    Attendees.ATTENDEE_STATUS,
1327                    Attendees.ATTENDEE_IDENTITY,
1328                    Attendees.ATTENDEE_ID_NAMESPACE
1329            };
1330            private static final int COLUMN_ATTENDEE_NAME = 0;
1331            private static final int COLUMN_ATTENDEE_EMAIL = 1;
1332            private static final int COLUMN_ATTENDEE_RELATIONSHIP = 2;
1333            private static final int COLUMN_ATTENDEE_TYPE = 3;
1334            private static final int COLUMN_ATTENDEE_STATUS = 4;
1335            private static final int COLUMN_ATTENDEE_IDENTITY = 5;
1336            private static final int COLUMN_ATTENDEE_ID_NAMESPACE = 6;
1337
1338            private static final String[] EXTENDED_PROJECTION = new String[] {
1339                    ExtendedProperties._ID,
1340                    ExtendedProperties.NAME,
1341                    ExtendedProperties.VALUE
1342            };
1343            private static final int COLUMN_ID = 0;
1344            private static final int COLUMN_NAME = 1;
1345            private static final int COLUMN_VALUE = 2;
1346
1347            private static final String WHERE_EVENT_ID = "event_id=?";
1348
1349            public EntityIteratorImpl(Cursor cursor, ContentResolver resolver) {
1350                super(cursor);
1351                mResolver = resolver;
1352                mProvider = null;
1353            }
1354
1355            public EntityIteratorImpl(Cursor cursor, ContentProviderClient provider) {
1356                super(cursor);
1357                mResolver = null;
1358                mProvider = provider;
1359            }
1360
1361            @Override
1362            public Entity getEntityAndIncrementCursor(Cursor cursor) throws RemoteException {
1363                // we expect the cursor is already at the row we need to read from
1364                final long eventId = cursor.getLong(cursor.getColumnIndexOrThrow(Events._ID));
1365                ContentValues cv = new ContentValues();
1366                cv.put(Events._ID, eventId);
1367                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, CALENDAR_ID);
1368                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, TITLE);
1369                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, DESCRIPTION);
1370                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, EVENT_LOCATION);
1371                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, STATUS);
1372                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, SELF_ATTENDEE_STATUS);
1373                DatabaseUtils.cursorLongToContentValuesIfPresent(cursor, cv, DTSTART);
1374                DatabaseUtils.cursorLongToContentValuesIfPresent(cursor, cv, DTEND);
1375                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, DURATION);
1376                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, EVENT_TIMEZONE);
1377                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, EVENT_END_TIMEZONE);
1378                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, ALL_DAY);
1379                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, ACCESS_LEVEL);
1380                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, AVAILABILITY);
1381                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, EVENT_COLOR);
1382                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, EVENT_COLOR_KEY);
1383                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, HAS_ALARM);
1384                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv,
1385                        HAS_EXTENDED_PROPERTIES);
1386                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, RRULE);
1387                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, RDATE);
1388                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, EXRULE);
1389                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, EXDATE);
1390                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, ORIGINAL_SYNC_ID);
1391                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, ORIGINAL_ID);
1392                DatabaseUtils.cursorLongToContentValuesIfPresent(cursor, cv,
1393                        ORIGINAL_INSTANCE_TIME);
1394                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, ORIGINAL_ALL_DAY);
1395                DatabaseUtils.cursorLongToContentValuesIfPresent(cursor, cv, LAST_DATE);
1396                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, HAS_ATTENDEE_DATA);
1397                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv,
1398                        GUESTS_CAN_INVITE_OTHERS);
1399                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, GUESTS_CAN_MODIFY);
1400                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, GUESTS_CAN_SEE_GUESTS);
1401                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CUSTOM_APP_PACKAGE);
1402                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CUSTOM_APP_URI);
1403                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, UID_2445);
1404                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, ORGANIZER);
1405                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, IS_ORGANIZER);
1406                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, _SYNC_ID);
1407                DatabaseUtils.cursorLongToContentValuesIfPresent(cursor, cv, DIRTY);
1408                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, MUTATORS);
1409                DatabaseUtils.cursorLongToContentValuesIfPresent(cursor, cv, LAST_SYNCED);
1410                DatabaseUtils.cursorIntToContentValuesIfPresent(cursor, cv, DELETED);
1411                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, SYNC_DATA1);
1412                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, SYNC_DATA2);
1413                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, SYNC_DATA3);
1414                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, SYNC_DATA4);
1415                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, SYNC_DATA5);
1416                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, SYNC_DATA6);
1417                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, SYNC_DATA7);
1418                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, SYNC_DATA8);
1419                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, SYNC_DATA9);
1420                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, SYNC_DATA10);
1421                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC1);
1422                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC2);
1423                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC3);
1424                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC4);
1425                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC5);
1426                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC6);
1427                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC7);
1428                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC8);
1429                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC9);
1430                DatabaseUtils.cursorStringToContentValuesIfPresent(cursor, cv, CAL_SYNC10);
1431
1432                Entity entity = new Entity(cv);
1433                Cursor subCursor;
1434                if (mResolver != null) {
1435                    subCursor = mResolver.query(Reminders.CONTENT_URI, REMINDERS_PROJECTION,
1436                            WHERE_EVENT_ID,
1437                            new String[] { Long.toString(eventId) }  /* selectionArgs */,
1438                            null /* sortOrder */);
1439                } else {
1440                    subCursor = mProvider.query(Reminders.CONTENT_URI, REMINDERS_PROJECTION,
1441                            WHERE_EVENT_ID,
1442                            new String[] { Long.toString(eventId) }  /* selectionArgs */,
1443                            null /* sortOrder */);
1444                }
1445                try {
1446                    while (subCursor.moveToNext()) {
1447                        ContentValues reminderValues = new ContentValues();
1448                        reminderValues.put(Reminders.MINUTES, subCursor.getInt(COLUMN_MINUTES));
1449                        reminderValues.put(Reminders.METHOD, subCursor.getInt(COLUMN_METHOD));
1450                        entity.addSubValue(Reminders.CONTENT_URI, reminderValues);
1451                    }
1452                } finally {
1453                    subCursor.close();
1454                }
1455
1456                if (mResolver != null) {
1457                    subCursor = mResolver.query(Attendees.CONTENT_URI, ATTENDEES_PROJECTION,
1458                            WHERE_EVENT_ID,
1459                            new String[] { Long.toString(eventId) } /* selectionArgs */,
1460                            null /* sortOrder */);
1461                } else {
1462                    subCursor = mProvider.query(Attendees.CONTENT_URI, ATTENDEES_PROJECTION,
1463                            WHERE_EVENT_ID,
1464                            new String[] { Long.toString(eventId) } /* selectionArgs */,
1465                            null /* sortOrder */);
1466                }
1467                try {
1468                    while (subCursor.moveToNext()) {
1469                        ContentValues attendeeValues = new ContentValues();
1470                        attendeeValues.put(Attendees.ATTENDEE_NAME,
1471                                subCursor.getString(COLUMN_ATTENDEE_NAME));
1472                        attendeeValues.put(Attendees.ATTENDEE_EMAIL,
1473                                subCursor.getString(COLUMN_ATTENDEE_EMAIL));
1474                        attendeeValues.put(Attendees.ATTENDEE_RELATIONSHIP,
1475                                subCursor.getInt(COLUMN_ATTENDEE_RELATIONSHIP));
1476                        attendeeValues.put(Attendees.ATTENDEE_TYPE,
1477                                subCursor.getInt(COLUMN_ATTENDEE_TYPE));
1478                        attendeeValues.put(Attendees.ATTENDEE_STATUS,
1479                                subCursor.getInt(COLUMN_ATTENDEE_STATUS));
1480                        attendeeValues.put(Attendees.ATTENDEE_IDENTITY,
1481                                subCursor.getString(COLUMN_ATTENDEE_IDENTITY));
1482                        attendeeValues.put(Attendees.ATTENDEE_ID_NAMESPACE,
1483                                subCursor.getString(COLUMN_ATTENDEE_ID_NAMESPACE));
1484                        entity.addSubValue(Attendees.CONTENT_URI, attendeeValues);
1485                    }
1486                } finally {
1487                    subCursor.close();
1488                }
1489
1490                if (mResolver != null) {
1491                    subCursor = mResolver.query(ExtendedProperties.CONTENT_URI, EXTENDED_PROJECTION,
1492                            WHERE_EVENT_ID,
1493                            new String[] { Long.toString(eventId) } /* selectionArgs */,
1494                            null /* sortOrder */);
1495                } else {
1496                    subCursor = mProvider.query(ExtendedProperties.CONTENT_URI, EXTENDED_PROJECTION,
1497                            WHERE_EVENT_ID,
1498                            new String[] { Long.toString(eventId) } /* selectionArgs */,
1499                            null /* sortOrder */);
1500                }
1501                try {
1502                    while (subCursor.moveToNext()) {
1503                        ContentValues extendedValues = new ContentValues();
1504                        extendedValues.put(ExtendedProperties._ID,
1505                                subCursor.getString(COLUMN_ID));
1506                        extendedValues.put(ExtendedProperties.NAME,
1507                                subCursor.getString(COLUMN_NAME));
1508                        extendedValues.put(ExtendedProperties.VALUE,
1509                                subCursor.getString(COLUMN_VALUE));
1510                        entity.addSubValue(ExtendedProperties.CONTENT_URI, extendedValues);
1511                    }
1512                } finally {
1513                    subCursor.close();
1514                }
1515
1516                cursor.moveToNext();
1517                return entity;
1518            }
1519        }
1520    }
1521
1522    /**
1523     * Constants and helpers for the Events table, which contains details for
1524     * individual events. <h3>Operations</h3> All operations can be done either
1525     * as an app or as a sync adapter. To perform an operation as a sync adapter
1526     * {@link #CALLER_IS_SYNCADAPTER} should be set to true and
1527     * {@link #ACCOUNT_NAME} and {@link #ACCOUNT_TYPE} must be set in the Uri
1528     * parameters. See
1529     * {@link Uri.Builder#appendQueryParameter(java.lang.String, java.lang.String)}
1530     * for details on adding parameters. Sync adapters have write access to more
1531     * columns but are restricted to a single account at a time.
1532     * <dl>
1533     * <dt><b>Insert</b></dt>
1534     * <dd>When inserting a new event the following fields must be included:
1535     * <ul>
1536     * <li>dtstart</li>
1537     * <li>dtend if the event is non-recurring</li>
1538     * <li>duration if the event is recurring</li>
1539     * <li>rrule or rdate if the event is recurring</li>
1540     * <li>eventTimezone</li>
1541     * <li>a calendar_id</li>
1542     * </ul>
1543     * There are also further requirements when inserting or updating an event.
1544     * See the section on Writing to Events.</dd>
1545     * <dt><b>Update</b></dt>
1546     * <dd>To perform an update of an Event the {@link Events#_ID} of the event
1547     * should be provided either as an appended id to the Uri (
1548     * {@link ContentUris#withAppendedId}) or as the first selection item--the
1549     * selection should start with "_id=?" and the first selectionArg should be
1550     * the _id of the event. Updates may also be done using a selection and no
1551     * id. Updating an event must respect the same rules as inserting and is
1552     * further restricted in the fields that can be written. See the section on
1553     * Writing to Events.</dd>
1554     * <dt><b>Delete</b></dt>
1555     * <dd>Events can be deleted either by the {@link Events#_ID} as an appended
1556     * id on the Uri or using any standard selection. If an appended id is used
1557     * a selection is not allowed. There are two versions of delete: as an app
1558     * and as a sync adapter. An app delete will set the deleted column on an
1559     * event and remove all instances of that event. A sync adapter delete will
1560     * remove the event from the database and all associated data.</dd>
1561     * <dt><b>Query</b></dt>
1562     * <dd>Querying the Events table will get you all information about a set of
1563     * events except their reminders, attendees, and extended properties. There
1564     * will be one row returned for each event that matches the query selection,
1565     * or at most a single row if the {@link Events#_ID} is appended to the Uri.
1566     * Recurring events will only return a single row regardless of the number
1567     * of times that event repeats.</dd>
1568     * </dl>
1569     * <h3>Writing to Events</h3> There are further restrictions on all Updates
1570     * and Inserts in the Events table:
1571     * <ul>
1572     * <li>If allDay is set to 1 eventTimezone must be {@link Time#TIMEZONE_UTC}
1573     * and the time must correspond to a midnight boundary.</li>
1574     * <li>Exceptions are not allowed to recur. If rrule or rdate is not empty,
1575     * original_id and original_sync_id must be empty.</li>
1576     * <li>In general a calendar_id should not be modified after insertion. This
1577     * is not explicitly forbidden but many sync adapters will not behave in an
1578     * expected way if the calendar_id is modified.</li>
1579     * </ul>
1580     * The following Events columns are writable by both an app and a sync
1581     * adapter.
1582     * <ul>
1583     * <li>{@link #CALENDAR_ID}</li>
1584     * <li>{@link #ORGANIZER}</li>
1585     * <li>{@link #TITLE}</li>
1586     * <li>{@link #EVENT_LOCATION}</li>
1587     * <li>{@link #DESCRIPTION}</li>
1588     * <li>{@link #EVENT_COLOR}</li>
1589     * <li>{@link #DTSTART}</li>
1590     * <li>{@link #DTEND}</li>
1591     * <li>{@link #EVENT_TIMEZONE}</li>
1592     * <li>{@link #EVENT_END_TIMEZONE}</li>
1593     * <li>{@link #DURATION}</li>
1594     * <li>{@link #ALL_DAY}</li>
1595     * <li>{@link #RRULE}</li>
1596     * <li>{@link #RDATE}</li>
1597     * <li>{@link #EXRULE}</li>
1598     * <li>{@link #EXDATE}</li>
1599     * <li>{@link #ORIGINAL_ID}</li>
1600     * <li>{@link #ORIGINAL_SYNC_ID}</li>
1601     * <li>{@link #ORIGINAL_INSTANCE_TIME}</li>
1602     * <li>{@link #ORIGINAL_ALL_DAY}</li>
1603     * <li>{@link #ACCESS_LEVEL}</li>
1604     * <li>{@link #AVAILABILITY}</li>
1605     * <li>{@link #GUESTS_CAN_MODIFY}</li>
1606     * <li>{@link #GUESTS_CAN_INVITE_OTHERS}</li>
1607     * <li>{@link #GUESTS_CAN_SEE_GUESTS}</li>
1608     * <li>{@link #CUSTOM_APP_PACKAGE}</li>
1609     * <li>{@link #CUSTOM_APP_URI}</li>
1610     * <li>{@link #UID_2445}</li>
1611     * </ul>
1612     * The following Events columns are writable only by a sync adapter
1613     * <ul>
1614     * <li>{@link #DIRTY}</li>
1615     * <li>{@link #MUTATORS}</li>
1616     * <li>{@link #_SYNC_ID}</li>
1617     * <li>{@link #SYNC_DATA1}</li>
1618     * <li>{@link #SYNC_DATA2}</li>
1619     * <li>{@link #SYNC_DATA3}</li>
1620     * <li>{@link #SYNC_DATA4}</li>
1621     * <li>{@link #SYNC_DATA5}</li>
1622     * <li>{@link #SYNC_DATA6}</li>
1623     * <li>{@link #SYNC_DATA7}</li>
1624     * <li>{@link #SYNC_DATA8}</li>
1625     * <li>{@link #SYNC_DATA9}</li>
1626     * <li>{@link #SYNC_DATA10}</li>
1627     * </ul>
1628     * The remaining columns are either updated by the provider only or are
1629     * views into other tables and cannot be changed through the Events table.
1630     */
1631    public static final class Events implements BaseColumns, SyncColumns, EventsColumns,
1632            CalendarColumns {
1633
1634        /**
1635         * The content:// style URL for interacting with events. Appending an
1636         * event id using {@link ContentUris#withAppendedId(Uri, long)} will
1637         * specify a single event.
1638         */
1639        @SuppressWarnings("hiding")
1640        public static final Uri CONTENT_URI =
1641                Uri.parse("content://" + AUTHORITY + "/events");
1642
1643        /**
1644         * The content:// style URI for recurring event exceptions.  Insertions require an
1645         * appended event ID.  Deletion of exceptions requires both the original event ID and
1646         * the exception event ID (see {@link Uri.Builder#appendPath}).
1647         */
1648        public static final Uri CONTENT_EXCEPTION_URI =
1649                Uri.parse("content://" + AUTHORITY + "/exception");
1650
1651        /**
1652         * This utility class cannot be instantiated
1653         */
1654        private Events() {}
1655
1656        /**
1657         * The default sort order for this table
1658         */
1659        private static final String DEFAULT_SORT_ORDER = "";
1660
1661        /**
1662         * These are columns that should only ever be updated by the provider,
1663         * either because they are views mapped to another table or because they
1664         * are used for provider only functionality. TODO move to provider
1665         *
1666         * @hide
1667         */
1668        public static String[] PROVIDER_WRITABLE_COLUMNS = new String[] {
1669                ACCOUNT_NAME,
1670                ACCOUNT_TYPE,
1671                CAL_SYNC1,
1672                CAL_SYNC2,
1673                CAL_SYNC3,
1674                CAL_SYNC4,
1675                CAL_SYNC5,
1676                CAL_SYNC6,
1677                CAL_SYNC7,
1678                CAL_SYNC8,
1679                CAL_SYNC9,
1680                CAL_SYNC10,
1681                ALLOWED_REMINDERS,
1682                ALLOWED_ATTENDEE_TYPES,
1683                ALLOWED_AVAILABILITY,
1684                CALENDAR_ACCESS_LEVEL,
1685                CALENDAR_COLOR,
1686                CALENDAR_TIME_ZONE,
1687                CAN_MODIFY_TIME_ZONE,
1688                CAN_ORGANIZER_RESPOND,
1689                CALENDAR_DISPLAY_NAME,
1690                CAN_PARTIALLY_UPDATE,
1691                SYNC_EVENTS,
1692                VISIBLE,
1693        };
1694
1695        /**
1696         * These fields are only writable by a sync adapter. To modify them the
1697         * caller must include CALLER_IS_SYNCADAPTER, _SYNC_ACCOUNT, and
1698         * _SYNC_ACCOUNT_TYPE in the query parameters. TODO move to provider.
1699         *
1700         * @hide
1701         */
1702        public static final String[] SYNC_WRITABLE_COLUMNS = new String[] {
1703            _SYNC_ID,
1704            DIRTY,
1705            MUTATORS,
1706            SYNC_DATA1,
1707            SYNC_DATA2,
1708            SYNC_DATA3,
1709            SYNC_DATA4,
1710            SYNC_DATA5,
1711            SYNC_DATA6,
1712            SYNC_DATA7,
1713            SYNC_DATA8,
1714            SYNC_DATA9,
1715            SYNC_DATA10,
1716        };
1717    }
1718
1719    /**
1720     * Fields and helpers for interacting with Instances. An instance is a
1721     * single occurrence of an event including time zone specific start and end
1722     * days and minutes. The instances table is not writable and only provides a
1723     * way to query event occurrences.
1724     */
1725    public static final class Instances implements BaseColumns, EventsColumns, CalendarColumns {
1726
1727        private static final String WHERE_CALENDARS_SELECTED = Calendars.VISIBLE + "=?";
1728        private static final String[] WHERE_CALENDARS_ARGS = {
1729            "1"
1730        };
1731
1732        /**
1733         * This utility class cannot be instantiated
1734         */
1735        private Instances() {}
1736
1737        /**
1738         * Performs a query to return all visible instances in the given range.
1739         * This is a blocking function and should not be done on the UI thread.
1740         * This will cause an expansion of recurring events to fill this time
1741         * range if they are not already expanded and will slow down for larger
1742         * time ranges with many recurring events.
1743         *
1744         * @param cr The ContentResolver to use for the query
1745         * @param projection The columns to return
1746         * @param begin The start of the time range to query in UTC millis since
1747         *            epoch
1748         * @param end The end of the time range to query in UTC millis since
1749         *            epoch
1750         * @return A Cursor containing all instances in the given range
1751         */
1752        public static final Cursor query(ContentResolver cr, String[] projection,
1753                                         long begin, long end) {
1754            Uri.Builder builder = CONTENT_URI.buildUpon();
1755            ContentUris.appendId(builder, begin);
1756            ContentUris.appendId(builder, end);
1757            return cr.query(builder.build(), projection, WHERE_CALENDARS_SELECTED,
1758                    WHERE_CALENDARS_ARGS, DEFAULT_SORT_ORDER);
1759        }
1760
1761        /**
1762         * Performs a query to return all visible instances in the given range
1763         * that match the given query. This is a blocking function and should
1764         * not be done on the UI thread. This will cause an expansion of
1765         * recurring events to fill this time range if they are not already
1766         * expanded and will slow down for larger time ranges with many
1767         * recurring events.
1768         *
1769         * @param cr The ContentResolver to use for the query
1770         * @param projection The columns to return
1771         * @param begin The start of the time range to query in UTC millis since
1772         *            epoch
1773         * @param end The end of the time range to query in UTC millis since
1774         *            epoch
1775         * @param searchQuery A string of space separated search terms. Segments
1776         *            enclosed by double quotes will be treated as a single
1777         *            term.
1778         * @return A Cursor of instances matching the search terms in the given
1779         *         time range
1780         */
1781        public static final Cursor query(ContentResolver cr, String[] projection,
1782                                         long begin, long end, String searchQuery) {
1783            Uri.Builder builder = CONTENT_SEARCH_URI.buildUpon();
1784            ContentUris.appendId(builder, begin);
1785            ContentUris.appendId(builder, end);
1786            builder = builder.appendPath(searchQuery);
1787            return cr.query(builder.build(), projection, WHERE_CALENDARS_SELECTED,
1788                    WHERE_CALENDARS_ARGS, DEFAULT_SORT_ORDER);
1789        }
1790
1791        /**
1792         * The content:// style URL for querying an instance range. The begin
1793         * and end of the range to query should be added as path segments if
1794         * this is used directly.
1795         */
1796        @SuppressWarnings("hiding")
1797        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY +
1798                "/instances/when");
1799        /**
1800         * The content:// style URL for querying an instance range by Julian
1801         * Day. The start and end day should be added as path segments if this
1802         * is used directly.
1803         */
1804        public static final Uri CONTENT_BY_DAY_URI =
1805            Uri.parse("content://" + AUTHORITY + "/instances/whenbyday");
1806        /**
1807         * The content:// style URL for querying an instance range with a search
1808         * term. The begin, end, and search string should be appended as path
1809         * segments if this is used directly.
1810         */
1811        public static final Uri CONTENT_SEARCH_URI = Uri.parse("content://" + AUTHORITY +
1812                "/instances/search");
1813        /**
1814         * The content:// style URL for querying an instance range with a search
1815         * term. The start day, end day, and search string should be appended as
1816         * path segments if this is used directly.
1817         */
1818        public static final Uri CONTENT_SEARCH_BY_DAY_URI =
1819            Uri.parse("content://" + AUTHORITY + "/instances/searchbyday");
1820
1821        /**
1822         * The default sort order for this table.
1823         */
1824        private static final String DEFAULT_SORT_ORDER = "begin ASC";
1825
1826        /**
1827         * The beginning time of the instance, in UTC milliseconds. Column name.
1828         * <P>Type: INTEGER (long; millis since epoch)</P>
1829         */
1830        public static final String BEGIN = "begin";
1831
1832        /**
1833         * The ending time of the instance, in UTC milliseconds. Column name.
1834         * <P>Type: INTEGER (long; millis since epoch)</P>
1835         */
1836        public static final String END = "end";
1837
1838        /**
1839         * The _id of the event for this instance. Column name.
1840         * <P>Type: INTEGER (long, foreign key to the Events table)</P>
1841         */
1842        public static final String EVENT_ID = "event_id";
1843
1844        /**
1845         * The Julian start day of the instance, relative to the local time
1846         * zone. Column name.
1847         * <P>Type: INTEGER (int)</P>
1848         */
1849        public static final String START_DAY = "startDay";
1850
1851        /**
1852         * The Julian end day of the instance, relative to the local time
1853         * zone. Column name.
1854         * <P>Type: INTEGER (int)</P>
1855         */
1856        public static final String END_DAY = "endDay";
1857
1858        /**
1859         * The start minute of the instance measured from midnight in the
1860         * local time zone. Column name.
1861         * <P>Type: INTEGER (int)</P>
1862         */
1863        public static final String START_MINUTE = "startMinute";
1864
1865        /**
1866         * The end minute of the instance measured from midnight in the
1867         * local time zone. Column name.
1868         * <P>Type: INTEGER (int)</P>
1869         */
1870        public static final String END_MINUTE = "endMinute";
1871    }
1872
1873    protected interface CalendarCacheColumns {
1874        /**
1875         * The key for the setting. Keys are defined in {@link CalendarCache}.
1876         */
1877        public static final String KEY = "key";
1878
1879        /**
1880         * The value of the given setting.
1881         */
1882        public static final String VALUE = "value";
1883    }
1884
1885    /**
1886     * CalendarCache stores some settings for calendar including the current
1887     * time zone for the instances. These settings are stored using a key/value
1888     * scheme. A {@link #KEY} must be specified when updating these values.
1889     */
1890    public static final class CalendarCache implements CalendarCacheColumns {
1891        /**
1892         * The URI to use for retrieving the properties from the Calendar db.
1893         */
1894        public static final Uri URI =
1895                Uri.parse("content://" + AUTHORITY + "/properties");
1896
1897        /**
1898         * This utility class cannot be instantiated
1899         */
1900        private CalendarCache() {}
1901
1902        /**
1903         * They key for updating the use of auto/home time zones in Calendar.
1904         * Valid values are {@link #TIMEZONE_TYPE_AUTO} or
1905         * {@link #TIMEZONE_TYPE_HOME}.
1906         */
1907        public static final String KEY_TIMEZONE_TYPE = "timezoneType";
1908
1909        /**
1910         * The key for updating the time zone used by the provider when it
1911         * generates the instances table. This should only be written if the
1912         * type is set to {@link #TIMEZONE_TYPE_HOME}. A valid time zone id
1913         * should be written to this field.
1914         */
1915        public static final String KEY_TIMEZONE_INSTANCES = "timezoneInstances";
1916
1917        /**
1918         * The key for reading the last time zone set by the user. This should
1919         * only be read by apps and it will be automatically updated whenever
1920         * {@link #KEY_TIMEZONE_INSTANCES} is updated with
1921         * {@link #TIMEZONE_TYPE_HOME} set.
1922         */
1923        public static final String KEY_TIMEZONE_INSTANCES_PREVIOUS = "timezoneInstancesPrevious";
1924
1925        /**
1926         * The value to write to {@link #KEY_TIMEZONE_TYPE} if the provider
1927         * should stay in sync with the device's time zone.
1928         */
1929        public static final String TIMEZONE_TYPE_AUTO = "auto";
1930
1931        /**
1932         * The value to write to {@link #KEY_TIMEZONE_TYPE} if the provider
1933         * should use a fixed time zone set by the user.
1934         */
1935        public static final String TIMEZONE_TYPE_HOME = "home";
1936    }
1937
1938    /**
1939     * A few Calendar globals are needed in the CalendarProvider for expanding
1940     * the Instances table and these are all stored in the first (and only) row
1941     * of the CalendarMetaData table.
1942     *
1943     * @hide
1944     */
1945    protected interface CalendarMetaDataColumns {
1946        /**
1947         * The local timezone that was used for precomputing the fields
1948         * in the Instances table.
1949         */
1950        public static final String LOCAL_TIMEZONE = "localTimezone";
1951
1952        /**
1953         * The minimum time used in expanding the Instances table,
1954         * in UTC milliseconds.
1955         * <P>Type: INTEGER</P>
1956         */
1957        public static final String MIN_INSTANCE = "minInstance";
1958
1959        /**
1960         * The maximum time used in expanding the Instances table,
1961         * in UTC milliseconds.
1962         * <P>Type: INTEGER</P>
1963         */
1964        public static final String MAX_INSTANCE = "maxInstance";
1965
1966        /**
1967         * The minimum Julian day in the EventDays table.
1968         * <P>Type: INTEGER</P>
1969         */
1970        public static final String MIN_EVENTDAYS = "minEventDays";
1971
1972        /**
1973         * The maximum Julian day in the EventDays table.
1974         * <P>Type: INTEGER</P>
1975         */
1976        public static final String MAX_EVENTDAYS = "maxEventDays";
1977    }
1978
1979    /**
1980     * @hide
1981     */
1982    public static final class CalendarMetaData implements CalendarMetaDataColumns, BaseColumns {
1983
1984        /**
1985         * This utility class cannot be instantiated
1986         */
1987        private CalendarMetaData() {}
1988    }
1989
1990    protected interface EventDaysColumns {
1991        /**
1992         * The Julian starting day number. Column name.
1993         * <P>Type: INTEGER (int)</P>
1994         */
1995        public static final String STARTDAY = "startDay";
1996        /**
1997         * The Julian ending day number. Column name.
1998         * <P>Type: INTEGER (int)</P>
1999         */
2000        public static final String ENDDAY = "endDay";
2001
2002    }
2003
2004    /**
2005     * Fields and helpers for querying for a list of days that contain events.
2006     */
2007    public static final class EventDays implements EventDaysColumns {
2008        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
2009                + "/instances/groupbyday");
2010        private static final String SELECTION = "selected=1";
2011
2012        /**
2013         * This utility class cannot be instantiated
2014         */
2015        private EventDays() {}
2016
2017        /**
2018         * Retrieves the days with events for the Julian days starting at
2019         * "startDay" for "numDays". It returns a cursor containing startday and
2020         * endday representing the max range of days for all events beginning on
2021         * each startday.This is a blocking function and should not be done on
2022         * the UI thread.
2023         *
2024         * @param cr the ContentResolver
2025         * @param startDay the first Julian day in the range
2026         * @param numDays the number of days to load (must be at least 1)
2027         * @param projection the columns to return in the cursor
2028         * @return a database cursor containing a list of start and end days for
2029         *         events
2030         */
2031        public static final Cursor query(ContentResolver cr, int startDay, int numDays,
2032                String[] projection) {
2033            if (numDays < 1) {
2034                return null;
2035            }
2036            int endDay = startDay + numDays - 1;
2037            Uri.Builder builder = CONTENT_URI.buildUpon();
2038            ContentUris.appendId(builder, startDay);
2039            ContentUris.appendId(builder, endDay);
2040            return cr.query(builder.build(), projection, SELECTION,
2041                    null /* selection args */, STARTDAY);
2042        }
2043    }
2044
2045    protected interface RemindersColumns {
2046        /**
2047         * The event the reminder belongs to. Column name.
2048         * <P>Type: INTEGER (foreign key to the Events table)</P>
2049         */
2050        public static final String EVENT_ID = "event_id";
2051
2052        /**
2053         * The minutes prior to the event that the alarm should ring.  -1
2054         * specifies that we should use the default value for the system.
2055         * Column name.
2056         * <P>Type: INTEGER</P>
2057         */
2058        public static final String MINUTES = "minutes";
2059
2060        /**
2061         * Passing this as a minutes value will use the default reminder
2062         * minutes.
2063         */
2064        public static final int MINUTES_DEFAULT = -1;
2065
2066        /**
2067         * The alarm method, as set on the server. {@link #METHOD_DEFAULT},
2068         * {@link #METHOD_ALERT}, {@link #METHOD_EMAIL}, {@link #METHOD_SMS} and
2069         * {@link #METHOD_ALARM} are possible values; the device will only
2070         * process {@link #METHOD_DEFAULT} and {@link #METHOD_ALERT} reminders
2071         * (the other types are simply stored so we can send the same reminder
2072         * info back to the server when we make changes).
2073         */
2074        public static final String METHOD = "method";
2075
2076        public static final int METHOD_DEFAULT = 0;
2077        public static final int METHOD_ALERT = 1;
2078        public static final int METHOD_EMAIL = 2;
2079        public static final int METHOD_SMS = 3;
2080        public static final int METHOD_ALARM = 4;
2081    }
2082
2083    /**
2084     * Fields and helpers for accessing reminders for an event. Each row of this
2085     * table represents a single reminder for an event. Calling
2086     * {@link #query(ContentResolver, long, String[])} will return a list of reminders for
2087     * the event with the given eventId. Both apps and sync adapters may write
2088     * to this table. There are three writable fields and all of them must be
2089     * included when inserting a new reminder. They are:
2090     * <ul>
2091     * <li>{@link #EVENT_ID}</li>
2092     * <li>{@link #MINUTES}</li>
2093     * <li>{@link #METHOD}</li>
2094     * </ul>
2095     */
2096    public static final class Reminders implements BaseColumns, RemindersColumns, EventsColumns {
2097        private static final String REMINDERS_WHERE = CalendarContract.Reminders.EVENT_ID + "=?";
2098        @SuppressWarnings("hiding")
2099        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/reminders");
2100
2101        /**
2102         * This utility class cannot be instantiated
2103         */
2104        private Reminders() {}
2105
2106        /**
2107         * Queries all reminders associated with the given event. This is a
2108         * blocking call and should not be done on the UI thread.
2109         *
2110         * @param cr The content resolver to use for the query
2111         * @param eventId The id of the event to retrieve reminders for
2112         * @param projection the columns to return in the cursor
2113         * @return A Cursor containing all reminders for the event
2114         */
2115        public static final Cursor query(ContentResolver cr, long eventId, String[] projection) {
2116            String[] remArgs = {Long.toString(eventId)};
2117            return cr.query(CONTENT_URI, projection, REMINDERS_WHERE, remArgs /*selection args*/,
2118                    null /* sort order */);
2119        }
2120    }
2121
2122    protected interface CalendarAlertsColumns {
2123        /**
2124         * The event that the alert belongs to. Column name.
2125         * <P>Type: INTEGER (foreign key to the Events table)</P>
2126         */
2127        public static final String EVENT_ID = "event_id";
2128
2129        /**
2130         * The start time of the event, in UTC. Column name.
2131         * <P>Type: INTEGER (long; millis since epoch)</P>
2132         */
2133        public static final String BEGIN = "begin";
2134
2135        /**
2136         * The end time of the event, in UTC. Column name.
2137         * <P>Type: INTEGER (long; millis since epoch)</P>
2138         */
2139        public static final String END = "end";
2140
2141        /**
2142         * The alarm time of the event, in UTC. Column name.
2143         * <P>Type: INTEGER (long; millis since epoch)</P>
2144         */
2145        public static final String ALARM_TIME = "alarmTime";
2146
2147        /**
2148         * The creation time of this database entry, in UTC.
2149         * Useful for debugging missed reminders. Column name.
2150         * <P>Type: INTEGER (long; millis since epoch)</P>
2151         */
2152        public static final String CREATION_TIME = "creationTime";
2153
2154        /**
2155         * The time that the alarm broadcast was received by the Calendar app,
2156         * in UTC. Useful for debugging missed reminders. Column name.
2157         * <P>Type: INTEGER (long; millis since epoch)</P>
2158         */
2159        public static final String RECEIVED_TIME = "receivedTime";
2160
2161        /**
2162         * The time that the notification was created by the Calendar app,
2163         * in UTC. Useful for debugging missed reminders. Column name.
2164         * <P>Type: INTEGER (long; millis since epoch)</P>
2165         */
2166        public static final String NOTIFY_TIME = "notifyTime";
2167
2168        /**
2169         * The state of this alert. It starts out as {@link #STATE_SCHEDULED}, then
2170         * when the alarm goes off, it changes to {@link #STATE_FIRED}, and then when
2171         * the user dismisses the alarm it changes to {@link #STATE_DISMISSED}. Column
2172         * name.
2173         * <P>Type: INTEGER</P>
2174         */
2175        public static final String STATE = "state";
2176
2177        /**
2178         * An alert begins in this state when it is first created.
2179         */
2180        public static final int STATE_SCHEDULED = 0;
2181        /**
2182         * After a notification for an alert has been created it should be
2183         * updated to fired.
2184         */
2185        public static final int STATE_FIRED = 1;
2186        /**
2187         * Once the user has dismissed the notification the alert's state should
2188         * be set to dismissed so it is not fired again.
2189         */
2190        public static final int STATE_DISMISSED = 2;
2191
2192        /**
2193         * The number of minutes that this alarm precedes the start time. Column
2194         * name.
2195         * <P>Type: INTEGER</P>
2196         */
2197        public static final String MINUTES = "minutes";
2198
2199        /**
2200         * The default sort order for this alerts queries
2201         */
2202        public static final String DEFAULT_SORT_ORDER = "begin ASC,title ASC";
2203    }
2204
2205    /**
2206     * Fields and helpers for accessing calendar alerts information. These
2207     * fields are for tracking which alerts have been fired. Scheduled alarms
2208     * will generate an intent using {@link #ACTION_EVENT_REMINDER}. Apps that
2209     * receive this action may update the {@link #STATE} for the reminder when
2210     * they have finished handling it. Apps that have their notifications
2211     * disabled should not modify the table to ensure that they do not conflict
2212     * with another app that is generating a notification. In general, apps
2213     * should not need to write to this table directly except to update the
2214     * state of a reminder.
2215     */
2216    public static final class CalendarAlerts implements BaseColumns,
2217            CalendarAlertsColumns, EventsColumns, CalendarColumns {
2218
2219        /**
2220         * @hide
2221         */
2222        public static final String TABLE_NAME = "CalendarAlerts";
2223        /**
2224         * The Uri for querying calendar alert information
2225         */
2226        @SuppressWarnings("hiding")
2227        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY +
2228                "/calendar_alerts");
2229
2230        /**
2231         * This utility class cannot be instantiated
2232         */
2233        private CalendarAlerts() {}
2234
2235        private static final String WHERE_ALARM_EXISTS = EVENT_ID + "=?"
2236                + " AND " + BEGIN + "=?"
2237                + " AND " + ALARM_TIME + "=?";
2238
2239        private static final String WHERE_FINDNEXTALARMTIME = ALARM_TIME + ">=?";
2240        private static final String SORT_ORDER_ALARMTIME_ASC = ALARM_TIME + " ASC";
2241
2242        private static final String WHERE_RESCHEDULE_MISSED_ALARMS = STATE + "=" + STATE_SCHEDULED
2243                + " AND " + ALARM_TIME + "<?"
2244                + " AND " + ALARM_TIME + ">?"
2245                + " AND " + END + ">=?";
2246
2247        /**
2248         * This URI is for grouping the query results by event_id and begin
2249         * time.  This will return one result per instance of an event.  So
2250         * events with multiple alarms will appear just once, but multiple
2251         * instances of a repeating event will show up multiple times.
2252         */
2253        public static final Uri CONTENT_URI_BY_INSTANCE =
2254            Uri.parse("content://" + AUTHORITY + "/calendar_alerts/by_instance");
2255
2256        private static final boolean DEBUG = false;
2257
2258        /**
2259         * Helper for inserting an alarm time associated with an event TODO move
2260         * to Provider
2261         *
2262         * @hide
2263         */
2264        public static final Uri insert(ContentResolver cr, long eventId,
2265                long begin, long end, long alarmTime, int minutes) {
2266            ContentValues values = new ContentValues();
2267            values.put(CalendarAlerts.EVENT_ID, eventId);
2268            values.put(CalendarAlerts.BEGIN, begin);
2269            values.put(CalendarAlerts.END, end);
2270            values.put(CalendarAlerts.ALARM_TIME, alarmTime);
2271            long currentTime = System.currentTimeMillis();
2272            values.put(CalendarAlerts.CREATION_TIME, currentTime);
2273            values.put(CalendarAlerts.RECEIVED_TIME, 0);
2274            values.put(CalendarAlerts.NOTIFY_TIME, 0);
2275            values.put(CalendarAlerts.STATE, STATE_SCHEDULED);
2276            values.put(CalendarAlerts.MINUTES, minutes);
2277            return cr.insert(CONTENT_URI, values);
2278        }
2279
2280        /**
2281         * Finds the next alarm after (or equal to) the given time and returns
2282         * the time of that alarm or -1 if no such alarm exists. This is a
2283         * blocking call and should not be done on the UI thread. TODO move to
2284         * provider
2285         *
2286         * @param cr the ContentResolver
2287         * @param millis the time in UTC milliseconds
2288         * @return the next alarm time greater than or equal to "millis", or -1
2289         *         if no such alarm exists.
2290         * @hide
2291         */
2292        public static final long findNextAlarmTime(ContentResolver cr, long millis) {
2293            String selection = ALARM_TIME + ">=" + millis;
2294            // TODO: construct an explicit SQL query so that we can add
2295            // "LIMIT 1" to the end and get just one result.
2296            String[] projection = new String[] { ALARM_TIME };
2297            Cursor cursor = cr.query(CONTENT_URI, projection, WHERE_FINDNEXTALARMTIME,
2298                    (new String[] {
2299                        Long.toString(millis)
2300                    }), SORT_ORDER_ALARMTIME_ASC);
2301            long alarmTime = -1;
2302            try {
2303                if (cursor != null && cursor.moveToFirst()) {
2304                    alarmTime = cursor.getLong(0);
2305                }
2306            } finally {
2307                if (cursor != null) {
2308                    cursor.close();
2309                }
2310            }
2311            return alarmTime;
2312        }
2313
2314        /**
2315         * Searches the CalendarAlerts table for alarms that should have fired
2316         * but have not and then reschedules them. This method can be called at
2317         * boot time to restore alarms that may have been lost due to a phone
2318         * reboot. TODO move to provider
2319         *
2320         * @param cr the ContentResolver
2321         * @param context the Context
2322         * @param manager the AlarmManager
2323         * @hide
2324         */
2325        public static final void rescheduleMissedAlarms(ContentResolver cr,
2326                Context context, AlarmManager manager) {
2327            // Get all the alerts that have been scheduled but have not fired
2328            // and should have fired by now and are not too old.
2329            long now = System.currentTimeMillis();
2330            long ancient = now - DateUtils.DAY_IN_MILLIS;
2331            String[] projection = new String[] {
2332                    ALARM_TIME,
2333            };
2334
2335            // TODO: construct an explicit SQL query so that we can add
2336            // "GROUPBY" instead of doing a sort and de-dup
2337            Cursor cursor = cr.query(CalendarAlerts.CONTENT_URI, projection,
2338                    WHERE_RESCHEDULE_MISSED_ALARMS, (new String[] {
2339                            Long.toString(now), Long.toString(ancient), Long.toString(now)
2340                    }), SORT_ORDER_ALARMTIME_ASC);
2341            if (cursor == null) {
2342                return;
2343            }
2344
2345            if (DEBUG) {
2346                Log.d(TAG, "missed alarms found: " + cursor.getCount());
2347            }
2348
2349            try {
2350                long alarmTime = -1;
2351
2352                while (cursor.moveToNext()) {
2353                    long newAlarmTime = cursor.getLong(0);
2354                    if (alarmTime != newAlarmTime) {
2355                        if (DEBUG) {
2356                            Log.w(TAG, "rescheduling missed alarm. alarmTime: " + newAlarmTime);
2357                        }
2358                        scheduleAlarm(context, manager, newAlarmTime);
2359                        alarmTime = newAlarmTime;
2360                    }
2361                }
2362            } finally {
2363                cursor.close();
2364            }
2365        }
2366
2367        /**
2368         * Schedules an alarm intent with the system AlarmManager that will
2369         * notify listeners when a reminder should be fired. The provider will
2370         * keep scheduled reminders up to date but apps may use this to
2371         * implement snooze functionality without modifying the reminders table.
2372         * Scheduled alarms will generate an intent using
2373         * {@link #ACTION_EVENT_REMINDER}. TODO Move to provider
2374         *
2375         * @param context A context for referencing system resources
2376         * @param manager The AlarmManager to use or null
2377         * @param alarmTime The time to fire the intent in UTC millis since
2378         *            epoch
2379         * @hide
2380         */
2381        public static void scheduleAlarm(Context context, AlarmManager manager, long alarmTime) {
2382            if (DEBUG) {
2383                Time time = new Time();
2384                time.set(alarmTime);
2385                String schedTime = time.format(" %a, %b %d, %Y %I:%M%P");
2386                Log.d(TAG, "Schedule alarm at " + alarmTime + " " + schedTime);
2387            }
2388
2389            if (manager == null) {
2390                manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
2391            }
2392
2393            Intent intent = new Intent(ACTION_EVENT_REMINDER);
2394            intent.setData(ContentUris.withAppendedId(CalendarContract.CONTENT_URI, alarmTime));
2395            intent.putExtra(ALARM_TIME, alarmTime);
2396            PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
2397            manager.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
2398        }
2399
2400        /**
2401         * Searches for an entry in the CalendarAlerts table that matches the
2402         * given event id, begin time and alarm time. If one is found then this
2403         * alarm already exists and this method returns true. TODO Move to
2404         * provider
2405         *
2406         * @param cr the ContentResolver
2407         * @param eventId the event id to match
2408         * @param begin the start time of the event in UTC millis
2409         * @param alarmTime the alarm time of the event in UTC millis
2410         * @return true if there is already an alarm for the given event with
2411         *         the same start time and alarm time.
2412         * @hide
2413         */
2414        public static final boolean alarmExists(ContentResolver cr, long eventId,
2415                long begin, long alarmTime) {
2416            // TODO: construct an explicit SQL query so that we can add
2417            // "LIMIT 1" to the end and get just one result.
2418            String[] projection = new String[] { ALARM_TIME };
2419            Cursor cursor = cr.query(CONTENT_URI, projection, WHERE_ALARM_EXISTS,
2420                    (new String[] {
2421                            Long.toString(eventId), Long.toString(begin), Long.toString(alarmTime)
2422                    }), null);
2423            boolean found = false;
2424            try {
2425                if (cursor != null && cursor.getCount() > 0) {
2426                    found = true;
2427                }
2428            } finally {
2429                if (cursor != null) {
2430                    cursor.close();
2431                }
2432            }
2433            return found;
2434        }
2435    }
2436
2437    protected interface ColorsColumns extends SyncStateContract.Columns {
2438
2439        /**
2440         * The type of color, which describes how it should be used. Valid types
2441         * are {@link #TYPE_CALENDAR} and {@link #TYPE_EVENT}. Column name.
2442         * <P>
2443         * Type: INTEGER (NOT NULL)
2444         * </P>
2445         */
2446        public static final String COLOR_TYPE = "color_type";
2447
2448        /**
2449         * This indicateds a color that can be used for calendars.
2450         */
2451        public static final int TYPE_CALENDAR = 0;
2452        /**
2453         * This indicates a color that can be used for events.
2454         */
2455        public static final int TYPE_EVENT = 1;
2456
2457        /**
2458         * The key used to reference this color. This can be any non-empty
2459         * string, but must be unique for a given {@link #ACCOUNT_TYPE} and
2460         * {@link #ACCOUNT_NAME}. Column name.
2461         * <P>
2462         * Type: TEXT
2463         * </P>
2464         */
2465        public static final String COLOR_KEY = "color_index";
2466
2467        /**
2468         * The color as an 8-bit ARGB integer value. Colors should specify alpha
2469         * as fully opaque (eg 0xFF993322) as the alpha may be ignored or
2470         * modified for display. It is reccomended that colors be usable with
2471         * light (near white) text. Apps should not depend on that assumption,
2472         * however. Column name.
2473         * <P>
2474         * Type: INTEGER (NOT NULL)
2475         * </P>
2476         */
2477        public static final String COLOR = "color";
2478
2479    }
2480
2481    /**
2482     * Fields for accessing colors available for a given account. Colors are
2483     * referenced by {@link #COLOR_KEY} which must be unique for a given
2484     * account name/type. These values can only be updated by the sync
2485     * adapter. Only {@link #COLOR} may be updated after the initial insert. In
2486     * addition, a row can only be deleted once all references to that color
2487     * have been removed from the {@link Calendars} or {@link Events} tables.
2488     */
2489    public static final class Colors implements ColorsColumns {
2490        /**
2491         * @hide
2492         */
2493        public static final String TABLE_NAME = "Colors";
2494        /**
2495         * The Uri for querying color information
2496         */
2497        @SuppressWarnings("hiding")
2498        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/colors");
2499
2500        /**
2501         * This utility class cannot be instantiated
2502         */
2503        private Colors() {
2504        }
2505    }
2506
2507    protected interface ExtendedPropertiesColumns {
2508        /**
2509         * The event the extended property belongs to. Column name.
2510         * <P>Type: INTEGER (foreign key to the Events table)</P>
2511         */
2512        public static final String EVENT_ID = "event_id";
2513
2514        /**
2515         * The name of the extended property.  This is a uri of the form
2516         * {scheme}#{local-name} convention. Column name.
2517         * <P>Type: TEXT</P>
2518         */
2519        public static final String NAME = "name";
2520
2521        /**
2522         * The value of the extended property. Column name.
2523         * <P>Type: TEXT</P>
2524         */
2525        public static final String VALUE = "value";
2526    }
2527
2528    /**
2529     * Fields for accessing the Extended Properties. This is a generic set of
2530     * name/value pairs for use by sync adapters to add extra
2531     * information to events. There are three writable columns and all three
2532     * must be present when inserting a new value. They are:
2533     * <ul>
2534     * <li>{@link #EVENT_ID}</li>
2535     * <li>{@link #NAME}</li>
2536     * <li>{@link #VALUE}</li>
2537     * </ul>
2538     */
2539   public static final class ExtendedProperties implements BaseColumns,
2540            ExtendedPropertiesColumns, EventsColumns {
2541        public static final Uri CONTENT_URI =
2542                Uri.parse("content://" + AUTHORITY + "/extendedproperties");
2543
2544        /**
2545         * This utility class cannot be instantiated
2546         */
2547        private ExtendedProperties() {}
2548
2549        // TODO: fill out this class when we actually start utilizing extendedproperties
2550        // in the calendar application.
2551   }
2552
2553    /**
2554     * A table provided for sync adapters to use for storing private sync state data.
2555     *
2556     * @see SyncStateContract
2557     */
2558    public static final class SyncState implements SyncStateContract.Columns {
2559        /**
2560         * This utility class cannot be instantiated
2561         */
2562        private SyncState() {}
2563
2564        private static final String CONTENT_DIRECTORY =
2565                SyncStateContract.Constants.CONTENT_DIRECTORY;
2566
2567        /**
2568         * The content:// style URI for this table
2569         */
2570        public static final Uri CONTENT_URI =
2571                Uri.withAppendedPath(CalendarContract.CONTENT_URI, CONTENT_DIRECTORY);
2572    }
2573
2574    /**
2575     * Columns from the EventsRawTimes table
2576     *
2577     * @hide
2578     */
2579    protected interface EventsRawTimesColumns {
2580        /**
2581         * The corresponding event id. Column name.
2582         * <P>Type: INTEGER (long)</P>
2583         */
2584        public static final String EVENT_ID = "event_id";
2585
2586        /**
2587         * The RFC2445 compliant time the event starts. Column name.
2588         * <P>Type: TEXT</P>
2589         */
2590        public static final String DTSTART_2445 = "dtstart2445";
2591
2592        /**
2593         * The RFC2445 compliant time the event ends. Column name.
2594         * <P>Type: TEXT</P>
2595         */
2596        public static final String DTEND_2445 = "dtend2445";
2597
2598        /**
2599         * The RFC2445 compliant original instance time of the recurring event
2600         * for which this event is an exception. Column name.
2601         * <P>Type: TEXT</P>
2602         */
2603        public static final String ORIGINAL_INSTANCE_TIME_2445 = "originalInstanceTime2445";
2604
2605        /**
2606         * The RFC2445 compliant last date this event repeats on, or NULL if it
2607         * never ends. Column name.
2608         * <P>Type: TEXT</P>
2609         */
2610        public static final String LAST_DATE_2445 = "lastDate2445";
2611    }
2612
2613    /**
2614     * @hide
2615     */
2616    public static final class EventsRawTimes implements BaseColumns, EventsRawTimesColumns {
2617
2618        /**
2619         * This utility class cannot be instantiated
2620         */
2621        private EventsRawTimes() {}
2622    }
2623}
2624