-
Notifications
You must be signed in to change notification settings - Fork 255
/
CalendarDelegate.kt
586 lines (492 loc) · 26.1 KB
/
CalendarDelegate.kt
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
package com.builttoroam.devicecalendar
import android.Manifest
import android.annotation.SuppressLint
import io.flutter.plugin.common.PluginRegistry
import android.content.pm.PackageManager
import android.app.Activity
import android.content.*
import android.database.Cursor
import android.net.Uri
import android.provider.CalendarContract
import com.builttoroam.devicecalendar.common.Constants.Companion.CALENDAR_PROJECTION
import com.builttoroam.devicecalendar.common.Constants.Companion.CALENDAR_PROJECTION_ACCESS_LEVEL_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.EVENT_PROJECTION
import com.builttoroam.devicecalendar.common.Constants.Companion.CALENDAR_PROJECTION_ACCOUNT_NAME_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.CALENDAR_PROJECTION_DISPLAY_NAME_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.CALENDAR_PROJECTION_ID_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.CALENDAR_PROJECTION_OWNER_ACCOUNT_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.EVENT_PROJECTION_DESCRIPTION_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.EVENT_PROJECTION_ID_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.EVENT_PROJECTION_TITLE_INDEX
import com.builttoroam.devicecalendar.common.ErrorCodes.Companion.NOT_FOUND
import com.builttoroam.devicecalendar.common.ErrorCodes.Companion.INVALID_ARGUMENT
import com.builttoroam.devicecalendar.models.Calendar
import com.builttoroam.devicecalendar.models.Event
import io.flutter.plugin.common.MethodChannel
import com.google.gson.Gson
import android.provider.CalendarContract.Events
import com.builttoroam.devicecalendar.common.Constants.Companion.ATTENDEE_EMAIL_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.ATTENDEE_EVENT_ID_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.ATTENDEE_ID_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.ATTENDEE_NAME_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.ATTENDEE_PROJECTION
import com.builttoroam.devicecalendar.common.Constants.Companion.ATTENDEE_TYPE_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.EVENT_PROJECTION_ALL_DAY_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.EVENT_PROJECTION_BEGIN_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.EVENT_PROJECTION_DURATION_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.EVENT_PROJECTION_END_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.EVENT_PROJECTION_EVENT_LOCATION_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.EVENT_PROJECTION_RECURRING_DATE_INDEX
import com.builttoroam.devicecalendar.common.Constants.Companion.EVENT_PROJECTION_RECURRING_RULE_INDEX
import com.builttoroam.devicecalendar.common.ErrorCodes.Companion.GENERIC_ERROR
import com.builttoroam.devicecalendar.common.ErrorCodes.Companion.NOT_ALLOWED
import com.builttoroam.devicecalendar.common.ErrorCodes.Companion.NOT_AUTHORIZED
import com.builttoroam.devicecalendar.common.ErrorMessages.Companion.CALENDAR_ID_INVALID_ARGUMENT_NOT_A_NUMBER_MESSAGE
import com.builttoroam.devicecalendar.common.ErrorMessages.Companion.CREATE_EVENT_ARGUMENTS_NOT_VALID_MESSAGE
import com.builttoroam.devicecalendar.common.ErrorMessages.Companion.DELETING_RECURRING_EVENT_NOT_SUPPORTED_MESSAGE
import com.builttoroam.devicecalendar.common.ErrorMessages.Companion.NOT_AUTHORIZED_MESSAGE
import com.builttoroam.devicecalendar.models.Attendee
import com.builttoroam.devicecalendar.models.CalendarMethodsParametersCacheModel
import java.util.*
public class CalendarDelegate : PluginRegistry.RequestPermissionsResultListener {
private val RETRIEVE_CALENDARS_METHOD_CODE = 0
private val RETRIEVE_EVENTS_METHOD_CODE = RETRIEVE_CALENDARS_METHOD_CODE + 1
private val RETRIEVE_CALENDAR_METHOD_CODE = RETRIEVE_EVENTS_METHOD_CODE + 1
private val CREATE_OR_UPDATE_EVENT_METHOD_CODE = RETRIEVE_CALENDAR_METHOD_CODE + 1
private val DELETE_EVENT_METHOD_CODE = CREATE_OR_UPDATE_EVENT_METHOD_CODE + 1
private val REQUEST_PERMISSIONS_METHOD_CODE = DELETE_EVENT_METHOD_CODE + 1
private val _cachedParametersMap: MutableMap<Int, CalendarMethodsParametersCacheModel> = mutableMapOf<Int, CalendarMethodsParametersCacheModel>()
private var _activity: Activity? = null
private var _context: Context? = null
private var _gson: Gson? = null
public constructor(activity: Activity, context: Context) {
_activity = activity
_context = context
_gson = Gson()
}
public override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray): Boolean {
val permissionGranted = grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED
if (!_cachedParametersMap.containsKey(requestCode)) {
// We ran into a situation which theoretically should never happen.
// However, we can potentially run into this situation if plugin user is requesting other permissions (e.g. image picking) in his app
//
// There's nothing that can be done at this stage, besides finishing gracefully
return true
}
val cachedValues: CalendarMethodsParametersCacheModel? = _cachedParametersMap[requestCode]
if (cachedValues == null) {
// Another situation that theoretically should never happen.
// No exceptions, this should not happen, ever
//
// There's nothing that can be done at this stage, besides finishing gracefully
return true
}
when (cachedValues.calendarDelegateMethodCode) {
RETRIEVE_CALENDARS_METHOD_CODE -> {
if (permissionGranted) {
retrieveCalendars(cachedValues.pendingChannelResult)
} else {
finishWithError(NOT_AUTHORIZED, NOT_AUTHORIZED_MESSAGE, cachedValues.pendingChannelResult)
}
_cachedParametersMap.remove(requestCode)
return true
}
RETRIEVE_EVENTS_METHOD_CODE -> {
if (permissionGranted) {
retrieveEvents(cachedValues.calendarId, cachedValues.calendarEventsStartDate, cachedValues.calendarEventsEndDate, cachedValues.calendarEventsIds, cachedValues.pendingChannelResult)
} else {
finishWithError(NOT_AUTHORIZED, NOT_AUTHORIZED_MESSAGE, cachedValues.pendingChannelResult)
}
_cachedParametersMap.remove(requestCode)
return true
}
RETRIEVE_CALENDAR_METHOD_CODE -> {
if (permissionGranted) {
retrieveCalendar(cachedValues.calendarId, cachedValues.pendingChannelResult)
} else {
finishWithError(NOT_AUTHORIZED, NOT_AUTHORIZED_MESSAGE, cachedValues.pendingChannelResult)
}
_cachedParametersMap.remove(requestCode)
return true
}
CREATE_OR_UPDATE_EVENT_METHOD_CODE -> {
if (permissionGranted) {
createOrUpdateEvent(cachedValues.calendarId, cachedValues.event, cachedValues.pendingChannelResult)
} else {
finishWithError(NOT_AUTHORIZED, NOT_AUTHORIZED_MESSAGE, cachedValues.pendingChannelResult)
}
_cachedParametersMap.remove(requestCode)
return true
}
DELETE_EVENT_METHOD_CODE -> {
if (permissionGranted) {
deleteEvent(cachedValues.eventId, cachedValues.calendarId, cachedValues.pendingChannelResult)
} else {
finishWithError(NOT_AUTHORIZED, NOT_AUTHORIZED_MESSAGE, cachedValues.pendingChannelResult)
}
_cachedParametersMap.remove(requestCode)
return true
}
REQUEST_PERMISSIONS_METHOD_CODE -> {
finishWithSuccess(permissionGranted, cachedValues.pendingChannelResult)
return true
}
}
return false
}
public fun requestPermissions(pendingChannelResult: MethodChannel.Result) {
if (arePermissionsGranted()) {
finishWithSuccess(true, pendingChannelResult)
} else {
val parameters = CalendarMethodsParametersCacheModel(pendingChannelResult, REQUEST_PERMISSIONS_METHOD_CODE)
requestPermissions(parameters)
}
}
public fun hasPermissions(pendingChannelResult: MethodChannel.Result) {
finishWithSuccess(arePermissionsGranted(), pendingChannelResult)
}
@SuppressLint("MissingPermission")
public fun retrieveCalendars(pendingChannelResult: MethodChannel.Result) {
if (arePermissionsGranted()) {
val contentResolver: ContentResolver? = _context?.getContentResolver()
val uri: Uri = CalendarContract.Calendars.CONTENT_URI
val cursor: Cursor? = contentResolver?.query(uri, CALENDAR_PROJECTION, null, null, null)
val calendars: MutableList<Calendar> = mutableListOf<Calendar>()
try {
while (cursor?.moveToNext() ?: false) {
val calendar = parseCalendar(cursor)
if (calendar == null) {
continue
}
calendars.add(calendar)
}
finishWithSuccess(_gson?.toJson(calendars), pendingChannelResult)
} catch (e: Exception) {
finishWithError(GENERIC_ERROR, e.message, pendingChannelResult)
println(e.message)
} finally {
cursor?.close()
}
} else {
val parameters = CalendarMethodsParametersCacheModel(pendingChannelResult, RETRIEVE_CALENDARS_METHOD_CODE)
requestPermissions(parameters)
}
return
}
public fun retrieveCalendar(calendarId: String, pendingChannelResult: MethodChannel.Result, isInternalCall: Boolean = false): Calendar? {
if (isInternalCall || arePermissionsGranted()) {
val calendarIdNumber = calendarId.toLongOrNull()
if (calendarIdNumber == null) {
if (!isInternalCall) {
finishWithError(INVALID_ARGUMENT, CALENDAR_ID_INVALID_ARGUMENT_NOT_A_NUMBER_MESSAGE, pendingChannelResult)
}
return null
}
val contentResolver: ContentResolver? = _context?.getContentResolver()
val uri: Uri = CalendarContract.Calendars.CONTENT_URI
val cursor: Cursor? = contentResolver?.query(ContentUris.withAppendedId(uri, calendarIdNumber), CALENDAR_PROJECTION, null, null, null)
try {
if (cursor?.moveToFirst() ?: false) {
val calendar = parseCalendar(cursor)
if (isInternalCall) {
return calendar
} else {
finishWithSuccess(_gson?.toJson(calendar), pendingChannelResult)
}
} else {
if (!isInternalCall) {
finishWithError(NOT_FOUND, "The calendar with the ID ${calendarId} could not be found", pendingChannelResult)
}
}
} catch (e: Exception) {
println(e.message)
} finally {
cursor?.close()
}
} else {
val parameters = CalendarMethodsParametersCacheModel(pendingChannelResult, RETRIEVE_CALENDAR_METHOD_CODE, calendarId)
requestPermissions(parameters)
}
return null
}
@SuppressLint("MissingPermission")
public fun retrieveEvents(calendarId: String, startDate: Long, endDate: Long, eventIds: List<String>, pendingChannelResult: MethodChannel.Result) {
if (arePermissionsGranted()) {
val calendar = retrieveCalendar(calendarId, pendingChannelResult, true)
if (calendar == null) {
finishWithError(NOT_FOUND, "Couldn't retrieve the Calendar with ID ${calendarId}", pendingChannelResult)
return
}
val contentResolver: ContentResolver? = _context?.getContentResolver()
val eventsUriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon()
ContentUris.appendId(eventsUriBuilder, startDate)
ContentUris.appendId(eventsUriBuilder, endDate)
val eventsUri = eventsUriBuilder.build()
val eventsCalendarQuery = "(${CalendarContract.Events.CALENDAR_ID} = ${calendarId})"
val eventsNotDeletedQuery = "(${CalendarContract.Events.DELETED} != 1)"
val eventsIdsQueryElements = eventIds.map { "(${CalendarContract.Instances.EVENT_ID} = ${it})" }
val eventsIdsQuery = eventsIdsQueryElements.joinToString(" OR ")
var eventsSelectionQuery = "$eventsCalendarQuery AND $eventsNotDeletedQuery"
if (!eventsIdsQuery.isNullOrEmpty()) {
eventsSelectionQuery += " AND ($eventsIdsQuery)"
}
val eventsSortOrder = CalendarContract.Events.DTSTART + " ASC"
val eventsCursor = contentResolver?.query(eventsUri, EVENT_PROJECTION, eventsSelectionQuery, null, eventsSortOrder)
val events: MutableList<Event> = mutableListOf()
try {
if (eventsCursor?.moveToFirst() ?: false) {
do {
val event = parseEvent(calendarId, eventsCursor)
if (event == null) {
continue
}
events.add(event)
} while (eventsCursor?.moveToNext() ?: false)
updateEventAttendees(events, contentResolver, pendingChannelResult)
}
} catch (e: Exception) {
finishWithError(GENERIC_ERROR, e.message, pendingChannelResult)
println(e.message)
} finally {
eventsCursor?.close()
}
finishWithSuccess(_gson?.toJson(events), pendingChannelResult)
} else {
val parameters = CalendarMethodsParametersCacheModel(pendingChannelResult, RETRIEVE_EVENTS_METHOD_CODE, calendarId, startDate, endDate)
requestPermissions(parameters)
}
return
}
@SuppressLint("MissingPermission")
public fun createOrUpdateEvent(calendarId: String, event: Event?, pendingChannelResult: MethodChannel.Result) {
if (arePermissionsGranted()) {
if (event == null) {
finishWithError(GENERIC_ERROR, CREATE_EVENT_ARGUMENTS_NOT_VALID_MESSAGE, pendingChannelResult)
return
}
val contentResolver: ContentResolver? = _context?.getContentResolver()
val values = ContentValues()
values.put(Events.DTSTART, event.start)
values.put(Events.DTEND, event.end)
values.put(Events.TITLE, event.title)
values.put(Events.DESCRIPTION, event.description)
values.put(Events.CALENDAR_ID, calendarId)
// MK using current device time zone
val calendar: java.util.Calendar = java.util.Calendar.getInstance()
val currentTimeZone: TimeZone = calendar.timeZone
values.put(Events.EVENT_TIMEZONE, currentTimeZone.displayName)
try {
var eventId: Long? = event.eventId?.toLongOrNull()
if (eventId == null) {
val uri = contentResolver?.insert(CalendarContract.Events.CONTENT_URI, values)
// get the event ID that is the last element in the Uri
eventId = java.lang.Long.parseLong(uri?.getLastPathSegment())
} else {
contentResolver?.update(ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId), values, null, null)
}
finishWithSuccess(eventId.toString(), pendingChannelResult)
} catch (e: Exception) {
finishWithError(GENERIC_ERROR, e.message, pendingChannelResult)
println(e.message)
} finally {
}
} else {
val parameters = CalendarMethodsParametersCacheModel(pendingChannelResult, CREATE_OR_UPDATE_EVENT_METHOD_CODE, calendarId)
parameters.event = event
requestPermissions(parameters)
}
}
public fun deleteEvent(calendarId: String, eventId: String, pendingChannelResult: MethodChannel.Result) {
if (arePermissionsGranted()) {
var existingCal = retrieveCalendar(calendarId, pendingChannelResult, true)
if (existingCal == null) {
finishWithError(NOT_FOUND, "The calendar with the ID ${calendarId} could not be found", pendingChannelResult)
return
}
if (existingCal.isReadOnly) {
finishWithError(NOT_ALLOWED, "Calendar with ID ${calendarId} is read-only", pendingChannelResult)
return
}
val eventIdNumber = eventId.toLongOrNull()
if (eventIdNumber == null) {
finishWithError(INVALID_ARGUMENT, CALENDAR_ID_INVALID_ARGUMENT_NOT_A_NUMBER_MESSAGE, pendingChannelResult)
return
}
val contentResolver: ContentResolver? = _context?.getContentResolver()
if (isRecurringEvent(eventIdNumber, contentResolver)) {
finishWithError(NOT_ALLOWED, DELETING_RECURRING_EVENT_NOT_SUPPORTED_MESSAGE, pendingChannelResult)
return
}
val eventsUriWithId = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventIdNumber)
val deleteSucceeded = contentResolver?.delete(eventsUriWithId, null, null) ?: 0
finishWithSuccess(deleteSucceeded > 0, pendingChannelResult)
} else {
val parameters = CalendarMethodsParametersCacheModel(pendingChannelResult, DELETE_EVENT_METHOD_CODE, calendarId)
parameters.eventId = eventId
requestPermissions(parameters)
}
}
private fun arePermissionsGranted(): Boolean {
if (atLeastAPI(23)) {
val writeCalendarPermissionGranted = _activity?.checkSelfPermission(Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED
val readCalendarPermissionGranted = _activity?.checkSelfPermission(Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED
return writeCalendarPermissionGranted && readCalendarPermissionGranted
}
return true
}
private fun requestPermissions(parameters: CalendarMethodsParametersCacheModel) {
val requestCode: Int = generateUniqueRequestCodeAndCacheParameters(parameters)
requestPermissions(requestCode)
}
private fun requestPermissions(requestCode: Int) {
if (atLeastAPI(23)) {
_activity?.requestPermissions(arrayOf(Manifest.permission.WRITE_CALENDAR, Manifest.permission.READ_CALENDAR), requestCode)
}
}
private fun parseCalendar(cursor: Cursor?): Calendar? {
if (cursor == null) {
return null
}
val calId = cursor.getLong(CALENDAR_PROJECTION_ID_INDEX)
val displayName = cursor.getString(CALENDAR_PROJECTION_DISPLAY_NAME_INDEX)
val accessLevel = cursor.getInt(CALENDAR_PROJECTION_ACCESS_LEVEL_INDEX)
val accountName = cursor.getString(CALENDAR_PROJECTION_ACCOUNT_NAME_INDEX)
val ownerName = cursor.getString(CALENDAR_PROJECTION_OWNER_ACCOUNT_INDEX)
val calendar = Calendar(calId.toString(), displayName)
calendar.isReadOnly = isCalendarReadOnly(accessLevel)
return calendar
}
private fun parseEvent(calendarId: String, cursor: Cursor?): Event? {
if (cursor == null) {
return null
}
val eventId = cursor.getLong(EVENT_PROJECTION_ID_INDEX)
val title = cursor.getString(EVENT_PROJECTION_TITLE_INDEX)
val description = cursor.getString(EVENT_PROJECTION_DESCRIPTION_INDEX)
val begin = cursor.getLong(EVENT_PROJECTION_BEGIN_INDEX)
val end = cursor.getLong(EVENT_PROJECTION_END_INDEX)
val duration = cursor.getLong(EVENT_PROJECTION_DURATION_INDEX)
val recurringDate = cursor.getString(EVENT_PROJECTION_RECURRING_DATE_INDEX)
val recurringRule = cursor.getString(EVENT_PROJECTION_RECURRING_RULE_INDEX)
val allDay = cursor.getInt(EVENT_PROJECTION_ALL_DAY_INDEX) > 0
val location = cursor.getString(EVENT_PROJECTION_EVENT_LOCATION_INDEX)
val event = Event(title)
event.eventId = eventId.toString()
event.calendarId = calendarId
event.description = description
event.start = begin
event.end = end
event.allDay = allDay
event.location = location
return event
}
private fun parseAttendee(cursor: Cursor?): Attendee? {
if (cursor == null) {
return null
}
val id = cursor.getLong(ATTENDEE_ID_INDEX)
val eventId = cursor.getLong(ATTENDEE_EVENT_ID_INDEX)
val name = cursor.getString(ATTENDEE_NAME_INDEX)
val email = cursor.getString(ATTENDEE_EMAIL_INDEX)
val type = cursor.getInt(ATTENDEE_TYPE_INDEX)
val attendee = Attendee(name)
attendee.id = id
attendee.eventId = eventId
attendee.email = email
attendee.attendanceRequired = type == CalendarContract.Attendees.TYPE_REQUIRED
return attendee
}
private fun isCalendarReadOnly(accessLevel: Int): Boolean {
return when (accessLevel) {
CalendarContract.Events.CAL_ACCESS_CONTRIBUTOR,
CalendarContract.Events.CAL_ACCESS_ROOT,
CalendarContract.Events.CAL_ACCESS_OWNER,
CalendarContract.Events.CAL_ACCESS_EDITOR
-> false
else -> true
}
}
private fun isRecurringEvent(eventId: Long, contentResolver: ContentResolver?): Boolean {
val eventProjection: Array<String> = arrayOf(
// There are a number of properties related to recurrence that
// we could check. The Android docs state: "For non-recurring events,
// you must include DTEND. For recurring events, you must include a
// DURATION in addition to RRULE or RDATE." The API will also throw
// an exception if you try to set both DTEND and DURATION on an
// event. Thus, it seems reasonable to trust that DURATION will
// only be present if the event is recurring.
//
CalendarContract.Events.DURATION
)
var isRecurring = false
var cursor: Cursor? = null
try {
cursor = contentResolver?.query(ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId), eventProjection, null, null, null)
if (cursor != null && cursor.moveToFirst()) {
isRecurring = !(cursor.getString(0)?.isNullOrEmpty() ?: true)
} else {
}
} catch (e: Exception) {
println(e)
} finally {
cursor?.close()
}
return isRecurring
}
@SuppressLint("MissingPermission")
private fun updateEventAttendees(events: MutableList<Event>, contentResolver: ContentResolver?, pendingChannelResult: MethodChannel.Result) {
if (events == null) {
return
}
val eventsMapById = events.associateBy { it.eventId }
val attendeesQueryEventIds = eventsMapById.values.map { "(${CalendarContract.Attendees.EVENT_ID} = ${it.eventId})" }
val attendeesQuery = attendeesQueryEventIds.joinToString(" OR ")
val attendeesCursor = contentResolver?.query(CalendarContract.Attendees.CONTENT_URI, ATTENDEE_PROJECTION, attendeesQuery, null, null);
try {
if (attendeesCursor?.moveToFirst() ?: false) {
do {
val attendee = parseAttendee(attendeesCursor)
if (attendee == null) {
continue
}
if (eventsMapById.containsKey(attendee.eventId.toString())) {
val attendeeEvent = eventsMapById[attendee.eventId.toString()]
attendeeEvent?.attendees?.add(attendee)
}
} while (attendeesCursor?.moveToNext() ?: false)
}
} catch (e: Exception) {
finishWithError(GENERIC_ERROR, e.message, pendingChannelResult)
println(e.message)
} finally {
attendeesCursor?.close();
}
}
@Synchronized
private fun generateUniqueRequestCodeAndCacheParameters(parameters: CalendarMethodsParametersCacheModel): Int {
// TODO we can ran out of Int's at some point so this probably should re-use some of the freed ones
val uniqueRequestCode: Int = (_cachedParametersMap.keys?.max() ?: 0) + 1
parameters.ownCacheKey = uniqueRequestCode
_cachedParametersMap[uniqueRequestCode] = parameters
return uniqueRequestCode
}
private fun <T> finishWithSuccess(result: T, pendingChannelResult: MethodChannel.Result) {
pendingChannelResult.success(result)
clearCachedParameters(pendingChannelResult)
}
private fun finishWithError(errorCode: String, errorMessage: String?, pendingChannelResult: MethodChannel.Result) {
pendingChannelResult.error(errorCode, errorMessage, null)
clearCachedParameters(pendingChannelResult)
}
private fun clearCachedParameters(pendingChannelResult: MethodChannel.Result) {
val cachedParameters = _cachedParametersMap.values.filter { it.pendingChannelResult == pendingChannelResult }.toList()
for (cachedParameter in cachedParameters) {
if (_cachedParametersMap.containsKey(cachedParameter.ownCacheKey)) {
_cachedParametersMap.remove(cachedParameter.ownCacheKey)
}
}
}
private fun atLeastAPI(api: Int): Boolean {
return api <= android.os.Build.VERSION.SDK_INT
}
}