-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
ReadSyncs.ts
201 lines (175 loc) · 5.88 KB
/
ReadSyncs.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
// Copyright 2017 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import type { AciString } from '../types/ServiceId';
import type { MessageModel } from '../models/messages';
import * as Errors from '../types/errors';
import * as log from '../logging/log';
import { StartupQueue } from '../util/StartupQueue';
import { drop } from '../util/drop';
import { getMessageIdForLogging } from '../util/idForLogging';
import { getMessageSentTimestamp } from '../util/getMessageSentTimestamp';
import { isIncoming } from '../state/selectors/message';
import { isMessageUnread } from '../util/isMessageUnread';
import { notificationService } from '../services/notifications';
import { queueUpdateMessage } from '../util/messageBatcher';
import { strictAssert } from '../util/assert';
import { generateCacheKey } from './generateCacheKey';
export type ReadSyncAttributesType = {
envelopeId: string;
readAt: number;
removeFromMessageReceiverCache: () => unknown;
sender?: string;
senderAci: AciString;
senderId: string;
timestamp: number;
};
const readSyncs = new Map<string, ReadSyncAttributesType>();
function remove(sync: ReadSyncAttributesType): void {
readSyncs.delete(
generateCacheKey({
sender: sync.senderId,
timestamp: sync.timestamp,
type: 'readsync',
})
);
sync.removeFromMessageReceiverCache();
}
async function maybeItIsAReactionReadSync(
sync: ReadSyncAttributesType
): Promise<void> {
const logId = `ReadSyncs.onSync(timestamp=${sync.timestamp})`;
const readReaction = await window.Signal.Data.markReactionAsRead(
sync.senderAci,
Number(sync.timestamp)
);
if (
!readReaction ||
readReaction?.targetAuthorAci !== window.storage.user.getCheckedAci()
) {
log.info(`${logId} not found:`, sync.senderId, sync.sender, sync.senderAci);
return;
}
log.info(
`${logId} read reaction sync found:`,
readReaction.conversationId,
sync.senderId,
sync.sender,
sync.senderAci
);
remove(sync);
notificationService.removeBy({
conversationId: readReaction.conversationId,
emoji: readReaction.emoji,
targetAuthorAci: readReaction.targetAuthorAci,
targetTimestamp: readReaction.targetTimestamp,
});
}
export function forMessage(
message: MessageModel
): ReadSyncAttributesType | null {
const logId = `ReadSyncs.forMessage(${getMessageIdForLogging(
message.attributes
)})`;
const sender = window.ConversationController.lookupOrCreate({
e164: message.get('source'),
serviceId: message.get('sourceServiceId'),
reason: logId,
});
const messageTimestamp = getMessageSentTimestamp(message.attributes, {
log,
});
const readSyncValues = Array.from(readSyncs.values());
const foundSync = readSyncValues.find(item => {
return item.senderId === sender?.id && item.timestamp === messageTimestamp;
});
if (foundSync) {
log.info(
`${logId}: Found early read sync for message ${foundSync.timestamp}`
);
remove(foundSync);
return foundSync;
}
return null;
}
export async function onSync(sync: ReadSyncAttributesType): Promise<void> {
readSyncs.set(
generateCacheKey({
sender: sync.senderId,
timestamp: sync.timestamp,
type: 'readsync',
}),
sync
);
const logId = `ReadSyncs.onSync(timestamp=${sync.timestamp})`;
try {
const messages = await window.Signal.Data.getMessagesBySentAt(
sync.timestamp
);
const found = messages.find(item => {
const sender = window.ConversationController.lookupOrCreate({
e164: item.source,
serviceId: item.sourceServiceId,
reason: logId,
});
return isIncoming(item) && sender?.id === sync.senderId;
});
if (!found) {
await maybeItIsAReactionReadSync(sync);
return;
}
notificationService.removeBy({ messageId: found.id });
const message = window.MessageCache.__DEPRECATED$register(
found.id,
found,
'ReadSyncs.onSync'
);
const readAt = Math.min(sync.readAt, Date.now());
const newestSentAt = sync.timestamp;
// If message is unread, we mark it read. Otherwise, we update the expiration
// timer to the time specified by the read sync if it's earlier than
// the previous read time.
if (isMessageUnread(message.attributes)) {
// TODO DESKTOP-1509: use MessageUpdater.markRead once this is TS
message.markRead(readAt, { skipSave: true });
const updateConversation = async () => {
const conversation = message.getConversation();
strictAssert(conversation, `${logId}: conversation not found`);
// onReadMessage may result in messages older than this one being
// marked read. We want those messages to have the same expire timer
// start time as this one, so we pass the readAt value through.
drop(conversation.onReadMessage(message, readAt, newestSentAt));
};
// only available during initialization
if (StartupQueue.isAvailable()) {
const conversation = message.getConversation();
strictAssert(
conversation,
`${logId}: conversation not found (StartupQueue)`
);
StartupQueue.add(
conversation.get('id'),
message.get('sent_at'),
updateConversation
);
} else {
// not awaiting since we don't want to block work happening in the
// eventHandlerQueue
drop(updateConversation());
}
} else {
log.info(`${logId}: updating expiration`);
const now = Date.now();
const existingTimestamp = message.get('expirationStartTimestamp');
const expirationStartTimestamp = Math.min(
now,
Math.min(existingTimestamp || now, readAt || now)
);
message.set({ expirationStartTimestamp });
}
queueUpdateMessage(message.attributes);
remove(sync);
} catch (error) {
remove(sync);
log.error(`${logId} error:`, Errors.toLogFormat(error));
}
}