Line data Source code
1 : import 'dart:convert';
2 : import 'dart:math';
3 :
4 : import 'package:cwtch/config.dart';
5 : import 'package:cwtch/models/remoteserver.dart';
6 : import 'package:cwtch/models/search.dart';
7 : import 'package:flutter/widgets.dart';
8 : import 'package:provider/provider.dart';
9 : import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
10 :
11 : import '../main.dart';
12 : import '../themes/opaque.dart';
13 : import '../views/contactsview.dart';
14 : import 'contact.dart';
15 : import 'contactlist.dart';
16 : import 'filedownloadprogress.dart';
17 : import 'profileservers.dart';
18 : import 'search.dart';
19 :
20 : class ProfileInfoState extends ChangeNotifier {
21 : ProfileServerListState _servers = ProfileServerListState();
22 : ContactListState _contacts = ContactListState();
23 : SearchState _searchState = SearchState();
24 : final String onion;
25 : String _nickname = "";
26 : String _privateName = "";
27 : String _imagePath = "";
28 : String _defaultImagePath = "";
29 : int _unreadMessages = 0;
30 : bool _online = false;
31 : Map<String, FileDownloadProgress> _downloads = Map<String, FileDownloadProgress>();
32 : Map<String, int> _downloadTriggers = Map<String, int>();
33 : ItemScrollController contactListScrollController = new ItemScrollController();
34 : // assume profiles are encrypted...this will be set to false
35 : // in the constructor if the profile is encrypted with the defacto password.
36 : bool _encrypted = true;
37 :
38 : bool _autostart = true;
39 : bool _enabled = false;
40 : bool _appearOffline = false;
41 : bool _appearOfflineAtStartup = false;
42 :
43 0 : ProfileInfoState({
44 : required this.onion,
45 : nickname = "",
46 : privateName = "",
47 : imagePath = "",
48 : defaultImagePath = "",
49 : unreadMessages = 0,
50 : contactsJson = "",
51 : serversJson = "",
52 : online = false,
53 : autostart = true,
54 : encrypted = true,
55 : appearOffline = false,
56 : String,
57 : }) {
58 0 : this._nickname = nickname;
59 0 : this._privateName = privateName;
60 0 : this._imagePath = imagePath;
61 0 : this._defaultImagePath = defaultImagePath;
62 0 : this._unreadMessages = unreadMessages;
63 0 : this._online = online;
64 0 : this._enabled = _enabled;
65 0 : this._autostart = autostart;
66 : if (autostart) {
67 0 : this._enabled = true;
68 : }
69 0 : this._appearOffline = appearOffline;
70 0 : this._appearOfflineAtStartup = appearOffline;
71 0 : this._encrypted = encrypted;
72 :
73 0 : _contacts.connectServers(this._servers);
74 :
75 0 : if (contactsJson != null && contactsJson != "" && contactsJson != "null") {
76 0 : this.replaceServers(serversJson);
77 :
78 0 : List<dynamic> contacts = jsonDecode(contactsJson);
79 0 : this._contacts.addAll(contacts.map((contact) {
80 0 : this._unreadMessages += contact["numUnread"] as int;
81 :
82 0 : return ContactInfoState(this.onion, contact["identifier"], contact["onion"],
83 0 : nickname: contact["name"],
84 0 : localNickname: contact["attributes"]?["local.profile.name"] ?? "", // contact may not have a local name
85 0 : status: contact["status"],
86 0 : imagePath: contact["picture"],
87 0 : defaultImagePath: contact["isGroup"] ? contact["picture"] : contact["defaultPicture"],
88 0 : accepted: contact["accepted"],
89 0 : blocked: contact["blocked"],
90 0 : savePeerHistory: contact["saveConversationHistory"],
91 0 : numMessages: contact["numMessages"],
92 0 : numUnread: contact["numUnread"],
93 0 : isGroup: contact["isGroup"],
94 0 : server: contact["groupServer"],
95 0 : archived: contact["isArchived"] == true,
96 0 : lastMessageTime: DateTime.fromMillisecondsSinceEpoch(1000 * int.parse(contact["lastMsgTime"])),
97 0 : pinned: contact["attributes"]?["local.profile.pinned"] == "true",
98 0 : notificationPolicy: contact["notificationPolicy"] ?? "ConversationNotificationPolicy.Default");
99 : }));
100 :
101 : // dummy set to invoke sort-on-load
102 0 : if (this._contacts.num > 0) {
103 0 : this._contacts.updateLastMessageReceivedTime(this._contacts.contacts.first.identifier, this._contacts.contacts.first.lastMessageReceivedTime);
104 : }
105 : }
106 : }
107 :
108 : // Parse out the server list json into our server info state struct...
109 0 : void replaceServers(String serversJson) {
110 0 : if (serversJson != "" && serversJson != "null") {
111 0 : List<dynamic> servers = jsonDecode(serversJson);
112 0 : this._servers.replace(servers.map((server) {
113 : // TODO Keys...
114 0 : var preSyncStartTime = DateTime.tryParse(server["syncProgress"]["startTime"]);
115 0 : var lastMessageTime = DateTime.tryParse(server["syncProgress"]["lastMessageTime"]);
116 0 : return RemoteServerInfoState(server["onion"], server["identifier"], server["description"], server["status"], lastPreSyncMessageTime: preSyncStartTime, mostRecentMessageTime: lastMessageTime);
117 : }));
118 :
119 0 : this._contacts.contacts.forEach((contact) {
120 0 : if (contact.isGroup) {
121 0 : _servers.addGroup(contact);
122 : }
123 : });
124 :
125 0 : notifyListeners();
126 : }
127 : }
128 :
129 : //
130 0 : void updateServerStatusCache(String server, String status) {
131 0 : this._servers.updateServerState(server, status);
132 0 : notifyListeners();
133 : }
134 :
135 : // Getters and Setters for Online Status
136 0 : bool get isOnline => this._online;
137 :
138 0 : set isOnline(bool newValue) {
139 0 : this._online = newValue;
140 0 : notifyListeners();
141 : }
142 :
143 : // Check encrypted status for profile info screen
144 0 : bool get isEncrypted => this._encrypted;
145 0 : set isEncrypted(bool newValue) {
146 0 : this._encrypted = newValue;
147 0 : notifyListeners();
148 : }
149 :
150 0 : String get nickname => this._nickname;
151 :
152 0 : set nickname(String newValue) {
153 0 : this._nickname = newValue;
154 0 : notifyListeners();
155 : }
156 :
157 0 : String get imagePath => this._imagePath;
158 :
159 0 : set imagePath(String newVal) {
160 0 : this._imagePath = newVal;
161 0 : notifyListeners();
162 : }
163 :
164 0 : bool get enabled => this._enabled;
165 :
166 0 : set enabled(bool newVal) {
167 0 : this._enabled = newVal;
168 0 : notifyListeners();
169 : }
170 :
171 0 : bool get autostart => this._autostart;
172 0 : set autostart(bool newVal) {
173 0 : this._autostart = newVal;
174 0 : notifyListeners();
175 : }
176 :
177 0 : bool get appearOfflineAtStartup => this._appearOfflineAtStartup;
178 0 : set appearOfflineAtStartup(bool newVal) {
179 0 : this._appearOfflineAtStartup = newVal;
180 0 : notifyListeners();
181 : }
182 :
183 0 : bool get appearOffline => this._appearOffline;
184 0 : set appearOffline(bool newVal) {
185 0 : this._appearOffline = newVal;
186 0 : notifyListeners();
187 : }
188 :
189 0 : String get defaultImagePath => this._defaultImagePath;
190 :
191 0 : set defaultImagePath(String newVal) {
192 0 : this._defaultImagePath = newVal;
193 0 : notifyListeners();
194 : }
195 :
196 0 : int get unreadMessages => this._unreadMessages;
197 :
198 0 : set unreadMessages(int newVal) {
199 0 : this._unreadMessages = newVal;
200 0 : notifyListeners();
201 : }
202 :
203 0 : void recountUnread() {
204 0 : this._unreadMessages = _contacts.contacts.fold(0, (i, c) => i + c.unreadMessages);
205 : }
206 :
207 : // Remove a contact from a list. Currently only used when rejecting a group invitation.
208 : // Eventually will also be used for other removals.
209 0 : void removeContact(String handle) {
210 0 : this.contactList.removeContactByHandle(handle);
211 0 : notifyListeners();
212 : }
213 :
214 0 : ContactListState get contactList => this._contacts;
215 :
216 0 : ProfileServerListState get serverList => this._servers;
217 :
218 0 : SearchState get searchState => this._searchState;
219 :
220 0 : List<ContactInfoState> filteredList() {
221 0 : if (!this._searchState.isFiltered) return this._contacts.contacts;
222 0 : return this._contacts.contacts.where((ContactInfoState c) => c.onion.toLowerCase().startsWith(this._searchState.filter) || (c.nickname.toLowerCase().contains(this._searchState.filter))).toList();
223 : }
224 :
225 0 : @override
226 : void dispose() {
227 0 : super.dispose();
228 : }
229 :
230 0 : void updateFrom(String onion, String name, String picture, String contactsJson, String serverJson, bool online) {
231 0 : this._nickname = name;
232 0 : this._imagePath = picture;
233 0 : this._online = online;
234 0 : this._unreadMessages = 0;
235 0 : this.replaceServers(serverJson);
236 :
237 0 : if (contactsJson != "" && contactsJson != "null") {
238 0 : List<dynamic> contacts = jsonDecode(contactsJson);
239 0 : contacts.forEach((contact) {
240 0 : var profileContact = this._contacts.getContact(contact["identifier"]);
241 0 : this._unreadMessages += contact["numUnread"] as int;
242 : if (profileContact != null) {
243 0 : profileContact.status = contact["status"];
244 :
245 0 : var newCount = contact["numMessages"] as int;
246 0 : if (newCount != profileContact.totalMessages) {
247 0 : if (newCount < profileContact.totalMessages) {
248 : // on Android, when sharing a file the UI may be briefly unloaded for the
249 : // OS to display the file management/selection screen. Afterwards a
250 : // call to ReconnectCwtchForeground will be made which will refresh all values (including count of numMessages)
251 : // **at the same time** the foreground will increment .totalMessages and send a new message to the backend.
252 : // This will result in a negative number of messages being calculated here, and an incorrect totalMessage count.
253 : // This bug is exacerbated in debug mode, and when multiple files are sent in succession. Both cases result in multiple ReconnectCwtchForeground
254 : // events that have the potential to conflict with currentMessageCounts.
255 : // Note that *if* a new message came in at the same time, we would be unable to distinguish this case - as such this is specific instance of a more general problem
256 : // TODO: A true-fix to this bug is to implement a syncing step in the foreground where totalMessages and inFlightMessages can be distinguished
257 : // This requires a change to the backend to confirm submission of an inFlightMessage, which will be implemented in #664
258 0 : EnvironmentConfig.debugLog("Conflicting message counts: $newCount ${profileContact.totalMessages}");
259 0 : newCount = max(newCount, profileContact.totalMessages);
260 : }
261 0 : profileContact.messageCache.addFrontIndexGap(newCount - profileContact.totalMessages);
262 : }
263 0 : profileContact.totalMessages = newCount;
264 0 : profileContact.unreadMessages = contact["numUnread"];
265 0 : profileContact.lastMessageReceivedTime = DateTime.fromMillisecondsSinceEpoch(1000 * int.parse(contact["lastMsgTime"]));
266 : } else {
267 0 : this._contacts.add(ContactInfoState(
268 0 : this.onion,
269 0 : contact["identifier"],
270 0 : contact["onion"],
271 0 : nickname: contact["name"],
272 0 : defaultImagePath: contact["defaultPicture"],
273 0 : status: contact["status"],
274 0 : imagePath: contact["picture"],
275 0 : accepted: contact["accepted"],
276 0 : blocked: contact["blocked"],
277 0 : savePeerHistory: contact["saveConversationHistory"],
278 0 : numMessages: contact["numMessages"],
279 0 : numUnread: contact["numUnread"],
280 0 : isGroup: contact["isGroup"],
281 0 : server: contact["groupServer"],
282 0 : lastMessageTime: DateTime.fromMillisecondsSinceEpoch(1000 * int.parse(contact["lastMsgTime"])),
283 0 : notificationPolicy: contact["notificationPolicy"] ?? "ConversationNotificationPolicy.Default",
284 : ));
285 : }
286 : });
287 : }
288 0 : this._contacts.resort();
289 : }
290 :
291 0 : void newMessage(
292 : int identifier, int messageID, DateTime timestamp, String senderHandle, String senderImage, bool isAuto, String data, String contenthash, bool selectedProfile, bool selectedConversation) {
293 : if (!selectedProfile) {
294 0 : unreadMessages++;
295 0 : notifyListeners();
296 : }
297 :
298 0 : contactList.newMessage(identifier, messageID, timestamp, senderHandle, senderImage, isAuto, data, contenthash, selectedConversation);
299 : }
300 :
301 0 : void downloadInit(String fileKey, int numChunks) {
302 0 : this._downloads[fileKey] = FileDownloadProgress(numChunks, DateTime.now());
303 0 : notifyListeners();
304 : }
305 :
306 0 : void downloadUpdate(String fileKey, int progress, int numChunks) {
307 0 : if (!downloadActive(fileKey)) {
308 0 : this._downloads[fileKey] = FileDownloadProgress(numChunks, DateTime.now());
309 0 : if (progress < 0) {
310 0 : this._downloads[fileKey]!.interrupted = true;
311 : }
312 : } else {
313 0 : if (this._downloads[fileKey]!.interrupted) {
314 0 : this._downloads[fileKey]!.interrupted = false;
315 : }
316 0 : this._downloads[fileKey]!.chunksDownloaded = progress;
317 0 : this._downloads[fileKey]!.chunksTotal = numChunks;
318 0 : this._downloads[fileKey]!.markUpdate();
319 : }
320 0 : notifyListeners();
321 : }
322 :
323 0 : void downloadMarkManifest(String fileKey) {
324 0 : if (!downloadActive(fileKey)) {
325 0 : this._downloads[fileKey] = FileDownloadProgress(1, DateTime.now());
326 : }
327 0 : this._downloads[fileKey]!.gotManifest = true;
328 0 : this._downloads[fileKey]!.markUpdate();
329 0 : notifyListeners();
330 : }
331 :
332 0 : void downloadMarkFinished(String fileKey, String finalPath) {
333 0 : if (!downloadActive(fileKey)) {
334 : // happens as a result of a CheckDownloadStatus call,
335 : // invoked from a historical (timeline) download message
336 : // so setting numChunks correctly shouldn't matter
337 0 : this.downloadInit(fileKey, 1);
338 : }
339 :
340 : // Update the contact with a custom profile image if we are
341 : // waiting for one...
342 0 : if (this._downloadTriggers.containsKey(fileKey)) {
343 0 : int identifier = this._downloadTriggers[fileKey]!;
344 0 : this.contactList.getContact(identifier)!.imagePath = finalPath;
345 0 : notifyListeners();
346 : }
347 :
348 : // only update if different
349 0 : if (!this._downloads[fileKey]!.complete) {
350 0 : this._downloads[fileKey]!.timeEnd = DateTime.now();
351 0 : this._downloads[fileKey]!.downloadedTo = finalPath;
352 0 : this._downloads[fileKey]!.complete = true;
353 0 : this._downloads[fileKey]!.markUpdate();
354 0 : notifyListeners();
355 : }
356 : }
357 :
358 0 : bool downloadKnown(String fileKey) {
359 0 : return this._downloads.containsKey(fileKey);
360 : }
361 :
362 0 : bool downloadActive(String fileKey) {
363 0 : return this._downloads.containsKey(fileKey) && !this._downloads[fileKey]!.interrupted;
364 : }
365 :
366 0 : bool downloadGotManifest(String fileKey) {
367 0 : return this._downloads.containsKey(fileKey) && this._downloads[fileKey]!.gotManifest;
368 : }
369 :
370 0 : bool downloadComplete(String fileKey) {
371 0 : return this._downloads.containsKey(fileKey) && this._downloads[fileKey]!.complete;
372 : }
373 :
374 0 : bool downloadInterrupted(String fileKey) {
375 0 : if (this._downloads.containsKey(fileKey)) {
376 0 : if (this._downloads[fileKey]!.interrupted) {
377 : return true;
378 : }
379 : }
380 : return false;
381 : }
382 :
383 0 : void downloadMarkResumed(String fileKey) {
384 0 : if (this._downloads.containsKey(fileKey)) {
385 0 : this._downloads[fileKey]!.interrupted = false;
386 0 : this._downloads[fileKey]!.requested = DateTime.now();
387 0 : this._downloads[fileKey]!.markUpdate();
388 0 : notifyListeners();
389 : }
390 : }
391 :
392 0 : double downloadProgress(String fileKey) {
393 0 : return this._downloads.containsKey(fileKey) ? this._downloads[fileKey]!.progress() : 0.0;
394 : }
395 :
396 : // used for loading interrupted download info; use downloadMarkFinished for successful downloads
397 0 : void downloadSetPath(String fileKey, String path) {
398 0 : if (this._downloads.containsKey(fileKey)) {
399 0 : this._downloads[fileKey]!.downloadedTo = path;
400 0 : notifyListeners();
401 : }
402 : }
403 :
404 : // set the download path for the sender
405 0 : void downloadSetPathForSender(String fileKey, String path) {
406 : // we may trigger this event for auto-downloaded receivers too,
407 : // as such we don't assume anything else about the file...other than that
408 : // it exists.
409 0 : if (!this._downloads.containsKey(fileKey)) {
410 : // this will be overwritten by download update if the file is being downloaded
411 0 : this._downloads[fileKey] = FileDownloadProgress(1, DateTime.now());
412 : }
413 0 : this._downloads[fileKey]!.downloadedTo = path;
414 0 : notifyListeners();
415 : }
416 :
417 0 : String? downloadFinalPath(String fileKey) {
418 0 : return this._downloads.containsKey(fileKey) ? this._downloads[fileKey]!.downloadedTo : null;
419 : }
420 :
421 0 : String downloadSpeed(String fileKey) {
422 0 : if (!downloadActive(fileKey) || this._downloads[fileKey]!.chunksDownloaded == 0) {
423 : return "0 B/s";
424 : }
425 0 : var bytes = this._downloads[fileKey]!.chunksDownloaded * 4096;
426 0 : var seconds = (this._downloads[fileKey]!.timeEnd ?? DateTime.now()).difference(this._downloads[fileKey]!.timeStart!).inSeconds;
427 0 : if (seconds == 0) {
428 : return "0 B/s";
429 : }
430 0 : return prettyBytes((bytes / seconds).round()) + "/s";
431 : }
432 :
433 0 : void waitForDownloadComplete(int identifier, String fileKey) {
434 0 : _downloadTriggers[fileKey] = identifier;
435 0 : notifyListeners();
436 : }
437 :
438 0 : int cacheMemUsage() {
439 0 : return _contacts.cacheMemUsage();
440 : }
441 :
442 0 : void downloadReset(String fileKey) {
443 0 : this._downloads.remove(fileKey);
444 0 : notifyListeners();
445 : }
446 :
447 0 : String getPrivateName() {
448 0 : return _privateName;
449 : }
450 :
451 0 : void setPrivateName(String pn) {
452 0 : _privateName = pn;
453 0 : notifyListeners();
454 : }
455 :
456 : // Profile Attributes. Can be set in Profile Edit View...
457 : List<String?> attributes = [null, null, null];
458 0 : void setAttribute(int i, String? value) {
459 0 : this.attributes[i] = value;
460 0 : notifyListeners();
461 : }
462 :
463 : ProfileStatusMenu availabilityStatus = ProfileStatusMenu.available;
464 0 : void setAvailabilityStatus(String status) {
465 : switch (status) {
466 0 : case "available":
467 0 : availabilityStatus = ProfileStatusMenu.available;
468 : break;
469 0 : case "busy":
470 0 : availabilityStatus = ProfileStatusMenu.busy;
471 : break;
472 0 : case "away":
473 0 : availabilityStatus = ProfileStatusMenu.away;
474 : break;
475 : default:
476 : ProfileStatusMenu.available;
477 : }
478 0 : notifyListeners();
479 : }
480 :
481 0 : Color getBorderColor(OpaqueThemeType theme) {
482 0 : switch (this.availabilityStatus) {
483 0 : case ProfileStatusMenu.available:
484 0 : return theme.portraitOnlineBorderColor;
485 0 : case ProfileStatusMenu.away:
486 0 : return theme.portraitOnlineAwayColor;
487 0 : case ProfileStatusMenu.busy:
488 0 : return theme.portraitOnlineBusyColor;
489 : default:
490 0 : throw UnimplementedError("not a valid status");
491 : }
492 : }
493 :
494 : // during deactivation it is possible that the event bus is cleaned up prior to statuses being updated
495 : // this method nicely cleans up our current state so that the UI functions as expected.
496 : // FIXME: Cwtch should be sending these events prior to shutting down the engine...
497 0 : void deactivatePeerEngine(BuildContext context) {
498 0 : Provider.of<FlwtchState>(context, listen: false).cwtch.DeactivatePeerEngine(onion);
499 0 : this.contactList.contacts.forEach((element) {
500 0 : element.status = "Disconnected";
501 : // reset retry time to allow for instant reconnection...
502 0 : element.lastRetryTime = element.loaded;
503 : });
504 0 : this.serverList.servers.forEach((element) {
505 0 : element.status = "Disconnected";
506 : });
507 : }
508 : }
|