Line data Source code
1 : /*
2 : * Famedly Matrix SDK
3 : * Copyright (C) 2019, 2020, 2021 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 'dart:convert';
20 : import 'dart:typed_data';
21 :
22 : import 'package:collection/collection.dart';
23 : import 'package:html/parser.dart';
24 :
25 : import 'package:matrix/matrix.dart';
26 : import 'package:matrix/src/utils/event_localizations.dart';
27 : import 'package:matrix/src/utils/file_send_request_credentials.dart';
28 : import 'package:matrix/src/utils/html_to_text.dart';
29 : import 'package:matrix/src/utils/markdown.dart';
30 :
31 : abstract class RelationshipTypes {
32 : static const String reply = 'm.in_reply_to';
33 : static const String edit = 'm.replace';
34 : static const String reaction = 'm.annotation';
35 : static const String thread = 'm.thread';
36 : }
37 :
38 : /// All data exchanged over Matrix is expressed as an "event". Typically each client action (e.g. sending a message) correlates with exactly one event.
39 : class Event extends MatrixEvent {
40 : /// Requests the user object of the sender of this event.
41 12 : Future<User?> fetchSenderUser() => room.requestUser(
42 4 : senderId,
43 : ignoreErrors: true,
44 : );
45 :
46 0 : @Deprecated(
47 : 'Use eventSender instead or senderFromMemoryOrFallback for a synchronous alternative',
48 : )
49 0 : User get sender => senderFromMemoryOrFallback;
50 :
51 4 : User get senderFromMemoryOrFallback =>
52 12 : room.unsafeGetUserFromMemoryOrFallback(senderId);
53 :
54 : /// The room this event belongs to. May be null.
55 : final Room room;
56 :
57 : /// The status of this event.
58 : EventStatus status;
59 :
60 : static const EventStatus defaultStatus = EventStatus.synced;
61 :
62 : /// Optional. The event that redacted this event, if any. Otherwise null.
63 12 : Event? get redactedBecause {
64 21 : final redacted_because = unsigned?['redacted_because'];
65 12 : final room = this.room;
66 12 : return (redacted_because is Map<String, dynamic>)
67 5 : ? Event.fromJson(redacted_because, room)
68 : : null;
69 : }
70 :
71 24 : bool get redacted => redactedBecause != null;
72 :
73 4 : User? get stateKeyUser => stateKey != null
74 6 : ? room.unsafeGetUserFromMemoryOrFallback(stateKey!)
75 : : null;
76 :
77 : MatrixEvent? _originalSource;
78 :
79 68 : MatrixEvent? get originalSource => _originalSource;
80 :
81 101 : String? get transactionId => unsigned?.tryGet<String>('transaction_id');
82 :
83 36 : Event({
84 : this.status = defaultStatus,
85 : required Map<String, dynamic> super.content,
86 : required super.type,
87 : required String eventId,
88 : required super.senderId,
89 : required DateTime originServerTs,
90 : Map<String, dynamic>? unsigned,
91 : Map<String, dynamic>? prevContent,
92 : String? stateKey,
93 : super.redacts,
94 : required this.room,
95 : MatrixEvent? originalSource,
96 : }) : _originalSource = originalSource,
97 36 : super(
98 : eventId: eventId,
99 : originServerTs: originServerTs,
100 36 : roomId: room.id,
101 : ) {
102 36 : this.eventId = eventId;
103 36 : this.unsigned = unsigned;
104 : // synapse unfortunately isn't following the spec and tosses the prev_content
105 : // into the unsigned block.
106 : // Currently we are facing a very strange bug in web which is impossible to debug.
107 : // It may be because of this line so we put this in try-catch until we can fix it.
108 : try {
109 72 : this.prevContent = (prevContent != null && prevContent.isNotEmpty)
110 : ? prevContent
111 : : (unsigned != null &&
112 36 : unsigned.containsKey('prev_content') &&
113 6 : unsigned['prev_content'] is Map)
114 3 : ? unsigned['prev_content']
115 : : null;
116 : } catch (_) {
117 : // A strange bug in dart web makes this crash
118 : }
119 36 : this.stateKey = stateKey;
120 :
121 : // Mark event as failed to send if status is `sending` and event is older
122 : // than the timeout. This should not happen with the deprecated Moor
123 : // database!
124 105 : if (status.isSending && room.client.database != null) {
125 : // Age of this event in milliseconds
126 21 : final age = DateTime.now().millisecondsSinceEpoch -
127 7 : originServerTs.millisecondsSinceEpoch;
128 :
129 7 : final room = this.room;
130 28 : if (age > room.client.sendTimelineEventTimeout.inMilliseconds) {
131 : // Update this event in database and open timelines
132 0 : final json = toJson();
133 0 : json['unsigned'] ??= <String, dynamic>{};
134 0 : json['unsigned'][messageSendingStatusKey] = EventStatus.error.intValue;
135 : // ignore: discarded_futures
136 0 : room.client.handleSync(
137 0 : SyncUpdate(
138 : nextBatch: '',
139 0 : rooms: RoomsUpdate(
140 0 : join: {
141 0 : room.id: JoinedRoomUpdate(
142 0 : timeline: TimelineUpdate(
143 0 : events: [MatrixEvent.fromJson(json)],
144 : ),
145 : ),
146 : },
147 : ),
148 : ),
149 : );
150 : }
151 : }
152 : }
153 :
154 36 : static Map<String, dynamic> getMapFromPayload(Object? payload) {
155 36 : if (payload is String) {
156 : try {
157 9 : return json.decode(payload);
158 : } catch (e) {
159 0 : return {};
160 : }
161 : }
162 36 : if (payload is Map<String, dynamic>) return payload;
163 36 : return {};
164 : }
165 :
166 36 : factory Event.fromMatrixEvent(
167 : MatrixEvent matrixEvent,
168 : Room room, {
169 : EventStatus? status,
170 : }) =>
171 36 : matrixEvent is Event
172 : ? matrixEvent
173 36 : : Event(
174 : status: status ??
175 36 : eventStatusFromInt(
176 36 : matrixEvent.unsigned
177 33 : ?.tryGet<int>(messageSendingStatusKey) ??
178 36 : defaultStatus.intValue,
179 : ),
180 36 : content: matrixEvent.content,
181 36 : type: matrixEvent.type,
182 36 : eventId: matrixEvent.eventId,
183 36 : senderId: matrixEvent.senderId,
184 36 : originServerTs: matrixEvent.originServerTs,
185 36 : unsigned: matrixEvent.unsigned,
186 36 : prevContent: matrixEvent.prevContent,
187 36 : stateKey: matrixEvent.stateKey,
188 36 : redacts: matrixEvent.redacts,
189 : room: room,
190 : );
191 :
192 : /// Get a State event from a table row or from the event stream.
193 36 : factory Event.fromJson(
194 : Map<String, dynamic> jsonPayload,
195 : Room room,
196 : ) {
197 72 : final content = Event.getMapFromPayload(jsonPayload['content']);
198 72 : final unsigned = Event.getMapFromPayload(jsonPayload['unsigned']);
199 72 : final prevContent = Event.getMapFromPayload(jsonPayload['prev_content']);
200 : final originalSource =
201 72 : Event.getMapFromPayload(jsonPayload['original_source']);
202 36 : return Event(
203 36 : status: eventStatusFromInt(
204 36 : jsonPayload['status'] ??
205 34 : unsigned[messageSendingStatusKey] ??
206 34 : defaultStatus.intValue,
207 : ),
208 36 : stateKey: jsonPayload['state_key'],
209 : prevContent: prevContent,
210 : content: content,
211 36 : type: jsonPayload['type'],
212 36 : eventId: jsonPayload['event_id'] ?? '',
213 36 : senderId: jsonPayload['sender'],
214 36 : originServerTs: DateTime.fromMillisecondsSinceEpoch(
215 36 : jsonPayload['origin_server_ts'] ?? 0,
216 : ),
217 : unsigned: unsigned,
218 : room: room,
219 36 : redacts: jsonPayload['redacts'],
220 : originalSource:
221 37 : originalSource.isEmpty ? null : MatrixEvent.fromJson(originalSource),
222 : );
223 : }
224 :
225 34 : @override
226 : Map<String, dynamic> toJson() {
227 34 : final data = <String, dynamic>{};
228 98 : if (stateKey != null) data['state_key'] = stateKey;
229 99 : if (prevContent?.isNotEmpty == true) {
230 62 : data['prev_content'] = prevContent;
231 : }
232 68 : data['content'] = content;
233 68 : data['type'] = type;
234 68 : data['event_id'] = eventId;
235 68 : data['room_id'] = roomId;
236 68 : data['sender'] = senderId;
237 102 : data['origin_server_ts'] = originServerTs.millisecondsSinceEpoch;
238 101 : if (unsigned?.isNotEmpty == true) {
239 66 : data['unsigned'] = unsigned;
240 : }
241 34 : if (originalSource != null) {
242 3 : data['original_source'] = originalSource?.toJson();
243 : }
244 102 : data['status'] = status.intValue;
245 : return data;
246 : }
247 :
248 66 : User get asUser => User.fromState(
249 : // state key should always be set for member events
250 33 : stateKey: stateKey!,
251 33 : prevContent: prevContent,
252 33 : content: content,
253 33 : typeKey: type,
254 33 : senderId: senderId,
255 33 : room: room,
256 : );
257 :
258 18 : String get messageType => type == EventTypes.Sticker
259 : ? MessageTypes.Sticker
260 12 : : (content.tryGet<String>('msgtype') ?? MessageTypes.Text);
261 :
262 5 : void setRedactionEvent(Event redactedBecause) {
263 10 : unsigned = {
264 5 : 'redacted_because': redactedBecause.toJson(),
265 : };
266 5 : prevContent = null;
267 5 : _originalSource = null;
268 5 : final contentKeyWhiteList = <String>[];
269 5 : switch (type) {
270 5 : case EventTypes.RoomMember:
271 2 : contentKeyWhiteList.add('membership');
272 : break;
273 5 : case EventTypes.RoomCreate:
274 2 : contentKeyWhiteList.add('creator');
275 : break;
276 5 : case EventTypes.RoomJoinRules:
277 2 : contentKeyWhiteList.add('join_rule');
278 : break;
279 5 : case EventTypes.RoomPowerLevels:
280 2 : contentKeyWhiteList.add('ban');
281 2 : contentKeyWhiteList.add('events');
282 2 : contentKeyWhiteList.add('events_default');
283 2 : contentKeyWhiteList.add('kick');
284 2 : contentKeyWhiteList.add('redact');
285 2 : contentKeyWhiteList.add('state_default');
286 2 : contentKeyWhiteList.add('users');
287 2 : contentKeyWhiteList.add('users_default');
288 : break;
289 5 : case EventTypes.RoomAliases:
290 2 : contentKeyWhiteList.add('aliases');
291 : break;
292 5 : case EventTypes.HistoryVisibility:
293 2 : contentKeyWhiteList.add('history_visibility');
294 : break;
295 : default:
296 : break;
297 : }
298 20 : content.removeWhere((k, v) => !contentKeyWhiteList.contains(k));
299 : }
300 :
301 : /// Returns the body of this event if it has a body.
302 30 : String get text => content.tryGet<String>('body') ?? '';
303 :
304 : /// Returns the formatted boy of this event if it has a formatted body.
305 15 : String get formattedText => content.tryGet<String>('formatted_body') ?? '';
306 :
307 : /// Use this to get the body.
308 10 : String get body {
309 10 : if (redacted) return 'Redacted';
310 30 : if (text != '') return text;
311 2 : return type;
312 : }
313 :
314 : /// Use this to get a plain-text representation of the event, stripping things
315 : /// like spoilers and thelike. Useful for plain text notifications.
316 4 : String get plaintextBody => switch (formattedText) {
317 : // if the formattedText is empty, fallback to body
318 4 : '' => body,
319 8 : final String s when content['format'] == 'org.matrix.custom.html' =>
320 2 : HtmlToText.convert(s),
321 2 : _ => body,
322 : };
323 :
324 : /// Returns a list of [Receipt] instances for this event.
325 3 : List<Receipt> get receipts {
326 3 : final room = this.room;
327 3 : final receipts = room.receiptState;
328 9 : final receiptsList = receipts.global.otherUsers.entries
329 8 : .where((entry) => entry.value.eventId == eventId)
330 3 : .map(
331 2 : (entry) => Receipt(
332 2 : room.unsafeGetUserFromMemoryOrFallback(entry.key),
333 2 : entry.value.timestamp,
334 : ),
335 : )
336 3 : .toList();
337 :
338 : // add your own only once
339 6 : final own = receipts.global.latestOwnReceipt ??
340 3 : receipts.mainThread?.latestOwnReceipt;
341 3 : if (own != null && own.eventId == eventId) {
342 1 : receiptsList.add(
343 1 : Receipt(
344 3 : room.unsafeGetUserFromMemoryOrFallback(room.client.userID!),
345 1 : own.timestamp,
346 : ),
347 : );
348 : }
349 :
350 : // also add main thread. https://github.com/famedly/product-management/issues/1020
351 : // also deduplicate.
352 3 : receiptsList.addAll(
353 5 : receipts.mainThread?.otherUsers.entries
354 1 : .where(
355 1 : (entry) =>
356 4 : entry.value.eventId == eventId &&
357 : receiptsList
358 6 : .every((element) => element.user.id != entry.key),
359 : )
360 1 : .map(
361 2 : (entry) => Receipt(
362 2 : room.unsafeGetUserFromMemoryOrFallback(entry.key),
363 2 : entry.value.timestamp,
364 : ),
365 : ) ??
366 3 : [],
367 : );
368 :
369 : return receiptsList;
370 : }
371 :
372 0 : @Deprecated('Use [cancelSend()] instead.')
373 : Future<bool> remove() async {
374 : try {
375 0 : await cancelSend();
376 : return true;
377 : } catch (_) {
378 : return false;
379 : }
380 : }
381 :
382 : /// Removes an unsent or yet-to-send event from the database and timeline.
383 : /// These are events marked with the status `SENDING` or `ERROR`.
384 : /// Throws an exception if used for an already sent event!
385 : ///
386 6 : Future<void> cancelSend() async {
387 12 : if (status.isSent) {
388 2 : throw Exception('Can only delete events which are not sent yet!');
389 : }
390 :
391 34 : await room.client.database?.removeEvent(eventId, room.id);
392 :
393 22 : if (room.lastEvent != null && room.lastEvent!.eventId == eventId) {
394 2 : final redactedBecause = Event.fromMatrixEvent(
395 2 : MatrixEvent(
396 : type: EventTypes.Redaction,
397 4 : content: {'redacts': eventId},
398 2 : redacts: eventId,
399 2 : senderId: senderId,
400 4 : eventId: '${eventId}_cancel_send',
401 2 : originServerTs: DateTime.now(),
402 : ),
403 2 : room,
404 : );
405 :
406 6 : await room.client.handleSync(
407 2 : SyncUpdate(
408 : nextBatch: '',
409 2 : rooms: RoomsUpdate(
410 2 : join: {
411 6 : room.id: JoinedRoomUpdate(
412 2 : timeline: TimelineUpdate(
413 2 : events: [redactedBecause],
414 : ),
415 : ),
416 : },
417 : ),
418 : ),
419 : );
420 : }
421 30 : room.client.onCancelSendEvent.add(eventId);
422 : }
423 :
424 : /// Try to send this event again. Only works with events of status -1.
425 4 : Future<String?> sendAgain({String? txid}) async {
426 8 : if (!status.isError) return null;
427 :
428 : // Retry sending a file:
429 : if ({
430 4 : MessageTypes.Image,
431 4 : MessageTypes.Video,
432 4 : MessageTypes.Audio,
433 4 : MessageTypes.File,
434 8 : }.contains(messageType)) {
435 0 : final file = room.sendingFilePlaceholders[eventId];
436 : if (file == null) {
437 0 : await cancelSend();
438 0 : throw Exception('Can not try to send again. File is no longer cached.');
439 : }
440 0 : final thumbnail = room.sendingFileThumbnails[eventId];
441 0 : final credentials = FileSendRequestCredentials.fromJson(unsigned ?? {});
442 0 : final inReplyTo = credentials.inReplyTo == null
443 : ? null
444 0 : : await room.getEventById(credentials.inReplyTo!);
445 0 : return await room.sendFileEvent(
446 : file,
447 0 : txid: txid ?? transactionId,
448 : thumbnail: thumbnail,
449 : inReplyTo: inReplyTo,
450 0 : editEventId: credentials.editEventId,
451 0 : shrinkImageMaxDimension: credentials.shrinkImageMaxDimension,
452 0 : extraContent: credentials.extraContent,
453 : );
454 : }
455 :
456 : // we do not remove the event here. It will automatically be updated
457 : // in the `sendEvent` method to transition -1 -> 0 -> 1 -> 2
458 8 : return await room.sendEvent(
459 4 : content,
460 2 : txid: txid ?? transactionId ?? eventId,
461 : );
462 : }
463 :
464 : /// Whether the client is allowed to redact this event.
465 12 : bool get canRedact => senderId == room.client.userID || room.canRedact;
466 :
467 : /// Redacts this event. Throws `ErrorResponse` on error.
468 1 : Future<String?> redactEvent({String? reason, String? txid}) async =>
469 3 : await room.redactEvent(eventId, reason: reason, txid: txid);
470 :
471 : /// Searches for the reply event in the given timeline.
472 0 : Future<Event?> getReplyEvent(Timeline timeline) async {
473 0 : if (relationshipType != RelationshipTypes.reply) return null;
474 0 : final relationshipEventId = this.relationshipEventId;
475 : return relationshipEventId == null
476 : ? null
477 0 : : await timeline.getEventById(relationshipEventId);
478 : }
479 :
480 : /// If this event is encrypted and the decryption was not successful because
481 : /// the session is unknown, this requests the session key from other devices
482 : /// in the room. If the event is not encrypted or the decryption failed because
483 : /// of a different error, this throws an exception.
484 1 : Future<void> requestKey() async {
485 2 : if (type != EventTypes.Encrypted ||
486 2 : messageType != MessageTypes.BadEncrypted ||
487 3 : content['can_request_session'] != true) {
488 : throw ('Session key not requestable');
489 : }
490 :
491 2 : final sessionId = content.tryGet<String>('session_id');
492 2 : final senderKey = content.tryGet<String>('sender_key');
493 : if (sessionId == null || senderKey == null) {
494 : throw ('Unknown session_id or sender_key');
495 : }
496 2 : await room.requestSessionKey(sessionId, senderKey);
497 : return;
498 : }
499 :
500 : /// Gets the info map of file events, or a blank map if none present
501 2 : Map get infoMap =>
502 6 : content.tryGetMap<String, Object?>('info') ?? <String, Object?>{};
503 :
504 : /// Gets the thumbnail info map of file events, or a blank map if nonepresent
505 8 : Map get thumbnailInfoMap => infoMap['thumbnail_info'] is Map
506 4 : ? infoMap['thumbnail_info']
507 1 : : <String, dynamic>{};
508 :
509 : /// Returns if a file event has an attachment
510 11 : bool get hasAttachment => content['url'] is String || content['file'] is Map;
511 :
512 : /// Returns if a file event has a thumbnail
513 2 : bool get hasThumbnail =>
514 12 : infoMap['thumbnail_url'] is String || infoMap['thumbnail_file'] is Map;
515 :
516 : /// Returns if a file events attachment is encrypted
517 8 : bool get isAttachmentEncrypted => content['file'] is Map;
518 :
519 : /// Returns if a file events thumbnail is encrypted
520 8 : bool get isThumbnailEncrypted => infoMap['thumbnail_file'] is Map;
521 :
522 : /// Gets the mimetype of the attachment of a file event, or a blank string if not present
523 8 : String get attachmentMimetype => infoMap['mimetype'] is String
524 6 : ? infoMap['mimetype'].toLowerCase()
525 1 : : (content
526 1 : .tryGetMap<String, Object?>('file')
527 1 : ?.tryGet<String>('mimetype') ??
528 : '');
529 :
530 : /// Gets the mimetype of the thumbnail of a file event, or a blank string if not present
531 8 : String get thumbnailMimetype => thumbnailInfoMap['mimetype'] is String
532 6 : ? thumbnailInfoMap['mimetype'].toLowerCase()
533 3 : : (infoMap['thumbnail_file'] is Map &&
534 4 : infoMap['thumbnail_file']['mimetype'] is String
535 3 : ? infoMap['thumbnail_file']['mimetype']
536 : : '');
537 :
538 : /// Gets the underlying mxc url of an attachment of a file event, or null if not present
539 2 : Uri? get attachmentMxcUrl {
540 2 : final url = isAttachmentEncrypted
541 3 : ? (content.tryGetMap<String, Object?>('file')?['url'])
542 4 : : content['url'];
543 4 : return url is String ? Uri.tryParse(url) : null;
544 : }
545 :
546 : /// Gets the underlying mxc url of a thumbnail of a file event, or null if not present
547 2 : Uri? get thumbnailMxcUrl {
548 2 : final url = isThumbnailEncrypted
549 3 : ? infoMap['thumbnail_file']['url']
550 4 : : infoMap['thumbnail_url'];
551 4 : return url is String ? Uri.tryParse(url) : null;
552 : }
553 :
554 : /// Gets the mxc url of an attachment/thumbnail of a file event, taking sizes into account, or null if not present
555 2 : Uri? attachmentOrThumbnailMxcUrl({bool getThumbnail = false}) {
556 : if (getThumbnail &&
557 6 : infoMap['size'] is int &&
558 6 : thumbnailInfoMap['size'] is int &&
559 0 : infoMap['size'] <= thumbnailInfoMap['size']) {
560 : getThumbnail = false;
561 : }
562 2 : if (getThumbnail && !hasThumbnail) {
563 : getThumbnail = false;
564 : }
565 4 : return getThumbnail ? thumbnailMxcUrl : attachmentMxcUrl;
566 : }
567 :
568 : // size determined from an approximate 800x800 jpeg thumbnail with method=scale
569 : static const _minNoThumbSize = 80 * 1024;
570 :
571 : /// Gets the attachment https URL to display in the timeline, taking into account if the original image is tiny.
572 : /// Returns null for encrypted rooms, if the image can't be fetched via http url or if the event does not contain an attachment.
573 : /// Set [getThumbnail] to true to fetch the thumbnail, set [width], [height] and [method]
574 : /// for the respective thumbnailing properties.
575 : /// [minNoThumbSize] is the minimum size that an original image may be to not fetch its thumbnail, defaults to 80k
576 : /// [useThumbnailMxcUrl] says weather to use the mxc url of the thumbnail, rather than the original attachment.
577 : /// [animated] says weather the thumbnail is animated
578 : ///
579 : /// Throws an exception if the scheme is not `mxc` or the homeserver is not
580 : /// set.
581 : ///
582 : /// Important! To use this link you have to set a http header like this:
583 : /// `headers: {"authorization": "Bearer ${client.accessToken}"}`
584 2 : Future<Uri?> getAttachmentUri({
585 : bool getThumbnail = false,
586 : bool useThumbnailMxcUrl = false,
587 : double width = 800.0,
588 : double height = 800.0,
589 : ThumbnailMethod method = ThumbnailMethod.scale,
590 : int minNoThumbSize = _minNoThumbSize,
591 : bool animated = false,
592 : }) async {
593 6 : if (![EventTypes.Message, EventTypes.Sticker].contains(type) ||
594 2 : !hasAttachment ||
595 2 : isAttachmentEncrypted) {
596 : return null; // can't url-thumbnail in encrypted rooms
597 : }
598 2 : if (useThumbnailMxcUrl && !hasThumbnail) {
599 : return null; // can't fetch from thumbnail
600 : }
601 4 : final thisInfoMap = useThumbnailMxcUrl ? thumbnailInfoMap : infoMap;
602 : final thisMxcUrl =
603 8 : useThumbnailMxcUrl ? infoMap['thumbnail_url'] : content['url'];
604 : // if we have as method scale, we can return safely the original image, should it be small enough
605 : if (getThumbnail &&
606 2 : method == ThumbnailMethod.scale &&
607 4 : thisInfoMap['size'] is int &&
608 4 : thisInfoMap['size'] < minNoThumbSize) {
609 : getThumbnail = false;
610 : }
611 : // now generate the actual URLs
612 : if (getThumbnail) {
613 4 : return await Uri.parse(thisMxcUrl).getThumbnailUri(
614 4 : room.client,
615 : width: width,
616 : height: height,
617 : method: method,
618 : animated: animated,
619 : );
620 : } else {
621 8 : return await Uri.parse(thisMxcUrl).getDownloadUri(room.client);
622 : }
623 : }
624 :
625 : /// Gets the attachment https URL to display in the timeline, taking into account if the original image is tiny.
626 : /// Returns null for encrypted rooms, if the image can't be fetched via http url or if the event does not contain an attachment.
627 : /// Set [getThumbnail] to true to fetch the thumbnail, set [width], [height] and [method]
628 : /// for the respective thumbnailing properties.
629 : /// [minNoThumbSize] is the minimum size that an original image may be to not fetch its thumbnail, defaults to 80k
630 : /// [useThumbnailMxcUrl] says weather to use the mxc url of the thumbnail, rather than the original attachment.
631 : /// [animated] says weather the thumbnail is animated
632 : ///
633 : /// Throws an exception if the scheme is not `mxc` or the homeserver is not
634 : /// set.
635 : ///
636 : /// Important! To use this link you have to set a http header like this:
637 : /// `headers: {"authorization": "Bearer ${client.accessToken}"}`
638 0 : @Deprecated('Use getAttachmentUri() instead')
639 : Uri? getAttachmentUrl({
640 : bool getThumbnail = false,
641 : bool useThumbnailMxcUrl = false,
642 : double width = 800.0,
643 : double height = 800.0,
644 : ThumbnailMethod method = ThumbnailMethod.scale,
645 : int minNoThumbSize = _minNoThumbSize,
646 : bool animated = false,
647 : }) {
648 0 : if (![EventTypes.Message, EventTypes.Sticker].contains(type) ||
649 0 : !hasAttachment ||
650 0 : isAttachmentEncrypted) {
651 : return null; // can't url-thumbnail in encrypted rooms
652 : }
653 0 : if (useThumbnailMxcUrl && !hasThumbnail) {
654 : return null; // can't fetch from thumbnail
655 : }
656 0 : final thisInfoMap = useThumbnailMxcUrl ? thumbnailInfoMap : infoMap;
657 : final thisMxcUrl =
658 0 : useThumbnailMxcUrl ? infoMap['thumbnail_url'] : content['url'];
659 : // if we have as method scale, we can return safely the original image, should it be small enough
660 : if (getThumbnail &&
661 0 : method == ThumbnailMethod.scale &&
662 0 : thisInfoMap['size'] is int &&
663 0 : thisInfoMap['size'] < minNoThumbSize) {
664 : getThumbnail = false;
665 : }
666 : // now generate the actual URLs
667 : if (getThumbnail) {
668 0 : return Uri.parse(thisMxcUrl).getThumbnail(
669 0 : room.client,
670 : width: width,
671 : height: height,
672 : method: method,
673 : animated: animated,
674 : );
675 : } else {
676 0 : return Uri.parse(thisMxcUrl).getDownloadLink(room.client);
677 : }
678 : }
679 :
680 : /// Returns if an attachment is in the local store
681 1 : Future<bool> isAttachmentInLocalStore({bool getThumbnail = false}) async {
682 3 : if (![EventTypes.Message, EventTypes.Sticker].contains(type)) {
683 0 : throw ("This event has the type '$type' and so it can't contain an attachment.");
684 : }
685 1 : final mxcUrl = attachmentOrThumbnailMxcUrl(getThumbnail: getThumbnail);
686 : if (mxcUrl == null) {
687 : throw "This event hasn't any attachment or thumbnail.";
688 : }
689 2 : getThumbnail = mxcUrl != attachmentMxcUrl;
690 : // Is this file storeable?
691 1 : final thisInfoMap = getThumbnail ? thumbnailInfoMap : infoMap;
692 3 : final database = room.client.database;
693 : if (database == null) {
694 : return false;
695 : }
696 :
697 2 : final storeable = thisInfoMap['size'] is int &&
698 3 : thisInfoMap['size'] <= database.maxFileSize;
699 :
700 : Uint8List? uint8list;
701 : if (storeable) {
702 0 : uint8list = await database.getFile(mxcUrl);
703 : }
704 : return uint8list != null;
705 : }
706 :
707 : /// Downloads (and decrypts if necessary) the attachment of this
708 : /// event and returns it as a [MatrixFile]. If this event doesn't
709 : /// contain an attachment, this throws an error. Set [getThumbnail] to
710 : /// true to download the thumbnail instead. Set [fromLocalStoreOnly] to true
711 : /// if you want to retrieve the attachment from the local store only without
712 : /// making http request.
713 2 : Future<MatrixFile> downloadAndDecryptAttachment({
714 : bool getThumbnail = false,
715 : Future<Uint8List> Function(Uri)? downloadCallback,
716 : bool fromLocalStoreOnly = false,
717 : }) async {
718 6 : if (![EventTypes.Message, EventTypes.Sticker].contains(type)) {
719 0 : throw ("This event has the type '$type' and so it can't contain an attachment.");
720 : }
721 4 : if (status.isSending) {
722 0 : final localFile = room.sendingFilePlaceholders[eventId];
723 : if (localFile != null) return localFile;
724 : }
725 6 : final database = room.client.database;
726 2 : final mxcUrl = attachmentOrThumbnailMxcUrl(getThumbnail: getThumbnail);
727 : if (mxcUrl == null) {
728 : throw "This event hasn't any attachment or thumbnail.";
729 : }
730 4 : getThumbnail = mxcUrl != attachmentMxcUrl;
731 : final isEncrypted =
732 4 : getThumbnail ? isThumbnailEncrypted : isAttachmentEncrypted;
733 3 : if (isEncrypted && !room.client.encryptionEnabled) {
734 : throw ('Encryption is not enabled in your Client.');
735 : }
736 :
737 : // Is this file storeable?
738 4 : final thisInfoMap = getThumbnail ? thumbnailInfoMap : infoMap;
739 : var storeable = database != null &&
740 2 : thisInfoMap['size'] is int &&
741 3 : thisInfoMap['size'] <= database.maxFileSize;
742 :
743 : Uint8List? uint8list;
744 : if (storeable) {
745 0 : uint8list = await room.client.database?.getFile(mxcUrl);
746 : }
747 :
748 : // Download the file
749 : final canDownloadFileFromServer = uint8list == null && !fromLocalStoreOnly;
750 : if (canDownloadFileFromServer) {
751 6 : final httpClient = room.client.httpClient;
752 0 : downloadCallback ??= (Uri url) async => (await httpClient.get(
753 : url,
754 0 : headers: {'authorization': 'Bearer ${room.client.accessToken}'},
755 : ))
756 0 : .bodyBytes;
757 : uint8list =
758 8 : await downloadCallback(await mxcUrl.getDownloadUri(room.client));
759 : storeable = database != null &&
760 : storeable &&
761 0 : uint8list.lengthInBytes < database.maxFileSize;
762 : if (storeable) {
763 0 : await database.storeFile(
764 : mxcUrl,
765 : uint8list,
766 0 : DateTime.now().millisecondsSinceEpoch,
767 : );
768 : }
769 : } else if (uint8list == null) {
770 : throw ('Unable to download file from local store.');
771 : }
772 :
773 : // Decrypt the file
774 : if (isEncrypted) {
775 : final fileMap =
776 4 : getThumbnail ? infoMap['thumbnail_file'] : content['file'];
777 3 : if (!fileMap['key']['key_ops'].contains('decrypt')) {
778 : throw ("Missing 'decrypt' in 'key_ops'.");
779 : }
780 1 : final encryptedFile = EncryptedFile(
781 : data: uint8list,
782 1 : iv: fileMap['iv'],
783 2 : k: fileMap['key']['k'],
784 2 : sha256: fileMap['hashes']['sha256'],
785 : );
786 : uint8list =
787 4 : await room.client.nativeImplementations.decryptFile(encryptedFile);
788 : if (uint8list == null) {
789 : throw ('Unable to decrypt file');
790 : }
791 : }
792 4 : return MatrixFile(bytes: uint8list, name: body);
793 : }
794 :
795 : /// Returns if this is a known event type.
796 2 : bool get isEventTypeKnown =>
797 6 : EventLocalizations.localizationsMap.containsKey(type);
798 :
799 : /// Returns a localized String representation of this event. For a
800 : /// room list you may find [withSenderNamePrefix] useful. Set [hideReply] to
801 : /// crop all lines starting with '>'. With [plaintextBody] it'll use the
802 : /// plaintextBody instead of the normal body which in practice will convert
803 : /// the html body to a plain text body before falling back to the body. In
804 : /// either case this function won't return the html body without converting
805 : /// it to plain text.
806 : /// [removeMarkdown] allow to remove the markdown formating from the event body.
807 : /// Usefull form message preview or notifications text.
808 4 : Future<String> calcLocalizedBody(
809 : MatrixLocalizations i18n, {
810 : bool withSenderNamePrefix = false,
811 : bool hideReply = false,
812 : bool hideEdit = false,
813 : bool plaintextBody = false,
814 : bool removeMarkdown = false,
815 : }) async {
816 4 : if (redacted) {
817 8 : await redactedBecause?.fetchSenderUser();
818 : }
819 :
820 : if (withSenderNamePrefix &&
821 4 : (type == EventTypes.Message || type.contains(EventTypes.Encrypted))) {
822 : // To be sure that if the event need to be localized, the user is in memory.
823 : // used by EventLocalizations._localizedBodyNormalMessage
824 2 : await fetchSenderUser();
825 : }
826 :
827 4 : return calcLocalizedBodyFallback(
828 : i18n,
829 : withSenderNamePrefix: withSenderNamePrefix,
830 : hideReply: hideReply,
831 : hideEdit: hideEdit,
832 : plaintextBody: plaintextBody,
833 : removeMarkdown: removeMarkdown,
834 : );
835 : }
836 :
837 0 : @Deprecated('Use calcLocalizedBody or calcLocalizedBodyFallback')
838 : String getLocalizedBody(
839 : MatrixLocalizations i18n, {
840 : bool withSenderNamePrefix = false,
841 : bool hideReply = false,
842 : bool hideEdit = false,
843 : bool plaintextBody = false,
844 : bool removeMarkdown = false,
845 : }) =>
846 0 : calcLocalizedBodyFallback(
847 : i18n,
848 : withSenderNamePrefix: withSenderNamePrefix,
849 : hideReply: hideReply,
850 : hideEdit: hideEdit,
851 : plaintextBody: plaintextBody,
852 : removeMarkdown: removeMarkdown,
853 : );
854 :
855 : /// Works similar to `calcLocalizedBody()` but does not wait for the sender
856 : /// user to be fetched. If it is not in the cache it will just use the
857 : /// fallback and display the localpart of the MXID according to the
858 : /// values of `formatLocalpart` and `mxidLocalPartFallback` in the `Client`
859 : /// class.
860 4 : String calcLocalizedBodyFallback(
861 : MatrixLocalizations i18n, {
862 : bool withSenderNamePrefix = false,
863 : bool hideReply = false,
864 : bool hideEdit = false,
865 : bool plaintextBody = false,
866 : bool removeMarkdown = false,
867 : }) {
868 4 : if (redacted) {
869 16 : if (status.intValue < EventStatus.synced.intValue) {
870 2 : return i18n.cancelledSend;
871 : }
872 2 : return i18n.removedBy(this);
873 : }
874 :
875 2 : final body = calcUnlocalizedBody(
876 : hideReply: hideReply,
877 : hideEdit: hideEdit,
878 : plaintextBody: plaintextBody,
879 : removeMarkdown: removeMarkdown,
880 : );
881 :
882 6 : final callback = EventLocalizations.localizationsMap[type];
883 4 : var localizedBody = i18n.unknownEvent(type);
884 : if (callback != null) {
885 2 : localizedBody = callback(this, i18n, body);
886 : }
887 :
888 : // Add the sender name prefix
889 : if (withSenderNamePrefix &&
890 4 : type == EventTypes.Message &&
891 4 : textOnlyMessageTypes.contains(messageType)) {
892 10 : final senderNameOrYou = senderId == room.client.userID
893 0 : ? i18n.you
894 4 : : senderFromMemoryOrFallback.calcDisplayname(i18n: i18n);
895 2 : localizedBody = '$senderNameOrYou: $localizedBody';
896 : }
897 :
898 : return localizedBody;
899 : }
900 :
901 : /// Calculating the body of an event regardless of localization.
902 2 : String calcUnlocalizedBody({
903 : bool hideReply = false,
904 : bool hideEdit = false,
905 : bool plaintextBody = false,
906 : bool removeMarkdown = false,
907 : }) {
908 2 : if (redacted) {
909 0 : return 'Removed by ${senderFromMemoryOrFallback.displayName ?? senderId}';
910 : }
911 4 : var body = plaintextBody ? this.plaintextBody : this.body;
912 :
913 : // Html messages will already have their reply fallback removed during the Html to Text conversion.
914 : var mayHaveReplyFallback = !plaintextBody ||
915 6 : (content['format'] != 'org.matrix.custom.html' ||
916 4 : formattedText.isEmpty);
917 :
918 : // If we have an edit, we want to operate on the new content
919 4 : final newContent = content.tryGetMap<String, Object?>('m.new_content');
920 : if (hideEdit &&
921 4 : relationshipType == RelationshipTypes.edit &&
922 : newContent != null) {
923 : final newBody =
924 2 : newContent.tryGet<String>('formatted_body', TryGet.silent);
925 : if (plaintextBody &&
926 4 : newContent['format'] == 'org.matrix.custom.html' &&
927 : newBody != null &&
928 2 : newBody.isNotEmpty) {
929 : mayHaveReplyFallback = false;
930 2 : body = HtmlToText.convert(newBody);
931 : } else {
932 : mayHaveReplyFallback = true;
933 2 : body = newContent.tryGet<String>('body') ?? body;
934 : }
935 : }
936 : // Hide reply fallback
937 : // Be sure that the plaintextBody already stripped teh reply fallback,
938 : // if the message is formatted
939 : if (hideReply && mayHaveReplyFallback) {
940 2 : body = body.replaceFirst(
941 2 : RegExp(r'^>( \*)? <[^>]+>[^\n\r]+\r?\n(> [^\n]*\r?\n)*\r?\n'),
942 : '',
943 : );
944 : }
945 :
946 : // return the html tags free body
947 2 : if (removeMarkdown == true) {
948 2 : final html = markdown(body, convertLinebreaks: false);
949 2 : final document = parse(
950 : html,
951 : );
952 4 : body = document.documentElement?.text ?? body;
953 : }
954 : return body;
955 : }
956 :
957 : static const Set<String> textOnlyMessageTypes = {
958 : MessageTypes.Text,
959 : MessageTypes.Notice,
960 : MessageTypes.Emote,
961 : MessageTypes.None,
962 : };
963 :
964 : /// returns if this event matches the passed event or transaction id
965 4 : bool matchesEventOrTransactionId(String? search) {
966 : if (search == null) {
967 : return false;
968 : }
969 8 : if (eventId == search) {
970 : return true;
971 : }
972 8 : return transactionId == search;
973 : }
974 :
975 : /// Get the relationship type of an event. `null` if there is none
976 33 : String? get relationshipType {
977 66 : final mRelatesTo = content.tryGetMap<String, Object?>('m.relates_to');
978 : if (mRelatesTo == null) {
979 : return null;
980 : }
981 7 : final relType = mRelatesTo.tryGet<String>('rel_type');
982 7 : if (relType == RelationshipTypes.thread) {
983 : return RelationshipTypes.thread;
984 : }
985 :
986 7 : if (mRelatesTo.containsKey('m.in_reply_to')) {
987 : return RelationshipTypes.reply;
988 : }
989 : return relType;
990 : }
991 :
992 : /// Get the event ID that this relationship will reference. `null` if there is none
993 9 : String? get relationshipEventId {
994 18 : final relatesToMap = content.tryGetMap<String, Object?>('m.relates_to');
995 5 : return relatesToMap?.tryGet<String>('event_id') ??
996 : relatesToMap
997 4 : ?.tryGetMap<String, Object?>('m.in_reply_to')
998 4 : ?.tryGet<String>('event_id');
999 : }
1000 :
1001 : /// Get whether this event has aggregated events from a certain [type]
1002 : /// To be able to do that you need to pass a [timeline]
1003 2 : bool hasAggregatedEvents(Timeline timeline, String type) =>
1004 10 : timeline.aggregatedEvents[eventId]?.containsKey(type) == true;
1005 :
1006 : /// Get all the aggregated event objects for a given [type]. To be able to do this
1007 : /// you have to pass a [timeline]
1008 2 : Set<Event> aggregatedEvents(Timeline timeline, String type) =>
1009 8 : timeline.aggregatedEvents[eventId]?[type] ?? <Event>{};
1010 :
1011 : /// Fetches the event to be rendered, taking into account all the edits and the like.
1012 : /// It needs a [timeline] for that.
1013 2 : Event getDisplayEvent(Timeline timeline) {
1014 2 : if (redacted) {
1015 : return this;
1016 : }
1017 2 : if (hasAggregatedEvents(timeline, RelationshipTypes.edit)) {
1018 : // alright, we have an edit
1019 2 : final allEditEvents = aggregatedEvents(timeline, RelationshipTypes.edit)
1020 : // we only allow edits made by the original author themself
1021 14 : .where((e) => e.senderId == senderId && e.type == EventTypes.Message)
1022 2 : .toList();
1023 : // we need to check again if it isn't empty, as we potentially removed all
1024 : // aggregated edits
1025 2 : if (allEditEvents.isNotEmpty) {
1026 2 : allEditEvents.sort(
1027 8 : (a, b) => a.originServerTs.millisecondsSinceEpoch -
1028 6 : b.originServerTs.millisecondsSinceEpoch >
1029 : 0
1030 : ? 1
1031 2 : : -1,
1032 : );
1033 4 : final rawEvent = allEditEvents.last.toJson();
1034 : // update the content of the new event to render
1035 6 : if (rawEvent['content']['m.new_content'] is Map) {
1036 6 : rawEvent['content'] = rawEvent['content']['m.new_content'];
1037 : }
1038 4 : return Event.fromJson(rawEvent, room);
1039 : }
1040 : }
1041 : return this;
1042 : }
1043 :
1044 : /// returns if a message is a rich message
1045 2 : bool get isRichMessage =>
1046 6 : content['format'] == 'org.matrix.custom.html' &&
1047 6 : content['formatted_body'] is String;
1048 :
1049 : // regexes to fetch the number of emotes, including emoji, and if the message consists of only those
1050 : // to match an emoji we can use the following regularly updated regex : https://stackoverflow.com/a/67705964
1051 : // to see if there is a custom emote, we use the following regex: <img[^>]+data-mx-(?:emote|emoticon)(?==|>|\s)[^>]*>
1052 : // now we combined the two to have four regexes and one helper:
1053 : // 0. the raw components
1054 : // - the pure unicode sequence from the link above and
1055 : // - the padded sequence with whitespace, option selection and copyright/tm sign
1056 : // - the matrix emoticon sequence
1057 : // 1. are there only emoji, or whitespace
1058 : // 2. are there only emoji, emotes, or whitespace
1059 : // 3. count number of emoji
1060 : // 4. count number of emoji or emotes
1061 :
1062 : // update from : https://stackoverflow.com/a/67705964
1063 : static const _unicodeSequences =
1064 : r'\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]';
1065 : // the above sequence but with copyright, trade mark sign and option selection
1066 : static const _paddedUnicodeSequence =
1067 : r'(?:\u00a9|\u00ae|' + _unicodeSequences + r')[\ufe00-\ufe0f]?';
1068 : // should match a <img> tag with the matrix emote/emoticon attribute set
1069 : static const _matrixEmoticonSequence =
1070 : r'<img[^>]+data-mx-(?:emote|emoticon)(?==|>|\s)[^>]*>';
1071 :
1072 6 : static final RegExp _onlyEmojiRegex = RegExp(
1073 4 : r'^(' + _paddedUnicodeSequence + r'|\s)*$',
1074 : caseSensitive: false,
1075 : multiLine: false,
1076 : );
1077 6 : static final RegExp _onlyEmojiEmoteRegex = RegExp(
1078 8 : r'^(' + _paddedUnicodeSequence + r'|' + _matrixEmoticonSequence + r'|\s)*$',
1079 : caseSensitive: false,
1080 : multiLine: false,
1081 : );
1082 6 : static final RegExp _countEmojiRegex = RegExp(
1083 4 : r'(' + _paddedUnicodeSequence + r')',
1084 : caseSensitive: false,
1085 : multiLine: false,
1086 : );
1087 6 : static final RegExp _countEmojiEmoteRegex = RegExp(
1088 8 : r'(' + _paddedUnicodeSequence + r'|' + _matrixEmoticonSequence + r')',
1089 : caseSensitive: false,
1090 : multiLine: false,
1091 : );
1092 :
1093 : /// Returns if a given event only has emotes, emojis or whitespace as content.
1094 : /// If the body contains a reply then it is stripped.
1095 : /// This is useful to determine if stand-alone emotes should be displayed bigger.
1096 2 : bool get onlyEmotes {
1097 2 : if (isRichMessage) {
1098 : // calcUnlocalizedBody strips out the <img /> tags in favor of a :placeholder:
1099 4 : final formattedTextStripped = formattedText.replaceAll(
1100 2 : RegExp(
1101 : '<mx-reply>.*</mx-reply>',
1102 : caseSensitive: false,
1103 : multiLine: false,
1104 : dotAll: true,
1105 : ),
1106 : '',
1107 : );
1108 4 : return _onlyEmojiEmoteRegex.hasMatch(formattedTextStripped);
1109 : } else {
1110 6 : return _onlyEmojiRegex.hasMatch(plaintextBody);
1111 : }
1112 : }
1113 :
1114 : /// Gets the number of emotes in a given message. This is useful to determine
1115 : /// if the emotes should be displayed bigger.
1116 : /// If the body contains a reply then it is stripped.
1117 : /// WARNING: This does **not** test if there are only emotes. Use `event.onlyEmotes` for that!
1118 2 : int get numberEmotes {
1119 2 : if (isRichMessage) {
1120 : // calcUnlocalizedBody strips out the <img /> tags in favor of a :placeholder:
1121 4 : final formattedTextStripped = formattedText.replaceAll(
1122 2 : RegExp(
1123 : '<mx-reply>.*</mx-reply>',
1124 : caseSensitive: false,
1125 : multiLine: false,
1126 : dotAll: true,
1127 : ),
1128 : '',
1129 : );
1130 6 : return _countEmojiEmoteRegex.allMatches(formattedTextStripped).length;
1131 : } else {
1132 8 : return _countEmojiRegex.allMatches(plaintextBody).length;
1133 : }
1134 : }
1135 :
1136 : /// If this event is in Status SENDING and it aims to send a file, then this
1137 : /// shows the status of the file sending.
1138 0 : FileSendingStatus? get fileSendingStatus {
1139 0 : final status = unsigned?.tryGet<String>(fileSendingStatusKey);
1140 : if (status == null) return null;
1141 0 : return FileSendingStatus.values.singleWhereOrNull(
1142 0 : (fileSendingStatus) => fileSendingStatus.name == status,
1143 : );
1144 : }
1145 : }
1146 :
1147 : enum FileSendingStatus {
1148 : generatingThumbnail,
1149 : encrypting,
1150 : uploading,
1151 : }
|