-
-
Notifications
You must be signed in to change notification settings - Fork 199
/
Helpers.gs
1352 lines (1218 loc) · 49.7 KB
/
Helpers.gs
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
/**
* Formats the date and time according to the format specified in the configuration.
*
* @param {string} date The date to be formatted.
* @return {string} The formatted date string.
*/
function formatDate(date) {
const year = date.slice(0,4);
const month = date.slice(5,7);
const day = date.slice(8,10);
let formattedDate;
if (dateFormat == "YYYY/MM/DD") {
formattedDate = year + "/" + month + "/" + day
}
else if (dateFormat == "DD/MM/YYYY") {
formattedDate = day + "/" + month + "/" + year
}
else if (dateFormat == "MM/DD/YYYY") {
formattedDate = month + "/" + day + "/" + year
}
else if (dateFormat == "YYYY-MM-DD") {
formattedDate = year + "-" + month + "-" + day
}
else if (dateFormat == "DD-MM-YYYY") {
formattedDate = day + "-" + month + "-" + year
}
else if (dateFormat == "MM-DD-YYYY") {
formattedDate = month + "-" + day + "-" + year
}
else if (dateFormat == "YYYY.MM.DD") {
formattedDate = year + "." + month + "." + day
}
else if (dateFormat == "DD.MM.YYYY") {
formattedDate = day + "." + month + "." + year
}
else if (dateFormat == "MM.DD.YYYY") {
formattedDate = month + "." + day + "." + year
}
if (date.length < 11) {
return formattedDate
}
const time = date.slice(11,16)
const timeZone = date.slice(19)
return formattedDate + " at " + time + " (UTC" + (timeZone == "Z" ? "": timeZone) + ")"
}
/**
* Takes an intended frequency in minutes and adjusts it to be the closest
* acceptable value to use Google "everyMinutes" trigger setting (i.e. one of
* the following values: 1, 5, 10, 15, 30).
*
* @param {?integer} The manually set frequency that the user intends to set.
* @return {integer} The closest valid value to the intended frequency setting. Defaulting to 15 if no valid input is provided.
*/
function getValidTriggerFrequency(origFrequency) {
if (!origFrequency > 0) {
Logger.log("No valid frequency specified. Defaulting to 15 minutes.");
return 15;
}
// Limit the original frequency to 1440
origFrequency = Math.min(origFrequency, 1440);
var acceptableValues = [5, 10, 15, 30].concat(
Array.from({ length: 24 }, (_, i) => (i + 1) * 60)
); // [5, 10, 15, 30, 60, 120, ..., 1440]
// Find the smallest acceptable value greater than or equal to the original frequency
var roundedUpValue = acceptableValues.find(value => value >= origFrequency);
Logger.log(
"Intended frequency = " + origFrequency + ", Adjusted frequency = " + roundedUpValue
);
return roundedUpValue;
}
String.prototype.includes = function(phrase){
return this.indexOf(phrase) > -1;
}
/**
* Takes an array of ICS calendars and target Google calendars and combines them
*
* @param {Array.string} calendarMap - User-defined calendar map
* @return {Array.string} Condensed calendar map
*/
function condenseCalendarMap(calendarMap){
var result = [];
for (var mapping of calendarMap){
var index = -1;
for (var i = 0; i < result.length; i++){
if (result[i][0] == mapping[1]){
index = i;
break;
}
}
if (index > -1)
result[index][1].push([mapping[0],mapping[2]]);
else
result.push([ mapping[1], [[mapping[0],mapping[2]]] ]);
}
return result;
}
/**
* Removes all triggers for the script's 'startSync' and 'install' function.
*/
function deleteAllTriggers(){
var triggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < triggers.length; i++){
if (["startSync","install","main","checkForUpdate"].includes(triggers[i].getHandlerFunction())){
ScriptApp.deleteTrigger(triggers[i]);
}
}
}
/**
* Gets the ressource from the specified URLs.
*
* @param {Array.string} sourceCalendarURLs - Array with URLs to fetch
* @return {Array.string} The ressources fetched from the specified URLs
*/
function fetchSourceCalendars(sourceCalendarURLs){
var result = []
for (var source of sourceCalendarURLs){
var url = source[0].replace("webcal://", "https://");
var colorId = source[1];
try {
callWithBackoff(function() {
var urlResponse = UrlFetchApp.fetch(url, { 'validateHttpsCertificates' : false, 'muteHttpExceptions' : true });
if (urlResponse.getResponseCode() == 200){
var icsContent = urlResponse.getContentText()
const icsRegex = RegExp("(BEGIN:VCALENDAR.*?END:VCALENDAR)", "s")
var urlContent = icsRegex.exec(icsContent);
if (urlContent == null){
// Microsoft Outlook has a bug that sometimes results in incorrectly formatted ics files. This tries to fix that problem.
// Add END:VEVENT for every BEGIN:VEVENT that's missing it
const veventRegex = /BEGIN:VEVENT(?:(?!END:VEVENT).)*?(?=.BEGIN|.END:VCALENDAR|$)/sg;
icsContent = icsContent.replace(veventRegex, (match) => match + "\nEND:VEVENT");
// Add END:VCALENDAR if missing
if (!icsContent.endsWith("END:VCALENDAR")){
icsContent += "\nEND:VCALENDAR";
}
urlContent = icsRegex.exec(icsContent)
if (urlContent == null){
Logger.log("[ERROR] Incorrect ics/ical URL: " + url)
reportOverallFailure = true;
return
}
Logger.log("[WARNING] Microsoft is incorrectly formatting ics/ical at: " + url)
}
result.push([urlContent[0], colorId]);
return;
}
else{ //Throw here to make callWithBackoff run again
throw "Error: Encountered HTTP error " + urlResponse.getResponseCode() + " when accessing " + url;
}
}, defaultMaxRetries);
}
catch (e) {
reportOverallFailure = true;
}
}
return result;
}
/**
* Gets the user's Google Calendar with the specified name.
* A new Calendar will be created if the user does not have a Calendar with the specified name.
*
* @param {string} targetCalendarName - The name of the calendar to return
* @return {Calendar} The calendar retrieved or created
*/
function setupTargetCalendar(targetCalendarName){
var targetCalendar = Calendar.CalendarList.list({showHidden: true, maxResults: 250}).items.filter(function(cal) {
return ((cal.summaryOverride || cal.summary) == targetCalendarName) &&
(cal.accessRole == "owner" || cal.accessRole == "writer");
})[0];
if(targetCalendar == null){
Logger.log("Creating Calendar: " + targetCalendarName);
targetCalendar = Calendar.newCalendar();
targetCalendar.summary = targetCalendarName;
targetCalendar.description = "Created by GAS";
targetCalendar.timeZone = Calendar.Settings.get("timezone").value;
targetCalendar = Calendar.Calendars.insert(targetCalendar);
}
return targetCalendar;
}
/**
* Parses all sources using ical.js.
* Registers all found timezones with TimezoneService.
* Creates an Array with all events and adds the event-ids to the provided Array.
*
* @param {Array.string} responses - Array with all ical sources
* @return {Array.ICALComponent} Array with all events found
*/
function parseResponses(responses){
var result = [];
for (var itm of responses){
var resp = itm[0];
var colorId = itm[1];
var jcalData = ICAL.parse(resp);
var component = new ICAL.Component(jcalData);
ICAL.helpers.updateTimezones(component);
var vtimezones = component.getAllSubcomponents("vtimezone");
for (var tz of vtimezones){
ICAL.TimezoneService.register(tz);
}
var allEvents = component.getAllSubcomponents("vevent");
if (colorId != undefined)
allEvents.forEach(function(event){event.addPropertyWithValue("color", colorId);});
var calName = component.getFirstPropertyValue("x-wr-calname") || component.getFirstPropertyValue("name");
if (calName != null)
allEvents.forEach(function(event){event.addPropertyWithValue("parentCal", calName); });
result = [].concat(allEvents, result);
}
//No need to process cancelled events as they will be added to gcal's trash anyway
result = result.filter(function(event){
try{
return (event.getFirstPropertyValue('status').toString().toLowerCase() != "cancelled");
}catch(e){
return true;
}
});
result = filterResults(result);
result.forEach(function(event){
if (!event.hasProperty('uid')){
event.updatePropertyWithValue('uid', Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, event.toString()).toString(), Utilities.Charset.UTF_8);
}
if(event.hasProperty('recurrence-id')){
let recID = new ICAL.Time.fromString(event.getFirstPropertyValue('recurrence-id').toString(), event.getFirstProperty('recurrence-id'));
if (event.getFirstProperty('recurrence-id').getParameter('tzid')){
let recUTCOffset = 0;
let tz = event.getFirstProperty('recurrence-id').getParameter('tzid').toString();
if (tz in tzidreplace){
tz = tzidreplace[tz];
}
let jsTime = new Date(event.getFirstPropertyValue('recurrence-id').toString());
let utcTime = new Date(Utilities.formatDate(jsTime, "Etc/GMT", "HH:mm:ss MM/dd/yyyy"));
let tgtTime = new Date(Utilities.formatDate(jsTime, tz, "HH:mm:ss MM/dd/yyyy"));
recUTCOffset = (tgtTime - utcTime)/-1000;
recID = recID.adjust(0,0,0,recUTCOffset).toString() + "Z";
event.updatePropertyWithValue('recurrence-id', recID);
}
icsEventsIds.push(event.getFirstPropertyValue('uid').toString() + "_" + recID);
}
else{
icsEventsIds.push(event.getFirstPropertyValue('uid').toString());
}
});
return result;
}
/**
* Applies filters to source events based on filters defined in filters.gs
*
* @param {Array.ICALComponent} Array with all events from the source calendars
* @return {Array.ICALComponent} Array with filtered events
*/
function filterResults(events){
Logger.log(`Applying ${filters.length} filters on ${events.length} events.`);
for (var filter of filters){
filter.parameter = filter.parameter.toLowerCase();
events = events.filter(function(event){
try{
if (["dtstart", "dtend"].includes(filter.parameter)){
let referenceDate = new ICAL.Time.fromJSDate(new Date(), true).adjust(filter.offset,0,0,0);
if (event.hasProperty('rrule') || event.hasProperty('rdate')) {
if ((filter.comparison === ">" && filter.type === "exclude")||(filter.comparison === "<" && filter.type === "include")) {
event = modifyRecurrenceEnd(event, referenceDate, filter.parameter);
} else if ((filter.comparison === "<" && filter.type === "exclude")||(filter.comparison === ">" && filter.type === "include")) {
event = modifyRecurrenceStart(event, referenceDate, filter.parameter);
}
return event !== null;
}
else{
let eventTime = new ICAL.Time.fromString(event.getFirstPropertyValue(filter.parameter).toString(), event.getFirstProperty(filter.parameter));
switch (filter.comparison){
case ">":
return ((eventTime.compare(referenceDate) > 0) ^ (filter.type == "exclude"));
case "<":
return ((eventTime.compare(referenceDate) < 0) ^ (filter.type == "exclude"));
case "default":
return true;
}
}
}
else{
let regexString = `${(["equals", "begins with"].includes(filter.comparison)) ? "^" : ""}(${filter.criterias.join("|")})${(filter.comparison == "equals") ? "$" : ""}`;
let regex = new RegExp(regexString);
let result = regex.test(event.getFirstPropertyValue(filter.parameter).toString()) ^ (filter.type == "exclude");
if (!result && event.hasProperty('recurrence-id')){
let id = event.getFirstPropertyValue('uid');
Logger.log(`Filtering recurrence instance of ${id} at ${event.getFirstPropertyValue('dtstart').toICALString()}`);
let indx = events.findIndex((e) => e.getFirstPropertyValue('uid') == id && !e.hasProperty('recurrence-id'));
if (!events[indx].hasProperty('exdate')){
events[indx].addProperty(new ICAL.Property('exdate'));
}
let exdates = events[indx].getFirstProperty('exdate').getValues().concat(event.getFirstPropertyValue('recurrence-id'));
events[indx].getFirstProperty('exdate').setValues(exdates);
}
return result;
}
}
catch(e){
Logger.log(e);
return (filter.type == "exclude");
}
});
}
Logger.log(`${events.length} events left.`);
return events;
}
/**
* Modifies the end of the given recurrence series.
*
* @param {ICAL.Component} event - The event to modify
* @param {ICAL.Time} referenceDate - The new recurrence end date
* @param {string} filterParameter - The parameter to filter on
* @return {ICAL.Component|null} The modified event or null if no instances are within the range
*/
function modifyRecurrenceEnd(event, referenceDate, filterParameter) {
let eventRefDate = new ICAL.Time.fromString(event.getFirstPropertyValue('dtstart').toString(), event.getFirstProperty('dtstart'));
if (filterParameter.toLowerCase() === "dtend"){
let eventEnd = new ICAL.Time.fromString(event.getFirstPropertyValue('dtend').toString(), event.getFirstProperty('dtend'));
var eventDurartion = eventEnd.subtractDate(eventRefDate);
eventRefDate = eventEnd;
}
let icalEvent = new ICAL.Event(event);
if (eventRefDate.compare(referenceDate) >= 0){
return null;
}
if (event.hasProperty('rrule')){
let rrule = event.getFirstProperty('rrule');
let recur = rrule.getFirstValue();
var dtstart = event.getFirstPropertyValue('dtstart');
var expand = new ICAL.RecurExpansion({component: event, dtstart: dtstart});
var next;
var lastStartDate = null;
var newCount = 0;
// Iterate through the recurrence instances to find the last valid one before referenceDate
while (next = expand.next()) {
if (filterParameter.toLowerCase() === "dtstart") {
if (next.compare(referenceDate) > 0) {
break;
}
newCount++;
lastStartDate = next;
}
else if (filterParameter.toLowerCase() === "dtend") {
let tempEnd = next.clone();
tempEnd.addDuration(eventDurartion);
if (tempEnd.compare(referenceDate) > 0) {
break;
}
newCount++;
lastStartDate = next;
}
}
// Remove EXDATEs that are after the endDate
var exDates = event.getAllProperties('exdate');
exDates.forEach(function(e) {
var ex = new ICAL.Time.fromString(e.getFirstValue().toString(), e);
if (ex.compare(lastStartDate) > 0) {
event.removeProperty(e);
}
else{
newCount++
}
});
if (newCount == 0){
event.removeProperty('rrule');
}
else{
if (recur.isByCount()) {
recur.count = newCount;
rrule.setValue(recur);
}
else{
recur.until = referenceDate.clone();
rrule.setValue(recur);
}
}
}
// Adjust RDATEs to exclude any dates beyond the endDate
var rdates = event.getAllProperties('rdate');
rdates.forEach(function(r) {
var vals = r.getValues();
vals = vals.filter(function(v) {
var valTime = new ICAL.Time.fromString(v.toString(), r);
if (filterParameter.toLowerCase() === "dtend") {
valTime.addDuration(eventDurartion);
}
return valTime.compare(referenceDate) <= 0;
});
if (vals.length === 0) {
event.removeProperty(r);
} else if (vals.length === 1) {
r.setValue(vals[0]);
} else if (vals.length > 1) {
r.setValues(vals);
}
});
//Check and filter recurrence-exceptions
if (filterParameter.toLowerCase() === "dtend"){
for (let key in icalEvent.exceptions) {
let recIdEnd = icalEvent.exceptions[key].recurrenceId.clone();
recIdEnd.addDuration(eventDurartion);
if((icalEvent.exceptions[key].endDate.compare(referenceDate) > 0) && (recIdEnd.compare(referenceDate) <= 0)){
icalEvent.component.addPropertyWithValue('exdate', icalEvent.exceptions[key].recurrenceId.toString());
}
else if((icalEvent.exceptions[key].endDate.compare(referenceDate) <= 0) && (recIdEnd.compare(referenceDate) > 0)){
icalEvent.component.addPropertyWithValue('rdate', icalEvent.exceptions[key].recurrenceId.toString());
}
}
}
else if (filterParameter.toLowerCase() === "dtstart"){
for (let key in icalEvent.exceptions) {
if((icalEvent.exceptions[key].startDate.compare(referenceDate) < 0) && (icalEvent.exceptions[key].recurrenceId.compare(referenceDate) >= 0)){
icalEvent.component.addPropertyWithValue('rdate', icalEvent.exceptions[key].recurrenceId.toString());
}
else if((icalEvent.exceptions[key].startDate.compare(referenceDate) >= 0) && (icalEvent.exceptions[key].recurrenceId.compare(referenceDate) < 0)){
icalEvent.component.addPropertyWithValue('exdate', icalEvent.exceptions[key].recurrenceId.toString());
}
}
}
return event;
}
/**
* Modifies the start of the given recurrence series.
*
* @param {ICAL.Component} event - The event to modify
* @param {ICAL.Time} referenceDate - The new recurrence start date
* @param {string} filterParameter - The parameter to filter on
* @return {ICAL.Component|null} The modified event or null if no instances are within the range
*/
function modifyRecurrenceStart(event, referenceDate, filterParameter) {
let eventRefDate = new ICAL.Time.fromString(event.getFirstPropertyValue('dtstart').toString(), event.getFirstProperty('dtstart'));
if (filterParameter.toLowerCase() === "dtend"){
let eventEnd = new ICAL.Time.fromString(event.getFirstPropertyValue('dtend').toString(), event.getFirstProperty('dtend'));
var eventDurartion = eventEnd.subtractDate(eventRefDate);
eventRefDate = eventEnd;
}
let icalEvent = new ICAL.Event(event);
if (eventRefDate.compare(referenceDate) < 0){
var dtstart = event.getFirstPropertyValue('dtstart');
var expand = new ICAL.RecurExpansion({component: event, dtstart: dtstart});
var next;
var newStartDate = null;
var countskipped = 0;
while (next = expand.next()) {
if (filterParameter.toLowerCase() === "dtstart"){
if (next.compare(referenceDate) < 0) {
countskipped ++;
continue;
}
}
else if(filterParameter.toLowerCase() === "dtend"){
let tempEnd = next.clone();
tempEnd.addDuration(eventDurartion);
if (tempEnd.compare(referenceDate) < 0) {
countskipped ++;
continue;
}
}
newStartDate = next;
break;
}
if (newStartDate === null) {
return null;
}
var diff = newStartDate.subtractDate(icalEvent.startDate);
icalEvent.endDate.addDuration(diff);
var newEndDate = icalEvent.endDate;
icalEvent.endDate = newEndDate;
icalEvent.startDate = newStartDate;
if (event.hasProperty('rrule') ){
let rrule = event.getFirstProperty('rrule');
let recur = rrule.getFirstValue();
var exDates = event.getAllProperties('exdate');
exDates.forEach(function(e){
var ex = new ICAL.Time.fromString(e.getFirstValue().toString(), e);
if (ex < newStartDate){
event.removeProperty(e);
if (recur.isByCount()) {
countskipped++;
}
}
});
if (recur.isByCount()) {
recur.count -= countskipped;
rrule.setValue(recur);
}
}
}
var rdates = event.getAllProperties('rdate');
rdates.forEach(function(r){
var vals = r.getValues();
vals = vals.filter(function(v){
var valTime = new ICAL.Time.fromString(v.toString(), r);
if (filterParameter.toLowerCase() === "dtend") {
valTime.addDuration(eventDurartion);
}
return (valTime.compare(referenceDate) >= 0 && valTime.compare(icalEvent.startDate) > 0)
});
if (vals.length == 0){
event.removeProperty(r);
}
else if(vals.length == 1){
r.setValue(vals[0]);
}
else if(vals.length > 1){
r.setValues(vals);
}
});
//Check and filter recurrence-exceptions
if (filterParameter.toLowerCase() === "dtend"){
for (let key in icalEvent.exceptions) {
let recIdEnd = icalEvent.exceptions[key].recurrenceId.clone();
recIdEnd.addDuration(eventDurartion);
//Exclude the instance if it was moved from future to past
if((icalEvent.exceptions[key].endDate.compare(referenceDate) < 0) && (recIdEnd.compare(referenceDate) >= 0)){
icalEvent.component.addPropertyWithValue('exdate', icalEvent.exceptions[key].recurrenceId.toString());
}//Re-add the instance if it is moved from past to future
else if((icalEvent.exceptions[key].endDate.compare(referenceDate) >= 0) && (recIdEnd.compare(referenceDate) < 0)){
icalEvent.component.addPropertyWithValue('rdate', icalEvent.exceptions[key].recurrenceId.toString());
}
}
}
else if (filterParameter.toLowerCase() === "dtstart"){
for (let key in icalEvent.exceptions) {
//Exclude the instance if it was moved from future to past
if((icalEvent.exceptions[key].startDate.compare(referenceDate) < 0) && (icalEvent.exceptions[key].recurrenceId.compare(referenceDate) >= 0)){
icalEvent.component.addPropertyWithValue('exdate', icalEvent.exceptions[key].recurrenceId.toString());
}//Re-add the instance if it is moved from past to future
else if((icalEvent.exceptions[key].startDate.compare(referenceDate) >= 0) && (icalEvent.exceptions[key].recurrenceId.compare(referenceDate) < 0)){
icalEvent.component.addPropertyWithValue('rdate', icalEvent.exceptions[key].recurrenceId.toString());
}
}
}
return event;
}
/**
* Creates a Google Calendar event and inserts it to the target calendar.
*
* @param {ICAL.Component} event - The event to process
* @param {string} calendarTz - The timezone of the target calendar
*/
function processEvent(event, calendarTz){
//------------------------ Create the event object ------------------------
var newEvent = createEvent(event, calendarTz);
if (newEvent == null)
return;
var index = calendarEventsIds.indexOf(newEvent.extendedProperties.private["id"]);
var needsUpdate = index > -1;
//------------------------ Save instance overrides ------------------------
//----------- To make sure the parent event is actually created -----------
if (event.hasProperty('recurrence-id')){
Logger.log("Saving event instance for later: " + newEvent.recurringEventId);
recurringEvents.push(newEvent);
return;
}
else{
//------------------------ Send event object to gcal ------------------------
if (needsUpdate){
if (modifyExistingEvents){
oldEvent = calendarEvents[index]
Logger.log("Updating existing event " + newEvent.extendedProperties.private["id"]);
try{
newEvent = callWithBackoff(function(){
return Calendar.Events.update(newEvent, targetCalendarId, calendarEvents[index].id);
}, defaultMaxRetries);
}
catch (e){
Logger.log(`Operation failed with error "${e}"`);
reportOverallFailure = true;
}
if (newEvent != null && emailSummary){
modifiedEvents.push([[oldEvent.summary, newEvent.summary, oldEvent.start.date||oldEvent.start.dateTime, newEvent.start.date||newEvent.start.dateTime, oldEvent.end.date||oldEvent.end.dateTime, newEvent.end.date||newEvent.end.dateTime, oldEvent.location, newEvent.location, oldEvent.description, newEvent.description], targetCalendarName]);
}
}
}
else{
if (addEventsToCalendar){
Logger.log("Adding new event " + newEvent.extendedProperties.private["id"]);
try{
newEvent = callWithBackoff(function(){
return Calendar.Events.insert(newEvent, targetCalendarId);
}, defaultMaxRetries);
}
catch (e){
Logger.log(`Operation failed with error "${e}"`);
reportOverallFailure = true;
}
if (newEvent != null && emailSummary){
addedEvents.push([[newEvent.summary, newEvent.start.date||newEvent.start.dateTime, newEvent.end.date||newEvent.end.dateTime, newEvent.location, newEvent.description], targetCalendarName]);
}
}
}
}
}
/**
* Creates a Google Calendar Event based on the specified ICALEvent.
* Will return null if the event has not changed since the last sync.
*
* @param {ICAL.Component} event - The event to process
* @param {string} calendarTz - The timezone of the target calendar
* @return {?Calendar.Event} The Calendar.Event that will be added to the target calendar
*/
function createEvent(event, calendarTz){
event.removeProperty('dtstamp');
var icalEvent = new ICAL.Event(event);
var digest = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, icalEvent.toString(), Utilities.Charset.UTF_8).toString();
if(calendarEventsMD5s.indexOf(digest) >= 0){
Logger.log("Skipping unchanged Event " + event.getFirstPropertyValue('uid').toString());
return;
}
var newEvent =
callWithBackoff(function() {
return Calendar.newEvent();
}, defaultMaxRetries);
if(icalEvent.startDate.isDate){ //All-day event
if (icalEvent.startDate.compare(icalEvent.endDate) == 0){
//Adjust dtend in case dtstart equals dtend as this is not valid for allday events
icalEvent.endDate = icalEvent.endDate.adjust(1,0,0,0);
}
newEvent = {
start: { date : icalEvent.startDate.toString() },
end: { date : icalEvent.endDate.toString() }
};
}
else{ //Normal (not all-day) event
newEvent = {
start: {
dateTime : icalEvent.startDate.toString(),
timeZone : validateTimeZone(icalEvent.startDate.timezone || icalEvent.startDate.zone, calendarTz)
},
end: {
dateTime : icalEvent.endDate.toString(),
timeZone : validateTimeZone(icalEvent.endDate.timezone || icalEvent.endDate.zone, calendarTz)
},
};
}
if (addAttendees && event.hasProperty('attendee')){
newEvent.attendees = [];
for (var att of icalEvent.attendees){
var mail = parseAttendeeMail(att.toICALString());
if (mail != null){
var newAttendee = {'email' : mail };
var name = parseAttendeeName(att.toICALString());
if (name != null)
newAttendee['displayName'] = name;
var resp = parseAttendeeResp(att.toICALString());
if (resp != null)
newAttendee['responseStatus'] = resp;
newEvent.attendees.push(newAttendee);
}
}
}
if (event.hasProperty('status')){
var status = event.getFirstPropertyValue('status').toString().toLowerCase();
if (["confirmed", "tentative", "cancelled"].indexOf(status) > -1)
newEvent.status = status;
}
if (event.hasProperty('url') && event.getFirstPropertyValue('url').toString().substring(0,4) == 'http'){
newEvent.source = callWithBackoff(function() {
return Calendar.newEventSource();
}, defaultMaxRetries);
newEvent.source.url = event.getFirstPropertyValue('url').toString();
newEvent.source.title = 'link';
}
if (event.hasProperty('sequence')){
//newEvent.sequence = icalEvent.sequence; Currently disabled as it is causing issues with recurrence exceptions
}
if (descriptionAsTitles && event.hasProperty('description'))
newEvent.summary = icalEvent.description;
else if (event.hasProperty('summary'))
newEvent.summary = icalEvent.summary;
if (event.hasProperty('organizer')){
var organizerName = event.getFirstProperty('organizer').getParameter('cn');
var organizerMail = event.getFirstProperty('organizer').getParameter('mailto');
newEvent.organizer = callWithBackoff(function() {
return Calendar.newEventOrganizer();
}, defaultMaxRetries);
if (organizerName)
newEvent.organizer.displayName = organizerName.toString();
if (organizerMail)
newEvent.organizer.email = organizerMail.toString();
if (addOrganizerToTitle && organizerName){
newEvent.summary = organizerName + ": " + newEvent.summary;
}
}
if (addCalToTitle && event.hasProperty('parentCal')){
var calName = event.getFirstPropertyValue('parentCal');
newEvent.summary = "(" + calName + ") " + newEvent.summary;
}
if (event.hasProperty('description'))
newEvent.description = icalEvent.description;
if (event.hasProperty('location'))
newEvent.location = icalEvent.location;
var validVisibilityValues = ["default", "public", "private", "confidential"];
if ( validVisibilityValues.includes(overrideVisibility.toLowerCase()) ) {
newEvent.visibility = overrideVisibility.toLowerCase();
} else if (event.hasProperty('class')){
var classString = event.getFirstPropertyValue('class').toString().toLowerCase();
if (validVisibilityValues.includes(classString))
newEvent.visibility = classString;
}
if (event.hasProperty('transp')){
var transparency = event.getFirstPropertyValue('transp').toString().toLowerCase();
if(["opaque", "transparent"].indexOf(transparency) > -1)
newEvent.transparency = transparency;
}
if (icalEvent.startDate.isDate){
if (0 <= defaultAllDayReminder && defaultAllDayReminder <= 40320){
newEvent.reminders = { 'useDefault' : false, 'overrides' : [{'method' : 'popup', 'minutes' : defaultAllDayReminder}]};//reminder as defined by the user
}
else{
newEvent.reminders = { 'useDefault' : false, 'overrides' : []};//no reminder
}
}
else{
newEvent.reminders = { 'useDefault' : true, 'overrides' : []};//will set the default reminders as set at calendar.google.com
}
switch (addAlerts) {
case "yes":
var valarms = event.getAllSubcomponents('valarm');
if (valarms.length > 0){
var overrides = [];
for (var valarm of valarms){
var trigger = valarm.getFirstPropertyValue('trigger').toString();
try{
var alarmTime = new ICAL.Time.fromString(trigger);
trigger = alarmTime.subtractDateTz(icalEvent.startDate).toString();
}catch(e){}
if (overrides.length < 5){ //Google supports max 5 reminder-overrides
var timer = parseNotificationTime(trigger);
if (0 <= timer && timer <= 40320)
overrides.push({'method' : 'popup', 'minutes' : timer});
}
}
if (overrides.length > 0){
newEvent.reminders = {
'useDefault' : false,
'overrides' : overrides
};
}
}
break;
case "no":
newEvent.reminders = {
'useDefault' : false,
'overrides' : []
};
break;
default:
case "default":
newEvent.reminders = {
'useDefault' : true,
'overrides' : []
};
break;
}
if (icalEvent.isRecurring()){
// Calculate targetTZ's UTC-Offset
var calendarUTCOffset = 0;
var jsTime = new Date();
var utcTime = new Date(Utilities.formatDate(jsTime, "Etc/GMT", "HH:mm:ss MM/dd/yyyy"));
var tgtTime = new Date(Utilities.formatDate(jsTime, calendarTz, "HH:mm:ss MM/dd/yyyy"));
calendarUTCOffset = tgtTime - utcTime;
newEvent.recurrence = parseRecurrenceRule(event, calendarUTCOffset);
}
newEvent.extendedProperties = { private: { MD5 : digest, fromGAS : "true", id : icalEvent.uid } };
if (event.hasProperty('recurrence-id')){
newEvent.recurringEventId = event.getFirstPropertyValue('recurrence-id').toString();
newEvent.extendedProperties.private['rec-id'] = newEvent.extendedProperties.private['id'] + "_" + newEvent.recurringEventId;
}
if (event.hasProperty('color')){
let colorID = event.getFirstPropertyValue('color').toString();
if (Object.keys(CalendarApp.EventColor).includes(colorID)){
newEvent.colorId = CalendarApp.EventColor[colorID];
}else if(Object.values(CalendarApp.EventColor).includes(colorID)){
newEvent.colorId = colorID;
}; //else unsupported value
}
return newEvent;
}
/**
* Patches an existing event instance with the provided Calendar.Event.
* The instance that needs to be updated is identified by the recurrence-id of the provided event.
*
* @param {Calendar.Event} recEvent - The event instance to process
*/
function processEventInstance(recEvent){
Logger.log("ID: " + recEvent.extendedProperties.private["id"] + " | Date: "+ recEvent.recurringEventId);
var eventInstanceToPatch = callWithBackoff(function(){
return Calendar.Events.list(targetCalendarId,
{ singleEvents : true,
privateExtendedProperty : "fromGAS=true",
privateExtendedProperty : "rec-id=" + recEvent.extendedProperties.private["id"] + "_" + recEvent.recurringEventId
}).items;
}, defaultMaxRetries);
if (eventInstanceToPatch == null || eventInstanceToPatch.length == 0){
if (recEvent.recurringEventId.length == 10){
recEvent.recurringEventId += "T00:00:00Z";
}
else if (recEvent.recurringEventId.substr(-1) !== "Z"){
recEvent.recurringEventId += "Z";
}
eventInstanceToPatch = callWithBackoff(function(){
return Calendar.Events.list(targetCalendarId,
{ singleEvents : true,
orderBy : "startTime",
maxResults: 1,
timeMin : recEvent.recurringEventId,
privateExtendedProperty : "fromGAS=true",
privateExtendedProperty : "id=" + recEvent.extendedProperties.private["id"]
}).items;
}, defaultMaxRetries);
}
if (eventInstanceToPatch !== null && eventInstanceToPatch.length == 1){
if (modifyExistingEvents){
Logger.log("Updating existing event instance");
callWithBackoff(function(){
Calendar.Events.update(recEvent, targetCalendarId, eventInstanceToPatch[0].id);
}, defaultMaxRetries);
}
}
else{
if (addEventsToCalendar){
Logger.log("No Instance matched, adding as new event!");
callWithBackoff(function(){
Calendar.Events.insert(recEvent, targetCalendarId);
}, defaultMaxRetries);
}
}
}
/**
* Deletes all events from the target calendar that no longer exist in the source calendars.
* If removePastEventsFromCalendar is set to false, events that have taken place will not be removed.
*/
function processEventCleanup(){
for (var i = 0; i < calendarEvents.length; i++){
var currentID = calendarEventsIds[i];
var feedIndex = icsEventsIds.indexOf(currentID);
if(feedIndex == -1 // Event is no longer in source
&& calendarEvents[i].recurringEventId == null // And it's not a recurring event
&& ( // And one of:
removePastEventsFromCalendar // We want to remove past events
|| new Date(calendarEvents[i].start.dateTime) > new Date() // Or the event is in the future
|| new Date(calendarEvents[i].start.date) > new Date() // (2 different ways event start can be stored)
)
)
{
Logger.log("Deleting old event " + currentID);
try{
callWithBackoff(function(){
Calendar.Events.remove(targetCalendarId, calendarEvents[i].id);
}, defaultMaxRetries);
}
catch (e){
Logger.log(`Operation failed with error "${e}"`);
reportOverallFailure = true;
}
if (emailSummary){
removedEvents.push([[calendarEvents[i].summary, calendarEvents[i].start.date||calendarEvents[i].start.dateTime, calendarEvents[i].end.date||calendarEvents[i].end.dateTime, calendarEvents[i].location, calendarEvents[i].description], targetCalendarName]);
}
}
}
}
/**
* Processes and adds all vtodo components as Tasks to the user's Google Account
*
* @param {Array.string} responses - Array with all ical sources
*/
function processTasks(responses){
var taskLists = Tasks.Tasklists.list().items;
var taskList = taskLists[0];
var existingTasks = Tasks.Tasks.list(taskList.id).items || [];
var existingTasksIds = []
Logger.log("Fetched " + existingTasks.length + " existing tasks from " + taskList.title);
for (var i = 0; i < existingTasks.length; i++){
existingTasksIds[i] = existingTasks[i].id;
}
var icsTasksIds = [];
var vtasks = [];
for (var resp of responses){
var jcalData = ICAL.parse(resp);
var component = new ICAL.Component(jcalData);
vtasks = [].concat(component.getAllSubcomponents("vtodo"), vtasks);
}
vtasks.forEach(function(task){ icsTasksIds.push(task.getFirstPropertyValue('uid').toString()); });
Logger.log("\tProcessing " + vtasks.length + " tasks");
for (var task of vtasks){
var newtask = Tasks.newTask();
newtask.id = task.getFirstPropertyValue("uid").toString();
newtask.title = task.getFirstPropertyValue("summary").toString();
var dueDate = task.getFirstPropertyValue("due").toJSDate();
newtask.due = (dueDate.getFullYear()) + "-" + ("0"+(dueDate.getMonth()+1)).slice(-2) + "-" + ("0" + dueDate.getDate()).slice(-2) + "T" + ("0" + dueDate.getHours()).slice(-2) + ":" + ("0" + dueDate.getMinutes()).slice(-2) + ":" + ("0" + dueDate.getSeconds()).slice(-2)+"Z";
Tasks.Tasks.insert(newtask, taskList.id);
}
Logger.log("\tDone processing tasks");
//-------------- Remove old Tasks -----------
// ID can't be used as identifier as the API reassignes a random id at task creation
if(removeEventsFromCalendar){
Logger.log("Checking " + existingTasksIds.length + " tasks for removal");
for (var i = 0; i < existingTasksIds.length; i++){
var currentID = existingTasks[i].id;
var feedIndex = icsTasksIds.indexOf(currentID);
if(feedIndex == -1){
Logger.log("Deleting old task " + currentID);
Tasks.Tasks.remove(taskList.id, currentID);