LCOV - code coverage report
Current view: top level - lib/src - room.dart (source / functions) Coverage Total Hit
Test: merged.info Lines: 74.4 % 969 721
Test Date: 2025-02-03 13:08:23 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:async';
      20              : import 'dart:convert';
      21              : import 'dart:math';
      22              : 
      23              : import 'package:async/async.dart';
      24              : import 'package:collection/collection.dart';
      25              : import 'package:html_unescape/html_unescape.dart';
      26              : 
      27              : import 'package:matrix/matrix.dart';
      28              : import 'package:matrix/src/models/timeline_chunk.dart';
      29              : import 'package:matrix/src/utils/cached_stream_controller.dart';
      30              : import 'package:matrix/src/utils/file_send_request_credentials.dart';
      31              : import 'package:matrix/src/utils/markdown.dart';
      32              : import 'package:matrix/src/utils/marked_unread.dart';
      33              : import 'package:matrix/src/utils/space_child.dart';
      34              : 
      35              : /// max PDU size for server to accept the event with some buffer incase the server adds unsigned data f.ex age
      36              : /// https://spec.matrix.org/v1.9/client-server-api/#size-limits
      37              : const int maxPDUSize = 60000;
      38              : 
      39              : const String messageSendingStatusKey =
      40              :     'com.famedly.famedlysdk.message_sending_status';
      41              : 
      42              : const String fileSendingStatusKey =
      43              :     'com.famedly.famedlysdk.file_sending_status';
      44              : 
      45              : /// Represents a Matrix room.
      46              : class Room {
      47              :   /// The full qualified Matrix ID for the room in the format '!localid:server.abc'.
      48              :   final String id;
      49              : 
      50              :   /// Membership status of the user for this room.
      51              :   Membership membership;
      52              : 
      53              :   /// The count of unread notifications.
      54              :   int notificationCount;
      55              : 
      56              :   /// The count of highlighted notifications.
      57              :   int highlightCount;
      58              : 
      59              :   /// A token that can be supplied to the from parameter of the rooms/{roomId}/messages endpoint.
      60              :   String? prev_batch;
      61              : 
      62              :   RoomSummary summary;
      63              : 
      64              :   /// The room states are a key value store of the key (`type`,`state_key`) => State(event).
      65              :   /// In a lot of cases the `state_key` might be an empty string. You **should** use the
      66              :   /// methods `getState()` and `setState()` to interact with the room states.
      67              :   Map<String, Map<String, StrippedStateEvent>> states = {};
      68              : 
      69              :   /// Key-Value store for ephemerals.
      70              :   Map<String, BasicEvent> ephemerals = {};
      71              : 
      72              :   /// Key-Value store for private account data only visible for this user.
      73              :   Map<String, BasicEvent> roomAccountData = {};
      74              : 
      75              :   final _sendingQueue = <Completer>[];
      76              : 
      77              :   Timer? _clearTypingIndicatorTimer;
      78              : 
      79           64 :   Map<String, dynamic> toJson() => {
      80           32 :         'id': id,
      81          128 :         'membership': membership.toString().split('.').last,
      82           32 :         'highlight_count': highlightCount,
      83           32 :         'notification_count': notificationCount,
      84           32 :         'prev_batch': prev_batch,
      85           64 :         'summary': summary.toJson(),
      86           63 :         'last_event': lastEvent?.toJson(),
      87              :       };
      88              : 
      89           13 :   factory Room.fromJson(Map<String, dynamic> json, Client client) {
      90           13 :     final room = Room(
      91              :       client: client,
      92           13 :       id: json['id'],
      93           13 :       membership: Membership.values.singleWhere(
      94           65 :         (m) => m.toString() == 'Membership.${json['membership']}',
      95            0 :         orElse: () => Membership.join,
      96              :       ),
      97           13 :       notificationCount: json['notification_count'],
      98           13 :       highlightCount: json['highlight_count'],
      99           13 :       prev_batch: json['prev_batch'],
     100           39 :       summary: RoomSummary.fromJson(Map<String, dynamic>.from(json['summary'])),
     101              :     );
     102           13 :     if (json['last_event'] != null) {
     103           36 :       room.lastEvent = Event.fromJson(json['last_event'], room);
     104              :     }
     105              :     return room;
     106              :   }
     107              : 
     108              :   /// Flag if the room is partial, meaning not all state events have been loaded yet
     109              :   bool partial = true;
     110              : 
     111              :   /// Post-loads the room.
     112              :   /// This load all the missing state events for the room from the database
     113              :   /// If the room has already been loaded, this does nothing.
     114            5 :   Future<void> postLoad() async {
     115            5 :     if (!partial) {
     116              :       return;
     117              :     }
     118              :     final allStates =
     119           15 :         await client.database?.getUnimportantRoomEventStatesForRoom(
     120           15 :       client.importantStateEvents.toList(),
     121              :       this,
     122              :     );
     123              : 
     124              :     if (allStates != null) {
     125            8 :       for (final state in allStates) {
     126            3 :         setState(state);
     127              :       }
     128              :     }
     129            5 :     partial = false;
     130              :   }
     131              : 
     132              :   /// Returns the [Event] for the given [typeKey] and optional [stateKey].
     133              :   /// If no [stateKey] is provided, it defaults to an empty string.
     134              :   /// This returns either a `StrippedStateEvent` for rooms with membership
     135              :   /// "invite" or a `User`/`Event`. If you need additional information like
     136              :   /// the Event ID or originServerTs you need to do a type check like:
     137              :   /// ```dart
     138              :   /// if (state is Event) { /*...*/ }
     139              :   /// ```
     140           34 :   StrippedStateEvent? getState(String typeKey, [String stateKey = '']) =>
     141          102 :       states[typeKey]?[stateKey];
     142              : 
     143              :   /// Adds the [state] to this room and overwrites a state with the same
     144              :   /// typeKey/stateKey key pair if there is one.
     145           34 :   void setState(StrippedStateEvent state) {
     146              :     // Ignore other non-state events
     147           34 :     final stateKey = state.stateKey;
     148              : 
     149              :     // For non invite rooms this is usually an Event and we should validate
     150              :     // the room ID:
     151           34 :     if (state is Event) {
     152           34 :       final roomId = state.roomId;
     153           68 :       if (roomId != id) {
     154            0 :         Logs().wtf('Tried to set state event for wrong room!');
     155            0 :         assert(roomId == id);
     156              :         return;
     157              :       }
     158              :     }
     159              : 
     160              :     if (stateKey == null) {
     161            6 :       Logs().w(
     162            6 :         'Tried to set a non state event with type "${state.type}" as state event for a room',
     163              :       );
     164            3 :       assert(stateKey != null);
     165              :       return;
     166              :     }
     167              : 
     168          170 :     (states[state.type] ??= {})[stateKey] = state;
     169              : 
     170          136 :     client.onRoomState.add((roomId: id, state: state));
     171              :   }
     172              : 
     173              :   /// ID of the fully read marker event.
     174            3 :   String get fullyRead =>
     175           10 :       roomAccountData['m.fully_read']?.content.tryGet<String>('event_id') ?? '';
     176              : 
     177              :   /// If something changes, this callback will be triggered. Will return the
     178              :   /// room id.
     179              :   @Deprecated('Use `client.onSync` instead and filter for this room ID')
     180              :   final CachedStreamController<String> onUpdate = CachedStreamController();
     181              : 
     182              :   /// If there is a new session key received, this will be triggered with
     183              :   /// the session ID.
     184              :   final CachedStreamController<String> onSessionKeyReceived =
     185              :       CachedStreamController();
     186              : 
     187              :   /// The name of the room if set by a participant.
     188            8 :   String get name {
     189           20 :     final n = getState(EventTypes.RoomName)?.content['name'];
     190            8 :     return (n is String) ? n : '';
     191              :   }
     192              : 
     193              :   /// The pinned events for this room. If there are none this returns an empty
     194              :   /// list.
     195            2 :   List<String> get pinnedEventIds {
     196            6 :     final pinned = getState(EventTypes.RoomPinnedEvents)?.content['pinned'];
     197           12 :     return pinned is Iterable ? pinned.map((e) => e.toString()).toList() : [];
     198              :   }
     199              : 
     200              :   /// Returns the heroes as `User` objects.
     201              :   /// This is very useful if you want to make sure that all users are loaded
     202              :   /// from the database, that you need to correctly calculate the displayname
     203              :   /// and the avatar of the room.
     204            2 :   Future<List<User>> loadHeroUsers() async {
     205              :     // For invite rooms request own user and invitor.
     206            4 :     if (membership == Membership.invite) {
     207            0 :       final ownUser = await requestUser(client.userID!, requestProfile: false);
     208            0 :       if (ownUser != null) await requestUser(ownUser.senderId);
     209              :     }
     210              : 
     211            4 :     var heroes = summary.mHeroes;
     212              :     if (heroes == null) {
     213            0 :       final directChatMatrixID = this.directChatMatrixID;
     214              :       if (directChatMatrixID != null) {
     215            0 :         heroes = [directChatMatrixID];
     216              :       }
     217              :     }
     218              : 
     219            0 :     if (heroes == null) return [];
     220              : 
     221            2 :     return await Future.wait(
     222            2 :       heroes.map(
     223            2 :         (hero) async =>
     224            2 :             (await requestUser(
     225              :               hero,
     226              :               ignoreErrors: true,
     227              :             )) ??
     228            0 :             User(hero, room: this),
     229              :       ),
     230              :     );
     231              :   }
     232              : 
     233              :   /// Returns a localized displayname for this server. If the room is a groupchat
     234              :   /// without a name, then it will return the localized version of 'Group with Alice' instead
     235              :   /// of just 'Alice' to make it different to a direct chat.
     236              :   /// Empty chats will become the localized version of 'Empty Chat'.
     237              :   /// Please note, that necessary room members are lazy loaded. To be sure
     238              :   /// that you have the room members, call and await `Room.loadHeroUsers()`
     239              :   /// before.
     240              :   /// This method requires a localization class which implements [MatrixLocalizations]
     241            4 :   String getLocalizedDisplayname([
     242              :     MatrixLocalizations i18n = const MatrixDefaultLocalizations(),
     243              :   ]) {
     244           10 :     if (name.isNotEmpty) return name;
     245              : 
     246            8 :     final canonicalAlias = this.canonicalAlias.localpart;
     247            2 :     if (canonicalAlias != null && canonicalAlias.isNotEmpty) {
     248              :       return canonicalAlias;
     249              :     }
     250              : 
     251            4 :     final directChatMatrixID = this.directChatMatrixID;
     252            8 :     final heroes = summary.mHeroes ?? [];
     253            0 :     if (directChatMatrixID != null && heroes.isEmpty) {
     254            0 :       heroes.add(directChatMatrixID);
     255              :     }
     256            4 :     if (heroes.isNotEmpty) {
     257              :       final result = heroes
     258            2 :           .where(
     259              :             // removing oneself from the hero list
     260           10 :             (hero) => hero.isNotEmpty && hero != client.userID,
     261              :           )
     262            2 :           .map(
     263            4 :             (hero) => unsafeGetUserFromMemoryOrFallback(hero)
     264            2 :                 .calcDisplayname(i18n: i18n),
     265              :           )
     266            2 :           .join(', ');
     267            2 :       if (isAbandonedDMRoom) {
     268            0 :         return i18n.wasDirectChatDisplayName(result);
     269              :       }
     270              : 
     271            4 :       return isDirectChat ? result : i18n.groupWith(result);
     272              :     }
     273            4 :     if (membership == Membership.invite) {
     274            0 :       final ownMember = unsafeGetUserFromMemoryOrFallback(client.userID!);
     275              : 
     276            0 :       if (ownMember.senderId != ownMember.stateKey) {
     277            0 :         return i18n.invitedBy(
     278            0 :           unsafeGetUserFromMemoryOrFallback(ownMember.senderId)
     279            0 :               .calcDisplayname(i18n: i18n),
     280              :         );
     281              :       }
     282              :     }
     283            4 :     if (membership == Membership.leave) {
     284              :       if (directChatMatrixID != null) {
     285            0 :         return i18n.wasDirectChatDisplayName(
     286            0 :           unsafeGetUserFromMemoryOrFallback(directChatMatrixID)
     287            0 :               .calcDisplayname(i18n: i18n),
     288              :         );
     289              :       }
     290              :     }
     291            2 :     return i18n.emptyChat;
     292              :   }
     293              : 
     294              :   /// The topic of the room if set by a participant.
     295            2 :   String get topic {
     296            6 :     final t = getState(EventTypes.RoomTopic)?.content['topic'];
     297            2 :     return t is String ? t : '';
     298              :   }
     299              : 
     300              :   /// The avatar of the room if set by a participant.
     301              :   /// Please note, that necessary room members are lazy loaded. To be sure
     302              :   /// that you have the room members, call and await `Room.loadHeroUsers()`
     303              :   /// before.
     304            4 :   Uri? get avatar {
     305              :     // Check content of `m.room.avatar`
     306              :     final avatarUrl =
     307            8 :         getState(EventTypes.RoomAvatar)?.content.tryGet<String>('url');
     308              :     if (avatarUrl != null) {
     309            2 :       return Uri.tryParse(avatarUrl);
     310              :     }
     311              : 
     312              :     // Room has no avatar and is not a direct chat
     313            4 :     final directChatMatrixID = this.directChatMatrixID;
     314              :     if (directChatMatrixID != null) {
     315            0 :       return unsafeGetUserFromMemoryOrFallback(directChatMatrixID).avatarUrl;
     316              :     }
     317              : 
     318              :     return null;
     319              :   }
     320              : 
     321              :   /// The address in the format: #roomname:homeserver.org.
     322            5 :   String get canonicalAlias {
     323           11 :     final alias = getState(EventTypes.RoomCanonicalAlias)?.content['alias'];
     324            5 :     return (alias is String) ? alias : '';
     325              :   }
     326              : 
     327              :   /// Sets the canonical alias. If the [canonicalAlias] is not yet an alias of
     328              :   /// this room, it will create one.
     329            0 :   Future<void> setCanonicalAlias(String canonicalAlias) async {
     330            0 :     final aliases = await client.getLocalAliases(id);
     331            0 :     if (!aliases.contains(canonicalAlias)) {
     332            0 :       await client.setRoomAlias(canonicalAlias, id);
     333              :     }
     334            0 :     await client.setRoomStateWithKey(id, EventTypes.RoomCanonicalAlias, '', {
     335              :       'alias': canonicalAlias,
     336              :     });
     337              :   }
     338              : 
     339              :   String? _cachedDirectChatMatrixId;
     340              : 
     341              :   /// If this room is a direct chat, this is the matrix ID of the user.
     342              :   /// Returns null otherwise.
     343           34 :   String? get directChatMatrixID {
     344              :     // Calculating the directChatMatrixId can be expensive. We cache it and
     345              :     // validate the cache instead every time.
     346           34 :     final cache = _cachedDirectChatMatrixId;
     347              :     if (cache != null) {
     348           12 :       final roomIds = client.directChats[cache];
     349           12 :       if (roomIds is List && roomIds.contains(id)) {
     350              :         return cache;
     351              :       }
     352              :     }
     353              : 
     354           68 :     if (membership == Membership.invite) {
     355            0 :       final userID = client.userID;
     356              :       if (userID == null) return null;
     357            0 :       final invitation = getState(EventTypes.RoomMember, userID);
     358            0 :       if (invitation != null && invitation.content['is_direct'] == true) {
     359            0 :         return _cachedDirectChatMatrixId = invitation.senderId;
     360              :       }
     361              :     }
     362              : 
     363          102 :     final mxId = client.directChats.entries
     364           50 :         .firstWhereOrNull((MapEntry<String, dynamic> e) {
     365           16 :       final roomIds = e.value;
     366           48 :       return roomIds is List<dynamic> && roomIds.contains(id);
     367            8 :     })?.key;
     368           48 :     if (mxId?.isValidMatrixId == true) return _cachedDirectChatMatrixId = mxId;
     369           34 :     return _cachedDirectChatMatrixId = null;
     370              :   }
     371              : 
     372              :   /// Wheither this is a direct chat or not
     373           68 :   bool get isDirectChat => directChatMatrixID != null;
     374              : 
     375              :   Event? lastEvent;
     376              : 
     377           33 :   void setEphemeral(BasicEvent ephemeral) {
     378           99 :     ephemerals[ephemeral.type] = ephemeral;
     379           66 :     if (ephemeral.type == 'm.typing') {
     380           33 :       _clearTypingIndicatorTimer?.cancel();
     381          134 :       _clearTypingIndicatorTimer = Timer(client.typingIndicatorTimeout, () {
     382            4 :         ephemerals.remove('m.typing');
     383              :       });
     384              :     }
     385              :   }
     386              : 
     387              :   /// Returns a list of all current typing users.
     388            1 :   List<User> get typingUsers {
     389            4 :     final typingMxid = ephemerals['m.typing']?.content['user_ids'];
     390            1 :     return (typingMxid is List)
     391              :         ? typingMxid
     392            1 :             .cast<String>()
     393            2 :             .map(unsafeGetUserFromMemoryOrFallback)
     394            1 :             .toList()
     395            0 :         : [];
     396              :   }
     397              : 
     398              :   /// Your current client instance.
     399              :   final Client client;
     400              : 
     401           36 :   Room({
     402              :     required this.id,
     403              :     this.membership = Membership.join,
     404              :     this.notificationCount = 0,
     405              :     this.highlightCount = 0,
     406              :     this.prev_batch,
     407              :     required this.client,
     408              :     Map<String, BasicEvent>? roomAccountData,
     409              :     RoomSummary? summary,
     410              :     this.lastEvent,
     411           36 :   })  : roomAccountData = roomAccountData ?? <String, BasicEvent>{},
     412              :         summary = summary ??
     413           72 :             RoomSummary.fromJson({
     414              :               'm.joined_member_count': 0,
     415              :               'm.invited_member_count': 0,
     416           36 :               'm.heroes': [],
     417              :             });
     418              : 
     419              :   /// The default count of how much events should be requested when requesting the
     420              :   /// history of this room.
     421              :   static const int defaultHistoryCount = 30;
     422              : 
     423              :   /// Checks if this is an abandoned DM room where the other participant has
     424              :   /// left the room. This is false when there are still other users in the room
     425              :   /// or the room is not marked as a DM room.
     426            2 :   bool get isAbandonedDMRoom {
     427            2 :     final directChatMatrixID = this.directChatMatrixID;
     428              : 
     429              :     if (directChatMatrixID == null) return false;
     430              :     final dmPartnerMembership =
     431            0 :         unsafeGetUserFromMemoryOrFallback(directChatMatrixID).membership;
     432            0 :     return dmPartnerMembership == Membership.leave &&
     433            0 :         summary.mJoinedMemberCount == 1 &&
     434            0 :         summary.mInvitedMemberCount == 0;
     435              :   }
     436              : 
     437              :   /// Calculates the displayname. First checks if there is a name, then checks for a canonical alias and
     438              :   /// then generates a name from the heroes.
     439            0 :   @Deprecated('Use `getLocalizedDisplayname()` instead')
     440            0 :   String get displayname => getLocalizedDisplayname();
     441              : 
     442              :   /// When was the last event received.
     443           33 :   DateTime get latestEventReceivedTime =>
     444           99 :       lastEvent?.originServerTs ?? DateTime.now();
     445              : 
     446              :   /// Call the Matrix API to change the name of this room. Returns the event ID of the
     447              :   /// new m.room.name event.
     448            6 :   Future<String> setName(String newName) => client.setRoomStateWithKey(
     449            2 :         id,
     450              :         EventTypes.RoomName,
     451              :         '',
     452            2 :         {'name': newName},
     453              :       );
     454              : 
     455              :   /// Call the Matrix API to change the topic of this room.
     456            6 :   Future<String> setDescription(String newName) => client.setRoomStateWithKey(
     457            2 :         id,
     458              :         EventTypes.RoomTopic,
     459              :         '',
     460            2 :         {'topic': newName},
     461              :       );
     462              : 
     463              :   /// Add a tag to the room.
     464            6 :   Future<void> addTag(String tag, {double? order}) => client.setRoomTag(
     465            4 :         client.userID!,
     466            2 :         id,
     467              :         tag,
     468            2 :         Tag(
     469              :           order: order,
     470              :         ),
     471              :       );
     472              : 
     473              :   /// Removes a tag from the room.
     474            6 :   Future<void> removeTag(String tag) => client.deleteRoomTag(
     475            4 :         client.userID!,
     476            2 :         id,
     477              :         tag,
     478              :       );
     479              : 
     480              :   // Tag is part of client-to-server-API, so it uses strict parsing.
     481              :   // For roomAccountData, permissive parsing is more suitable,
     482              :   // so it is implemented here.
     483           33 :   static Tag _tryTagFromJson(Object o) {
     484           33 :     if (o is Map<String, dynamic>) {
     485           33 :       return Tag(
     486           66 :         order: o.tryGet<num>('order', TryGet.silent)?.toDouble(),
     487           66 :         additionalProperties: Map.from(o)..remove('order'),
     488              :       );
     489              :     }
     490            0 :     return Tag();
     491              :   }
     492              : 
     493              :   /// Returns all tags for this room.
     494           33 :   Map<String, Tag> get tags {
     495          132 :     final tags = roomAccountData['m.tag']?.content['tags'];
     496              : 
     497           33 :     if (tags is Map) {
     498              :       final parsedTags =
     499          132 :           tags.map((k, v) => MapEntry<String, Tag>(k, _tryTagFromJson(v)));
     500           99 :       parsedTags.removeWhere((k, v) => !TagType.isValid(k));
     501              :       return parsedTags;
     502              :     }
     503              : 
     504           33 :     return {};
     505              :   }
     506              : 
     507            2 :   bool get markedUnread {
     508            2 :     return MarkedUnread.fromJson(
     509            6 :       roomAccountData[EventType.markedUnread]?.content ??
     510            4 :           roomAccountData[EventType.oldMarkedUnread]?.content ??
     511            2 :           {},
     512            2 :     ).unread;
     513              :   }
     514              : 
     515              :   /// Checks if the last event has a read marker of the user.
     516              :   /// Warning: This compares the origin server timestamp which might not map
     517              :   /// to the real sort order of the timeline.
     518            2 :   bool get hasNewMessages {
     519            2 :     final lastEvent = this.lastEvent;
     520              : 
     521              :     // There is no known event or the last event is only a state fallback event,
     522              :     // we assume there is no new messages.
     523              :     if (lastEvent == null ||
     524            8 :         !client.roomPreviewLastEvents.contains(lastEvent.type)) {
     525              :       return false;
     526              :     }
     527              : 
     528              :     // Read marker is on the last event so no new messages.
     529            2 :     if (lastEvent.receipts
     530            2 :         .any((receipt) => receipt.user.senderId == client.userID!)) {
     531              :       return false;
     532              :     }
     533              : 
     534              :     // If the last event is sent, we mark the room as read.
     535            8 :     if (lastEvent.senderId == client.userID) return false;
     536              : 
     537              :     // Get the timestamp of read marker and compare
     538            6 :     final readAtMilliseconds = receiptState.global.latestOwnReceipt?.ts ?? 0;
     539            6 :     return readAtMilliseconds < lastEvent.originServerTs.millisecondsSinceEpoch;
     540              :   }
     541              : 
     542           66 :   LatestReceiptState get receiptState => LatestReceiptState.fromJson(
     543           68 :         roomAccountData[LatestReceiptState.eventType]?.content ??
     544           33 :             <String, dynamic>{},
     545              :       );
     546              : 
     547              :   /// Returns true if this room is unread. To check if there are new messages
     548              :   /// in muted rooms, use [hasNewMessages].
     549            8 :   bool get isUnread => notificationCount > 0 || markedUnread;
     550              : 
     551              :   /// Returns true if this room is to be marked as unread. This extends
     552              :   /// [isUnread] to rooms with [Membership.invite].
     553            8 :   bool get isUnreadOrInvited => isUnread || membership == Membership.invite;
     554              : 
     555            0 :   @Deprecated('Use waitForRoomInSync() instead')
     556            0 :   Future<SyncUpdate> get waitForSync => waitForRoomInSync();
     557              : 
     558              :   /// Wait for the room to appear in join, leave or invited section of the
     559              :   /// sync.
     560            0 :   Future<SyncUpdate> waitForRoomInSync() async {
     561            0 :     return await client.waitForRoomInSync(id);
     562              :   }
     563              : 
     564              :   /// Sets an unread flag manually for this room. This changes the local account
     565              :   /// data model before syncing it to make sure
     566              :   /// this works if there is no connection to the homeserver. This does **not**
     567              :   /// set a read marker!
     568            2 :   Future<void> markUnread(bool unread) async {
     569            4 :     final content = MarkedUnread(unread).toJson();
     570            2 :     await _handleFakeSync(
     571            2 :       SyncUpdate(
     572              :         nextBatch: '',
     573            2 :         rooms: RoomsUpdate(
     574            2 :           join: {
     575            4 :             id: JoinedRoomUpdate(
     576            2 :               accountData: [
     577            2 :                 BasicEvent(
     578              :                   content: content,
     579              :                   type: EventType.markedUnread,
     580              :                 ),
     581              :               ],
     582              :             ),
     583              :           },
     584              :         ),
     585              :       ),
     586              :     );
     587            4 :     await client.setAccountDataPerRoom(
     588            4 :       client.userID!,
     589            2 :       id,
     590              :       EventType.markedUnread,
     591              :       content,
     592              :     );
     593              :   }
     594              : 
     595              :   /// Returns true if this room has a m.favourite tag.
     596           99 :   bool get isFavourite => tags[TagType.favourite] != null;
     597              : 
     598              :   /// Sets the m.favourite tag for this room.
     599            2 :   Future<void> setFavourite(bool favourite) =>
     600            2 :       favourite ? addTag(TagType.favourite) : removeTag(TagType.favourite);
     601              : 
     602              :   /// Call the Matrix API to change the pinned events of this room.
     603            0 :   Future<String> setPinnedEvents(List<String> pinnedEventIds) =>
     604            0 :       client.setRoomStateWithKey(
     605            0 :         id,
     606              :         EventTypes.RoomPinnedEvents,
     607              :         '',
     608            0 :         {'pinned': pinnedEventIds},
     609              :       );
     610              : 
     611              :   /// returns the resolved mxid for a mention string, or null if none found
     612            4 :   String? getMention(String mention) => getParticipants()
     613            8 :       .firstWhereOrNull((u) => u.mentionFragments.contains(mention))
     614            2 :       ?.id;
     615              : 
     616              :   /// Sends a normal text message to this room. Returns the event ID generated
     617              :   /// by the server for this message.
     618            5 :   Future<String?> sendTextEvent(
     619              :     String message, {
     620              :     String? txid,
     621              :     Event? inReplyTo,
     622              :     String? editEventId,
     623              :     bool parseMarkdown = true,
     624              :     bool parseCommands = true,
     625              :     String msgtype = MessageTypes.Text,
     626              :     String? threadRootEventId,
     627              :     String? threadLastEventId,
     628              :   }) {
     629              :     if (parseCommands) {
     630           10 :       return client.parseAndRunCommand(
     631              :         this,
     632              :         message,
     633              :         inReplyTo: inReplyTo,
     634              :         editEventId: editEventId,
     635              :         txid: txid,
     636              :         threadRootEventId: threadRootEventId,
     637              :         threadLastEventId: threadLastEventId,
     638              :       );
     639              :     }
     640            5 :     final event = <String, dynamic>{
     641              :       'msgtype': msgtype,
     642              :       'body': message,
     643              :     };
     644              :     if (parseMarkdown) {
     645            5 :       final html = markdown(
     646            5 :         event['body'],
     647            0 :         getEmotePacks: () => getImagePacksFlat(ImagePackUsage.emoticon),
     648            5 :         getMention: getMention,
     649           10 :         convertLinebreaks: client.convertLinebreaksInFormatting,
     650              :       );
     651              :       // if the decoded html is the same as the body, there is no need in sending a formatted message
     652           25 :       if (HtmlUnescape().convert(html.replaceAll(RegExp(r'<br />\n?'), '\n')) !=
     653            5 :           event['body']) {
     654            3 :         event['format'] = 'org.matrix.custom.html';
     655            3 :         event['formatted_body'] = html;
     656              :       }
     657              :     }
     658            5 :     return sendEvent(
     659              :       event,
     660              :       txid: txid,
     661              :       inReplyTo: inReplyTo,
     662              :       editEventId: editEventId,
     663              :       threadRootEventId: threadRootEventId,
     664              :       threadLastEventId: threadLastEventId,
     665              :     );
     666              :   }
     667              : 
     668              :   /// Sends a reaction to an event with an [eventId] and the content [key] into a room.
     669              :   /// Returns the event ID generated by the server for this reaction.
     670            3 :   Future<String?> sendReaction(String eventId, String key, {String? txid}) {
     671            3 :     return sendEvent(
     672            3 :       {
     673            3 :         'm.relates_to': {
     674              :           'rel_type': RelationshipTypes.reaction,
     675              :           'event_id': eventId,
     676              :           'key': key,
     677              :         },
     678              :       },
     679              :       type: EventTypes.Reaction,
     680              :       txid: txid,
     681              :     );
     682              :   }
     683              : 
     684              :   /// Sends the location with description [body] and geo URI [geoUri] into a room.
     685              :   /// Returns the event ID generated by the server for this message.
     686            2 :   Future<String?> sendLocation(String body, String geoUri, {String? txid}) {
     687            2 :     final event = <String, dynamic>{
     688              :       'msgtype': 'm.location',
     689              :       'body': body,
     690              :       'geo_uri': geoUri,
     691              :     };
     692            2 :     return sendEvent(event, txid: txid);
     693              :   }
     694              : 
     695              :   final Map<String, MatrixFile> sendingFilePlaceholders = {};
     696              :   final Map<String, MatrixImageFile> sendingFileThumbnails = {};
     697              : 
     698              :   /// Sends a [file] to this room after uploading it. Returns the mxc uri of
     699              :   /// the uploaded file. If [waitUntilSent] is true, the future will wait until
     700              :   /// the message event has received the server. Otherwise the future will only
     701              :   /// wait until the file has been uploaded.
     702              :   /// Optionally specify [extraContent] to tack on to the event.
     703              :   ///
     704              :   /// In case [file] is a [MatrixImageFile], [thumbnail] is automatically
     705              :   /// computed unless it is explicitly provided.
     706              :   /// Set [shrinkImageMaxDimension] to for example `1600` if you want to shrink
     707              :   /// your image before sending. This is ignored if the File is not a
     708              :   /// [MatrixImageFile].
     709            3 :   Future<String?> sendFileEvent(
     710              :     MatrixFile file, {
     711              :     String? txid,
     712              :     Event? inReplyTo,
     713              :     String? editEventId,
     714              :     int? shrinkImageMaxDimension,
     715              :     MatrixImageFile? thumbnail,
     716              :     Map<String, dynamic>? extraContent,
     717              :     String? threadRootEventId,
     718              :     String? threadLastEventId,
     719              :   }) async {
     720            2 :     txid ??= client.generateUniqueTransactionId();
     721            6 :     sendingFilePlaceholders[txid] = file;
     722              :     if (thumbnail != null) {
     723            0 :       sendingFileThumbnails[txid] = thumbnail;
     724              :     }
     725              : 
     726              :     // Create a fake Event object as a placeholder for the uploading file:
     727            3 :     final syncUpdate = SyncUpdate(
     728              :       nextBatch: '',
     729            3 :       rooms: RoomsUpdate(
     730            3 :         join: {
     731            6 :           id: JoinedRoomUpdate(
     732            3 :             timeline: TimelineUpdate(
     733            3 :               events: [
     734            3 :                 MatrixEvent(
     735            3 :                   content: {
     736            3 :                     'msgtype': file.msgType,
     737            3 :                     'body': file.name,
     738            3 :                     'filename': file.name,
     739              :                   },
     740              :                   type: EventTypes.Message,
     741              :                   eventId: txid,
     742            6 :                   senderId: client.userID!,
     743            3 :                   originServerTs: DateTime.now(),
     744            3 :                   unsigned: {
     745            6 :                     messageSendingStatusKey: EventStatus.sending.intValue,
     746            3 :                     'transaction_id': txid,
     747            3 :                     ...FileSendRequestCredentials(
     748            0 :                       inReplyTo: inReplyTo?.eventId,
     749              :                       editEventId: editEventId,
     750              :                       shrinkImageMaxDimension: shrinkImageMaxDimension,
     751              :                       extraContent: extraContent,
     752            3 :                     ).toJson(),
     753              :                   },
     754              :                 ),
     755              :               ],
     756              :             ),
     757              :           ),
     758              :         },
     759              :       ),
     760              :     );
     761              : 
     762              :     MatrixFile uploadFile = file; // ignore: omit_local_variable_types
     763              :     // computing the thumbnail in case we can
     764            3 :     if (file is MatrixImageFile &&
     765              :         (thumbnail == null || shrinkImageMaxDimension != null)) {
     766            0 :       syncUpdate.rooms!.join!.values.first.timeline!.events!.first
     767            0 :               .unsigned![fileSendingStatusKey] =
     768            0 :           FileSendingStatus.generatingThumbnail.name;
     769            0 :       await _handleFakeSync(syncUpdate);
     770            0 :       thumbnail ??= await file.generateThumbnail(
     771            0 :         nativeImplementations: client.nativeImplementations,
     772            0 :         customImageResizer: client.customImageResizer,
     773              :       );
     774              :       if (shrinkImageMaxDimension != null) {
     775            0 :         file = await MatrixImageFile.shrink(
     776            0 :           bytes: file.bytes,
     777            0 :           name: file.name,
     778              :           maxDimension: shrinkImageMaxDimension,
     779            0 :           customImageResizer: client.customImageResizer,
     780            0 :           nativeImplementations: client.nativeImplementations,
     781              :         );
     782              :       }
     783              : 
     784            0 :       if (thumbnail != null && file.size < thumbnail.size) {
     785              :         thumbnail = null; // in this case, the thumbnail is not usefull
     786              :       }
     787              :     }
     788              : 
     789              :     // Check media config of the server before sending the file. Stop if the
     790              :     // Media config is unreachable or the file is bigger than the given maxsize.
     791              :     try {
     792            6 :       final mediaConfig = await client.getConfig();
     793            3 :       final maxMediaSize = mediaConfig.mUploadSize;
     794            9 :       if (maxMediaSize != null && maxMediaSize < file.bytes.lengthInBytes) {
     795            0 :         throw FileTooBigMatrixException(file.bytes.lengthInBytes, maxMediaSize);
     796              :       }
     797              :     } catch (e) {
     798            0 :       Logs().d('Config error while sending file', e);
     799            0 :       syncUpdate.rooms!.join!.values.first.timeline!.events!.first
     800            0 :           .unsigned![messageSendingStatusKey] = EventStatus.error.intValue;
     801            0 :       await _handleFakeSync(syncUpdate);
     802              :       rethrow;
     803              :     }
     804              : 
     805              :     MatrixFile? uploadThumbnail =
     806              :         thumbnail; // ignore: omit_local_variable_types
     807              :     EncryptedFile? encryptedFile;
     808              :     EncryptedFile? encryptedThumbnail;
     809            3 :     if (encrypted && client.fileEncryptionEnabled) {
     810            0 :       syncUpdate.rooms!.join!.values.first.timeline!.events!.first
     811            0 :           .unsigned![fileSendingStatusKey] = FileSendingStatus.encrypting.name;
     812            0 :       await _handleFakeSync(syncUpdate);
     813            0 :       encryptedFile = await file.encrypt();
     814            0 :       uploadFile = encryptedFile.toMatrixFile();
     815              : 
     816              :       if (thumbnail != null) {
     817            0 :         encryptedThumbnail = await thumbnail.encrypt();
     818            0 :         uploadThumbnail = encryptedThumbnail.toMatrixFile();
     819              :       }
     820              :     }
     821              :     Uri? uploadResp, thumbnailUploadResp;
     822              : 
     823           12 :     final timeoutDate = DateTime.now().add(client.sendTimelineEventTimeout);
     824              : 
     825           21 :     syncUpdate.rooms!.join!.values.first.timeline!.events!.first
     826            9 :         .unsigned![fileSendingStatusKey] = FileSendingStatus.uploading.name;
     827              :     while (uploadResp == null ||
     828              :         (uploadThumbnail != null && thumbnailUploadResp == null)) {
     829              :       try {
     830            6 :         uploadResp = await client.uploadContent(
     831            3 :           uploadFile.bytes,
     832            3 :           filename: uploadFile.name,
     833            3 :           contentType: uploadFile.mimeType,
     834              :         );
     835              :         thumbnailUploadResp = uploadThumbnail != null
     836            0 :             ? await client.uploadContent(
     837            0 :                 uploadThumbnail.bytes,
     838            0 :                 filename: uploadThumbnail.name,
     839            0 :                 contentType: uploadThumbnail.mimeType,
     840              :               )
     841              :             : null;
     842            0 :       } on MatrixException catch (_) {
     843            0 :         syncUpdate.rooms!.join!.values.first.timeline!.events!.first
     844            0 :             .unsigned![messageSendingStatusKey] = EventStatus.error.intValue;
     845            0 :         await _handleFakeSync(syncUpdate);
     846              :         rethrow;
     847              :       } catch (_) {
     848            0 :         if (DateTime.now().isAfter(timeoutDate)) {
     849            0 :           syncUpdate.rooms!.join!.values.first.timeline!.events!.first
     850            0 :               .unsigned![messageSendingStatusKey] = EventStatus.error.intValue;
     851            0 :           await _handleFakeSync(syncUpdate);
     852              :           rethrow;
     853              :         }
     854            0 :         Logs().v('Send File into room failed. Try again...');
     855            0 :         await Future.delayed(Duration(seconds: 1));
     856              :       }
     857              :     }
     858              : 
     859              :     // Send event
     860            3 :     final content = <String, dynamic>{
     861            6 :       'msgtype': file.msgType,
     862            6 :       'body': file.name,
     863            6 :       'filename': file.name,
     864            6 :       if (encryptedFile == null) 'url': uploadResp.toString(),
     865              :       if (encryptedFile != null)
     866            0 :         'file': {
     867            0 :           'url': uploadResp.toString(),
     868            0 :           'mimetype': file.mimeType,
     869              :           'v': 'v2',
     870            0 :           'key': {
     871              :             'alg': 'A256CTR',
     872              :             'ext': true,
     873            0 :             'k': encryptedFile.k,
     874            0 :             'key_ops': ['encrypt', 'decrypt'],
     875              :             'kty': 'oct',
     876              :           },
     877            0 :           'iv': encryptedFile.iv,
     878            0 :           'hashes': {'sha256': encryptedFile.sha256},
     879              :         },
     880            6 :       'info': {
     881            3 :         ...file.info,
     882              :         if (thumbnail != null && encryptedThumbnail == null)
     883            0 :           'thumbnail_url': thumbnailUploadResp.toString(),
     884              :         if (thumbnail != null && encryptedThumbnail != null)
     885            0 :           'thumbnail_file': {
     886            0 :             'url': thumbnailUploadResp.toString(),
     887            0 :             'mimetype': thumbnail.mimeType,
     888              :             'v': 'v2',
     889            0 :             'key': {
     890              :               'alg': 'A256CTR',
     891              :               'ext': true,
     892            0 :               'k': encryptedThumbnail.k,
     893            0 :               'key_ops': ['encrypt', 'decrypt'],
     894              :               'kty': 'oct',
     895              :             },
     896            0 :             'iv': encryptedThumbnail.iv,
     897            0 :             'hashes': {'sha256': encryptedThumbnail.sha256},
     898              :           },
     899            0 :         if (thumbnail != null) 'thumbnail_info': thumbnail.info,
     900            0 :         if (thumbnail?.blurhash != null &&
     901            0 :             file is MatrixImageFile &&
     902            0 :             file.blurhash == null)
     903            0 :           'xyz.amorgan.blurhash': thumbnail!.blurhash,
     904              :       },
     905            0 :       if (extraContent != null) ...extraContent,
     906              :     };
     907            3 :     final eventId = await sendEvent(
     908              :       content,
     909              :       txid: txid,
     910              :       inReplyTo: inReplyTo,
     911              :       editEventId: editEventId,
     912              :       threadRootEventId: threadRootEventId,
     913              :       threadLastEventId: threadLastEventId,
     914              :     );
     915            6 :     sendingFilePlaceholders.remove(txid);
     916            6 :     sendingFileThumbnails.remove(txid);
     917              :     return eventId;
     918              :   }
     919              : 
     920              :   /// Calculates how secure the communication is. When all devices are blocked or
     921              :   /// verified, then this returns [EncryptionHealthState.allVerified]. When at
     922              :   /// least one device is not verified, then it returns
     923              :   /// [EncryptionHealthState.unverifiedDevices]. Apps should display this health
     924              :   /// state next to the input text field to inform the user about the current
     925              :   /// encryption security level.
     926            2 :   Future<EncryptionHealthState> calcEncryptionHealthState() async {
     927            2 :     final users = await requestParticipants();
     928            2 :     users.removeWhere(
     929            2 :       (u) =>
     930            8 :           !{Membership.invite, Membership.join}.contains(u.membership) ||
     931            8 :           !client.userDeviceKeys.containsKey(u.id),
     932              :     );
     933              : 
     934            2 :     if (users.any(
     935            2 :       (u) =>
     936           12 :           client.userDeviceKeys[u.id]!.verified != UserVerifiedStatus.verified,
     937              :     )) {
     938              :       return EncryptionHealthState.unverifiedDevices;
     939              :     }
     940              : 
     941              :     return EncryptionHealthState.allVerified;
     942              :   }
     943              : 
     944            9 :   Future<String?> _sendContent(
     945              :     String type,
     946              :     Map<String, dynamic> content, {
     947              :     String? txid,
     948              :   }) async {
     949            0 :     txid ??= client.generateUniqueTransactionId();
     950              : 
     951           13 :     final mustEncrypt = encrypted && client.encryptionEnabled;
     952              : 
     953              :     final sendMessageContent = mustEncrypt
     954            2 :         ? await client.encryption!
     955            2 :             .encryptGroupMessagePayload(id, content, type: type)
     956              :         : content;
     957              : 
     958           18 :     return await client.sendMessage(
     959            9 :       id,
     960            9 :       sendMessageContent.containsKey('ciphertext')
     961              :           ? EventTypes.Encrypted
     962              :           : type,
     963              :       txid,
     964              :       sendMessageContent,
     965              :     );
     966              :   }
     967              : 
     968            3 :   String _stripBodyFallback(String body) {
     969            3 :     if (body.startsWith('> <@')) {
     970              :       var temp = '';
     971              :       var inPrefix = true;
     972            4 :       for (final l in body.split('\n')) {
     973            4 :         if (inPrefix && (l.isEmpty || l.startsWith('> '))) {
     974              :           continue;
     975              :         }
     976              : 
     977              :         inPrefix = false;
     978            4 :         temp += temp.isEmpty ? l : ('\n$l');
     979              :       }
     980              : 
     981              :       return temp;
     982              :     } else {
     983              :       return body;
     984              :     }
     985              :   }
     986              : 
     987              :   /// Sends an event to this room with this json as a content. Returns the
     988              :   /// event ID generated from the server.
     989              :   /// It uses list of completer to make sure events are sending in a row.
     990            9 :   Future<String?> sendEvent(
     991              :     Map<String, dynamic> content, {
     992              :     String type = EventTypes.Message,
     993              :     String? txid,
     994              :     Event? inReplyTo,
     995              :     String? editEventId,
     996              :     String? threadRootEventId,
     997              :     String? threadLastEventId,
     998              :   }) async {
     999              :     // Create new transaction id
    1000              :     final String messageID;
    1001              :     if (txid == null) {
    1002            6 :       messageID = client.generateUniqueTransactionId();
    1003              :     } else {
    1004              :       messageID = txid;
    1005              :     }
    1006              : 
    1007              :     if (inReplyTo != null) {
    1008              :       var replyText =
    1009           12 :           '<${inReplyTo.senderId}> ${_stripBodyFallback(inReplyTo.body)}';
    1010           15 :       replyText = replyText.split('\n').map((line) => '> $line').join('\n');
    1011            3 :       content['format'] = 'org.matrix.custom.html';
    1012              :       // be sure that we strip any previous reply fallbacks
    1013            6 :       final replyHtml = (inReplyTo.formattedText.isNotEmpty
    1014            2 :               ? inReplyTo.formattedText
    1015            9 :               : htmlEscape.convert(inReplyTo.body).replaceAll('\n', '<br>'))
    1016            3 :           .replaceAll(
    1017            3 :         RegExp(
    1018              :           r'<mx-reply>.*</mx-reply>',
    1019              :           caseSensitive: false,
    1020              :           multiLine: false,
    1021              :           dotAll: true,
    1022              :         ),
    1023              :         '',
    1024              :       );
    1025            3 :       final repliedHtml = content.tryGet<String>('formatted_body') ??
    1026              :           htmlEscape
    1027            6 :               .convert(content.tryGet<String>('body') ?? '')
    1028            3 :               .replaceAll('\n', '<br>');
    1029            3 :       content['formatted_body'] =
    1030           15 :           '<mx-reply><blockquote><a href="https://matrix.to/#/${inReplyTo.roomId!}/${inReplyTo.eventId}">In reply to</a> <a href="https://matrix.to/#/${inReplyTo.senderId}">${inReplyTo.senderId}</a><br>$replyHtml</blockquote></mx-reply>$repliedHtml';
    1031              :       // We escape all @room-mentions here to prevent accidental room pings when an admin
    1032              :       // replies to a message containing that!
    1033            3 :       content['body'] =
    1034            9 :           '${replyText.replaceAll('@room', '@\u200broom')}\n\n${content.tryGet<String>('body') ?? ''}';
    1035            6 :       content['m.relates_to'] = {
    1036            3 :         'm.in_reply_to': {
    1037            3 :           'event_id': inReplyTo.eventId,
    1038              :         },
    1039              :       };
    1040              :     }
    1041              : 
    1042              :     if (threadRootEventId != null) {
    1043            2 :       content['m.relates_to'] = {
    1044            1 :         'event_id': threadRootEventId,
    1045            1 :         'rel_type': RelationshipTypes.thread,
    1046            1 :         'is_falling_back': inReplyTo == null,
    1047            1 :         if (inReplyTo != null) ...{
    1048            1 :           'm.in_reply_to': {
    1049            1 :             'event_id': inReplyTo.eventId,
    1050              :           },
    1051            1 :         } else ...{
    1052              :           if (threadLastEventId != null)
    1053            2 :             'm.in_reply_to': {
    1054              :               'event_id': threadLastEventId,
    1055              :             },
    1056              :         },
    1057              :       };
    1058              :     }
    1059              : 
    1060              :     if (editEventId != null) {
    1061            2 :       final newContent = content.copy();
    1062            2 :       content['m.new_content'] = newContent;
    1063            4 :       content['m.relates_to'] = {
    1064              :         'event_id': editEventId,
    1065              :         'rel_type': RelationshipTypes.edit,
    1066              :       };
    1067            4 :       if (content['body'] is String) {
    1068            6 :         content['body'] = '* ${content['body']}';
    1069              :       }
    1070            4 :       if (content['formatted_body'] is String) {
    1071            0 :         content['formatted_body'] = '* ${content['formatted_body']}';
    1072              :       }
    1073              :     }
    1074            9 :     final sentDate = DateTime.now();
    1075            9 :     final syncUpdate = SyncUpdate(
    1076              :       nextBatch: '',
    1077            9 :       rooms: RoomsUpdate(
    1078            9 :         join: {
    1079           18 :           id: JoinedRoomUpdate(
    1080            9 :             timeline: TimelineUpdate(
    1081            9 :               events: [
    1082            9 :                 MatrixEvent(
    1083              :                   content: content,
    1084              :                   type: type,
    1085              :                   eventId: messageID,
    1086           18 :                   senderId: client.userID!,
    1087              :                   originServerTs: sentDate,
    1088            9 :                   unsigned: {
    1089            9 :                     messageSendingStatusKey: EventStatus.sending.intValue,
    1090              :                     'transaction_id': messageID,
    1091              :                   },
    1092              :                 ),
    1093              :               ],
    1094              :             ),
    1095              :           ),
    1096              :         },
    1097              :       ),
    1098              :     );
    1099            9 :     await _handleFakeSync(syncUpdate);
    1100            9 :     final completer = Completer();
    1101           18 :     _sendingQueue.add(completer);
    1102           27 :     while (_sendingQueue.first != completer) {
    1103            0 :       await _sendingQueue.first.future;
    1104              :     }
    1105              : 
    1106           36 :     final timeoutDate = DateTime.now().add(client.sendTimelineEventTimeout);
    1107              :     // Send the text and on success, store and display a *sent* event.
    1108              :     String? res;
    1109              : 
    1110              :     while (res == null) {
    1111              :       try {
    1112            9 :         res = await _sendContent(
    1113              :           type,
    1114              :           content,
    1115              :           txid: messageID,
    1116              :         );
    1117              :       } catch (e, s) {
    1118            4 :         if (e is MatrixException &&
    1119            4 :             e.retryAfterMs != null &&
    1120            0 :             !DateTime.now()
    1121            0 :                 .add(Duration(milliseconds: e.retryAfterMs!))
    1122            0 :                 .isAfter(timeoutDate)) {
    1123            0 :           Logs().w(
    1124            0 :             'Ratelimited while sending message, waiting for ${e.retryAfterMs}ms',
    1125              :           );
    1126            0 :           await Future.delayed(Duration(milliseconds: e.retryAfterMs!));
    1127            4 :         } else if (e is MatrixException ||
    1128            2 :             e is EventTooLarge ||
    1129            0 :             DateTime.now().isAfter(timeoutDate)) {
    1130            8 :           Logs().w('Problem while sending message', e, s);
    1131           28 :           syncUpdate.rooms!.join!.values.first.timeline!.events!.first
    1132           12 :               .unsigned![messageSendingStatusKey] = EventStatus.error.intValue;
    1133            4 :           await _handleFakeSync(syncUpdate);
    1134            4 :           completer.complete();
    1135            8 :           _sendingQueue.remove(completer);
    1136            4 :           if (e is EventTooLarge ||
    1137           12 :               (e is MatrixException && e.error == MatrixError.M_FORBIDDEN)) {
    1138              :             rethrow;
    1139              :           }
    1140              :           return null;
    1141              :         } else {
    1142            0 :           Logs()
    1143            0 :               .w('Problem while sending message: $e Try again in 1 seconds...');
    1144            0 :           await Future.delayed(Duration(seconds: 1));
    1145              :         }
    1146              :       }
    1147              :     }
    1148           63 :     syncUpdate.rooms!.join!.values.first.timeline!.events!.first
    1149           27 :         .unsigned![messageSendingStatusKey] = EventStatus.sent.intValue;
    1150           72 :     syncUpdate.rooms!.join!.values.first.timeline!.events!.first.eventId = res;
    1151            9 :     await _handleFakeSync(syncUpdate);
    1152            9 :     completer.complete();
    1153           18 :     _sendingQueue.remove(completer);
    1154              : 
    1155              :     return res;
    1156              :   }
    1157              : 
    1158              :   /// Call the Matrix API to join this room if the user is not already a member.
    1159              :   /// If this room is intended to be a direct chat, the direct chat flag will
    1160              :   /// automatically be set.
    1161            0 :   Future<void> join({
    1162              :     /// In case of the room is not found on the server, the client leaves the
    1163              :     /// room and rethrows the exception.
    1164              :     bool leaveIfNotFound = true,
    1165              :   }) async {
    1166            0 :     final dmId = directChatMatrixID;
    1167              :     try {
    1168              :       // If this is a DM, mark it as a DM first, because otherwise the current member
    1169              :       // event might be the join event already and there is also a race condition there for SDK users.
    1170            0 :       if (dmId != null) await addToDirectChat(dmId);
    1171              : 
    1172              :       // now join
    1173            0 :       await client.joinRoomById(id);
    1174            0 :     } on MatrixException catch (exception) {
    1175            0 :       if (dmId != null) await removeFromDirectChat();
    1176              :       if (leaveIfNotFound &&
    1177            0 :           membership == Membership.invite &&
    1178              :           // Right now Synapse responses with `M_UNKNOWN` when the room can not
    1179              :           // be found. This is the case for example when User A invites User B
    1180              :           // to a direct chat and then User A leaves the chat before User B
    1181              :           // joined.
    1182              :           // See: https://github.com/element-hq/synapse/issues/1533
    1183            0 :           exception.error == MatrixError.M_UNKNOWN) {
    1184            0 :         await leave();
    1185              :       }
    1186              :       rethrow;
    1187              :     }
    1188              :     return;
    1189              :   }
    1190              : 
    1191              :   /// Call the Matrix API to leave this room. If this room is set as a direct
    1192              :   /// chat, this will be removed too.
    1193            1 :   Future<void> leave() async {
    1194              :     try {
    1195            3 :       await client.leaveRoom(id);
    1196            0 :     } on MatrixException catch (e, s) {
    1197            0 :       if ([MatrixError.M_NOT_FOUND, MatrixError.M_UNKNOWN].contains(e.error)) {
    1198            0 :         Logs().w(
    1199              :           'Unable to leave room. Deleting manually from database...',
    1200              :           e,
    1201              :           s,
    1202              :         );
    1203            0 :         await _handleFakeSync(
    1204            0 :           SyncUpdate(
    1205              :             nextBatch: '',
    1206            0 :             rooms: RoomsUpdate(
    1207            0 :               leave: {
    1208            0 :                 id: LeftRoomUpdate(),
    1209              :               },
    1210              :             ),
    1211              :           ),
    1212              :         );
    1213              :       }
    1214              :       rethrow;
    1215              :     }
    1216              :     return;
    1217              :   }
    1218              : 
    1219              :   /// Call the Matrix API to forget this room if you already left it.
    1220            0 :   Future<void> forget() async {
    1221            0 :     await client.database?.forgetRoom(id);
    1222            0 :     await client.forgetRoom(id);
    1223              :     // Update archived rooms, otherwise an archived room may still be in the
    1224              :     // list after a forget room call
    1225            0 :     final roomIndex = client.archivedRooms.indexWhere((r) => r.room.id == id);
    1226            0 :     if (roomIndex != -1) {
    1227            0 :       client.archivedRooms.removeAt(roomIndex);
    1228              :     }
    1229              :     return;
    1230              :   }
    1231              : 
    1232              :   /// Call the Matrix API to kick a user from this room.
    1233           20 :   Future<void> kick(String userID) => client.kick(id, userID);
    1234              : 
    1235              :   /// Call the Matrix API to ban a user from this room.
    1236           20 :   Future<void> ban(String userID) => client.ban(id, userID);
    1237              : 
    1238              :   /// Call the Matrix API to unban a banned user from this room.
    1239           20 :   Future<void> unban(String userID) => client.unban(id, userID);
    1240              : 
    1241              :   /// Set the power level of the user with the [userID] to the value [power].
    1242              :   /// Returns the event ID of the new state event. If there is no known
    1243              :   /// power level event, there might something broken and this returns null.
    1244              :   /// Please note, that you need to await the power level state from sync before
    1245              :   /// the changes are actually applied. Especially if you want to set multiple
    1246              :   /// power levels at once, you need to await each change in the sync, to not
    1247              :   /// override those.
    1248            5 :   Future<String> setPower(String userId, int power) async {
    1249              :     final powerLevelMapCopy =
    1250           13 :         getState(EventTypes.RoomPowerLevels)?.content.copy() ?? {};
    1251              : 
    1252            5 :     var users = powerLevelMapCopy['users'];
    1253              : 
    1254            5 :     if (users is! Map<String, Object?>) {
    1255              :       if (users != null) {
    1256            4 :         Logs().v(
    1257            6 :           'Repairing Power Level "users" has the wrong type "${powerLevelMapCopy['users'].runtimeType}"',
    1258              :         );
    1259              :       }
    1260           10 :       users = powerLevelMapCopy['users'] = <String, Object?>{};
    1261              :     }
    1262              : 
    1263            5 :     users[userId] = power;
    1264              : 
    1265           10 :     return await client.setRoomStateWithKey(
    1266            5 :       id,
    1267              :       EventTypes.RoomPowerLevels,
    1268              :       '',
    1269              :       powerLevelMapCopy,
    1270              :     );
    1271              :   }
    1272              : 
    1273              :   /// Call the Matrix API to invite a user to this room.
    1274            3 :   Future<void> invite(
    1275              :     String userID, {
    1276              :     String? reason,
    1277              :   }) =>
    1278            6 :       client.inviteUser(
    1279            3 :         id,
    1280              :         userID,
    1281              :         reason: reason,
    1282              :       );
    1283              : 
    1284              :   /// Request more previous events from the server. [historyCount] defines how many events should
    1285              :   /// be received maximum. When the request is answered, [onHistoryReceived] will be triggered **before**
    1286              :   /// the historical events will be published in the onEvent stream. [filter] allows you to specify a
    1287              :   /// [StateFilter] object to filter the events, which can include various criteria such as event types
    1288              :   /// (e.g., [EventTypes.Message]) and other state-related filters. The [StateFilter] object will have
    1289              :   /// [lazyLoadMembers] set to true by default, but this can be overridden.
    1290              :   /// Returns the actual count of received timeline events.
    1291            3 :   Future<int> requestHistory({
    1292              :     int historyCount = defaultHistoryCount,
    1293              :     void Function()? onHistoryReceived,
    1294              :     direction = Direction.b,
    1295              :     StateFilter? filter,
    1296              :   }) async {
    1297            3 :     final prev_batch = this.prev_batch;
    1298              : 
    1299            3 :     final storeInDatabase = !isArchived;
    1300              : 
    1301              :     // Ensure stateFilter is not null and set lazyLoadMembers to true if not already set
    1302            3 :     filter ??= StateFilter(lazyLoadMembers: true);
    1303            3 :     filter.lazyLoadMembers ??= true;
    1304              : 
    1305              :     if (prev_batch == null) {
    1306              :       throw 'Tried to request history without a prev_batch token';
    1307              :     }
    1308            6 :     final resp = await client.getRoomEvents(
    1309            3 :       id,
    1310              :       direction,
    1311              :       from: prev_batch,
    1312              :       limit: historyCount,
    1313            6 :       filter: jsonEncode(filter.toJson()),
    1314              :     );
    1315              : 
    1316            2 :     if (onHistoryReceived != null) onHistoryReceived();
    1317            6 :     this.prev_batch = resp.end;
    1318              : 
    1319            3 :     Future<void> loadFn() async {
    1320            9 :       if (!((resp.chunk.isNotEmpty) && resp.end != null)) return;
    1321              : 
    1322            6 :       await client.handleSync(
    1323            3 :         SyncUpdate(
    1324              :           nextBatch: '',
    1325            3 :           rooms: RoomsUpdate(
    1326            6 :             join: membership == Membership.join
    1327            1 :                 ? {
    1328            2 :                     id: JoinedRoomUpdate(
    1329            1 :                       state: resp.state,
    1330            1 :                       timeline: TimelineUpdate(
    1331              :                         limited: false,
    1332            1 :                         events: direction == Direction.b
    1333            1 :                             ? resp.chunk
    1334            0 :                             : resp.chunk.reversed.toList(),
    1335              :                         prevBatch:
    1336            2 :                             direction == Direction.b ? resp.end : resp.start,
    1337              :                       ),
    1338              :                     ),
    1339              :                   }
    1340              :                 : null,
    1341            6 :             leave: membership != Membership.join
    1342            2 :                 ? {
    1343            4 :                     id: LeftRoomUpdate(
    1344            2 :                       state: resp.state,
    1345            2 :                       timeline: TimelineUpdate(
    1346              :                         limited: false,
    1347            2 :                         events: direction == Direction.b
    1348            2 :                             ? resp.chunk
    1349            0 :                             : resp.chunk.reversed.toList(),
    1350              :                         prevBatch:
    1351            4 :                             direction == Direction.b ? resp.end : resp.start,
    1352              :                       ),
    1353              :                     ),
    1354              :                   }
    1355              :                 : null,
    1356              :           ),
    1357              :         ),
    1358              :         direction: Direction.b,
    1359              :       );
    1360              :     }
    1361              : 
    1362            6 :     if (client.database != null) {
    1363           12 :       await client.database?.transaction(() async {
    1364              :         if (storeInDatabase) {
    1365            6 :           await client.database?.setRoomPrevBatch(resp.end, id, client);
    1366              :         }
    1367            3 :         await loadFn();
    1368              :       });
    1369              :     } else {
    1370            0 :       await loadFn();
    1371              :     }
    1372              : 
    1373            6 :     return resp.chunk.length;
    1374              :   }
    1375              : 
    1376              :   /// Sets this room as a direct chat for this user if not already.
    1377            8 :   Future<void> addToDirectChat(String userID) async {
    1378           16 :     final directChats = client.directChats;
    1379           16 :     if (directChats[userID] is List) {
    1380            0 :       if (!directChats[userID].contains(id)) {
    1381            0 :         directChats[userID].add(id);
    1382              :       } else {
    1383              :         return;
    1384              :       } // Is already in direct chats
    1385              :     } else {
    1386           24 :       directChats[userID] = [id];
    1387              :     }
    1388              : 
    1389           16 :     await client.setAccountData(
    1390           16 :       client.userID!,
    1391              :       'm.direct',
    1392              :       directChats,
    1393              :     );
    1394              :     return;
    1395              :   }
    1396              : 
    1397              :   /// Removes this room from all direct chat tags.
    1398            1 :   Future<void> removeFromDirectChat() async {
    1399            3 :     final directChats = client.directChats.copy();
    1400            2 :     for (final k in directChats.keys) {
    1401            1 :       final directChat = directChats[k];
    1402            3 :       if (directChat is List && directChat.contains(id)) {
    1403            2 :         directChat.remove(id);
    1404              :       }
    1405              :     }
    1406              : 
    1407            4 :     directChats.removeWhere((_, v) => v is List && v.isEmpty);
    1408              : 
    1409            3 :     if (directChats == client.directChats) {
    1410              :       return;
    1411              :     }
    1412              : 
    1413            2 :     await client.setAccountData(
    1414            2 :       client.userID!,
    1415              :       'm.direct',
    1416              :       directChats,
    1417              :     );
    1418              :     return;
    1419              :   }
    1420              : 
    1421              :   /// Get the user fully read marker
    1422            0 :   @Deprecated('Use fullyRead marker')
    1423            0 :   String? get userFullyReadMarker => fullyRead;
    1424              : 
    1425            2 :   bool get isFederated =>
    1426            6 :       getState(EventTypes.RoomCreate)?.content.tryGet<bool>('m.federate') ??
    1427              :       true;
    1428              : 
    1429              :   /// Sets the position of the read marker for a given room, and optionally the
    1430              :   /// read receipt's location.
    1431              :   /// If you set `public` to false, only a private receipt will be sent. A private receipt is always sent if `mRead` is set. If no value is provided, the default from the `client` is used.
    1432              :   /// You can leave out the `eventId`, which will not update the read marker but just send receipts, but there are few cases where that makes sense.
    1433            4 :   Future<void> setReadMarker(
    1434              :     String? eventId, {
    1435              :     String? mRead,
    1436              :     bool? public,
    1437              :   }) async {
    1438            8 :     await client.setReadMarker(
    1439            4 :       id,
    1440              :       mFullyRead: eventId,
    1441            8 :       mRead: (public ?? client.receiptsPublicByDefault) ? mRead : null,
    1442              :       // we always send the private receipt, because there is no reason not to.
    1443              :       mReadPrivate: mRead,
    1444              :     );
    1445              :     return;
    1446              :   }
    1447              : 
    1448            0 :   Future<TimelineChunk?> getEventContext(String eventId) async {
    1449            0 :     final resp = await client.getEventContext(
    1450            0 :       id, eventId,
    1451              :       limit: Room.defaultHistoryCount,
    1452              :       // filter: jsonEncode(StateFilter(lazyLoadMembers: true).toJson()),
    1453              :     );
    1454              : 
    1455            0 :     final events = [
    1456            0 :       if (resp.eventsAfter != null) ...resp.eventsAfter!.reversed,
    1457            0 :       if (resp.event != null) resp.event!,
    1458            0 :       if (resp.eventsBefore != null) ...resp.eventsBefore!,
    1459            0 :     ].map((e) => Event.fromMatrixEvent(e, this)).toList();
    1460              : 
    1461              :     // Try again to decrypt encrypted events but don't update the database.
    1462            0 :     if (encrypted && client.database != null && client.encryptionEnabled) {
    1463            0 :       for (var i = 0; i < events.length; i++) {
    1464            0 :         if (events[i].type == EventTypes.Encrypted &&
    1465            0 :             events[i].content['can_request_session'] == true) {
    1466            0 :           events[i] = await client.encryption!.decryptRoomEvent(events[i]);
    1467              :         }
    1468              :       }
    1469              :     }
    1470              : 
    1471            0 :     final chunk = TimelineChunk(
    1472            0 :       nextBatch: resp.end ?? '',
    1473            0 :       prevBatch: resp.start ?? '',
    1474              :       events: events,
    1475              :     );
    1476              : 
    1477              :     return chunk;
    1478              :   }
    1479              : 
    1480              :   /// This API updates the marker for the given receipt type to the event ID
    1481              :   /// specified. In general you want to use `setReadMarker` instead to set private
    1482              :   /// and public receipt as well as the marker at the same time.
    1483            0 :   @Deprecated(
    1484              :     'Use setReadMarker with mRead set instead. That allows for more control and there are few cases to not send a marker at the same time.',
    1485              :   )
    1486              :   Future<void> postReceipt(
    1487              :     String eventId, {
    1488              :     ReceiptType type = ReceiptType.mRead,
    1489              :   }) async {
    1490            0 :     await client.postReceipt(
    1491            0 :       id,
    1492              :       ReceiptType.mRead,
    1493              :       eventId,
    1494              :     );
    1495              :     return;
    1496              :   }
    1497              : 
    1498              :   /// Is the room archived
    1499           15 :   bool get isArchived => membership == Membership.leave;
    1500              : 
    1501              :   /// Creates a timeline from the store. Returns a [Timeline] object. If you
    1502              :   /// just want to update the whole timeline on every change, use the [onUpdate]
    1503              :   /// callback. For updating only the parts that have changed, use the
    1504              :   /// [onChange], [onRemove], [onInsert] and the [onHistoryReceived] callbacks.
    1505              :   /// This method can also retrieve the timeline at a specific point by setting
    1506              :   /// the [eventContextId]
    1507            4 :   Future<Timeline> getTimeline({
    1508              :     void Function(int index)? onChange,
    1509              :     void Function(int index)? onRemove,
    1510              :     void Function(int insertID)? onInsert,
    1511              :     void Function()? onNewEvent,
    1512              :     void Function()? onUpdate,
    1513              :     String? eventContextId,
    1514              :   }) async {
    1515            4 :     await postLoad();
    1516              : 
    1517              :     List<Event> events;
    1518              : 
    1519            4 :     if (!isArchived) {
    1520            6 :       events = await client.database?.getEventList(
    1521              :             this,
    1522              :             limit: defaultHistoryCount,
    1523              :           ) ??
    1524            0 :           <Event>[];
    1525              :     } else {
    1526            6 :       final archive = client.getArchiveRoomFromCache(id);
    1527            6 :       events = archive?.timeline.events.toList() ?? [];
    1528            6 :       for (var i = 0; i < events.length; i++) {
    1529              :         // Try to decrypt encrypted events but don't update the database.
    1530            2 :         if (encrypted && client.encryptionEnabled) {
    1531            0 :           if (events[i].type == EventTypes.Encrypted) {
    1532            0 :             events[i] = await client.encryption!.decryptRoomEvent(events[i]);
    1533              :           }
    1534              :         }
    1535              :       }
    1536              :     }
    1537              : 
    1538            4 :     var chunk = TimelineChunk(events: events);
    1539              :     // Load the timeline arround eventContextId if set
    1540              :     if (eventContextId != null) {
    1541            0 :       if (!events.any((Event event) => event.eventId == eventContextId)) {
    1542              :         chunk =
    1543            0 :             await getEventContext(eventContextId) ?? TimelineChunk(events: []);
    1544              :       }
    1545              :     }
    1546              : 
    1547            4 :     final timeline = Timeline(
    1548              :       room: this,
    1549              :       chunk: chunk,
    1550              :       onChange: onChange,
    1551              :       onRemove: onRemove,
    1552              :       onInsert: onInsert,
    1553              :       onNewEvent: onNewEvent,
    1554              :       onUpdate: onUpdate,
    1555              :     );
    1556              : 
    1557              :     // Fetch all users from database we have got here.
    1558              :     if (eventContextId == null) {
    1559           16 :       final userIds = events.map((event) => event.senderId).toSet();
    1560            8 :       for (final userId in userIds) {
    1561            4 :         if (getState(EventTypes.RoomMember, userId) != null) continue;
    1562           12 :         final dbUser = await client.database?.getUser(userId, this);
    1563            0 :         if (dbUser != null) setState(dbUser);
    1564              :       }
    1565              :     }
    1566              : 
    1567              :     // Try again to decrypt encrypted events and update the database.
    1568            4 :     if (encrypted && client.encryptionEnabled) {
    1569              :       // decrypt messages
    1570            0 :       for (var i = 0; i < chunk.events.length; i++) {
    1571            0 :         if (chunk.events[i].type == EventTypes.Encrypted) {
    1572              :           if (eventContextId != null) {
    1573              :             // for the fragmented timeline, we don't cache the decrypted
    1574              :             //message in the database
    1575            0 :             chunk.events[i] = await client.encryption!.decryptRoomEvent(
    1576            0 :               chunk.events[i],
    1577              :             );
    1578            0 :           } else if (client.database != null) {
    1579              :             // else, we need the database
    1580            0 :             await client.database?.transaction(() async {
    1581            0 :               for (var i = 0; i < chunk.events.length; i++) {
    1582            0 :                 if (chunk.events[i].content['can_request_session'] == true) {
    1583            0 :                   chunk.events[i] = await client.encryption!.decryptRoomEvent(
    1584            0 :                     chunk.events[i],
    1585            0 :                     store: !isArchived,
    1586              :                     updateType: EventUpdateType.history,
    1587              :                   );
    1588              :                 }
    1589              :               }
    1590              :             });
    1591              :           }
    1592              :         }
    1593              :       }
    1594              :     }
    1595              : 
    1596              :     return timeline;
    1597              :   }
    1598              : 
    1599              :   /// Returns all participants for this room. With lazy loading this
    1600              :   /// list may not be complete. Use [requestParticipants] in this
    1601              :   /// case.
    1602              :   /// List `membershipFilter` defines with what membership do you want the
    1603              :   /// participants, default set to
    1604              :   /// [[Membership.join, Membership.invite, Membership.knock]]
    1605           33 :   List<User> getParticipants([
    1606              :     List<Membership> membershipFilter = const [
    1607              :       Membership.join,
    1608              :       Membership.invite,
    1609              :       Membership.knock,
    1610              :     ],
    1611              :   ]) {
    1612           66 :     final members = states[EventTypes.RoomMember];
    1613              :     if (members != null) {
    1614           33 :       return members.entries
    1615          165 :           .where((entry) => entry.value.type == EventTypes.RoomMember)
    1616          132 :           .map((entry) => entry.value.asUser(this))
    1617          132 :           .where((user) => membershipFilter.contains(user.membership))
    1618           33 :           .toList();
    1619              :     }
    1620            6 :     return <User>[];
    1621              :   }
    1622              : 
    1623              :   /// Request the full list of participants from the server. The local list
    1624              :   /// from the store is not complete if the client uses lazy loading.
    1625              :   /// List `membershipFilter` defines with what membership do you want the
    1626              :   /// participants, default set to
    1627              :   /// [[Membership.join, Membership.invite, Membership.knock]]
    1628              :   /// Set [cache] to `false` if you do not want to cache the users in memory
    1629              :   /// for this session which is highly recommended for large public rooms.
    1630              :   /// By default users are only cached in encrypted rooms as encrypted rooms
    1631              :   /// need a full member list.
    1632           31 :   Future<List<User>> requestParticipants([
    1633              :     List<Membership> membershipFilter = const [
    1634              :       Membership.join,
    1635              :       Membership.invite,
    1636              :       Membership.knock,
    1637              :     ],
    1638              :     bool suppressWarning = false,
    1639              :     bool? cache,
    1640              :   ]) async {
    1641           62 :     if (!participantListComplete || partial) {
    1642              :       // we aren't fully loaded, maybe the users are in the database
    1643              :       // We always need to check the database in the partial case, since state
    1644              :       // events won't get written to memory in this case and someone new could
    1645              :       // have joined, while someone else left, which might lead to the same
    1646              :       // count in the completeness check.
    1647           94 :       final users = await client.database?.getUsers(this) ?? [];
    1648           34 :       for (final user in users) {
    1649            3 :         setState(user);
    1650              :       }
    1651              :     }
    1652              : 
    1653              :     // Do not request users from the server if we have already have a complete list locally.
    1654           31 :     if (participantListComplete) {
    1655           31 :       return getParticipants(membershipFilter);
    1656              :     }
    1657              : 
    1658            3 :     cache ??= encrypted;
    1659              : 
    1660            6 :     final memberCount = summary.mJoinedMemberCount;
    1661            3 :     if (!suppressWarning && cache && memberCount != null && memberCount > 100) {
    1662            0 :       Logs().w('''
    1663            0 :         Loading a list of $memberCount participants for the room $id.
    1664              :         This may affect the performance. Please make sure to not unnecessary
    1665              :         request so many participants or suppress this warning.
    1666            0 :       ''');
    1667              :     }
    1668              : 
    1669            9 :     final matrixEvents = await client.getMembersByRoom(id);
    1670              :     final users = matrixEvents
    1671           12 :             ?.map((e) => Event.fromMatrixEvent(e, this).asUser)
    1672            3 :             .toList() ??
    1673            0 :         [];
    1674              : 
    1675              :     if (cache) {
    1676            6 :       for (final user in users) {
    1677            3 :         setState(user); // at *least* cache this in-memory
    1678            9 :         await client.database?.storeEventUpdate(
    1679            3 :           id,
    1680              :           user,
    1681              :           EventUpdateType.state,
    1682            3 :           client,
    1683              :         );
    1684              :       }
    1685              :     }
    1686              : 
    1687           12 :     users.removeWhere((u) => !membershipFilter.contains(u.membership));
    1688              :     return users;
    1689              :   }
    1690              : 
    1691              :   /// Checks if the local participant list of joined and invited users is complete.
    1692           31 :   bool get participantListComplete {
    1693           31 :     final knownParticipants = getParticipants();
    1694              :     final joinedCount =
    1695          155 :         knownParticipants.where((u) => u.membership == Membership.join).length;
    1696              :     final invitedCount = knownParticipants
    1697          124 :         .where((u) => u.membership == Membership.invite)
    1698           31 :         .length;
    1699              : 
    1700           93 :     return (summary.mJoinedMemberCount ?? 0) == joinedCount &&
    1701           93 :         (summary.mInvitedMemberCount ?? 0) == invitedCount;
    1702              :   }
    1703              : 
    1704            0 :   @Deprecated(
    1705              :     'The method was renamed unsafeGetUserFromMemoryOrFallback. Please prefer requestParticipants.',
    1706              :   )
    1707              :   User getUserByMXIDSync(String mxID) {
    1708            0 :     return unsafeGetUserFromMemoryOrFallback(mxID);
    1709              :   }
    1710              : 
    1711              :   /// Returns the [User] object for the given [mxID] or return
    1712              :   /// a fallback [User] and start a request to get the user
    1713              :   /// from the homeserver.
    1714            8 :   User unsafeGetUserFromMemoryOrFallback(String mxID) {
    1715            8 :     final user = getState(EventTypes.RoomMember, mxID);
    1716              :     if (user != null) {
    1717            6 :       return user.asUser(this);
    1718              :     } else {
    1719            5 :       if (mxID.isValidMatrixId) {
    1720              :         // ignore: discarded_futures
    1721            5 :         requestUser(
    1722              :           mxID,
    1723              :           ignoreErrors: true,
    1724              :         );
    1725              :       }
    1726            5 :       return User(mxID, room: this);
    1727              :     }
    1728              :   }
    1729              : 
    1730              :   // Internal helper to implement requestUser
    1731            8 :   Future<User?> _requestSingleParticipantViaState(
    1732              :     String mxID, {
    1733              :     required bool ignoreErrors,
    1734              :   }) async {
    1735              :     try {
    1736           32 :       Logs().v('Request missing user $mxID in room $id from the server...');
    1737           16 :       final resp = await client.getRoomStateWithKey(
    1738            8 :         id,
    1739              :         EventTypes.RoomMember,
    1740              :         mxID,
    1741              :       );
    1742              : 
    1743              :       // valid member events require a valid membership key
    1744            6 :       final membership = resp.tryGet<String>('membership', TryGet.required);
    1745            6 :       assert(membership != null);
    1746              : 
    1747            6 :       final foundUser = User(
    1748              :         mxID,
    1749              :         room: this,
    1750            6 :         displayName: resp.tryGet<String>('displayname', TryGet.silent),
    1751            6 :         avatarUrl: resp.tryGet<String>('avatar_url', TryGet.silent),
    1752              :         membership: membership,
    1753              :       );
    1754              : 
    1755              :       // Store user in database:
    1756           24 :       await client.database?.transaction(() async {
    1757           18 :         await client.database?.storeEventUpdate(
    1758            6 :           id,
    1759              :           foundUser,
    1760              :           EventUpdateType.state,
    1761            6 :           client,
    1762              :         );
    1763              :       });
    1764              : 
    1765              :       return foundUser;
    1766            5 :     } on MatrixException catch (_) {
    1767              :       // Ignore if we have no permission
    1768              :       return null;
    1769              :     } catch (e, s) {
    1770              :       if (!ignoreErrors) {
    1771              :         rethrow;
    1772              :       } else {
    1773            6 :         Logs().w('Unable to request the user $mxID from the server', e, s);
    1774              :         return null;
    1775              :       }
    1776              :     }
    1777              :   }
    1778              : 
    1779              :   // Internal helper to implement requestUser
    1780            9 :   Future<User?> _requestUser(
    1781              :     String mxID, {
    1782              :     required bool ignoreErrors,
    1783              :     required bool requestState,
    1784              :     required bool requestProfile,
    1785              :   }) async {
    1786              :     // Is user already in cache?
    1787              : 
    1788              :     // If not in cache, try the database
    1789           12 :     User? foundUser = getState(EventTypes.RoomMember, mxID)?.asUser(this);
    1790              : 
    1791              :     // If the room is not postloaded, check the database
    1792            9 :     if (partial && foundUser == null) {
    1793           16 :       foundUser = await client.database?.getUser(mxID, this);
    1794              :     }
    1795              : 
    1796              :     // If not in the database, try fetching the member from the server
    1797              :     if (requestState && foundUser == null) {
    1798            8 :       foundUser = await _requestSingleParticipantViaState(
    1799              :         mxID,
    1800              :         ignoreErrors: ignoreErrors,
    1801              :       );
    1802              :     }
    1803              : 
    1804              :     // If the user isn't found or they have left and no displayname set anymore, request their profile from the server
    1805              :     if (requestProfile) {
    1806              :       if (foundUser
    1807              :           case null ||
    1808              :               User(
    1809           14 :                 membership: Membership.ban || Membership.leave,
    1810            6 :                 displayName: null
    1811              :               )) {
    1812              :         try {
    1813           10 :           final profile = await client.getUserProfile(mxID);
    1814            2 :           foundUser = User(
    1815              :             mxID,
    1816            2 :             displayName: profile.displayname,
    1817            4 :             avatarUrl: profile.avatarUrl?.toString(),
    1818            6 :             membership: foundUser?.membership.name ?? Membership.leave.name,
    1819              :             room: this,
    1820              :           );
    1821              :         } catch (e, s) {
    1822              :           if (!ignoreErrors) {
    1823              :             rethrow;
    1824              :           } else {
    1825            2 :             Logs()
    1826            4 :                 .w('Unable to request the profile $mxID from the server', e, s);
    1827              :           }
    1828              :         }
    1829              :       }
    1830              :     }
    1831              : 
    1832              :     if (foundUser == null) return null;
    1833              :     // make sure we didn't actually store anything by the time we did those requests
    1834              :     final userFromCurrentState =
    1835           10 :         getState(EventTypes.RoomMember, mxID)?.asUser(this);
    1836              : 
    1837              :     // Set user in the local state if the state changed.
    1838              :     // If we set the state unconditionally, we might end up with a client calling this over and over thinking the user changed.
    1839              :     if (userFromCurrentState == null ||
    1840            9 :         userFromCurrentState.displayName != foundUser.displayName) {
    1841            6 :       setState(foundUser);
    1842              :       // ignore: deprecated_member_use_from_same_package
    1843           18 :       onUpdate.add(id);
    1844              :     }
    1845              : 
    1846              :     return foundUser;
    1847              :   }
    1848              : 
    1849              :   final Map<
    1850              :       ({
    1851              :         String mxID,
    1852              :         bool ignoreErrors,
    1853              :         bool requestState,
    1854              :         bool requestProfile,
    1855              :       }),
    1856              :       AsyncCache<User?>> _inflightUserRequests = {};
    1857              : 
    1858              :   /// Requests a missing [User] for this room. Important for clients using
    1859              :   /// lazy loading. If the user can't be found this method tries to fetch
    1860              :   /// the displayname and avatar from the server if [requestState] is true.
    1861              :   /// If that fails, it falls back to requesting the global profile if
    1862              :   /// [requestProfile] is true.
    1863            9 :   Future<User?> requestUser(
    1864              :     String mxID, {
    1865              :     bool ignoreErrors = false,
    1866              :     bool requestState = true,
    1867              :     bool requestProfile = true,
    1868              :   }) async {
    1869           18 :     assert(mxID.isValidMatrixId);
    1870              : 
    1871              :     final parameters = (
    1872              :       mxID: mxID,
    1873              :       ignoreErrors: ignoreErrors,
    1874              :       requestState: requestState,
    1875              :       requestProfile: requestProfile,
    1876              :     );
    1877              : 
    1878           27 :     final cache = _inflightUserRequests[parameters] ??= AsyncCache.ephemeral();
    1879              : 
    1880              :     try {
    1881            9 :       final user = await cache.fetch(
    1882           18 :         () => _requestUser(
    1883              :           mxID,
    1884              :           ignoreErrors: ignoreErrors,
    1885              :           requestState: requestState,
    1886              :           requestProfile: requestProfile,
    1887              :         ),
    1888              :       );
    1889           18 :       _inflightUserRequests.remove(parameters);
    1890              :       return user;
    1891              :     } catch (_) {
    1892            2 :       _inflightUserRequests.remove(parameters);
    1893              :       rethrow;
    1894              :     }
    1895              :   }
    1896              : 
    1897              :   /// Searches for the event in the local cache and then on the server if not
    1898              :   /// found. Returns null if not found anywhere.
    1899            4 :   Future<Event?> getEventById(String eventID) async {
    1900              :     try {
    1901           12 :       final dbEvent = await client.database?.getEventById(eventID, this);
    1902              :       if (dbEvent != null) return dbEvent;
    1903           12 :       final matrixEvent = await client.getOneRoomEvent(id, eventID);
    1904            4 :       final event = Event.fromMatrixEvent(matrixEvent, this);
    1905           12 :       if (event.type == EventTypes.Encrypted && client.encryptionEnabled) {
    1906              :         // attempt decryption
    1907            6 :         return await client.encryption?.decryptRoomEvent(event);
    1908              :       }
    1909              :       return event;
    1910            2 :     } on MatrixException catch (err) {
    1911            4 :       if (err.errcode == 'M_NOT_FOUND') {
    1912              :         return null;
    1913              :       }
    1914              :       rethrow;
    1915              :     }
    1916              :   }
    1917              : 
    1918              :   /// Returns the power level of the given user ID.
    1919              :   /// If a user_id is in the users list, then that user_id has the associated
    1920              :   /// power level. Otherwise they have the default level users_default.
    1921              :   /// If users_default is not supplied, it is assumed to be 0. If the room
    1922              :   /// contains no m.room.power_levels event, the room’s creator has a power
    1923              :   /// level of 100, and all other users have a power level of 0.
    1924            8 :   int getPowerLevelByUserId(String userId) {
    1925           14 :     final powerLevelMap = getState(EventTypes.RoomPowerLevels)?.content;
    1926              : 
    1927              :     final userSpecificPowerLevel =
    1928           12 :         powerLevelMap?.tryGetMap<String, Object?>('users')?.tryGet<int>(userId);
    1929              : 
    1930            6 :     final defaultUserPowerLevel = powerLevelMap?.tryGet<int>('users_default');
    1931              : 
    1932              :     final fallbackPowerLevel =
    1933           18 :         getState(EventTypes.RoomCreate)?.senderId == userId ? 100 : 0;
    1934              : 
    1935              :     return userSpecificPowerLevel ??
    1936              :         defaultUserPowerLevel ??
    1937              :         fallbackPowerLevel;
    1938              :   }
    1939              : 
    1940              :   /// Returns the user's own power level.
    1941           24 :   int get ownPowerLevel => getPowerLevelByUserId(client.userID!);
    1942              : 
    1943              :   /// Returns the power levels from all users for this room or null if not given.
    1944            0 :   @Deprecated('Use `getPowerLevelByUserId(String userId)` instead')
    1945              :   Map<String, int>? get powerLevels {
    1946              :     final powerLevelState =
    1947            0 :         getState(EventTypes.RoomPowerLevels)?.content['users'];
    1948            0 :     return (powerLevelState is Map<String, int>) ? powerLevelState : null;
    1949              :   }
    1950              : 
    1951              :   /// Uploads a new user avatar for this room. Returns the event ID of the new
    1952              :   /// m.room.avatar event. Leave empty to remove the current avatar.
    1953            2 :   Future<String> setAvatar(MatrixFile? file) async {
    1954              :     final uploadResp = file == null
    1955              :         ? null
    1956            8 :         : await client.uploadContent(file.bytes, filename: file.name);
    1957            4 :     return await client.setRoomStateWithKey(
    1958            2 :       id,
    1959              :       EventTypes.RoomAvatar,
    1960              :       '',
    1961            2 :       {
    1962            4 :         if (uploadResp != null) 'url': uploadResp.toString(),
    1963              :       },
    1964              :     );
    1965              :   }
    1966              : 
    1967              :   /// The level required to ban a user.
    1968            4 :   bool get canBan =>
    1969            8 :       (getState(EventTypes.RoomPowerLevels)?.content.tryGet<int>('ban') ??
    1970            4 :           50) <=
    1971            4 :       ownPowerLevel;
    1972              : 
    1973              :   /// returns if user can change a particular state event by comparing `ownPowerLevel`
    1974              :   /// with possible overrides in `events`, if not present compares `ownPowerLevel`
    1975              :   /// with state_default
    1976            6 :   bool canChangeStateEvent(String action) {
    1977           18 :     return powerForChangingStateEvent(action) <= ownPowerLevel;
    1978              :   }
    1979              : 
    1980              :   /// returns the powerlevel required for changing the `action` defaults to
    1981              :   /// state_default if `action` isn't specified in events override.
    1982              :   /// If there is no state_default in the m.room.power_levels event, the
    1983              :   /// state_default is 50. If the room contains no m.room.power_levels event,
    1984              :   /// the state_default is 0.
    1985            6 :   int powerForChangingStateEvent(String action) {
    1986           10 :     final powerLevelMap = getState(EventTypes.RoomPowerLevels)?.content;
    1987              :     if (powerLevelMap == null) return 0;
    1988              :     return powerLevelMap
    1989            4 :             .tryGetMap<String, Object?>('events')
    1990            4 :             ?.tryGet<int>(action) ??
    1991            4 :         powerLevelMap.tryGet<int>('state_default') ??
    1992              :         50;
    1993              :   }
    1994              : 
    1995              :   /// if returned value is not null `EventTypes.GroupCallMember` is present
    1996              :   /// and group calls can be used
    1997            2 :   bool get groupCallsEnabledForEveryone {
    1998            4 :     final powerLevelMap = getState(EventTypes.RoomPowerLevels)?.content;
    1999              :     if (powerLevelMap == null) return false;
    2000            4 :     return powerForChangingStateEvent(EventTypes.GroupCallMember) <=
    2001            2 :         getDefaultPowerLevel(powerLevelMap);
    2002              :   }
    2003              : 
    2004            4 :   bool get canJoinGroupCall => canChangeStateEvent(EventTypes.GroupCallMember);
    2005              : 
    2006              :   /// sets the `EventTypes.GroupCallMember` power level to users default for
    2007              :   /// group calls, needs permissions to change power levels
    2008            2 :   Future<void> enableGroupCalls() async {
    2009            2 :     if (!canChangePowerLevel) return;
    2010            4 :     final currentPowerLevelsMap = getState(EventTypes.RoomPowerLevels)?.content;
    2011              :     if (currentPowerLevelsMap != null) {
    2012              :       final newPowerLevelMap = currentPowerLevelsMap;
    2013            2 :       final eventsMap = newPowerLevelMap.tryGetMap<String, Object?>('events') ??
    2014            2 :           <String, Object?>{};
    2015            4 :       eventsMap.addAll({
    2016            2 :         EventTypes.GroupCallMember: getDefaultPowerLevel(currentPowerLevelsMap),
    2017              :       });
    2018            4 :       newPowerLevelMap.addAll({'events': eventsMap});
    2019            4 :       await client.setRoomStateWithKey(
    2020            2 :         id,
    2021              :         EventTypes.RoomPowerLevels,
    2022              :         '',
    2023              :         newPowerLevelMap,
    2024              :       );
    2025              :     }
    2026              :   }
    2027              : 
    2028              :   /// Takes in `[m.room.power_levels].content` and returns the default power level
    2029            2 :   int getDefaultPowerLevel(Map<String, dynamic> powerLevelMap) {
    2030            2 :     return powerLevelMap.tryGet('users_default') ?? 0;
    2031              :   }
    2032              : 
    2033              :   /// The default level required to send message events. This checks if the
    2034              :   /// user is capable of sending `m.room.message` events.
    2035              :   /// Please be aware that this also returns false
    2036              :   /// if the room is encrypted but the client is not able to use encryption.
    2037              :   /// If you do not want this check or want to check other events like
    2038              :   /// `m.sticker` use `canSendEvent('<event-type>')`.
    2039            2 :   bool get canSendDefaultMessages {
    2040            2 :     if (encrypted && !client.encryptionEnabled) return false;
    2041              : 
    2042            4 :     return canSendEvent(encrypted ? EventTypes.Encrypted : EventTypes.Message);
    2043              :   }
    2044              : 
    2045              :   /// The level required to invite a user.
    2046            2 :   bool get canInvite =>
    2047            6 :       (getState(EventTypes.RoomPowerLevels)?.content.tryGet<int>('invite') ??
    2048            2 :           0) <=
    2049            2 :       ownPowerLevel;
    2050              : 
    2051              :   /// The level required to kick a user.
    2052            4 :   bool get canKick =>
    2053            8 :       (getState(EventTypes.RoomPowerLevels)?.content.tryGet<int>('kick') ??
    2054            4 :           50) <=
    2055            4 :       ownPowerLevel;
    2056              : 
    2057              :   /// The level required to redact an event.
    2058            2 :   bool get canRedact =>
    2059            6 :       (getState(EventTypes.RoomPowerLevels)?.content.tryGet<int>('redact') ??
    2060            2 :           50) <=
    2061            2 :       ownPowerLevel;
    2062              : 
    2063              :   ///   The default level required to send state events. Can be overridden by the events key.
    2064            0 :   bool get canSendDefaultStates {
    2065            0 :     final powerLevelsMap = getState(EventTypes.RoomPowerLevels)?.content;
    2066            0 :     if (powerLevelsMap == null) return 0 <= ownPowerLevel;
    2067            0 :     return (getState(EventTypes.RoomPowerLevels)
    2068            0 :                 ?.content
    2069            0 :                 .tryGet<int>('state_default') ??
    2070            0 :             50) <=
    2071            0 :         ownPowerLevel;
    2072              :   }
    2073              : 
    2074            6 :   bool get canChangePowerLevel =>
    2075            6 :       canChangeStateEvent(EventTypes.RoomPowerLevels);
    2076              : 
    2077              :   /// The level required to send a certain event. Defaults to 0 if there is no
    2078              :   /// events_default set or there is no power level state in the room.
    2079            2 :   bool canSendEvent(String eventType) {
    2080            4 :     final powerLevelsMap = getState(EventTypes.RoomPowerLevels)?.content;
    2081              : 
    2082              :     final pl = powerLevelsMap
    2083            2 :             ?.tryGetMap<String, Object?>('events')
    2084            2 :             ?.tryGet<int>(eventType) ??
    2085            2 :         powerLevelsMap?.tryGet<int>('events_default') ??
    2086              :         0;
    2087              : 
    2088            4 :     return ownPowerLevel >= pl;
    2089              :   }
    2090              : 
    2091              :   /// The power level requirements for specific notification types.
    2092            2 :   bool canSendNotification(String userid, {String notificationType = 'room'}) {
    2093            2 :     final userLevel = getPowerLevelByUserId(userid);
    2094            2 :     final notificationLevel = getState(EventTypes.RoomPowerLevels)
    2095            2 :             ?.content
    2096            2 :             .tryGetMap<String, Object?>('notifications')
    2097            2 :             ?.tryGet<int>(notificationType) ??
    2098              :         50;
    2099              : 
    2100            2 :     return userLevel >= notificationLevel;
    2101              :   }
    2102              : 
    2103              :   /// Returns the [PushRuleState] for this room, based on the m.push_rules stored in
    2104              :   /// the account_data.
    2105            2 :   PushRuleState get pushRuleState {
    2106            4 :     final globalPushRules = client.globalPushRules;
    2107              :     if (globalPushRules == null) {
    2108              :       // We have no push rules specified at all so we fallback to just notify:
    2109              :       return PushRuleState.notify;
    2110              :     }
    2111              : 
    2112            2 :     final overridePushRules = globalPushRules.override;
    2113              :     if (overridePushRules != null) {
    2114            4 :       for (final pushRule in overridePushRules) {
    2115            6 :         if (pushRule.ruleId == id) {
    2116              :           // "dont_notify" and "coalesce" should be ignored in actions since
    2117              :           // https://spec.matrix.org/v1.7/client-server-api/#actions
    2118            2 :           pushRule.actions
    2119            2 :             ..remove('dont_notify')
    2120            2 :             ..remove('coalesce');
    2121            4 :           if (pushRule.actions.isEmpty) {
    2122              :             return PushRuleState.dontNotify;
    2123              :           }
    2124              :           break;
    2125              :         }
    2126              :       }
    2127              :     }
    2128              : 
    2129            2 :     final roomPushRules = globalPushRules.room;
    2130              :     if (roomPushRules != null) {
    2131            4 :       for (final pushRule in roomPushRules) {
    2132            6 :         if (pushRule.ruleId == id) {
    2133              :           // "dont_notify" and "coalesce" should be ignored in actions since
    2134              :           // https://spec.matrix.org/v1.7/client-server-api/#actions
    2135            2 :           pushRule.actions
    2136            2 :             ..remove('dont_notify')
    2137            2 :             ..remove('coalesce');
    2138            4 :           if (pushRule.actions.isEmpty) {
    2139              :             return PushRuleState.mentionsOnly;
    2140              :           }
    2141              :           break;
    2142              :         }
    2143              :       }
    2144              :     }
    2145              : 
    2146              :     return PushRuleState.notify;
    2147              :   }
    2148              : 
    2149              :   /// Sends a request to the homeserver to set the [PushRuleState] for this room.
    2150              :   /// Returns ErrorResponse if something goes wrong.
    2151            2 :   Future<void> setPushRuleState(PushRuleState newState) async {
    2152            4 :     if (newState == pushRuleState) return;
    2153              :     dynamic resp;
    2154              :     switch (newState) {
    2155              :       // All push notifications should be sent to the user
    2156            2 :       case PushRuleState.notify:
    2157            4 :         if (pushRuleState == PushRuleState.dontNotify) {
    2158            6 :           await client.deletePushRule(PushRuleKind.override, id);
    2159            0 :         } else if (pushRuleState == PushRuleState.mentionsOnly) {
    2160            0 :           await client.deletePushRule(PushRuleKind.room, id);
    2161              :         }
    2162              :         break;
    2163              :       // Only when someone mentions the user, a push notification should be sent
    2164            2 :       case PushRuleState.mentionsOnly:
    2165            4 :         if (pushRuleState == PushRuleState.dontNotify) {
    2166            6 :           await client.deletePushRule(PushRuleKind.override, id);
    2167            4 :           await client.setPushRule(
    2168              :             PushRuleKind.room,
    2169            2 :             id,
    2170            2 :             [],
    2171              :           );
    2172            0 :         } else if (pushRuleState == PushRuleState.notify) {
    2173            0 :           await client.setPushRule(
    2174              :             PushRuleKind.room,
    2175            0 :             id,
    2176            0 :             [],
    2177              :           );
    2178              :         }
    2179              :         break;
    2180              :       // No push notification should be ever sent for this room.
    2181            0 :       case PushRuleState.dontNotify:
    2182            0 :         if (pushRuleState == PushRuleState.mentionsOnly) {
    2183            0 :           await client.deletePushRule(PushRuleKind.room, id);
    2184              :         }
    2185            0 :         await client.setPushRule(
    2186              :           PushRuleKind.override,
    2187            0 :           id,
    2188            0 :           [],
    2189            0 :           conditions: [
    2190            0 :             PushCondition(
    2191            0 :               kind: PushRuleConditions.eventMatch.name,
    2192              :               key: 'room_id',
    2193            0 :               pattern: id,
    2194              :             ),
    2195              :           ],
    2196              :         );
    2197              :     }
    2198              :     return resp;
    2199              :   }
    2200              : 
    2201              :   /// Redacts this event. Throws `ErrorResponse` on error.
    2202            1 :   Future<String?> redactEvent(
    2203              :     String eventId, {
    2204              :     String? reason,
    2205              :     String? txid,
    2206              :   }) async {
    2207              :     // Create new transaction id
    2208              :     String messageID;
    2209            2 :     final now = DateTime.now().millisecondsSinceEpoch;
    2210              :     if (txid == null) {
    2211            0 :       messageID = 'msg$now';
    2212              :     } else {
    2213              :       messageID = txid;
    2214              :     }
    2215            1 :     final data = <String, dynamic>{};
    2216            1 :     if (reason != null) data['reason'] = reason;
    2217            2 :     return await client.redactEvent(
    2218            1 :       id,
    2219              :       eventId,
    2220              :       messageID,
    2221              :       reason: reason,
    2222              :     );
    2223              :   }
    2224              : 
    2225              :   /// This tells the server that the user is typing for the next N milliseconds
    2226              :   /// where N is the value specified in the timeout key. Alternatively, if typing is false,
    2227              :   /// it tells the server that the user has stopped typing.
    2228            0 :   Future<void> setTyping(bool isTyping, {int? timeout}) =>
    2229            0 :       client.setTyping(client.userID!, id, isTyping, timeout: timeout);
    2230              : 
    2231              :   /// A room may be public meaning anyone can join the room without any prior action. Alternatively,
    2232              :   /// it can be invite meaning that a user who wishes to join the room must first receive an invite
    2233              :   /// to the room from someone already inside of the room. Currently, knock and private are reserved
    2234              :   /// keywords which are not implemented.
    2235            2 :   JoinRules? get joinRules {
    2236              :     final joinRulesString =
    2237            6 :         getState(EventTypes.RoomJoinRules)?.content.tryGet<String>('join_rule');
    2238              :     return JoinRules.values
    2239            8 :         .singleWhereOrNull((element) => element.text == joinRulesString);
    2240              :   }
    2241              : 
    2242              :   /// Changes the join rules. You should check first if the user is able to change it.
    2243            2 :   Future<void> setJoinRules(JoinRules joinRules) async {
    2244            4 :     await client.setRoomStateWithKey(
    2245            2 :       id,
    2246              :       EventTypes.RoomJoinRules,
    2247              :       '',
    2248            2 :       {
    2249            4 :         'join_rule': joinRules.toString().replaceAll('JoinRules.', ''),
    2250              :       },
    2251              :     );
    2252              :     return;
    2253              :   }
    2254              : 
    2255              :   /// Whether the user has the permission to change the join rules.
    2256            4 :   bool get canChangeJoinRules => canChangeStateEvent(EventTypes.RoomJoinRules);
    2257              : 
    2258              :   /// This event controls whether guest users are allowed to join rooms. If this event
    2259              :   /// is absent, servers should act as if it is present and has the guest_access value "forbidden".
    2260            2 :   GuestAccess get guestAccess {
    2261            2 :     final guestAccessString = getState(EventTypes.GuestAccess)
    2262            2 :         ?.content
    2263            2 :         .tryGet<String>('guest_access');
    2264            2 :     return GuestAccess.values.singleWhereOrNull(
    2265            6 :           (element) => element.text == guestAccessString,
    2266              :         ) ??
    2267              :         GuestAccess.forbidden;
    2268              :   }
    2269              : 
    2270              :   /// Changes the guest access. You should check first if the user is able to change it.
    2271            2 :   Future<void> setGuestAccess(GuestAccess guestAccess) async {
    2272            4 :     await client.setRoomStateWithKey(
    2273            2 :       id,
    2274              :       EventTypes.GuestAccess,
    2275              :       '',
    2276            2 :       {
    2277            2 :         'guest_access': guestAccess.text,
    2278              :       },
    2279              :     );
    2280              :     return;
    2281              :   }
    2282              : 
    2283              :   /// Whether the user has the permission to change the guest access.
    2284            4 :   bool get canChangeGuestAccess => canChangeStateEvent(EventTypes.GuestAccess);
    2285              : 
    2286              :   /// This event controls whether a user can see the events that happened in a room from before they joined.
    2287            2 :   HistoryVisibility? get historyVisibility {
    2288            2 :     final historyVisibilityString = getState(EventTypes.HistoryVisibility)
    2289            2 :         ?.content
    2290            2 :         .tryGet<String>('history_visibility');
    2291            2 :     return HistoryVisibility.values.singleWhereOrNull(
    2292            6 :       (element) => element.text == historyVisibilityString,
    2293              :     );
    2294              :   }
    2295              : 
    2296              :   /// Changes the history visibility. You should check first if the user is able to change it.
    2297            2 :   Future<void> setHistoryVisibility(HistoryVisibility historyVisibility) async {
    2298            4 :     await client.setRoomStateWithKey(
    2299            2 :       id,
    2300              :       EventTypes.HistoryVisibility,
    2301              :       '',
    2302            2 :       {
    2303            2 :         'history_visibility': historyVisibility.text,
    2304              :       },
    2305              :     );
    2306              :     return;
    2307              :   }
    2308              : 
    2309              :   /// Whether the user has the permission to change the history visibility.
    2310            2 :   bool get canChangeHistoryVisibility =>
    2311            2 :       canChangeStateEvent(EventTypes.HistoryVisibility);
    2312              : 
    2313              :   /// Returns the encryption algorithm. Currently only `m.megolm.v1.aes-sha2` is supported.
    2314              :   /// Returns null if there is no encryption algorithm.
    2315           33 :   String? get encryptionAlgorithm =>
    2316           95 :       getState(EventTypes.Encryption)?.parsedRoomEncryptionContent.algorithm;
    2317              : 
    2318              :   /// Checks if this room is encrypted.
    2319           66 :   bool get encrypted => encryptionAlgorithm != null;
    2320              : 
    2321            2 :   Future<void> enableEncryption({int algorithmIndex = 0}) async {
    2322            2 :     if (encrypted) throw ('Encryption is already enabled!');
    2323            2 :     final algorithm = Client.supportedGroupEncryptionAlgorithms[algorithmIndex];
    2324            4 :     await client.setRoomStateWithKey(
    2325            2 :       id,
    2326              :       EventTypes.Encryption,
    2327              :       '',
    2328            2 :       {
    2329              :         'algorithm': algorithm,
    2330              :       },
    2331              :     );
    2332              :     return;
    2333              :   }
    2334              : 
    2335              :   /// Returns all known device keys for all participants in this room.
    2336            7 :   Future<List<DeviceKeys>> getUserDeviceKeys() async {
    2337           14 :     await client.userDeviceKeysLoading;
    2338            7 :     final deviceKeys = <DeviceKeys>[];
    2339            7 :     final users = await requestParticipants();
    2340           11 :     for (final user in users) {
    2341           24 :       final userDeviceKeys = client.userDeviceKeys[user.id]?.deviceKeys.values;
    2342           12 :       if ([Membership.invite, Membership.join].contains(user.membership) &&
    2343              :           userDeviceKeys != null) {
    2344            8 :         for (final deviceKeyEntry in userDeviceKeys) {
    2345            4 :           deviceKeys.add(deviceKeyEntry);
    2346              :         }
    2347              :       }
    2348              :     }
    2349              :     return deviceKeys;
    2350              :   }
    2351              : 
    2352            1 :   Future<void> requestSessionKey(String sessionId, String senderKey) async {
    2353            2 :     if (!client.encryptionEnabled) {
    2354              :       return;
    2355              :     }
    2356            4 :     await client.encryption?.keyManager.request(this, sessionId, senderKey);
    2357              :   }
    2358              : 
    2359            9 :   Future<void> _handleFakeSync(
    2360              :     SyncUpdate syncUpdate, {
    2361              :     Direction? direction,
    2362              :   }) async {
    2363           18 :     if (client.database != null) {
    2364           28 :       await client.database?.transaction(() async {
    2365           14 :         await client.handleSync(syncUpdate, direction: direction);
    2366              :       });
    2367              :     } else {
    2368            4 :       await client.handleSync(syncUpdate, direction: direction);
    2369              :     }
    2370              :   }
    2371              : 
    2372              :   /// Whether this is an extinct room which has been archived in favor of a new
    2373              :   /// room which replaces this. Use `getLegacyRoomInformations()` to get more
    2374              :   /// informations about it if this is true.
    2375            0 :   bool get isExtinct => getState(EventTypes.RoomTombstone) != null;
    2376              : 
    2377              :   /// Returns informations about how this room is
    2378            0 :   TombstoneContent? get extinctInformations =>
    2379            0 :       getState(EventTypes.RoomTombstone)?.parsedTombstoneContent;
    2380              : 
    2381              :   /// Checks if the `m.room.create` state has a `type` key with the value
    2382              :   /// `m.space`.
    2383            2 :   bool get isSpace =>
    2384            8 :       getState(EventTypes.RoomCreate)?.content.tryGet<String>('type') ==
    2385              :       RoomCreationTypes.mSpace;
    2386              : 
    2387              :   /// The parents of this room. Currently this SDK doesn't yet set the canonical
    2388              :   /// flag and is not checking if this room is in fact a child of this space.
    2389              :   /// You should therefore not rely on this and always check the children of
    2390              :   /// the space.
    2391            2 :   List<SpaceParent> get spaceParents =>
    2392            4 :       states[EventTypes.SpaceParent]
    2393            2 :           ?.values
    2394            6 :           .map((state) => SpaceParent.fromState(state))
    2395            8 :           .where((child) => child.via.isNotEmpty)
    2396            2 :           .toList() ??
    2397            2 :       [];
    2398              : 
    2399              :   /// List all children of this space. Children without a `via` domain will be
    2400              :   /// ignored.
    2401              :   /// Children are sorted by the `order` while those without this field will be
    2402              :   /// sorted at the end of the list.
    2403            4 :   List<SpaceChild> get spaceChildren => !isSpace
    2404            0 :       ? throw Exception('Room is not a space!')
    2405            4 :       : (states[EventTypes.SpaceChild]
    2406            2 :               ?.values
    2407            6 :               .map((state) => SpaceChild.fromState(state))
    2408            8 :               .where((child) => child.via.isNotEmpty)
    2409            2 :               .toList() ??
    2410            2 :           [])
    2411            2 :     ..sort(
    2412           10 :       (a, b) => a.order.isEmpty || b.order.isEmpty
    2413            6 :           ? b.order.compareTo(a.order)
    2414            6 :           : a.order.compareTo(b.order),
    2415              :     );
    2416              : 
    2417              :   /// Adds or edits a child of this space.
    2418            0 :   Future<void> setSpaceChild(
    2419              :     String roomId, {
    2420              :     List<String>? via,
    2421              :     String? order,
    2422              :     bool? suggested,
    2423              :   }) async {
    2424            0 :     if (!isSpace) throw Exception('Room is not a space!');
    2425            0 :     via ??= [client.userID!.domain!];
    2426            0 :     await client.setRoomStateWithKey(id, EventTypes.SpaceChild, roomId, {
    2427            0 :       'via': via,
    2428            0 :       if (order != null) 'order': order,
    2429            0 :       if (suggested != null) 'suggested': suggested,
    2430              :     });
    2431            0 :     await client.setRoomStateWithKey(roomId, EventTypes.SpaceParent, id, {
    2432              :       'via': via,
    2433              :     });
    2434              :     return;
    2435              :   }
    2436              : 
    2437              :   /// Generates a matrix.to link with appropriate routing info to share the room
    2438            2 :   Future<Uri> matrixToInviteLink() async {
    2439            4 :     if (canonicalAlias.isNotEmpty) {
    2440            2 :       return Uri.parse(
    2441            6 :         'https://matrix.to/#/${Uri.encodeComponent(canonicalAlias)}',
    2442              :       );
    2443              :     }
    2444            2 :     final List queryParameters = [];
    2445            4 :     final users = await requestParticipants([Membership.join]);
    2446            4 :     final currentPowerLevelsMap = getState(EventTypes.RoomPowerLevels)?.content;
    2447              : 
    2448            2 :     final temp = List<User>.from(users);
    2449            8 :     temp.removeWhere((user) => user.powerLevel < 50);
    2450              :     if (currentPowerLevelsMap != null) {
    2451              :       // just for weird rooms
    2452            2 :       temp.removeWhere(
    2453            0 :         (user) => user.powerLevel < getDefaultPowerLevel(currentPowerLevelsMap),
    2454              :       );
    2455              :     }
    2456              : 
    2457            2 :     if (temp.isNotEmpty) {
    2458            0 :       temp.sort((a, b) => a.powerLevel.compareTo(b.powerLevel));
    2459            0 :       if (temp.last.id.domain != null) {
    2460            0 :         queryParameters.add(temp.last.id.domain!);
    2461              :       }
    2462              :     }
    2463              : 
    2464            2 :     final Map<String, int> servers = {};
    2465            4 :     for (final user in users) {
    2466            4 :       if (user.id.domain != null) {
    2467            6 :         if (servers.containsKey(user.id.domain!)) {
    2468            0 :           servers[user.id.domain!] = servers[user.id.domain!]! + 1;
    2469              :         } else {
    2470            6 :           servers[user.id.domain!] = 1;
    2471              :         }
    2472              :       }
    2473              :     }
    2474            2 :     final sortedServers = Map.fromEntries(
    2475           14 :       servers.entries.toList()..sort((e1, e2) => e2.value.compareTo(e1.value)),
    2476            4 :     ).keys.take(3);
    2477            4 :     for (final server in sortedServers) {
    2478            2 :       if (!queryParameters.contains(server)) {
    2479            2 :         queryParameters.add(server);
    2480              :       }
    2481              :     }
    2482              : 
    2483              :     var queryString = '?';
    2484            8 :     for (var i = 0; i < min(queryParameters.length, 3); i++) {
    2485            2 :       if (i != 0) {
    2486            2 :         queryString += '&';
    2487              :       }
    2488            6 :       queryString += 'via=${queryParameters[i]}';
    2489              :     }
    2490            2 :     return Uri.parse(
    2491            6 :       'https://matrix.to/#/${Uri.encodeComponent(id)}$queryString',
    2492              :     );
    2493              :   }
    2494              : 
    2495              :   /// Remove a child from this space by setting the `via` to an empty list.
    2496            0 :   Future<void> removeSpaceChild(String roomId) => !isSpace
    2497            0 :       ? throw Exception('Room is not a space!')
    2498            0 :       : setSpaceChild(roomId, via: const []);
    2499              : 
    2500            1 :   @override
    2501            4 :   bool operator ==(Object other) => (other is Room && other.id == id);
    2502              : 
    2503            0 :   @override
    2504            0 :   int get hashCode => Object.hashAll([id]);
    2505              : }
    2506              : 
    2507              : enum EncryptionHealthState {
    2508              :   allVerified,
    2509              :   unverifiedDevices,
    2510              : }
        

Generated by: LCOV version 2.0-1