LCOV - code coverage report
Current view: top level - lib/models - profile.dart (source / functions) Hit Total Coverage
Test: lcov.info Lines: 0 270 0.0 %
Date: 2026-07-15 19:28:30 Functions: 0 0 -

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

Generated by: LCOV version 1.14