-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
expiring_messages.js
101 lines (84 loc) · 2.66 KB
/
expiring_messages.js
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
// Copyright 2016-2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
/* global
_,
MessageController,
Whisper
*/
// eslint-disable-next-line func-names
(function () {
window.Whisper = window.Whisper || {};
async function destroyExpiredMessages() {
try {
window.log.info('destroyExpiredMessages: Loading messages...');
const messages = await window.Signal.Data.getExpiredMessages({
MessageCollection: Whisper.MessageCollection,
});
await Promise.all(
messages.map(async fromDB => {
const message = MessageController.register(fromDB.id, fromDB);
window.log.info('Message expired', {
sentAt: message.get('sent_at'),
});
// We delete after the trigger to allow the conversation time to process
// the expiration before the message is removed from the database.
await window.Signal.Data.removeMessage(message.id, {
Message: Whisper.Message,
});
Whisper.events.trigger(
'messageExpired',
message.id,
message.conversationId
);
const conversation = message.getConversation();
if (conversation) {
conversation.trigger('expired', message);
}
})
);
} catch (error) {
window.log.error(
'destroyExpiredMessages: Error deleting expired messages',
error && error.stack ? error.stack : error
);
}
window.log.info('destroyExpiredMessages: complete');
checkExpiringMessages();
}
let timeout;
async function checkExpiringMessages() {
// Look up the next expiring message and set a timer to destroy it
const message = await window.Signal.Data.getNextExpiringMessage({
Message: Whisper.Message,
});
if (!message) {
return;
}
const expiresAt = message.get('expires_at');
Whisper.ExpiringMessagesListener.nextExpiration = expiresAt;
window.log.info('next message expires', new Date(expiresAt).toISOString());
let wait = expiresAt - Date.now();
// In the past
if (wait < 0) {
wait = 0;
}
// Too far in the future, since it's limited to a 32-bit value
if (wait > 2147483647) {
wait = 2147483647;
}
clearTimeout(timeout);
timeout = setTimeout(destroyExpiredMessages, wait);
}
const debouncedCheckExpiringMessages = _.debounce(
checkExpiringMessages,
1000
);
Whisper.ExpiringMessagesListener = {
nextExpiration: null,
init(events) {
checkExpiringMessages();
events.on('timetravel', debouncedCheckExpiringMessages);
},
update: debouncedCheckExpiringMessages,
};
})();