-
Notifications
You must be signed in to change notification settings - Fork 96
/
calItemUtils.sys.mjs
673 lines (614 loc) · 20.5 KB
/
calItemUtils.sys.mjs
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
/* 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/. */
var { cal } = ChromeUtils.import("resource:///modules/calendar/calHashedArray.jsm");
/*
* Calendar item related functions
*/
// NOTE: This module should not be loaded directly, it is available when
// including calUtils.jsm under the cal.item namespace.
export var item = {
ItemDiff: (function () {
/**
* Given two sets of items, find out which items were added, changed or
* removed.
*
* The general flow is to first use load method to load the engine with
* the first set of items, then use difference to load the set of
* items to diff against. Afterwards, call the complete method to tell the
* engine that no more items are coming.
*
* You can then access the mAddedItems/mModifiedItems/mDeletedItems attributes to
* get the items that were changed during the process.
*/
function ItemDiff() {
this.reset();
}
ItemDiff.prototype = {
STATE_INITIAL: 1,
STATE_LOADING: 2,
STATE_DIFFERING: 4,
STATE_COMPLETED: 8,
state: 1,
mInitialItems: null,
mModifiedItems: null,
mModifiedOldItems: null,
mAddedItems: null,
mDeletedItems: null,
/**
* Expect the difference engine to be in the given state.
*
* @param aState The state to be in
* @param aMethod The method name expecting the state
*/
_expectState(aState, aMethod) {
if ((this.state & aState) == 0) {
throw new Error(
"ItemDiff method " + aMethod + " called while in unexpected state " + this.state
);
}
},
/**
* Loads an array of items. This step cannot be executed
* after calling the difference methods.
*
* @param items The array of items to load
*/
load(items) {
this._expectState(this.STATE_INITIAL | this.STATE_LOADING, "load");
for (const calendarItem of items) {
this.mInitialItems[calendarItem.hashId] = calendarItem;
}
this.state = this.STATE_LOADING;
},
/**
* Calculate the difference for the array of items. This method should be
* called after all load methods and before the complete method.
*
* @param items The array of items to calculate difference with
*/
difference(items) {
this._expectState(
this.STATE_INITIAL | this.STATE_LOADING | this.STATE_DIFFERING,
"difference"
);
this.mModifiedOldItems.startBatch();
this.mModifiedItems.startBatch();
this.mAddedItems.startBatch();
for (const calendarItem of items) {
if (calendarItem.hashId in this.mInitialItems) {
const oldItem = this.mInitialItems[calendarItem.hashId];
this.mModifiedOldItems.addItem(oldItem);
this.mModifiedItems.addItem(calendarItem);
} else {
this.mAddedItems.addItem(calendarItem);
}
delete this.mInitialItems[calendarItem.hashId];
}
this.mModifiedOldItems.endBatch();
this.mModifiedItems.endBatch();
this.mAddedItems.endBatch();
this.state = this.STATE_DIFFERING;
},
/**
* Tell the engine that all load and difference calls have been made, this
* makes sure that all item states are correctly returned.
*/
complete() {
this._expectState(
this.STATE_INITIAL | this.STATE_LOADING | this.STATE_DIFFERING,
"complete"
);
this.mDeletedItems.startBatch();
for (const hashId in this.mInitialItems) {
const calendarItem = this.mInitialItems[hashId];
this.mDeletedItems.addItem(calendarItem);
}
this.mDeletedItems.endBatch();
this.mInitialItems = {};
this.state = this.STATE_COMPLETED;
},
/** @returns a HashedArray containing the new version of the modified items */
get modifiedItems() {
this._expectState(this.STATE_COMPLETED, "get modifiedItems");
return this.mModifiedItems;
},
/** @returns a HashedArray containing the old version of the modified items */
get modifiedOldItems() {
this._expectState(this.STATE_COMPLETED, "get modifiedOldItems");
return this.mModifiedOldItems;
},
/** @returns a HashedArray containing added items */
get addedItems() {
this._expectState(this.STATE_COMPLETED, "get addedItems");
return this.mAddedItems;
},
/** @returns a HashedArray containing deleted items */
get deletedItems() {
this._expectState(this.STATE_COMPLETED, "get deletedItems");
return this.mDeletedItems;
},
/** @returns the number of loaded items */
get count() {
return Object.keys(this.mInitialItems).length;
},
/**
* Resets the difference engine to its initial state.
*/
reset() {
this.mInitialItems = {};
this.mModifiedItems = new cal.HashedArray();
this.mModifiedOldItems = new cal.HashedArray();
this.mAddedItems = new cal.HashedArray();
this.mDeletedItems = new cal.HashedArray();
this.state = this.STATE_INITIAL;
},
};
return ItemDiff;
})(),
/**
* Checks if an item is supported by a Calendar.
*
* @param aCalendar the calendar
* @param aItem the item either a task or an event
* @returns true or false
*/
isItemSupported(aItem, aCalendar) {
if (aItem.isTodo()) {
return aCalendar.getProperty("capabilities.tasks.supported") !== false;
} else if (aItem.isEvent()) {
return aCalendar.getProperty("capabilities.events.supported") !== false;
}
return false;
},
/*
* Checks whether a calendar supports events
*
* @param aCalendar
*/
isEventCalendar(aCalendar) {
return aCalendar.getProperty("capabilities.events.supported") !== false;
},
/*
* Checks whether a calendar supports tasks
*
* @param aCalendar
*/
isTaskCalendar(aCalendar) {
return aCalendar.getProperty("capabilities.tasks.supported") !== false;
},
/**
* Checks whether the passed item fits into the demanded range.
*
* @param calendarItem the item
* @param rangeStart (inclusive) range start or null (open range)
* @param rangeStart (exclusive) range end or null (open range)
* @param returnDtstartOrDue returns item's start (or due) date in case
* the item is in the specified Range; null otherwise.
*/
checkIfInRange(calendarItem, rangeStart, rangeEnd, returnDtstartOrDue) {
let startDate;
let endDate;
const queryStart = cal.dtz.ensureDateTime(rangeStart);
if (calendarItem.isEvent()) {
startDate = calendarItem.startDate;
if (!startDate) {
// DTSTART mandatory
// xxx todo: should we assert this case?
return null;
}
endDate = calendarItem.endDate || startDate;
} else {
let dueDate = calendarItem.dueDate;
startDate = calendarItem.entryDate || dueDate;
if (!calendarItem.entryDate) {
if (returnDtstartOrDue) {
// DTSTART or DUE mandatory
return null;
}
// 3.6.2. To-do Component
// A "VTODO" calendar component without the "DTSTART" and "DUE" (or
// "DURATION") properties specifies a to-do that will be associated
// with each successive calendar date, until it is completed.
const completedDate = cal.dtz.ensureDateTime(calendarItem.completedDate);
dueDate = cal.dtz.ensureDateTime(dueDate);
return (
!completedDate ||
!queryStart ||
completedDate.compare(queryStart) > 0 ||
(dueDate && dueDate.compare(queryStart) >= 0)
);
}
endDate = dueDate || startDate;
}
const start = cal.dtz.ensureDateTime(startDate);
const end = cal.dtz.ensureDateTime(endDate);
const queryEnd = cal.dtz.ensureDateTime(rangeEnd);
if (start.compare(end) == 0) {
if (
(!queryStart || start.compare(queryStart) >= 0) &&
(!queryEnd || start.compare(queryEnd) < 0)
) {
return startDate;
}
} else if (
(!queryEnd || start.compare(queryEnd) < 0) &&
(!queryStart || end.compare(queryStart) > 0)
) {
return startDate;
}
return null;
},
setItemProperty(calendarItem, propertyName, aValue, aCapability) {
const isSupported =
calendarItem.calendar.getProperty("capabilities." + aCapability + ".supported") !== false;
const value = aCapability && !isSupported ? null : aValue;
switch (propertyName) {
case "startDate":
if (
(value.isDate && !calendarItem.startDate.isDate) ||
(!value.isDate && calendarItem.startDate.isDate) ||
!cal.data.compareObjects(value.timezone, calendarItem.startDate.timezone) ||
value.compare(calendarItem.startDate) != 0
) {
calendarItem.startDate = value;
}
break;
case "endDate":
if (
(value.isDate && !calendarItem.endDate.isDate) ||
(!value.isDate && calendarItem.endDate.isDate) ||
!cal.data.compareObjects(value.timezone, calendarItem.endDate.timezone) ||
value.compare(calendarItem.endDate) != 0
) {
calendarItem.endDate = value;
}
break;
case "entryDate":
if (value == calendarItem.entryDate) {
break;
}
if (
(value && !calendarItem.entryDate) ||
(!value && calendarItem.entryDate) ||
value.isDate != calendarItem.entryDate.isDate ||
!cal.data.compareObjects(value.timezone, calendarItem.entryDate.timezone) ||
value.compare(calendarItem.entryDate) != 0
) {
calendarItem.entryDate = value;
}
break;
case "dueDate":
if (value == calendarItem.dueDate) {
break;
}
if (
(value && !calendarItem.dueDate) ||
(!value && calendarItem.dueDate) ||
value.isDate != calendarItem.dueDate.isDate ||
!cal.data.compareObjects(value.timezone, calendarItem.dueDate.timezone) ||
value.compare(calendarItem.dueDate) != 0
) {
calendarItem.dueDate = value;
}
break;
case "isCompleted":
if (value != calendarItem.isCompleted) {
calendarItem.isCompleted = value;
}
break;
case "PERCENT-COMPLETE": {
let perc = parseInt(calendarItem.getProperty(propertyName), 10);
if (isNaN(perc)) {
perc = 0;
}
if (perc != value) {
calendarItem.setProperty(propertyName, value);
}
break;
}
case "title":
if (value != calendarItem.title) {
calendarItem.title = value;
}
break;
default:
if (!value || value == "") {
calendarItem.deleteProperty(propertyName);
} else if (calendarItem.getProperty(propertyName) != value) {
calendarItem.setProperty(propertyName, value);
}
break;
}
},
/**
* Returns the default transparency to apply for an event depending on whether its an all-day event
*
* @param aIsAllDay If true, the default transparency for all-day events is returned
*/
getEventDefaultTransparency(aIsAllDay) {
let transp = null;
if (aIsAllDay) {
transp = Services.prefs.getBoolPref(
"calendar.events.defaultTransparency.allday.transparent",
false
)
? "TRANSPARENT"
: "OPAQUE";
} else {
transp = Services.prefs.getBoolPref(
"calendar.events.defaultTransparency.standard.transparent",
false
)
? "TRANSPARENT"
: "OPAQUE";
}
return transp;
},
/**
* Compare two items by *content*, leaving out any revision information such as
* X-MOZ-GENERATION, SEQUENCE, DTSTAMP, LAST-MODIFIED.
* The format for the parameters to ignore object is:
* { "PROPERTY-NAME": ["PARAM-NAME", ...] }
*
* If aIgnoreProps is not passed, these properties are ignored:
* X-MOZ-GENERATION, SEQUENCE, DTSTAMP, LAST-MODIFIED, X-MOZ-SEND-INVITATIONS
*
* If aIgnoreParams is not passed, these parameters are ignored:
* ATTENDEE: CN
* ORGANIZER: CN
*
* @param aFirstItem The item to compare.
* @param aSecondItem The item to compare to.
* @param aIgnoreProps (optional) An array of parameters to ignore.
* @param aIgnoreParams (optional) An object describing which parameters to
* ignore.
* @returns True, if items match.
*/
compareContent(aFirstItem, aSecondItem, aIgnoreProps, aIgnoreParams) {
const ignoreProps = arr2hash(
aIgnoreProps || [
"SEQUENCE",
"DTSTAMP",
"LAST-MODIFIED",
"X-MOZ-GENERATION",
"X-MICROSOFT-DISALLOW-COUNTER",
"X-MOZ-SEND-INVITATIONS",
"X-MOZ-SEND-INVITATIONS-UNDISCLOSED",
]
);
const ignoreParams = aIgnoreParams || { ATTENDEE: ["CN"], ORGANIZER: ["CN"] };
for (const x in ignoreParams) {
ignoreParams[x] = arr2hash(ignoreParams[x]);
}
function arr2hash(arr) {
const hash = {};
for (const x of arr) {
hash[x] = true;
}
return hash;
}
// This doesn't have to be super correct rfc5545, it just needs to be
// in the same order
function normalizeComponent(comp) {
let props = [];
for (const prop of cal.iterate.icalProperty(comp)) {
if (!(prop.propertyName in ignoreProps)) {
props.push(normalizeProperty(prop));
}
}
props = props.sort();
let comps = [];
for (const subcomp of cal.iterate.icalSubcomponent(comp)) {
comps.push(normalizeComponent(subcomp));
}
comps = comps.sort();
return comp.componentType + props.join("\r\n") + comps.join("\r\n");
}
function normalizeProperty(prop) {
const params = [...cal.iterate.icalParameter(prop)]
.filter(
([k, v]) =>
!(prop.propertyName in ignoreParams) || !(k in ignoreParams[prop.propertyName])
)
.map(([k, v]) => k + "=" + v)
.sort();
return prop.propertyName + ";" + params.join(";") + ":" + prop.valueAsIcalString;
}
return (
normalizeComponent(aFirstItem.icalComponent) == normalizeComponent(aSecondItem.icalComponent)
);
},
/**
* Shifts an item by the given timely offset.
*
* @param calendarItem an item
* @param offset an offset (calIDuration)
*/
shiftOffset(calendarItem, offset) {
// When modifying dates explicitly using the setters is important
// since those may triggers e.g. calIRecurrenceInfo::onStartDateChange
// or invalidate other properties. Moreover don't modify the date-time objects
// without cloning, because changes cannot be calculated if doing so.
if (calendarItem.isEvent()) {
let date = calendarItem.startDate.clone();
date.addDuration(offset);
calendarItem.startDate = date;
date = calendarItem.endDate.clone();
date.addDuration(offset);
calendarItem.endDate = date;
} else {
/* isToDo */
if (calendarItem.entryDate) {
const date = calendarItem.entryDate.clone();
date.addDuration(offset);
calendarItem.entryDate = date;
}
if (calendarItem.dueDate) {
const date = calendarItem.dueDate.clone();
date.addDuration(offset);
calendarItem.dueDate = date;
}
}
},
/**
* moves an item to another startDate
*
* @param aOldItem The Item to be modified
* @param aNewDate The date at which the new item is going to start
* @returns The modified item
*/
moveToDate(aOldItem, aNewDate) {
const newItem = aOldItem.clone();
const start = (
aOldItem[cal.dtz.startDateProp(aOldItem)] || aOldItem[cal.dtz.endDateProp(aOldItem)]
).clone();
const isDate = start.isDate;
start.resetTo(
aNewDate.year,
aNewDate.month,
aNewDate.day,
start.hour,
start.minute,
start.second,
start.timezone
);
start.isDate = isDate;
if (newItem[cal.dtz.startDateProp(newItem)]) {
newItem[cal.dtz.startDateProp(newItem)] = start;
const oldDuration = aOldItem.duration;
if (oldDuration) {
const oldEnd = aOldItem[cal.dtz.endDateProp(aOldItem)];
let newEnd = start.clone();
newEnd.addDuration(oldDuration);
newEnd = newEnd.getInTimezone(oldEnd.timezone);
newItem[cal.dtz.endDateProp(newItem)] = newEnd;
}
} else if (newItem[cal.dtz.endDateProp(newItem)]) {
newItem[cal.dtz.endDateProp(newItem)] = start;
}
return newItem;
},
/**
* Shortcut function to serialize an item (including all overridden items).
*/
serialize(aItem) {
const serializer = Cc["@mozilla.org/calendar/ics-serializer;1"].createInstance(
Ci.calIIcsSerializer
);
serializer.addItems([aItem]);
return serializer.serializeToString();
},
/**
* Centralized functions for accessing prodid and version
*/
get productId() {
return "-//Mozilla.org/NONSGML Mozilla Calendar V1.1//EN";
},
get productVersion() {
return "2.0";
},
/**
* This is a centralized function for setting the prodid and version on an
* ical component. This should be used whenever you need to set the prodid
* and version on a calIcalComponent object.
*
* @param aIcalComponent The ical component to set the prodid and
* version on.
*/
setStaticProps(aIcalComponent) {
// Throw for an invalid parameter
if (!aIcalComponent) {
throw Components.Exception("", Cr.NS_ERROR_INVALID_ARG);
}
// Set the prodid and version
aIcalComponent.prodid = item.productId;
aIcalComponent.version = item.productVersion;
},
/**
* Search for already open item dialog.
*
* @param aItem The item of the dialog to search for.
*/
findWindow(aItem) {
// check for existing dialog windows
for (const dlg of Services.wm.getEnumerator("Calendar:EventDialog")) {
if (
dlg.arguments[0] &&
dlg.arguments[0].mode == "modify" &&
dlg.arguments[0].calendarEvent &&
dlg.arguments[0].calendarEvent.hashId == aItem.hashId
) {
return dlg;
}
}
// check for existing summary windows
for (const dlg of Services.wm.getEnumerator("Calendar:EventSummaryDialog")) {
if (dlg.calendarItem && dlg.calendarItem.hashId == aItem.hashId) {
return dlg;
}
}
return null;
},
/**
* sets the 'isDate' property of an item
*
* @param aItem The Item to be modified
* @param aIsDate True or false indicating the new value of 'isDate'
* @returns The modified item
*/
setToAllDay(aItem, aIsDate) {
let start = aItem[cal.dtz.startDateProp(aItem)];
let end = aItem[cal.dtz.endDateProp(aItem)];
if (start || end) {
const calendarItem = aItem.clone();
if (start && start.isDate != aIsDate) {
start = start.clone();
start.isDate = aIsDate;
calendarItem[cal.dtz.startDateProp(calendarItem)] = start;
}
if (end && end.isDate != aIsDate) {
end = end.clone();
end.isDate = aIsDate;
calendarItem[cal.dtz.endDateProp(calendarItem)] = end;
}
return calendarItem;
}
return aItem;
},
/**
* This function return the progress state of a task:
* completed, overdue, duetoday, inprogress, future
*
* @param aTask The task to check.
* @returns The progress atom.
*/
getProgressAtom(aTask) {
const nowdate = new Date();
if (aTask.recurrenceInfo) {
return "repeating";
}
if (aTask.isCompleted) {
return "completed";
}
if (aTask.dueDate && aTask.dueDate.isValid) {
if (cal.dtz.dateTimeToJsDate(aTask.dueDate).getTime() < nowdate.getTime()) {
return "overdue";
} else if (
aTask.dueDate.year == nowdate.getFullYear() &&
aTask.dueDate.month == nowdate.getMonth() &&
aTask.dueDate.day == nowdate.getDate()
) {
return "duetoday";
}
}
if (
aTask.entryDate &&
aTask.entryDate.isValid &&
cal.dtz.dateTimeToJsDate(aTask.entryDate).getTime() < nowdate.getTime()
) {
return "inprogress";
}
return "future";
},
};