LCOV - code coverage report
Current view: top level - lib/src - room.dart (source / functions) Coverage Total Hit
Test: merged.info Lines: 74.7 % 979 731
Test Date: 2025-05-24 18:14:12 Functions: - 0 0

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

Generated by: LCOV version 2.0-1