summaryrefslogtreecommitdiffstats
path: root/comm/calendar/base/src/calItemBase.js
blob: d1cd1599e512a6162a36ba9d2e5cc8159ba982e4 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
/* 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/. */

/* exported makeMemberAttr, makeMemberAttrProperty */

var { cal } = ChromeUtils.import("resource:///modules/calendar/calUtils.jsm");
var { CalAttendee } = ChromeUtils.import("resource:///modules/CalAttendee.jsm");
var { CalRelation } = ChromeUtils.import("resource:///modules/CalRelation.jsm");
var { CalAttachment } = ChromeUtils.import("resource:///modules/CalAttachment.jsm");
var { XPCOMUtils } = ChromeUtils.importESModule("resource://gre/modules/XPCOMUtils.sys.mjs");

XPCOMUtils.defineLazyModuleGetters(this, {
  CalAlarm: "resource:///modules/CalAlarm.jsm",
  CalDateTime: "resource:///modules/CalDateTime.jsm",
  CalRecurrenceInfo: "resource:///modules/CalRecurrenceInfo.jsm",
});

XPCOMUtils.defineLazyServiceGetter(
  this,
  "gParserUtils",
  "@mozilla.org/parserutils;1",
  "nsIParserUtils"
);

XPCOMUtils.defineLazyServiceGetter(
  this,
  "gTextToHtmlConverter",
  "@mozilla.org/txttohtmlconv;1",
  "mozITXTToHTMLConv"
);

/**
 * calItemBase prototype definition
 *
 * @implements calIItemBase
 * @class
 */
function calItemBase() {
  cal.ASSERT(false, "Inheriting objects call initItemBase()!");
}

calItemBase.prototype = {
  mProperties: null,
  mPropertyParams: null,

  mIsProxy: false,
  mHashId: null,
  mImmutable: false,
  mDirty: false,
  mCalendar: null,
  mParentItem: null,
  mRecurrenceInfo: null,
  mOrganizer: null,

  mAlarms: null,
  mAlarmLastAck: null,

  mAttendees: null,
  mAttachments: null,
  mRelations: null,
  mCategories: null,

  mACLEntry: null,

  /**
   * Initialize the base item's attributes. Can be called from inheriting
   * objects in their constructor.
   */
  initItemBase() {
    this.wrappedJSObject = this;
    this.mProperties = new Map();
    this.mPropertyParams = {};
    this.setProperty("CREATED", cal.dtz.jsDateToDateTime(new Date()));
  },

  /**
   * @see nsISupports
   */
  QueryInterface: ChromeUtils.generateQI(["calIItemBase"]),

  /**
   * @see calIItemBase
   */
  get aclEntry() {
    let aclEntry = this.mACLEntry;
    let aclManager = this.calendar && this.calendar.superCalendar.aclManager;

    if (!aclEntry && aclManager) {
      this.mACLEntry = aclManager.getItemEntry(this);
      aclEntry = this.mACLEntry;
    }

    if (!aclEntry && this.parentItem != this) {
      // No ACL entry on this item, check the parent
      aclEntry = this.parentItem.aclEntry;
    }

    return aclEntry;
  },

  // readonly attribute AUTF8String hashId;
  get hashId() {
    if (this.mHashId === null) {
      let rid = this.recurrenceId;
      let calendar = this.calendar;
      // some unused delim character:
      this.mHashId = [
        encodeURIComponent(this.id),
        rid ? rid.getInTimezone(cal.dtz.UTC).icalString : "",
        calendar ? encodeURIComponent(calendar.id) : "",
      ].join("#");
    }
    return this.mHashId;
  },

  // attribute AUTF8String id;
  get id() {
    return this.getProperty("UID");
  },
  set id(uid) {
    this.mHashId = null; // recompute hashId
    this.setProperty("UID", uid);
    if (this.mRecurrenceInfo) {
      this.mRecurrenceInfo.onIdChange(uid);
    }
  },

  // attribute calIDateTime recurrenceId;
  get recurrenceId() {
    return this.getProperty("RECURRENCE-ID");
  },
  set recurrenceId(rid) {
    this.mHashId = null; // recompute hashId
    this.setProperty("RECURRENCE-ID", rid);
  },

  // attribute calIRecurrenceInfo recurrenceInfo;
  get recurrenceInfo() {
    return this.mRecurrenceInfo;
  },
  set recurrenceInfo(value) {
    this.modify();
    this.mRecurrenceInfo = cal.unwrapInstance(value);
  },

  // attribute calIItemBase parentItem;
  get parentItem() {
    return this.mParentItem || this;
  },
  set parentItem(value) {
    if (this.mImmutable) {
      throw Components.Exception("", Cr.NS_ERROR_OBJECT_IS_IMMUTABLE);
    }
    this.mParentItem = cal.unwrapInstance(value);
  },

  /**
   * Initializes the base item to be an item proxy. Used by inheriting
   * objects createProxy() method.
   *
   * XXXdbo Explain proxy a bit better, either here or in
   * calIInternalShallowCopy.
   *
   * @see calIInternalShallowCopy
   * @param aParentItem     The parent item to initialize the proxy on.
   * @param aRecurrenceId   The recurrence id to initialize the proxy for.
   */
  initializeProxy(aParentItem, aRecurrenceId) {
    this.mIsProxy = true;

    aParentItem = cal.unwrapInstance(aParentItem);
    this.mParentItem = aParentItem;
    this.mCalendar = aParentItem.mCalendar;
    this.recurrenceId = aRecurrenceId;

    // Make sure organizer is unset, as the getter checks for this.
    this.mOrganizer = undefined;

    this.mImmutable = aParentItem.mImmutable;
  },

  // readonly attribute boolean isMutable;
  get isMutable() {
    return !this.mImmutable;
  },

  /**
   * This function should be called by all members that modify the item. It
   * checks if the item is immutable and throws accordingly, and sets the
   * mDirty property.
   */
  modify() {
    if (this.mImmutable) {
      throw Components.Exception("", Cr.NS_ERROR_OBJECT_IS_IMMUTABLE);
    }
    this.mDirty = true;
  },

  /**
   * Makes sure the item is not dirty. If the item is dirty, properties like
   * LAST-MODIFIED and DTSTAMP are set to now.
   */
  ensureNotDirty() {
    if (this.mDirty) {
      let now = cal.dtz.jsDateToDateTime(new Date());
      this.setProperty("LAST-MODIFIED", now);
      this.setProperty("DTSTAMP", now);
      this.mDirty = false;
    }
  },

  /**
   * Makes all properties of the base item immutable. Can be called by
   * inheriting objects' makeImmutable method.
   */
  makeItemBaseImmutable() {
    if (this.mImmutable) {
      return;
    }

    // make all our components immutable
    if (this.mRecurrenceInfo) {
      this.mRecurrenceInfo.makeImmutable();
    }

    if (this.mOrganizer) {
      this.mOrganizer.makeImmutable();
    }
    if (this.mAttendees) {
      for (let att of this.mAttendees) {
        att.makeImmutable();
      }
    }

    for (let propValue of this.mProperties.values()) {
      if (propValue?.isMutable) {
        propValue.makeImmutable();
      }
    }

    if (this.mAlarms) {
      for (let alarm of this.mAlarms) {
        alarm.makeImmutable();
      }
    }

    if (this.mAlarmLastAck) {
      this.mAlarmLastAck.makeImmutable();
    }

    this.ensureNotDirty();
    this.mImmutable = true;
  },

  // boolean hasSameIds(in calIItemBase aItem);
  hasSameIds(that) {
    return (
      that &&
      this.id == that.id &&
      (this.recurrenceId == that.recurrenceId || // both null
        (this.recurrenceId &&
          that.recurrenceId &&
          this.recurrenceId.compare(that.recurrenceId) == 0))
    );
  },

  /**
   * Overridden by CalEvent to indicate the item is an event.
   */
  isEvent() {
    return false;
  },

  /**
   * Overridden by CalTodo to indicate the item is a todo.
   */
  isTodo() {
    return false;
  },

  // calIItemBase clone();
  clone() {
    return this.cloneShallow(this.mParentItem);
  },

  /**
   * Clones the base item's properties into the passed object, potentially
   * setting a new parent item.
   *
   * @param m     The item to clone this item into
   * @param aNewParent    (optional) The new parent item to set on m.
   */
  cloneItemBaseInto(cloned, aNewParent) {
    cloned.mImmutable = false;
    cloned.mACLEntry = this.mACLEntry;
    cloned.mIsProxy = this.mIsProxy;
    cloned.mParentItem = cal.unwrapInstance(aNewParent) || this.mParentItem;
    cloned.mHashId = this.mHashId;
    cloned.mCalendar = this.mCalendar;
    if (this.mRecurrenceInfo) {
      cloned.mRecurrenceInfo = cal.unwrapInstance(this.mRecurrenceInfo.clone());
      cloned.mRecurrenceInfo.item = cloned;
    }

    let org = this.organizer;
    if (org) {
      org = org.clone();
    }
    cloned.mOrganizer = org;

    cloned.mAttendees = [];
    for (let att of this.getAttendees()) {
      cloned.mAttendees.push(att.clone());
    }

    cloned.mProperties = new Map();
    for (let [name, value] of this.mProperties.entries()) {
      if (value instanceof CalDateTime || value instanceof Ci.calIDateTime) {
        value = value.clone();
      }

      cloned.mProperties.set(name, value);

      let propBucket = this.mPropertyParams[name];
      if (propBucket) {
        let newBucket = {};
        for (let param in propBucket) {
          newBucket[param] = propBucket[param];
        }
        cloned.mPropertyParams[name] = newBucket;
      }
    }

    cloned.mAttachments = [];
    for (let att of this.getAttachments()) {
      cloned.mAttachments.push(att.clone());
    }

    cloned.mRelations = [];
    for (let rel of this.getRelations()) {
      cloned.mRelations.push(rel.clone());
    }

    cloned.mCategories = this.getCategories();

    cloned.mAlarms = [];
    for (let alarm of this.getAlarms()) {
      // Clone alarms into new item, assume the alarms from the old item
      // are valid and don't need validation.
      cloned.mAlarms.push(alarm.clone());
    }

    let alarmLastAck = this.alarmLastAck;
    if (alarmLastAck) {
      alarmLastAck = alarmLastAck.clone();
    }
    cloned.mAlarmLastAck = alarmLastAck;

    cloned.mDirty = this.mDirty;

    return cloned;
  },

  // attribute calIDateTime alarmLastAck;
  get alarmLastAck() {
    return this.mAlarmLastAck;
  },
  set alarmLastAck(aValue) {
    this.modify();
    if (aValue && !aValue.timezone.isUTC) {
      aValue = aValue.getInTimezone(cal.dtz.UTC);
    }
    this.mAlarmLastAck = aValue;
  },

  // readonly attribute calIDateTime lastModifiedTime;
  get lastModifiedTime() {
    this.ensureNotDirty();
    return this.getProperty("LAST-MODIFIED");
  },

  // readonly attribute calIDateTime stampTime;
  get stampTime() {
    this.ensureNotDirty();
    return this.getProperty("DTSTAMP");
  },

  // attribute AUTF8string descriptionText;
  get descriptionText() {
    return this.getProperty("DESCRIPTION");
  },

  set descriptionText(text) {
    this.setProperty("DESCRIPTION", text);
    if (text) {
      this.setPropertyParameter("DESCRIPTION", "ALTREP", null);
    } // else: property parameter deleted by setProperty(..., null)
  },

  // attribute AUTF8string descriptionHTML;
  get descriptionHTML() {
    let altrep = this.getPropertyParameter("DESCRIPTION", "ALTREP");
    if (altrep?.startsWith("data:text/html,")) {
      try {
        return decodeURIComponent(altrep.slice("data:text/html,".length));
      } catch (ex) {
        console.error(ex);
      }
    }
    // Fallback: Upconvert the plaintext
    let description = this.getProperty("DESCRIPTION");
    if (!description) {
      return null;
    }
    let mode = Ci.mozITXTToHTMLConv.kStructPhrase | Ci.mozITXTToHTMLConv.kURLs;
    description = gTextToHtmlConverter.scanTXT(description, mode);
    return description.replace(/\r?\n/g, "<br>");
  },

  set descriptionHTML(html) {
    if (html) {
      // We need to output a plaintext version of the description, even if we're
      // using the ALTREP parameter. We use the "preformatted" option in case
      // the HTML contains a <pre/> tag with newlines.
      let mode =
        Ci.nsIDocumentEncoder.OutputDropInvisibleBreak |
        Ci.nsIDocumentEncoder.OutputLFLineBreak |
        Ci.nsIDocumentEncoder.OutputPreformatted;
      let text = gParserUtils.convertToPlainText(html, mode, 0);

      this.setProperty("DESCRIPTION", text);

      // If the text is non-empty, create a standard ALTREP representation of
      // the description as HTML.
      // N.B. There's logic in nsMsgCompose for determining if HTML is
      // convertible to plaintext without losing formatting. We could test if we
      // could leave this part off if we generalized that logic.
      if (text) {
        this.setPropertyParameter(
          "DESCRIPTION",
          "ALTREP",
          "data:text/html," + encodeURIComponent(html)
        );
      }
    } else {
      this.deleteProperty("DESCRIPTION");
    }
  },

  // Each inner array has two elements: a string and a nsIVariant.
  // readonly attribute Array<Array<jsval> > properties;
  get properties() {
    let properties = this.mProperties;
    if (this.mIsProxy) {
      let parentProperties = this.mParentItem.wrappedJSObject.mProperties;
      let thisProperties = this.mProperties;
      properties = new Map(
        (function* () {
          yield* parentProperties;
          yield* thisProperties;
        })()
      );
    }

    return [...properties.entries()];
  },

  // nsIVariant getProperty(in AString name);
  getProperty(aName) {
    let name = aName.toUpperCase();
    if (this.mProperties.has(name)) {
      return this.mProperties.get(name);
    }
    return this.mIsProxy ? this.mParentItem.getProperty(name) : null;
  },

  // boolean hasProperty(in AString name);
  hasProperty(aName) {
    return this.getProperty(aName) != null;
  },

  // void setProperty(in AString name, in nsIVariant value);
  setProperty(aName, aValue) {
    this.modify();
    aName = aName.toUpperCase();
    if (aValue || !isNaN(parseInt(aValue, 10))) {
      this.mProperties.set(aName, aValue);
      if (!(aName in this.mPropertyParams)) {
        this.mPropertyParams[aName] = {};
      }
    } else {
      this.deleteProperty(aName);
    }
    if (aName == "LAST-MODIFIED") {
      // setting LAST-MODIFIED cleans/undirties the item, we use this for preserving DTSTAMP
      this.mDirty = false;
    }
  },

  // void deleteProperty(in AString name);
  deleteProperty(aName) {
    this.modify();
    aName = aName.toUpperCase();
    if (this.mIsProxy) {
      // deleting a proxy's property will mark the bag's item as null, so we could
      // distinguish it when enumerating/getting properties from the undefined ones.
      this.mProperties.set(aName, null);
    } else {
      this.mProperties.delete(aName);
    }
    delete this.mPropertyParams[aName];
  },

  // AString getPropertyParameter(in AString aPropertyName,
  //                              in AString aParameterName);
  getPropertyParameter(aPropName, aParamName) {
    let propName = aPropName.toUpperCase();
    let paramName = aParamName.toUpperCase();
    if (propName in this.mPropertyParams) {
      if (paramName in this.mPropertyParams[propName]) {
        // If the property is not in mPropertyParams, then this just means
        // there are no properties set.
        return this.mPropertyParams[propName][paramName];
      }
      return null;
    }
    return this.mIsProxy ? this.mParentItem.getPropertyParameter(propName, paramName) : null;
  },

  // boolean hasPropertyParameter(in AString aPropertyName,
  //                              in AString aParameterName);
  hasPropertyParameter(aPropName, aParamName) {
    return this.getPropertyParameter(aPropName, aParamName) != null;
  },

  // void setPropertyParameter(in AString aPropertyName,
  //                           in AString aParameterName,
  //                           in AUTF8String aParameterValue);
  setPropertyParameter(aPropName, aParamName, aParamValue) {
    let propName = aPropName.toUpperCase();
    let paramName = aParamName.toUpperCase();
    this.modify();
    if (!(propName in this.mPropertyParams)) {
      if (this.hasProperty(propName)) {
        this.mPropertyParams[propName] = {};
      } else {
        throw new Error("Property " + aPropName + " not set");
      }
    }
    if (aParamValue || !isNaN(parseInt(aParamValue, 10))) {
      this.mPropertyParams[propName][paramName] = aParamValue;
    } else {
      delete this.mPropertyParams[propName][paramName];
    }
    return aParamValue;
  },

  // Array<AString> getParameterNames(in AString aPropertyName);
  getParameterNames(aPropName) {
    let propName = aPropName.toUpperCase();
    if (!(propName in this.mPropertyParams)) {
      if (this.mIsProxy) {
        return this.mParentItem.getParameterNames(aPropName);
      }
      throw new Error("Property " + aPropName + " not set");
    }
    return Object.keys(this.mPropertyParams[propName]);
  },

  // Array<calIAttendee> getAttendees();
  getAttendees() {
    if (!this.mAttendees && this.mIsProxy) {
      this.mAttendees = this.mParentItem.getAttendees();
    }
    if (this.mAttendees) {
      return Array.from(this.mAttendees); // clone
    }
    return [];
  },

  // calIAttendee getAttendeeById(in AUTF8String id);
  getAttendeeById(id) {
    let attendees = this.getAttendees();
    let lowerCaseId = id.toLowerCase();
    for (let attendee of attendees) {
      // This match must be case insensitive to deal with differing
      // cases of things like MAILTO:
      if (attendee.id.toLowerCase() == lowerCaseId) {
        return attendee;
      }
    }
    return null;
  },

  // void removeAttendee(in calIAttendee attendee);
  removeAttendee(attendee) {
    this.modify();
    let found = false,
      newAttendees = [];
    let attendees = this.getAttendees();
    let attIdLowerCase = attendee.id.toLowerCase();

    for (let i = 0; i < attendees.length; i++) {
      if (attendees[i].id.toLowerCase() == attIdLowerCase) {
        found = true;
      } else {
        newAttendees.push(attendees[i]);
      }
    }
    if (found) {
      this.mAttendees = newAttendees;
    }
  },

  // void removeAllAttendees();
  removeAllAttendees() {
    this.modify();
    this.mAttendees = [];
  },

  // void addAttendee(in calIAttendee attendee);
  addAttendee(attendee) {
    if (!attendee.id) {
      cal.LOG("Tried to add invalid attended");
      return;
    }
    // the duplicate check is migration code for bug 1204255
    let exists = this.getAttendeeById(attendee.id);
    if (exists) {
      cal.LOG(
        "Ignoring attendee duplicate for item " + this.id + " (" + this.title + "): " + exists.id
      );
      if (
        exists.participationStatus == "NEEDS-ACTION" ||
        attendee.participationStatus == "DECLINED"
      ) {
        this.removeAttendee(exists);
      } else {
        attendee = null;
      }
    }
    if (attendee) {
      if (attendee.commonName) {
        // migration code for bug 1209399 to remove leading/training double quotes in
        let commonName = attendee.commonName.replace(/^["]*([^"]*)["]*$/, "$1");
        if (commonName.length == 0) {
          commonName = null;
        }
        if (commonName != attendee.commonName) {
          if (attendee.isMutable) {
            attendee.commonName = commonName;
          } else {
            cal.LOG(
              "Failed to cleanup malformed commonName for immutable attendee " +
                attendee.toString() +
                "\n" +
                cal.STACK(20)
            );
          }
        }
      }
      this.modify();
      this.mAttendees = this.getAttendees();
      this.mAttendees.push(attendee);
    }
  },

  // Array<calIAttachment> getAttachments();
  getAttachments() {
    if (!this.mAttachments && this.mIsProxy) {
      this.mAttachments = this.mParentItem.getAttachments();
    }
    if (this.mAttachments) {
      return this.mAttachments.concat([]); // clone
    }
    return [];
  },

  // void removeAttachment(in calIAttachment attachment);
  removeAttachment(aAttachment) {
    this.modify();
    for (let attIndex in this.mAttachments) {
      if (cal.data.compareObjects(this.mAttachments[attIndex], aAttachment, Ci.calIAttachment)) {
        this.modify();
        this.mAttachments.splice(attIndex, 1);
        break;
      }
    }
  },

  // void addAttachment(in calIAttachment attachment);
  addAttachment(attachment) {
    this.modify();
    this.mAttachments = this.getAttachments();
    if (!this.mAttachments.some(x => x.hashId == attachment.hashId)) {
      this.mAttachments.push(attachment);
    }
  },

  // void removeAllAttachments();
  removeAllAttachments() {
    this.modify();
    this.mAttachments = [];
  },

  // Array<calIRelation> getRelations();
  getRelations() {
    if (!this.mRelations && this.mIsProxy) {
      this.mRelations = this.mParentItem.getRelations();
    }
    if (this.mRelations) {
      return this.mRelations.concat([]);
    }
    return [];
  },

  // void removeRelation(in calIRelation relation);
  removeRelation(aRelation) {
    this.modify();
    for (let attIndex in this.mRelations) {
      // Could we have the same item as parent and as child ?
      if (
        this.mRelations[attIndex].relId == aRelation.relId &&
        this.mRelations[attIndex].relType == aRelation.relType
      ) {
        this.modify();
        this.mRelations.splice(attIndex, 1);
        break;
      }
    }
  },

  // void addRelation(in calIRelation relation);
  addRelation(aRelation) {
    this.modify();
    this.mRelations = this.getRelations();
    this.mRelations.push(aRelation);
    // XXX ensure that the relation isn't already there?
  },

  // void removeAllRelations();
  removeAllRelations() {
    this.modify();
    this.mRelations = [];
  },

  // attribute calICalendar calendar;
  get calendar() {
    if (!this.mCalendar && this.parentItem != this) {
      return this.parentItem.calendar;
    }
    return this.mCalendar;
  },
  set calendar(calendar) {
    if (this.mImmutable) {
      throw Components.Exception("", Cr.NS_ERROR_OBJECT_IS_IMMUTABLE);
    }
    this.mHashId = null; // recompute hashId
    this.mCalendar = calendar;
  },

  // attribute calIAttendee organizer;
  get organizer() {
    if (this.mIsProxy && this.mOrganizer === undefined) {
      return this.mParentItem.organizer;
    }
    return this.mOrganizer;
  },
  set organizer(organizer) {
    this.modify();
    this.mOrganizer = organizer;
  },

  // Array<AString> getCategories();
  getCategories() {
    if (!this.mCategories && this.mIsProxy) {
      this.mCategories = this.mParentItem.getCategories();
    }
    if (this.mCategories) {
      return this.mCategories.concat([]); // clone
    }
    return [];
  },

  // void setCategories(in Array<AString> aCategories);
  setCategories(aCategories) {
    this.modify();
    this.mCategories = aCategories.concat([]);
  },

  // attribute AUTF8String icalString;
  get icalString() {
    throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED);
  },
  set icalString(str) {
    throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED);
  },

  /**
   * The map of promoted properties is a list of those properties that are
   * represented directly by getters/setters.
   * All of these property names must be in upper case isPropertyPromoted to
   * function correctly. The has/get/set/deleteProperty interfaces
   * are case-insensitive, but these are not.
   */
  itemBasePromotedProps: {
    CREATED: true,
    UID: true,
    "LAST-MODIFIED": true,
    SUMMARY: true,
    PRIORITY: true,
    STATUS: true,
    DTSTAMP: true,
    RRULE: true,
    EXDATE: true,
    RDATE: true,
    ATTENDEE: true,
    ATTACH: true,
    CATEGORIES: true,
    ORGANIZER: true,
    "RECURRENCE-ID": true,
    "X-MOZ-LASTACK": true,
    "RELATED-TO": true,
  },

  /**
   * A map of properties that need translation between the ical component
   * property and their ICS counterpart.
   */
  icsBasePropMap: [
    { cal: "CREATED", ics: "createdTime" },
    { cal: "LAST-MODIFIED", ics: "lastModified" },
    { cal: "DTSTAMP", ics: "stampTime" },
    { cal: "UID", ics: "uid" },
    { cal: "SUMMARY", ics: "summary" },
    { cal: "PRIORITY", ics: "priority" },
    { cal: "STATUS", ics: "status" },
    { cal: "RECURRENCE-ID", ics: "recurrenceId" },
  ],

  /**
   * Walks through the propmap and sets all properties on this item from the
   * given icalcomp.
   *
   * @param icalcomp      The calIIcalComponent to read from.
   * @param propmap       The property map to walk through.
   */
  mapPropsFromICS(icalcomp, propmap) {
    for (let i = 0; i < propmap.length; i++) {
      let prop = propmap[i];
      let val = icalcomp[prop.ics];
      if (val != null && val != Ci.calIIcalComponent.INVALID_VALUE) {
        this.setProperty(prop.cal, val);
      }
    }
  },

  /**
   * Walks through the propmap and sets all properties on the given icalcomp
   * from the properties set on this item.
   * given icalcomp.
   *
   * @param icalcomp      The calIIcalComponent to write to.
   * @param propmap       The property map to walk through.
   */
  mapPropsToICS(icalcomp, propmap) {
    for (let i = 0; i < propmap.length; i++) {
      let prop = propmap[i];
      let val = this.getProperty(prop.cal);
      if (val != null && val != Ci.calIIcalComponent.INVALID_VALUE) {
        icalcomp[prop.ics] = val;
      }
    }
  },

  /**
   * Reads an ical component and sets up the base item's properties to match
   * it.
   *
   * @param icalcomp      The ical component to read.
   */
  setItemBaseFromICS(icalcomp) {
    this.modify();

    // re-initializing from scratch -- no light proxy anymore:
    this.mIsProxy = false;
    this.mProperties = new Map();
    this.mPropertyParams = {};

    this.mapPropsFromICS(icalcomp, this.icsBasePropMap);

    this.mAttendees = []; // don't inherit anything from parent
    for (let attprop of cal.iterate.icalProperty(icalcomp, "ATTENDEE")) {
      let att = new CalAttendee();
      att.icalProperty = attprop;
      this.addAttendee(att);
    }

    this.mAttachments = []; // don't inherit anything from parent
    for (let attprop of cal.iterate.icalProperty(icalcomp, "ATTACH")) {
      let att = new CalAttachment();
      att.icalProperty = attprop;
      this.addAttachment(att);
    }

    this.mRelations = []; // don't inherit anything from parent
    for (let relprop of cal.iterate.icalProperty(icalcomp, "RELATED-TO")) {
      let rel = new CalRelation();
      rel.icalProperty = relprop;
      this.addRelation(rel);
    }

    let org = null;
    let orgprop = icalcomp.getFirstProperty("ORGANIZER");
    if (orgprop) {
      org = new CalAttendee();
      org.icalProperty = orgprop;
      org.isOrganizer = true;
    }
    this.mOrganizer = org;

    this.mCategories = [];
    for (let catprop of cal.iterate.icalProperty(icalcomp, "CATEGORIES")) {
      this.mCategories.push(catprop.value);
    }

    // find recurrence properties
    let rec = null;
    if (!this.recurrenceId) {
      for (let recprop of cal.iterate.icalProperty(icalcomp)) {
        let ritem = null;
        switch (recprop.propertyName) {
          case "RRULE":
          case "EXRULE":
            ritem = cal.createRecurrenceRule();
            break;
          case "RDATE":
          case "EXDATE":
            ritem = cal.createRecurrenceDate();
            break;
          default:
            continue;
        }
        ritem.icalProperty = recprop;

        if (!rec) {
          rec = new CalRecurrenceInfo(this);
        }
        rec.appendRecurrenceItem(ritem);
      }
    }
    this.mRecurrenceInfo = rec;

    this.mAlarms = []; // don't inherit anything from parent
    for (let alarmComp of cal.iterate.icalSubcomponent(icalcomp, "VALARM")) {
      let alarm = new CalAlarm();
      try {
        alarm.icalComponent = alarmComp;
        this.addAlarm(alarm, true);
      } catch (e) {
        cal.ERROR(
          "Invalid alarm for item: " +
            this.id +
            " (" +
            alarmComp.serializeToICS() +
            ")" +
            " exception: " +
            e
        );
      }
    }

    let lastAck = icalcomp.getFirstProperty("X-MOZ-LASTACK");
    this.mAlarmLastAck = null;
    if (lastAck) {
      this.mAlarmLastAck = cal.createDateTime(lastAck.value);
    }

    this.mDirty = false;
  },

  /**
   * Import all properties not in the promoted map into this item's extended
   * properties bag.
   *
   * @param icalcomp      The ical component to read.
   * @param promoted      The map of promoted properties.
   */
  importUnpromotedProperties(icalcomp, promoted) {
    for (let prop of cal.iterate.icalProperty(icalcomp)) {
      let propName = prop.propertyName;
      if (!promoted[propName]) {
        this.setProperty(propName, prop.value);
        for (let [paramName, paramValue] of cal.iterate.icalParameter(prop)) {
          if (!(propName in this.mPropertyParams)) {
            this.mPropertyParams[propName] = {};
          }
          this.mPropertyParams[propName][paramName] = paramValue;
        }
      }
    }
  },

  // boolean isPropertyPromoted(in AString name);
  isPropertyPromoted(name) {
    return this.itemBasePromotedProps[name.toUpperCase()];
  },

  // attribute calIIcalComponent icalComponent;
  get icalComponent() {
    throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED);
  },
  set icalComponent(val) {
    throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED);
  },

  // attribute PRUint32 generation;
  get generation() {
    let gen = this.getProperty("X-MOZ-GENERATION");
    return gen ? parseInt(gen, 10) : 0;
  },
  set generation(aValue) {
    this.setProperty("X-MOZ-GENERATION", String(aValue));
  },

  /**
   * Fills the passed ical component with the base item's properties.
   *
   * @param icalcomp    The ical component to write to.
   */
  fillIcalComponentFromBase(icalcomp) {
    this.ensureNotDirty();

    this.mapPropsToICS(icalcomp, this.icsBasePropMap);

    let org = this.organizer;
    if (org) {
      icalcomp.addProperty(org.icalProperty);
    }

    for (let attendee of this.getAttendees()) {
      icalcomp.addProperty(attendee.icalProperty);
    }

    for (let attachment of this.getAttachments()) {
      icalcomp.addProperty(attachment.icalProperty);
    }

    for (let relation of this.getRelations()) {
      icalcomp.addProperty(relation.icalProperty);
    }

    if (this.mRecurrenceInfo) {
      for (let ritem of this.mRecurrenceInfo.getRecurrenceItems()) {
        icalcomp.addProperty(ritem.icalProperty);
      }
    }

    for (let cat of this.getCategories()) {
      let catprop = cal.icsService.createIcalProperty("CATEGORIES");
      catprop.value = cat;
      icalcomp.addProperty(catprop);
    }

    if (this.mAlarms) {
      for (let alarm of this.mAlarms) {
        icalcomp.addSubcomponent(alarm.icalComponent);
      }
    }

    let alarmLastAck = this.alarmLastAck;
    if (alarmLastAck) {
      let lastAck = cal.icsService.createIcalProperty("X-MOZ-LASTACK");
      // - should we further ensure that those are UTC or rely on calAlarmService doing so?
      lastAck.value = alarmLastAck.icalString;
      icalcomp.addProperty(lastAck);
    }
  },

  // Array<calIAlarm> getAlarms();
  getAlarms() {
    if (!this.mAlarms && this.mIsProxy) {
      this.mAlarms = this.mParentItem.getAlarms();
    }
    if (this.mAlarms) {
      return this.mAlarms.concat([]); // clone
    }
    return [];
  },

  /**
   * Adds an alarm. The second parameter is for internal use only, i.e not
   * provided on the interface.
   *
   * @see calIItemBase
   * @param aDoNotValidate    Don't serialize the component to check for
   *                            errors.
   */
  addAlarm(aAlarm, aDoNotValidate) {
    if (!aDoNotValidate) {
      try {
        // Trigger the icalComponent getter to make sure the alarm is valid.
        aAlarm.icalComponent; // eslint-disable-line no-unused-expressions
      } catch (e) {
        throw Components.Exception("", Cr.NS_ERROR_INVALID_ARG);
      }
    }

    this.modify();
    this.mAlarms = this.getAlarms();
    this.mAlarms.push(aAlarm);
  },

  // void deleteAlarm(in calIAlarm aAlarm);
  deleteAlarm(aAlarm) {
    this.modify();
    this.mAlarms = this.getAlarms();
    for (let i = 0; i < this.mAlarms.length; i++) {
      if (cal.data.compareObjects(this.mAlarms[i], aAlarm, Ci.calIAlarm)) {
        this.mAlarms.splice(i, 1);
        break;
      }
    }
  },

  // void clearAlarms();
  clearAlarms() {
    this.modify();
    this.mAlarms = [];
  },

  // Array<calIItemBase> getOccurrencesBetween(in calIDateTime aStartDate, in calIDateTime aEndDate);
  getOccurrencesBetween(aStartDate, aEndDate) {
    if (this.recurrenceInfo) {
      return this.recurrenceInfo.getOccurrences(aStartDate, aEndDate, 0);
    }

    if (cal.item.checkIfInRange(this, aStartDate, aEndDate)) {
      return [this];
    }

    return [];
  },
};

makeMemberAttrProperty(calItemBase, "CREATED", "creationDate");
makeMemberAttrProperty(calItemBase, "SUMMARY", "title");
makeMemberAttrProperty(calItemBase, "PRIORITY", "priority");
makeMemberAttrProperty(calItemBase, "CLASS", "privacy");
makeMemberAttrProperty(calItemBase, "STATUS", "status");
makeMemberAttrProperty(calItemBase, "ALARMTIME", "alarmTime");

/**
 * Adds a member attribute to the given prototype.
 *
 * @param {Function} ctor - The constructor function of the prototype.
 * @param {string} varname - The variable name to get/set.
 * @param {string} attr - The attribute name to be used.
 * @param {*} dflt - The default value in case none is set.
 */
function makeMemberAttr(ctor, varname, attr, dflt) {
  let getter = function () {
    return varname in this ? this[varname] : dflt;
  };
  let setter = function (value) {
    this.modify();
    this[varname] = value;
    return value;
  };

  ctor.prototype.__defineGetter__(attr, getter);
  ctor.prototype.__defineSetter__(attr, setter);
}

/**
 * Adds a member attribute to the given prototype, using `getProperty` and
 * `setProperty` for access.
 *
 * Default values are not handled here, but instead are set in constructors,
 * which makes it possible to e.g. iterate through `mProperties` when cloning
 * an object.
 *
 * @param {Function} ctor - The constructor function of the prototype.
 * @param {string} name - The property name to get/set.
 * @param {string} attr - The attribute name to be used.
 */
function makeMemberAttrProperty(ctor, name, attr) {
  let getter = function () {
    return this.getProperty(name);
  };
  let setter = function (value) {
    this.modify();
    return this.setProperty(name, value);
  };
  ctor.prototype.__defineGetter__(attr, getter);
  ctor.prototype.__defineSetter__(attr, setter);
}