file.dart 9.4 KB

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