LCOV - code coverage report
Current view: top level - lib/models - message.dart (source / functions) Hit Total Coverage
Test: lcov.info Lines: 0 131 0.0 %
Date: 2024-02-26 20:09:01 Functions: 0 0 -

          Line data    Source code
       1             : import 'dart:convert';
       2             : import 'package:cwtch/config.dart';
       3             : import 'package:cwtch/cwtch/cwtch.dart';
       4             : import 'package:flutter/material.dart';
       5             : import 'package:flutter/widgets.dart';
       6             : import 'package:provider/provider.dart';
       7             : 
       8             : import '../main.dart';
       9             : import 'messagecache.dart';
      10             : import 'messages/filemessage.dart';
      11             : import 'messages/invitemessage.dart';
      12             : import 'messages/malformedmessage.dart';
      13             : import 'messages/quotedmessage.dart';
      14             : import 'messages/textmessage.dart';
      15             : import 'profile.dart';
      16             : 
      17             : // Define the overlays
      18             : const TextMessageOverlay = 1;
      19             : const QuotedMessageOverlay = 10;
      20             : const SuggestContactOverlay = 100;
      21             : const InviteGroupOverlay = 101;
      22             : const FileShareOverlay = 200;
      23             : 
      24             : // Defines the length of the tor v3 onion address. Code using this constant will
      25             : // need to updated when we allow multiple different identifiers. At which time
      26             : // it will likely be prudent to define a proper Contact wrapper.
      27             : const TorV3ContactHandleLength = 56;
      28             : 
      29             : // Defines the length of a Cwtch v2 Group.
      30             : const GroupConversationHandleLength = 32;
      31             : 
      32             : abstract class Message {
      33             :   MessageMetadata getMetadata();
      34             : 
      35             :   Widget getWidget(BuildContext context, Key key, int index);
      36             : 
      37             :   Widget getPreviewWidget(BuildContext context, {BoxConstraints? constraints});
      38             : }
      39             : 
      40           0 : Message compileOverlay(MessageInfo messageInfo) {
      41             :   try {
      42           0 :     dynamic message = jsonDecode(messageInfo.wrapper);
      43           0 :     var content = message['d'] as dynamic;
      44           0 :     var overlay = int.parse(message['o'].toString());
      45             : 
      46             :     switch (overlay) {
      47           0 :       case TextMessageOverlay:
      48           0 :         return TextMessage(messageInfo.metadata, content);
      49           0 :       case SuggestContactOverlay:
      50           0 :       case InviteGroupOverlay:
      51           0 :         return InviteMessage(overlay, messageInfo.metadata, content);
      52           0 :       case QuotedMessageOverlay:
      53           0 :         return QuotedMessage(messageInfo.metadata, content);
      54           0 :       case FileShareOverlay:
      55           0 :         return FileMessage(messageInfo.metadata, content);
      56             :       default:
      57             :         // Metadata is valid, content is not..
      58           0 :         return MalformedMessage(messageInfo.metadata);
      59             :     }
      60             :   } catch (e) {
      61           0 :     return MalformedMessage(messageInfo.metadata);
      62             :   }
      63             : }
      64             : 
      65             : abstract class CacheHandler {
      66             :   Future<MessageInfo?> get(Cwtch cwtch, String profileOnion, int conversationIdentifier, MessageCache cache);
      67             : }
      68             : 
      69             : class ByIndex implements CacheHandler {
      70             :   int index;
      71             : 
      72           0 :   ByIndex(this.index);
      73             : 
      74           0 :   Future<MessageInfo?> lookup(MessageCache cache) async {
      75           0 :     var msg = cache.getByIndex(index);
      76             :     return msg;
      77             :   }
      78             : 
      79           0 :   Future<MessageInfo?> get(Cwtch cwtch, String profileOnion, int conversationIdentifier, MessageCache cache) async {
      80             :     // if in cache, get. But if the cache has unsynced or not in cache, we'll have to do a fetch
      81           0 :     if (index < cache.cacheByIndex.length) {
      82           0 :       return cache.getByIndex(index);
      83             :     }
      84             : 
      85             :     // otherwise we are going to fetch, so we'll fetch a chunk of messages
      86             :     // observationally flutter future builder seemed to be reaching for 20-40 message on pane load, so we start trying to load up to that many messages in one request
      87             :     var amount = 40;
      88           0 :     var start = index;
      89             :     // we have to keep the indexed cache contiguous so reach back to the end of it and start the fetch from there
      90           0 :     if (index > cache.cacheByIndex.length) {
      91           0 :       start = cache.cacheByIndex.length;
      92           0 :       amount += index - start;
      93             :     }
      94             : 
      95             :     // check that we aren't asking for messages beyond stored messages
      96           0 :     if (start + amount >= cache.storageMessageCount) {
      97           0 :       amount = cache.storageMessageCount - start;
      98           0 :       if (amount <= 0) {
      99           0 :         return Future.value(null);
     100             :       }
     101             :     }
     102             : 
     103           0 :     cache.lockIndexes(start, start + amount);
     104           0 :     await fetchAndProcess(start, amount, cwtch, profileOnion, conversationIdentifier, cache);
     105             : 
     106           0 :     return cache.getByIndex(index);
     107             :   }
     108             : 
     109           0 :   void loadUnsynced(Cwtch cwtch, String profileOnion, int conversationIdentifier, MessageCache cache) {
     110             :     // return if inadvertently called when no unsynced messages
     111           0 :     if (cache.indexUnsynced == 0) {
     112             :       return;
     113             :     }
     114             : 
     115             :     // otherwise we are going to fetch, so we'll fetch a chunk of messages
     116             :     var start = 0;
     117           0 :     var amount = cache.indexUnsynced;
     118             : 
     119           0 :     cache.lockIndexes(start, start + amount);
     120           0 :     fetchAndProcess(start, amount, cwtch, profileOnion, conversationIdentifier, cache);
     121             :     return;
     122             :   }
     123             : 
     124           0 :   Future<void> fetchAndProcess(int start, int amount, Cwtch cwtch, String profileOnion, int conversationIdentifier, MessageCache cache) async {
     125           0 :     var msgs = await cwtch.GetMessages(profileOnion, conversationIdentifier, start, amount);
     126             :     int i = 0; // i used to loop through returned messages. if doesn't reach the requested count, we will use it in the finally stanza to error out the remaining asked for messages in the cache
     127             :     try {
     128           0 :       List<dynamic> messagesWrapper = jsonDecode(msgs);
     129             : 
     130           0 :       for (; i < messagesWrapper.length; i++) {
     131           0 :         var messageInfo = messageWrapperToInfo(profileOnion, conversationIdentifier, messagesWrapper[i]);
     132           0 :         cache.addIndexed(messageInfo, start + i);
     133             :       }
     134             :     } catch (e, stacktrace) {
     135           0 :       EnvironmentConfig.debugLog("Error: Getting indexed messages $start to ${start + amount} failed parsing: " + e.toString() + " " + stacktrace.toString());
     136             :     } finally {
     137           0 :       if (i != amount) {
     138           0 :         cache.malformIndexes(start + i, start + amount);
     139             :       }
     140             :     }
     141             :   }
     142             : 
     143           0 :   void add(MessageCache cache, MessageInfo messageInfo) {
     144           0 :     cache.addIndexed(messageInfo, index);
     145             :   }
     146             : }
     147             : 
     148             : class ById implements CacheHandler {
     149             :   int id;
     150             : 
     151           0 :   ById(this.id);
     152             : 
     153           0 :   Future<MessageInfo?> lookup(MessageCache cache) {
     154           0 :     return Future<MessageInfo?>.value(cache.getById(id));
     155             :   }
     156             : 
     157           0 :   Future<MessageInfo?> fetch(Cwtch cwtch, String profileOnion, int conversationIdentifier, MessageCache cache) async {
     158           0 :     var rawMessageEnvelope = await cwtch.GetMessageByID(profileOnion, conversationIdentifier, id);
     159           0 :     var messageInfo = messageJsonToInfo(profileOnion, conversationIdentifier, rawMessageEnvelope);
     160             :     if (messageInfo == null) {
     161           0 :       return Future.value(null);
     162             :     }
     163           0 :     EnvironmentConfig.debugLog("fetching $profileOnion $conversationIdentifier $id ${messageInfo.wrapper}");
     164           0 :     cache.addUnindexed(messageInfo);
     165           0 :     return Future.value(messageInfo);
     166             :   }
     167             : 
     168           0 :   Future<MessageInfo?> get(Cwtch cwtch, String profileOnion, int conversationIdentifier, MessageCache cache) async {
     169           0 :     var messageInfo = await lookup(cache);
     170             :     if (messageInfo != null) {
     171           0 :       return Future.value(messageInfo);
     172             :     }
     173           0 :     return fetch(cwtch, profileOnion, conversationIdentifier, cache);
     174             :   }
     175             : }
     176             : 
     177             : class ByContentHash implements CacheHandler {
     178             :   String hash;
     179             : 
     180           0 :   ByContentHash(this.hash);
     181             : 
     182           0 :   Future<MessageInfo?> lookup(MessageCache cache) {
     183           0 :     return Future<MessageInfo?>.value(cache.getByContentHash(hash));
     184             :   }
     185             : 
     186           0 :   Future<MessageInfo?> fetch(Cwtch cwtch, String profileOnion, int conversationIdentifier, MessageCache cache) async {
     187           0 :     var rawMessageEnvelope = await cwtch.GetMessageByContentHash(profileOnion, conversationIdentifier, hash);
     188           0 :     var messageInfo = messageJsonToInfo(profileOnion, conversationIdentifier, rawMessageEnvelope);
     189             :     if (messageInfo == null) {
     190           0 :       return Future.value(null);
     191             :     }
     192           0 :     cache.addUnindexed(messageInfo);
     193           0 :     return Future.value(messageInfo);
     194             :   }
     195             : 
     196           0 :   Future<MessageInfo?> get(Cwtch cwtch, String profileOnion, int conversationIdentifier, MessageCache cache) async {
     197           0 :     var messageInfo = await lookup(cache);
     198             :     if (messageInfo != null) {
     199           0 :       return Future.value(messageInfo);
     200             :     }
     201           0 :     return fetch(cwtch, profileOnion, conversationIdentifier, cache);
     202             :   }
     203             : }
     204             : 
     205           0 : List<Message> getReplies(MessageCache cache, int messageIdentifier) {
     206           0 :   List<Message> replies = List.empty(growable: true);
     207             : 
     208             :   try {
     209           0 :     MessageInfo original = cache.cache[messageIdentifier]!;
     210           0 :     String hash = original.metadata.contenthash;
     211             : 
     212           0 :     cache.cache.forEach((key, messageInfo) {
     213             :       // only bother searching for identifiers that came *after*
     214           0 :       if (key > messageIdentifier) {
     215             :         try {
     216           0 :           dynamic message = jsonDecode(messageInfo.wrapper);
     217           0 :           var content = message['d'] as dynamic;
     218           0 :           dynamic qmessage = jsonDecode(content);
     219           0 :           if (qmessage["body"] == null || qmessage["quotedHash"] == null) {
     220             :             return;
     221             :           }
     222           0 :           if (qmessage["quotedHash"] == hash) {
     223           0 :             replies.add(compileOverlay(messageInfo));
     224             :           }
     225             :         } catch (e) {
     226             :           // ignore
     227             :         }
     228             :       }
     229             :     });
     230             :   } catch (e) {
     231           0 :     EnvironmentConfig.debugLog("message handler exception on get from cache: $e");
     232             :   }
     233             : 
     234           0 :   replies.sort((a, b) {
     235           0 :     return a.getMetadata().messageID.compareTo(b.getMetadata().messageID);
     236             :   });
     237             : 
     238             :   return replies;
     239             : }
     240             : 
     241           0 : Future<Message> messageHandler(BuildContext context, String profileOnion, int conversationIdentifier, CacheHandler cacheHandler) async {
     242           0 :   var malformedMetadata = MessageMetadata(profileOnion, conversationIdentifier, 0, DateTime.now(), "", "", "", <String, String>{}, false, true, false, "");
     243           0 :   var cwtch = Provider.of<FlwtchState>(context, listen: false).cwtch;
     244             : 
     245             :   MessageCache? cache;
     246             :   try {
     247           0 :     cache = Provider.of<ProfileInfoState>(context, listen: false).contactList.getContact(conversationIdentifier)?.messageCache;
     248             :     if (cache == null) {
     249           0 :       EnvironmentConfig.debugLog("error: cannot get message cache for profile: $profileOnion conversation: $conversationIdentifier");
     250           0 :       return MalformedMessage(malformedMetadata);
     251             :     }
     252             :   } catch (e) {
     253           0 :     EnvironmentConfig.debugLog("message handler exception on get from cache: $e");
     254             :     // provider check failed...make an expensive call...
     255           0 :     return MalformedMessage(malformedMetadata);
     256             :   }
     257             : 
     258           0 :   MessageInfo? messageInfo = await cacheHandler.get(cwtch, profileOnion, conversationIdentifier, cache);
     259             : 
     260             :   if (messageInfo != null) {
     261           0 :     return compileOverlay(messageInfo);
     262             :   } else {
     263           0 :     return MalformedMessage(malformedMetadata);
     264             :   }
     265             : }
     266             : 
     267           0 : MessageInfo? messageJsonToInfo(String profileOnion, int conversationIdentifier, dynamic messageJson) {
     268             :   try {
     269           0 :     dynamic messageWrapper = jsonDecode(messageJson);
     270             : 
     271           0 :     if (messageWrapper == null || messageWrapper['Message'] == '' || messageWrapper['Message'] == '{}') {
     272             :       return null;
     273             :     }
     274             : 
     275           0 :     return messageWrapperToInfo(profileOnion, conversationIdentifier, messageWrapper);
     276             :   } catch (e, stacktrace) {
     277           0 :     EnvironmentConfig.debugLog("message handler exception on parse message and cache: " + e.toString() + " " + stacktrace.toString());
     278             :     return null;
     279             :   }
     280             : }
     281             : 
     282           0 : MessageInfo messageWrapperToInfo(String profileOnion, int conversationIdentifier, dynamic messageWrapper) {
     283             :   // Construct the initial metadata
     284           0 :   var messageID = messageWrapper['ID'];
     285           0 :   var timestamp = DateTime.tryParse(messageWrapper['Timestamp'])!;
     286           0 :   var senderHandle = messageWrapper['PeerID'];
     287           0 :   var senderImage = messageWrapper['ContactImage'];
     288           0 :   var attributes = messageWrapper['Attributes'];
     289           0 :   var ackd = messageWrapper['Acknowledged'];
     290           0 :   var error = messageWrapper['Error'] != null;
     291           0 :   var signature = messageWrapper['Signature'];
     292           0 :   var contenthash = messageWrapper['ContentHash'];
     293           0 :   var metadata = MessageMetadata(profileOnion, conversationIdentifier, messageID, timestamp, senderHandle, senderImage, signature, attributes, ackd, error, false, contenthash);
     294           0 :   var messageInfo = new MessageInfo(metadata, messageWrapper['Message']);
     295             : 
     296             :   return messageInfo;
     297             : }
     298             : 
     299             : class MessageMetadata extends ChangeNotifier {
     300             :   // meta-metadata
     301             :   final String profileOnion;
     302             :   final int conversationIdentifier;
     303             :   final int messageID;
     304             : 
     305             :   final DateTime timestamp;
     306             :   final String senderHandle;
     307             :   final String? senderImage;
     308             :   final dynamic _attributes;
     309             :   bool _ackd;
     310             :   bool _error;
     311             :   final bool isAuto;
     312             : 
     313             :   final String? signature;
     314             :   final String contenthash;
     315             : 
     316           0 :   dynamic get attributes => this._attributes;
     317             : 
     318           0 :   bool get ackd => this._ackd;
     319             : 
     320             :   String translation = "";
     321           0 :   void updateTranslationEvent(String translation) {
     322           0 :     this.translation += translation;
     323           0 :     notifyListeners();
     324             :   }
     325             : 
     326           0 :   set ackd(bool newVal) {
     327           0 :     this._ackd = newVal;
     328           0 :     notifyListeners();
     329             :   }
     330             : 
     331           0 :   bool get error => this._error;
     332             : 
     333           0 :   set error(bool newVal) {
     334           0 :     this._error = newVal;
     335           0 :     notifyListeners();
     336             :   }
     337             : 
     338           0 :   MessageMetadata(this.profileOnion, this.conversationIdentifier, this.messageID, this.timestamp, this.senderHandle, this.senderImage, this.signature, this._attributes, this._ackd, this._error,
     339             :       this.isAuto, this.contenthash);
     340             : }

Generated by: LCOV version 1.14