This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
CalendarProvider2.java
5114 lines (4698 loc) · 232 KB
/
CalendarProvider2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** See the License for the specific language governing permissions and
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** limitations under the License.
*/
package com.android.providers.calendar;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.OnAccountsUpdateListener;
import android.app.AppOpsManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.UriMatcher;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.provider.BaseColumns;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.CalendarAlerts;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Colors;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Instances;
import android.provider.CalendarContract.Reminders;
import android.provider.CalendarContract.SyncState;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
import android.util.TimeFormatException;
import android.util.TimeUtils;
import com.android.calendarcommon2.DateException;
import com.android.calendarcommon2.Duration;
import com.android.calendarcommon2.EventRecurrence;
import com.android.calendarcommon2.RecurrenceProcessor;
import com.android.calendarcommon2.RecurrenceSet;
import com.android.providers.calendar.CalendarDatabaseHelper.Tables;
import com.android.providers.calendar.CalendarDatabaseHelper.Views;
import com.google.android.collect.Sets;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Calendar content provider. The contract between this provider and applications
* is defined in {@link android.provider.CalendarContract}.
*/
public class CalendarProvider2 extends SQLiteContentProvider implements OnAccountsUpdateListener {
protected static final String TAG = "CalendarProvider2";
// Turn on for b/22449592
static final boolean DEBUG_INSTANCES = Log.isLoggable(TAG, Log.DEBUG);
private static final String TIMEZONE_GMT = "GMT";
private static final String ACCOUNT_SELECTION_PREFIX = Calendars.ACCOUNT_NAME + "=? AND "
+ Calendars.ACCOUNT_TYPE + "=?";
protected static final boolean PROFILE = false;
private static final boolean MULTIPLE_ATTENDEES_PER_EVENT = true;
private static final String[] ID_ONLY_PROJECTION =
new String[] {Events._ID};
private static final String[] EVENTS_PROJECTION = new String[] {
Events._SYNC_ID,
Events.RRULE,
Events.RDATE,
Events.ORIGINAL_ID,
Events.ORIGINAL_SYNC_ID,
};
private static final int EVENTS_SYNC_ID_INDEX = 0;
private static final int EVENTS_RRULE_INDEX = 1;
private static final int EVENTS_RDATE_INDEX = 2;
private static final int EVENTS_ORIGINAL_ID_INDEX = 3;
private static final int EVENTS_ORIGINAL_SYNC_ID_INDEX = 4;
private static final String[] COLORS_PROJECTION = new String[] {
Colors.ACCOUNT_NAME,
Colors.ACCOUNT_TYPE,
Colors.COLOR_TYPE,
Colors.COLOR_KEY,
Colors.COLOR,
};
private static final int COLORS_ACCOUNT_NAME_INDEX = 0;
private static final int COLORS_ACCOUNT_TYPE_INDEX = 1;
private static final int COLORS_COLOR_TYPE_INDEX = 2;
private static final int COLORS_COLOR_INDEX_INDEX = 3;
private static final int COLORS_COLOR_INDEX = 4;
private static final String COLOR_FULL_SELECTION = Colors.ACCOUNT_NAME + "=? AND "
+ Colors.ACCOUNT_TYPE + "=? AND " + Colors.COLOR_TYPE + "=? AND " + Colors.COLOR_KEY
+ "=?";
private static final String GENERIC_ACCOUNT_NAME = Calendars.ACCOUNT_NAME;
private static final String GENERIC_ACCOUNT_TYPE = Calendars.ACCOUNT_TYPE;
private static final String[] ACCOUNT_PROJECTION = new String[] {
GENERIC_ACCOUNT_NAME,
GENERIC_ACCOUNT_TYPE,
};
private static final int ACCOUNT_NAME_INDEX = 0;
private static final int ACCOUNT_TYPE_INDEX = 1;
// many tables have _id and event_id; pick a representative version to use as our generic
private static final String GENERIC_ID = Attendees._ID;
private static final String GENERIC_EVENT_ID = Attendees.EVENT_ID;
private static final String[] ID_PROJECTION = new String[] {
GENERIC_ID,
GENERIC_EVENT_ID,
};
private static final int ID_INDEX = 0;
private static final int EVENT_ID_INDEX = 1;
/**
* Projection to query for correcting times in allDay events.
*/
private static final String[] ALLDAY_TIME_PROJECTION = new String[] {
Events._ID,
Events.DTSTART,
Events.DTEND,
Events.DURATION
};
private static final int ALLDAY_ID_INDEX = 0;
private static final int ALLDAY_DTSTART_INDEX = 1;
private static final int ALLDAY_DTEND_INDEX = 2;
private static final int ALLDAY_DURATION_INDEX = 3;
private static final int DAY_IN_SECONDS = 24 * 60 * 60;
/**
* The cached copy of the CalendarMetaData database table.
* Make this "package private" instead of "private" so that test code
* can access it.
*/
MetaData mMetaData;
CalendarCache mCalendarCache;
private CalendarDatabaseHelper mDbHelper;
private CalendarInstancesHelper mInstancesHelper;
private static final String SQL_SELECT_EVENTSRAWTIMES = "SELECT " +
CalendarContract.EventsRawTimes.EVENT_ID + ", " +
CalendarContract.EventsRawTimes.DTSTART_2445 + ", " +
CalendarContract.EventsRawTimes.DTEND_2445 + ", " +
Events.EVENT_TIMEZONE +
" FROM " +
Tables.EVENTS_RAW_TIMES + ", " +
Tables.EVENTS +
" WHERE " +
CalendarContract.EventsRawTimes.EVENT_ID + " = " + Tables.EVENTS + "." + Events._ID;
private static final String SQL_UPDATE_EVENT_SET_DIRTY_AND_MUTATORS = "UPDATE " +
Tables.EVENTS + " SET " +
Events.DIRTY + "=1," +
Events.MUTATORS + "=? " +
" WHERE " + Events._ID + "=?";
private static final String SQL_QUERY_EVENT_MUTATORS = "SELECT " + Events.MUTATORS +
" FROM " + Tables.EVENTS +
" WHERE " + Events._ID + "=?";
private static final String SQL_WHERE_CALENDAR_COLOR = Calendars.ACCOUNT_NAME + "=? AND "
+ Calendars.ACCOUNT_TYPE + "=? AND " + Calendars.CALENDAR_COLOR_KEY + "=?";
private static final String SQL_WHERE_EVENT_COLOR = "calendar_id in (SELECT _id from "
+ Tables.CALENDARS + " WHERE " + Events.ACCOUNT_NAME + "=? AND " + Events.ACCOUNT_TYPE
+ "=?) AND " + Events.EVENT_COLOR_KEY + "=?";
protected static final String SQL_WHERE_ID = GENERIC_ID + "=?";
private static final String SQL_WHERE_EVENT_ID = GENERIC_EVENT_ID + "=?";
private static final String SQL_WHERE_ORIGINAL_ID = Events.ORIGINAL_ID + "=?";
private static final String SQL_WHERE_ORIGINAL_ID_NO_SYNC_ID = Events.ORIGINAL_ID +
"=? AND " + Events._SYNC_ID + " IS NULL";
private static final String SQL_WHERE_ATTENDEE_BASE =
Tables.EVENTS + "." + Events._ID + "=" + Tables.ATTENDEES + "." + Attendees.EVENT_ID
+ " AND " +
Tables.EVENTS + "." + Events.CALENDAR_ID + "=" + Tables.CALENDARS + "." + Calendars._ID;
private static final String SQL_WHERE_ATTENDEES_ID =
Tables.ATTENDEES + "." + Attendees._ID + "=? AND " + SQL_WHERE_ATTENDEE_BASE;
private static final String SQL_WHERE_REMINDERS_ID =
Tables.REMINDERS + "." + Reminders._ID + "=? AND " +
Tables.EVENTS + "." + Events._ID + "=" + Tables.REMINDERS + "." + Reminders.EVENT_ID +
" AND " +
Tables.EVENTS + "." + Events.CALENDAR_ID + "=" + Tables.CALENDARS + "." + Calendars._ID;
private static final String SQL_WHERE_CALENDAR_ALERT =
Views.EVENTS + "." + Events._ID + "=" +
Tables.CALENDAR_ALERTS + "." + CalendarAlerts.EVENT_ID;
private static final String SQL_WHERE_CALENDAR_ALERT_ID =
Views.EVENTS + "." + Events._ID + "=" +
Tables.CALENDAR_ALERTS + "." + CalendarAlerts.EVENT_ID +
" AND " +
Tables.CALENDAR_ALERTS + "." + CalendarAlerts._ID + "=?";
private static final String SQL_WHERE_EXTENDED_PROPERTIES_ID =
Tables.EXTENDED_PROPERTIES + "." + CalendarContract.ExtendedProperties._ID + "=?";
private static final String SQL_DELETE_FROM_CALENDARS = "DELETE FROM " + Tables.CALENDARS +
" WHERE " + Calendars.ACCOUNT_NAME + "=? AND " +
Calendars.ACCOUNT_TYPE + "=?";
private static final String SQL_DELETE_FROM_COLORS = "DELETE FROM " + Tables.COLORS + " WHERE "
+ Calendars.ACCOUNT_NAME + "=? AND " + Calendars.ACCOUNT_TYPE + "=?";
private static final String SQL_SELECT_COUNT_FOR_SYNC_ID =
"SELECT COUNT(*) FROM " + Tables.EVENTS + " WHERE " + Events._SYNC_ID + "=?";
// Make sure we load at least two months worth of data.
// Client apps can load more data in a background thread.
private static final long MINIMUM_EXPANSION_SPAN =
2L * 31 * 24 * 60 * 60 * 1000;
private static final String[] sCalendarsIdProjection = new String[] { Calendars._ID };
private static final int CALENDARS_INDEX_ID = 0;
private static final String INSTANCE_QUERY_TABLES =
CalendarDatabaseHelper.Tables.INSTANCES + " INNER JOIN " +
CalendarDatabaseHelper.Views.EVENTS + " AS " +
CalendarDatabaseHelper.Tables.EVENTS +
" ON (" + CalendarDatabaseHelper.Tables.INSTANCES + "."
+ CalendarContract.Instances.EVENT_ID + "=" +
CalendarDatabaseHelper.Tables.EVENTS + "."
+ CalendarContract.Events._ID + ")";
private static final String INSTANCE_SEARCH_QUERY_TABLES = "(" +
CalendarDatabaseHelper.Tables.INSTANCES + " INNER JOIN " +
CalendarDatabaseHelper.Views.EVENTS + " AS " +
CalendarDatabaseHelper.Tables.EVENTS +
" ON (" + CalendarDatabaseHelper.Tables.INSTANCES + "."
+ CalendarContract.Instances.EVENT_ID + "=" +
CalendarDatabaseHelper.Tables.EVENTS + "."
+ CalendarContract.Events._ID + ")" + ") LEFT OUTER JOIN " +
CalendarDatabaseHelper.Tables.ATTENDEES +
" ON (" + CalendarDatabaseHelper.Tables.ATTENDEES + "."
+ CalendarContract.Attendees.EVENT_ID + "=" +
CalendarDatabaseHelper.Tables.EVENTS + "."
+ CalendarContract.Events._ID + ")";
private static final String SQL_WHERE_INSTANCES_BETWEEN_DAY =
CalendarContract.Instances.START_DAY + "<=? AND " +
CalendarContract.Instances.END_DAY + ">=?";
private static final String SQL_WHERE_INSTANCES_BETWEEN =
CalendarContract.Instances.BEGIN + "<=? AND " +
CalendarContract.Instances.END + ">=?";
private static final int INSTANCES_INDEX_START_DAY = 0;
private static final int INSTANCES_INDEX_END_DAY = 1;
private static final int INSTANCES_INDEX_START_MINUTE = 2;
private static final int INSTANCES_INDEX_END_MINUTE = 3;
private static final int INSTANCES_INDEX_ALL_DAY = 4;
/**
* The sort order is: events with an earlier start time occur first and if
* the start times are the same, then events with a later end time occur
* first. The later end time is ordered first so that long-running events in
* the calendar views appear first. If the start and end times of two events
* are the same then we sort alphabetically on the title. This isn't
* required for correctness, it just adds a nice touch.
*/
public static final String SORT_CALENDAR_VIEW = "begin ASC, end DESC, title ASC";
/**
* A regex for describing how we split search queries into tokens. Keeps
* quoted phrases as one token. "one \"two three\"" ==> ["one" "two three"]
*/
private static final Pattern SEARCH_TOKEN_PATTERN =
Pattern.compile("[^\\s\"'.?!,]+|" // first part matches unquoted words
+ "\"([^\"]*)\""); // second part matches quoted phrases
/**
* A special character that was use to escape potentially problematic
* characters in search queries.
*
* Note: do not use backslash for this, as it interferes with the regex
* escaping mechanism.
*/
private static final String SEARCH_ESCAPE_CHAR = "#";
/**
* A regex for matching any characters in an incoming search query that we
* need to escape with {@link #SEARCH_ESCAPE_CHAR}, including the escape
* character itself.
*/
private static final Pattern SEARCH_ESCAPE_PATTERN =
Pattern.compile("([%_" + SEARCH_ESCAPE_CHAR + "])");
/**
* Alias used for aggregate concatenation of attendee e-mails when grouping
* attendees by instance.
*/
private static final String ATTENDEES_EMAIL_CONCAT =
"group_concat(" + CalendarContract.Attendees.ATTENDEE_EMAIL + ")";
/**
* Alias used for aggregate concatenation of attendee names when grouping
* attendees by instance.
*/
private static final String ATTENDEES_NAME_CONCAT =
"group_concat(" + CalendarContract.Attendees.ATTENDEE_NAME + ")";
private static final String[] SEARCH_COLUMNS = new String[] {
CalendarContract.Events.TITLE,
CalendarContract.Events.DESCRIPTION,
CalendarContract.Events.EVENT_LOCATION,
ATTENDEES_EMAIL_CONCAT,
ATTENDEES_NAME_CONCAT
};
/**
* Arbitrary integer that we assign to the messages that we send to this
* thread's handler, indicating that these are requests to send an update
* notification intent.
*/
private static final int UPDATE_BROADCAST_MSG = 1;
/**
* Any requests to send a PROVIDER_CHANGED intent will be collapsed over
* this window, to prevent spamming too many intents at once.
*/
private static final long UPDATE_BROADCAST_TIMEOUT_MILLIS =
DateUtils.SECOND_IN_MILLIS;
private static final long SYNC_UPDATE_BROADCAST_TIMEOUT_MILLIS =
30 * DateUtils.SECOND_IN_MILLIS;
private static final HashSet<String> ALLOWED_URI_PARAMETERS = Sets.newHashSet(
CalendarContract.CALLER_IS_SYNCADAPTER,
CalendarContract.EventsEntity.ACCOUNT_NAME,
CalendarContract.EventsEntity.ACCOUNT_TYPE);
/** Set of columns allowed to be altered when creating an exception to a recurring event. */
private static final HashSet<String> ALLOWED_IN_EXCEPTION = new HashSet<String>();
static {
// _id, _sync_account, _sync_account_type, dirty, _sync_mark, calendar_id
ALLOWED_IN_EXCEPTION.add(Events._SYNC_ID);
ALLOWED_IN_EXCEPTION.add(Events.SYNC_DATA1);
ALLOWED_IN_EXCEPTION.add(Events.SYNC_DATA7);
ALLOWED_IN_EXCEPTION.add(Events.SYNC_DATA3);
ALLOWED_IN_EXCEPTION.add(Events.TITLE);
ALLOWED_IN_EXCEPTION.add(Events.EVENT_LOCATION);
ALLOWED_IN_EXCEPTION.add(Events.DESCRIPTION);
ALLOWED_IN_EXCEPTION.add(Events.EVENT_COLOR);
ALLOWED_IN_EXCEPTION.add(Events.EVENT_COLOR_KEY);
ALLOWED_IN_EXCEPTION.add(Events.STATUS);
ALLOWED_IN_EXCEPTION.add(Events.SELF_ATTENDEE_STATUS);
ALLOWED_IN_EXCEPTION.add(Events.SYNC_DATA6);
ALLOWED_IN_EXCEPTION.add(Events.DTSTART);
// dtend -- set from duration as part of creating the exception
ALLOWED_IN_EXCEPTION.add(Events.EVENT_TIMEZONE);
ALLOWED_IN_EXCEPTION.add(Events.EVENT_END_TIMEZONE);
ALLOWED_IN_EXCEPTION.add(Events.DURATION);
ALLOWED_IN_EXCEPTION.add(Events.ALL_DAY);
ALLOWED_IN_EXCEPTION.add(Events.ACCESS_LEVEL);
ALLOWED_IN_EXCEPTION.add(Events.AVAILABILITY);
ALLOWED_IN_EXCEPTION.add(Events.HAS_ALARM);
ALLOWED_IN_EXCEPTION.add(Events.HAS_EXTENDED_PROPERTIES);
ALLOWED_IN_EXCEPTION.add(Events.RRULE);
ALLOWED_IN_EXCEPTION.add(Events.RDATE);
ALLOWED_IN_EXCEPTION.add(Events.EXRULE);
ALLOWED_IN_EXCEPTION.add(Events.EXDATE);
ALLOWED_IN_EXCEPTION.add(Events.ORIGINAL_SYNC_ID);
ALLOWED_IN_EXCEPTION.add(Events.ORIGINAL_INSTANCE_TIME);
// originalAllDay, lastDate
ALLOWED_IN_EXCEPTION.add(Events.HAS_ATTENDEE_DATA);
ALLOWED_IN_EXCEPTION.add(Events.GUESTS_CAN_MODIFY);
ALLOWED_IN_EXCEPTION.add(Events.GUESTS_CAN_INVITE_OTHERS);
ALLOWED_IN_EXCEPTION.add(Events.GUESTS_CAN_SEE_GUESTS);
ALLOWED_IN_EXCEPTION.add(Events.ORGANIZER);
ALLOWED_IN_EXCEPTION.add(Events.CUSTOM_APP_PACKAGE);
ALLOWED_IN_EXCEPTION.add(Events.CUSTOM_APP_URI);
ALLOWED_IN_EXCEPTION.add(Events.UID_2445);
// deleted, original_id, alerts
}
/** Don't clone these from the base event into the exception event. */
private static final String[] DONT_CLONE_INTO_EXCEPTION = {
Events._SYNC_ID,
Events.SYNC_DATA1,
Events.SYNC_DATA2,
Events.SYNC_DATA3,
Events.SYNC_DATA4,
Events.SYNC_DATA5,
Events.SYNC_DATA6,
Events.SYNC_DATA7,
Events.SYNC_DATA8,
Events.SYNC_DATA9,
Events.SYNC_DATA10,
};
/** set to 'true' to enable debug logging for recurrence exception code */
private static final boolean DEBUG_EXCEPTION = false;
private final ThreadLocal<Boolean> mCallingPackageErrorLogged = new ThreadLocal<Boolean>();
private Context mContext;
private ContentResolver mContentResolver;
private static CalendarProvider2 mInstance;
@VisibleForTesting
protected CalendarAlarmManager mCalendarAlarm;
private final Handler mBroadcastHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Context context = CalendarProvider2.this.mContext;
if (msg.what == UPDATE_BROADCAST_MSG) {
// Broadcast a provider changed intent
doSendUpdateNotification();
// Because the handler does not guarantee message delivery in
// the case that the provider is killed, we need to make sure
// that the provider stays alive long enough to deliver the
// notification. This empty service is sufficient to "wedge" the
// process until we stop it here.
context.stopService(new Intent(context, EmptyService.class));
}
}
};
/**
* Listens for timezone changes and disk-no-longer-full events
*/
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onReceive() " + action);
}
if (Intent.ACTION_TIMEZONE_CHANGED.equals(action)) {
updateTimezoneDependentFields();
mCalendarAlarm.checkNextAlarm(false /* do not remove alarms */);
} else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action)) {
// Try to clean up if things were screwy due to a full disk
updateTimezoneDependentFields();
mCalendarAlarm.checkNextAlarm(false /* do not remove alarms */);
} else if (Intent.ACTION_TIME_CHANGED.equals(action)) {
mCalendarAlarm.checkNextAlarm(false /* do not remove alarms */);
}
}
};
/* Visible for testing */
@Override
protected CalendarDatabaseHelper getDatabaseHelper(final Context context) {
return CalendarDatabaseHelper.getInstance(context);
}
protected static CalendarProvider2 getInstance() {
return mInstance;
}
@Override
public void shutdown() {
if (mDbHelper != null) {
mDbHelper.close();
mDbHelper = null;
mDb = null;
}
}
@Override
public boolean onCreate() {
super.onCreate();
setAppOps(AppOpsManager.OP_READ_CALENDAR, AppOpsManager.OP_WRITE_CALENDAR);
try {
return initialize();
} catch (RuntimeException e) {
if (Log.isLoggable(TAG, Log.ERROR)) {
Log.e(TAG, "Cannot start provider", e);
}
return false;
}
}
private boolean initialize() {
mInstance = this;
mContext = getContext();
mContentResolver = mContext.getContentResolver();
mDbHelper = (CalendarDatabaseHelper)getDatabaseHelper();
mDb = mDbHelper.getWritableDatabase();
mMetaData = new MetaData(mDbHelper);
mInstancesHelper = new CalendarInstancesHelper(mDbHelper, mMetaData);
// Register for Intent broadcasts
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
filter.addAction(Intent.ACTION_TIME_CHANGED);
// We don't ever unregister this because this thread always wants
// to receive notifications, even in the background. And if this
// thread is killed then the whole process will be killed and the
// memory resources will be reclaimed.
mContext.registerReceiver(mIntentReceiver, filter);
mCalendarCache = new CalendarCache(mDbHelper);
// This is pulled out for testing
initCalendarAlarm();
postInitialize();
return true;
}
protected void initCalendarAlarm() {
mCalendarAlarm = getOrCreateCalendarAlarmManager();
}
synchronized CalendarAlarmManager getOrCreateCalendarAlarmManager() {
if (mCalendarAlarm == null) {
mCalendarAlarm = new CalendarAlarmManager(mContext);
Log.i(TAG, "Created " + mCalendarAlarm + "(" + this + ")");
}
return mCalendarAlarm;
}
protected void postInitialize() {
Thread thread = new PostInitializeThread();
thread.start();
}
private class PostInitializeThread extends Thread {
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
verifyAccounts();
try {
doUpdateTimezoneDependentFields();
} catch (IllegalStateException e) {
// Added this because tests would fail if the provider is
// closed by the time this is executed
// Nothing actionable here anyways.
}
}
}
private void verifyAccounts() {
AccountManager.get(getContext()).addOnAccountsUpdatedListener(this, null, false);
removeStaleAccounts(AccountManager.get(getContext()).getAccounts());
}
/**
* This creates a background thread to check the timezone and update
* the timezone dependent fields in the Instances table if the timezone
* has changed.
*/
protected void updateTimezoneDependentFields() {
Thread thread = new TimezoneCheckerThread();
thread.start();
}
private class TimezoneCheckerThread extends Thread {
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
doUpdateTimezoneDependentFields();
}
}
/**
* Check if we are in the same time zone
*/
private boolean isLocalSameAsInstancesTimezone() {
String localTimezone = TimeZone.getDefault().getID();
return TextUtils.equals(mCalendarCache.readTimezoneInstances(), localTimezone);
}
/**
* This method runs in a background thread. If the timezone has changed
* then the Instances table will be regenerated.
*/
protected void doUpdateTimezoneDependentFields() {
try {
String timezoneType = mCalendarCache.readTimezoneType();
// Nothing to do if we have the "home" timezone type (timezone is sticky)
if (timezoneType != null && timezoneType.equals(CalendarCache.TIMEZONE_TYPE_HOME)) {
return;
}
// We are here in "auto" mode, the timezone is coming from the device
if (! isSameTimezoneDatabaseVersion()) {
String localTimezone = TimeZone.getDefault().getID();
doProcessEventRawTimes(localTimezone, TimeUtils.getTimeZoneDatabaseVersion());
}
if (isLocalSameAsInstancesTimezone()) {
// Even if the timezone hasn't changed, check for missed alarms.
// This code executes when the CalendarProvider2 is created and
// helps to catch missed alarms when the Calendar process is
// killed (because of low-memory conditions) and then restarted.
mCalendarAlarm.rescheduleMissedAlarms();
}
} catch (SQLException e) {
if (Log.isLoggable(TAG, Log.ERROR)) {
Log.e(TAG, "doUpdateTimezoneDependentFields() failed", e);
}
try {
// Clear at least the in-memory data (and if possible the
// database fields) to force a re-computation of Instances.
mMetaData.clearInstanceRange();
} catch (SQLException e2) {
if (Log.isLoggable(TAG, Log.ERROR)) {
Log.e(TAG, "clearInstanceRange() also failed: " + e2);
}
}
}
}
protected void doProcessEventRawTimes(String localTimezone, String timeZoneDatabaseVersion) {
mDb.beginTransaction();
try {
updateEventsStartEndFromEventRawTimesLocked();
updateTimezoneDatabaseVersion(timeZoneDatabaseVersion);
mCalendarCache.writeTimezoneInstances(localTimezone);
regenerateInstancesTable();
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
private void updateEventsStartEndFromEventRawTimesLocked() {
Cursor cursor = mDb.rawQuery(SQL_SELECT_EVENTSRAWTIMES, null /* selection args */);
try {
while (cursor.moveToNext()) {
long eventId = cursor.getLong(0);
String dtStart2445 = cursor.getString(1);
String dtEnd2445 = cursor.getString(2);
String eventTimezone = cursor.getString(3);
if (dtStart2445 == null && dtEnd2445 == null) {
if (Log.isLoggable(TAG, Log.ERROR)) {
Log.e(TAG, "Event " + eventId + " has dtStart2445 and dtEnd2445 null "
+ "at the same time in EventsRawTimes!");
}
continue;
}
updateEventsStartEndLocked(eventId,
eventTimezone,
dtStart2445,
dtEnd2445);
}
} finally {
cursor.close();
cursor = null;
}
}
private long get2445ToMillis(String timezone, String dt2445) {
if (null == dt2445) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Cannot parse null RFC2445 date");
}
return 0;
}
Time time = (timezone != null) ? new Time(timezone) : new Time();
try {
time.parse(dt2445);
} catch (TimeFormatException e) {
if (Log.isLoggable(TAG, Log.ERROR)) {
Log.e(TAG, "Cannot parse RFC2445 date " + dt2445);
}
return 0;
}
return time.toMillis(true /* ignore DST */);
}
private void updateEventsStartEndLocked(long eventId,
String timezone, String dtStart2445, String dtEnd2445) {
ContentValues values = new ContentValues();
values.put(Events.DTSTART, get2445ToMillis(timezone, dtStart2445));
values.put(Events.DTEND, get2445ToMillis(timezone, dtEnd2445));
int result = mDb.update(Tables.EVENTS, values, SQL_WHERE_ID,
new String[] {String.valueOf(eventId)});
if (0 == result) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Could not update Events table with values " + values);
}
}
}
private void updateTimezoneDatabaseVersion(String timeZoneDatabaseVersion) {
try {
mCalendarCache.writeTimezoneDatabaseVersion(timeZoneDatabaseVersion);
} catch (CalendarCache.CacheException e) {
if (Log.isLoggable(TAG, Log.ERROR)) {
Log.e(TAG, "Could not write timezone database version in the cache");
}
}
}
/**
* Check if the time zone database version is the same as the cached one
*/
protected boolean isSameTimezoneDatabaseVersion() {
String timezoneDatabaseVersion = mCalendarCache.readTimezoneDatabaseVersion();
if (timezoneDatabaseVersion == null) {
return false;
}
return TextUtils.equals(timezoneDatabaseVersion, TimeUtils.getTimeZoneDatabaseVersion());
}
@VisibleForTesting
protected String getTimezoneDatabaseVersion() {
String timezoneDatabaseVersion = mCalendarCache.readTimezoneDatabaseVersion();
if (timezoneDatabaseVersion == null) {
return "";
}
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "timezoneDatabaseVersion = " + timezoneDatabaseVersion);
}
return timezoneDatabaseVersion;
}
private boolean isHomeTimezone() {
final String type = mCalendarCache.readTimezoneType();
return CalendarCache.TIMEZONE_TYPE_HOME.equals(type);
}
private void regenerateInstancesTable() {
// The database timezone is different from the current timezone.
// Regenerate the Instances table for this month. Include events
// starting at the beginning of this month.
long now = System.currentTimeMillis();
String instancesTimezone = mCalendarCache.readTimezoneInstances();
Time time = new Time(instancesTimezone);
time.set(now);
time.monthDay = 1;
time.hour = 0;
time.minute = 0;
time.second = 0;
long begin = time.normalize(true);
long end = begin + MINIMUM_EXPANSION_SPAN;
Cursor cursor = null;
try {
cursor = handleInstanceQuery(new SQLiteQueryBuilder(),
begin, end,
new String[] { Instances._ID },
null /* selection */, null,
null /* sort */,
false /* searchByDayInsteadOfMillis */,
true /* force Instances deletion and expansion */,
instancesTimezone, isHomeTimezone());
} finally {
if (cursor != null) {
cursor.close();
}
}
mCalendarAlarm.rescheduleMissedAlarms();
}
@Override
protected void notifyChange(boolean syncToNetwork) {
// Note that semantics are changed: notification is for CONTENT_URI, not the specific
// Uri that was modified.
mContentResolver.notifyChange(CalendarContract.CONTENT_URI, null, syncToNetwork);
}
/**
* ALERT table is maintained locally so don't request a sync for changes in it
*/
@Override
protected boolean shouldSyncFor(Uri uri) {
final int match = sUriMatcher.match(uri);
return !(match == CALENDAR_ALERTS ||
match == CALENDAR_ALERTS_ID ||
match == CALENDAR_ALERTS_BY_INSTANCE);
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
final long identity = clearCallingIdentityInternal();
try {
return queryInternal(uri, projection, selection, selectionArgs, sortOrder);
} finally {
restoreCallingIdentityInternal(identity);
}
}
private Cursor queryInternal(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "query uri - " + uri);
}
validateUriParameters(uri.getQueryParameterNames());
final SQLiteDatabase db = mDbHelper.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String groupBy = null;
String limit = null; // Not currently implemented
String instancesTimezone;
final int match = sUriMatcher.match(uri);
switch (match) {
case SYNCSTATE:
return mDbHelper.getSyncState().query(db, projection, selection, selectionArgs,
sortOrder);
case SYNCSTATE_ID:
String selectionWithId = (SyncState._ID + "=?")
+ (selection == null ? "" : " AND (" + selection + ")");
// Prepend id to selectionArgs
selectionArgs = insertSelectionArg(selectionArgs,
String.valueOf(ContentUris.parseId(uri)));
return mDbHelper.getSyncState().query(db, projection, selectionWithId,
selectionArgs, sortOrder);
case EVENTS:
qb.setTables(CalendarDatabaseHelper.Views.EVENTS);
qb.setProjectionMap(sEventsProjectionMap);
selection = appendAccountToSelection(uri, selection, Calendars.ACCOUNT_NAME,
Calendars.ACCOUNT_TYPE);
selection = appendLastSyncedColumnToSelection(selection, uri);
break;
case EVENTS_ID:
qb.setTables(CalendarDatabaseHelper.Views.EVENTS);
qb.setProjectionMap(sEventsProjectionMap);
selectionArgs = insertSelectionArg(selectionArgs, uri.getPathSegments().get(1));
qb.appendWhere(SQL_WHERE_ID);
break;
case EVENT_ENTITIES:
qb.setTables(CalendarDatabaseHelper.Views.EVENTS);
qb.setProjectionMap(sEventEntitiesProjectionMap);
selection = appendAccountToSelection(uri, selection, Calendars.ACCOUNT_NAME,
Calendars.ACCOUNT_TYPE);
selection = appendLastSyncedColumnToSelection(selection, uri);
break;
case EVENT_ENTITIES_ID:
qb.setTables(CalendarDatabaseHelper.Views.EVENTS);
qb.setProjectionMap(sEventEntitiesProjectionMap);
selectionArgs = insertSelectionArg(selectionArgs, uri.getPathSegments().get(1));
qb.appendWhere(SQL_WHERE_ID);
break;
case COLORS:
qb.setTables(Tables.COLORS);
qb.setProjectionMap(sColorsProjectionMap);
selection = appendAccountToSelection(uri, selection, Calendars.ACCOUNT_NAME,
Calendars.ACCOUNT_TYPE);
break;
case CALENDARS:
case CALENDAR_ENTITIES:
qb.setTables(Tables.CALENDARS);
qb.setProjectionMap(sCalendarsProjectionMap);
selection = appendAccountToSelection(uri, selection, Calendars.ACCOUNT_NAME,
Calendars.ACCOUNT_TYPE);
break;
case CALENDARS_ID:
case CALENDAR_ENTITIES_ID:
qb.setTables(Tables.CALENDARS);
qb.setProjectionMap(sCalendarsProjectionMap);
selectionArgs = insertSelectionArg(selectionArgs, uri.getPathSegments().get(1));
qb.appendWhere(SQL_WHERE_ID);
break;
case INSTANCES:
case INSTANCES_BY_DAY:
long begin;
long end;
try {
begin = Long.valueOf(uri.getPathSegments().get(2));
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Cannot parse begin "
+ uri.getPathSegments().get(2));
}
try {
end = Long.valueOf(uri.getPathSegments().get(3));
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Cannot parse end "
+ uri.getPathSegments().get(3));
}
instancesTimezone = mCalendarCache.readTimezoneInstances();
return handleInstanceQuery(qb, begin, end, projection, selection, selectionArgs,
sortOrder, match == INSTANCES_BY_DAY, false /* don't force an expansion */,
instancesTimezone, isHomeTimezone());
case INSTANCES_SEARCH:
case INSTANCES_SEARCH_BY_DAY:
try {
begin = Long.valueOf(uri.getPathSegments().get(2));
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Cannot parse begin "
+ uri.getPathSegments().get(2));
}
try {
end = Long.valueOf(uri.getPathSegments().get(3));
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Cannot parse end "
+ uri.getPathSegments().get(3));
}
instancesTimezone = mCalendarCache.readTimezoneInstances();
// this is already decoded
String query = uri.getPathSegments().get(4);
return handleInstanceSearchQuery(qb, begin, end, query, projection, selection,
selectionArgs, sortOrder, match == INSTANCES_SEARCH_BY_DAY,
instancesTimezone, isHomeTimezone());
case EVENT_DAYS:
int startDay;
int endDay;
try {
startDay = Integer.parseInt(uri.getPathSegments().get(2));
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Cannot parse start day "
+ uri.getPathSegments().get(2));
}
try {
endDay = Integer.parseInt(uri.getPathSegments().get(3));
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Cannot parse end day "
+ uri.getPathSegments().get(3));
}
instancesTimezone = mCalendarCache.readTimezoneInstances();
return handleEventDayQuery(qb, startDay, endDay, projection, selection,
instancesTimezone, isHomeTimezone());
case ATTENDEES:
qb.setTables(Tables.ATTENDEES + ", " + Tables.EVENTS + ", " + Tables.CALENDARS);
qb.setProjectionMap(sAttendeesProjectionMap);
qb.appendWhere(SQL_WHERE_ATTENDEE_BASE);
break;
case ATTENDEES_ID:
qb.setTables(Tables.ATTENDEES + ", " + Tables.EVENTS + ", " + Tables.CALENDARS);
qb.setProjectionMap(sAttendeesProjectionMap);
selectionArgs = insertSelectionArg(selectionArgs, uri.getPathSegments().get(1));
qb.appendWhere(SQL_WHERE_ATTENDEES_ID);
break;
case REMINDERS:
qb.setTables(Tables.REMINDERS);
break;
case REMINDERS_ID:
qb.setTables(Tables.REMINDERS + ", " + Tables.EVENTS + ", " + Tables.CALENDARS);
qb.setProjectionMap(sRemindersProjectionMap);
selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment());
qb.appendWhere(SQL_WHERE_REMINDERS_ID);
break;
case CALENDAR_ALERTS:
qb.setTables(Tables.CALENDAR_ALERTS + ", " + CalendarDatabaseHelper.Views.EVENTS);
qb.setProjectionMap(sCalendarAlertsProjectionMap);
qb.appendWhere(SQL_WHERE_CALENDAR_ALERT);
break;
case CALENDAR_ALERTS_BY_INSTANCE:
qb.setTables(Tables.CALENDAR_ALERTS + ", " + CalendarDatabaseHelper.Views.EVENTS);