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.

300 lines
8.4 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.messageExpiryDefault = detailsJson['message_expiry'];
  132. conversation.twoUser = AesHelper.aesDecrypt(
  133. base64.decode(conversation.symmetricKey),
  134. base64.decode(detailsJson['two_user']),
  135. ) == 'true';
  136. if (conversation.twoUser) {
  137. MyProfile profile = await MyProfile.getProfile();
  138. final db = await getDatabaseConnection();
  139. List<Map<String, dynamic>> maps = await db.query(
  140. 'conversation_users',
  141. where: 'conversation_id = ? AND user_id != ?',
  142. whereArgs: [ conversation.id, profile.id ],
  143. );
  144. if (maps.length != 1) {
  145. conversation.name = 'TODO: Fix this';
  146. } else {
  147. conversation.name = maps[0]['username'];
  148. }
  149. } else {
  150. conversation.name = AesHelper.aesDecrypt(
  151. base64.decode(conversation.symmetricKey),
  152. base64.decode(detailsJson['name']),
  153. );
  154. }
  155. if (detailsJson['attachment_id'] != null) {
  156. conversation.icon = await getFile(
  157. '$defaultServerUrl/files/${detailsJson['attachment']['image_link']}',
  158. conversation.id,
  159. conversation.symmetricKey,
  160. ).catchError((dynamic) async {});
  161. }
  162. await db.insert(
  163. 'conversations',
  164. conversation.toMap(),
  165. conflictAlgorithm: ConflictAlgorithm.replace,
  166. );
  167. List<dynamic> usersData = detailsJson['users'];
  168. for (var i = 0; i < usersData.length; i++) {
  169. ConversationUser conversationUser = ConversationUser.fromJson(
  170. usersData[i] as Map<String, dynamic>,
  171. base64.decode(conversation.symmetricKey),
  172. );
  173. await db.insert(
  174. 'conversation_users',
  175. conversationUser.toMap(),
  176. conflictAlgorithm: ConflictAlgorithm.replace,
  177. );
  178. }
  179. }
  180. static Future<void> updateConversations({DateTime? updatedAt}) async {
  181. _BaseConversationsResult baseConvs = await _getBaseConversations();
  182. if (baseConvs.detailIds.isEmpty) {
  183. return;
  184. }
  185. Map<String, String> params = {};
  186. if (updatedAt != null) {
  187. params['updated_at'] = updatedAt.toIso8601String();
  188. }
  189. params['conversation_detail_ids'] = baseConvs.detailIds.join(',');
  190. var uri = await MyProfile.getServerUrl('api/v1/auth/conversation_details');
  191. uri = uri.replace(queryParameters: params);
  192. http.Response resp = await http.get(
  193. uri,
  194. headers: {
  195. 'cookie': await getSessionCookie(),
  196. }
  197. );
  198. if (resp.statusCode != 200) {
  199. throw Exception(resp.body);
  200. }
  201. final db = await getDatabaseConnection();
  202. List<dynamic> conversationsDetailsJson = jsonDecode(resp.body);
  203. for (var i = 0; i < conversationsDetailsJson.length; i++) {
  204. Map<String, dynamic> detailsJson = conversationsDetailsJson[i] as Map<String, dynamic>;
  205. Conversation conversation = _findConversationByDetailId(baseConvs.conversations, detailsJson['id']);
  206. await _storeConversations(db, conversation, detailsJson);
  207. }
  208. }
  209. static Future<void> uploadConversation(Conversation conversation) async {
  210. String sessionCookie = await getSessionCookie();
  211. Map<String, dynamic> conversationJson = await conversation.payloadJson();
  212. var resp = await http.post(
  213. await MyProfile.getServerUrl('api/v1/auth/conversations'),
  214. headers: <String, String>{
  215. 'Content-Type': 'application/json; charset=UTF-8',
  216. 'cookie': sessionCookie,
  217. },
  218. body: jsonEncode(conversationJson),
  219. );
  220. if (resp.statusCode != 204) {
  221. throw Exception('Failed to create conversation');
  222. }
  223. }
  224. static Future<void> updateMessageExpiry(String id, String messageExpiry) async {
  225. http.Response resp = await http.post(
  226. await MyProfile.getServerUrl(
  227. 'api/v1/auth/conversations/$id/message_expiry'
  228. ),
  229. headers: {
  230. 'cookie': await getSessionCookie(),
  231. },
  232. body: jsonEncode({
  233. 'message_expiry': messageExpiry,
  234. }),
  235. );
  236. if (resp.statusCode == 204) {
  237. return;
  238. }
  239. throw Exception('Cannot set message expiry for conversation');
  240. }
  241. }