LCOV - code coverage report
Current view: top level - lib/cwtch - cwtchNotifier.dart (source / functions) Hit Total Coverage
Test: lcov.info Lines: 0 352 0.0 %
Date: 2026-08-31 22:32:18 Functions: 0 0 -

          Line data    Source code
       1             : import 'dart:convert';
       2             : import 'package:cwtch/cwtch/cwtch.dart';
       3             : import 'package:cwtch/main.dart';
       4             : import 'package:cwtch/models/appstate.dart';
       5             : import 'package:cwtch/models/contact.dart';
       6             : import 'package:cwtch/models/groupmembers.dart';
       7             : import 'package:cwtch/models/hybridgroups.dart';
       8             : import 'package:cwtch/models/profilelist.dart';
       9             : import 'package:cwtch/models/remoteserver.dart';
      10             : import 'package:cwtch/models/search.dart';
      11             : import 'package:cwtch/models/servers.dart';
      12             : import 'package:cwtch/notification_manager.dart';
      13             : 
      14             : import 'package:cwtch/torstatus.dart';
      15             : 
      16             : import '../config.dart';
      17             : import '../errorHandler.dart';
      18             : import '../settings.dart';
      19             : 
      20             : typedef SeenMessageCallback = Function(String, int, DateTime);
      21             : 
      22             : // Class that handles libcwtch-go events (received either via ffi with an isolate or gomobile over a method channel from kotlin)
      23             : //   Takes Notifiers and triggers them on appropriate events
      24             : class CwtchNotifier {
      25             :   late ProfileListState profileCN;
      26             :   late Settings settings;
      27             :   late ErrorHandler error;
      28             :   late TorStatus torStatus;
      29             :   late NotificationsManager notificationManager;
      30             :   late AppState appState;
      31             :   late ServerListState serverListState;
      32             :   late HybridGroupsListState groupListState;
      33             :   late FlwtchState flwtchState;
      34             : 
      35             :   String? notificationSimple;
      36             :   String? notificationConversationInfo;
      37             : 
      38             :   SeenMessageCallback? seenMessageCallback;
      39             : 
      40           0 :   CwtchNotifier(
      41             :     ProfileListState pcn,
      42             :     Settings settingsCN,
      43             :     ErrorHandler errorCN,
      44             :     TorStatus torStatusCN,
      45             :     NotificationsManager notificationManagerP,
      46             :     AppState appStateCN,
      47             :     ServerListState serverListStateCN,
      48             :     HybridGroupsListState groupListStateCN,
      49             :     FlwtchState flwtchStateCN,
      50             :   ) {
      51           0 :     profileCN = pcn;
      52           0 :     settings = settingsCN;
      53           0 :     error = errorCN;
      54           0 :     torStatus = torStatusCN;
      55           0 :     notificationManager = notificationManagerP;
      56           0 :     appState = appStateCN;
      57           0 :     serverListState = serverListStateCN;
      58           0 :     groupListState = groupListStateCN;
      59           0 :     flwtchState = flwtchStateCN;
      60             :   }
      61             : 
      62           0 :   void l10nInit(String notificationSimple, String notificationConversationInfo) {
      63           0 :     this.notificationSimple = notificationSimple;
      64           0 :     this.notificationConversationInfo = notificationConversationInfo;
      65             :   }
      66             : 
      67           0 :   void setMessageSeenCallback(SeenMessageCallback callback) {
      68           0 :     seenMessageCallback = callback;
      69             :   }
      70             : 
      71           0 :   void handleMessage(String type, dynamic data) {
      72             :     // EnvironmentConfig.debugLog("NewEvent $type $data");
      73             :     switch (type) {
      74           0 :       case "CwtchStarted":
      75           0 :         if (data["Reload"] == "true" && profileCN.num > 0) {
      76             :           // don't reload...
      77             :           // unless we have loaded no profiles...then there isnt a risk and this
      78             :           // might be a first time (e.g. new apk, existing service)
      79             :         } else {
      80           0 :           flwtchState.cwtch.LoadProfiles(DefaultPassword);
      81             :         }
      82             : 
      83           0 :         appState.SetCwtchInit();
      84             :         break;
      85           0 :       case "CwtchStartError":
      86           0 :         appState.SetAppError(data["Error"]);
      87             :         break;
      88           0 :       case "NewPeer":
      89           0 :         if (data["tag"] == "v1-managedGroup") break;
      90             : 
      91             :         // else if tag != v1-defaultPassword then it is either encrypted OR it is an unencrypted account created during pre-beta...
      92           0 :         profileCN.add(
      93           0 :           data["Identity"],
      94           0 :           data["name"],
      95           0 :           data["private-name"],
      96           0 :           data["picture"],
      97           0 :           data["defaultPicture"],
      98           0 :           data["ContactsJson"],
      99           0 :           data["ServerList"],
     100           0 :           data["Online"] == "true",
     101           0 :           data["autostart"] == "true",
     102           0 :           data["tag"] != "v1-defaultPassword",
     103           0 :           data["appearOffline"] == "true",
     104             :         );
     105             : 
     106             :         // Update Profile Attributes
     107           0 :         flwtchState.cwtch.GetProfileAttribute(data["Identity"], "profile.profile-attribute-1").then((value) => profileCN.getProfile(data["Identity"])?.setAttribute(0, value));
     108           0 :         flwtchState.cwtch.GetProfileAttribute(data["Identity"], "profile.profile-attribute-2").then((value) => profileCN.getProfile(data["Identity"])?.setAttribute(1, value));
     109           0 :         flwtchState.cwtch.GetProfileAttribute(data["Identity"], "profile.profile-attribute-3").then((value) => profileCN.getProfile(data["Identity"])?.setAttribute(2, value));
     110           0 :         flwtchState.cwtch.GetProfileAttribute(data["Identity"], "profile.profile-status").then((value) => profileCN.getProfile(data["Identity"])?.setAvailabilityStatus(value ?? ""));
     111             : 
     112           0 :         profileCN.getProfile(data["Identity"])?.contactList.contacts.forEach((contact) {
     113           0 :           flwtchState.cwtch.GetConversationAttribute(data["Identity"], contact.identifier, "public.profile.profile-attribute-1").then((value) => contact.setAttribute(0, value));
     114           0 :           flwtchState.cwtch.GetConversationAttribute(data["Identity"], contact.identifier, "public.profile.profile-attribute-2").then((value) => contact.setAttribute(1, value));
     115           0 :           flwtchState.cwtch.GetConversationAttribute(data["Identity"], contact.identifier, "public.profile.profile-attribute-3").then((value) => contact.setAttribute(2, value));
     116           0 :           flwtchState.cwtch.GetConversationAttribute(data["Identity"], contact.identifier, "public.profile.profile-status").then((value) => contact.setAvailabilityStatus(value ?? ""));
     117             :         });
     118             : 
     119             :         break;
     120             : 
     121           0 :       case "ContactCreated":
     122           0 :         var contact = profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(int.parse(data["ConversationID"]));
     123             :         if (contact != null) {
     124           0 :           contact.accepted = (data["accepted"] == "true");
     125           0 :           contact.isShadowed = (data["Shadowed"] == "true");
     126             :         } else {
     127           0 :           profileCN
     128           0 :               .getProfile(data["ProfileOnion"])
     129           0 :               ?.contactList
     130           0 :               .add(
     131           0 :                 ContactInfoState(
     132           0 :                   data["ProfileOnion"],
     133           0 :                   int.parse(data["ConversationID"]),
     134           0 :                   data["RemotePeer"],
     135           0 :                   nickname: data["nick"],
     136           0 :                   status: data["status"],
     137           0 :                   imagePath: data["picture"],
     138           0 :                   defaultImagePath: data["defaultPicture"],
     139           0 :                   blocked: data["blocked"] == "true",
     140           0 :                   accepted: data["accepted"] == "true",
     141           0 :                   savePeerHistory: data["saveConversationHistory"] == null ? "DeleteHistoryConfirmed" : data["saveConversationHistory"],
     142           0 :                   numMessages: int.parse(data["numMessages"]),
     143           0 :                   numUnread: int.parse(data["unread"]),
     144             :                   isGroup: false, // by definition
     145             :                   server: null,
     146             :                   archived: false,
     147           0 :                   lastMessageTime: DateTime.now(), //show at the top of the contact list even if no messages yet
     148           0 :                   notificationPolicy: data["notificationPolicy"] ?? "ConversationNotificationPolicy.Default",
     149           0 :                   isManaged: data["managed"] == "true",
     150             :                 ),
     151             :               );
     152           0 :           contact = profileCN.getProfile(data["ProfileOnion"])?.contactList.findContact(data["RemotePeer"]);
     153           0 :           contact!.isShadowed = data["Shadowed"] == "true";
     154             :         }
     155             : 
     156             :         break;
     157           0 :       case "NewServer":
     158           0 :         serverListState.add(data["Onion"], data["ServerBundle"], data["Running"] == "true", data["Description"], data["Autostart"] == "true", data["StorageType"] == "storage-password");
     159             :         break;
     160           0 :       case "ServerIntentUpdate":
     161           0 :         var server = serverListState.getServer(data["Identity"]);
     162             :         if (server != null) {
     163           0 :           server.setRunning(data["Intent"] == "running");
     164             :         }
     165             :         break;
     166           0 :       case "ServerStatsUpdate":
     167           0 :         EnvironmentConfig.debugLog("ServerStatsUpdate $data");
     168           0 :         var totalMessages = int.parse(data["TotalMessages"]);
     169           0 :         var connections = int.parse(data["Connections"]);
     170           0 :         serverListState.updateServerStats(data["Identity"], totalMessages, connections);
     171             :         break;
     172           0 :       case "GroupCreated":
     173             :         // Retrieve Server Status from Cache...
     174             :         String status = "";
     175           0 :         RemoteServerInfoState? serverInfoState = profileCN.getProfile(data["ProfileOnion"])?.serverList.getServer(data["GroupServer"]);
     176             :         if (serverInfoState != null) {
     177           0 :           status = serverInfoState.status;
     178             :         }
     179           0 :         if (profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(int.parse(data["ConversationID"])) == null) {
     180           0 :           profileCN
     181           0 :               .getProfile(data["ProfileOnion"])
     182           0 :               ?.contactList
     183           0 :               .add(
     184           0 :                 ContactInfoState(
     185           0 :                   data["ProfileOnion"],
     186           0 :                   int.parse(data["ConversationID"]),
     187           0 :                   data["GroupID"],
     188             :                   blocked: false, // we created
     189             :                   accepted: true, // we created
     190           0 :                   imagePath: data["picture"],
     191           0 :                   defaultImagePath: data["picture"],
     192           0 :                   nickname: data["GroupName"],
     193             :                   status: status,
     194           0 :                   server: data["GroupServer"],
     195             :                   isGroup: true,
     196           0 :                   lastMessageTime: DateTime.now(),
     197           0 :                   notificationPolicy: data["notificationPolicy"] ?? "ConversationNotificationPolicy.Default",
     198             :                 ),
     199             :               );
     200             : 
     201           0 :           profileCN.getProfile(data["ProfileOnion"])?.contactList.updateLastMessageReceivedTime(int.parse(data["ConversationID"]), DateTime.now());
     202             :         }
     203             :         break;
     204           0 :       case "PeerDeleted":
     205           0 :         profileCN.delete(data["Identity"]);
     206             :         // todo standarize
     207           0 :         error.handleUpdate("deleteprofile.success");
     208             :         break;
     209           0 :       case "ServerDeleted":
     210           0 :         error.handleUpdate("deletedserver." + data["Status"]);
     211           0 :         if (data["Status"] == "success") {
     212           0 :           serverListState.delete(data["Identity"]);
     213             :         }
     214             :         break;
     215           0 :       case "DeleteContact":
     216           0 :         var identifier = int.parse(data["ConversationID"]);
     217           0 :         profileCN.getProfile(data["ProfileOnion"])?.contactList.removeContact(identifier);
     218             :         break;
     219           0 :       case "PeerStateChange":
     220           0 :         ContactInfoState? contact = profileCN.getProfile(data["ProfileOnion"])?.contactList.findContact(data["RemotePeer"]);
     221             :         if (contact != null) {
     222           0 :           if (data["ConnectionState"] != null) {
     223           0 :             contact.status = data["ConnectionState"];
     224             :           }
     225           0 :           profileCN.getProfile(data["ProfileOnion"])?.resortContacts();
     226             :         }
     227             :         break;
     228           0 :       case "NewMessageFromPeer":
     229           0 :         var identifier = int.parse(data["ConversationID"]);
     230           0 :         var messageID = int.parse(data["Index"]);
     231           0 :         var timestamp = DateTime.tryParse(data['TimestampReceived'])!;
     232           0 :         var senderHandle = data['RemotePeer'];
     233           0 :         var senderImage = data['picture'];
     234           0 :         var isAuto = data['Auto'] == "true";
     235           0 :         String contenthash = data['ContentHash'];
     236             : 
     237             :         try {
     238           0 :           dynamic message = jsonDecode(data["Data"]);
     239           0 :           var overlay = int.parse(message['o'].toString());
     240           0 :           if (overlay > 1024 && overlay & 0x07 != 0) {
     241             :             break;
     242             :           }
     243             :         } catch (e) {
     244             :           // malformed message...
     245             :         }
     246             : 
     247           0 :         var selectedProfile = appState.selectedProfile == data["ProfileOnion"];
     248           0 :         var selectedConversation = selectedProfile && appState.selectedConversation == identifier;
     249           0 :         profileCN
     250           0 :             .getProfile(data["ProfileOnion"])
     251           0 :             ?.newMessage(identifier, messageID, timestamp, senderHandle, senderImage, isAuto, data["Data"], contenthash, selectedProfile, selectedConversation, "");
     252             : 
     253             :         // Now perform the notification logic...
     254           0 :         var notification = data["notification"];
     255           0 :         if (selectedConversation && seenMessageCallback != null) {
     256           0 :           seenMessageCallback!(data["ProfileOnion"]!, identifier, DateTime.now().toUtc());
     257             :         }
     258             : 
     259           0 :         if (notification == "SimpleEvent") {
     260           0 :           notificationManager.notify(notificationSimple ?? "New Message", "", 0);
     261           0 :         } else if (notification == "ContactInfo") {
     262           0 :           var contact = profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(identifier);
     263           0 :           notificationManager.notify((notificationConversationInfo ?? "New Message from %1").replaceFirst("%1", (contact?.nickname ?? senderHandle.toString())), data["ProfileOnion"], identifier);
     264             :         }
     265           0 :         appState.notifyProfileUnread();
     266             :         break;
     267           0 :       case "PeerAcknowledgement":
     268             :         // We don't use these anymore, IndexedAcknowledgement is more suited to the UI front end...
     269             :         break;
     270           0 :       case "IndexedAcknowledgement":
     271           0 :         var conversation = int.parse(data["ConversationID"]);
     272           0 :         var messageID = int.parse(data["Index"]);
     273             : 
     274             :         // We only ever see acks from authenticated peers.
     275             :         // If the contact is marked as offline then override this - can happen when the contact is removed from the front
     276             :         // end during syncing.
     277           0 :         if (profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(conversation)!.isOnline() == false) {
     278           0 :           profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(conversation)!.status = "Authenticated";
     279             :         }
     280           0 :         profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(conversation)!.ackCache(messageID);
     281             : 
     282             :         break;
     283           0 :       case "NewMessageFromGroup":
     284           0 :         var identifier = int.parse(data["ConversationID"]);
     285           0 :         if (data["ProfileOnion"] != data["RemotePeer"]) {
     286           0 :           var idx = int.parse(data["Index"]);
     287           0 :           var senderHandle = data['RemotePeer'];
     288           0 :           var senderImage = data['picture'];
     289           0 :           var timestampSent = DateTime.tryParse(data['TimestampSent'])!;
     290           0 :           var contact = profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(identifier);
     291           0 :           var currentTotal = contact!.totalMessages;
     292           0 :           var isAuto = data['Auto'] == "true";
     293           0 :           String contenthash = data['ContentHash'];
     294           0 :           var selectedProfile = appState.selectedProfile == data["ProfileOnion"];
     295           0 :           var selectedConversation = selectedProfile && appState.selectedConversation == identifier;
     296           0 :           var notification = data["notification"];
     297           0 :           var signature = data["Signature"] ?? "";
     298             : 
     299             :           // Only bother to do anything if we know about the group and the provided index is greater than our current total...
     300           0 :           if (idx >= currentTotal) {
     301             :             // TODO: There are 2 timestamps associated with a new group message - time sent and time received.
     302             :             // Sent refers to the time a profile alleges they sent a message
     303             :             // Received refers to the time we actually saw the message from the server
     304             :             // These can obviously be very different for legitimate reasons.
     305             :             // We also maintain a relative hash-link through PreviousMessageSignature which is the ground truth for
     306             :             // order.
     307             :             // In the future we will want to combine these 3 ordering mechanisms into a cohesive view of the timeline
     308             :             // For now we perform some minimal checks on the sent timestamp to use to provide a useful ordering for honest contacts
     309             :             // and ensure that malicious contacts in groups can only set this timestamp to a value within the range of `last seen message time`
     310             :             // and `local now`.
     311           0 :             profileCN
     312           0 :                 .getProfile(data["ProfileOnion"])
     313           0 :                 ?.newMessage(identifier, idx, timestampSent, senderHandle, senderImage, isAuto, data["Data"], contenthash, selectedProfile, selectedConversation, signature);
     314           0 :             if (selectedConversation && seenMessageCallback != null) {
     315           0 :               seenMessageCallback!(data["ProfileOnion"]!, identifier, DateTime.now().toUtc());
     316             :             }
     317             : 
     318           0 :             if (notification == "SimpleEvent") {
     319           0 :               notificationManager.notify(notificationSimple ?? "New Message", "", 0);
     320           0 :             } else if (notification == "ContactInfo") {
     321           0 :               var contact = profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(identifier);
     322           0 :               notificationManager.notify((notificationConversationInfo ?? "New Message from %1").replaceFirst("%1", (contact?.nickname ?? senderHandle.toString())), data["ProfileOnion"], identifier);
     323             :             }
     324           0 :             appState.notifyProfileUnread();
     325             :           }
     326           0 :           RemoteServerInfoState? server = profileCN.getProfile(data["ProfileOnion"])?.serverList.getServer(contact.server ?? "");
     327           0 :           server?.updateSyncProgressFor(timestampSent);
     328             :         } else {
     329             :           // This is dealt with by IndexedAcknowledgment
     330           0 :           EnvironmentConfig.debugLog("new message from group from yourself - this should not happen");
     331             :         }
     332             :         break;
     333           0 :       case "IndexedFailure":
     334           0 :         var identifier = int.parse(data["ConversationID"]);
     335           0 :         var contact = profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(identifier);
     336           0 :         var messageID = int.parse(data["Index"]);
     337           0 :         contact?.errCache(messageID);
     338             :         break;
     339           0 :       case "AppError":
     340           0 :         EnvironmentConfig.debugLog("New App Error: $data");
     341             :         // special case for delete error (todo: standardize cwtch errors)
     342           0 :         if (data["Error"] == "Password did not match") {
     343           0 :           error.handleUpdate("deleteprofile.error");
     344           0 :         } else if (data["Data"] != null) {
     345           0 :           error.handleUpdate(data["Data"]);
     346             :         }
     347             :         break;
     348           0 :       case "UpdateGlobalSettings":
     349           0 :         settings.handleUpdate(jsonDecode(data["Data"]));
     350           0 :         appState.settingsLoaded = true;
     351             :         break;
     352           0 :       case "UpdatedProfileAttribute":
     353           0 :         if (data["Key"] == "public.profile.name") {
     354           0 :           profileCN.getProfile(data["ProfileOnion"])?.nickname = data["Data"];
     355           0 :         } else if (data["Key"].toString().startsWith("local.filesharing.")) {
     356           0 :           if (data["Key"].toString().endsWith(".path")) {
     357             :             // local.conversation.filekey.path
     358           0 :             List<String> keyparts = data["Key"].toString().split(".");
     359           0 :             if (keyparts.length == 5) {
     360           0 :               String filekey = keyparts[2] + "." + keyparts[3];
     361           0 :               profileCN.getProfile(data["ProfileOnion"])?.downloadSetPathForSender(filekey, data["Data"]);
     362             :             }
     363             :           }
     364           0 :         } else if (data["Key"].toString().startsWith("local.profile.private-name")) {
     365           0 :           profileCN.getProfile(data["ProfileOnion"])?.setPrivateName(data["Data"]);
     366           0 :         } else if (data["Key"].toString().startsWith("public.profile.profile-attribute")) {
     367             :           // ignore these events...
     368           0 :         } else if (data["Key"].toString().startsWith("public.profile.profile-status")) {
     369           0 :           profileCN.getProfile(data["ProfileOnion"])?.setAvailabilityStatus(data["Data"]);
     370             :         } else {
     371           0 :           EnvironmentConfig.debugLog("unhandled set attribute event: ${data['Key']}");
     372             :         }
     373             :         break;
     374           0 :       case "NetworkError":
     375           0 :         var isOnline = data["Status"] == "Success";
     376           0 :         profileCN.getProfile(data["ProfileOnion"])?.isOnline = isOnline;
     377             :         break;
     378           0 :       case "ACNStatus":
     379           0 :         EnvironmentConfig.debugLog("acn status: $data");
     380           0 :         torStatus.handleUpdate(int.parse(data["Progress"]), data["Status"]);
     381             :         break;
     382           0 :       case "ACNVersion":
     383           0 :         EnvironmentConfig.debugLog("acn version: $data");
     384           0 :         torStatus.updateVersion(data["Data"]);
     385             :         break;
     386           0 :       case "UpdateServerInfo":
     387           0 :         EnvironmentConfig.debugLog("NewEvent  UpdateServerInfo $type $data");
     388           0 :         profileCN.getProfile(data["ProfileOnion"])?.replaceServers(data["ServerList"]);
     389             :         break;
     390           0 :       case "TokenManagerInfo":
     391             :         try {
     392           0 :           List<dynamic> associatedGroups = jsonDecode(data["Data"]);
     393           0 :           int count = int.parse(data["ServerTokenCount"]);
     394           0 :           associatedGroups.forEach((identifier) {
     395           0 :             profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(int.parse(identifier.toString()))!.antispamTickets = count;
     396             :           });
     397           0 :           EnvironmentConfig.debugLog("update server token count for $associatedGroups, $count");
     398             :         } catch (e) {
     399             :           //  No tokens in data...
     400             :         }
     401             :         break;
     402           0 :       case "NewGroup":
     403           0 :         String invite = data["GroupInvite"].toString();
     404           0 :         if (invite.startsWith("torv3")) {
     405           0 :           String inviteJson = new String.fromCharCodes(base64Decode(invite.substring(5)));
     406           0 :           dynamic groupInvite = jsonDecode(inviteJson);
     407             : 
     408             :           // Retrieve Server Status from Cache...
     409             :           String status = "";
     410           0 :           RemoteServerInfoState? serverInfoState = profileCN.getProfile(data["ProfileOnion"])!.serverList.getServer(groupInvite["ServerHost"]);
     411             :           if (serverInfoState != null) {
     412           0 :             status = serverInfoState.status;
     413             :           }
     414             : 
     415           0 :           if (profileCN.getProfile(data["ProfileOnion"])?.contactList.findContact(groupInvite["GroupID"]) == null) {
     416           0 :             var identifier = int.parse(data["ConversationID"]);
     417           0 :             profileCN
     418           0 :                 .getProfile(data["ProfileOnion"])
     419           0 :                 ?.contactList
     420           0 :                 .add(
     421           0 :                   ContactInfoState(
     422           0 :                     data["ProfileOnion"],
     423             :                     identifier,
     424           0 :                     groupInvite["GroupID"],
     425             :                     blocked: false, // NewGroup only issued on accepting invite
     426             :                     accepted: true, // NewGroup only issued on accepting invite
     427           0 :                     imagePath: data["picture"],
     428           0 :                     nickname: groupInvite["GroupName"],
     429           0 :                     server: groupInvite["ServerHost"],
     430             :                     status: status,
     431             :                     isGroup: true,
     432           0 :                     lastMessageTime: DateTime.now(),
     433             :                   ),
     434             :                 );
     435             : 
     436           0 :             profileCN.getProfile(data["ProfileOnion"])?.contactList.updateLastMessageReceivedTime(identifier, DateTime.fromMillisecondsSinceEpoch(0));
     437             :           }
     438             :           // request a new server update...
     439             :           // NOTE: In the future this should also update the TokenManagerInfo
     440             :           // This is not currently communicated by ServerUpdateInfo (but it probably should be)
     441           0 :           flwtchState.cwtch.PublishServerUpdate(data["ProfileOnion"]);
     442             :         }
     443             :         break;
     444           0 :       case "ServerStateChange":
     445             :         // Update the Server Cache
     446           0 :         profileCN.getProfile(data["ProfileOnion"])?.updateServerStatusCache(data["GroupServer"], data["ConnectionState"]);
     447           0 :         profileCN.getProfile(data["ProfileOnion"])?.contactList.contacts.forEach((contact) {
     448           0 :           if (contact.isGroup == true && contact.server == data["GroupServer"]) {
     449           0 :             contact.status = data["ConnectionState"];
     450             :           }
     451             :         });
     452           0 :         profileCN.getProfile(data["ProfileOnion"])?.resortContacts();
     453             :         break;
     454           0 :       case "UpdatedConversationAttribute":
     455           0 :         if (data["Path"] == "profile.name") {
     456           0 :           if (data["Data"].toString().trim().length > 0) {
     457             :             // Update locally on the UI...
     458           0 :             if (profileCN.getProfile(data["ProfileOnion"])?.contactList.findContact(data["RemotePeer"]) != null) {
     459           0 :               profileCN.getProfile(data["ProfileOnion"])?.contactList.findContact(data["RemotePeer"])!.nickname = data["Data"];
     460             :             }
     461             :           }
     462           0 :         } else if (data['Path'] == "profile.custom-profile-image") {
     463           0 :           EnvironmentConfig.debugLog("received ret val of custom profile image: $data");
     464           0 :           String fileKey = data['Data'];
     465           0 :           var contact = profileCN.getProfile(data["ProfileOnion"])?.contactList.findContact(data["RemotePeer"]);
     466             :           if (contact != null) {
     467           0 :             EnvironmentConfig.debugLog("waiting for download from $contact");
     468           0 :             profileCN.getProfile(data["ProfileOnion"])?.waitForDownloadComplete(contact.identifier, fileKey);
     469             :           }
     470           0 :         } else if (data['Path'] == "profile.profile-attribute-1" || data['Path'] == "profile.profile-attribute-2" || data['Path'] == "profile.profile-attribute-3") {
     471           0 :           var contact = profileCN.getProfile(data["ProfileOnion"])?.contactList.findContact(data["RemotePeer"]);
     472             :           if (contact != null) {
     473           0 :             switch (data['Path']) {
     474           0 :               case "profile.profile-attribute-1":
     475           0 :                 contact.setAttribute(0, data["Data"]);
     476             :                 break;
     477           0 :               case "profile.profile-attribute-2":
     478           0 :                 contact.setAttribute(1, data["Data"]);
     479             :                 break;
     480           0 :               case "profile.profile-attribute-3":
     481           0 :                 contact.setAttribute(2, data["Data"]);
     482             :                 break;
     483             :             }
     484             :           }
     485           0 :         } else if (data['Path'] == "profile.profile-status") {
     486           0 :           var contact = profileCN.getProfile(data["ProfileOnion"])?.contactList.findContact(data["RemotePeer"]);
     487             :           if (contact != null) {
     488           0 :             contact.setAvailabilityStatus(data['Data']);
     489             :           }
     490           0 :         } else if (data['Path'] == 'conversation.shadowed') {
     491           0 :           var contact = profileCN.getProfile(data["ProfileOnion"])?.contactList.findContact(data["RemotePeer"]);
     492             :           if (contact != null) {
     493           0 :             contact.isShadowed = data['Data'] == "true";
     494             :           }
     495           0 :         } else if (data['Path'] == 'filesharing.custom-profile-image-path') {
     496             :           //ignore
     497             :         } else {
     498           0 :           EnvironmentConfig.debugLog("unhandled ret val event: ${data['Path']}");
     499             :         }
     500           0 :         var c = profileCN.getProfile(data["ProfileOnion"])?.contactList.findContact(data["RemotePeer"]);
     501           0 :         if (c != null && c.isManaged) {
     502           0 :           profileCN.getProfile(data["ProfileOnion"])?.contactList.findContact(data["RemotePeer"])?.isOpPending = false;
     503             :         }
     504             :         break;
     505           0 :       case "ManifestSizeReceived":
     506           0 :         if (profileCN.getProfile(data["ProfileOnion"]) == null) {
     507             :           break;
     508             :         }
     509           0 :         if (!profileCN.getProfile(data["ProfileOnion"])!.downloadActive(data["FileKey"])) {
     510           0 :           profileCN.getProfile(data["ProfileOnion"])?.downloadUpdate(data["FileKey"], 0, 1);
     511             :         }
     512             :         break;
     513           0 :       case "ManifestSaved":
     514           0 :         profileCN.getProfile(data["ProfileOnion"])?.downloadMarkManifest(data["FileKey"]);
     515             :         break;
     516           0 :       case "FileDownloadProgressUpdate":
     517           0 :         var progress = int.parse(data["Progress"]);
     518           0 :         profileCN.getProfile(data["ProfileOnion"])?.downloadUpdate(data["FileKey"], progress, int.parse(data["FileSizeInChunks"]));
     519             :         // progress == -1 is a "download was interrupted" message and should contain a path
     520           0 :         if (progress < 0) {
     521           0 :           profileCN.getProfile(data["ProfileOnion"])?.downloadSetPath(data["FileKey"], data["FilePath"]);
     522             :         }
     523             :         break;
     524           0 :       case "FileDownloaded":
     525           0 :         profileCN.getProfile(data["ProfileOnion"])?.downloadMarkFinished(data["FileKey"], data["FilePath"]);
     526             :         break;
     527           0 :       case "ImportingProfileEvent":
     528             :         break;
     529           0 :       case "StartingStorageMigration":
     530           0 :         appState.SetModalState(ModalState.storageMigration);
     531             :         break;
     532           0 :       case "DoneStorageMigration":
     533           0 :         appState.SetModalState(ModalState.none);
     534             :         break;
     535           0 :       case "BlodeuweddSummary":
     536           0 :         var identifier = int.parse(data["ConversationID"]);
     537           0 :         profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(identifier)?.updateSummaryEvent(data["Summary"]);
     538             :         break;
     539           0 :       case "BlodeuweddTranslation":
     540           0 :         var identifier = int.parse(data["ConversationID"]);
     541           0 :         var mid = int.parse(data["Index"]);
     542           0 :         EnvironmentConfig.debugLog("received translation event: $identifier $mid $data");
     543           0 :         profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(identifier)?.updateTranslationEvent(mid, data["Translation"]);
     544             :         break;
     545           0 :       case "ACNInfo":
     546           0 :         var key = data["Key"];
     547           0 :         var handle = data["Handle"];
     548           0 :         if (key == "circuit") {
     549           0 :           profileCN.getProfile(data["ProfileOnion"])?.contactList.findContact(handle)?.acnCircuit = data["Data"];
     550             :         }
     551             :         break;
     552           0 :       case "SearchResult":
     553           0 :         String searchID = data["SearchID"];
     554           0 :         var conversationIdentifier = int.parse(data["ConversationID"]);
     555           0 :         var messageIndex = int.parse(data["RowIndex"]);
     556           0 :         profileCN.getProfile(data["ProfileOnion"])?.searchState.handleSearchResult(searchID, conversationIdentifier, messageIndex);
     557             :         break;
     558           0 :       case "NewHybridGroup":
     559           0 :         groupListState.add(data["Onion"], data["GroupBundle"], data["Running"] == "true", data["Description"], data["Autostart"] == "true", data["StorageType"] == "storage-password");
     560             :         break;
     561           0 :       case "HybridGroupDeleted":
     562           0 :         error.handleUpdate("deletedhybridgroup." + data["Status"]);
     563           0 :         if (data["Status"] == "success") {
     564           0 :           groupListState.delete(data["Identity"]);
     565             :         }
     566             :         break;
     567           0 :       case "HybridGroupStatsUpdate":
     568           0 :         var totalMessages = int.parse(data["TotalMessages"]);
     569           0 :         var connections = int.parse(data["Connections"]);
     570           0 :         groupListState.updateGroupStats(data["Identity"], totalMessages, connections);
     571             :         break;
     572           0 :       case "MemberList":
     573           0 :         dynamic message = jsonDecode(data["Data"]);
     574           0 :         var identifier = int.parse(data["ConversationID"]);
     575           0 :         List<GroupMember> members = [];
     576           0 :         profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(identifier)?.members = message["m"]
     577           0 :             .map<String, GroupMember>(
     578           0 :               (k, v) => MapEntry<String, GroupMember>(
     579             :                 k,
     580           0 :                 GroupMember(
     581             :                   k, //v["Name"],
     582           0 :                   v["AC"].cast<String, dynamic>(),
     583             :                   //v["AC"].map<String,bool>((k,v)=>MapEntry<String,bool>(k, v as bool))  as Map<String,bool>
     584             :                 ),
     585             :               ),
     586             :             )
     587           0 :             .values
     588           0 :             .toList();
     589           0 :         profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(identifier)?.modeLine = message["g"];
     590           0 :         profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(identifier)?.modeMask = message["h"];
     591           0 :         profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(identifier)?.isOpPending = false;
     592           0 :         profileCN.getProfile(data["ProfileOnion"])?.notifyListeners();
     593             :         break;
     594           0 :       case "MessageUpdated":
     595           0 :         var identifier = int.parse(data["ConversationID"]);
     596           0 :         var contact = profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(identifier);
     597           0 :         var messageID = int.parse(data["Index"]);
     598           0 :         String? sig = data.containsKey("Signature") ? data["Signature"] : null;
     599           0 :         profileCN.getProfile(data["ProfileOnion"])?.contactList.getContact(identifier)?.isOpPending = false;
     600           0 :         contact?.updateMessage(messageID, data["Message"], sig, jsonDecode(data["Attributes"])); //.cast<String,String>());
     601             :         break;
     602             :       default:
     603           0 :         EnvironmentConfig.debugLog("unhandled event: $type");
     604             :     }
     605             :   }
     606             : }

Generated by: LCOV version 1.14