/
background.ts
3873 lines (3352 loc) · 119 KB
/
background.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
// Copyright 2020-2022 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import { webFrame } from 'electron';
import { isNumber } from 'lodash';
import { bindActionCreators } from 'redux';
import { render } from 'react-dom';
import { batch as batchDispatch } from 'react-redux';
import PQueue from 'p-queue';
import MessageReceiver from './textsecure/MessageReceiver';
import type {
SessionResetsType,
ProcessedDataMessage,
} from './textsecure/Types.d';
import { HTTPError } from './textsecure/Errors';
import createTaskWithTimeout, {
suspendTasksWithTimeout,
resumeTasksWithTimeout,
reportLongRunningTasks,
} from './textsecure/TaskWithTimeout';
import type {
MessageAttributesType,
ConversationAttributesType,
ReactionAttributesType,
} from './model-types.d';
import * as Bytes from './Bytes';
import * as Timers from './Timers';
import * as indexedDb from './indexeddb';
import type { MenuOptionsType } from './types/menu';
import type { Receipt } from './types/Receipt';
import { SocketStatus } from './types/SocketStatus';
import { DEFAULT_CONVERSATION_COLOR } from './types/Colors';
import { ThemeType } from './types/Util';
import { ChallengeHandler } from './challenge';
import * as durations from './util/durations';
import { explodePromise } from './util/explodePromise';
import { isWindowDragElement } from './util/isWindowDragElement';
import { assertDev, strictAssert } from './util/assert';
import { normalizeUuid } from './util/normalizeUuid';
import { filter } from './util/iterables';
import { isNotNil } from './util/isNotNil';
import { setAppLoadingScreenMessage } from './setAppLoadingScreenMessage';
import { IdleDetector } from './IdleDetector';
import { expiringMessagesDeletionService } from './services/expiringMessagesDeletion';
import { tapToViewMessagesDeletionService } from './services/tapToViewMessagesDeletionService';
import { getStoriesForRedux, loadStories } from './services/storyLoader';
import {
getDistributionListsForRedux,
loadDistributionLists,
} from './services/distributionListLoader';
import { senderCertificateService } from './services/senderCertificate';
import { GROUP_CREDENTIALS_KEY } from './services/groupCredentialFetcher';
import * as KeyboardLayout from './services/keyboardLayout';
import * as StorageService from './services/storage';
import { RoutineProfileRefresher } from './routineProfileRefresh';
import { isMoreRecentThan, isOlderThan, toDayMillis } from './util/timestamp';
import { isValidReactionEmoji } from './reactions/isValidReactionEmoji';
import type { ConversationModel } from './models/conversations';
import { getContact, isIncoming } from './messages/helpers';
import { migrateMessageData } from './messages/migrateMessageData';
import { createBatcher } from './util/batcher';
import { updateConversationsWithUuidLookup } from './updateConversationsWithUuidLookup';
import { initializeAllJobQueues } from './jobs/initializeAllJobQueues';
import { removeStorageKeyJobQueue } from './jobs/removeStorageKeyJobQueue';
import { ourProfileKeyService } from './services/ourProfileKey';
import { notificationService } from './services/notifications';
import { areWeASubscriberService } from './services/areWeASubscriber';
import { onContactSync, setIsInitialSync } from './services/contactSync';
import { startTimeTravelDetector } from './util/startTimeTravelDetector';
import { shouldRespondWithProfileKey } from './util/shouldRespondWithProfileKey';
import { LatestQueue } from './util/LatestQueue';
import { parseIntOrThrow } from './util/parseIntOrThrow';
import { getProfile } from './util/getProfile';
import type {
ConfigurationEvent,
DecryptionErrorEvent,
DeliveryEvent,
EnvelopeEvent,
ErrorEvent,
FetchLatestEvent,
GroupEvent,
KeysEvent,
MessageEvent,
MessageEventData,
MessageRequestResponseEvent,
ProfileKeyUpdateEvent,
ReadEvent,
ReadSyncEvent,
RetryRequestEvent,
SentEvent,
SentEventData,
StickerPackEvent,
TypingEvent,
ViewEvent,
ViewOnceOpenSyncEvent,
ViewSyncEvent,
} from './textsecure/messageReceiverEvents';
import type { WebAPIType } from './textsecure/WebAPI';
import * as KeyChangeListener from './textsecure/KeyChangeListener';
import { RotateSignedPreKeyListener } from './textsecure/RotateSignedPreKeyListener';
import { isDirectConversation, isGroupV2 } from './util/whatTypeOfConversation';
import { BackOff, FIBONACCI_TIMEOUTS } from './util/BackOff';
import { AppViewType } from './state/ducks/app';
import type { BadgesStateType } from './state/ducks/badges';
import { badgeImageFileDownloader } from './badges/badgeImageFileDownloader';
import { actionCreators } from './state/actions';
import { Deletes } from './messageModifiers/Deletes';
import {
MessageReceipts,
MessageReceiptType,
} from './messageModifiers/MessageReceipts';
import { MessageRequests } from './messageModifiers/MessageRequests';
import { Reactions } from './messageModifiers/Reactions';
import { ReadSyncs } from './messageModifiers/ReadSyncs';
import { ViewSyncs } from './messageModifiers/ViewSyncs';
import { ViewOnceOpenSyncs } from './messageModifiers/ViewOnceOpenSyncs';
import type { DeleteAttributesType } from './messageModifiers/Deletes';
import type { MessageReceiptAttributesType } from './messageModifiers/MessageReceipts';
import type { MessageRequestAttributesType } from './messageModifiers/MessageRequests';
import type { ReadSyncAttributesType } from './messageModifiers/ReadSyncs';
import type { ViewSyncAttributesType } from './messageModifiers/ViewSyncs';
import type { ViewOnceOpenSyncAttributesType } from './messageModifiers/ViewOnceOpenSyncs';
import { ReadStatus } from './messages/MessageReadStatus';
import type { SendStateByConversationId } from './messages/MessageSendState';
import { SendStatus } from './messages/MessageSendState';
import * as AttachmentDownloads from './messageModifiers/AttachmentDownloads';
import * as Conversation from './types/Conversation';
import * as Stickers from './types/Stickers';
import * as Errors from './types/errors';
import { SignalService as Proto } from './protobuf';
import { onRetryRequest, onDecryptionError } from './util/handleRetry';
import { themeChanged } from './shims/themeChanged';
import { createIPCEvents } from './util/createIPCEvents';
import { RemoveAllConfiguration } from './types/RemoveAllConfiguration';
import { isValidUuid, UUIDKind, UUID } from './types/UUID';
import * as log from './logging/log';
import { loadRecentEmojis } from './util/loadRecentEmojis';
import { deleteAllLogs } from './util/deleteAllLogs';
import { ReactWrapperView } from './views/ReactWrapperView';
import { ToastCaptchaFailed } from './components/ToastCaptchaFailed';
import { ToastCaptchaSolved } from './components/ToastCaptchaSolved';
import { ToastConversationArchived } from './components/ToastConversationArchived';
import { ToastConversationUnarchived } from './components/ToastConversationUnarchived';
import { showToast } from './util/showToast';
import { startInteractionMode } from './windows/startInteractionMode';
import type { MainWindowStatsType } from './windows/context';
import { deliveryReceiptsJobQueue } from './jobs/deliveryReceiptsJobQueue';
import { updateOurUsernameAndPni } from './util/updateOurUsernameAndPni';
import { ReactionSource } from './reactions/ReactionSource';
import { singleProtoJobQueue } from './jobs/singleProtoJobQueue';
import { getInitialState } from './state/getInitialState';
import { conversationJobQueue } from './jobs/conversationJobQueue';
import { SeenStatus } from './MessageSeenStatus';
import MessageSender from './textsecure/SendMessage';
import type AccountManager from './textsecure/AccountManager';
import { onStoryRecipientUpdate } from './util/onStoryRecipientUpdate';
import { StoryViewModeType, StoryViewTargetType } from './types/Stories';
import { downloadOnboardingStory } from './util/downloadOnboardingStory';
const MAX_ATTACHMENT_DOWNLOAD_AGE = 3600 * 72 * 1000;
export function isOverHourIntoPast(timestamp: number): boolean {
const HOUR = 1000 * 60 * 60;
return isNumber(timestamp) && isOlderThan(timestamp, HOUR);
}
export async function cleanupSessionResets(): Promise<void> {
const sessionResets = window.storage.get(
'sessionResets',
<SessionResetsType>{}
);
const keys = Object.keys(sessionResets);
keys.forEach(key => {
const timestamp = sessionResets[key];
if (!timestamp || isOverHourIntoPast(timestamp)) {
delete sessionResets[key];
}
});
await window.storage.put('sessionResets', sessionResets);
}
export async function startApp(): Promise<void> {
window.textsecure.storage.protocol = new window.SignalProtocolStore();
if (window.initialTheme === ThemeType.light) {
document.body.classList.add('light-theme');
}
if (window.initialTheme === ThemeType.dark) {
document.body.classList.add('dark-theme');
}
const idleDetector = new IdleDetector();
await KeyboardLayout.initialize();
window.Whisper.events = window._.clone(window.Backbone.Events);
window.Signal.Util.MessageController.install();
window.Signal.conversationControllerStart();
window.startupProcessingQueue = new window.Signal.Util.StartupQueue();
notificationService.initialize({
i18n: window.i18n,
storage: window.storage,
});
window.attachmentDownloadQueue = [];
await window.Signal.Util.initializeMessageCounter();
let initialBadgesState: BadgesStateType = { byId: {} };
async function loadInitialBadgesState(): Promise<void> {
initialBadgesState = {
byId: window.Signal.Util.makeLookup(
await window.Signal.Data.getAllBadges(),
'id'
),
};
}
// Initialize WebAPI as early as possible
let server: WebAPIType | undefined;
let messageReceiver: MessageReceiver | undefined;
let challengeHandler: ChallengeHandler | undefined;
let routineProfileRefresher: RoutineProfileRefresher | undefined;
window.storage.onready(() => {
server = window.WebAPI.connect({
...window.textsecure.storage.user.getWebAPICredentials(),
hasStoriesDisabled: window.storage.get('hasStoriesDisabled', false),
});
window.textsecure.server = server;
window.textsecure.messaging = new window.textsecure.MessageSender(server);
initializeAllJobQueues({
server,
});
challengeHandler = new ChallengeHandler({
storage: window.storage,
startQueue(conversationId: string) {
conversationJobQueue.resolveVerificationWaiter(conversationId);
},
requestChallenge(request) {
if (window.CI) {
window.CI.handleEvent('challenge', request);
return;
}
window.sendChallengeRequest(request);
},
async sendChallengeResponse(data) {
const { messaging } = window.textsecure;
if (!messaging) {
throw new Error('sendChallengeResponse: messaging is not available!');
}
await messaging.sendChallengeResponse(data);
},
onChallengeFailed() {
// TODO: DESKTOP-1530
// Display humanized `retryAfter`
showToast(ToastCaptchaFailed);
},
onChallengeSolved() {
showToast(ToastCaptchaSolved);
},
setChallengeStatus(challengeStatus) {
window.reduxActions.network.setChallengeStatus(challengeStatus);
},
});
window.Whisper.events.on('challengeResponse', response => {
if (!challengeHandler) {
throw new Error('Expected challenge handler to be there');
}
challengeHandler.onResponse(response);
});
window.Signal.challengeHandler = challengeHandler;
log.info('Initializing MessageReceiver');
messageReceiver = new MessageReceiver({
server,
storage: window.storage,
serverTrustRoot: window.getServerTrustRoot(),
});
function queuedEventListener<E extends Event>(
handler: (event: E) => Promise<void> | void,
track = true
): (event: E) => void {
return (event: E): void => {
eventHandlerQueue.add(
createTaskWithTimeout(async () => {
try {
await handler(event);
} finally {
// message/sent: Message.handleDataMessage has its own queue and will
// trigger this event itself when complete.
// error: Error processing (below) also has its own queue and self-trigger.
if (track) {
window.Whisper.events.trigger('incrementProgress');
}
}
}, `queuedEventListener(${event.type}, ${event.timeStamp})`)
);
};
}
messageReceiver.addEventListener(
'envelope',
queuedEventListener(onEnvelopeReceived, false)
);
messageReceiver.addEventListener(
'message',
queuedEventListener(onMessageReceived, false)
);
messageReceiver.addEventListener(
'delivery',
queuedEventListener(onDeliveryReceipt)
);
messageReceiver.addEventListener(
'contactSync',
queuedEventListener(onContactSync)
);
messageReceiver.addEventListener(
'group',
queuedEventListener(onGroupReceived)
);
messageReceiver.addEventListener(
'groupSync',
queuedEventListener(onGroupSyncComplete)
);
messageReceiver.addEventListener(
'sent',
queuedEventListener(onSentMessage, false)
);
messageReceiver.addEventListener(
'readSync',
queuedEventListener(onReadSync)
);
messageReceiver.addEventListener(
'viewSync',
queuedEventListener(onViewSync)
);
messageReceiver.addEventListener(
'read',
queuedEventListener(onReadReceipt)
);
messageReceiver.addEventListener(
'view',
queuedEventListener(onViewReceipt)
);
messageReceiver.addEventListener(
'error',
queuedEventListener(onError, false)
);
messageReceiver.addEventListener(
'decryption-error',
queuedEventListener((event: DecryptionErrorEvent): void => {
onDecryptionErrorQueue.add(() => onDecryptionError(event));
})
);
messageReceiver.addEventListener(
'retry-request',
queuedEventListener((event: RetryRequestEvent): void => {
onRetryRequestQueue.add(() => onRetryRequest(event));
})
);
messageReceiver.addEventListener('empty', queuedEventListener(onEmpty));
messageReceiver.addEventListener(
'configuration',
queuedEventListener(onConfiguration)
);
messageReceiver.addEventListener('typing', queuedEventListener(onTyping));
messageReceiver.addEventListener(
'sticker-pack',
queuedEventListener(onStickerPack)
);
messageReceiver.addEventListener(
'viewOnceOpenSync',
queuedEventListener(onViewOnceOpenSync)
);
messageReceiver.addEventListener(
'messageRequestResponse',
queuedEventListener(onMessageRequestResponse)
);
messageReceiver.addEventListener(
'profileKeyUpdate',
queuedEventListener(onProfileKeyUpdate)
);
messageReceiver.addEventListener(
'fetchLatest',
queuedEventListener(onFetchLatestSync)
);
messageReceiver.addEventListener('keys', queuedEventListener(onKeysSync));
messageReceiver.addEventListener(
'storyRecipientUpdate',
queuedEventListener(onStoryRecipientUpdate, false)
);
});
ourProfileKeyService.initialize(window.storage);
window.storage.onready(() => {
if (!window.storage.get('defaultConversationColor')) {
window.storage.put(
'defaultConversationColor',
DEFAULT_CONVERSATION_COLOR
);
}
});
let resolveOnAppView: (() => void) | undefined;
const onAppView = new Promise<void>(resolve => {
resolveOnAppView = resolve;
});
const reconnectBackOff = new BackOff(FIBONACCI_TIMEOUTS);
window.storage.onready(() => {
strictAssert(server, 'WebAPI not ready');
senderCertificateService.initialize({
server,
navigator,
onlineEventTarget: window,
storage: window.storage,
});
areWeASubscriberService.update(window.storage, server);
});
const eventHandlerQueue = new PQueue({
concurrency: 1,
});
// Note: this queue is meant to allow for stop/start of tasks, not limit parallelism.
const profileKeyResponseQueue = new PQueue();
profileKeyResponseQueue.pause();
const lightSessionResetQueue = new PQueue({ concurrency: 1 });
window.Signal.Services.lightSessionResetQueue = lightSessionResetQueue;
lightSessionResetQueue.pause();
const onDecryptionErrorQueue = new PQueue({ concurrency: 1 });
onDecryptionErrorQueue.pause();
const onRetryRequestQueue = new PQueue({ concurrency: 1 });
onRetryRequestQueue.pause();
window.Whisper.deliveryReceiptQueue = new PQueue({
concurrency: 1,
timeout: durations.MINUTE * 30,
});
window.Whisper.deliveryReceiptQueue.pause();
window.Whisper.deliveryReceiptBatcher =
window.Signal.Util.createBatcher<Receipt>({
name: 'Whisper.deliveryReceiptBatcher',
wait: 500,
maxSize: 100,
processBatch: async deliveryReceipts => {
await deliveryReceiptsJobQueue.add({ deliveryReceipts });
},
});
if (window.platform === 'darwin') {
window.addEventListener('dblclick', (event: Event) => {
const target = event.target as HTMLElement;
if (isWindowDragElement(target)) {
window.titleBarDoubleClick();
}
});
}
// Globally disable drag and drop
document.body.addEventListener(
'dragover',
e => {
e.preventDefault();
e.stopPropagation();
},
false
);
document.body.addEventListener(
'drop',
e => {
e.preventDefault();
e.stopPropagation();
},
false
);
startInteractionMode();
// Load these images now to ensure that they don't flicker on first use
window.preloadedImages = [];
function preload(list: ReadonlyArray<string>) {
for (let index = 0, max = list.length; index < max; index += 1) {
const image = new Image();
image.src = `./images/${list[index]}`;
window.preloadedImages.push(image);
}
}
const builtInImages = await window.getBuiltInImages();
preload(builtInImages);
// We add this to window here because the default Node context is erased at the end
// of preload.js processing
window.setImmediate = window.nodeSetImmediate;
const { Message } = window.Signal.Types;
const {
upgradeMessageSchema,
writeNewAttachmentData,
deleteAttachmentData,
doesAttachmentExist,
} = window.Signal.Migrations;
log.info('background page reloaded');
log.info('environment:', window.getEnvironment());
let newVersion = false;
let lastVersion: string | undefined;
window.document.title = window.getTitle();
document.documentElement.setAttribute(
'lang',
window.getLocale().substring(0, 2)
);
KeyChangeListener.init(window.textsecure.storage.protocol);
window.textsecure.storage.protocol.on('removePreKey', (ourUuid: UUID) => {
const uuidKind = window.textsecure.storage.user.getOurUuidKind(ourUuid);
window.getAccountManager().refreshPreKeys(uuidKind);
});
window.textsecure.storage.protocol.on('removeAllData', () => {
window.reduxActions.stories.removeAllStories();
});
window.getSocketStatus = () => {
if (server === undefined) {
return SocketStatus.CLOSED;
}
return server.getSocketStatus();
};
let accountManager: AccountManager;
window.getAccountManager = () => {
if (accountManager) {
return accountManager;
}
if (!server) {
throw new Error('getAccountManager: server is not available!');
}
accountManager = new window.textsecure.AccountManager(server);
accountManager.addEventListener('registration', () => {
window.Whisper.events.trigger('userChanged', false);
window.Signal.Util.Registration.markDone();
log.info('dispatching registration event');
window.Whisper.events.trigger('registration_done');
});
return accountManager;
};
const cancelInitializationMessage = setAppLoadingScreenMessage(
undefined,
window.i18n
);
const version = await window.Signal.Data.getItemById('version');
if (!version) {
const isIndexedDBPresent = await indexedDb.doesDatabaseExist();
if (isIndexedDBPresent) {
log.info('Found IndexedDB database.');
try {
log.info('Confirming deletion of old data with user...');
try {
await new Promise<void>((resolve, reject) => {
window.showConfirmationDialog({
dialogName: 'deleteOldIndexedDBData',
onTopOfEverything: true,
cancelText: window.i18n('quit'),
confirmStyle: 'negative',
message: window.i18n('deleteOldIndexedDBData'),
okText: window.i18n('deleteOldData'),
reject: () => reject(),
resolve: () => resolve(),
});
});
} catch (error) {
log.info(
'User chose not to delete old data. Shutting down.',
error && error.stack ? error.stack : error
);
window.shutdown();
return;
}
log.info('Deleting all previously-migrated data in SQL...');
log.info('Deleting IndexedDB file...');
await Promise.all([
indexedDb.removeDatabase(),
window.Signal.Data.removeAll(),
window.Signal.Data.removeIndexedDBFiles(),
]);
log.info('Done with SQL deletion and IndexedDB file deletion.');
} catch (error) {
log.error(
'Failed to remove IndexedDB file or remove SQL data:',
error && error.stack ? error.stack : error
);
}
// Set a flag to delete IndexedDB on next startup if it wasn't deleted just now.
// We need to use direct data calls, since window.storage isn't ready yet.
await window.Signal.Data.createOrUpdateItem({
id: 'indexeddb-delete-needed',
value: true,
});
}
}
log.info('Storage fetch');
window.storage.fetch();
function mapOldThemeToNew(
theme: Readonly<
'system' | 'light' | 'dark' | 'android' | 'ios' | 'android-dark'
>
): 'system' | 'light' | 'dark' {
switch (theme) {
case 'dark':
case 'light':
case 'system':
return theme;
case 'android-dark':
return 'dark';
case 'android':
case 'ios':
default:
return 'light';
}
}
// We need this 'first' check because we don't want to start the app up any other time
// than the first time. And window.storage.fetch() will cause onready() to fire.
let first = true;
window.storage.onready(async () => {
if (!first) {
return;
}
first = false;
strictAssert(server !== undefined, 'WebAPI not ready');
cleanupSessionResets();
// These make key operations available to IPC handlers created in preload.js
window.Events = createIPCEvents({
shutdown: async () => {
log.info('background/shutdown');
window.Signal.Util.flushMessageCounter();
// Stop background processing
AttachmentDownloads.stop();
idleDetector.stop();
// Stop processing incoming messages
if (messageReceiver) {
strictAssert(
server !== undefined,
'WebAPI should be initialized together with MessageReceiver'
);
log.info('background/shutdown: shutting down messageReceiver');
server.unregisterRequestHandler(messageReceiver);
messageReceiver.stopProcessing();
await window.waitForAllBatchers();
}
log.info('background/shutdown: flushing conversations');
// Flush debounced updates for conversations
await Promise.all(
window.ConversationController.getAll().map(convo =>
convo.flushDebouncedUpdates()
)
);
log.info('background/shutdown: waiting for all batchers');
// A number of still-to-queue database queries might be waiting inside batchers.
// We wait for these to empty first, and then shut down the data interface.
await Promise.all([
window.waitForAllBatchers(),
window.waitForAllWaitBatchers(),
]);
log.info('background/shutdown: closing the database');
// Shut down the data interface cleanly
await window.Signal.Data.shutdown();
},
});
const zoomFactor = window.Events.getZoomFactor();
webFrame.setZoomFactor(zoomFactor);
document.body.style.setProperty('--zoom-factor', zoomFactor.toString());
window.addEventListener('resize', () => {
document.body.style.setProperty(
'--zoom-factor',
webFrame.getZoomFactor().toString()
);
});
// How long since we were last running?
const lastHeartbeat = toDayMillis(window.storage.get('lastHeartbeat', 0));
const previousLastStartup = window.storage.get('lastStartup');
await window.storage.put('lastStartup', Date.now());
const THIRTY_DAYS = 30 * 24 * 60 * 60 * 1000;
if (lastHeartbeat > 0 && isOlderThan(lastHeartbeat, THIRTY_DAYS)) {
log.warn(
`This instance has not been used for 30 days. Last heartbeat: ${lastHeartbeat}. Last startup: ${previousLastStartup}.`
);
await unlinkAndDisconnect(RemoveAllConfiguration.Soft);
}
// Start heartbeat timer
window.storage.put('lastHeartbeat', toDayMillis(Date.now()));
const TWELVE_HOURS = 12 * 60 * 60 * 1000;
setInterval(
() => window.storage.put('lastHeartbeat', toDayMillis(Date.now())),
TWELVE_HOURS
);
const currentVersion = window.getVersion();
lastVersion = window.storage.get('version');
newVersion = !lastVersion || currentVersion !== lastVersion;
await window.storage.put('version', currentVersion);
if (newVersion && lastVersion) {
log.info(
`New version detected: ${currentVersion}; previous: ${lastVersion}`
);
const remoteBuildExpiration = window.storage.get('remoteBuildExpiration');
if (remoteBuildExpiration) {
log.info(
`Clearing remoteBuildExpiration. Previous value was ${remoteBuildExpiration}`
);
window.storage.remove('remoteBuildExpiration');
}
if (window.isBeforeVersion(lastVersion, 'v1.29.2-beta.1')) {
// Stickers flags
await Promise.all([
window.storage.put('showStickersIntroduction', true),
window.storage.put('showStickerPickerHint', true),
]);
}
if (window.isBeforeVersion(lastVersion, 'v1.26.0')) {
// Ensure that we re-register our support for sealed sender
await window.storage.put(
'hasRegisterSupportForUnauthenticatedDelivery',
false
);
}
const themeSetting = window.Events.getThemeSetting();
const newThemeSetting = mapOldThemeToNew(themeSetting);
if (window.isBeforeVersion(lastVersion, 'v1.25.0')) {
if (newThemeSetting === window.systemTheme) {
window.Events.setThemeSetting('system');
} else {
window.Events.setThemeSetting(newThemeSetting);
}
}
if (
window.isBeforeVersion(lastVersion, 'v1.36.0-beta.1') &&
window.isAfterVersion(lastVersion, 'v1.35.0-beta.1')
) {
await StorageService.eraseAllStorageServiceState();
}
if (window.isBeforeVersion(lastVersion, 'v5.2.0')) {
const legacySenderCertificateStorageKey = 'senderCertificateWithUuid';
await removeStorageKeyJobQueue.add({
key: legacySenderCertificateStorageKey,
});
}
if (window.isBeforeVersion(lastVersion, 'v5.18.0')) {
await window.storage.remove('senderCertificate');
await window.storage.remove('senderCertificateNoE164');
}
if (window.isBeforeVersion(lastVersion, 'v5.19.0')) {
await window.storage.remove(GROUP_CREDENTIALS_KEY);
}
if (window.isBeforeVersion(lastVersion, 'v5.37.0-alpha')) {
const legacyChallengeKey = 'challenge:retry-message-ids';
await removeStorageKeyJobQueue.add({
key: legacyChallengeKey,
});
await window.Signal.Data.clearAllErrorStickerPackAttempts();
}
if (window.isBeforeVersion(lastVersion, 'v5.51.0-beta.2')) {
await window.storage.put('groupCredentials', []);
await window.Signal.Data.removeAllProfileKeyCredentials();
}
// This one should always be last - it could restart the app
if (window.isBeforeVersion(lastVersion, 'v5.30.0-alpha')) {
await deleteAllLogs();
window.restart();
return;
}
}
setAppLoadingScreenMessage(
window.i18n('optimizingApplication'),
window.i18n
);
if (newVersion) {
// We've received reports that this update can take longer than two minutes, so we
// allow it to continue and just move on in that timeout case.
try {
await window.Signal.Data.cleanupOrphanedAttachments();
} catch (error) {
log.error(
'background: Failed to cleanup orphaned attachments:',
error && error.stack ? error.stack : error
);
}
// Don't block on the following operation
window.Signal.Data.ensureFilePermissions();
}
try {
await window.Signal.Data.startInRendererProcess();
} catch (err) {
log.error('SQL failed to initialize', err && err.stack ? err.stack : err);
}
setAppLoadingScreenMessage(window.i18n('loading'), window.i18n);
let isMigrationWithIndexComplete = false;
let isIdleTaskProcessing = false;
log.info(
`Starting background data migration. Target version: ${Message.CURRENT_SCHEMA_VERSION}`
);
idleDetector.on('idle', async () => {
const NUM_MESSAGES_PER_BATCH = 25;
const BATCH_DELAY = 10 * durations.SECOND;
if (isIdleTaskProcessing) {
log.warn(
'idleDetector/idle: previous batch incomplete, not starting another'
);
return;
}
try {
isIdleTaskProcessing = true;
if (!isMigrationWithIndexComplete) {
log.warn(
`idleDetector/idle: fetching at most ${NUM_MESSAGES_PER_BATCH} for migration`
);
const batchWithIndex = await migrateMessageData({
numMessagesPerBatch: NUM_MESSAGES_PER_BATCH,
upgradeMessageSchema,
getMessagesNeedingUpgrade:
window.Signal.Data.getMessagesNeedingUpgrade,
saveMessages: window.Signal.Data.saveMessages,
});
log.info('idleDetector/idle: Upgraded messages:', batchWithIndex);
isMigrationWithIndexComplete = batchWithIndex.done;
}
} finally {
idleDetector.stop();
if (isMigrationWithIndexComplete) {
log.info(
'idleDetector/idle: Background migration complete. Stopping.'
);
} else {
log.info(
`idleDetector/idle: Background migration not complete. Pausing for ${BATCH_DELAY}ms.`
);
setTimeout(() => {
idleDetector.start();
}, BATCH_DELAY);
}
isIdleTaskProcessing = false;
}
});
window.Signal.RemoteConfig.initRemoteConfig(server);
let retryReceiptLifespan: number | undefined;
try {
retryReceiptLifespan = parseIntOrThrow(
window.Signal.RemoteConfig.getValue('desktop.retryReceiptLifespan'),
'retryReceiptLifeSpan'
);
} catch (error) {
log.warn(
'Failed to parse integer out of desktop.retryReceiptLifespan feature flag'
);
}
const retryPlaceholders = new window.Signal.Util.RetryPlaceholders({
retryReceiptLifespan,
});
window.Signal.Services.retryPlaceholders = retryPlaceholders;
setInterval(async () => {
const now = Date.now();
const HOUR = 1000 * 60 * 60;
const DAY = 24 * HOUR;
let sentProtoMaxAge = 14 * DAY;
try {
sentProtoMaxAge = parseIntOrThrow(
window.Signal.RemoteConfig.getValue('desktop.retryRespondMaxAge'),
'retryRespondMaxAge'
);
} catch (error) {
log.warn(
'background/setInterval: Failed to parse integer from desktop.retryRespondMaxAge feature flag',
error && error.stack ? error.stack : error
);
}
try {
await window.Signal.Data.deleteSentProtosOlderThan(
now - sentProtoMaxAge
);
} catch (error) {
log.error(
'background/onready/setInterval: Error deleting sent protos: ',
error && error.stack ? error.stack : error
);
}
try {
const expired = await retryPlaceholders.getExpiredAndRemove();
log.info(
`retryPlaceholders/interval: Found ${expired.length} expired items`
);
expired.forEach(item => {
const { conversationId, senderUuid, sentAt } = item;
const conversation =
window.ConversationController.get(conversationId);
if (conversation) {
const receivedAt = Date.now();
const receivedAtCounter =
window.Signal.Util.incrementMessageCounter();
conversation.queueJob('addDeliveryIssue', () =>
conversation.addDeliveryIssue({
receivedAt,
receivedAtCounter,
senderUuid,
sentAt,
})
);
}
});
} catch (error) {
log.error(
'background/onready/setInterval: Error getting expired retry placeholders: ',
error && error.stack ? error.stack : error
);
}
}, FIVE_MINUTES);