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