-
Notifications
You must be signed in to change notification settings - Fork 290
/
NotificationRepository.ts
903 lines (795 loc) · 33 KB
/
NotificationRepository.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
/*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
import {Availability} from '@wireapp/protocol-messaging';
import {amplify} from 'amplify';
import ko from 'knockout';
import {Environment} from 'Util/Environment';
import {Declension, t} from 'Util/LocalizerUtil';
import {Logger, getLogger} from 'Util/Logger';
import {getFirstName} from 'Util/SanitizationUtil';
import {truncate} from 'Util/StringUtil';
import {TIME_IN_MILLIS, formatDuration} from 'Util/TimeUtil';
import {ValidationUtilError} from 'Util/ValidationUtil';
import {AudioType} from '../audio/AudioType';
import {TERMINATION_REASON} from '../calling/enum/TerminationReason';
import {WebAppEvents} from '../event/WebApp';
import {PermissionStatusState} from '../permission/PermissionStatusState';
import {PermissionType} from '../permission/PermissionType';
import {NotificationPreference} from './NotificationPreference';
import {PermissionState} from './PermissionState';
import {CallingRepository} from '../calling/CallingRepository';
import {ConnectionEntity} from '../connection/ConnectionEntity';
import {ConversationEphemeralHandler} from '../conversation/ConversationEphemeralHandler';
import {ConversationRepository} from '../conversation/ConversationRepository';
import {Conversation} from '../entity/Conversation';
import {CallMessage} from '../entity/message/CallMessage';
import {ContentMessage} from '../entity/message/ContentMessage';
import {DeleteConversationMessage} from '../entity/message/DeleteConversationMessage';
import {MemberMessage} from '../entity/message/MemberMessage';
import {Message} from '../entity/message/Message';
import {MessageTimerUpdateMessage} from '../entity/message/MessageTimerUpdateMessage';
import {RenameMessage} from '../entity/message/RenameMessage';
import {SystemMessage} from '../entity/message/SystemMessage';
import {User} from '../entity/User';
import {SuperType} from '../message/SuperType';
import {SystemMessageType} from '../message/SystemMessageType';
import {PermissionRepository} from '../permission/PermissionRepository';
import {UserRepository} from '../user/UserRepository';
import {ContentViewModel} from '../view_model/ContentViewModel';
import {WarningsViewModel} from '../view_model/WarningsViewModel';
interface ContentViewModelState {
multitasking: {isMinimized: ko.Observable<boolean> | (() => false)};
state: () => string | false;
}
interface NotificationContent {
/** Notification options */
options: {data: {conversationId: string; messageId: string; messageType: string}};
/** Function to be triggered on click */
trigger: Function;
/** Notification title */
title: string;
/** Timeout for notification */
timeout: number;
}
/**
* Notification repository to trigger browser and audio notifications.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/notification
* @see http://www.w3.org/TR/notifications
*/
export class NotificationRepository {
private contentViewModelState: ContentViewModelState;
private readonly callingRepository: CallingRepository;
private readonly conversationRepository: ConversationRepository;
private readonly logger: Logger;
private readonly notifications: any[];
private readonly notificationsPreference: ko.Observable<NotificationPreference>;
private readonly permissionRepository: PermissionRepository;
private readonly permissionState: ko.Observable<string>;
private readonly selfUser: ko.Observable<User>;
private readonly userRepository: UserRepository;
// tslint:disable-next-line:typedef
static get CONFIG() {
return {
BODY_LENGTH: 80,
ICON_URL: '/image/logo/notification.png',
TIMEOUT: TIME_IN_MILLIS.SECOND * 5,
TITLE_LENGTH: 38,
};
}
static get EVENTS_TO_NOTIFY(): SuperType[] {
return [SuperType.CALL, SuperType.CONTENT, SuperType.MEMBER, SuperType.PING, SuperType.REACTION, SuperType.SYSTEM];
}
/**
* Construct a new Notification Repository.
* @param callingRepository Repository for all call interactions
* @param conversationRepository Repository for all conversation interactions
* @param permissionRepository Repository for all permission interactions
* @param userRepository Repository for users
*/
constructor(
callingRepository: CallingRepository,
conversationRepository: ConversationRepository,
permissionRepository: PermissionRepository,
userRepository: UserRepository,
) {
this.callingRepository = callingRepository;
this.conversationRepository = conversationRepository;
this.permissionRepository = permissionRepository;
this.userRepository = userRepository;
this.contentViewModelState = {multitasking: {isMinimized: () => false}, state: () => false};
this.logger = getLogger('NotificationRepository');
this.notifications = [];
this.subscribeToEvents();
this.notificationsPreference = ko.observable(NotificationPreference.ON);
this.notificationsPreference.subscribe(notificationsPreference => {
const preferenceIsNone = notificationsPreference === NotificationPreference.NONE;
if (!preferenceIsNone) {
this.checkPermission();
}
});
this.permissionState = this.permissionRepository.permissionState[PermissionType.NOTIFICATIONS];
this.selfUser = this.userRepository.self;
}
__test__assignEnvironment(data: any): void {
Object.assign(Environment, data);
}
setContentViewModelStates(state: () => string, multitasking: {isMinimized: () => false}): void {
this.contentViewModelState = {multitasking, state};
}
subscribeToEvents(): void {
amplify.subscribe(WebAppEvents.NOTIFICATION.NOTIFY, this.notify.bind(this));
amplify.subscribe(WebAppEvents.NOTIFICATION.PERMISSION_STATE, this.updatePermissionState.bind(this));
amplify.subscribe(WebAppEvents.NOTIFICATION.REMOVE_READ, this.removeReadNotifications.bind(this));
amplify.subscribe(WebAppEvents.PROPERTIES.UPDATED, this.updatedProperties.bind(this));
amplify.subscribe(WebAppEvents.PROPERTIES.UPDATE.NOTIFICATIONS, this.updatedNotificationsProperty.bind(this));
}
/**
* Check for browser permission if we have not yet asked.
* @returns Promise that resolves with the permission state
*/
async checkPermission(): Promise<boolean | void> {
const isPermitted = await this.checkPermissionState();
if (typeof isPermitted === 'boolean') {
return isPermitted;
}
if (!Environment.browser.supports.notifications) {
return this.updatePermissionState(PermissionState.UNSUPPORTED);
}
if (Environment.browser.supports.permissions) {
const notificationState = this.permissionRepository.getPermissionState(PermissionType.NOTIFICATIONS);
const shouldRequestPermission = notificationState === PermissionStatusState.PROMPT;
return shouldRequestPermission ? this._requestPermission() : this.checkPermissionState();
}
const currentPermission = window.Notification.permission;
const shouldRequestPermission = currentPermission === PermissionState.DEFAULT;
return shouldRequestPermission ? this._requestPermission() : this.updatePermissionState(currentPermission);
}
/**
* Close all notifications.
*/
clearNotifications(): void {
this.notifications.forEach(notification => {
notification.close();
if (notification.data) {
const {conversationId, messageId} = notification.data;
this.logger.info(`Notification for '${messageId}' in '${conversationId}' closed on unload.`, notification);
}
});
}
/**
* Display browser notification and play sound notification.
* @returns Resolves when notification has been handled
*/
notify(
messageEntity: ContentMessage,
connectionEntity: ConnectionEntity,
conversationEntity: Conversation,
): Promise<void> {
const isUserAway = this.selfUser().availability() === Availability.Type.AWAY;
if (isUserAway) {
return Promise.resolve();
}
const isUserBusy = this.selfUser().availability() === Availability.Type.BUSY;
const isSelfMentionOrReply = messageEntity.is_content() && messageEntity.isUserTargeted(this.selfUser().id);
const isCallMessage = messageEntity.super_type === SuperType.CALL;
if (isUserBusy && !isSelfMentionOrReply && !isCallMessage) {
return Promise.resolve();
}
const notifyInConversation = conversationEntity
? NotificationRepository.shouldNotifyInConversation(conversationEntity, messageEntity, this.selfUser().id)
: true;
if (notifyInConversation) {
this.notifySound(messageEntity);
return this.notifyBanner(messageEntity, connectionEntity, conversationEntity);
}
return Promise.resolve();
}
// Remove notifications from the queue that are no longer unread
removeReadNotifications(): void {
this.notifications.forEach(notification => {
const {conversationId, messageId, messageType} = notification.data || {};
if (messageId) {
this.conversationRepository.is_message_read(conversationId, messageId).then(isRead => {
if (isRead) {
notification.close();
const messageInfo = messageId
? `message '${messageId}' of type '${messageType}'`
: `'${messageType}' message`;
this.logger.info(`Removed read notification for ${messageInfo} in '${conversationId}'.`);
}
});
}
});
}
updatedProperties(properties: any): void {
const notificationPreference = properties.settings.notifications;
return this.notificationsPreference(notificationPreference);
}
updatedNotificationsProperty(notificationPreference: NotificationPreference): void {
return this.notificationsPreference(notificationPreference);
}
/**
* Set the permission state.
* @param permissionState State of browser permission
* @returns Resolves with `true` if notifications are enabled
*/
updatePermissionState(permissionState: string): Promise<boolean> {
this.permissionState(permissionState);
return this.checkPermissionState();
}
/**
* Creates the notification body for calls.
*/
private createBodyCall(messageEntity: CallMessage): string | void {
if (messageEntity.is_activation()) {
return t('notificationVoiceChannelActivate');
}
if (messageEntity.is_deactivation() && messageEntity.finished_reason === TERMINATION_REASON.MISSED) {
return t('notificationVoiceChannelDeactivate');
}
}
/**
* Creates the notification body for text messages and pictures.
*
* @param messageEntity Normal message entity
* @returns Notification message body
*/
private createBodyContent(messageEntity: ContentMessage): string | void {
if (messageEntity.has_asset_text()) {
for (const assetEntity of messageEntity.assets()) {
if (assetEntity.is_text()) {
let notificationText;
if (assetEntity.isUserMentioned(this.selfUser().id)) {
notificationText = t('notificationMention', assetEntity.text, {}, true);
} else if (messageEntity.isUserQuoted(this.selfUser().id)) {
notificationText = t('notificationReply', assetEntity.text, {}, true);
} else {
notificationText = assetEntity.text;
}
return truncate(notificationText, NotificationRepository.CONFIG.BODY_LENGTH);
}
}
}
if (messageEntity.has_asset_image()) {
return t('notificationAssetAdd');
}
if (messageEntity.has_asset_location()) {
return t('notificationSharedLocation');
}
if (messageEntity.has_asset()) {
const assetEntity = messageEntity.get_first_asset();
if (assetEntity.is_audio()) {
return t('notificationSharedAudio');
}
if (assetEntity.is_video()) {
return t('notificationSharedVideo');
}
if (assetEntity.is_file()) {
return t('notificationSharedFile');
}
}
}
/**
* Creates the notification body for people being added to a group conversation.
*
* @param messageEntity Member message entity
* @param Notification message body
*/
private createBodyMemberJoin(messageEntity: MemberMessage): string {
const updatedOneParticipant = messageEntity.userEntities().length === 1;
if (updatedOneParticipant) {
const [otherUserEntity] = messageEntity.userEntities();
const declension = Declension.ACCUSATIVE;
const nameOfJoinedUser = getFirstName(otherUserEntity, declension);
const senderJoined = messageEntity.user().id === otherUserEntity.id;
if (senderJoined) {
return t('notificationMemberJoinSelf', nameOfJoinedUser, {}, true);
}
const substitutions = {user1: messageEntity.user().first_name(), user2: nameOfJoinedUser};
return t('notificationMemberJoinOne', substitutions, {}, true);
}
const substitutions = {number: messageEntity.userIds().length.toString(), user: messageEntity.user().first_name()};
return t('notificationMemberJoinMany', substitutions, {}, true);
}
/**
* Creates the notification body for people being removed from or leaving a group conversation.
* @note Only show a notification if self user was removed
*
* @param messageEntity Member message entity
* @param Notification message body
*/
private createBodyMemberLeave(messageEntity: MemberMessage): string | void {
const updatedOneParticipant = messageEntity.userEntities().length === 1;
if (updatedOneParticipant && !messageEntity.remoteUserEntities().length) {
return t('notificationMemberLeaveRemovedYou', messageEntity.user().first_name(), {}, true);
}
}
/**
* Selects the type of system message that the notification body needs to be created for.
*
* @param messageEntity Member message entity
* @param conversationEntity Conversation entity
*/
private createBodyMemberUpdate(messageEntity?: MemberMessage, conversationEntity?: Conversation): string | void {
const isGroup = conversationEntity && conversationEntity.isGroup();
switch (messageEntity.memberMessageType) {
case SystemMessageType.NORMAL:
if (isGroup) {
if (messageEntity.isMemberJoin()) {
return this.createBodyMemberJoin(messageEntity);
}
if (messageEntity.isMemberLeave()) {
return this.createBodyMemberLeave(messageEntity);
}
}
break;
case SystemMessageType.CONNECTION_ACCEPTED:
return t('notificationConnectionAccepted');
case SystemMessageType.CONNECTION_CONNECTED:
return t('notificationConnectionConnected');
case SystemMessageType.CONNECTION_REQUEST:
return t('notificationConnectionRequest');
case SystemMessageType.CONVERSATION_CREATE:
return t('notificationConversationCreate', messageEntity.user().first_name(), {}, true);
}
}
/**
* Creates the notification body for obfuscated messages.
*
* @param messageEntity Message to obfuscate body for
* @returns Notification message body
*/
private createBodyObfuscated(messageEntity: ContentMessage): string {
if (messageEntity.is_content()) {
const isSelfMentioned = messageEntity.isUserMentioned(this.selfUser().id);
if (isSelfMentioned) {
return t('notificationObfuscatedMention');
}
const isSelfQuoted = messageEntity.isUserQuoted(this.selfUser().id);
if (isSelfQuoted) {
return t('notificationObfuscatedReply');
}
}
return t('notificationObfuscated');
}
/**
* Creates the notification body for ping.
* @returns Notification message body
*/
private createBodyPing(): string {
return t('notificationPing');
}
/**
* Creates the notification body for reaction.
* @param messageEntity Fake reaction message entity
* @returns Notification message body
*/
private createBodyReaction(messageEntity: any): string {
return t('notificationReaction', messageEntity.reaction);
}
/**
* Selects the type of system message that the notification body needs to be created for.
*
* @param messageEntity Member message entity
* @returns Notification message body
*/
private createBodySystem(messageEntity: Message): string | void {
const createBodyMessageTimerUpdate = () => {
const messageTimer = ConversationEphemeralHandler.validateTimer(
(messageEntity as MessageTimerUpdateMessage).message_timer,
);
if (messageTimer) {
const timeString = formatDuration(messageTimer).text;
const substitutions = {time: timeString, user: messageEntity.user().first_name()};
return t('notificationConversationMessageTimerUpdate', substitutions, {}, true);
}
return t('notificationConversationMessageTimerReset', messageEntity.user().first_name(), {}, true);
};
const createBodyRename = () => {
const substitutions = {name: (messageEntity as RenameMessage).name, user: messageEntity.user().first_name()};
return t('notificationConversationRename', substitutions, {}, true);
};
switch ((messageEntity as SystemMessage).system_message_type) {
case SystemMessageType.CONVERSATION_RENAME: {
return createBodyRename();
}
case SystemMessageType.CONVERSATION_MESSAGE_TIMER_UPDATE: {
return createBodyMessageTimerUpdate();
}
case SystemMessageType.CONVERSATION_DELETE: {
return (messageEntity as DeleteConversationMessage).caption;
}
}
}
/**
* Create notification content.
*
* @returns Resolves with the notification content
*/
private createNotificationContent(
messageEntity: ContentMessage,
connectionEntity: ConnectionEntity,
conversationEntity: Conversation,
): Promise<any> {
const body = this.createOptionsBody(messageEntity, conversationEntity);
if (!body) {
return Promise.resolve();
}
const shouldObfuscateSender = this.shouldObfuscateNotificationSender(messageEntity);
return this.createOptionsIcon(shouldObfuscateSender, messageEntity.user()).then(iconUrl => {
const shouldObfuscateMessage = this.shouldObfuscateNotificationMessage(messageEntity);
return {
options: {
body: shouldObfuscateMessage ? this.createBodyObfuscated(messageEntity) : body,
data: this.createOptionsData(messageEntity, connectionEntity, conversationEntity),
icon: iconUrl,
silent: true, // @note When Firefox supports this we can remove the fix for WEBAPP-731
tag: this.createOptionsTag(connectionEntity, conversationEntity),
},
timeout: NotificationRepository.CONFIG.TIMEOUT,
title: shouldObfuscateSender
? this.createTitleObfuscated()
: this.createTitle(messageEntity, conversationEntity),
trigger: this.createTrigger(messageEntity, connectionEntity, conversationEntity),
};
});
}
/**
* Selects the type of message that the notification body needs to be created for.
*
* @returns The notification message body
*/
private createOptionsBody(
messageEntity: Message | CallMessage | ContentMessage | MemberMessage,
conversationEntity: Conversation,
): string | void {
switch (messageEntity.super_type) {
case SuperType.CALL:
return this.createBodyCall(messageEntity as CallMessage);
case SuperType.CONTENT:
return this.createBodyContent(messageEntity as ContentMessage);
case SuperType.MEMBER:
return this.createBodyMemberUpdate(messageEntity as MemberMessage, conversationEntity);
case SuperType.PING:
return this.createBodyPing();
case SuperType.REACTION:
return this.createBodyReaction(messageEntity);
case SuperType.SYSTEM:
return this.createBodySystem(messageEntity as MemberMessage);
}
}
/**
* Creates the notification data to help check its content.
*
* @returns Notification message data
*/
private createOptionsData(
messageEntity: Message,
connectionEntity: ConnectionEntity,
conversationEntity: Conversation,
): {conversationId: string; messageId: string | undefined; messageType: string} {
const {id: messageId, type: messageType} = messageEntity;
return {
conversationId: this.getConversationId(connectionEntity, conversationEntity),
messageId: messageId === '0' ? undefined : messageId,
messageType: messageType,
};
}
/**
* Creates the notification icon.
*
* @param shouldObfuscateSender Sender visible in notification
* @param userEntity Sender of message
* @returns Resolves with the icon URL
*/
private createOptionsIcon(shouldObfuscateSender: boolean, userEntity: User): Promise<string> {
const canShowUserImage = userEntity.previewPictureResource() && !shouldObfuscateSender;
if (canShowUserImage) {
return userEntity
.previewPictureResource()
.generateUrl()
.catch((error: Error) => {
if (error instanceof ValidationUtilError) {
this.logger.error(`Failed to validate an asset URL: ${error.message}`);
}
return '';
});
}
const isMacOsWrapper = Environment.electron && Environment.os.mac;
return Promise.resolve(isMacOsWrapper ? '' : NotificationRepository.CONFIG.ICON_URL);
}
/**
* Creates the notification tag.
*
* @param connectionEntity Connection entity
* @param conversationEntity Conversation entity
*/
private createOptionsTag(connectionEntity?: ConnectionEntity, conversationEntity?: Conversation): string {
return this.getConversationId(connectionEntity, conversationEntity);
}
/**
* Creates the notification title.
*
* @param Notification message title
*/
private createTitle(messageEntity: Message, conversationEntity?: Conversation): string {
const conversationName = conversationEntity && conversationEntity.display_name();
const userEntity = messageEntity.user();
let title;
if (conversationName) {
title = conversationEntity.isGroup()
? t('notificationTitleGroup', {conversation: conversationName, user: userEntity.first_name()}, {}, true)
: conversationName;
}
return truncate(title || userEntity.name(), NotificationRepository.CONFIG.TITLE_LENGTH, false);
}
/**
* Create obfuscated title.
*
* @returns Obfuscated notification message title
*/
private createTitleObfuscated(): string {
const obfuscatedTitle = t('notificationObfuscatedTitle');
return truncate(obfuscatedTitle, NotificationRepository.CONFIG.TITLE_LENGTH, false);
}
/**
* Creates the notification trigger.
*
* @returns Function to be called when notification is clicked
*/
private createTrigger(
messageEntity: ContentMessage | MemberMessage,
connectionEntity?: ConnectionEntity,
conversationEntity?: Conversation,
): () => void {
const conversationId = this.getConversationId(connectionEntity, conversationEntity);
const containsSelfMention =
messageEntity.is_content() && (messageEntity as ContentMessage).isUserMentioned(this.selfUser().id);
if (containsSelfMention) {
const showOptions = {exposeMessage: messageEntity, openFirstSelfMention: true};
return () => amplify.publish(WebAppEvents.CONVERSATION.SHOW, conversationEntity, showOptions);
}
const isConnectionRequest = messageEntity.is_member() && (messageEntity as MemberMessage).isConnectionRequest();
if (isConnectionRequest) {
return () => {
amplify.publish(WebAppEvents.CONTENT.SWITCH, ContentViewModel.STATE.CONNECTION_REQUESTS);
};
}
return () => amplify.publish(WebAppEvents.CONVERSATION.SHOW, conversationEntity || conversationId);
}
/**
* Retrieve conversation ID from either conversation or connection.
*
* @param connectionEntity Connection entity
* @param conversationEntity Conversation entity
* @returns ID of conversation
*/
private getConversationId(connectionEntity?: ConnectionEntity, conversationEntity?: Conversation): string {
if (connectionEntity) {
return connectionEntity.conversationId;
}
return conversationEntity && conversationEntity.id;
}
/**
* Evaluates the current permission state.
* @returns Resolves with `true` if notifications are permitted
*/
private checkPermissionState(): Promise<boolean | undefined> {
switch (this.permissionState()) {
case PermissionStatusState.GRANTED: {
return Promise.resolve(true);
}
case PermissionState.IGNORED:
case PermissionState.UNSUPPORTED:
case PermissionStatusState.DENIED: {
return Promise.resolve(false);
}
default: {
return Promise.resolve(undefined);
}
}
}
/**
* Creates the browser notification and sends it.
*
* @see https://developer.mozilla.org/en/docs/Web/API/notification#Parameters
* @returns Resolves when notification was handled
*/
private async notifyBanner(
messageEntity: ContentMessage,
connectionEntity: ConnectionEntity,
conversationEntity: Conversation,
): Promise<void> {
if (!this.shouldShowNotification(messageEntity, conversationEntity)) {
return;
}
const notificationContent = await this.createNotificationContent(
messageEntity,
connectionEntity,
conversationEntity,
);
if (notificationContent) {
const isPermitted = await this.checkPermission();
if (isPermitted) {
this.showNotification(notificationContent);
}
}
}
/**
* Plays the sound from the audio repository.
*
* @param messageEntity Message entity
* @param No return value
*/
private notifySound(messageEntity: Message): void {
const muteSound = !document.hasFocus() && Environment.browser.firefox && Environment.os.mac;
const isFromSelf = messageEntity.user().is_me;
const shouldPlaySound = !muteSound && !isFromSelf;
if (shouldPlaySound) {
switch (messageEntity.super_type) {
case SuperType.CONTENT: {
amplify.publish(WebAppEvents.AUDIO.PLAY, AudioType.NEW_MESSAGE);
break;
}
case SuperType.PING: {
amplify.publish(WebAppEvents.AUDIO.PLAY, AudioType.INCOMING_PING);
break;
}
}
}
}
// Request browser permission for notifications.
private async _requestPermission(): Promise<void> {
amplify.publish(WebAppEvents.WARNING.SHOW, WarningsViewModel.TYPE.REQUEST_NOTIFICATION);
// Note: The callback will be only triggered in Chrome.
// If you ignore a permission request on Firefox, then the callback will not be triggered.
if (window.Notification.requestPermission) {
const permissionState = await window.Notification.requestPermission();
amplify.publish(WebAppEvents.WARNING.DISMISS, WarningsViewModel.TYPE.REQUEST_NOTIFICATION);
await this.updatePermissionState(permissionState);
}
}
/**
* Should message in a notification be obfuscated?
*
* @param messageEntity Message entity
* @param Obfuscate message in notification
*/
private shouldObfuscateNotificationMessage(messageEntity: Message): boolean {
const preferencesToObfuscateMessage = [NotificationPreference.OBFUSCATE, NotificationPreference.OBFUSCATE_MESSAGE];
return preferencesToObfuscateMessage.includes(this.notificationsPreference()) || messageEntity.is_ephemeral();
}
/**
* Should sender in a notification be obfuscated?
*
* @param messageEntity Message entity
* @returns Obfuscate sender in notification
*/
private shouldObfuscateNotificationSender(messageEntity: Message): boolean {
const isSetToObfuscate = this.notificationsPreference() === NotificationPreference.OBFUSCATE;
return isSetToObfuscate || messageEntity.is_ephemeral();
}
/**
* @param messageEntity Message entity
* @param conversationEntity Conversation entity
* @returns Returns `true` if the notification should be shown, `false` otherwise
*/
private shouldShowNotification(messageEntity: Message, conversationEntity?: Conversation): boolean {
const inActiveConversation = conversationEntity
? this.conversationRepository.is_active_conversation(conversationEntity)
: false;
const inConversationView = this.contentViewModelState.state() === ContentViewModel.STATE.CONVERSATION;
const inMaximizedCall =
this.callingRepository.joinedCall() && !this.contentViewModelState.multitasking.isMinimized();
const activeConversation = document.hasFocus() && inConversationView && inActiveConversation && !inMaximizedCall;
const messageFromSelf = messageEntity.user().is_me;
const permissionDenied = this.permissionState() === PermissionStatusState.DENIED;
const preferenceIsNone = this.notificationsPreference() === NotificationPreference.NONE;
const supportsNotification = Environment.browser.supports.notifications;
const hideNotification =
activeConversation || messageFromSelf || permissionDenied || preferenceIsNone || !supportsNotification;
return !hideNotification;
}
/**
* Sending the notification.
*
* @param notificationContent Content of notification
* @param notificationContent.title - Title of notification
* @param notificationContent.options - Notification options
* @param notificationContent.trigger - Function to be called on notificiation click
* @param notificationContent.timeout - Timeout after which notification is closed
* @returns No return value
*/
private showNotification(notificationContent: NotificationContent): void {
amplify.publish(WebAppEvents.NOTIFICATION.SHOW, notificationContent);
this.showNotificationInBrowser(notificationContent);
}
/**
* Sending the browser notification.
*
* @param notificationContent Content of notification
* @param notificationContent.title - Notification title
* @param notificationContent.options - Notification options
* @param notificationContent.trigger - Function to be triggered on click [Function] trigger
* @param notificationContent.timeout - Timeout for notification
* @param No return value
*/
private showNotificationInBrowser(notificationContent: NotificationContent): void {
/*
* @note Notification.data is only supported on Chrome
* @see https://developer.mozilla.org/en-US/docs/Web/API/Notification/data
*/
this.removeReadNotifications();
const notification = new window.Notification(notificationContent.title, notificationContent.options);
const {conversationId, messageId, messageType} = notificationContent.options.data;
let timeoutTriggerId: number;
const messageInfo = messageId ? `message '${messageId}' of type '${messageType}'` : `'${messageType}' message`;
notification.onclick = () => {
amplify.publish(WebAppEvents.NOTIFICATION.CLICK);
window.focus();
this.contentViewModelState.multitasking.isMinimized(true);
notificationContent.trigger();
this.logger.info(`Notification for ${messageInfo} in '${conversationId}' closed by click.`);
notification.close();
};
notification.onclose = () => {
window.clearTimeout(timeoutTriggerId);
this.notifications.splice(this.notifications.indexOf(notification), 1);
this.logger.info(`Removed notification for ${messageInfo} in '${conversationId}' locally.`);
};
notification.onerror = error => {
this.logger.error(`Notification for ${messageInfo} in '${conversationId}' closed by error.`, error);
notification.close();
};
notification.onshow = () => {
timeoutTriggerId = window.setTimeout(() => {
this.logger.info(`Notification for ${messageInfo} in '${conversationId}' closed by timeout.`);
notification.close();
}, notificationContent.timeout);
};
this.notifications.push(notification);
this.logger.info(`Added notification for ${messageInfo} in '${conversationId}' to queue.`);
}
/**
* Check whether conversation is in state to trigger notitication.
*
* @param conversationEntity Conversation to notify in
* @param messageEntity The message to filter from
* @param userId The user id to check mentions for
* @returns `true` if the conversation should show notification
*/
static shouldNotifyInConversation(
conversationEntity: Conversation,
messageEntity: ContentMessage,
userId: string,
): boolean {
if (conversationEntity.showNotificationsNothing()) {
return false;
}
const isEventTypeToNotify = NotificationRepository.EVENTS_TO_NOTIFY.includes(messageEntity.super_type);
const isEventToNotify = isEventTypeToNotify && !messageEntity.isEdited() && !messageEntity.isLinkPreview();
if (conversationEntity.showNotificationsEverything()) {
return isEventToNotify;
}
const isSelfMentionOrReply = messageEntity.is_content() && messageEntity.isUserTargeted(userId);
const isCallMessage = messageEntity.super_type === SuperType.CALL;
return isEventToNotify && (isCallMessage || isSelfMentionOrReply);
}
}