asset.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. import 'dart:convert';
  2. import 'package:immich_mobile/shared/models/exif_info.dart';
  3. import 'package:immich_mobile/shared/models/store.dart';
  4. import 'package:immich_mobile/utils/hash.dart';
  5. import 'package:isar/isar.dart';
  6. import 'package:openapi/api.dart';
  7. import 'package:photo_manager/photo_manager.dart';
  8. import 'package:immich_mobile/utils/builtin_extensions.dart';
  9. import 'package:path/path.dart' as p;
  10. part 'asset.g.dart';
  11. /// Asset (online or local)
  12. @Collection(inheritance: false)
  13. class Asset {
  14. Asset.remote(AssetResponseDto remote)
  15. : remoteId = remote.id,
  16. checksum = remote.checksum,
  17. fileCreatedAt = remote.fileCreatedAt,
  18. fileModifiedAt = remote.fileModifiedAt,
  19. updatedAt = remote.updatedAt,
  20. durationInSeconds = remote.duration.toDuration()?.inSeconds ?? 0,
  21. type = remote.type.toAssetType(),
  22. fileName = p.basename(remote.originalPath),
  23. height = remote.exifInfo?.exifImageHeight?.toInt(),
  24. width = remote.exifInfo?.exifImageWidth?.toInt(),
  25. livePhotoVideoId = remote.livePhotoVideoId,
  26. ownerId = fastHash(remote.ownerId),
  27. exifInfo =
  28. remote.exifInfo != null ? ExifInfo.fromDto(remote.exifInfo!) : null,
  29. isFavorite = remote.isFavorite,
  30. isArchived = remote.isArchived;
  31. Asset.local(AssetEntity local, List<int> hash)
  32. : localId = local.id,
  33. checksum = base64.encode(hash),
  34. durationInSeconds = local.duration,
  35. type = AssetType.values[local.typeInt],
  36. height = local.height,
  37. width = local.width,
  38. fileName = local.title!,
  39. ownerId = Store.get(StoreKey.currentUser).isarId,
  40. fileModifiedAt = local.modifiedDateTime,
  41. updatedAt = local.modifiedDateTime,
  42. isFavorite = local.isFavorite,
  43. isArchived = false,
  44. fileCreatedAt = local.createDateTime {
  45. if (fileCreatedAt.year == 1970) {
  46. fileCreatedAt = fileModifiedAt;
  47. }
  48. if (local.latitude != null) {
  49. exifInfo = ExifInfo(lat: local.latitude, long: local.longitude);
  50. }
  51. _local = local;
  52. assert(hash.length == 20, "invalid SHA1 hash");
  53. }
  54. Asset({
  55. this.id = Isar.autoIncrement,
  56. required this.checksum,
  57. this.remoteId,
  58. required this.localId,
  59. required this.ownerId,
  60. required this.fileCreatedAt,
  61. required this.fileModifiedAt,
  62. required this.updatedAt,
  63. required this.durationInSeconds,
  64. required this.type,
  65. this.width,
  66. this.height,
  67. required this.fileName,
  68. this.livePhotoVideoId,
  69. this.exifInfo,
  70. required this.isFavorite,
  71. required this.isArchived,
  72. });
  73. @ignore
  74. AssetEntity? _local;
  75. @ignore
  76. AssetEntity? get local {
  77. if (isLocal && _local == null) {
  78. _local = AssetEntity(
  79. id: localId!,
  80. typeInt: isImage ? 1 : 2,
  81. width: width ?? 0,
  82. height: height ?? 0,
  83. duration: durationInSeconds,
  84. createDateSecond: fileCreatedAt.millisecondsSinceEpoch ~/ 1000,
  85. modifiedDateSecond: fileModifiedAt.millisecondsSinceEpoch ~/ 1000,
  86. title: fileName,
  87. );
  88. }
  89. return _local;
  90. }
  91. Id id = Isar.autoIncrement;
  92. /// stores the raw SHA1 bytes as a base64 String
  93. /// because Isar cannot sort lists of byte arrays
  94. String checksum;
  95. @Index(unique: false, replace: false, type: IndexType.hash)
  96. String? remoteId;
  97. @Index(unique: false, replace: false, type: IndexType.hash)
  98. String? localId;
  99. @Index(
  100. unique: true,
  101. replace: false,
  102. composite: [CompositeIndex("checksum", type: IndexType.hash)],
  103. )
  104. int ownerId;
  105. DateTime fileCreatedAt;
  106. DateTime fileModifiedAt;
  107. DateTime updatedAt;
  108. int durationInSeconds;
  109. @Enumerated(EnumType.ordinal)
  110. AssetType type;
  111. short? width;
  112. short? height;
  113. String fileName;
  114. String? livePhotoVideoId;
  115. bool isFavorite;
  116. bool isArchived;
  117. @ignore
  118. ExifInfo? exifInfo;
  119. /// `true` if this [Asset] is present on the device
  120. @ignore
  121. bool get isLocal => localId != null;
  122. @ignore
  123. bool get isInDb => id != Isar.autoIncrement;
  124. @ignore
  125. String get name => p.withoutExtension(fileName);
  126. /// `true` if this [Asset] is present on the server
  127. @ignore
  128. bool get isRemote => remoteId != null;
  129. @ignore
  130. bool get isImage => type == AssetType.image;
  131. @ignore
  132. AssetState get storage {
  133. if (isRemote && isLocal) {
  134. return AssetState.merged;
  135. } else if (isRemote) {
  136. return AssetState.remote;
  137. } else if (isLocal) {
  138. return AssetState.local;
  139. } else {
  140. throw Exception("Asset has illegal state: $this");
  141. }
  142. }
  143. @ignore
  144. Duration get duration => Duration(seconds: durationInSeconds);
  145. @override
  146. bool operator ==(other) {
  147. if (other is! Asset) return false;
  148. if (identical(this, other)) return true;
  149. return id == other.id &&
  150. checksum == other.checksum &&
  151. remoteId == other.remoteId &&
  152. localId == other.localId &&
  153. ownerId == other.ownerId &&
  154. fileCreatedAt.isAtSameMomentAs(other.fileCreatedAt) &&
  155. fileModifiedAt.isAtSameMomentAs(other.fileModifiedAt) &&
  156. updatedAt.isAtSameMomentAs(other.updatedAt) &&
  157. durationInSeconds == other.durationInSeconds &&
  158. type == other.type &&
  159. width == other.width &&
  160. height == other.height &&
  161. fileName == other.fileName &&
  162. livePhotoVideoId == other.livePhotoVideoId &&
  163. isFavorite == other.isFavorite &&
  164. isLocal == other.isLocal &&
  165. isArchived == other.isArchived;
  166. }
  167. @override
  168. @ignore
  169. int get hashCode =>
  170. id.hashCode ^
  171. checksum.hashCode ^
  172. remoteId.hashCode ^
  173. localId.hashCode ^
  174. ownerId.hashCode ^
  175. fileCreatedAt.hashCode ^
  176. fileModifiedAt.hashCode ^
  177. updatedAt.hashCode ^
  178. durationInSeconds.hashCode ^
  179. type.hashCode ^
  180. width.hashCode ^
  181. height.hashCode ^
  182. fileName.hashCode ^
  183. livePhotoVideoId.hashCode ^
  184. isFavorite.hashCode ^
  185. isLocal.hashCode ^
  186. isArchived.hashCode;
  187. /// Returns `true` if this [Asset] can updated with values from parameter [a]
  188. bool canUpdate(Asset a) {
  189. assert(isInDb);
  190. assert(checksum == a.checksum);
  191. assert(a.storage != AssetState.merged);
  192. return a.updatedAt.isAfter(updatedAt) ||
  193. a.isRemote && !isRemote ||
  194. a.isLocal && !isLocal ||
  195. width == null && a.width != null ||
  196. height == null && a.height != null ||
  197. livePhotoVideoId == null && a.livePhotoVideoId != null ||
  198. !isRemote && a.isRemote && isFavorite != a.isFavorite ||
  199. !isRemote && a.isRemote && isArchived != a.isArchived;
  200. }
  201. /// Returns a new [Asset] with values from this and merged & updated with [a]
  202. Asset updatedCopy(Asset a) {
  203. assert(canUpdate(a));
  204. if (a.updatedAt.isAfter(updatedAt)) {
  205. // take most values from newer asset
  206. // keep vales that can never be set by the asset not in DB
  207. if (a.isRemote) {
  208. return a._copyWith(
  209. id: id,
  210. localId: localId,
  211. width: a.width ?? width,
  212. height: a.height ?? height,
  213. exifInfo: a.exifInfo?.copyWith(id: id) ?? exifInfo,
  214. );
  215. } else if (isRemote) {
  216. return _copyWith(
  217. localId: localId ?? a.localId,
  218. width: width ?? a.width,
  219. height: height ?? a.height,
  220. exifInfo: exifInfo ?? a.exifInfo?.copyWith(id: id),
  221. );
  222. } else {
  223. return a._copyWith(
  224. id: id,
  225. remoteId: remoteId,
  226. livePhotoVideoId: livePhotoVideoId,
  227. isFavorite: isFavorite,
  228. isArchived: isArchived,
  229. );
  230. }
  231. } else {
  232. // fill in potentially missing values, i.e. merge assets
  233. if (a.isRemote) {
  234. // values from remote take precedence
  235. return _copyWith(
  236. remoteId: a.remoteId,
  237. width: a.width,
  238. height: a.height,
  239. livePhotoVideoId: a.livePhotoVideoId,
  240. // isFavorite + isArchived are not set by device-only assets
  241. isFavorite: a.isFavorite,
  242. isArchived: a.isArchived,
  243. exifInfo: a.exifInfo?.copyWith(id: id) ?? exifInfo,
  244. );
  245. } else {
  246. // add only missing values (and set isLocal to true)
  247. return _copyWith(
  248. localId: localId ?? a.localId,
  249. width: width ?? a.width,
  250. height: height ?? a.height,
  251. exifInfo: exifInfo ?? a.exifInfo?.copyWith(id: id),
  252. );
  253. }
  254. }
  255. }
  256. Asset _copyWith({
  257. Id? id,
  258. String? checksum,
  259. String? remoteId,
  260. String? localId,
  261. int? ownerId,
  262. DateTime? fileCreatedAt,
  263. DateTime? fileModifiedAt,
  264. DateTime? updatedAt,
  265. int? durationInSeconds,
  266. AssetType? type,
  267. short? width,
  268. short? height,
  269. String? fileName,
  270. String? livePhotoVideoId,
  271. bool? isFavorite,
  272. bool? isArchived,
  273. ExifInfo? exifInfo,
  274. }) =>
  275. Asset(
  276. id: id ?? this.id,
  277. checksum: checksum ?? this.checksum,
  278. remoteId: remoteId ?? this.remoteId,
  279. localId: localId ?? this.localId,
  280. ownerId: ownerId ?? this.ownerId,
  281. fileCreatedAt: fileCreatedAt ?? this.fileCreatedAt,
  282. fileModifiedAt: fileModifiedAt ?? this.fileModifiedAt,
  283. updatedAt: updatedAt ?? this.updatedAt,
  284. durationInSeconds: durationInSeconds ?? this.durationInSeconds,
  285. type: type ?? this.type,
  286. width: width ?? this.width,
  287. height: height ?? this.height,
  288. fileName: fileName ?? this.fileName,
  289. livePhotoVideoId: livePhotoVideoId ?? this.livePhotoVideoId,
  290. isFavorite: isFavorite ?? this.isFavorite,
  291. isArchived: isArchived ?? this.isArchived,
  292. exifInfo: exifInfo ?? this.exifInfo,
  293. );
  294. Future<void> put(Isar db) async {
  295. await db.assets.put(this);
  296. if (exifInfo != null) {
  297. exifInfo!.id = id;
  298. await db.exifInfos.put(exifInfo!);
  299. }
  300. }
  301. static int compareById(Asset a, Asset b) => a.id.compareTo(b.id);
  302. static int compareByChecksum(Asset a, Asset b) =>
  303. a.checksum.compareTo(b.checksum);
  304. static int compareByOwnerChecksum(Asset a, Asset b) {
  305. final int ownerIdOrder = a.ownerId.compareTo(b.ownerId);
  306. if (ownerIdOrder != 0) return ownerIdOrder;
  307. return compareByChecksum(a, b);
  308. }
  309. static int compareByOwnerChecksumCreatedModified(Asset a, Asset b) {
  310. final int ownerIdOrder = a.ownerId.compareTo(b.ownerId);
  311. if (ownerIdOrder != 0) return ownerIdOrder;
  312. final int checksumOrder = compareByChecksum(a, b);
  313. if (checksumOrder != 0) return checksumOrder;
  314. final int createdOrder = a.fileCreatedAt.compareTo(b.fileCreatedAt);
  315. if (createdOrder != 0) return createdOrder;
  316. return a.fileModifiedAt.compareTo(b.fileModifiedAt);
  317. }
  318. @override
  319. String toString() {
  320. return """
  321. {
  322. "id": ${id == Isar.autoIncrement ? '"N/A"' : id},
  323. "remoteId": "${remoteId ?? "N/A"}",
  324. "localId": "${localId ?? "N/A"}",
  325. "checksum": "$checksum",
  326. "ownerId": $ownerId,
  327. "livePhotoVideoId": "${livePhotoVideoId ?? "N/A"}",
  328. "fileCreatedAt": "$fileCreatedAt",
  329. "fileModifiedAt": "$fileModifiedAt",
  330. "updatedAt": "$updatedAt",
  331. "durationInSeconds": $durationInSeconds,
  332. "type": "$type",
  333. "fileName": "$fileName",
  334. "isFavorite": $isFavorite,
  335. "isRemote: $isRemote,
  336. "storage": "$storage",
  337. "width": ${width ?? "N/A"},
  338. "height": ${height ?? "N/A"},
  339. "isArchived": $isArchived
  340. }""";
  341. }
  342. }
  343. enum AssetType {
  344. // do not change this order!
  345. other,
  346. image,
  347. video,
  348. audio,
  349. }
  350. extension AssetTypeEnumHelper on AssetTypeEnum {
  351. AssetType toAssetType() {
  352. switch (this) {
  353. case AssetTypeEnum.IMAGE:
  354. return AssetType.image;
  355. case AssetTypeEnum.VIDEO:
  356. return AssetType.video;
  357. case AssetTypeEnum.AUDIO:
  358. return AssetType.audio;
  359. case AssetTypeEnum.OTHER:
  360. return AssetType.other;
  361. }
  362. throw Exception();
  363. }
  364. }
  365. /// Describes where the information of this asset came from:
  366. /// only from the local device, only from the remote server or merged from both
  367. enum AssetState {
  368. local,
  369. remote,
  370. merged,
  371. }
  372. extension AssetsHelper on IsarCollection<Asset> {
  373. Future<int> deleteAllByRemoteId(Iterable<String> ids) =>
  374. ids.isEmpty ? Future.value(0) : remote(ids).deleteAll();
  375. Future<int> deleteAllByLocalId(Iterable<String> ids) =>
  376. ids.isEmpty ? Future.value(0) : local(ids).deleteAll();
  377. Future<List<Asset>> getAllByRemoteId(Iterable<String> ids) =>
  378. ids.isEmpty ? Future.value([]) : remote(ids).findAll();
  379. Future<List<Asset>> getAllByLocalId(Iterable<String> ids) =>
  380. ids.isEmpty ? Future.value([]) : local(ids).findAll();
  381. QueryBuilder<Asset, Asset, QAfterWhereClause> remote(Iterable<String> ids) =>
  382. where().anyOf(ids, (q, String e) => q.remoteIdEqualTo(e));
  383. QueryBuilder<Asset, Asset, QAfterWhereClause> local(Iterable<String> ids) {
  384. return where().anyOf(ids, (q, String e) => q.localIdEqualTo(e));
  385. }
  386. }