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
|
/*
* This file is part of TbSync.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
"use strict";
var { XPCOMUtils } = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
CalAlarm: "resource:///modules/CalAlarm.jsm",
CalAttachment: "resource:///modules/CalAttachment.jsm",
CalAttendee: "resource:///modules/CalAttendee.jsm",
CalEvent: "resource:///modules/CalEvent.jsm",
CalTodo: "resource:///modules/CalTodo.jsm",
});
var lightning = {
cal: null,
ICAL: null,
load: async function () {
try {
TbSync.lightning.cal = ChromeUtils.import("resource:///modules/calendar/calUtils.jsm").cal;
TbSync.lightning.ICAL = ChromeUtils.import("resource:///modules/calendar/Ical.jsm").ICAL;
let manager = TbSync.lightning.cal.manager;
manager.addCalendarObserver(this.calendarObserver);
manager.addObserver(this.calendarManagerObserver);
} catch (e) {
TbSync.dump("Check4Lightning","Error during lightning module import: " + e.toString() + "\n" + e.stack);
Components.utils.reportError(e);
}
},
unload: async function () {
//removing global observer
let manager = TbSync.lightning.cal.manager;
manager.removeCalendarObserver(this.calendarObserver);
manager.removeObserver(this.calendarManagerObserver);
//remove listeners on global sync buttons
if (TbSync.window.document.getElementById("calendar-synchronize-button")) {
TbSync.window.document.getElementById("calendar-synchronize-button").removeEventListener("click", function(event){Services.obs.notifyObservers(null, 'tbsync.observer.sync', null);}, false);
}
if (TbSync.window.document.getElementById("task-synchronize-button")) {
TbSync.window.document.getElementById("task-synchronize-button").removeEventListener("click", function(event){Services.obs.notifyObservers(null, 'tbsync.observer.sync', null);}, false);
}
},
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// * AdvancedTargetData, an extended TargetData implementation, providers
// * can use this as their own TargetData by extending it and just
// * defining the extra methods
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
AdvancedTargetData : class {
constructor(folderData) {
this._folderData = folderData;
this._targetObj = null;
}
// Check, if the target exists and return true/false.
hasTarget() {
let calManager = TbSync.lightning.cal.manager;
let target = this._folderData.getFolderProperty("target");
let calendar = calManager.getCalendarById(target);
return calendar ? true : false;
}
// Returns the target obj, which TbSync should return as the target. It can
// be whatever you want and is returned by FolderData.targetData.getTarget().
// If the target does not exist, it should be created. Throw a simple Error, if that
// failed.
async getTarget() {
let calManager = TbSync.lightning.cal.manager;
let target = this._folderData.getFolderProperty("target");
let calendar = calManager.getCalendarById(target);
if (!calendar) {
calendar = await TbSync.lightning.prepareAndCreateCalendar(this._folderData);
if (!calendar)
throw new Error("notargets");
}
if (!this._targetObj || this._targetObj.id != calendar.id)
this._targetObj = new TbSync.lightning.TbCalendar(calendar, this._folderData);
return this._targetObj;
}
/**
* Removes the target from the local storage. If it does not exist, return
* silently. A call to ``hasTarget()`` should return false, after this has
* been executed.
*
*/
removeTarget() {
let calManager = TbSync.lightning.cal.manager;
let target = this._folderData.getFolderProperty("target");
let calendar = calManager.getCalendarById(target);
try {
if (calendar) {
calManager.removeCalendar(calendar);
}
} catch (e) {}
TbSync.db.clearChangeLog(target);
this._folderData.resetFolderProperty("target");
}
/**
* Disconnects the target in the local storage from this TargetData, but
* does not delete it, so it becomes a stale "left over" . A call
* to ``hasTarget()`` should return false, after this has been executed.
*
*/
disconnectTarget() {
let calManager = TbSync.lightning.cal.manager;
let target = this._folderData.getFolderProperty("target");
let calendar = calManager.getCalendarById(target);
if (calendar) {
let changes = TbSync.db.getItemsFromChangeLog(target, 0, "_by_user");
if (changes.length > 0) {
this.targetName = this.targetName + " (*)";
}
calendar.setProperty("disabled", true);
calendar.setProperty("tbSyncProvider", "orphaned");
calendar.setProperty("tbSyncAccountID", "");
}
TbSync.db.clearChangeLog(target);
this._folderData.resetFolderProperty("target");
}
set targetName(newName) {
let calManager = TbSync.lightning.cal.manager;
let target = this._folderData.getFolderProperty("target");
let calendar = calManager.getCalendarById(target);
if (calendar) {
calendar.name = newName;
} else {
throw new Error("notargets");
}
}
get targetName() {
let calManager = TbSync.lightning.cal.manager;
let target = this._folderData.getFolderProperty("target");
let calendar = calManager.getCalendarById(target);
if (calendar) {
return calendar.name;
} else {
throw new Error("notargets");
}
}
setReadOnly(value) {
// hasTarget() can throw an error, ignore that here
try {
if (this.hasTarget()) {
this.getTarget().then(target => target.calendar.setProperty("readOnly", value));
}
} catch (e) {
Components.utils.reportError(e);
}
}
// * * * * * * * * * * * * * * * * *
// * AdvancedTargetData extension *
// * * * * * * * * * * * * * * * * *
get isAdvancedCalendarTargetData() {
return true;
}
get folderData() {
return this._folderData;
}
// The calendar target does not support a custom primaryKeyField, because
// the lightning implementation only allows to search for items via UID.
// Like the addressbook target, the calendar target item element has a
// primaryKey getter/setter which - however - only works on the UID.
// enable or disable changelog
get logUserChanges(){
return true;
}
calendarObserver(aTopic, tbCalendar, aPropertyName, aPropertyValue, aOldPropertyValue) {
switch (aTopic) {
case "onCalendarPropertyChanged":
//Services.console.logStringMessage("["+ aTopic + "] " + tbCalendar.calendar.name + " : " + aPropertyName);
break;
case "onCalendarDeleted":
case "onCalendarPropertyDeleted":
//Services.console.logStringMessage("["+ aTopic + "] " +tbCalendar.calendar.name);
break;
}
}
itemObserver(aTopic, tbItem, tbOldItem) {
switch (aTopic) {
case "onAddItem":
case "onModifyItem":
case "onDeleteItem":
//Services.console.logStringMessage("["+ aTopic + "] " + tbItem.nativeItem.title);
break;
}
}
// replace this with your own implementation to create the actual addressbook,
// when this class is extended
async createCalendar(newname) {
let calManager = TbSync.lightning.cal.manager;
let newCalendar = calManager.createCalendar("storage", Services.io.newURI("moz-storage-calendar://"));
newCalendar.id = TbSync.lightning.cal.getUUID();
newCalendar.name = newname;
return newCalendar
}
},
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// * TbItem and TbCalendar Classes
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
TbItem : class {
constructor(TbCalendar, item) {
if (!TbCalendar)
throw new Error("TbItem::constructor is missing its first parameter!");
if (!item)
throw new Error("TbItem::constructor is missing its second parameter!");
this._tbCalendar = TbCalendar;
this._item = item;
this._isTodo = (item instanceof Ci.calITodo);
this._isEvent = (item instanceof Ci.calIEvent);
}
get tbCalendar() {
return this._tbCalendar;
}
get isTodo() {
return this._isTodo;
}
get isEvent() {
return this._isEvent;
}
get nativeItem() {
return this._item;
}
get UID() {
return this._item.id;
}
get primaryKey() {
// no custom key possible with lightning, must use the UID
return this._item.id;
}
set primaryKey(value) {
// no custom key possible with lightning, must use the UID
this._item.id = value;
}
clone() {
return new TbSync.lightning.TbItem(this._tbCalendar, this._item.clone());
}
toString() {
return this._item.icalString;
}
getProperty(property, fallback = "") {
return this._item.hasProperty(property) ? this._item.getProperty(property) : fallback;
}
setProperty(property, value) {
this._item.setProperty(property, value);
}
deleteProperty(property) {
this._item.deleteProperty(property);
}
get changelogData() {
return TbSync.db.getItemDataFromChangeLog(this._tbCalendar.UID, this.primaryKey);
}
get changelogStatus() {
return TbSync.db.getItemStatusFromChangeLog(this._tbCalendar.UID, this.primaryKey);
}
set changelogStatus(status) {
let value = this.primaryKey;
if (value) {
if (!status) {
TbSync.db.removeItemFromChangeLog(this._tbCalendar.UID, value);
return;
}
if (this._tbCalendar.logUserChanges || status.endsWith("_by_server")) {
TbSync.db.addItemToChangeLog(this._tbCalendar.UID, value, status);
}
}
}
},
TbCalendar : class {
constructor(calendar, folderData) {
this._calendar = calendar;
this._folderData = folderData;
}
get calendar() {
return this._calendar;
}
get promisifyCalendar() {
return this._calendar;
}
get logUserChanges() {
return this._folderData.targetData.logUserChanges;
}
get primaryKeyField() {
// Not supported by lightning. We let the implementation sit here, it may get changed in the future.
// In order to support this, lightning needs to implement a proper getItemfromProperty() method.
return null;
}
get UID() {
return this._calendar.id;
}
createNewEvent() {
let event = new CalEvent();
return new TbSync.lightning.TbItem(this, event);
}
createNewTodo() {
let todo = new CalTodo();
return new TbSync.lightning.TbItem(this, todo);
}
async addItem(tbItem, pretagChangelogWithByServerEntry = true) {
if (this.primaryKeyField && !tbItem.getProperty(this.primaryKeyField)) {
tbItem.setProperty(this.primaryKeyField, this._folderData.targetData.generatePrimaryKey());
//Services.console.logStringMessage("[TbCalendar::addItem] Generated primary key!");
}
if (pretagChangelogWithByServerEntry) {
tbItem.changelogStatus = "added_by_server";
}
return await this._calendar.addItem(tbItem._item);
}
async modifyItem(tbNewItem, tbOldItem, pretagChangelogWithByServerEntry = true) {
// only add entry if the current entry does not start with _by_user
let status = tbNewItem.changelogStatus ? tbNewItem.changelogStatus : "";
if (pretagChangelogWithByServerEntry && !status.endsWith("_by_user")) {
tbNewItem.changelogStatus = "modified_by_server";
}
return await this._calendar.modifyItem(tbNewItem._item, tbOldItem._item);
}
async deleteItem(tbItem, pretagChangelogWithByServerEntry = true) {
if (pretagChangelogWithByServerEntry) {
tbItem.changelogStatus = "deleted_by_server";
}
return await this._calendar.deleteItem(tbItem._item);
}
// searchId is interpreted as the primaryKeyField, which is the UID for this target
async getItem (searchId) {
let item = await this._calendar.getItem(searchId);
if (item) {
return new TbSync.lightning.TbItem(this, item);
}
return null;
}
async getItemFromProperty(property, value) {
if (property == "UID") return await this.getItem(value);
else throw ("TbSync.lightning.getItemFromProperty: Currently onle the UID property can be used to search for items.");
}
async getAllItems() {
return await this._calendar.getItems(Ci.calICalendar.ITEM_FILTER_ALL_ITEMS, 0, null, null);
}
getAddedItemsFromChangeLog(maxitems = 0) {
return TbSync.db.getItemsFromChangeLog(this.calendar.id, maxitems, "added_by_user").map(item => item.itemId);
}
getModifiedItemsFromChangeLog(maxitems = 0) {
return TbSync.db.getItemsFromChangeLog(this.calendar.id, maxitems, "modified_by_user").map(item => item.itemId);
}
getDeletedItemsFromChangeLog(maxitems = 0) {
return TbSync.db.getItemsFromChangeLog(this.calendar.id, maxitems, "deleted_by_user").map(item => item.itemId);
}
getItemsFromChangeLog(maxitems = 0) {
return TbSync.db.getItemsFromChangeLog(this.calendar.id, maxitems, "_by_user");
}
removeItemFromChangeLog(id, moveToEndInsteadOfDelete = false) {
TbSync.db.removeItemFromChangeLog(this.calendar.id, id, moveToEndInsteadOfDelete);
}
clearChangelog() {
TbSync.db.clearChangeLog(this.calendar.id);
}
},
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// * Internal Functions
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
getFolderFromCalendarUID: function(calUID) {
let folders = TbSync.db.findFolders({"target": calUID});
if (folders.length == 1) {
let accountData = new TbSync.AccountData(folders[0].accountID);
return new TbSync.FolderData(accountData, folders[0].folderID);
}
return null;
},
getFolderFromCalendarURL: function(calURL) {
let folders = TbSync.db.findFolders({"url": calURL});
if (folders.length == 1) {
let accountData = new TbSync.AccountData(folders[0].accountID);
return new TbSync.FolderData(accountData, folders[0].folderID);
}
return null;
},
calendarObserver : {
onStartBatch : function () {},
onEndBatch : function () {},
onLoad : function (aCalendar) {},
onError : function (aCalendar, aErrNo, aMessage) {},
onAddItem : function (aAddedItem) {
if (!(aAddedItem && aAddedItem.calendar))
return;
let folderData = TbSync.lightning.getFolderFromCalendarUID(aAddedItem.calendar.id);
if (folderData
&& folderData.targetData
&& folderData.targetData.isAdvancedCalendarTargetData) {
let tbCalendar = new TbSync.lightning.TbCalendar(aAddedItem.calendar, folderData);
let tbItem = new TbSync.lightning.TbItem(tbCalendar, aAddedItem);
let itemStatus = tbItem.changelogStatus;
// if this card was created by us, it will be in the log
if (itemStatus && itemStatus.endsWith("_by_server")) {
let age = Date.now() - tbItem.changelogData.timestamp;
if (age < 1500) {
// during freeze, local modifications are not possible
return;
} else {
// remove blocking entry from changelog after freeze time is over (1.5s),
// and continue evaluating this event
abItem.changelogStatus = "";
}
}
if (itemStatus == "deleted_by_user") {
// deleted ? user moved item out and back in -> modified
tbItem.changelogStatus = "modified_by_user";
} else {
tbItem.changelogStatus = "added_by_user";
}
if (tbCalendar.logUserChanges) TbSync.core.setTargetModified(folderData);
folderData.targetData.itemObserver("onAddItem", tbItem, null);
}
},
onModifyItem : function (aNewItem, aOldItem) {
//check, if it is a pure modification within the same calendar
if (!(aNewItem && aNewItem.calendar && aOldItem && aOldItem.calendar && aNewItem.calendar.id == aOldItem.calendar.id))
return;
let folderData = TbSync.lightning.getFolderFromCalendarUID(aNewItem.calendar.id);
if (folderData
&& folderData.targetData
&& folderData.targetData.isAdvancedCalendarTargetData) {
let tbCalendar = new TbSync.lightning.TbCalendar(aNewItem.calendar, folderData);
let tbNewItem = new TbSync.lightning.TbItem(tbCalendar, aNewItem);
let tbOldItem = new TbSync.lightning.TbItem(tbCalendar, aOldItem);
let itemStatus = tbNewItem.changelogStatus;
// if this card was created by us, it will be in the log
if (itemStatus && itemStatus.endsWith("_by_server")) {
let age = Date.now() - tbNewItem.changelogData.timestamp;
if (age < 1500) {
// during freeze, local modifications are not possible
return;
} else {
// remove blocking entry from changelog after freeze time is over (1.5s),
// and continue evaluating this event
tbNewItem.changelogStatus = "";
}
}
if (itemStatus != "added_by_user") {
//added_by_user -> it is a local unprocessed add do not re-add it to changelog
tbNewItem.changelogStatus = "modified_by_user";
}
if (tbCalendar.logUserChanges) TbSync.core.setTargetModified(folderData);
folderData.targetData.itemObserver("onModifyItem", tbNewItem, tbOldItem);
}
},
onDeleteItem : function (aDeletedItem) {
if (!(aDeletedItem && aDeletedItem.calendar))
return;
let folderData = TbSync.lightning.getFolderFromCalendarUID(aDeletedItem.calendar.id);
if (folderData
&& folderData.targetData
&& folderData.targetData.isAdvancedCalendarTargetData) {
let tbCalendar = new TbSync.lightning.TbCalendar(aDeletedItem.calendar, folderData);
let tbItem = new TbSync.lightning.TbItem(tbCalendar, aDeletedItem);
let itemStatus = tbItem.changelogStatus;
// if this card was created by us, it will be in the log
if (itemStatus && itemStatus.endsWith("_by_server")) {
let age = Date.now() - tbItem.changelogData.timestamp;
if (age < 1500) {
// during freeze, local modifications are not possible
return;
} else {
// remove blocking entry from changelog after freeze time is over (1.5s),
// and continue evaluating this event
tbItem.changelogStatus = "";
}
}
if (itemStatus == "added_by_user") {
//a local add, which has not yet been processed (synced) is deleted -> remove all traces
tbItem.changelogStatus = "";
} else {
tbItem.changelogStatus = "deleted_by_user";
}
if (tbCalendar.logUserChanges) TbSync.core.setTargetModified(folderData);
folderData.targetData.itemObserver("onDeleteItem", tbItem, null);
}
},
//Changed properties of the calendar itself (name, color etc.)
onPropertyChanged : function (aCalendar, aName, aValue, aOldValue) {
let folderData = TbSync.lightning.getFolderFromCalendarUID(aCalendar.id);
if (folderData
&& folderData.targetData
&& folderData.targetData.isAdvancedCalendarTargetData) {
let tbCalendar = new TbSync.lightning.TbCalendar(aCalendar, folderData);
switch (aName) {
case "color":
// update stored color to recover after disable
folderData.setFolderProperty("targetColor", aValue);
break;
case "name":
// update stored name to recover after disable
folderData.setFolderProperty("targetName", aValue);
// update settings window, if open
Services.obs.notifyObservers(null, "tbsync.observer.manager.updateSyncstate", folderData.accountID);
break;
}
folderData.targetData.calendarObserver("onCalendarPropertyChanged", tbCalendar, aName, aValue, aOldValue);
}
},
//Deleted properties of the calendar itself (name, color etc.)
onPropertyDeleting : function (aCalendar, aName) {
let folderData = TbSync.lightning.getFolderFromCalendarUID(aCalendar.id);
if (folderData
&& folderData.targetData
&& folderData.targetData.isAdvancedCalendarTargetData) {
let tbCalendar = new TbSync.lightning.TbCalendar(aCalendar, folderData);
switch (aName) {
case "color":
case "name":
//update settings window, if open
Services.obs.notifyObservers(null, "tbsync.observer.manager.updateSyncstate", folderData.accountID);
break;
}
folderData.targetData.calendarObserver("onCalendarPropertyDeleted", tbCalendar, aName);
}
}
},
calendarManagerObserver : {
onCalendarRegistered : function (aCalendar) {
},
onCalendarUnregistering : function (aCalendar) {
/*let folderData = TbSync.lightning.getFolderFromCalendarUID(aCalendar.id);
if (folderData
&& folderData.targetData
&& folderData.targetData.isAdvancedCalendarTargetData) {
folderData.targetData.calendarObserver("onCalendarUnregistered", aCalendar);
}*/
},
onCalendarDeleting : async function (aCalendar) {
let folderData = TbSync.lightning.getFolderFromCalendarUID(aCalendar.id);
if (folderData
&& folderData.targetData
&& folderData.targetData.isAdvancedCalendarTargetData) {
// If the user switches "offline support", the calendar is deleted and recreated. Thus,
// we wait a bit and check, if the calendar is back again and ignore the delete event.
if (aCalendar.type == "caldav") {
await TbSync.tools.sleep(1500);
let calManager = TbSync.lightning.cal.manager;
for (let calendar of calManager.getCalendars({})) {
if (calendar.uri.spec == aCalendar.uri.spec) {
// update the target
folderData.setFolderProperty("target", calendar.id)
return;
}
}
}
//delete any pending changelog of the deleted calendar
TbSync.db.clearChangeLog(aCalendar.id);
let tbCalendar = new TbSync.lightning.TbCalendar(aCalendar, folderData);
//unselect calendar if deleted by user and update settings window, if open
if (folderData.getFolderProperty("selected")) {
folderData.setFolderProperty("selected", false);
//update settings window, if open
Services.obs.notifyObservers(null, "tbsync.observer.manager.updateSyncstate", folderData.accountID);
}
folderData.resetFolderProperty("target");
folderData.targetData.calendarObserver("onCalendarDeleted", tbCalendar);
}
},
},
//this function actually creates a calendar if missing
prepareAndCreateCalendar: async function (folderData) {
let calManager = TbSync.lightning.cal.manager;
let provider = folderData.accountData.getAccountProperty("provider");
//check if there is a known/cached name, and use that as starting point to generate unique name for new calendar
let cachedName = folderData.getFolderProperty("targetName");
let newname = cachedName == "" ? folderData.accountData.getAccountProperty("accountname") + " (" + folderData.getFolderProperty("foldername") + ")" : cachedName;
//check if there is a cached or preloaded color - if not, chose one
if (!folderData.getFolderProperty("targetColor")) {
//define color set
let allColors = [
"#3366CC",
"#DC3912",
"#FF9900",
"#109618",
"#990099",
"#3B3EAC",
"#0099C6",
"#DD4477",
"#66AA00",
"#B82E2E",
"#316395",
"#994499",
"#22AA99",
"#AAAA11",
"#6633CC",
"#E67300",
"#8B0707",
"#329262",
"#5574A6",
"#3B3EAC"];
//find all used colors
let usedColors = [];
for (let calendar of calManager.getCalendars({})) {
if (calendar && calendar.getProperty("color")) {
usedColors.push(calendar.getProperty("color").toUpperCase());
}
}
//we do not want to change order of colors, we want to FILTER by counts, so we need to find the least count, filter by that and then take the first one
let minCount = null;
let statColors = [];
for (let i=0; i< allColors.length; i++) {
let count = usedColors.filter(item => item == allColors[i]).length;
if (minCount === null) minCount = count;
else if (count < minCount) minCount = count;
let obj = {};
obj.color = allColors[i];
obj.count = count;
statColors.push(obj);
}
//filter by minCount
let freeColors = statColors.filter(item => (minCount == null || item.count == minCount));
folderData.setFolderProperty("targetColor", freeColors[0].color);
}
//create and register new calendar
let newCalendar = await folderData.targetData.createCalendar(newname);
newCalendar.setProperty("tbSyncProvider", provider);
newCalendar.setProperty("tbSyncAccountID", folderData.accountData.accountID);
//store id of calendar as target in DB
folderData.setFolderProperty("target", newCalendar.id);
folderData.setFolderProperty("targetName", newCalendar.name);
folderData.setFolderProperty("targetColor", newCalendar.getProperty("color"));
return newCalendar;
}
}
|