file_magic_service.dart 7.6 KB

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