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

Generated by: LCOV version 1.14