file_magic_service.dart 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. // @dart=2.9
  2. import 'dart:convert';
  3. import 'package:dio/dio.dart';
  4. import 'package:flutter_sodium/flutter_sodium.dart';
  5. import 'package:logging/logging.dart';
  6. import 'package:photos/core/configuration.dart';
  7. import 'package:photos/core/event_bus.dart';
  8. import 'package:photos/core/network.dart';
  9. import 'package:photos/db/files_db.dart';
  10. import 'package:photos/events/files_updated_event.dart';
  11. import 'package:photos/events/force_reload_home_gallery_event.dart';
  12. import 'package:photos/events/local_photos_updated_event.dart';
  13. import 'package:photos/models/file.dart';
  14. import 'package:photos/models/magic_metadata.dart';
  15. import 'package:photos/services/remote_sync_service.dart';
  16. import 'package:photos/utils/crypto_util.dart';
  17. import 'package:photos/utils/file_download_util.dart';
  18. class FileMagicService {
  19. final _logger = Logger("FileMagicService");
  20. Dio _dio;
  21. FilesDB _filesDB;
  22. FileMagicService._privateConstructor() {
  23. _filesDB = FilesDB.instance;
  24. _dio = Network.instance.getDio();
  25. }
  26. static final FileMagicService instance =
  27. FileMagicService._privateConstructor();
  28. Future<void> changeVisibility(List<File> files, int visibility) async {
  29. final Map<String, dynamic> update = {kMagicKeyVisibility: visibility};
  30. await _updateMagicData(files, update);
  31. if (visibility == kVisibilityVisible) {
  32. // Force reload home gallery to pull in the now unarchived files
  33. Bus.instance.fire(ForceReloadHomeGalleryEvent());
  34. Bus.instance
  35. .fire(LocalPhotosUpdatedEvent(files, type: EventType.unarchived));
  36. } else {
  37. Bus.instance
  38. .fire(LocalPhotosUpdatedEvent(files, type: EventType.archived));
  39. }
  40. }
  41. Future<void> updatePublicMagicMetadata(
  42. List<File> files,
  43. Map<String, dynamic> newMetadataUpdate,
  44. ) async {
  45. final params = <String, dynamic>{};
  46. params['metadataList'] = [];
  47. final int ownerID = Configuration.instance.getUserID();
  48. try {
  49. for (final file in files) {
  50. if (file.uploadedFileID == null) {
  51. throw AssertionError(
  52. "operation is only supported on backed up files",
  53. );
  54. } else if (file.ownerID != ownerID) {
  55. throw AssertionError("cannot modify memories not owned by you");
  56. }
  57. // read the existing magic metadata and apply new updates to existing data
  58. // current update is simple replace. This will be enhanced in the future,
  59. // as required.
  60. final Map<String, dynamic> jsonToUpdate = jsonDecode(file.pubMmdEncodedJson);
  61. newMetadataUpdate.forEach((key, value) {
  62. jsonToUpdate[key] = value;
  63. });
  64. // update the local information so that it's reflected on UI
  65. file.pubMmdEncodedJson = jsonEncode(jsonToUpdate);
  66. file.pubMagicMetadata = PubMagicMetadata.fromJson(jsonToUpdate);
  67. final fileKey = decryptFileKey(file);
  68. final encryptedMMd = await CryptoUtil.encryptChaCha(
  69. utf8.encode(jsonEncode(jsonToUpdate)),
  70. fileKey,
  71. );
  72. params['metadataList'].add(
  73. UpdateMagicMetadataRequest(
  74. id: file.uploadedFileID,
  75. magicMetadata: MetadataRequest(
  76. version: file.pubMmdVersion,
  77. count: jsonToUpdate.length,
  78. data: Sodium.bin2base64(encryptedMMd.encryptedData),
  79. header: Sodium.bin2base64(encryptedMMd.header),
  80. ),
  81. ),
  82. );
  83. file.pubMmdVersion = file.pubMmdVersion + 1;
  84. }
  85. await _dio.put(
  86. Configuration.instance.getHttpEndpoint() +
  87. "/files/public-magic-metadata",
  88. data: params,
  89. options: Options(
  90. headers: {"X-Auth-Token": Configuration.instance.getToken()},
  91. ),
  92. );
  93. // update the state of the selected file. Same file in other collection
  94. // should be eventually synced after remote sync has completed
  95. await _filesDB.insertMultiple(files);
  96. RemoteSyncService.instance.sync(silently: true);
  97. } on DioError catch (e) {
  98. if (e.response != null && e.response.statusCode == 409) {
  99. RemoteSyncService.instance.sync(silently: true);
  100. }
  101. rethrow;
  102. } catch (e, s) {
  103. _logger.severe("failed to sync magic metadata", e, s);
  104. rethrow;
  105. }
  106. }
  107. Future<void> _updateMagicData(
  108. List<File> files,
  109. Map<String, dynamic> newMetadataUpdate,
  110. ) async {
  111. final params = <String, dynamic>{};
  112. params['metadataList'] = [];
  113. final int ownerID = Configuration.instance.getUserID();
  114. try {
  115. for (final file in files) {
  116. if (file.uploadedFileID == null) {
  117. throw AssertionError(
  118. "operation is only supported on backed up files",
  119. );
  120. } else if (file.ownerID != ownerID) {
  121. throw AssertionError("cannot modify memories not owned by you");
  122. }
  123. // read the existing magic metadata and apply new updates to existing data
  124. // current update is simple replace. This will be enhanced in the future,
  125. // as required.
  126. final Map<String, dynamic> jsonToUpdate = jsonDecode(file.mMdEncodedJson);
  127. newMetadataUpdate.forEach((key, value) {
  128. jsonToUpdate[key] = value;
  129. });
  130. // update the local information so that it's reflected on UI
  131. file.mMdEncodedJson = jsonEncode(jsonToUpdate);
  132. file.magicMetadata = MagicMetadata.fromJson(jsonToUpdate);
  133. final fileKey = decryptFileKey(file);
  134. final encryptedMMd = await CryptoUtil.encryptChaCha(
  135. utf8.encode(jsonEncode(jsonToUpdate)),
  136. fileKey,
  137. );
  138. params['metadataList'].add(
  139. UpdateMagicMetadataRequest(
  140. id: file.uploadedFileID,
  141. magicMetadata: MetadataRequest(
  142. version: file.mMdVersion,
  143. count: jsonToUpdate.length,
  144. data: Sodium.bin2base64(encryptedMMd.encryptedData),
  145. header: Sodium.bin2base64(encryptedMMd.header),
  146. ),
  147. ),
  148. );
  149. file.mMdVersion = file.mMdVersion + 1;
  150. }
  151. await _dio.put(
  152. Configuration.instance.getHttpEndpoint() + "/files/magic-metadata",
  153. data: params,
  154. options: Options(
  155. headers: {"X-Auth-Token": Configuration.instance.getToken()},
  156. ),
  157. );
  158. // update the state of the selected file. Same file in other collection
  159. // should be eventually synced after remote sync has completed
  160. await _filesDB.insertMultiple(files);
  161. RemoteSyncService.instance.sync(silently: true);
  162. } on DioError catch (e) {
  163. if (e.response != null && e.response.statusCode == 409) {
  164. RemoteSyncService.instance.sync(silently: true);
  165. }
  166. rethrow;
  167. } catch (e, s) {
  168. _logger.severe("failed to sync magic metadata", e, s);
  169. rethrow;
  170. }
  171. }
  172. }
  173. class UpdateMagicMetadataRequest {
  174. final int id;
  175. final MetadataRequest magicMetadata;
  176. UpdateMagicMetadataRequest({this.id, this.magicMetadata});
  177. factory UpdateMagicMetadataRequest.fromJson(dynamic json) {
  178. return UpdateMagicMetadataRequest(
  179. id: json['id'],
  180. magicMetadata: json['magicMetadata'] != null
  181. ? MetadataRequest.fromJson(json['magicMetadata'])
  182. : null,
  183. );
  184. }
  185. Map<String, dynamic> toJson() {
  186. final map = <String, dynamic>{};
  187. map['id'] = id;
  188. if (magicMetadata != null) {
  189. map['magicMetadata'] = magicMetadata.toJson();
  190. }
  191. return map;
  192. }
  193. }
  194. class MetadataRequest {
  195. int version;
  196. int count;
  197. String data;
  198. String header;
  199. MetadataRequest({this.version, this.count, this.data, this.header});
  200. MetadataRequest.fromJson(dynamic json) {
  201. version = json['version'];
  202. count = json['count'];
  203. data = json['data'];
  204. header = json['header'];
  205. }
  206. Map<String, dynamic> toJson() {
  207. final map = <String, dynamic>{};
  208. map['version'] = version;
  209. map['count'] = count;
  210. map['data'] = data;
  211. map['header'] = header;
  212. return map;
  213. }
  214. }