/
CalendarEventViewModel.ts
1307 lines (1136 loc) · 46.7 KB
/
CalendarEventViewModel.ts
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
import {
AccountType,
AlarmInterval,
CalendarAttendeeStatus,
EndType,
FeatureType,
getAttendeeStatus,
RepeatPeriod,
ShareCapability,
TimeFormat,
} from "../../api/common/TutanotaConstants"
import type {CalendarEvent, CalendarRepeatRule, Contact, EncryptedMailAddress, Mail} from "../../api/entities/tutanota/TypeRefs.js"
import {createCalendarEvent, createCalendarEventAttendee, createEncryptedMailAddress} from "../../api/entities/tutanota/TypeRefs.js"
import type {AlarmInfo, RepeatRule} from "../../api/entities/sys/TypeRefs.js"
import {createAlarmInfo} from "../../api/entities/sys/TypeRefs.js"
import type {MailboxDetail} from "../../mail/model/MailModel"
import stream from "mithril/stream"
import Stream from "mithril/stream"
import {copyMailAddress, getDefaultSenderFromUser, getEnabledMailAddressesWithUser, getSenderNameForUser, RecipientField} from "../../mail/model/MailUtils"
import {
CalendarEventValidity,
checkEventValidity,
createRepeatRuleWithValues,
generateUid,
getAllDayDateUTCFromZone,
getDiffInDays,
getEventEnd,
getEventStart,
getNextHalfHour,
getRepeatEndTime,
getStartOfDayWithZone,
getStartOfNextDayWithZone,
getTimeZone,
incrementByRepeatPeriod,
incrementSequence,
prepareCalendarDescription,
} from "./CalendarUtils"
import {isCustomizationEnabledForCustomer} from "../../api/common/utils/Utils"
import {
addMapEntry,
arrayEqualsWithPredicate,
assertNotNull,
clone,
deleteMapEntry,
downcast,
incrementDate,
neverNull,
noOp,
ofClass,
} from "@tutao/tutanota-utils"
import {generateEventElementId, isAllDayEvent} from "../../api/common/utils/CommonCalendarUtils"
import type {CalendarInfo} from "../model/CalendarModel"
import {CalendarModel} from "../model/CalendarModel"
import {DateTime} from "luxon"
import {NotFoundError, PayloadTooLargeError, TooManyRequestsError} from "../../api/common/error/RestError"
import type {CalendarUpdateDistributor} from "./CalendarUpdateDistributor"
import {calendarUpdateDistributor} from "./CalendarUpdateDistributor"
import type {UserController} from "../../api/main/UserController"
import type {SendMailModel} from "../../mail/editor/SendMailModel"
import {UserError} from "../../api/main/UserError"
import {logins} from "../../api/main/LoginController"
import {locator} from "../../api/main/MainLocator"
import {EntityClient} from "../../api/common/EntityClient"
import {BusinessFeatureRequiredError} from "../../api/main/BusinessFeatureRequiredError"
import {hasCapabilityOnGroup} from "../../sharing/GroupUtils"
import {Time} from "../../api/common/utils/Time"
import {hasError} from "../../api/common/utils/ErrorCheckUtils"
import {Recipient, RecipientType} from "../../api/common/recipients/Recipient"
import {ResolveMode} from "../../api/main/RecipientsModel.js"
import {TIMESTAMP_ZERO_YEAR} from "@tutao/tutanota-utils/dist/DateUtils"
// whether to close dialog
export type EventCreateResult = boolean
const enum EventType {
OWN = "own",
// event in our own calendar and we are organizer
SHARED_RO = "shared_ro",
// event in shared calendar with read permission
SHARED_RW = "shared_rw",
// event in shared calendar with write permission
INVITE = "invite", // invite from calendar invitation which is not stored in calendar yet, or event stored and we are not organizer
}
export type Guest = {
address: EncryptedMailAddress
type: RecipientType
status: CalendarAttendeeStatus
}
type SendMailPurpose = "invite" | "update" | "cancel" | "response"
type SendMailModelFactory = (arg0: MailboxDetail, arg1: SendMailPurpose) => SendMailModel
export type RepeatData = {
frequency: RepeatPeriod
interval: number
endType: EndType
endValue: number
}
type ShowProgressCallback = (arg0: Promise<unknown>) => unknown
type InitEventTypeReturn = {
eventType: EventType,
organizer: EncryptedMailAddress | null,
possibleOrganizers: Array<EncryptedMailAddress>
}
/**
* ViewModel for viewing/editing the event. Takes care of sending out updates.
*/
export class CalendarEventViewModel {
readonly summary: Stream<string>
readonly selectedCalendar: Stream<CalendarInfo | null>
startDate!: Date
endDate!: Date
// Null start or end time means the user input was invalid
startTime: Time | null = null
endTime: Time | null = null
readonly allDay: Stream<boolean>
repeat: RepeatData | null = null
calendars: ReadonlyMap<Id, CalendarInfo>
readonly attendees: Stream<ReadonlyArray<Guest>>
organizer: EncryptedMailAddress | null
readonly possibleOrganizers: ReadonlyArray<EncryptedMailAddress>
readonly location: Stream<string>
note: string
readonly amPmFormat: boolean
readonly existingEvent: CalendarEvent | null
private _oldStartTime: Time | null = null
readonly _zone: string
// We keep alarms read-only so that view can diff just array and not all elements
alarms: ReadonlyArray<AlarmInfo>
// UserController already keeps track of user updates, it is better to not have our own reference to the user, we might miss
// important updates like premium upgrade
readonly _userController: UserController
readonly _eventType: EventType
readonly _distributor: CalendarUpdateDistributor
readonly _calendarModel: CalendarModel
readonly _inviteModel: SendMailModel
readonly _updateModel: SendMailModel
readonly _cancelModel: SendMailModel
readonly _ownMailAddresses: Array<string>
readonly _entityClient: EntityClient
// We want to observe changes to it. To not mutate accidentally without stream update we keep it immutable.
readonly _guestStatuses: Stream<ReadonlyMap<string, CalendarAttendeeStatus>>
readonly _sendModelFactory: () => SendMailModel
/** Our own attendee, it should not be included in any of the sendMailModels. */
readonly _ownAttendee: Stream<EncryptedMailAddress | null>
_responseTo: Mail | null
readonly sendingOutUpdate: Stream<boolean>
_processing: boolean
hasBusinessFeature: Stream<boolean>
hasPremiumLegacy: Stream<boolean>
isForceUpdates: Stream<boolean>
readonly initialized: Promise<CalendarEventViewModel>
constructor(
userController: UserController,
distributor: CalendarUpdateDistributor,
calendarModel: CalendarModel,
entityClient: EntityClient,
mailboxDetail: MailboxDetail,
sendMailModelFactory: SendMailModelFactory,
date: Date,
zone: string,
calendars: ReadonlyMap<Id, CalendarInfo>,
existingEvent: CalendarEvent | null,
responseTo: Mail | null,
resolveRecipientsLazily: boolean,
) {
this._distributor = distributor
this._calendarModel = calendarModel
this._entityClient = entityClient
this._userController = userController
this._responseTo = responseTo ?? null
this._inviteModel = sendMailModelFactory(mailboxDetail, "invite")
this._updateModel = sendMailModelFactory(mailboxDetail, "update")
this._cancelModel = sendMailModelFactory(mailboxDetail, "cancel")
this.summary = stream("")
this._sendModelFactory = () => sendMailModelFactory(mailboxDetail, "response")
this._ownMailAddresses = getEnabledMailAddressesWithUser(mailboxDetail, userController.userGroupInfo)
this._ownAttendee = stream<EncryptedMailAddress | null>(null)
this.sendingOutUpdate = stream<boolean>(false)
this._processing = false
this.hasBusinessFeature = stream<boolean>(false)
this.hasPremiumLegacy = stream<boolean>(false)
this.isForceUpdates = stream<boolean>(false)
this.location = stream("")
this.note = ""
this.allDay = stream<boolean>(false)
this.amPmFormat = userController.userSettingsGroupRoot.timeFormat === TimeFormat.TWELVE_HOURS
this.existingEvent = existingEvent ?? null
this._zone = zone
this._guestStatuses = this._initGuestStatus(existingEvent, resolveRecipientsLazily)
this.attendees = this._initAttendees()
const {eventType, organizer, possibleOrganizers} = this.initEventTypeAndOrganizers(existingEvent, calendars, mailboxDetail, userController)
this._eventType = eventType
this.organizer = organizer
this.possibleOrganizers = possibleOrganizers
this.alarms = []
this.calendars = calendars
this.selectedCalendar = stream<CalendarInfo | null>(this.getAvailableCalendars()[0] ?? null)
this.initialized = Promise.resolve().then(async () => {
if (existingEvent) {
if (existingEvent.invitedConfidentially != null) {
this.setConfidential(existingEvent.invitedConfidentially)
}
}
if (existingEvent) {
await this._applyValuesFromExistingEvent(existingEvent, calendars)
} else {
// We care about passed time here, use it for default time values.
this._setDefaultTimes(date)
this.startDate = getStartOfDayWithZone(date, this._zone)
this.endDate = getStartOfDayWithZone(date, this._zone)
}
await this.updateCustomerFeatures()
return this
})
}
rescheduleEvent(newStartDate: Date) {
const oldStartDate = new Date(this.startDate)
const startTime = this.startTime
if (startTime) {
oldStartDate.setHours(startTime.hours)
oldStartDate.setMinutes(startTime.minutes)
}
const oldEndDate = new Date(this.endDate)
const endTime = this.endTime
if (endTime) {
oldEndDate.setHours(endTime.hours)
oldEndDate.setMinutes(endTime.minutes)
}
const diff = newStartDate.getTime() - oldStartDate.getTime()
const newEndDate = new Date(oldEndDate.getTime() + diff)
this.startDate = getStartOfDayWithZone(newStartDate, this._zone)
this.endDate = getStartOfDayWithZone(newEndDate, this._zone)
this.startTime = Time.fromDate(newStartDate)
this.endTime = Time.fromDate(newEndDate)
}
async _applyValuesFromExistingEvent(existingEvent: CalendarEvent, calendars: ReadonlyMap<Id, CalendarInfo>): Promise<void> {
this.summary(existingEvent.summary)
const calendarForGroup = calendars.get(neverNull(existingEvent._ownerGroup))
if (calendarForGroup) {
this.selectedCalendar(calendarForGroup)
}
this.allDay(isAllDayEvent(existingEvent))
this.startDate = getStartOfDayWithZone(getEventStart(existingEvent, this._zone), this._zone)
if (this.allDay()) {
this.endDate = incrementDate(getEventEnd(existingEvent, this._zone), -1)
// We don't care about passed time here, just use current one as default
this._setDefaultTimes()
} else {
const startDate = DateTime.fromJSDate(getEventStart(existingEvent, this._zone), {
zone: this._zone,
})
const endDate = DateTime.fromJSDate(getEventEnd(existingEvent, this._zone), {
zone: this._zone,
})
this.startTime = Time.fromDateTime(startDate)
this.endTime = Time.fromDateTime(endDate)
this.endDate = getStartOfDayWithZone(endDate.toJSDate(), this._zone)
}
if (existingEvent.repeatRule) {
const existingRule = existingEvent.repeatRule
const repeat: RepeatData = {
frequency: downcast(existingRule.frequency),
interval: Number(existingRule.interval),
endType: downcast(existingRule.endType),
endValue: existingRule.endType === EndType.Count ? Number(existingRule.endValue) : 1,
}
if (existingRule.endType === EndType.UntilDate) {
repeat.endValue = getRepeatEndTime(existingRule, this.allDay(), this._zone).getTime()
}
this.repeat = repeat
} else {
this.repeat = null
}
this.location(existingEvent.location)
this.note = prepareCalendarDescription(existingEvent.description)
const alarms = await this._calendarModel.loadAlarms(existingEvent.alarmInfos, this._userController.user)
for (let alarm of alarms) {
this.addAlarm(downcast(alarm.alarmInfo.trigger))
}
}
/**
* Determines the event type, the organizer of the event and possible organizers in accordance with the capabilities for events (see table).
* Note that the only "real" organizer that an event can have is the owner of the calendar.
* If events are created by someone we share our personal calendar with, the organizer is overwritten and set to our own primary address.
* Possible organizers are all email addresses of the user, allowed to modify the organizer. This is only the owner of the calendar ("real" organizer)
* and only if there are no guests.
*
* Capability for events is fairly complicated:
* Note: share "shared" means "not owner of the calendar". Calendar always looks like personal for the owner.
*
* | Calendar | is organizer | can edit details | can modify own attendance | can modify guests | can modify organizer
* |--------------------|------------------|---------------------|---------------------------|-------------------|----------
* | Personal (own) | yes | yes | yes | yes | yes
* | Personal (invite) | no | yes (local) | yes | no | no
* | Personal (own) | no**** | yes | yes | yes | yes
* | Shared | yes**** | yes*** | no | no* | no*
* | Shared | no | no | no** | no* | no*
*
* * we don't allow inviting guests in other people's calendar because later only organizer can modify event and
* we don't want to prevent calendar owner from editing events in their own calendar.
*
* ** this is not "our" copy of the event, from the point of organizer we saw it just accidentally.
* Later we might support proposing ourselves as attendee but currently organizer should be asked to
* send out the event.
*
* *** depends on share capability and whether there are attendees.
*
* **** The creator of the event. Will be overwritten with owner of the calendar by this function.
*/
private initEventTypeAndOrganizers(existingEvent: CalendarEvent | null, calendars: ReadonlyMap<Id, CalendarInfo>, mailboxDetail: MailboxDetail, userController: UserController): InitEventTypeReturn {
const ownDefaultSender = addressToMailAddress(getDefaultSenderFromUser(userController), mailboxDetail, userController)
if (!existingEvent) {
return {
eventType: EventType.OWN,
organizer: ownDefaultSender,
possibleOrganizers: this._ownPossibleOrganizers(mailboxDetail, userController)
}
} else {
// OwnerGroup is not set for events from file
const calendarInfoForEvent = existingEvent._ownerGroup && calendars.get(existingEvent._ownerGroup)
const existingOrganizer = existingEvent.organizer
if (calendarInfoForEvent) {
if (calendarInfoForEvent.shared) {
return {
eventType: hasCapabilityOnGroup(this._userController.user, calendarInfoForEvent.group, ShareCapability.Write)
? EventType.SHARED_RW
: EventType.SHARED_RO,
organizer: existingOrganizer ? copyMailAddress(existingOrganizer) : null,
possibleOrganizers: existingOrganizer ? [existingOrganizer] : []
}
} else {
//For an event in a personal calendar there are 3 options (see table)
//1. We are the organizer of the event (or the event does not have an organizer yet and we become the organizer of the event)
//2. If we are not the organizer and the event does not have guests, it was created by someone we shared our calendar with (also considered our own event)
if (!existingOrganizer || this._ownMailAddresses.includes(existingOrganizer.address) || existingEvent.attendees.length === 0) {
//we want to keep the existing organizer if it is one of our email addresses in all other cases we use our primary address
const actualOrganizer = existingOrganizer && this._ownMailAddresses.includes(existingOrganizer.address) ? existingOrganizer : ownDefaultSender
return {
eventType: EventType.OWN,
organizer: copyMailAddress(actualOrganizer),
possibleOrganizers: this.hasGuests() ? [actualOrganizer] : this._ownPossibleOrganizers(mailboxDetail, userController)
}
}
//3. the event is an invitation
else {
return {
eventType: EventType.INVITE,
organizer: existingOrganizer,
possibleOrganizers: [existingOrganizer]
}
}
}
} else {
// We can edit new invites (from files)
return {
eventType: EventType.INVITE,
organizer: existingOrganizer ? copyMailAddress(existingOrganizer) : null,
possibleOrganizers: existingOrganizer ? [existingOrganizer] : []
}
}
}
}
_initGuestStatus(
existingEvent: CalendarEvent | null,
resolveRecipientsLazily: boolean,
): Stream<ReadonlyMap<string, CalendarAttendeeStatus>> {
const newStatuses = new Map()
if (existingEvent) {
existingEvent.attendees
.filter(attendee => !hasError(attendee.address))
.forEach(attendee => {
if (this._ownMailAddresses.includes(attendee.address.address)) {
this._ownAttendee(copyMailAddress(attendee.address))
} else {
this._updateModel.addRecipient(
RecipientField.BCC,
{
name: attendee.address.name,
address: attendee.address.address,
},
resolveRecipientsLazily ? ResolveMode.Lazy : ResolveMode.Eager,
)
}
newStatuses.set(attendee.address.address, getAttendeeStatus(attendee))
})
}
return stream<ReadonlyMap<string, CalendarAttendeeStatus>>(newStatuses)
}
async updateCustomerFeatures(): Promise<void> {
if (this._userController.isInternalUser()) {
const customer = await this._userController.loadCustomer()
this.hasBusinessFeature(isCustomizationEnabledForCustomer(customer, FeatureType.BusinessFeatureEnabled))
this.hasPremiumLegacy(isCustomizationEnabledForCustomer(customer, FeatureType.PremiumLegacy))
} else {
this.hasBusinessFeature(false)
this.hasPremiumLegacy(false)
}
}
_initAttendees(): Stream<ReadonlyArray<Guest>> {
return stream.merge([this._inviteModel.onMailChanged, this._updateModel.onMailChanged, this._guestStatuses, this._ownAttendee] as Stream<unknown>[]).map(() => {
const makeGuestList = (model: SendMailModel) => {
return model.bccRecipients().map(recipient => {
const guest = {
address: createEncryptedMailAddress({
name: recipient.name,
address: recipient.address,
}),
status: this._guestStatuses().get(recipient.address) || CalendarAttendeeStatus.NEEDS_ACTION,
type: recipient.type,
}
return guest
})
}
const guests = makeGuestList(this._inviteModel).concat(makeGuestList(this._updateModel))
const ownAttendee = this._ownAttendee()
if (ownAttendee) {
guests.unshift({
address: ownAttendee,
status: this._guestStatuses().get(ownAttendee.address) || CalendarAttendeeStatus.ACCEPTED,
type: RecipientType.INTERNAL,
})
}
return guests as ReadonlyArray<Guest>
})
}
_setDefaultTimes(date: Date = getNextHalfHour()) {
const endTimeDate = new Date(date)
endTimeDate.setMinutes(endTimeDate.getMinutes() + 30)
this.startTime = Time.fromDate(date)
this.endTime = Time.fromDate(endTimeDate)
}
_ownPossibleOrganizers(mailboxDetail: MailboxDetail, userController: UserController): Array<EncryptedMailAddress> {
return this._ownMailAddresses.map(address => addressToMailAddress(address, mailboxDetail, userController))
}
findOwnAttendee(): Guest | null {
return this.attendees().find(a => this._ownMailAddresses.includes(a.address.address)) ?? null
}
setStartTime(value: Time | null) {
this._oldStartTime = this.startTime
this.startTime = value
if (this.startDate.getTime() === this.endDate.getTime()) {
this._adjustEndTime()
}
}
setEndTime(value: Time | null) {
this.endTime = value
}
addGuest(mailAddress: string, contact: Contact | null) {
// 1: if the attendee already exists, do nothing
// 2: if the attendee is not yourself, add to the invite model
// 3: if the attendee is yourself and you already exist as an attendee, remove yourself
// 4: add the attendee
// 5: add organizer if you are not already in the list
// We don't add a guest if they are already an attendee
// even though the SendMailModel handles deduplication, we need to check here because recipients shouldn't be duplicated across the 3 models either
if (this.attendees().some(a => a.address.address === mailAddress)) {
return
}
const isOwnAttendee = this._ownMailAddresses.includes(mailAddress)
// SendMailModel handles deduplication
// this.attendees will be updated when the model's recipients are updated
if (!isOwnAttendee) {
this._inviteModel.addRecipient(
RecipientField.BCC,
{
address: mailAddress,
contact,
}
)
}
const status = isOwnAttendee ? CalendarAttendeeStatus.ACCEPTED : CalendarAttendeeStatus.ADDED
// If we exist as an attendee and the added guest is also an attendee, then remove the existing ownAttendee
// and the new one will be added in the next step
if (isOwnAttendee) {
const ownAttendee = this.findOwnAttendee()
if (ownAttendee) {
this._guestStatuses(deleteMapEntry(this._guestStatuses(), ownAttendee.address.address))
}
}
// if this guy wasn't already an attendee with a status
if (!this._guestStatuses().has(mailAddress)) {
this._guestStatuses(addMapEntry(this._guestStatuses(), mailAddress, status))
}
// this duplicated condition check may or may not be redundant to do here
if (isOwnAttendee) {
const newOrganizer = this.possibleOrganizers.find(o => o.address === mailAddress)
if (newOrganizer) this.setOrganizer(newOrganizer)
}
// Add organizer as attendee if not currenly in the list
if (this.attendees().length === 1 && this.findOwnAttendee() == null) {
this.selectGoing(CalendarAttendeeStatus.ACCEPTED)
}
}
getGuestPassword(guest: Guest): string {
return (
this._inviteModel.getPassword(guest.address.address) ||
this._updateModel.getPassword(guest.address.address) ||
this._cancelModel.getPassword(guest.address.address)
)
}
isReadOnlyEvent(): boolean {
// For the RW calendar we have two similar cases:
//
// Case 1:
// Owner of the calendar created the event and invited some people. We, user with whom calendar was shared as RW, are seeing this event.
// We cannot modify that event even though we have RW permission because we are the not organizer.
// If the event is changed, the update must be sent out and we cannot do that because we are not the organizer.
//
// Case 2:
// Owner of the calendar received an invite and saved the event to the calendar. We, user with whom the calendar was shared as RW, are seeing this event.
// We can (theoretically) modify the event locally because we don't need to send any updates but we cannot change attendance because this would require sending an email.
// But we don't want to allow editing the event to make it more understandable for everyone.
return this._eventType === EventType.SHARED_RO || (this._eventType === EventType.SHARED_RW && this.attendees().length > 0)
}
_adjustEndTime() {
if (!this.startTime || !this.endTime || !this._oldStartTime) {
return
}
const endTotalMinutes = this.endTime.hours * 60 + this.endTime.minutes
const startTotalMinutes = this.startTime.hours * 60 + this.startTime.minutes
const diff = Math.abs(endTotalMinutes - this._oldStartTime.hours * 60 - this._oldStartTime.minutes)
const newEndTotalMinutes = startTotalMinutes + diff
let newEndHours = Math.floor(newEndTotalMinutes / 60)
if (newEndHours > 23) {
newEndHours = 23
}
const newEndMinutes = newEndTotalMinutes % 60
this.endTime = new Time(newEndHours, newEndMinutes)
}
setStartDate(date: Date) {
// The custom ID for events is derived from the unix timestamp, and sorting
// the negative ids is a challenge we decided not to
// tackle because it is a rare case.
if (date && date.getFullYear() < TIMESTAMP_ZERO_YEAR) {
const thisYear = new Date().getFullYear()
let newDate = new Date(date)
newDate.setFullYear(thisYear)
this.startDate = newDate
} else {
const diff = getDiffInDays(this.startDate, date)
this.endDate = DateTime.fromJSDate(this.endDate, {
zone: this._zone,
})
.plus({
days: diff,
})
.toJSDate()
this.startDate = date
}
}
setEndDate(date: Date) {
this.endDate = date
}
onRepeatPeriodSelected(repeatPeriod: RepeatPeriod | null) {
if (repeatPeriod == null) {
this.repeat = null
} else {
// Provide default values if repeat is not there, override them with existing repeat if it's there, provide new frequency
this.repeat = Object.assign(
{
interval: 1,
endType: EndType.Never,
endValue: 1,
frequency: repeatPeriod,
},
this.repeat,
{
frequency: repeatPeriod,
},
)
}
}
onEndOccurencesSelected(endValue: number) {
if (this.repeat && this.repeat.endType === EndType.Count) {
this.repeat.endValue = endValue
}
}
onRepeatEndDateSelected(endDate: Date | null) {
const {repeat} = this
if (endDate && repeat && repeat.endType === EndType.UntilDate) {
repeat.endValue = endDate.getTime()
}
}
onRepeatIntervalChanged(interval: number) {
if (this.repeat) {
this.repeat.interval = interval
}
}
onRepeatEndTypeChanged(endType: EndType) {
const {repeat} = this
if (repeat) {
repeat.endType = endType
if (endType === EndType.UntilDate) {
repeat.endValue = incrementByRepeatPeriod(new Date(), RepeatPeriod.MONTHLY, 1, this._zone).getTime()
} else {
repeat.endValue = 1
}
}
}
addAlarm(trigger: AlarmInterval) {
const alarm = createCalendarAlarm(generateEventElementId(Date.now()), trigger)
this.alarms = this.alarms.concat(alarm)
}
changeAlarm(identifier: string, trigger: AlarmInterval | null) {
const newAlarms = this.alarms.slice()
for (let i = 0; i < newAlarms.length; i++) {
if (newAlarms[i].alarmIdentifier === identifier) {
if (trigger) {
newAlarms[i].trigger = trigger
} else {
newAlarms.splice(i, 1)
}
this.alarms = newAlarms
break
}
}
}
changeDescription(description: string) {
this.note = description
}
canModifyGuests(): boolean {
// It is not allowed to modify guests in shared calendar or invite.
const selectedCalendar = this.selectedCalendar()
return selectedCalendar != null && !selectedCalendar.shared && this._eventType !== EventType.INVITE
}
shouldShowSendInviteNotAvailable(): boolean {
if (this._userController.user.accountType === AccountType.FREE) {
return true
}
if (this._userController.user.accountType === AccountType.EXTERNAL) {
return false
}
return !this.hasBusinessFeature() && !this.hasPremiumLegacy()
}
removeAttendee(guest: Guest) {
const existingRecipient = this.existingEvent && this.existingEvent.attendees.find(a => a.address.address === guest.address.address)
for (const model of [this._inviteModel, this._updateModel, this._cancelModel]) {
const recipientInfo = model.bccRecipients().find(r => r.address === guest.address.address)
if (recipientInfo) {
model.removeRecipient(recipientInfo, RecipientField.BCC)
const newStatuses = new Map(this._guestStatuses())
newStatuses.delete(recipientInfo.address)
this._guestStatuses(newStatuses)
}
}
if (existingRecipient) {
this._cancelModel.addRecipient(RecipientField.BCC, {
address: existingRecipient.address.address,
name: existingRecipient.address.name,
})
}
}
canModifyOwnAttendance(): boolean {
// We can always modify own attendance in own event. Also can modify if it's invite in our calendar and we are invited.
return this._eventType === EventType.OWN || (this._eventType === EventType.INVITE && !!this.findOwnAttendee())
}
canModifyOrganizer(): boolean {
// We can only modify the organizer if it is our own event and there are no guests
return (
this._eventType === EventType.OWN && !this.hasGuests()
)
}
private hasGuests() {
return this.existingEvent && this.existingEvent.attendees.length > 0 &&
!(this.existingEvent.attendees.length === 1 && this._ownMailAddresses.includes(this.existingEvent.attendees[0].address.address))
}
setOrganizer(newOrganizer: EncryptedMailAddress): void {
if (this.canModifyOrganizer()) {
this.organizer = newOrganizer
// we always add the organizer to the attendee list
this._ownAttendee(newOrganizer)
}
}
canModifyAlarms(): boolean {
return this._eventType === EventType.OWN || this._eventType === EventType.INVITE || this._eventType === EventType.SHARED_RW
}
async deleteEvent(): Promise<void> {
const event = this.existingEvent
if (event) {
try {
// We must always be in attendees so we just check that there's more than one attendee
if (this._eventType === EventType.OWN && event.attendees.length > 1) {
await this.sendCancellation(event)
}
return this._calendarModel.deleteEvent(event).catch(ofClass(NotFoundError, noOp))
} catch (e) {
if (!(e instanceof NotFoundError)) {
throw e
}
}
}
}
async waitForResolvedRecipients(): Promise<void> {
await Promise.all([
this._inviteModel.waitForResolvedRecipients(),
this._updateModel.waitForResolvedRecipients(),
this._cancelModel.waitForResolvedRecipients(),
])
}
isForceUpdateAvailable(): boolean {
return this._eventType === EventType.OWN && !this.shouldShowSendInviteNotAvailable() && this._hasUpdatableAttendees()
}
/**
* @reject UserError
*/
async saveAndSend({
askForUpdates,
askInsecurePassword,
showProgress,
}: {
askForUpdates: () => Promise<"yes" | "no" | "cancel">
askInsecurePassword: () => Promise<boolean>
showProgress: ShowProgressCallback
}): Promise<EventCreateResult> {
await this.initialized
if (this._processing) {
return Promise.resolve(false)
}
this._processing = true
return Promise.resolve()
.then(async () => {
await this.waitForResolvedRecipients()
const newEvent = this._initializeNewEvent()
const newAlarms = this.alarms.slice()
// We want to avoid asking whether to send out updates in case nothing has changed
if (this._eventType === EventType.OWN && (this.isForceUpdates() || this._hasChanges(newEvent))) {
// It is our own event. We might need to send out invites/cancellations/updates
return this._sendNotificationAndSave(askInsecurePassword, askForUpdates, showProgress, newEvent, newAlarms)
} else if (this._eventType === EventType.INVITE) {
// We have been invited by another person (internal/ unsecure external)
return this._respondToOrganizerAndSave(showProgress, assertNotNull(this.existingEvent), newEvent, newAlarms)
} else {
// Either this is an event in a shared calendar. We cannot send anything because it's not our event.
// Or no changes were made that require sending updates and we just save other changes.
const p = this._saveEvent(newEvent, newAlarms)
showProgress(p)
return p.then(() => true)
}
})
.catch(
ofClass(PayloadTooLargeError, () => {
throw new UserError("requestTooLarge_msg")
}),
)
.finally(() => {
this._processing = false
})
}
private async sendCancellation(event: CalendarEvent): Promise<any> {
const updatedEvent = clone(event)
// This is guaranteed to be our own event.
updatedEvent.sequence = incrementSequence(updatedEvent.sequence, true)
const cancelAddresses = event.attendees.filter(a => !this._ownMailAddresses.includes(a.address.address)).map(a => a.address)
try {
for (const address of cancelAddresses) {
this._cancelModel.addRecipient(RecipientField.BCC, {
name: address.name,
address: address.address,
contact: null,
})
const recipient = await this._cancelModel.getRecipient(RecipientField.BCC, address.address)!.resolved()
// We cannot send a notification to external recipients without a password, so we exclude them
if (this._cancelModel.isConfidential()) {
if (recipient.type === RecipientType.EXTERNAL && !this._cancelModel.getPassword(recipient.address)) {
this._cancelModel.removeRecipient(recipient, RecipientField.BCC, false)
}
}
}
if (this._cancelModel.allRecipients().length) {
await this._distributor.sendCancellation(updatedEvent, this._cancelModel)
}
} catch (e) {
if (e instanceof TooManyRequestsError) {
throw new UserError("mailAddressDelay_msg") // This will be caught and open error dialog
} else {
throw e
}
}
}
_saveEvent(newEvent: CalendarEvent, newAlarms: Array<AlarmInfo>): Promise<void> {
if (this._userController.user.accountType === AccountType.EXTERNAL) {
return Promise.resolve()
}
const groupRoot = assertNotNull(this.selectedCalendar()).groupRoot
if (this.existingEvent == null || this.existingEvent._id == null) {
return this._calendarModel.createEvent(newEvent, newAlarms, this._zone, groupRoot)
} else {
return this._calendarModel.updateEvent(newEvent, newAlarms, this._zone, groupRoot, this.existingEvent).then(noOp)
}
}
_hasUpdatableAttendees(): boolean {
return this._updateModel.bccRecipients().length > 0
}
_sendNotificationAndSave(
askInsecurePassword: () => Promise<boolean>,
askForUpdates: () => Promise<"yes" | "no" | "cancel">,
showProgress: ShowProgressCallback,
newEvent: CalendarEvent,
newAlarms: Array<AlarmInfo>,
): Promise<boolean> {
// ask for update
const askForUpdatesAwait = this._hasUpdatableAttendees()
? this.isForceUpdates()
? Promise.resolve("yes") // we do not ask again because the user has already indicated that they want to send updates
: askForUpdates()
: Promise.resolve("no")
// no updates possible
const passwordCheck = () => (this.hasInsecurePasswords() && this.containsExternalRecipients() ? askInsecurePassword() : Promise.resolve(true))
return askForUpdatesAwait.then(updateResponse => {
if (updateResponse === "cancel") {
return false
} else if (
this.shouldShowSendInviteNotAvailable() && // we check again to prevent updates after cancelling business or updates for an imported event
(updateResponse === "yes" || this._inviteModel.bccRecipients().length || this._cancelModel.bccRecipients().length)
) {
throw new BusinessFeatureRequiredError("businessFeatureRequiredInvite_msg")
}
// Do check passwords if there are new recipients. We already made decision for those who we invited before
return Promise.resolve(this._inviteModel.bccRecipients().length ? passwordCheck() : true).then(passwordCheckPassed => {
if (!passwordCheckPassed) {
// User said to not send despite insecure password, stop
return false
}
// Invites are cancellations are sent out independent of the updates decision
const p = this._sendInvite(newEvent)
.then(() =>
this._cancelModel.bccRecipients().length ? this._distributor.sendCancellation(newEvent, this._cancelModel) : Promise.resolve(),
)
.then(() => this._saveEvent(newEvent, newAlarms))
.then(() => (updateResponse === "yes" ? this._distributor.sendUpdate(newEvent, this._updateModel) : Promise.resolve()))
.then(() => true)
showProgress(p)
return p
})
})
}
_sendInvite(event: CalendarEvent): Promise<void> {
const newAttendees = event.attendees.filter(a => a.status === CalendarAttendeeStatus.ADDED)
if (newAttendees.length > 0) {
return this._distributor.sendInvite(event, this._inviteModel).then(() => {
newAttendees.forEach(a => {
if (a.status === CalendarAttendeeStatus.ADDED) {
a.status = CalendarAttendeeStatus.NEEDS_ACTION
}
this._guestStatuses(addMapEntry(this._guestStatuses(), a.address.address, CalendarAttendeeStatus.NEEDS_ACTION))
})
})
} else {
return Promise.resolve()
}
}
_respondToOrganizerAndSave(
showProgress: ShowProgressCallback,
existingEvent: CalendarEvent,
newEvent: CalendarEvent,
newAlarms: Array<AlarmInfo>,
): Promise<boolean> {
// We are not using this._findAttendee() because we want to search it on the event, before our modifications
const ownAttendee = existingEvent.attendees.find(a => this._ownMailAddresses.includes(a.address.address))
const selectedOwnAttendeeStatus = ownAttendee && this._guestStatuses().get(ownAttendee.address.address)
let sendPromise = Promise.resolve()
if (ownAttendee && selectedOwnAttendeeStatus !== CalendarAttendeeStatus.NEEDS_ACTION && ownAttendee.status !== selectedOwnAttendeeStatus) {
ownAttendee.status = assertNotNull(selectedOwnAttendeeStatus)
const sendResponseModel = this._sendModelFactory()
const organizer = assertNotNull(existingEvent.organizer)
sendResponseModel.addRecipient(RecipientField.TO, {
name: organizer.name,
address: organizer.address,
})
sendPromise = this._distributor
.sendResponse(newEvent, sendResponseModel, ownAttendee.address.address, this._responseTo, assertNotNull(selectedOwnAttendeeStatus))
.then(() => sendResponseModel.dispose())
}
const p = sendPromise.then(() => this._saveEvent(newEvent, newAlarms))
showProgress(p)
return p.then(() => true)
}