@ebarooni/capacitor-calendar 8.9.0 → 8.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +114 -59
  2. package/android/src/main/java/dev/barooni/capacitor/calendar/CapacitorCalendarPlugin.kt +20 -4
  3. package/android/src/main/java/dev/barooni/capacitor/calendar/PluginError.kt +41 -22
  4. package/android/src/main/java/dev/barooni/capacitor/calendar/implementation/CapacitorCalendar.kt +129 -3
  5. package/android/src/main/java/dev/barooni/capacitor/calendar/models/data/CalendarInfo.kt +1 -0
  6. package/android/src/main/java/dev/barooni/capacitor/calendar/models/data/EventRecurrenceRule.kt +4 -3
  7. package/android/src/main/java/dev/barooni/capacitor/calendar/models/inputs/CreateEventInput.kt +4 -1
  8. package/android/src/main/java/dev/barooni/capacitor/calendar/models/inputs/DeleteEventInput.kt +4 -1
  9. package/android/src/main/java/dev/barooni/capacitor/calendar/models/inputs/DeleteEventWithPromptInput.kt +4 -1
  10. package/android/src/main/java/dev/barooni/capacitor/calendar/models/inputs/GetEventByIdInput.kt +13 -0
  11. package/android/src/main/java/dev/barooni/capacitor/calendar/models/inputs/ListEventsInRangeInput.kt +5 -0
  12. package/android/src/main/java/dev/barooni/capacitor/calendar/models/inputs/ModifyEvent.kt +8 -2
  13. package/android/src/main/java/dev/barooni/capacitor/calendar/models/inputs/ModifyEventWithPromptInput.kt +1 -1
  14. package/android/src/main/java/dev/barooni/capacitor/calendar/models/results/GetDefaultCalendarResult.kt +1 -1
  15. package/android/src/main/java/dev/barooni/capacitor/calendar/models/results/GetEventByIdResult.kt +15 -0
  16. package/android/src/main/java/dev/barooni/capacitor/calendar/models/results/ListCalendarsResult.kt +1 -1
  17. package/android/src/main/java/dev/barooni/capacitor/calendar/models/results/ListEventsInRangeResult.kt +47 -43
  18. package/android/src/main/java/dev/barooni/capacitor/calendar/utils/ImplementationHelper.kt +61 -3
  19. package/android/src/main/java/dev/barooni/capacitor/calendar/utils/PluginCallRejecter.kt +69 -0
  20. package/dist/docs.json +206 -8
  21. package/dist/esm/index.d.ts +4 -1
  22. package/dist/esm/index.js.map +1 -1
  23. package/dist/esm/schemas/enums/capacitor-calendar-error-code.d.ts +31 -0
  24. package/dist/esm/schemas/enums/capacitor-calendar-error-code.js +31 -0
  25. package/dist/esm/schemas/enums/capacitor-calendar-error-code.js.map +1 -1
  26. package/dist/esm/schemas/interfaces/calendar.d.ts +3 -1
  27. package/dist/esm/schemas/interfaces/calendar.js.map +1 -1
  28. package/dist/esm/schemas/interfaces/delete-event-options.d.ts +2 -1
  29. package/dist/esm/schemas/interfaces/delete-event-options.js.map +1 -1
  30. package/dist/esm/schemas/interfaces/delete-event-with-prompt-options.d.ts +2 -1
  31. package/dist/esm/schemas/interfaces/delete-event-with-prompt-options.js.map +1 -1
  32. package/dist/esm/schemas/interfaces/get-event-by-id-options.d.ts +11 -0
  33. package/dist/esm/schemas/interfaces/get-event-by-id-options.js +2 -0
  34. package/dist/esm/schemas/interfaces/get-event-by-id-options.js.map +1 -0
  35. package/dist/esm/schemas/interfaces/get-event-by-id-result.d.ts +13 -0
  36. package/dist/esm/schemas/interfaces/get-event-by-id-result.js +2 -0
  37. package/dist/esm/schemas/interfaces/get-event-by-id-result.js.map +1 -0
  38. package/dist/esm/schemas/interfaces/list-events-in-range-options.d.ts +8 -0
  39. package/dist/esm/schemas/interfaces/list-events-in-range-options.js.map +1 -1
  40. package/dist/esm/schemas/interfaces/modify-event-options.d.ts +11 -0
  41. package/dist/esm/schemas/interfaces/modify-event-options.js.map +1 -1
  42. package/dist/esm/schemas/interfaces/modify-event-with-prompt-options.d.ts +10 -0
  43. package/dist/esm/schemas/interfaces/modify-event-with-prompt-options.js.map +1 -1
  44. package/dist/esm/sub-definitions/event-operations.d.ts +33 -0
  45. package/dist/esm/sub-definitions/event-operations.js.map +1 -1
  46. package/dist/esm/web.d.ts +3 -0
  47. package/dist/esm/web.js +3 -0
  48. package/dist/esm/web.js.map +1 -1
  49. package/dist/plugin.cjs.js +34 -0
  50. package/dist/plugin.cjs.js.map +1 -1
  51. package/dist/plugin.js +34 -0
  52. package/dist/plugin.js.map +1 -1
  53. package/ios/Plugin/CapacitorCalendarPlugin.swift +18 -4
  54. package/ios/Plugin/Implementation/CapacitorCalendar.swift +41 -7
  55. package/ios/Plugin/Models/Inputs/CreateEventInput.swift +1 -1
  56. package/ios/Plugin/Models/Inputs/CreateEventWithPromptInput.swift +61 -70
  57. package/ios/Plugin/Models/Inputs/DeleteEventInput.swift +7 -0
  58. package/ios/Plugin/Models/Inputs/DeleteEventWithPromptInput.swift +7 -0
  59. package/ios/Plugin/Models/Inputs/GetEventByIdInput.swift +16 -0
  60. package/ios/Plugin/Models/Inputs/ListEventsInRangeInput.swift +20 -0
  61. package/ios/Plugin/Models/Inputs/ModifyEventInput.swift +13 -23
  62. package/ios/Plugin/Models/Inputs/ModifyEventWithPromptInput.swift +10 -5
  63. package/ios/Plugin/Models/Results/GetEventByIdResult.swift +27 -0
  64. package/ios/Plugin/Models/Structs/RecurrenceInput.swift +14 -0
  65. package/ios/Plugin/PluginConfig.swift +1 -0
  66. package/ios/Plugin/PluginError.swift +41 -0
  67. package/ios/Plugin/Utils/ImplementationHelper.swift +33 -2
  68. package/ios/Plugin/Utils/PluginCallRejecter.swift +36 -0
  69. package/package.json +1 -1
@@ -21,6 +21,7 @@ import dev.barooni.capacitor.calendar.models.inputs.DeleteEventInput
21
21
  import dev.barooni.capacitor.calendar.models.inputs.DeleteEventWithPromptInput
22
22
  import dev.barooni.capacitor.calendar.models.inputs.DeleteEventsByIdInput
23
23
  import dev.barooni.capacitor.calendar.models.inputs.GetDefaultCalendarInput
24
+ import dev.barooni.capacitor.calendar.models.inputs.GetEventByIdInput
24
25
  import dev.barooni.capacitor.calendar.models.inputs.ListEventsInRangeInput
25
26
  import dev.barooni.capacitor.calendar.models.inputs.ModifyCalendarInput
26
27
  import dev.barooni.capacitor.calendar.models.inputs.ModifyEvent
@@ -35,6 +36,7 @@ import dev.barooni.capacitor.calendar.models.results.CreateEventResult
35
36
  import dev.barooni.capacitor.calendar.models.results.DeleteEventWithPromptResult
36
37
  import dev.barooni.capacitor.calendar.models.results.DeleteEventsByIdResult
37
38
  import dev.barooni.capacitor.calendar.models.results.GetDefaultCalendarResult
39
+ import dev.barooni.capacitor.calendar.models.results.GetEventByIdResult
38
40
  import dev.barooni.capacitor.calendar.models.results.ListCalendarsResult
39
41
  import dev.barooni.capacitor.calendar.models.results.ListEventsInRangeResult
40
42
  import dev.barooni.capacitor.calendar.models.templates.PluginCompletion
@@ -113,7 +115,7 @@ class CapacitorCalendar(
113
115
  input.recurrence?.let { put(CalendarContract.Events.RRULE, it.toRRule()) }
114
116
  }
115
117
  val uri: Uri? = cr.insert(CalendarContract.Events.CONTENT_URI, values)
116
- val eventId: Long = uri?.lastPathSegment?.toLong() ?: throw PluginError.FailedToRetrieveEventId
118
+ val eventId: Long = uri?.lastPathSegment?.toLongOrNull() ?: throw PluginError.FailedToRetrieveEventId
117
119
  input.attendees?.let { ImplementationHelper.insertAttendeesToEvent(eventId, cr, it) }
118
120
  input.alerts?.let { ImplementationHelper.insertAlertsToEvents(eventId, cr, it) }
119
121
  return CreateEventResult(eventId)
@@ -121,6 +123,7 @@ class CapacitorCalendar(
121
123
 
122
124
  fun modifyEvent(input: ModifyEvent) {
123
125
  val cr = plugin.context.contentResolver
126
+ ImplementationHelper.ensureEventExists(cr, input.id)
124
127
  val updatingDates = input.startDate != null || input.endDate != null
125
128
  val settingAllDay = input.isAllDay == 1
126
129
  // Normalize when setting all-day, or when editing dates on an existing all-day event
@@ -413,10 +416,31 @@ class CapacitorCalendar(
413
416
  CalendarContract.Instances.DTSTART,
414
417
  )
415
418
 
419
+ val calendarIds = input.calendarIds
420
+ calendarIds?.forEach { calendarId ->
421
+ val exists =
422
+ cr
423
+ .query(
424
+ ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId),
425
+ arrayOf(CalendarContract.Calendars._ID),
426
+ null,
427
+ null,
428
+ null,
429
+ )?.use { it.moveToFirst() } ?: false
430
+ if (!exists) {
431
+ throw PluginError.CalendarNotFound
432
+ }
433
+ }
434
+ val calendarFilter =
435
+ calendarIds
436
+ ?.let { " AND (${CalendarContract.Instances.CALENDAR_ID} IN (${it.joinToString(",") { "?" }}))" }
437
+ ?: ""
416
438
  val selection =
417
439
  "(${CalendarContract.Instances.BEGIN} < ?) AND " +
418
- "(${CalendarContract.Instances.END} > ?)"
419
- val selectionArgs = arrayOf(input.to.toString(), input.from.toString())
440
+ "(${CalendarContract.Instances.END} > ?)" + calendarFilter
441
+ val selectionArgs =
442
+ arrayOf(input.to.toString(), input.from.toString()) +
443
+ (calendarIds?.map { it.toString() } ?: emptyList())
420
444
 
421
445
  val sortOrder = "${CalendarContract.Instances.BEGIN} ASC"
422
446
 
@@ -571,6 +595,108 @@ class CapacitorCalendar(
571
595
  return ListEventsInRangeResult(events)
572
596
  }
573
597
 
598
+ fun getEventById(
599
+ input: GetEventByIdInput,
600
+ completion: PluginCompletion<GetEventByIdResult>,
601
+ ) {
602
+ try {
603
+ completion(getEventByIdResult(input), null)
604
+ } catch (error: Exception) {
605
+ completion(null, error)
606
+ }
607
+ }
608
+
609
+ private fun getEventByIdResult(input: GetEventByIdInput): GetEventByIdResult {
610
+ val cr = plugin.context.contentResolver
611
+ val eventUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, input.id)
612
+ val projection =
613
+ arrayOf(
614
+ CalendarContract.Events.TITLE,
615
+ CalendarContract.Events.CALENDAR_ID,
616
+ CalendarContract.Events.EVENT_LOCATION,
617
+ CalendarContract.Events.DTSTART,
618
+ CalendarContract.Events.DTEND,
619
+ CalendarContract.Events.ALL_DAY,
620
+ CalendarContract.Events.DESCRIPTION,
621
+ CalendarContract.Events.AVAILABILITY,
622
+ CalendarContract.Events.ORGANIZER,
623
+ CalendarContract.Events.EVENT_COLOR,
624
+ CalendarContract.Events.EVENT_TIMEZONE,
625
+ CalendarContract.Events.STATUS,
626
+ CalendarContract.Events.DURATION,
627
+ CalendarContract.Events.RRULE,
628
+ CalendarContract.Events.ORIGINAL_ID,
629
+ CalendarContract.Events.DELETED,
630
+ )
631
+
632
+ val event =
633
+ cr.query(eventUri, projection, null, null, null)?.use { cursor ->
634
+ if (!cursor.moveToFirst()) {
635
+ return@use null
636
+ }
637
+
638
+ fun column(name: String): Int? = cursor.getColumnIndex(name).takeIf { it != -1 && !cursor.isNull(it) }
639
+
640
+ if (column(CalendarContract.Events.DELETED)?.let { cursor.getInt(it) == 1 } == true) {
641
+ return@use null
642
+ }
643
+
644
+ val startDate = column(CalendarContract.Events.DTSTART)?.let { cursor.getLong(it) } ?: 0L
645
+ val isAllDay = column(CalendarContract.Events.ALL_DAY)?.let { cursor.getInt(it) == 1 } ?: false
646
+ val rrule = column(CalendarContract.Events.RRULE)?.let { cursor.getString(it) }
647
+ val originalId = column(CalendarContract.Events.ORIGINAL_ID)?.let { cursor.getLong(it) }?.takeIf { it != 0L }
648
+ val storedDuration = column(CalendarContract.Events.DURATION)?.let { cursor.getString(it) }
649
+ // Recurring masters have DURATION and no DTEND.
650
+ val endDate =
651
+ column(CalendarContract.Events.DTEND)?.let { cursor.getLong(it) }
652
+ ?: (startDate + (storedDuration?.let { ImplementationHelper.durationToMillis(it) } ?: 0L))
653
+ val duration = storedDuration ?: ImplementationHelper.buildDurationFromBeginEnd(startDate, endDate, isAllDay)
654
+ val isPartOfSeries = !rrule.isNullOrEmpty() || originalId != null
655
+ val seriesStartDate =
656
+ originalId?.let { masterId ->
657
+ cr
658
+ .query(
659
+ ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, masterId),
660
+ arrayOf(CalendarContract.Events.DTSTART),
661
+ null,
662
+ null,
663
+ null,
664
+ )?.use { masterCursor ->
665
+ if (masterCursor.moveToFirst() && !masterCursor.isNull(0)) masterCursor.getLong(0) else null
666
+ }
667
+ } ?: startDate
668
+
669
+ CalendarEvent(
670
+ input.id.toString(),
671
+ (originalId ?: input.id).toString(),
672
+ column(CalendarContract.Events.TITLE)?.let { cursor.getString(it) } ?: "",
673
+ column(CalendarContract.Events.CALENDAR_ID)?.let { cursor.getLong(it).toString() },
674
+ null,
675
+ column(CalendarContract.Events.EVENT_LOCATION)?.let { cursor.getString(it) },
676
+ startDate,
677
+ seriesStartDate,
678
+ endDate,
679
+ isAllDay,
680
+ ImplementationHelper.getEventAlerts(cr, input.id),
681
+ null,
682
+ column(CalendarContract.Events.DESCRIPTION)?.let { cursor.getString(it) },
683
+ column(CalendarContract.Events.AVAILABILITY)?.let { cursor.getInt(it) },
684
+ column(CalendarContract.Events.ORGANIZER)?.let { cursor.getString(it) },
685
+ column(CalendarContract.Events.EVENT_COLOR)?.let { ImplementationHelper.intToHexColor(cursor.getInt(it)) },
686
+ duration,
687
+ null,
688
+ isPartOfSeries,
689
+ null,
690
+ column(CalendarContract.Events.STATUS)?.let { ImplementationHelper.mapEventStatus(cursor.getInt(it)) },
691
+ null,
692
+ null,
693
+ ImplementationHelper.getEventAttendees(cr, input.id),
694
+ column(CalendarContract.Events.EVENT_TIMEZONE)?.let { cursor.getString(it) },
695
+ )
696
+ }
697
+ return GetEventByIdResult(event)
698
+ }
699
+
574
700
  fun modifyCalendar(input: ModifyCalendarInput) {
575
701
  val cr = plugin.context.contentResolver
576
702
  val values =
@@ -11,4 +11,5 @@ data class CalendarInfo(
11
11
  val maxReminders: Int?,
12
12
  val location: String?,
13
13
  val isPrimary: Boolean?,
14
+ val allowsContentModifications: Boolean?,
14
15
  )
@@ -1,6 +1,7 @@
1
1
  package dev.barooni.capacitor.calendar.models.data
2
2
 
3
3
  import com.getcapacitor.JSObject
4
+ import dev.barooni.capacitor.calendar.PluginError
4
5
  import org.json.JSONArray
5
6
  import org.json.JSONException
6
7
  import java.util.Calendar
@@ -45,8 +46,8 @@ data class EventRecurrenceRule(
45
46
  }
46
47
 
47
48
  companion object {
48
- fun parseRecurrence(obj: JSObject): EventRecurrenceRule? {
49
- val frequencyString = obj.getString("frequency") ?: return null
49
+ fun parseRecurrence(obj: JSObject): EventRecurrenceRule {
50
+ val frequencyString = obj.getString("frequency") ?: throw PluginError.MissingFrequency
50
51
  val frequency =
51
52
  try {
52
53
  Frequency.valueOf(
@@ -55,7 +56,7 @@ data class EventRecurrenceRule(
55
56
  .replaceFirstChar { it.uppercase() },
56
57
  )
57
58
  } catch (_: IllegalArgumentException) {
58
- return null
59
+ throw PluginError.InvalidFrequency
59
60
  }
60
61
 
61
62
  val interval = (obj.getInteger("interval") ?: 1).coerceAtLeast(1)
@@ -13,7 +13,10 @@ data class CreateEventInput(
13
13
  val title: String = call.getString("title") ?: throw PluginError.TitleMissing
14
14
  val isAllDay: Int? = input.isAllDay?.let { if (it) 1 else 0 }
15
15
  val alerts: List<Int>? = ImplementationHelper.jsArrayToIntArray(call.getArray("alerts"))
16
- val calendarId: Long? = call.getString("calendarId")?.toLong()
16
+ val calendarId: Long? =
17
+ call.getString("calendarId")?.let {
18
+ it.toLongOrNull() ?: throw PluginError.InvalidCalendarId
19
+ }
17
20
  val location: String? = input.location
18
21
  val startDate: Long? = input.startDate
19
22
  val endDate: Long? = input.endDate
@@ -7,7 +7,10 @@ import dev.barooni.capacitor.calendar.models.enums.EventSpan
7
7
  data class DeleteEventInput(
8
8
  private val call: PluginCall,
9
9
  ) {
10
- val id = call.getString("id")?.toLongOrNull() ?: throw PluginError.MissingId
10
+ val id =
11
+ call.getString("id")?.let { idString ->
12
+ idString.toLongOrNull() ?: throw PluginError.InvalidEventId
13
+ } ?: throw PluginError.MissingId
11
14
  val instanceDate: Long? = call.getLong("instanceDate")
12
15
  val span: EventSpan = call.getInt("span")?.let { EventSpan.fromInt(it) } ?: EventSpan.THIS_EVENT
13
16
  }
@@ -7,7 +7,10 @@ import dev.barooni.capacitor.calendar.models.enums.EventSpan
7
7
  data class DeleteEventWithPromptInput(
8
8
  private val call: PluginCall,
9
9
  ) {
10
- val id: Long = call.getString("id")?.toLongOrNull() ?: throw PluginError.MissingId
10
+ val id: Long =
11
+ call.getString("id")?.let { idString ->
12
+ idString.toLongOrNull() ?: throw PluginError.InvalidEventId
13
+ } ?: throw PluginError.MissingId
11
14
  val title: String = call.getString("title") ?: throw PluginError.TitleMissing
12
15
  val message: String = call.getString("message") ?: throw PluginError.MessageMissing
13
16
  val confirmButtonText: String = call.getString("confirmButtonText") ?: "Delete"
@@ -0,0 +1,13 @@
1
+ package dev.barooni.capacitor.calendar.models.inputs
2
+
3
+ import com.getcapacitor.PluginCall
4
+ import dev.barooni.capacitor.calendar.PluginError
5
+
6
+ data class GetEventByIdInput(
7
+ private val call: PluginCall,
8
+ ) {
9
+ val id: Long =
10
+ call.getString("id")?.let { idString ->
11
+ idString.toLongOrNull() ?: throw PluginError.InvalidEventId
12
+ } ?: throw PluginError.MissingId
13
+ }
@@ -11,4 +11,9 @@ data class ListEventsInRangeInput(
11
11
  call.getLong("from")?.let { ImplementationHelper.getCalendarFromTimestamp(it).timeInMillis } ?: throw PluginError.FromDateMissing
12
12
  val to: Long =
13
13
  call.getLong("to")?.let { ImplementationHelper.getCalendarFromTimestamp(it).timeInMillis } ?: throw PluginError.ToDateMissing
14
+ val calendarIds: List<Long>? =
15
+ call
16
+ .getArray("calendarIds")
17
+ ?.let { ImplementationHelper.jsArrayToLongArray(it, PluginError.InvalidCalendarId) }
18
+ ?.takeIf { it.isNotEmpty() }
14
19
  }
@@ -9,9 +9,15 @@ import dev.barooni.capacitor.calendar.utils.ImplementationHelper
9
9
  data class ModifyEvent(
10
10
  private val call: PluginCall,
11
11
  ) {
12
- val id: Long = call.getString("id")?.toLong() ?: throw PluginError.MissingId
12
+ val id: Long =
13
+ call.getString("id")?.let { idString ->
14
+ idString.toLongOrNull() ?: throw PluginError.InvalidEventId
15
+ } ?: throw PluginError.MissingId
13
16
  val title: String? = call.getString("title")
14
- val calendarId: Long? = call.getString("calendarId")?.toLong()
17
+ val calendarId: Long? =
18
+ call.getString("calendarId")?.let {
19
+ it.toLongOrNull() ?: throw PluginError.InvalidCalendarId
20
+ }
15
21
  val location: String? = call.getString("location")
16
22
  val startDate: Long? = call.getLong("startDate")?.let { ImplementationHelper.getCalendarFromTimestamp(it).timeInMillis }
17
23
  val endDate: Long? = call.getLong("endDate")?.let { ImplementationHelper.getCalendarFromTimestamp(it).timeInMillis }
@@ -18,7 +18,7 @@ data class ModifyEventWithPromptInput(
18
18
 
19
19
  init {
20
20
  val idString = call.getString("id") ?: throw PluginError.MissingId
21
- id = idString.toLong()
21
+ id = idString.toLongOrNull() ?: throw PluginError.InvalidEventId
22
22
  val uri: Uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, id)
23
23
  intent.setData(uri)
24
24
  setEventUpdates()
@@ -19,7 +19,7 @@ data class GetDefaultCalendarResult(
19
19
  put("color", cal.color)
20
20
  put("colorName", null)
21
21
  put("isImmutable", null)
22
- put("allowsContentModifications", null)
22
+ put("allowsContentModifications", cal.allowsContentModifications)
23
23
  put("type", null)
24
24
  put("isSubscribed", null)
25
25
  put("source", null)
@@ -0,0 +1,15 @@
1
+ package dev.barooni.capacitor.calendar.models.results
2
+
3
+ import com.getcapacitor.JSObject
4
+ import dev.barooni.capacitor.calendar.models.data.CalendarEvent
5
+ import dev.barooni.capacitor.calendar.models.templates.JSResult
6
+
7
+ data class GetEventByIdResult(
8
+ private val event: CalendarEvent?,
9
+ ) : JSResult {
10
+ override fun toJSON(): JSObject {
11
+ val result = JSObject()
12
+ result.put("event", event?.toJSObject() ?: JSObject.NULL)
13
+ return result
14
+ }
15
+ }
@@ -24,7 +24,7 @@ data class ListCalendarsResult(
24
24
  obj.put("color", calendar.color)
25
25
  obj.put("colorName", null)
26
26
  obj.put("isImmutable", null)
27
- obj.put("allowsContentModifications", null)
27
+ obj.put("allowsContentModifications", calendar.allowsContentModifications)
28
28
  obj.put("type", null)
29
29
  obj.put("isSubscribed", null)
30
30
  obj.put("source", null)
@@ -12,51 +12,55 @@ data class ListEventsInRangeResult(
12
12
  val result = JSObject()
13
13
  val array = JSArray()
14
14
  events.forEach { event ->
15
- val obj = JSObject()
16
- obj.put("id", event.id)
17
- obj.put("masterId", event.masterId)
18
- obj.put("title", event.title)
19
- obj.put("calendarId", event.calendarId)
20
- obj.put("calendarItemExternalIdentifier", event.calendarItemExternalIdentifier)
21
- obj.put("location", event.location)
22
- obj.put("startDate", event.startDate)
23
- obj.put("seriesStartDate", event.seriesStartDate)
24
- obj.put("endDate", event.endDate)
25
- obj.put("isAllDay", event.isAllDay)
26
- event.alerts.let { alerts ->
27
- val alertsJSArray = JSArray()
28
- alerts.forEach { alert -> alertsJSArray.put(alert) }
29
- obj.put("alerts", alertsJSArray)
30
- }
31
- obj.put("url", event.url)
32
- obj.put("description", event.description)
33
- obj.put("availability", event.availability)
34
- obj.put("organizer", event.organizer)
35
- obj.put("color", event.color)
36
- obj.put("duration", event.duration)
37
- obj.put("isDetached", event.isDetached)
38
- obj.put("isPartOfSeries", event.isPartOfSeries)
39
- obj.put("birthdayContactIdentifier", event.birthdayContactIdentifier)
40
- obj.put("status", event.status)
41
- obj.put("creationDate", event.creationDate)
42
- obj.put("lastModifiedDate", event.lastModifiedDate)
43
- event.attendees.let { attendees ->
44
- val attendeesJSArray = JSArray()
45
- attendees.forEach { attendee ->
46
- val attendeeObj = JSObject()
47
- attendeeObj.put("email", attendee.email)
48
- attendeeObj.put("name", attendee.name)
49
- attendeeObj.put("role", attendee.relationship)
50
- attendeeObj.put("status", attendee.status)
51
- attendeeObj.put("type", attendee.type)
52
- attendeesJSArray.put(attendeeObj)
53
- }
54
- obj.put("attendees", attendeesJSArray)
55
- }
56
- obj.put("timezone", event.timezone)
57
- array.put(obj)
15
+ array.put(event.toJSObject())
58
16
  }
59
17
  result.put("result", array)
60
18
  return result
61
19
  }
62
20
  }
21
+
22
+ internal fun CalendarEvent.toJSObject(): JSObject {
23
+ val obj = JSObject()
24
+ obj.put("id", id)
25
+ obj.put("masterId", masterId)
26
+ obj.put("title", title)
27
+ obj.put("calendarId", calendarId)
28
+ obj.put("calendarItemExternalIdentifier", calendarItemExternalIdentifier)
29
+ obj.put("location", location)
30
+ obj.put("startDate", startDate)
31
+ obj.put("seriesStartDate", seriesStartDate)
32
+ obj.put("endDate", endDate)
33
+ obj.put("isAllDay", isAllDay)
34
+ alerts.let { alerts ->
35
+ val alertsJSArray = JSArray()
36
+ alerts.forEach { alert -> alertsJSArray.put(alert) }
37
+ obj.put("alerts", alertsJSArray)
38
+ }
39
+ obj.put("url", url)
40
+ obj.put("description", description)
41
+ obj.put("availability", availability)
42
+ obj.put("organizer", organizer)
43
+ obj.put("color", color)
44
+ obj.put("duration", duration)
45
+ obj.put("isDetached", isDetached)
46
+ obj.put("isPartOfSeries", isPartOfSeries)
47
+ obj.put("birthdayContactIdentifier", birthdayContactIdentifier)
48
+ obj.put("status", status)
49
+ obj.put("creationDate", creationDate)
50
+ obj.put("lastModifiedDate", lastModifiedDate)
51
+ attendees.let { attendees ->
52
+ val attendeesJSArray = JSArray()
53
+ attendees.forEach { attendee ->
54
+ val attendeeObj = JSObject()
55
+ attendeeObj.put("email", attendee.email)
56
+ attendeeObj.put("name", attendee.name)
57
+ attendeeObj.put("role", attendee.relationship)
58
+ attendeeObj.put("status", attendee.status)
59
+ attendeeObj.put("type", attendee.type)
60
+ attendeesJSArray.put(attendeeObj)
61
+ }
62
+ obj.put("attendees", attendeesJSArray)
63
+ }
64
+ obj.put("timezone", timezone)
65
+ return obj
66
+ }
@@ -87,6 +87,21 @@ class ImplementationHelper {
87
87
  return Pair(start, exclusiveEnd)
88
88
  }
89
89
 
90
+ /**
91
+ * Throws [PluginError.EventNotFound] when no event row has this id.
92
+ */
93
+ fun ensureEventExists(
94
+ cr: ContentResolver,
95
+ eventId: Long,
96
+ ) {
97
+ val uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId)
98
+ val projection = arrayOf(CalendarContract.Events._ID)
99
+ val exists = cr.query(uri, projection, null, null, null)?.use { cursor -> cursor.moveToFirst() } ?: false
100
+ if (!exists) {
101
+ throw PluginError.EventNotFound
102
+ }
103
+ }
104
+
90
105
  /**
91
106
  * Reads [CalendarContract.Events.ALL_DAY] for an existing event.
92
107
  * Throws [PluginError.EventNotFound] when the row is missing or unreadable,
@@ -121,9 +136,12 @@ class ImplementationHelper {
121
136
  return list
122
137
  }
123
138
 
124
- fun jsArrayToLongArray(array: JSArray): List<Long> {
139
+ fun jsArrayToLongArray(
140
+ array: JSArray,
141
+ error: PluginError = PluginError.InvalidEventId,
142
+ ): List<Long> {
125
143
  val list = array.toList<String>()
126
- return list.map { it.toLongOrNull() ?: throw PluginError.MissingId }
144
+ return list.map { it.toLongOrNull() ?: throw error }
127
145
  }
128
146
 
129
147
  fun hexToColorInt(hex: String?): Int? {
@@ -294,6 +312,7 @@ class ImplementationHelper {
294
312
  CalendarContract.Calendars.MAX_REMINDERS,
295
313
  CalendarContract.Calendars.CALENDAR_LOCATION,
296
314
  CalendarContract.Calendars.IS_PRIMARY,
315
+ CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
297
316
  )
298
317
 
299
318
  val calendars = mutableListOf<CalendarInfo>()
@@ -385,14 +404,38 @@ class ImplementationHelper {
385
404
  cursor.getColumnIndexOrThrow(CalendarContract.Calendars.IS_PRIMARY).let {
386
405
  if (it < 0) null else cursor.getInt(it) == 1
387
406
  }
407
+ val accessLevel =
408
+ cursor.getColumnIndex(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL).let {
409
+ if (it < 0 || cursor.isNull(it)) null else cursor.getInt(it)
410
+ }
388
411
  calendars.add(
389
- CalendarInfo(id, title, internalName, color, visible, accountName, ownerAccount, maxReminders, location, isPrimary),
412
+ CalendarInfo(
413
+ id,
414
+ title,
415
+ internalName,
416
+ color,
417
+ visible,
418
+ accountName,
419
+ ownerAccount,
420
+ maxReminders,
421
+ location,
422
+ isPrimary,
423
+ allowsContentModifications(accessLevel),
424
+ ),
390
425
  )
391
426
  }
392
427
  }
393
428
  return calendars
394
429
  }
395
430
 
431
+ /**
432
+ * Whether events can be added to a calendar with the given `CALENDAR_ACCESS_LEVEL`: contributor
433
+ * access or above, the same threshold the AOSP Calendar app uses. `null` when the provider did
434
+ * not report a level.
435
+ */
436
+ fun allowsContentModifications(accessLevel: Int?): Boolean? =
437
+ accessLevel?.let { it >= CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR }
438
+
396
439
  fun requiresInstanceDateForDelete(
397
440
  cr: ContentResolver,
398
441
  eventId: Long,
@@ -776,6 +819,21 @@ class ImplementationHelper {
776
819
  }
777
820
  }
778
821
 
822
+ fun durationToMillis(duration: String): Long {
823
+ val match =
824
+ Regex("^P(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?$").matchEntire(duration.trim())
825
+ ?: return 0L
826
+ val (weeks, days, hours, minutes, seconds) = match.destructured
827
+
828
+ fun part(value: String) = value.toLongOrNull() ?: 0L
829
+ return (
830
+ (part(weeks) * 7 + part(days)) * 24 * 3600 +
831
+ part(hours) * 3600 +
832
+ part(minutes) * 60 +
833
+ part(seconds)
834
+ ) * 1000
835
+ }
836
+
779
837
  fun mapAttendeeRelationship(relationship: Int): String =
780
838
  when (relationship) {
781
839
  CalendarContract.Attendees.RELATIONSHIP_ATTENDEE -> "attendee"
@@ -0,0 +1,69 @@
1
+ package dev.barooni.capacitor.calendar.utils
2
+
3
+ import android.content.ActivityNotFoundException
4
+ import com.getcapacitor.PluginCall
5
+ import dev.barooni.capacitor.calendar.PluginError
6
+
7
+ /**
8
+ * Maps thrown exceptions to [PluginError] and rejects the Capacitor call.
9
+ */
10
+ object PluginCallRejecter {
11
+ fun reject(
12
+ call: PluginCall,
13
+ error: Exception?,
14
+ ) {
15
+ val pluginError = toPluginError(error)
16
+ val message =
17
+ pluginError?.message
18
+ ?: error?.message
19
+ ?: PluginError.CustomError("An unknown error has occurred.").message
20
+ call.reject(message, pluginError?.code)
21
+ }
22
+
23
+ fun toPluginError(error: Exception?): PluginError? =
24
+ when (error) {
25
+ is PluginError -> {
26
+ error
27
+ }
28
+
29
+ is ActivityNotFoundException -> {
30
+ PluginError.NotSupported(
31
+ wrapSystemError("Failed to launch calendar app.", error.message),
32
+ )
33
+ }
34
+
35
+ is SecurityException -> {
36
+ PluginError.PermissionDenied(
37
+ wrapSystemError("Calendar permission was denied.", error.message),
38
+ )
39
+ }
40
+
41
+ null -> {
42
+ null
43
+ }
44
+
45
+ else -> {
46
+ PluginError.IoError(
47
+ wrapSystemError(
48
+ "An I/O error occurred while accessing the calendar.",
49
+ error.message,
50
+ ),
51
+ )
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Lead with the stable plugin sentence; append a different non-blank OS message in parentheses.
57
+ */
58
+ fun wrapSystemError(
59
+ canonicalMessage: String,
60
+ systemMessage: String?,
61
+ ): String {
62
+ val detail = systemMessage?.trim().orEmpty()
63
+ return if (detail.isEmpty() || detail == canonicalMessage) {
64
+ canonicalMessage
65
+ } else {
66
+ "$canonicalMessage ($detail)"
67
+ }
68
+ }
69
+ }