file.dart 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import 'package:logging/logging.dart';
  2. import 'package:path/path.dart';
  3. import 'package:photo_manager/photo_manager.dart';
  4. import 'package:photos/core/configuration.dart';
  5. import 'package:photos/core/constants.dart';
  6. import 'package:photos/models/ente_file.dart';
  7. import 'package:photos/models/file_type.dart';
  8. import 'package:photos/models/location.dart';
  9. import 'package:photos/models/magic_metadata.dart';
  10. // ignore: import_of_legacy_library_into_null_safe
  11. import 'package:photos/services/feature_flag_service.dart';
  12. // ignore: import_of_legacy_library_into_null_safe
  13. import 'package:photos/utils/exif_util.dart';
  14. // ignore: import_of_legacy_library_into_null_safe
  15. import 'package:photos/utils/file_uploader_util.dart';
  16. class File extends EnteFile {
  17. int? generatedID;
  18. int? uploadedFileID;
  19. int? ownerID;
  20. int? collectionID;
  21. String? localID;
  22. String? title;
  23. String? deviceFolder;
  24. int? creationTime;
  25. int? modificationTime;
  26. int? updationTime;
  27. Location? location;
  28. late FileType fileType;
  29. int? fileSubType;
  30. int? duration;
  31. String? exif;
  32. String? hash;
  33. int? metadataVersion;
  34. String? encryptedKey;
  35. String? keyDecryptionNonce;
  36. String? fileDecryptionHeader;
  37. String? thumbnailDecryptionHeader;
  38. String? metadataDecryptionHeader;
  39. String? mMdEncodedJson;
  40. int mMdVersion = 0;
  41. MagicMetadata? _mmd;
  42. MagicMetadata get magicMetadata =>
  43. _mmd ?? MagicMetadata.fromEncodedJson(mMdEncodedJson ?? '{}');
  44. set magicMetadata(val) => _mmd = val;
  45. // public magic metadata is shared if during file/album sharing
  46. String? pubMmdEncodedJson;
  47. int pubMmdVersion = 0;
  48. PubMagicMetadata? _pubMmd;
  49. PubMagicMetadata? get pubMagicMetadata =>
  50. _pubMmd ?? PubMagicMetadata.fromEncodedJson(pubMmdEncodedJson ?? '{}');
  51. set pubMagicMetadata(val) => _pubMmd = val;
  52. // in Version 1, live photo hash is stored as zip's hash.
  53. // in V2: LivePhoto hash is stored as imgHash:vidHash
  54. static const kCurrentMetadataVersion = 2;
  55. static final _logger = Logger('File');
  56. File();
  57. static Future<File> fromAsset(String pathName, AssetEntity asset) async {
  58. final File file = File();
  59. file.localID = asset.id;
  60. file.title = asset.title;
  61. file.deviceFolder = pathName;
  62. file.location = Location(asset.latitude, asset.longitude);
  63. file.fileType = _fileTypeFromAsset(asset);
  64. file.creationTime = asset.createDateTime.microsecondsSinceEpoch;
  65. if (file.creationTime == 0) {
  66. try {
  67. final parsedDateTime = DateTime.parse(
  68. basenameWithoutExtension(file.title!)
  69. .replaceAll("IMG_", "")
  70. .replaceAll("VID_", "")
  71. .replaceAll("DCIM_", "")
  72. .replaceAll("_", " "),
  73. );
  74. file.creationTime = parsedDateTime.microsecondsSinceEpoch;
  75. } catch (e) {
  76. file.creationTime = asset.modifiedDateTime.microsecondsSinceEpoch;
  77. }
  78. }
  79. file.modificationTime = asset.modifiedDateTime.microsecondsSinceEpoch;
  80. file.fileSubType = asset.subtype;
  81. file.metadataVersion = kCurrentMetadataVersion;
  82. return file;
  83. }
  84. static FileType _fileTypeFromAsset(AssetEntity asset) {
  85. FileType type = FileType.image;
  86. switch (asset.type) {
  87. case AssetType.image:
  88. type = FileType.image;
  89. // PHAssetMediaSubtype.photoLive.rawValue is 8
  90. // This hack should go away once photos_manager support livePhotos
  91. if (asset.subtype != null &&
  92. asset.subtype > -1 &&
  93. (asset.subtype & 8) != 0) {
  94. type = FileType.livePhoto;
  95. }
  96. break;
  97. case AssetType.video:
  98. type = FileType.video;
  99. break;
  100. default:
  101. type = FileType.other;
  102. break;
  103. }
  104. return type;
  105. }
  106. Future<AssetEntity?> getAsset() {
  107. if (localID == null) {
  108. return Future.value(null);
  109. }
  110. return AssetEntity.fromId(localID!);
  111. }
  112. void applyMetadata(Map<String, dynamic> metadata) {
  113. localID = metadata["localID"];
  114. title = metadata["title"];
  115. deviceFolder = metadata["deviceFolder"];
  116. creationTime = metadata["creationTime"] ?? 0;
  117. modificationTime = metadata["modificationTime"] ?? creationTime;
  118. final latitude = double.tryParse(metadata["latitude"].toString());
  119. final longitude = double.tryParse(metadata["longitude"].toString());
  120. if (latitude == null || longitude == null) {
  121. location = null;
  122. } else {
  123. location = Location(latitude, longitude);
  124. }
  125. fileType = getFileType(metadata["fileType"]);
  126. fileSubType = metadata["subType"] ?? -1;
  127. duration = metadata["duration"] ?? 0;
  128. exif = metadata["exif"];
  129. hash = metadata["hash"];
  130. // handle past live photos upload from web client
  131. if (hash == null &&
  132. fileType == FileType.livePhoto &&
  133. metadata.containsKey('imgHash') &&
  134. metadata.containsKey('vidHash')) {
  135. // convert to imgHash:vidHash
  136. hash =
  137. '${metadata['imgHash']}$kLivePhotoHashSeparator${metadata['vidHash']}';
  138. }
  139. metadataVersion = metadata["version"] ?? 0;
  140. }
  141. Future<Map<String, dynamic>> getMetadataForUpload(
  142. MediaUploadData mediaUploadData,
  143. ) async {
  144. final asset = await getAsset();
  145. // asset can be null for files shared to app
  146. if (asset != null) {
  147. fileSubType = asset.subtype;
  148. if (fileType == FileType.video) {
  149. duration = asset.duration;
  150. }
  151. }
  152. if (fileType == FileType.image) {
  153. final exifTime =
  154. await getCreationTimeFromEXIF(mediaUploadData.sourceFile);
  155. if (exifTime != null) {
  156. creationTime = exifTime.microsecondsSinceEpoch;
  157. }
  158. }
  159. hash = mediaUploadData.hashData?.fileHash;
  160. return getMetadata();
  161. }
  162. Map<String, dynamic> getMetadata() {
  163. final metadata = <String, dynamic>{};
  164. metadata["localID"] = isSharedMediaToAppSandbox() ? null : localID;
  165. metadata["title"] = title;
  166. metadata["deviceFolder"] = deviceFolder;
  167. metadata["creationTime"] = creationTime;
  168. metadata["modificationTime"] = modificationTime;
  169. metadata["fileType"] = fileType.index;
  170. if (location != null &&
  171. location!.latitude != null &&
  172. location!.longitude != null) {
  173. metadata["latitude"] = location!.latitude;
  174. metadata["longitude"] = location!.longitude;
  175. }
  176. if (fileSubType != null) {
  177. metadata["subType"] = fileSubType;
  178. }
  179. if (duration != null) {
  180. metadata["duration"] = duration;
  181. }
  182. if (hash != null) {
  183. metadata["hash"] = hash;
  184. }
  185. if (metadataVersion != null) {
  186. metadata["version"] = metadataVersion;
  187. }
  188. return metadata;
  189. }
  190. String getDownloadUrl() {
  191. final endpoint = Configuration.instance.getHttpEndpoint();
  192. if (endpoint != kDefaultProductionEndpoint ||
  193. FeatureFlagService.instance.disableCFWorker()) {
  194. return endpoint + "/files/download/" + uploadedFileID.toString();
  195. } else {
  196. return "https://files.ente.io/?fileID=" + uploadedFileID.toString();
  197. }
  198. }
  199. String getThumbnailUrl() {
  200. final endpoint = Configuration.instance.getHttpEndpoint();
  201. if (endpoint != kDefaultProductionEndpoint ||
  202. FeatureFlagService.instance.disableCFWorker()) {
  203. return endpoint + "/files/preview/" + uploadedFileID.toString();
  204. } else {
  205. return "https://thumbnails.ente.io/?fileID=" + uploadedFileID.toString();
  206. }
  207. }
  208. String getDisplayName() {
  209. if (pubMagicMetadata != null && pubMagicMetadata!.editedName != null) {
  210. return pubMagicMetadata!.editedName!;
  211. }
  212. if (title == null) _logger.severe('File title is null');
  213. return title ?? '';
  214. }
  215. // returns true if the file isn't available in the user's gallery
  216. bool isRemoteFile() {
  217. return localID == null && uploadedFileID != null;
  218. }
  219. bool isSharedMediaToAppSandbox() {
  220. return localID != null &&
  221. (localID!.startsWith(oldSharedMediaIdentifier) ||
  222. localID!.startsWith(sharedMediaIdentifier));
  223. }
  224. bool hasLocation() {
  225. return location != null &&
  226. (location!.longitude != 0 || location!.latitude != 0);
  227. }
  228. @override
  229. String toString() {
  230. return '''File(generatedID: $generatedID, localID: $localID, title: $title,
  231. uploadedFileId: $uploadedFileID, modificationTime: $modificationTime,
  232. ownerID: $ownerID, collectionID: $collectionID, updationTime: $updationTime)''';
  233. }
  234. @override
  235. bool operator ==(Object o) {
  236. if (identical(this, o)) return true;
  237. return o is File &&
  238. o.generatedID == generatedID &&
  239. o.uploadedFileID == uploadedFileID &&
  240. o.localID == localID;
  241. }
  242. @override
  243. int get hashCode {
  244. return generatedID.hashCode ^ uploadedFileID.hashCode ^ localID.hashCode;
  245. }
  246. String tag() {
  247. return "local_" +
  248. localID.toString() +
  249. ":remote_" +
  250. uploadedFileID.toString() +
  251. ":generated_" +
  252. generatedID.toString();
  253. }
  254. @override
  255. String cacheKey() {
  256. // todo: Neeraj: 19thJuly'22: evaluate and add fileHash as the key?
  257. return localID ?? uploadedFileID?.toString() ?? generatedID.toString();
  258. }
  259. }