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 'package:matrix/matrix.dart';
20 :
21 : /// Represents a Matrix User which may be a participant in a Matrix Room.
22 : class User extends StrippedStateEvent {
23 : final Room room;
24 : final Map<String, Object?>? prevContent;
25 : final DateTime? originServerTs;
26 :
27 10 : factory User(
28 : String id, {
29 : String? membership,
30 : String? displayName,
31 : String? avatarUrl,
32 : DateTime? originServerTs,
33 : required Room room,
34 : }) {
35 10 : return User.fromState(
36 : stateKey: id,
37 : senderId: id,
38 10 : content: {
39 8 : if (membership != null) 'membership': membership,
40 8 : if (displayName != null) 'displayname': displayName,
41 4 : if (avatarUrl != null) 'avatar_url': avatarUrl,
42 : },
43 : typeKey: EventTypes.RoomMember,
44 : room: room,
45 : originServerTs: originServerTs,
46 : );
47 : }
48 :
49 33 : User.fromState({
50 : required String super.stateKey,
51 : super.content = const {},
52 : required String typeKey,
53 : required super.senderId,
54 : required this.room,
55 : this.originServerTs,
56 : this.prevContent,
57 33 : }) : super(
58 : type: typeKey,
59 : );
60 :
61 : /// The full qualified Matrix ID in the format @username:server.abc.
62 66 : String get id => stateKey ?? '@unknown:unknown';
63 :
64 : /// The displayname of the user if the user has set one.
65 11 : String? get displayName =>
66 22 : content.tryGet<String>('displayname') ??
67 18 : (membership == Membership.join
68 : ? null
69 2 : : prevContent?.tryGet<String>('displayname'));
70 :
71 : /// Returns the power level of this user.
72 16 : int get powerLevel => room.getPowerLevelByUserId(id);
73 :
74 : /// The membership status of the user. One of:
75 : /// join
76 : /// invite
77 : /// leave
78 : /// ban
79 66 : Membership get membership => Membership.values.firstWhere(
80 33 : (e) {
81 66 : if (content['membership'] != null) {
82 165 : return e.toString() == 'Membership.${content['membership']}';
83 : }
84 : return false;
85 : },
86 9 : orElse: () => Membership.join,
87 : );
88 :
89 : /// The avatar if the user has one.
90 2 : Uri? get avatarUrl {
91 4 : final uri = content.tryGet<String>('avatar_url') ??
92 0 : (membership == Membership.join
93 : ? null
94 0 : : prevContent?.tryGet<String>('avatar_url'));
95 2 : return uri == null ? null : Uri.tryParse(uri);
96 : }
97 :
98 : /// Returns the displayname or the local part of the Matrix ID if the user
99 : /// has no displayname. If [formatLocalpart] is true, then the localpart will
100 : /// be formatted in the way, that all "_" characters are becomming white spaces and
101 : /// the first character of each word becomes uppercase.
102 : /// If [mxidLocalPartFallback] is true, then the local part of the mxid will be shown
103 : /// if there is no other displayname available. If not then this will return "Unknown user".
104 7 : String calcDisplayname({
105 : bool? formatLocalpart,
106 : bool? mxidLocalPartFallback,
107 : MatrixLocalizations i18n = const MatrixDefaultLocalizations(),
108 : }) {
109 21 : formatLocalpart ??= room.client.formatLocalpart;
110 21 : mxidLocalPartFallback ??= room.client.mxidLocalPartFallback;
111 7 : final displayName = this.displayName;
112 5 : if (displayName != null && displayName.isNotEmpty) {
113 : return displayName;
114 : }
115 4 : final stateKey = this.stateKey;
116 : if (stateKey != null && mxidLocalPartFallback) {
117 : if (!formatLocalpart) {
118 2 : return stateKey.localpart ?? '';
119 : }
120 12 : final words = stateKey.localpart?.replaceAll('_', ' ').split(' ') ?? [];
121 12 : for (var i = 0; i < words.length; i++) {
122 8 : if (words[i].isNotEmpty) {
123 28 : words[i] = words[i][0].toUpperCase() + words[i].substring(1);
124 : }
125 : }
126 8 : return words.join(' ').trim();
127 : }
128 2 : return i18n.unknownUser;
129 : }
130 :
131 : /// Call the Matrix API to kick this user from this room.
132 8 : Future<void> kick() async => await room.kick(id);
133 :
134 : /// Call the Matrix API to ban this user from this room.
135 8 : Future<void> ban() async => await room.ban(id);
136 :
137 : /// Call the Matrix API to unban this banned user from this room.
138 8 : Future<void> unban() async => await room.unban(id);
139 :
140 : /// Call the Matrix API to change the power level of this user.
141 8 : Future<void> setPower(int power) async => await room.setPower(id, power);
142 :
143 : /// Returns an existing direct chat ID with this user or creates a new one.
144 : /// Returns null on error.
145 2 : Future<String> startDirectChat({
146 : bool? enableEncryption,
147 : List<StateEvent>? initialState,
148 : bool waitForSync = true,
149 : }) async =>
150 6 : room.client.startDirectChat(
151 2 : id,
152 : enableEncryption: enableEncryption,
153 : initialState: initialState,
154 : waitForSync: waitForSync,
155 : );
156 :
157 : /// The newest presence of this user if there is any and null if not.
158 0 : @Deprecated('Deprecated in favour of currentPresence.')
159 0 : Presence? get presence => room.client.presences[id]?.toPresence();
160 :
161 0 : @Deprecated('Use fetchCurrentPresence() instead')
162 0 : Future<CachedPresence> get currentPresence => fetchCurrentPresence();
163 :
164 : /// The newest presence of this user if there is any. Fetches it from the
165 : /// database first and then from the server if necessary or returns offline.
166 2 : Future<CachedPresence> fetchCurrentPresence() =>
167 8 : room.client.fetchCurrentPresence(id);
168 :
169 : /// Whether the client is able to ban/unban this user.
170 6 : bool get canBan => room.canBan && powerLevel < room.ownPowerLevel;
171 :
172 : /// Whether the client is able to kick this user.
173 2 : bool get canKick =>
174 6 : [Membership.join, Membership.invite].contains(membership) &&
175 4 : room.canKick &&
176 0 : powerLevel < room.ownPowerLevel;
177 :
178 0 : @Deprecated('Use [canChangeUserPowerLevel] instead.')
179 0 : bool get canChangePowerLevel => canChangeUserPowerLevel;
180 :
181 : /// Whether the client is allowed to change the power level of this user.
182 : /// Please be aware that you can only set the power level to at least your own!
183 2 : bool get canChangeUserPowerLevel =>
184 4 : room.canChangePowerLevel &&
185 18 : (powerLevel < room.ownPowerLevel || id == room.client.userID);
186 :
187 1 : @override
188 1 : bool operator ==(Object other) => (other is User &&
189 3 : other.id == id &&
190 3 : other.room == room &&
191 3 : other.membership == membership);
192 :
193 0 : @override
194 0 : int get hashCode => Object.hash(id, room, membership);
195 :
196 : /// Get the mention text to use in a plain text body to mention this specific user
197 : /// in this specific room
198 2 : String get mention {
199 : // if the displayname has [ or ] or : we can't build our more fancy stuff, so fall back to the id
200 : // [] is used for the delimitors
201 : // If we allowed : we could get collissions with the mxid fallbacks
202 2 : final displayName = this.displayName;
203 : if (displayName == null ||
204 2 : displayName.isEmpty ||
205 10 : {'[', ']', ':'}.any(displayName.contains)) {
206 2 : return id;
207 : }
208 :
209 : final identifier =
210 8 : '@${RegExp(r'^\w+$').hasMatch(displayName) ? displayName : '[$displayName]'}';
211 :
212 : // get all the users with the same display name
213 4 : final allUsersWithSameDisplayname = room.getParticipants();
214 2 : allUsersWithSameDisplayname.removeWhere(
215 2 : (user) =>
216 6 : user.id == id ||
217 4 : (user.displayName?.isEmpty ?? true) ||
218 4 : user.displayName != displayName,
219 : );
220 2 : if (allUsersWithSameDisplayname.isEmpty) {
221 : return identifier;
222 : }
223 : // ok, we have multiple users with the same display name....time to calculate a hash
224 8 : final hashes = allUsersWithSameDisplayname.map((u) => _hash(u.id));
225 4 : final ourHash = _hash(id);
226 : // hash collission...just return our own mxid again
227 2 : if (hashes.contains(ourHash)) {
228 0 : return id;
229 : }
230 2 : return '$identifier#$ourHash';
231 : }
232 :
233 : /// Get the mention fragments for this user.
234 4 : Set<String> get mentionFragments {
235 4 : final displayName = this.displayName;
236 : if (displayName == null ||
237 4 : displayName.isEmpty ||
238 20 : {'[', ']', ':'}.any(displayName.contains)) {
239 : return {};
240 : }
241 : final identifier =
242 16 : '@${RegExp(r'^\w+$').hasMatch(displayName) ? displayName : '[$displayName]'}';
243 :
244 8 : final hash = _hash(id);
245 8 : return {identifier, '$identifier#$hash'};
246 : }
247 : }
248 :
249 : const _maximumHashLength = 10000;
250 4 : String _hash(String s) =>
251 24 : (s.codeUnits.fold<int>(0, (a, b) => a + b) % _maximumHashLength).toString();
252 :
253 : extension FromStrippedStateEventExtension on StrippedStateEvent {
254 66 : User asUser(Room room) => User.fromState(
255 : // state key should always be set for member events
256 33 : stateKey: stateKey!,
257 33 : content: content,
258 33 : typeKey: type,
259 33 : senderId: senderId,
260 : room: room,
261 : originServerTs: null,
262 : );
263 : }
|