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.

304 lines
8.5 KiB

  1. import 'dart:convert';
  2. import 'package:Envelope/utils/storage/get_file.dart';
  3. import 'package:http/http.dart' as http;
  4. import 'package:pointycastle/export.dart';
  5. import 'package:sqflite/sqflite.dart';
  6. import 'package:uuid/uuid.dart';
  7. import '/database/models/friends.dart';
  8. import '/database/models/conversation_users.dart';
  9. import '/database/models/conversations.dart';
  10. import '/database/models/my_profile.dart';
  11. import '/exceptions/update_data_exception.dart';
  12. import '/utils/encryption/aes_helper.dart';
  13. import '/utils/storage/database.dart';
  14. import '/utils/storage/session_cookie.dart';
  15. class _BaseConversationsResult {
  16. List<Conversation> conversations;
  17. List<String> detailIds;
  18. _BaseConversationsResult({
  19. required this.conversations,
  20. required this.detailIds,
  21. });
  22. }
  23. class ConversationsService {
  24. static Future<void> saveConversation(Conversation conversation) async {
  25. final db = await getDatabaseConnection();
  26. db.update(
  27. 'conversations',
  28. conversation.toMap(),
  29. where: 'id = ?',
  30. whereArgs: [conversation.id],
  31. );
  32. }
  33. static Future<Conversation> addUsersToConversation(Conversation conversation, List<Friend> friends) async {
  34. final db = await getDatabaseConnection();
  35. var uuid = const Uuid();
  36. for (Friend friend in friends) {
  37. await db.insert(
  38. 'conversation_users',
  39. ConversationUser(
  40. id: uuid.v4(),
  41. userId: friend.friendId,
  42. conversationId: conversation.id,
  43. username: friend.username,
  44. associationKey: uuid.v4(),
  45. publicKey: friend.publicKey,
  46. admin: false,
  47. ).toMap(),
  48. conflictAlgorithm: ConflictAlgorithm.replace,
  49. );
  50. }
  51. return conversation;
  52. }
  53. static Future<void> updateConversation(
  54. Conversation conversation,
  55. {
  56. includeUsers = false,
  57. updatedImage = false,
  58. saveConversation = true,
  59. } ) async {
  60. if (saveConversation) {
  61. await saveConversation(conversation);
  62. }
  63. String sessionCookie = await getSessionCookie();
  64. Map<String, dynamic> conversationJson = await conversation.payloadJson(includeUsers: includeUsers);
  65. var resp = await http.put(
  66. await MyProfile.getServerUrl('api/v1/auth/conversations'),
  67. headers: <String, String>{
  68. 'Content-Type': 'application/json; charset=UTF-8',
  69. 'cookie': sessionCookie,
  70. },
  71. body: jsonEncode(conversationJson),
  72. );
  73. if (resp.statusCode != 204) {
  74. throw UpdateDataException('Unable to update conversation, please try again later.');
  75. }
  76. if (!updatedImage) {
  77. return;
  78. }
  79. Map<String, dynamic> attachmentJson = conversation.payloadImageJson();
  80. resp = await http.post(
  81. await MyProfile.getServerUrl('api/v1/auth/conversations/${conversation.id}/image'),
  82. headers: <String, String>{
  83. 'Content-Type': 'application/json; charset=UTF-8',
  84. 'cookie': sessionCookie,
  85. },
  86. body: jsonEncode(attachmentJson),
  87. );
  88. if (resp.statusCode != 204) {
  89. throw UpdateDataException('Unable to update conversation image, please try again later.');
  90. }
  91. }
  92. static Future<_BaseConversationsResult> _getBaseConversations() async {
  93. RSAPrivateKey privKey = await MyProfile.getPrivateKey();
  94. http.Response resp = await http.get(
  95. await MyProfile.getServerUrl('api/v1/auth/conversations'),
  96. headers: {
  97. 'cookie': await getSessionCookie(),
  98. }
  99. );
  100. if (resp.statusCode != 200) {
  101. throw Exception(resp.body);
  102. }
  103. _BaseConversationsResult result = _BaseConversationsResult(
  104. conversations: [],
  105. detailIds: []
  106. );
  107. List<dynamic> conversationsJson = jsonDecode(resp.body);
  108. if (conversationsJson.isEmpty) {
  109. return result;
  110. }
  111. for (var i = 0; i < conversationsJson.length; i++) {
  112. Conversation conversation = Conversation.fromJson(
  113. conversationsJson[i] as Map<String, dynamic>,
  114. privKey,
  115. );
  116. result.conversations.add(conversation);
  117. result.detailIds.add(conversation.id);
  118. }
  119. return result;
  120. }
  121. static Conversation _findConversationByDetailId(List<Conversation> conversations, String id) {
  122. for (var conversation in conversations) {
  123. if (conversation.id == id) {
  124. return conversation;
  125. }
  126. }
  127. // Or return `null`.
  128. throw ArgumentError.value(id, 'id', 'No element with that id');
  129. }
  130. static Future<void> _storeConversations(Database db, Conversation conversation, Map<String, dynamic> detailsJson) async {
  131. conversation.createdAt = DateTime.parse(detailsJson['created_at']);
  132. conversation.updatedAt = DateTime.parse(detailsJson['updated_at']);
  133. conversation.messageExpiryDefault = detailsJson['message_expiry'];
  134. conversation.twoUser = AesHelper.aesDecrypt(
  135. base64.decode(conversation.symmetricKey),
  136. base64.decode(detailsJson['two_user']),
  137. ) == 'true';
  138. if (conversation.twoUser) {
  139. MyProfile profile = await MyProfile.getProfile();
  140. final db = await getDatabaseConnection();
  141. List<Map<String, dynamic>> maps = await db.query(
  142. 'conversation_users',
  143. where: 'conversation_id = ? AND user_id != ?',
  144. whereArgs: [ conversation.id, profile.id ],
  145. );
  146. if (maps.length != 1) {
  147. conversation.name = 'TODO: Fix this';
  148. } else {
  149. conversation.name = maps[0]['username'];
  150. }
  151. } else {
  152. conversation.name = AesHelper.aesDecrypt(
  153. base64.decode(conversation.symmetricKey),
  154. base64.decode(detailsJson['name']),
  155. );
  156. }
  157. if (detailsJson['attachment_id'] != null) {
  158. conversation.icon = await getFile(
  159. '$defaultServerUrl/files/${detailsJson['attachment']['image_link']}',
  160. conversation.id,
  161. conversation.symmetricKey,
  162. ).catchError((dynamic) async {});
  163. }
  164. await db.insert(
  165. 'conversations',
  166. conversation.toMap(),
  167. conflictAlgorithm: ConflictAlgorithm.replace,
  168. );
  169. List<dynamic> usersData = detailsJson['users'];
  170. for (var i = 0; i < usersData.length; i++) {
  171. ConversationUser conversationUser = ConversationUser.fromJson(
  172. usersData[i] as Map<String, dynamic>,
  173. base64.decode(conversation.symmetricKey),
  174. );
  175. await db.insert(
  176. 'conversation_users',
  177. conversationUser.toMap(),
  178. conflictAlgorithm: ConflictAlgorithm.replace,
  179. );
  180. }
  181. }
  182. static Future<void> updateConversations({DateTime? updatedAt}) async {
  183. _BaseConversationsResult baseConvs = await _getBaseConversations();
  184. if (baseConvs.detailIds.isEmpty) {
  185. return;
  186. }
  187. Map<String, String> params = {};
  188. if (updatedAt != null) {
  189. params['updated_at'] = updatedAt.toIso8601String();
  190. }
  191. params['conversation_detail_ids'] = baseConvs.detailIds.join(',');
  192. var uri = await MyProfile.getServerUrl('api/v1/auth/conversation_details');
  193. uri = uri.replace(queryParameters: params);
  194. http.Response resp = await http.get(
  195. uri,
  196. headers: {
  197. 'cookie': await getSessionCookie(),
  198. }
  199. );
  200. if (resp.statusCode != 200) {
  201. throw Exception(resp.body);
  202. }
  203. final db = await getDatabaseConnection();
  204. List<dynamic> conversationsDetailsJson = jsonDecode(resp.body);
  205. for (var i = 0; i < conversationsDetailsJson.length; i++) {
  206. Map<String, dynamic> detailsJson = conversationsDetailsJson[i] as Map<String, dynamic>;
  207. Conversation conversation = _findConversationByDetailId(baseConvs.conversations, detailsJson['id']);
  208. await _storeConversations(db, conversation, detailsJson);
  209. }
  210. }
  211. static Future<void> uploadConversation(Conversation conversation) async {
  212. String sessionCookie = await getSessionCookie();
  213. Map<String, dynamic> conversationJson = await conversation.payloadJson();
  214. var resp = await http.post(
  215. await MyProfile.getServerUrl('api/v1/auth/conversations'),
  216. headers: <String, String>{
  217. 'Content-Type': 'application/json; charset=UTF-8',
  218. 'cookie': sessionCookie,
  219. },
  220. body: jsonEncode(conversationJson),
  221. );
  222. if (resp.statusCode != 204) {
  223. throw Exception('Failed to create conversation');
  224. }
  225. }
  226. static Future<void> updateMessageExpiry(String id, String messageExpiry) async {
  227. http.Response resp = await http.post(
  228. await MyProfile.getServerUrl(
  229. 'api/v1/auth/conversations/$id/message_expiry'
  230. ),
  231. headers: {
  232. 'cookie': await getSessionCookie(),
  233. },
  234. body: jsonEncode({
  235. 'message_expiry': messageExpiry,
  236. }),
  237. );
  238. if (resp.statusCode == 204) {
  239. return;
  240. }
  241. throw Exception('Cannot set message expiry for conversation');
  242. }
  243. }