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.

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