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

Generated by: LCOV version 1.14