Line data Source code
1 : /*
2 : * Famedly Matrix SDK
3 : * Copyright (C) 2020, 2021, 2023 Famedly GmbH
4 : *
5 : * This program is free software: you can redistribute it and/or modify
6 : * it under the terms of the GNU Affero General Public License as
7 : * published by the Free Software Foundation, either version 3 of the
8 : * License, or (at your option) any later version.
9 : *
10 : * This program is distributed in the hope that it will be useful,
11 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 : * GNU Affero General Public License for more details.
14 : *
15 : * You should have received a copy of the GNU Affero General Public License
16 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 : */
18 :
19 : import 'package:matrix/matrix.dart';
20 :
21 : // Receipts are pretty complicated nowadays. We basicaly have 3 different aspects, that we need to multiplex together:
22 : // 1. A receipt can be public or private. Currently clients can send either a public one, a private one or both. This means you have 2 receipts for your own user and no way to know, which one is ahead!
23 : // 2. A receipt can be for the normal timeline, but with threads they can also be for the main timeline (which is messages without thread ids) and for threads. So we have have 3 options there basically, with the last one being a thread for each thread id!
24 : // 3. Edits can make the timeline non-linear, so receipts don't match the visual order.
25 : // Additionally of course timestamps are usually not reliable, but we can probably assume they are correct for the same user unless their server had wrong clocks in between.
26 : //
27 : // So how do we solve that? Users of the SDK usually do one of these operations:
28 : // - Check if the current user has read the last event in a room (usually in the global timeline, but also possibly in the main thread or a specific thread)
29 : // - Check if the current users receipt is before or after the current event
30 : // - List users that have read up to a certain point (possibly in a specific timeline?)
31 : //
32 : // One big simplification we could do, would be to always assume our own user sends a private receipt with their public one. This won't play nicely with other SDKs, but it would simplify our work a lot.
33 : // If we don't do that, we have to compare receipts when updating them. This can be very annoying, because we can only compare event ids, if we have stored both of them, which we often have not.
34 : // If we fall back to the timestamp then it will break if a user ever has a client sending laggy public receipts, i.e. sends public receipts at a later point for previous events, because it will move the read marker back.
35 : // Here is how Element solves it: https://github.com/matrix-org/matrix-js-sdk/blob/da03c3b529576a8fcde6f2c9a171fa6cca012830/src/models/read-receipt.ts#L97
36 : // Luckily that is only an issue for our own events. We can also assume, that if we only have one event in the database, that it is newer.
37 :
38 : /// Represents a receipt.
39 : /// This [user] has read an event at the given [time].
40 : class Receipt {
41 : final User user;
42 : final DateTime time;
43 :
44 2 : const Receipt(this.user, this.time);
45 :
46 1 : @override
47 1 : bool operator ==(Object other) => (other is Receipt &&
48 3 : other.user == user &&
49 5 : other.time.millisecondsSinceEpoch == time.millisecondsSinceEpoch);
50 :
51 0 : @override
52 0 : int get hashCode => Object.hash(user, time);
53 : }
54 :
55 : class ReceiptData {
56 : int originServerTs;
57 : String? threadId;
58 :
59 0 : DateTime get timestamp => DateTime.fromMillisecondsSinceEpoch(originServerTs);
60 :
61 33 : ReceiptData(this.originServerTs, {this.threadId});
62 : }
63 :
64 : class ReceiptEventContent {
65 : Map<String, Map<ReceiptType, Map<String, ReceiptData>>> receipts;
66 33 : ReceiptEventContent(this.receipts);
67 :
68 33 : factory ReceiptEventContent.fromJson(Map<String, dynamic> json) {
69 : // Example data:
70 : // {
71 : // "$I": {
72 : // "m.read": {
73 : // "@user:example.org": {
74 : // "ts": 1661384801651,
75 : // "thread_id": "main" // because `I` is not in a thread, but is a threaded receipt
76 : // }
77 : // }
78 : // },
79 : // "$E": {
80 : // "m.read": {
81 : // "@user:example.org": {
82 : // "ts": 1661384801651,
83 : // "thread_id": "$A" // because `E` is in Thread `A`
84 : // }
85 : // }
86 : // },
87 : // "$D": {
88 : // "m.read": {
89 : // "@user:example.org": {
90 : // "ts": 1661384801651
91 : // // no `thread_id` because the receipt is *unthreaded*
92 : // }
93 : // }
94 : // }
95 : // }
96 :
97 33 : final Map<String, Map<ReceiptType, Map<String, ReceiptData>>> receipts = {};
98 66 : for (final eventIdEntry in json.entries) {
99 33 : final eventId = eventIdEntry.key;
100 33 : final contentForEventId = eventIdEntry.value;
101 :
102 66 : if (!eventId.startsWith('\$') || contentForEventId is! Map) continue;
103 :
104 66 : for (final receiptTypeEntry in contentForEventId.entries) {
105 66 : if (receiptTypeEntry.key is! String) continue;
106 :
107 66 : final receiptType = ReceiptType.values.fromString(receiptTypeEntry.key);
108 33 : final contentForReceiptType = receiptTypeEntry.value;
109 :
110 33 : if (receiptType == null || contentForReceiptType is! Map) continue;
111 :
112 66 : for (final userIdEntry in contentForReceiptType.entries) {
113 33 : final userId = userIdEntry.key;
114 33 : final receiptContent = userIdEntry.value;
115 :
116 33 : if (userId is! String ||
117 33 : !userId.isValidMatrixId ||
118 33 : receiptContent is! Map) continue;
119 :
120 33 : final ts = receiptContent['ts'];
121 33 : final threadId = receiptContent['thread_id'];
122 :
123 34 : if (ts is int && (threadId == null || threadId is String)) {
124 165 : ((receipts[eventId] ??= {})[receiptType] ??= {})[userId] =
125 33 : ReceiptData(ts, threadId: threadId);
126 : }
127 : }
128 : }
129 : }
130 :
131 33 : return ReceiptEventContent(receipts);
132 : }
133 : }
134 :
135 : class LatestReceiptStateData {
136 : String eventId;
137 : int ts;
138 :
139 3 : DateTime get timestamp => DateTime.fromMillisecondsSinceEpoch(ts);
140 :
141 33 : LatestReceiptStateData(this.eventId, this.ts);
142 :
143 2 : factory LatestReceiptStateData.fromJson(Map<String, dynamic> json) {
144 6 : return LatestReceiptStateData(json['e'], json['ts']);
145 : }
146 :
147 66 : Map<String, dynamic> toJson() => {
148 : // abbreviated names, because we will store a lot of these.
149 33 : 'e': eventId,
150 33 : 'ts': ts,
151 : };
152 : }
153 :
154 : class LatestReceiptStateForTimeline {
155 : LatestReceiptStateData? ownPrivate;
156 : LatestReceiptStateData? ownPublic;
157 : LatestReceiptStateData? latestOwnReceipt;
158 :
159 : Map<String, LatestReceiptStateData> otherUsers;
160 :
161 33 : LatestReceiptStateForTimeline({
162 : required this.ownPrivate,
163 : required this.ownPublic,
164 : required this.latestOwnReceipt,
165 : required this.otherUsers,
166 : });
167 :
168 1 : factory LatestReceiptStateForTimeline.empty() =>
169 1 : LatestReceiptStateForTimeline(
170 : ownPrivate: null,
171 : ownPublic: null,
172 : latestOwnReceipt: null,
173 1 : otherUsers: {},
174 : );
175 :
176 33 : factory LatestReceiptStateForTimeline.fromJson(Map<String, dynamic> json) {
177 33 : final private = json['private'];
178 33 : final public = json['public'];
179 33 : final latest = json['latest'];
180 33 : final Map<String, dynamic>? others = json['others'];
181 :
182 : final Map<String, LatestReceiptStateData> byUser = others
183 8 : ?.map((k, v) => MapEntry(k, LatestReceiptStateData.fromJson(v))) ??
184 33 : {};
185 :
186 33 : return LatestReceiptStateForTimeline(
187 : ownPrivate:
188 1 : private != null ? LatestReceiptStateData.fromJson(private) : null,
189 : ownPublic:
190 1 : public != null ? LatestReceiptStateData.fromJson(public) : null,
191 : latestOwnReceipt:
192 1 : latest != null ? LatestReceiptStateData.fromJson(latest) : null,
193 : otherUsers: byUser,
194 : );
195 : }
196 :
197 66 : Map<String, dynamic> toJson() => {
198 36 : if (ownPrivate != null) 'private': ownPrivate!.toJson(),
199 36 : if (ownPublic != null) 'public': ownPublic!.toJson(),
200 36 : if (latestOwnReceipt != null) 'latest': latestOwnReceipt!.toJson(),
201 198 : 'others': otherUsers.map((k, v) => MapEntry(k, v.toJson())),
202 : };
203 : }
204 :
205 : class LatestReceiptState {
206 : static const eventType = 'com.famedly.receipts_state';
207 :
208 : /// Receipts for no specific thread
209 : LatestReceiptStateForTimeline global;
210 :
211 : /// Receipt for the "main" thread, which is the global timeline without any thread events
212 : LatestReceiptStateForTimeline? mainThread;
213 :
214 : /// Receipts inside threads
215 : Map<String, LatestReceiptStateForTimeline> byThread;
216 :
217 33 : LatestReceiptState({
218 : required this.global,
219 : this.mainThread,
220 : this.byThread = const {},
221 : });
222 :
223 33 : factory LatestReceiptState.fromJson(Map<String, dynamic> json) {
224 66 : final global = json['global'] ?? <String, dynamic>{};
225 66 : final Map<String, dynamic> main = json['main'] ?? <String, dynamic>{};
226 66 : final Map<String, dynamic> byThread = json['thread'] ?? <String, dynamic>{};
227 :
228 33 : return LatestReceiptState(
229 33 : global: LatestReceiptStateForTimeline.fromJson(global),
230 : mainThread:
231 34 : main.isNotEmpty ? LatestReceiptStateForTimeline.fromJson(main) : null,
232 33 : byThread: byThread.map(
233 3 : (k, v) => MapEntry(k, LatestReceiptStateForTimeline.fromJson(v)),
234 : ),
235 : );
236 : }
237 :
238 66 : Map<String, dynamic> toJson() => {
239 99 : 'global': global.toJson(),
240 36 : if (mainThread != null) 'main': mainThread!.toJson(),
241 66 : if (byThread.isNotEmpty)
242 6 : 'thread': byThread.map((k, v) => MapEntry(k, v.toJson())),
243 : };
244 :
245 33 : Future<void> update(
246 : ReceiptEventContent content,
247 : Room room,
248 : ) async {
249 33 : final List<LatestReceiptStateForTimeline> updatedTimelines = [];
250 66 : final ownUserid = room.client.userID!;
251 :
252 99 : content.receipts.forEach((eventId, receiptsByType) {
253 66 : receiptsByType.forEach((receiptType, receiptsByUser) {
254 66 : receiptsByUser.forEach((user, receipt) {
255 : LatestReceiptStateForTimeline? timeline;
256 33 : final threadId = receipt.threadId;
257 33 : if (threadId == 'main') {
258 2 : timeline = (mainThread ??= LatestReceiptStateForTimeline.empty());
259 : } else if (threadId != null) {
260 : timeline =
261 3 : (byThread[threadId] ??= LatestReceiptStateForTimeline.empty());
262 : } else {
263 33 : timeline = global;
264 : }
265 :
266 : final receiptData =
267 66 : LatestReceiptStateData(eventId, receipt.originServerTs);
268 33 : if (user == ownUserid) {
269 1 : if (receiptType == ReceiptType.mReadPrivate) {
270 1 : timeline.ownPrivate = receiptData;
271 1 : } else if (receiptType == ReceiptType.mRead) {
272 1 : timeline.ownPublic = receiptData;
273 : }
274 1 : updatedTimelines.add(timeline);
275 : } else {
276 66 : timeline.otherUsers[user] = receiptData;
277 : }
278 : });
279 : });
280 : });
281 :
282 : // set the latest receipt to the one furthest down in the timeline, or if we don't know that, the newest ts.
283 33 : if (updatedTimelines.isEmpty) return;
284 :
285 3 : final eventOrder = await room.client.database?.getEventIdList(room) ?? [];
286 :
287 2 : for (final timeline in updatedTimelines) {
288 5 : if (timeline.ownPrivate?.eventId == timeline.ownPublic?.eventId) {
289 1 : if (timeline.ownPrivate != null) {
290 2 : timeline.latestOwnReceipt = timeline.ownPrivate;
291 : }
292 : continue;
293 : }
294 :
295 1 : final public = timeline.ownPublic;
296 1 : final private = timeline.ownPrivate;
297 :
298 : if (private == null) {
299 1 : timeline.latestOwnReceipt = public;
300 : } else if (public == null) {
301 0 : timeline.latestOwnReceipt = private;
302 : } else {
303 2 : final privatePos = eventOrder.indexOf(private.eventId);
304 2 : final publicPos = eventOrder.indexOf(public.eventId);
305 :
306 1 : if (publicPos < 0 ||
307 1 : privatePos <= publicPos ||
308 0 : (privatePos < 0 && private.ts > public.ts)) {
309 1 : timeline.latestOwnReceipt = private;
310 : } else {
311 0 : timeline.latestOwnReceipt = public;
312 : }
313 : }
314 : }
315 : }
316 : }
|