import 'dart:convert'; import 'package:Envelope/models/messages.dart'; import 'package:http/http.dart' as http; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:pointycastle/export.dart'; import 'package:sqflite/sqflite.dart'; import 'package:Envelope/models/conversations.dart'; import '/utils/storage/session_cookie.dart'; import '/utils/storage/encryption_keys.dart'; import '/utils/storage/database.dart'; import '/models/conversations.dart'; // TODO: Move this to table Map> _mapUsers(String users) { List usersJson = jsonDecode(users); Map> mapped = {}; for (var i = 0; i < usersJson.length; i++) { mapped[usersJson[i]['id']] = { 'username': usersJson[i]['username'], 'admin': usersJson[i]['admin'], }; } return mapped; } Future updateMessageThread(Conversation conversation, {RSAPrivateKey? privKey}) async { privKey ??= await getPrivateKey(); var resp = await http.get( Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/messages/${conversation.messageThreadKey}'), headers: { 'cookie': await getSessionCookie(), } ); if (resp.statusCode != 200) { throw Exception(resp.body); } var mapped = _mapUsers(conversation.users!); List messageThreadJson = jsonDecode(resp.body); final db = await getDatabaseConnection(); for (var i = 0; i < messageThreadJson.length; i++) { Message message = Message.fromJson( messageThreadJson[i] as Map, privKey, ); // TODO: Fix this message.senderUsername = mapped[message.senderId]!['username']!; await db.insert( 'messages', message.toMap(), conflictAlgorithm: ConflictAlgorithm.replace, ); } } Future updateMessageThreads({List? conversations}) async { RSAPrivateKey privKey = await getPrivateKey(); conversations ??= await getConversations(); for (var i = 0; i < conversations.length; i++) { await updateMessageThread(conversations[i], privKey: privKey); } }