-
-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathContext.kt
More file actions
1205 lines (1086 loc) · 43.5 KB
/
Context.kt
File metadata and controls
1205 lines (1086 loc) · 43.5 KB
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
package org.fossify.calendar.extensions
import android.accounts.Account
import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Resources
import android.database.Cursor
import android.graphics.Bitmap
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Bundle
import android.provider.CalendarContract
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import androidx.print.PrintHelper
import org.fossify.calendar.R
import org.fossify.calendar.activities.CalendarPickerActivity
import org.fossify.calendar.activities.EventActivity
import org.fossify.calendar.activities.SnoozeReminderActivity
import org.fossify.calendar.activities.TaskActivity
import org.fossify.calendar.databases.EventsDatabase
import org.fossify.calendar.databinding.DayMonthlyEventViewBinding
import org.fossify.calendar.helpers.ACTION_MARK_COMPLETED
import org.fossify.calendar.helpers.AUTOMATIC_BACKUP_REQUEST_CODE
import org.fossify.calendar.helpers.CalDAVHelper
import org.fossify.calendar.helpers.Config
import org.fossify.calendar.helpers.DAY
import org.fossify.calendar.helpers.DEFAULT_START_TIME_CURRENT_TIME
import org.fossify.calendar.helpers.DEFAULT_START_TIME_NEXT_FULL_HOUR
import org.fossify.calendar.helpers.DELETE_ALL_OCCURRENCES
import org.fossify.calendar.helpers.DELETE_FUTURE_OCCURRENCES
import org.fossify.calendar.helpers.DELETE_SELECTED_OCCURRENCE
import org.fossify.calendar.helpers.DUMMY_ALARM_REQUEST_CODE
import org.fossify.calendar.helpers.EVENT_ID
import org.fossify.calendar.helpers.EVENT_OCCURRENCE_TS
import org.fossify.calendar.helpers.EventsHelper
import org.fossify.calendar.helpers.FLAG_TASK_COMPLETED
import org.fossify.calendar.helpers.Formatter
import org.fossify.calendar.helpers.IS_TASK_COMPLETED
import org.fossify.calendar.helpers.IcsExporter
import org.fossify.calendar.helpers.MONTH
import org.fossify.calendar.helpers.MyWidgetDateProvider
import org.fossify.calendar.helpers.MyWidgetListProvider
import org.fossify.calendar.helpers.MyWidgetMonthlyProvider
import org.fossify.calendar.helpers.NEW_EVENT_START_TS
import org.fossify.calendar.helpers.REMINDER_NOTIFICATION
import org.fossify.calendar.helpers.REMINDER_OFF
import org.fossify.calendar.helpers.SCHEDULE_CALDAV_REQUEST_CODE
import org.fossify.calendar.helpers.WEEK
import org.fossify.calendar.helpers.YEAR
import org.fossify.calendar.helpers.generateImportId
import org.fossify.calendar.helpers.getActivityToOpen
import org.fossify.calendar.helpers.getNextAutoBackupTime
import org.fossify.calendar.helpers.getNowSeconds
import org.fossify.calendar.helpers.getPreviousAutoBackupTime
import org.fossify.calendar.helpers.isWeekend
import org.fossify.calendar.interfaces.CalendarsDao
import org.fossify.calendar.interfaces.EventsDao
import org.fossify.calendar.interfaces.TasksDao
import org.fossify.calendar.interfaces.WidgetsDao
import org.fossify.calendar.models.DayMonthly
import org.fossify.calendar.models.Event
import org.fossify.calendar.models.ListEvent
import org.fossify.calendar.models.ListItem
import org.fossify.calendar.models.ListSectionDay
import org.fossify.calendar.models.ListSectionMonth
import org.fossify.calendar.models.Task
import org.fossify.calendar.receivers.AutomaticBackupReceiver
import org.fossify.calendar.receivers.CalDAVSyncReceiver
import org.fossify.calendar.receivers.DummyAlarmReceiver
import org.fossify.calendar.receivers.NotificationReceiver
import org.fossify.calendar.services.MarkCompletedService
import org.fossify.calendar.services.SnoozeService
import org.fossify.commons.extensions.adjustAlpha
import org.fossify.commons.extensions.applyColorFilter
import org.fossify.commons.extensions.beVisibleIf
import org.fossify.commons.extensions.createDocumentUriUsingFirstParentTreeUri
import org.fossify.commons.extensions.createSAFFileSdk30
import org.fossify.commons.extensions.ensureTwoDigits
import org.fossify.commons.extensions.formatSecondsToTimeString
import org.fossify.commons.extensions.getContrastColor
import org.fossify.commons.extensions.getDoesFilePathExist
import org.fossify.commons.extensions.getMimeType
import org.fossify.commons.extensions.grantReadUriPermission
import org.fossify.commons.extensions.hasProperStoredFirstParentUri
import org.fossify.commons.extensions.removeBit
import org.fossify.commons.extensions.showErrorToast
import org.fossify.commons.extensions.toast
import org.fossify.commons.helpers.FONT_SIZE_LARGE
import org.fossify.commons.helpers.FONT_SIZE_MEDIUM
import org.fossify.commons.helpers.FONT_SIZE_SMALL
import org.fossify.commons.helpers.FRIDAY_BIT
import org.fossify.commons.helpers.MONDAY_BIT
import org.fossify.commons.helpers.SATURDAY_BIT
import org.fossify.commons.helpers.SILENT
import org.fossify.commons.helpers.SUNDAY_BIT
import org.fossify.commons.helpers.THURSDAY_BIT
import org.fossify.commons.helpers.TUESDAY_BIT
import org.fossify.commons.helpers.WEDNESDAY_BIT
import org.fossify.commons.helpers.WEEK_SECONDS
import org.fossify.commons.helpers.YEAR_SECONDS
import org.fossify.commons.helpers.ensureBackgroundThread
import org.fossify.commons.helpers.isOreoPlus
import org.fossify.commons.helpers.isRPlus
import org.fossify.commons.helpers.isSPlus
import org.fossify.commons.helpers.isTiramisuPlus
import org.joda.time.DateTime
import org.joda.time.DateTimeConstants
import org.joda.time.Days
import org.joda.time.LocalDate
import java.io.File
import java.io.FileOutputStream
import java.util.Calendar
import java.util.concurrent.TimeUnit
import kotlin.math.absoluteValue
import kotlin.math.roundToInt
val Context.config: Config get() = Config.newInstance(applicationContext)
val Context.eventsDB: EventsDao get() = EventsDatabase.getInstance(applicationContext).EventsDao()
val Context.calendarsDB: CalendarsDao
get() = EventsDatabase.getInstance(applicationContext).CalendarsDao()
val Context.widgetsDB: WidgetsDao
get() = EventsDatabase.getInstance(applicationContext).WidgetsDao()
val Context.completedTasksDB: TasksDao
get() = EventsDatabase.getInstance(applicationContext).TasksDao()
val Context.eventsHelper: EventsHelper get() = EventsHelper(this)
val Context.calDAVHelper: CalDAVHelper get() = CalDAVHelper(this)
fun Context.updateWidgets() {
val widgetIDs = AppWidgetManager.getInstance(applicationContext)
?.getAppWidgetIds(ComponentName(applicationContext, MyWidgetMonthlyProvider::class.java))
?: return
if (widgetIDs.isNotEmpty()) {
Intent(applicationContext, MyWidgetMonthlyProvider::class.java).apply {
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIDs)
sendBroadcast(this)
}
}
updateListWidget()
updateDateWidget()
}
fun Context.updateListWidget() {
val widgetIDs = AppWidgetManager.getInstance(applicationContext)
?.getAppWidgetIds(ComponentName(applicationContext, MyWidgetListProvider::class.java))
?: return
if (widgetIDs.isNotEmpty()) {
Intent(applicationContext, MyWidgetListProvider::class.java).apply {
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIDs)
sendBroadcast(this)
}
}
AppWidgetManager.getInstance(applicationContext)
?.notifyAppWidgetViewDataChanged(widgetIDs, R.id.widget_event_list)
}
fun Context.updateDateWidget() {
val widgetIDs = AppWidgetManager.getInstance(applicationContext)
?.getAppWidgetIds(ComponentName(applicationContext, MyWidgetDateProvider::class.java))
?: return
if (widgetIDs.isNotEmpty()) {
Intent(applicationContext, MyWidgetDateProvider::class.java).apply {
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIDs)
sendBroadcast(this)
}
}
}
fun Context.scheduleAllEvents() {
val events = eventsDB.getEventsOrTasksAtReboot(getNowSeconds())
events.forEach {
scheduleNextEventReminder(it, false)
}
}
fun Context.scheduleNextEventReminder(event: Event, showToasts: Boolean) {
val validReminders = event.getReminders().filter { it.type == REMINDER_NOTIFICATION }
if (validReminders.isEmpty()) {
if (showToasts) {
toast(org.fossify.commons.R.string.saving)
}
return
}
val now = getNowSeconds()
val reminderSeconds = validReminders.reversed().map { it.minutes * 60 }
val isTask = event.isTask()
eventsHelper.getEvents(now, now + YEAR, event.id!!, false) { events ->
if (events.isNotEmpty()) {
for (curEvent in events) {
if (isTask && curEvent.isTaskCompleted()) {
// skip scheduling reminders for completed tasks
continue
}
for (curReminder in reminderSeconds) {
if (curEvent.getEventStartTS() - curReminder > now) {
scheduleEventIn(
(curEvent.getEventStartTS() - curReminder) * 1000L,
curEvent,
showToasts
)
return@getEvents
}
}
}
}
if (showToasts) {
toast(org.fossify.commons.R.string.saving)
}
}
}
fun Context.scheduleEventIn(notifyAtMillis: Long, event: Event, showToasts: Boolean) {
val now = System.currentTimeMillis() / 1000
if (event.getEventStartTS() < now) {
if (showToasts) {
toast(org.fossify.commons.R.string.saving)
}
return
}
if (showToasts) {
val secondsTillEvent = event.getEventStartTS() - now
val msg = String.format(
getString(org.fossify.commons.R.string.time_remaining),
formatSecondsToTimeString(secondsTillEvent.toInt())
)
toast(msg)
}
val pendingIntent = getNotificationIntent(event)
setExactAlarm(notifyAtMillis + 1000, pendingIntent)
}
// hide the actual notification from the top bar
fun Context.cancelNotification(id: Long) {
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(id.toInt())
}
fun Context.getNotificationIntent(event: Event): PendingIntent {
val intent = Intent(this, NotificationReceiver::class.java)
intent.putExtra(EVENT_ID, event.id)
intent.putExtra(EVENT_OCCURRENCE_TS, event.startTS)
return PendingIntent.getBroadcast(
this,
event.id!!.toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
fun Context.cancelPendingIntent(id: Long) {
val intent = Intent(this, NotificationReceiver::class.java)
PendingIntent.getBroadcast(
this,
id.toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
).cancel()
}
fun Context.getAutomaticBackupIntent(): PendingIntent {
val intent = Intent(this, AutomaticBackupReceiver::class.java)
return PendingIntent.getBroadcast(
this,
AUTOMATIC_BACKUP_REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
fun Context.scheduleNextAutomaticBackup() {
if (config.autoBackup) {
val backupAtMillis = getNextAutoBackupTime().millis
val pendingIntent = getAutomaticBackupIntent()
setExactAlarm(backupAtMillis, pendingIntent)
}
}
fun Context.cancelScheduledAutomaticBackup() = getAlarmManager().cancel(getAutomaticBackupIntent())
fun Context.checkAndBackupEventsOnBoot() {
if (config.autoBackup) {
val previousRealBackupTime = config.lastAutoBackupTime
val previousScheduledBackupTime = getPreviousAutoBackupTime().seconds()
val missedPreviousBackup = previousRealBackupTime < previousScheduledBackupTime
if (missedPreviousBackup) {
// device was probably off at the scheduled time so backup now
backupEventsAndTasks()
}
}
}
fun Context.backupEventsAndTasks() {
require(isRPlus())
ensureBackgroundThread {
val config = config
val events = eventsHelper.getEventsToExport(
calendars = config.autoBackupCalendars.map { it.toLong() } as ArrayList<Long>,
exportEvents = config.autoBackupEvents,
exportTasks = config.autoBackupTasks,
exportPastEntries = config.autoBackupPastEntries
)
if (events.isEmpty()) {
toast(org.fossify.commons.R.string.no_entries_for_exporting)
config.lastAutoBackupTime = getNowSeconds()
scheduleNextAutomaticBackup()
return@ensureBackgroundThread
}
val now = DateTime.now()
val year = now.year.toString()
val month = now.monthOfYear.ensureTwoDigits()
val day = now.dayOfMonth.ensureTwoDigits()
val hours = now.hourOfDay.ensureTwoDigits()
val minutes = now.minuteOfHour.ensureTwoDigits()
val seconds = now.secondOfMinute.ensureTwoDigits()
val filename = config.autoBackupFilename
.replace("%Y", year, false)
.replace("%M", month, false)
.replace("%D", day, false)
.replace("%h", hours, false)
.replace("%m", minutes, false)
.replace("%s", seconds, false)
val outputFolder = File(config.autoBackupFolder).apply {
mkdirs()
}
var exportFile = File(outputFolder, "$filename.ics")
var exportFilePath = exportFile.absolutePath
val outputStream = try {
if (hasProperStoredFirstParentUri(exportFilePath)) {
val exportFileUri = createDocumentUriUsingFirstParentTreeUri(exportFilePath)
if (!getDoesFilePathExist(exportFilePath)) {
createSAFFileSdk30(exportFilePath)
}
applicationContext.contentResolver.openOutputStream(exportFileUri, "wt")
?: FileOutputStream(exportFile)
} else {
var num = 0
while (getDoesFilePathExist(exportFilePath) && !exportFile.canWrite()) {
num++
exportFile = File(outputFolder, "${filename}_${num}.ics")
exportFilePath = exportFile.absolutePath
}
FileOutputStream(exportFile)
}
} catch (e: Exception) {
showErrorToast(e)
null
}
IcsExporter(this).exportEvents(outputStream, events, showExportingToast = false) { result ->
when (result) {
IcsExporter.ExportResult.EXPORT_PARTIAL -> toast(org.fossify.commons.R.string.exporting_some_entries_failed)
IcsExporter.ExportResult.EXPORT_FAIL -> toast(org.fossify.commons.R.string.exporting_failed)
else -> {}
}
MediaScannerConnection.scanFile(
this,
arrayOf(exportFilePath),
arrayOf(exportFilePath.getMimeType())
) { _, _ -> }
config.lastAutoBackupTime = getNowSeconds()
}
scheduleNextAutomaticBackup()
}
}
fun Context.getRepetitionText(seconds: Int) = when (seconds) {
0 -> getString(R.string.no_repetition)
DAY -> getString(R.string.daily)
WEEK -> getString(R.string.weekly)
MONTH -> getString(R.string.monthly)
YEAR -> getString(R.string.yearly)
else -> {
when {
seconds % YEAR == 0 -> resources.getQuantityString(
org.fossify.commons.R.plurals.years,
seconds / YEAR,
seconds / YEAR
)
seconds % MONTH == 0 -> resources.getQuantityString(
org.fossify.commons.R.plurals.months,
seconds / MONTH,
seconds / MONTH
)
seconds % WEEK == 0 -> resources.getQuantityString(
org.fossify.commons.R.plurals.weeks,
seconds / WEEK,
seconds / WEEK
)
else -> resources.getQuantityString(
org.fossify.commons.R.plurals.days,
seconds / DAY,
seconds / DAY
)
}
}
}
fun Context.notifyRunningEvents() {
eventsHelper.getRunningEventsOrTasks()
.filter { !it.isAttendeeInviteDeclined() }
.filter { it.getReminders().any { reminder -> reminder.type == REMINDER_NOTIFICATION } }
.forEach {
notifyEvent(it)
}
}
fun Context.notifyEvent(originalEvent: Event) {
var event = originalEvent.copy()
val currentSeconds = getNowSeconds()
var eventStartTS =
if (event.getIsAllDay()) Formatter.getDayStartTS(Formatter.getDayCodeFromTS(event.startTS)) else event.startTS
// make sure refer to the proper repeatable event instance with "Tomorrow", or the specific date
if (event.repeatInterval != 0 && eventStartTS - event.reminder1Minutes * 60 < currentSeconds) {
val events = eventsHelper.getRepeatableEventsFor(
currentSeconds - WEEK_SECONDS,
currentSeconds + YEAR_SECONDS,
event.id!!
)
for (currEvent in events) {
eventStartTS = if (currEvent.getIsAllDay()) Formatter.getDayStartTS(
Formatter.getDayCodeFromTS(currEvent.startTS)
) else currEvent.startTS
val firstReminderMinutes =
arrayOf(
currEvent.reminder3Minutes,
currEvent.reminder2Minutes,
currEvent.reminder1Minutes
).filter { it != REMINDER_OFF }.max()
if (eventStartTS - firstReminderMinutes * 60 > currentSeconds) {
break
}
event = currEvent
}
}
val pendingIntent = getPendingIntent(applicationContext, event)
val startTime = Formatter.getTimeFromTS(applicationContext, event.startTS)
val endTime = Formatter.getTimeFromTS(applicationContext, event.endTS)
val startDate = Formatter.getDateFromTS(event.startTS)
val displayedStartDate = when (startDate) {
LocalDate.now() -> ""
LocalDate.now().plusDays(1) -> getString(org.fossify.commons.R.string.tomorrow)
else -> "${Formatter.getDateFromCode(this, Formatter.getDayCodeFromTS(event.startTS))},"
}
val timeRange = if (event.getIsAllDay()) getString(R.string.all_day) else getFormattedEventTime(
startTime,
endTime
)
val descriptionOrLocation = if (config.replaceDescription) event.location else event.description
val content = "$displayedStartDate $timeRange $descriptionOrLocation".trim()
ensureBackgroundThread {
if (event.isTask()) eventsHelper.updateIsTaskCompleted(event)
val notification = getNotification(pendingIntent, event, content)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
try {
if (notification != null) {
notificationManager.notify(event.id!!.toInt(), notification)
}
} catch (e: Exception) {
showErrorToast(e)
}
}
}
fun Context.getUsageAttributeForStreamType(): Int {
return when (config.reminderAudioStream) {
AudioManager.STREAM_ALARM -> AudioAttributes.USAGE_ALARM
AudioManager.STREAM_SYSTEM -> AudioAttributes.USAGE_ASSISTANCE_SONIFICATION
AudioManager.STREAM_NOTIFICATION -> AudioAttributes.USAGE_NOTIFICATION_EVENT
AudioManager.STREAM_RING -> AudioAttributes.USAGE_NOTIFICATION_RINGTONE
else -> AudioAttributes.USAGE_NOTIFICATION_EVENT
}
}
@SuppressLint("NewApi")
fun Context.getNotification(
pendingIntent: PendingIntent,
event: Event,
content: String,
publicVersion: Boolean = false
): Notification? {
var soundUri = config.reminderSoundUri
if (soundUri == SILENT) {
soundUri = ""
} else {
grantReadUriPermission(soundUri)
}
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// create a new channel for every new sound uri as the new Android Oreo notification system is fundamentally broken
if (soundUri != config.lastSoundUri || config.lastVibrateOnReminder != config.vibrateOnReminder) {
if (!publicVersion) {
if (isOreoPlus()) {
val oldChannelId =
"simple_calendar_${config.lastReminderChannel}_${config.reminderAudioStream}_${event.calendarId}"
notificationManager.deleteNotificationChannel(oldChannelId)
}
}
config.lastVibrateOnReminder = config.vibrateOnReminder
config.lastReminderChannel = System.currentTimeMillis()
config.lastSoundUri = soundUri
}
val channelId =
"simple_calendar_${config.lastReminderChannel}_${config.reminderAudioStream}_${event.calendarId}"
val audioAttributes = AudioAttributes.Builder()
.setUsage(getUsageAttributeForStreamType())
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
val name = calendarsDB.getCalendarWithId(event.calendarId)?.getDisplayTitle()
val importance = NotificationManager.IMPORTANCE_HIGH
NotificationChannel(channelId, name, importance).apply {
setBypassDnd(true)
enableLights(true)
lightColor = event.color
enableVibration(config.vibrateOnReminder)
setSound(soundUri.toUri(), audioAttributes)
try {
notificationManager.createNotificationChannel(this)
} catch (e: Exception) {
showErrorToast(e)
return null
}
}
val contentTitle = if (publicVersion) resources.getString(R.string.app_name) else event.title
val contentText =
if (publicVersion) resources.getString(R.string.public_event_notification_text) else content
val builder = NotificationCompat.Builder(this, channelId)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_calendar_vector)
.setStyle(NotificationCompat.BigTextStyle().bigText(contentText))
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_LIGHTS)
.setCategory(Notification.CATEGORY_EVENT)
.setAutoCancel(true)
.setChannelId(channelId)
.apply {
if (event.isTask() && !event.isTaskCompleted()) {
addAction(
R.drawable.ic_task_vector,
getString(R.string.mark_completed),
getMarkCompletedPendingIntent(this@getNotification, event)
)
}
addAction(
org.fossify.commons.R.drawable.ic_snooze_vector,
getString(org.fossify.commons.R.string.snooze),
getSnoozePendingIntent(this@getNotification, event)
)
}
if (config.vibrateOnReminder) {
val vibrateArray = LongArray(2) { 500 }
builder.setVibrate(vibrateArray)
}
if (!publicVersion) {
val notification = getNotification(pendingIntent, event, content, true)
if (notification != null) {
builder.setPublicVersion(notification)
}
}
val notification = builder.build()
if (config.loopReminders) {
notification.flags = notification.flags or Notification.FLAG_INSISTENT
}
return notification
}
private fun getFormattedEventTime(startTime: String, endTime: String) =
if (startTime == endTime) startTime else "$startTime \u2013 $endTime"
private fun getPendingIntent(context: Context, event: Event): PendingIntent {
val activityClass = getActivityToOpen(event.isTask())
val intent = Intent(context, activityClass)
intent.putExtra(EVENT_ID, event.id)
intent.putExtra(EVENT_OCCURRENCE_TS, event.startTS)
return PendingIntent.getActivity(
context,
event.id!!.toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
private fun getSnoozePendingIntent(context: Context, event: Event): PendingIntent {
val snoozeClass =
if (context.config.useSameSnooze) SnoozeService::class.java else SnoozeReminderActivity::class.java
val intent = Intent(context, snoozeClass).setAction("Snooze")
intent.putExtra(EVENT_ID, event.id)
return if (context.config.useSameSnooze) {
PendingIntent.getService(
context,
event.id!!.toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
} else {
PendingIntent.getActivity(
context,
event.id!!.toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
}
private fun getMarkCompletedPendingIntent(context: Context, task: Event): PendingIntent {
val intent = Intent(context, MarkCompletedService::class.java).setAction(ACTION_MARK_COMPLETED)
intent.putExtra(EVENT_ID, task.id)
intent.putExtra(EVENT_OCCURRENCE_TS, task.startTS)
return PendingIntent.getService(
context,
task.id!!.toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
fun Context.rescheduleReminder(event: Event?, minutes: Int) {
if (event != null) {
cancelPendingIntent(event.id!!)
applicationContext.scheduleEventIn(
System.currentTimeMillis() + minutes * 60000,
event,
false
)
cancelNotification(event.id!!)
}
}
// if the default event start time is set to "Next full hour" and the event is created before midnight, it could change the day
fun Context.launchNewEventIntent(
dayCode: String = Formatter.getTodayCode(),
allowChangingDay: Boolean = false
) {
Intent(applicationContext, EventActivity::class.java).apply {
putExtra(NEW_EVENT_START_TS, getNewEventTimestampFromCode(dayCode, allowChangingDay))
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(this)
}
}
// if the default start time is set to "Next full hour" and the task is created before midnight, it could change the day
fun Context.launchNewTaskIntent(
dayCode: String = Formatter.getTodayCode(),
allowChangingDay: Boolean = false
) {
Intent(applicationContext, TaskActivity::class.java).apply {
putExtra(NEW_EVENT_START_TS, getNewEventTimestampFromCode(dayCode, allowChangingDay))
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(this)
}
}
fun Context.launchNewEventOrTaskActivity() {
if (config.allowCreatingTasks) {
Intent(this, CalendarPickerActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(this)
}
} else {
launchNewEventIntent()
}
}
fun Context.getNewEventTimestampFromCode(dayCode: String, allowChangingDay: Boolean = false): Long {
val calendar = Calendar.getInstance()
val defaultStartTime = config.defaultStartTime
val currHour = calendar.get(Calendar.HOUR_OF_DAY)
var dateTime = Formatter.getLocalDateTimeFromCode(dayCode).withHourOfDay(currHour)
var newDateTime =
dateTime.plusHours(1).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0)
if (!allowChangingDay && dateTime.dayOfMonth() != newDateTime.dayOfMonth()) {
newDateTime = newDateTime.minusDays(1)
}
return when (defaultStartTime) {
DEFAULT_START_TIME_CURRENT_TIME -> {
val currMinutes = calendar.get(Calendar.MINUTE)
dateTime.withMinuteOfHour(currMinutes).seconds()
}
DEFAULT_START_TIME_NEXT_FULL_HOUR -> newDateTime.seconds()
else -> {
val hours = defaultStartTime / 60
val minutes = defaultStartTime % 60
dateTime = Formatter.getLocalDateTimeFromCode(dayCode).withHourOfDay(hours)
.withMinuteOfHour(minutes)
newDateTime = dateTime
// make sure the date doesn't change
newDateTime.withDate(dateTime.year, dateTime.monthOfYear, dateTime.dayOfMonth).seconds()
}
}
}
fun Context.getSyncedCalDAVCalendars() =
calDAVHelper.getCalDAVCalendars(config.caldavSyncedCalendarIds, false)
fun Context.recheckCalDAVCalendars(scheduleNextCalDAVSync: Boolean, callback: () -> Unit) {
if (config.caldavSync) {
ensureBackgroundThread {
calDAVHelper.refreshCalendars(false, scheduleNextCalDAVSync, callback)
updateWidgets()
}
}
}
fun Context.scheduleCalDAVSync(activate: Boolean) {
val syncIntent = Intent(applicationContext, CalDAVSyncReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
applicationContext,
SCHEDULE_CALDAV_REQUEST_CODE,
syncIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val alarmManager = getAlarmManager()
alarmManager.cancel(pendingIntent)
if (activate) {
val syncCheckInterval = 2 * AlarmManager.INTERVAL_HOUR
try {
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + syncCheckInterval,
syncCheckInterval,
pendingIntent
)
} catch (ignored: Exception) {
}
}
}
fun Context.addDayEvents(
day: DayMonthly,
linearLayout: LinearLayout,
res: Resources,
dividerMargin: Int
) {
val eventLayoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
day.dayEvents.sortedWith(compareBy<Event> {
if (it.getIsAllDay()) {
Formatter.getDayStartTS(Formatter.getDayCodeFromTS(it.startTS)) - 1
} else {
it.startTS
}
}.thenBy {
if (it.getIsAllDay()) {
Formatter.getDayEndTS(Formatter.getDayCodeFromTS(it.endTS))
} else {
it.endTS
}
}.thenBy { it.title }).forEach {
val backgroundDrawable = res.getDrawable(R.drawable.day_monthly_event_background)
backgroundDrawable.applyColorFilter(it.color)
eventLayoutParams.setMargins(dividerMargin, 0, dividerMargin, dividerMargin)
var textColor = it.color.getContrastColor()
if (!day.isThisMonth) {
backgroundDrawable.alpha = 64
textColor = textColor.adjustAlpha(0.25f)
}
DayMonthlyEventViewBinding.inflate(LayoutInflater.from(this)).apply {
root.background = backgroundDrawable
root.layoutParams = eventLayoutParams
linearLayout.addView(root)
dayMonthlyEventId.apply {
setTextColor(textColor)
text = it.title.replace(" ", "\u00A0") // allow word break by char
checkViewStrikeThrough(it.shouldStrikeThrough())
contentDescription = it.title
}
dayMonthlyTaskImage.beVisibleIf(it.isTask())
if (it.isTask()) {
dayMonthlyTaskImage.applyColorFilter(textColor)
}
}
}
}
fun Context.getEventListItems(
events: List<Event>,
addSectionDays: Boolean = true,
addSectionMonths: Boolean = true
): ArrayList<ListItem> {
val listItems = ArrayList<ListItem>(events.size)
val replaceDescription = config.replaceDescription
// move all-day events in front of others
val sorted = events.sortedWith(compareBy<Event> {
if (it.getIsAllDay()) {
Formatter.getDayStartTS(Formatter.getDayCodeFromTS(it.startTS)) - 1
} else {
it.startTS
}
}.thenBy {
if (it.getIsAllDay()) {
Formatter.getDayEndTS(Formatter.getDayCodeFromTS(it.endTS))
} else {
it.endTS
}
}.thenBy { it.title }.thenBy { if (replaceDescription) it.location else it.description })
var prevCode = ""
var prevMonthLabel = ""
val now = getNowSeconds()
val todayCode = Formatter.getDayCodeFromTS(now)
sorted.forEach {
val code = Formatter.getDayCodeFromTS(it.startTS)
if (addSectionMonths) {
val monthLabel = Formatter.getLongMonthYear(this, code)
if (monthLabel != prevMonthLabel) {
val listSectionMonth = ListSectionMonth(monthLabel)
listItems.add(listSectionMonth)
prevMonthLabel = monthLabel
}
}
if (code != prevCode && addSectionDays) {
val day = Formatter.getDateDayTitle(code)
val isToday = code == todayCode
val listSectionDay = ListSectionDay(day, code, isToday, !isToday && it.startTS < now)
listItems.add(listSectionDay)
prevCode = code
}
val listEvent =
ListEvent(
it.id!!,
it.startTS,
it.endTS,
it.title,
it.description,
it.getIsAllDay(),
it.color,
it.location,
it.isPastEvent,
it.repeatInterval > 0,
it.isTask(),
it.isTaskCompleted(),
it.isAttendeeInviteDeclined(),
it.isEventCanceled()
)
listItems.add(listEvent)
}
return listItems
}
fun Context.handleEventDeleting(eventIds: List<Long>, timestamps: List<Long>, action: Int) {
when (action) {
DELETE_SELECTED_OCCURRENCE -> {
eventIds.forEachIndexed { index, value ->
eventsHelper.deleteRepeatingEventOccurrence(value, timestamps[index], true)
}
}
DELETE_FUTURE_OCCURRENCES -> {
eventIds.forEachIndexed { index, value ->
eventsHelper.addEventRepeatLimit(value, timestamps[index])
}
}
DELETE_ALL_OCCURRENCES -> {
eventsHelper.deleteEvents(eventIds.toMutableList(), true)
}
}
}
fun Context.refreshCalDAVCalendars(ids: String, showToasts: Boolean) {
val uri = CalendarContract.Calendars.CONTENT_URI
val accounts = HashSet<Account>()
val calendars = calDAVHelper.getCalDAVCalendars(ids, showToasts)
calendars.forEach {
accounts.add(Account(it.accountName, it.accountType))
}
Bundle().apply {
putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true)
if (showToasts) {
// Assume this is a manual synchronisation when we showToasts to the user (swipe refresh, MainMenu-> refresh caldav calendars, ...)
putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true)
}
accounts.forEach {
ContentResolver.requestSync(it, uri.authority, this)
}
}
}
fun Context.getWidgetFontSize() = when (config.fontSize) {
FONT_SIZE_SMALL -> getWidgetSmallFontSize()
FONT_SIZE_MEDIUM -> getWidgetMediumFontSize()
FONT_SIZE_LARGE -> getWidgetLargeFontSize()
else -> getWidgetExtraLargeFontSize()
}
fun Context.getWidgetSmallFontSize() = getWidgetMediumFontSize() - 3f
fun Context.getWidgetMediumFontSize() =
resources.getDimension(R.dimen.day_text_size) / resources.displayMetrics.density
fun Context.getWidgetLargeFontSize() = getWidgetMediumFontSize() + 3f
fun Context.getWidgetExtraLargeFontSize() = getWidgetMediumFontSize() + 6f
fun Context.getWeeklyViewItemHeight(): Float {
val defaultHeight = resources.getDimension(R.dimen.weekly_view_row_height)
val multiplier = config.weeklyViewItemHeightMultiplier
return defaultHeight * multiplier
}
fun Context.printBitmap(bitmap: Bitmap) {
val printHelper = PrintHelper(this)
printHelper.scaleMode = PrintHelper.SCALE_MODE_FIT
printHelper.orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
printHelper.printBitmap(getString(R.string.app_name), bitmap)
}
fun Context.editEvent(event: ListEvent) {
Intent(this, getActivityToOpen(event.isTask)).apply {
putExtra(EVENT_ID, event.id)
putExtra(EVENT_OCCURRENCE_TS, event.startTS)
putExtra(IS_TASK_COMPLETED, event.isTaskCompleted)
startActivity(this)
}
}
fun Context.getFirstDayOfWeek(date: DateTime): String {
return getFirstDayOfWeekDt(date).toString()
}
fun Context.getFirstDayOfWeekDt(date: DateTime): DateTime {
val today = date.withTimeAtStartOfDay()
var currentDate = today
if (!config.startWeekWithCurrentDay) {
val firstDayOfWeek = config.firstDayOfWeek
val currentDayOfWeek = currentDate.dayOfWeek
if (currentDayOfWeek != firstDayOfWeek) {
// Joda-time's weeks always starts on Monday but user preferred firstDayOfWeek could be any week day
if (firstDayOfWeek < currentDayOfWeek) {
currentDate = currentDate.withDayOfWeek(firstDayOfWeek)
} else {
currentDate = currentDate.minusWeeks(1).withDayOfWeek(firstDayOfWeek)
}
// moving start of the week according to the weeklyViewDays setting
if (config.weeklyViewDays < 7) {
val diff = Days.daysBetween(currentDate, today).days.absoluteValue
// integer division first to get a starting day of the screen