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