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

Generated by: LCOV version 1.14