LCOV - code coverage report
Current view: top level - lib/src - event.dart (source / functions) Coverage Total Hit
Test: merged.info Lines: 86.1 % 454 391
Test Date: 2025-06-22 15:00:10 Functions: - 0 0

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

Generated by: LCOV version 2.0-1