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