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.

202 lines
5.9 KiB

  1. import 'dart:convert';
  2. import 'package:Capsule/exceptions/update_data_exception.dart';
  3. import 'package:Capsule/utils/storage/get_file.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:http/http.dart' as http;
  6. import 'package:pointycastle/export.dart';
  7. import 'package:sqflite/sqflite.dart';
  8. import '/components/flash_message.dart';
  9. import '/models/conversation_users.dart';
  10. import '/models/conversations.dart';
  11. import '/models/my_profile.dart';
  12. import '/utils/encryption/aes_helper.dart';
  13. import '/utils/storage/database.dart';
  14. import '/utils/storage/session_cookie.dart';
  15. Future<void> updateConversation(
  16. Conversation conversation,
  17. {
  18. includeUsers = false,
  19. updatedImage = false,
  20. } ) async {
  21. String sessionCookie = await getSessionCookie();
  22. Map<String, dynamic> conversationJson = await conversation.payloadJson(includeUsers: includeUsers);
  23. var resp = await http.put(
  24. await MyProfile.getServerUrl('api/v1/auth/conversations'),
  25. headers: <String, String>{
  26. 'Content-Type': 'application/json; charset=UTF-8',
  27. 'cookie': sessionCookie,
  28. },
  29. body: jsonEncode(conversationJson),
  30. );
  31. if (resp.statusCode != 204) {
  32. throw UpdateDataException('Unable to update conversation, please try again later.');
  33. }
  34. if (!updatedImage) {
  35. return;
  36. }
  37. Map<String, dynamic> attachmentJson = conversation.payloadImageJson();
  38. resp = await http.post(
  39. await MyProfile.getServerUrl('api/v1/auth/conversations/${conversation.id}/image'),
  40. headers: <String, String>{
  41. 'Content-Type': 'application/json; charset=UTF-8',
  42. 'cookie': sessionCookie,
  43. },
  44. body: jsonEncode(attachmentJson),
  45. );
  46. if (resp.statusCode != 204) {
  47. throw UpdateDataException('Unable to update conversation image, please try again later.');
  48. }
  49. }
  50. // TODO: Refactor this function
  51. Future<void> updateConversations() async {
  52. RSAPrivateKey privKey = await MyProfile.getPrivateKey();
  53. // try {
  54. var resp = await http.get(
  55. await MyProfile.getServerUrl('api/v1/auth/conversations'),
  56. headers: {
  57. 'cookie': await getSessionCookie(),
  58. }
  59. );
  60. if (resp.statusCode != 200) {
  61. throw Exception(resp.body);
  62. }
  63. List<Conversation> conversations = [];
  64. List<String> conversationsDetailIds = [];
  65. List<dynamic> conversationsJson = jsonDecode(resp.body);
  66. if (conversationsJson.isEmpty) {
  67. return;
  68. }
  69. for (var i = 0; i < conversationsJson.length; i++) {
  70. Conversation conversation = Conversation.fromJson(
  71. conversationsJson[i] as Map<String, dynamic>,
  72. privKey,
  73. );
  74. conversations.add(conversation);
  75. conversationsDetailIds.add(conversation.id);
  76. }
  77. Map<String, String> params = {};
  78. params['conversation_detail_ids'] = conversationsDetailIds.join(',');
  79. var uri = await MyProfile.getServerUrl('api/v1/auth/conversation_details');
  80. uri = uri.replace(queryParameters: params);
  81. resp = await http.get(
  82. uri,
  83. headers: {
  84. 'cookie': await getSessionCookie(),
  85. }
  86. );
  87. if (resp.statusCode != 200) {
  88. throw Exception(resp.body);
  89. }
  90. final db = await getDatabaseConnection();
  91. List<dynamic> conversationsDetailsJson = jsonDecode(resp.body);
  92. for (var i = 0; i < conversationsDetailsJson.length; i++) {
  93. var conversationDetailJson = conversationsDetailsJson[i] as Map<String, dynamic>;
  94. var conversation = findConversationByDetailId(conversations, conversationDetailJson['id']);
  95. conversation.messageExpiryDefault = conversationDetailJson['message_expiry'];
  96. conversation.twoUser = AesHelper.aesDecrypt(
  97. base64.decode(conversation.symmetricKey),
  98. base64.decode(conversationDetailJson['two_user']),
  99. ) == 'true';
  100. if (conversation.twoUser) {
  101. MyProfile profile = await MyProfile.getProfile();
  102. final db = await getDatabaseConnection();
  103. List<Map<String, dynamic>> maps = await db.query(
  104. 'conversation_users',
  105. where: 'conversation_id = ? AND user_id != ?',
  106. whereArgs: [ conversation.id, profile.id ],
  107. );
  108. if (maps.length != 1) {
  109. throw ArgumentError('Invalid user id');
  110. }
  111. conversation.name = maps[0]['username'];
  112. } else {
  113. conversation.name = AesHelper.aesDecrypt(
  114. base64.decode(conversation.symmetricKey),
  115. base64.decode(conversationDetailJson['name']),
  116. );
  117. }
  118. // TODO: Handle exception here
  119. if (conversationDetailJson['attachment_id'] != null) {
  120. conversation.icon = await getFile(
  121. '$defaultServerUrl/files/${conversationDetailJson['attachment']['image_link']}',
  122. conversation.id,
  123. conversation.symmetricKey,
  124. );
  125. }
  126. await db.insert(
  127. 'conversations',
  128. conversation.toMap(),
  129. conflictAlgorithm: ConflictAlgorithm.replace,
  130. );
  131. List<dynamic> usersData = conversationDetailJson['users'];
  132. for (var i = 0; i < usersData.length; i++) {
  133. ConversationUser conversationUser = ConversationUser.fromJson(
  134. usersData[i] as Map<String, dynamic>,
  135. base64.decode(conversation.symmetricKey),
  136. );
  137. await db.insert(
  138. 'conversation_users',
  139. conversationUser.toMap(),
  140. conflictAlgorithm: ConflictAlgorithm.replace,
  141. );
  142. }
  143. }
  144. // } catch (SocketException) {
  145. // return;
  146. // }
  147. }
  148. Future<void> uploadConversation(Conversation conversation, BuildContext context) async {
  149. String sessionCookie = await getSessionCookie();
  150. Map<String, dynamic> conversationJson = await conversation.payloadJson();
  151. var resp = await http.post(
  152. await MyProfile.getServerUrl('api/v1/auth/conversations'),
  153. headers: <String, String>{
  154. 'Content-Type': 'application/json; charset=UTF-8',
  155. 'cookie': sessionCookie,
  156. },
  157. body: jsonEncode(conversationJson),
  158. );
  159. if (resp.statusCode != 204) {
  160. showMessage('Failed to create conversation', context);
  161. }
  162. }