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 32 : ReceiptData(this.originServerTs, {this.threadId});
62 : }
63 :
64 : class ReceiptEventContent {
65 : Map<String, Map<ReceiptType, Map<String, ReceiptData>>> receipts;
66 32 : ReceiptEventContent(this.receipts);
67 :
68 32 : 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 32 : final Map<String, Map<ReceiptType, Map<String, ReceiptData>>> receipts = {};
98 64 : for (final eventIdEntry in json.entries) {
99 32 : final eventId = eventIdEntry.key;
100 32 : final contentForEventId = eventIdEntry.value;
101 :
102 64 : if (!eventId.startsWith('\$') || contentForEventId is! Map) continue;
103 :
104 64 : for (final receiptTypeEntry in contentForEventId.entries) {
105 64 : if (receiptTypeEntry.key is! String) continue;
106 :
107 64 : final receiptType = ReceiptType.values.fromString(receiptTypeEntry.key);
108 32 : final contentForReceiptType = receiptTypeEntry.value;
109 :
110 32 : if (receiptType == null || contentForReceiptType is! Map) continue;
111 :
112 64 : for (final userIdEntry in contentForReceiptType.entries) {
113 32 : final userId = userIdEntry.key;
114 32 : final receiptContent = userIdEntry.value;
115 :
116 32 : if (userId is! String ||
117 32 : !userId.isValidMatrixId ||
118 32 : receiptContent is! Map) continue;
119 :
120 32 : final ts = receiptContent['ts'];
121 32 : final threadId = receiptContent['thread_id'];
122 :
123 33 : if (ts is int && (threadId == null || threadId is String)) {
124 160 : ((receipts[eventId] ??= {})[receiptType] ??= {})[userId] =
125 32 : ReceiptData(ts, threadId: threadId);
126 : }
127 : }
128 : }
129 : }
130 :
131 32 : 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 32 : 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 64 : Map<String, dynamic> toJson() => {
148 : // abbreviated names, because we will store a lot of these.
149 32 : 'e': eventId,
150 32 : '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 32 : 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 32 : factory LatestReceiptStateForTimeline.fromJson(Map<String, dynamic> json) {
176 32 : final private = json['private'];
177 32 : final public = json['public'];
178 32 : final latest = json['latest'];
179 32 : final Map<String, dynamic>? others = json['others'];
180 :
181 : final Map<String, LatestReceiptStateData> byUser = others
182 8 : ?.map((k, v) => MapEntry(k, LatestReceiptStateData.fromJson(v))) ??
183 32 : {};
184 :
185 32 : return LatestReceiptStateForTimeline(
186 : ownPrivate:
187 1 : private != null ? LatestReceiptStateData.fromJson(private) : null,
188 : ownPublic:
189 1 : public != null ? LatestReceiptStateData.fromJson(public) : null,
190 : latestOwnReceipt:
191 1 : latest != null ? LatestReceiptStateData.fromJson(latest) : null,
192 : otherUsers: byUser,
193 : );
194 : }
195 :
196 64 : Map<String, dynamic> toJson() => {
197 35 : if (ownPrivate != null) 'private': ownPrivate!.toJson(),
198 35 : if (ownPublic != null) 'public': ownPublic!.toJson(),
199 35 : if (latestOwnReceipt != null) 'latest': latestOwnReceipt!.toJson(),
200 192 : 'others': otherUsers.map((k, v) => MapEntry(k, v.toJson())),
201 : };
202 : }
203 :
204 : class LatestReceiptState {
205 : static const eventType = 'com.famedly.receipts_state';
206 :
207 : /// Receipts for no specific thread
208 : LatestReceiptStateForTimeline global;
209 :
210 : /// Receipt for the "main" thread, which is the global timeline without any thread events
211 : LatestReceiptStateForTimeline? mainThread;
212 :
213 : /// Receipts inside threads
214 : Map<String, LatestReceiptStateForTimeline> byThread;
215 :
216 32 : LatestReceiptState({
217 : required this.global,
218 : this.mainThread,
219 : this.byThread = const {},
220 : });
221 :
222 32 : factory LatestReceiptState.fromJson(Map<String, dynamic> json) {
223 64 : final global = json['global'] ?? <String, dynamic>{};
224 64 : final Map<String, dynamic> main = json['main'] ?? <String, dynamic>{};
225 64 : final Map<String, dynamic> byThread = json['thread'] ?? <String, dynamic>{};
226 :
227 32 : return LatestReceiptState(
228 32 : global: LatestReceiptStateForTimeline.fromJson(global),
229 : mainThread:
230 33 : main.isNotEmpty ? LatestReceiptStateForTimeline.fromJson(main) : null,
231 32 : byThread: byThread.map(
232 3 : (k, v) => MapEntry(k, LatestReceiptStateForTimeline.fromJson(v))),
233 : );
234 : }
235 :
236 64 : Map<String, dynamic> toJson() => {
237 96 : 'global': global.toJson(),
238 35 : if (mainThread != null) 'main': mainThread!.toJson(),
239 64 : if (byThread.isNotEmpty)
240 6 : 'thread': byThread.map((k, v) => MapEntry(k, v.toJson())),
241 : };
242 :
243 32 : Future<void> update(
244 : ReceiptEventContent content,
245 : Room room,
246 : ) async {
247 32 : final List<LatestReceiptStateForTimeline> updatedTimelines = [];
248 64 : final ownUserid = room.client.userID!;
249 :
250 96 : content.receipts.forEach((eventId, receiptsByType) {
251 64 : receiptsByType.forEach((receiptType, receiptsByUser) {
252 64 : receiptsByUser.forEach((user, receipt) {
253 : LatestReceiptStateForTimeline? timeline;
254 32 : final threadId = receipt.threadId;
255 32 : if (threadId == 'main') {
256 2 : timeline = (mainThread ??= LatestReceiptStateForTimeline.empty());
257 : } else if (threadId != null) {
258 : timeline =
259 3 : (byThread[threadId] ??= LatestReceiptStateForTimeline.empty());
260 : } else {
261 32 : timeline = global;
262 : }
263 :
264 : final receiptData =
265 64 : LatestReceiptStateData(eventId, receipt.originServerTs);
266 32 : if (user == ownUserid) {
267 1 : if (receiptType == ReceiptType.mReadPrivate) {
268 1 : timeline.ownPrivate = receiptData;
269 1 : } else if (receiptType == ReceiptType.mRead) {
270 1 : timeline.ownPublic = receiptData;
271 : }
272 1 : updatedTimelines.add(timeline);
273 : } else {
274 64 : timeline.otherUsers[user] = receiptData;
275 : }
276 : });
277 : });
278 : });
279 :
280 : // set the latest receipt to the one furthest down in the timeline, or if we don't know that, the newest ts.
281 32 : if (updatedTimelines.isEmpty) return;
282 :
283 3 : final eventOrder = await room.client.database?.getEventIdList(room) ?? [];
284 :
285 2 : for (final timeline in updatedTimelines) {
286 5 : if (timeline.ownPrivate?.eventId == timeline.ownPublic?.eventId) {
287 1 : if (timeline.ownPrivate != null) {
288 2 : timeline.latestOwnReceipt = timeline.ownPrivate;
289 : }
290 : continue;
291 : }
292 :
293 1 : final public = timeline.ownPublic;
294 1 : final private = timeline.ownPrivate;
295 :
296 : if (private == null) {
297 1 : timeline.latestOwnReceipt = public;
298 : } else if (public == null) {
299 0 : timeline.latestOwnReceipt = private;
300 : } else {
301 2 : final privatePos = eventOrder.indexOf(private.eventId);
302 2 : final publicPos = eventOrder.indexOf(public.eventId);
303 :
304 1 : if (publicPos < 0 ||
305 1 : privatePos <= publicPos ||
306 0 : (privatePos < 0 && private.ts > public.ts)) {
307 1 : timeline.latestOwnReceipt = private;
308 : } else {
309 0 : timeline.latestOwnReceipt = public;
310 : }
311 : }
312 : }
313 : }
314 : }
|