Encrypted messaging app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.2 KiB

  1. import 'dart:convert';
  2. import 'package:Envelope/models/messages.dart';
  3. import 'package:http/http.dart' as http;
  4. import 'package:flutter_dotenv/flutter_dotenv.dart';
  5. import 'package:pointycastle/export.dart';
  6. import 'package:sqflite/sqflite.dart';
  7. import 'package:Envelope/models/conversations.dart';
  8. import '/utils/storage/session_cookie.dart';
  9. import '/utils/storage/encryption_keys.dart';
  10. import '/utils/storage/database.dart';
  11. import '/models/conversations.dart';
  12. // TODO: Move this to table
  13. Map<String, Map<String, String>> _mapUsers(String users) {
  14. List<dynamic> usersJson = jsonDecode(users);
  15. Map<String, Map<String, String>> mapped = {};
  16. for (var i = 0; i < usersJson.length; i++) {
  17. mapped[usersJson[i]['id']] = {
  18. 'username': usersJson[i]['username'],
  19. 'admin': usersJson[i]['admin'],
  20. };
  21. }
  22. return mapped;
  23. }
  24. Future<void> updateMessageThread(Conversation conversation, {RSAPrivateKey? privKey}) async {
  25. privKey ??= await getPrivateKey();
  26. var resp = await http.get(
  27. Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/messages/${conversation.messageThreadKey}'),
  28. headers: {
  29. 'cookie': await getSessionCookie(),
  30. }
  31. );
  32. if (resp.statusCode != 200) {
  33. throw Exception(resp.body);
  34. }
  35. var mapped = _mapUsers(conversation.users!);
  36. List<dynamic> messageThreadJson = jsonDecode(resp.body);
  37. final db = await getDatabaseConnection();
  38. for (var i = 0; i < messageThreadJson.length; i++) {
  39. Message message = Message.fromJson(
  40. messageThreadJson[i] as Map<String, dynamic>,
  41. privKey,
  42. );
  43. // TODO: Fix this
  44. message.senderUsername = mapped[message.senderId]!['username']!;
  45. await db.insert(
  46. 'messages',
  47. message.toMap(),
  48. conflictAlgorithm: ConflictAlgorithm.replace,
  49. );
  50. }
  51. }
  52. Future<void> updateMessageThreads({List<Conversation>? conversations}) async {
  53. RSAPrivateKey privKey = await getPrivateKey();
  54. conversations ??= await getConversations();
  55. for (var i = 0; i < conversations.length; i++) {
  56. await updateMessageThread(conversations[i], privKey: privKey);
  57. }
  58. }