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.

108 lines
2.6 KiB

  1. import 'dart:convert';
  2. import 'package:pointycastle/export.dart';
  3. import '/utils/encryption/crypto_utils.dart';
  4. import '/utils/encryption/aes_helper.dart';
  5. import '/utils/storage/database.dart';
  6. import '/models/friends.dart';
  7. const messageTypeSender = 'sender';
  8. const messageTypeReceiver = 'receiver';
  9. class Message {
  10. String id;
  11. String symmetricKey;
  12. String messageThreadKey;
  13. String data;
  14. String senderId;
  15. String senderUsername;
  16. String createdAt;
  17. Message({
  18. required this.id,
  19. required this.symmetricKey,
  20. required this.messageThreadKey,
  21. required this.data,
  22. required this.senderId,
  23. required this.senderUsername,
  24. required this.createdAt,
  25. });
  26. factory Message.fromJson(Map<String, dynamic> json, RSAPrivateKey privKey) {
  27. var symmetricKey = CryptoUtils.rsaDecrypt(
  28. base64.decode(json['symmetric_key']),
  29. privKey,
  30. );
  31. var data = AesHelper.aesDecrypt(
  32. symmetricKey,
  33. base64.decode(json['message_data']['data']),
  34. );
  35. var senderId = AesHelper.aesDecrypt(
  36. symmetricKey,
  37. base64.decode(json['message_data']['sender_id']),
  38. );
  39. return Message(
  40. id: json['id'],
  41. messageThreadKey: json['message_thread_key'],
  42. symmetricKey: base64.encode(symmetricKey),
  43. data: data,
  44. senderId: senderId,
  45. senderUsername: 'Unknown', // TODO
  46. createdAt: json['created_at'],
  47. );
  48. }
  49. @override
  50. String toString() {
  51. return '''
  52. id: $id
  53. data: $data
  54. senderId: $senderId
  55. senderUsername: $senderUsername
  56. createdAt: $createdAt
  57. ''';
  58. }
  59. Map<String, dynamic> toMap() {
  60. return {
  61. 'id': id,
  62. 'message_thread_key': messageThreadKey,
  63. 'symmetric_key': symmetricKey,
  64. 'data': data,
  65. 'sender_id': senderId,
  66. 'sender_username': senderUsername,
  67. 'created_at': createdAt,
  68. };
  69. }
  70. }
  71. Future<List<Message>> getMessagesForThread(String messageThreadKey) async {
  72. final db = await getDatabaseConnection();
  73. List<dynamic> whereArguments = [messageThreadKey];
  74. final List<Map<String, dynamic>> maps = await db.query(
  75. 'messages',
  76. where: 'message_thread_key = ?',
  77. whereArgs: whereArguments,
  78. orderBy: 'created_at DESC',
  79. );
  80. return List.generate(maps.length, (i) {
  81. return Message(
  82. id: maps[i]['id'],
  83. messageThreadKey: maps[i]['message_thread_key'],
  84. symmetricKey: maps[i]['symmetric_key'],
  85. data: maps[i]['data'],
  86. senderId: maps[i]['sender_id'],
  87. senderUsername: maps[i]['sender_username'],
  88. createdAt: maps[i]['created_at'],
  89. );
  90. });
  91. }