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<String, Map<String, String>> _mapUsers(String users) {
|
|
List<dynamic> usersJson = jsonDecode(users);
|
|
|
|
Map<String, Map<String, String>> mapped = {};
|
|
|
|
for (var i = 0; i < usersJson.length; i++) {
|
|
mapped[usersJson[i]['id']] = {
|
|
'username': usersJson[i]['username'],
|
|
'admin': usersJson[i]['admin'],
|
|
};
|
|
}
|
|
|
|
return mapped;
|
|
}
|
|
|
|
Future<void> 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<dynamic> messageThreadJson = jsonDecode(resp.body);
|
|
|
|
final db = await getDatabaseConnection();
|
|
|
|
for (var i = 0; i < messageThreadJson.length; i++) {
|
|
Message message = Message.fromJson(
|
|
messageThreadJson[i] as Map<String, dynamic>,
|
|
privKey,
|
|
);
|
|
|
|
// TODO: Fix this
|
|
message.senderUsername = mapped[message.senderId]!['username']!;
|
|
|
|
await db.insert(
|
|
'messages',
|
|
message.toMap(),
|
|
conflictAlgorithm: ConflictAlgorithm.replace,
|
|
);
|
|
|
|
}
|
|
}
|
|
|
|
Future<void> updateMessageThreads({List<Conversation>? conversations}) async {
|
|
RSAPrivateKey privKey = await getPrivateKey();
|
|
|
|
conversations ??= await getConversations();
|
|
|
|
for (var i = 0; i < conversations.length; i++) {
|
|
await updateMessageThread(conversations[i], privKey: privKey);
|
|
}
|
|
}
|
|
|