2023-03-04 00:38:30 +02:00
|
|
|
import 'dart:async';
|
|
|
|
|
|
|
|
import 'package:collection/collection.dart';
|
|
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
|
|
import 'package:immich_mobile/shared/models/album.dart';
|
|
|
|
import 'package:immich_mobile/shared/models/asset.dart';
|
2023-06-10 20:13:59 +02:00
|
|
|
import 'package:immich_mobile/shared/models/etag.dart';
|
2023-03-04 00:38:30 +02:00
|
|
|
import 'package:immich_mobile/shared/models/exif_info.dart';
|
|
|
|
import 'package:immich_mobile/shared/models/store.dart';
|
|
|
|
import 'package:immich_mobile/shared/models/user.dart';
|
|
|
|
import 'package:immich_mobile/shared/providers/db.provider.dart';
|
2023-06-10 20:13:59 +02:00
|
|
|
import 'package:immich_mobile/shared/services/hash.service.dart';
|
2023-03-04 00:38:30 +02:00
|
|
|
import 'package:immich_mobile/utils/async_mutex.dart';
|
2023-04-15 03:50:58 +02:00
|
|
|
import 'package:immich_mobile/utils/builtin_extensions.dart';
|
2023-03-04 00:38:30 +02:00
|
|
|
import 'package:immich_mobile/utils/diff.dart';
|
|
|
|
import 'package:isar/isar.dart';
|
2023-03-20 00:05:18 +02:00
|
|
|
import 'package:logging/logging.dart';
|
2023-03-04 00:38:30 +02:00
|
|
|
import 'package:openapi/api.dart';
|
|
|
|
import 'package:photo_manager/photo_manager.dart';
|
|
|
|
|
2023-06-10 20:13:59 +02:00
|
|
|
final syncServiceProvider = Provider(
|
|
|
|
(ref) => SyncService(ref.watch(dbProvider), ref.watch(hashServiceProvider)),
|
|
|
|
);
|
2023-03-04 00:38:30 +02:00
|
|
|
|
|
|
|
class SyncService {
|
|
|
|
final Isar _db;
|
2023-06-10 20:13:59 +02:00
|
|
|
final HashService _hashService;
|
2023-03-04 00:38:30 +02:00
|
|
|
final AsyncMutex _lock = AsyncMutex();
|
2023-03-20 00:05:18 +02:00
|
|
|
final Logger _log = Logger('SyncService');
|
2023-03-04 00:38:30 +02:00
|
|
|
|
2023-06-10 20:13:59 +02:00
|
|
|
SyncService(this._db, this._hashService);
|
2023-03-04 00:38:30 +02:00
|
|
|
|
|
|
|
// public methods:
|
|
|
|
|
|
|
|
/// Syncs users from the server to the local database
|
|
|
|
/// Returns `true`if there were any changes
|
|
|
|
Future<bool> syncUsersFromServer(List<User> users) async {
|
|
|
|
users.sortBy((u) => u.id);
|
|
|
|
final dbUsers = await _db.users.where().sortById().findAll();
|
2023-06-10 20:13:59 +02:00
|
|
|
assert(dbUsers.isSortedBy((u) => u.id), "dbUsers not sorted!");
|
2023-03-04 00:38:30 +02:00
|
|
|
final List<int> toDelete = [];
|
|
|
|
final List<User> toUpsert = [];
|
|
|
|
final changes = diffSortedListsSync(
|
|
|
|
users,
|
|
|
|
dbUsers,
|
|
|
|
compare: (User a, User b) => a.id.compareTo(b.id),
|
|
|
|
both: (User a, User b) {
|
2023-05-25 05:52:43 +02:00
|
|
|
if (!a.updatedAt.isAtSameMomentAs(b.updatedAt) ||
|
|
|
|
a.isPartnerSharedBy != b.isPartnerSharedBy ||
|
|
|
|
a.isPartnerSharedWith != b.isPartnerSharedWith) {
|
2023-03-04 00:38:30 +02:00
|
|
|
toUpsert.add(a);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
},
|
|
|
|
onlyFirst: (User a) => toUpsert.add(a),
|
|
|
|
onlySecond: (User b) => toDelete.add(b.isarId),
|
|
|
|
);
|
|
|
|
if (changes) {
|
|
|
|
await _db.writeTxn(() async {
|
|
|
|
await _db.users.deleteAll(toDelete);
|
|
|
|
await _db.users.putAll(toUpsert);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return changes;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Syncs remote assets owned by the logged-in user to the DB
|
|
|
|
/// Returns `true` if there were any changes
|
2023-03-27 04:35:52 +02:00
|
|
|
Future<bool> syncRemoteAssetsToDb(
|
2023-05-25 05:52:43 +02:00
|
|
|
User user,
|
2023-09-10 14:51:18 +02:00
|
|
|
Future<(List<Asset>? toUpsert, List<String>? toDelete)> Function(
|
|
|
|
User user,
|
|
|
|
DateTime since,
|
|
|
|
) getChangedAssets,
|
|
|
|
FutureOr<List<Asset>?> Function(User user) loadAssets,
|
2023-03-27 04:35:52 +02:00
|
|
|
) =>
|
2023-09-10 14:51:18 +02:00
|
|
|
_lock.run(
|
|
|
|
() async =>
|
|
|
|
await _syncRemoteAssetChanges(user, getChangedAssets) ??
|
|
|
|
await _syncRemoteAssetsFull(user, loadAssets),
|
|
|
|
);
|
2023-03-04 00:38:30 +02:00
|
|
|
|
|
|
|
/// Syncs remote albums to the database
|
|
|
|
/// returns `true` if there were any changes
|
|
|
|
Future<bool> syncRemoteAlbumsToDb(
|
|
|
|
List<AlbumResponseDto> remote, {
|
|
|
|
required bool isShared,
|
|
|
|
required FutureOr<AlbumResponseDto> Function(AlbumResponseDto) loadDetails,
|
|
|
|
}) =>
|
|
|
|
_lock.run(() => _syncRemoteAlbumsToDb(remote, isShared, loadDetails));
|
|
|
|
|
|
|
|
/// Syncs all device albums and their assets to the database
|
|
|
|
/// Returns `true` if there were any changes
|
2023-03-20 00:05:18 +02:00
|
|
|
Future<bool> syncLocalAlbumAssetsToDb(
|
|
|
|
List<AssetPathEntity> onDevice, [
|
|
|
|
Set<String>? excludedAssets,
|
|
|
|
]) =>
|
|
|
|
_lock.run(() => _syncLocalAlbumAssetsToDb(onDevice, excludedAssets));
|
2023-03-04 00:38:30 +02:00
|
|
|
|
|
|
|
/// returns all Asset IDs that are not contained in the existing list
|
|
|
|
List<int> sharedAssetsToRemove(
|
|
|
|
List<Asset> deleteCandidates,
|
|
|
|
List<Asset> existing,
|
|
|
|
) {
|
|
|
|
if (deleteCandidates.isEmpty) {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
deleteCandidates.sort(Asset.compareById);
|
|
|
|
existing.sort(Asset.compareById);
|
|
|
|
return _diffAssets(existing, deleteCandidates, compare: Asset.compareById)
|
2023-05-21 03:41:34 +02:00
|
|
|
.$3
|
2023-03-04 00:38:30 +02:00
|
|
|
.map((e) => e.id)
|
|
|
|
.toList();
|
|
|
|
}
|
|
|
|
|
2023-03-27 04:35:52 +02:00
|
|
|
/// Syncs a new asset to the db. Returns `true` if successful
|
|
|
|
Future<bool> syncNewAssetToDb(Asset newAsset) =>
|
|
|
|
_lock.run(() => _syncNewAssetToDb(newAsset));
|
|
|
|
|
2023-03-04 00:38:30 +02:00
|
|
|
// private methods:
|
|
|
|
|
2023-03-27 04:35:52 +02:00
|
|
|
/// Syncs a new asset to the db. Returns `true` if successful
|
2023-06-10 20:13:59 +02:00
|
|
|
Future<bool> _syncNewAssetToDb(Asset a) async {
|
|
|
|
final Asset? inDb =
|
2023-09-28 05:43:55 +02:00
|
|
|
await _db.assets.getByOwnerIdChecksum(a.ownerId, a.checksum);
|
2023-06-10 20:13:59 +02:00
|
|
|
if (inDb != null) {
|
2023-03-27 04:35:52 +02:00
|
|
|
// unify local/remote assets by replacing the
|
|
|
|
// local-only asset in the DB with a local&remote asset
|
2023-06-10 20:13:59 +02:00
|
|
|
a = inDb.updatedCopy(a);
|
2023-03-27 04:35:52 +02:00
|
|
|
}
|
|
|
|
try {
|
2023-06-10 20:13:59 +02:00
|
|
|
await _db.writeTxn(() => a.put(_db));
|
2023-03-27 04:35:52 +02:00
|
|
|
} on IsarError catch (e) {
|
|
|
|
_log.severe("Failed to put new asset into db: $e");
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2023-09-10 14:51:18 +02:00
|
|
|
/// Efficiently syncs assets via changes. Returns `null` when a full sync is required.
|
|
|
|
Future<bool?> _syncRemoteAssetChanges(
|
2023-05-25 05:52:43 +02:00
|
|
|
User user,
|
2023-09-10 14:51:18 +02:00
|
|
|
Future<(List<Asset>? toUpsert, List<String>? toDelete)> Function(
|
|
|
|
User user,
|
|
|
|
DateTime since,
|
|
|
|
) getChangedAssets,
|
2023-03-27 04:35:52 +02:00
|
|
|
) async {
|
2023-09-10 14:51:18 +02:00
|
|
|
final DateTime? since = _db.eTags.getByIdSync(user.id)?.time?.toUtc();
|
|
|
|
if (since == null) return null;
|
|
|
|
final DateTime now = DateTime.now();
|
|
|
|
final (toUpsert, toDelete) = await getChangedAssets(user, since);
|
|
|
|
if (toUpsert == null || toDelete == null) return null;
|
|
|
|
try {
|
|
|
|
if (toDelete.isNotEmpty) {
|
2023-10-16 20:01:38 +02:00
|
|
|
await handleRemoteAssetRemoval(toDelete);
|
2023-09-10 14:51:18 +02:00
|
|
|
}
|
|
|
|
if (toUpsert.isNotEmpty) {
|
|
|
|
final (_, updated) = await _linkWithExistingFromDb(toUpsert);
|
|
|
|
await upsertAssetsWithExif(updated);
|
|
|
|
}
|
|
|
|
if (toUpsert.isNotEmpty || toDelete.isNotEmpty) {
|
|
|
|
await _updateUserAssetsETag(user, now);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
} on IsarError catch (e) {
|
|
|
|
_log.severe("Failed to sync remote assets to db: $e");
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Deletes remote-only assets, updates merged assets to be local-only
|
2023-10-16 20:01:38 +02:00
|
|
|
Future<void> handleRemoteAssetRemoval(List<String> idsToDelete) {
|
2023-09-10 14:51:18 +02:00
|
|
|
return _db.writeTxn(() async {
|
2023-10-25 18:02:59 +02:00
|
|
|
final idsToRemove = await _db.assets
|
|
|
|
.remote(idsToDelete)
|
|
|
|
.filter()
|
|
|
|
.localIdIsNull()
|
|
|
|
.idProperty()
|
|
|
|
.findAll();
|
|
|
|
await _db.assets.deleteAll(idsToRemove);
|
|
|
|
await _db.exifInfos.deleteAll(idsToRemove);
|
2023-09-10 14:51:18 +02:00
|
|
|
final onlyLocal = await _db.assets.remote(idsToDelete).findAll();
|
|
|
|
if (onlyLocal.isNotEmpty) {
|
|
|
|
for (final Asset a in onlyLocal) {
|
|
|
|
a.remoteId = null;
|
2023-10-16 19:26:35 +02:00
|
|
|
a.isTrashed = false;
|
2023-09-10 14:51:18 +02:00
|
|
|
}
|
|
|
|
await _db.assets.putAll(onlyLocal);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Syncs assets by loading and comparing all assets from the server.
|
|
|
|
Future<bool> _syncRemoteAssetsFull(
|
|
|
|
User user,
|
|
|
|
FutureOr<List<Asset>?> Function(User user) loadAssets,
|
|
|
|
) async {
|
2023-11-06 19:40:43 +02:00
|
|
|
final DateTime now = DateTime.now().toUtc();
|
2023-09-10 14:51:18 +02:00
|
|
|
final List<Asset>? remote = await loadAssets(user);
|
2023-03-27 04:35:52 +02:00
|
|
|
if (remote == null) {
|
|
|
|
return false;
|
|
|
|
}
|
2023-03-04 00:38:30 +02:00
|
|
|
final List<Asset> inDb = await _db.assets
|
2023-09-28 05:43:55 +02:00
|
|
|
.where()
|
|
|
|
.ownerIdEqualToAnyChecksum(user.isarId)
|
2023-06-10 20:13:59 +02:00
|
|
|
.sortByChecksum()
|
2023-03-04 00:38:30 +02:00
|
|
|
.findAll();
|
2023-06-10 20:13:59 +02:00
|
|
|
assert(inDb.isSorted(Asset.compareByChecksum), "inDb not sorted!");
|
|
|
|
|
|
|
|
remote.sort(Asset.compareByChecksum);
|
2023-11-06 19:40:43 +02:00
|
|
|
|
|
|
|
// filter our duplicates that might be introduced by the chunked retrieval
|
|
|
|
remote.uniqueConsecutive(compare: Asset.compareByChecksum);
|
|
|
|
|
2023-05-21 03:41:34 +02:00
|
|
|
final (toAdd, toUpdate, toRemove) = _diffAssets(remote, inDb, remote: true);
|
|
|
|
if (toAdd.isEmpty && toUpdate.isEmpty && toRemove.isEmpty) {
|
2023-09-10 14:51:18 +02:00
|
|
|
await _updateUserAssetsETag(user, now);
|
2023-03-04 00:38:30 +02:00
|
|
|
return false;
|
|
|
|
}
|
2023-05-21 03:41:34 +02:00
|
|
|
final idsToDelete = toRemove.map((e) => e.id).toList();
|
2023-03-04 00:38:30 +02:00
|
|
|
try {
|
|
|
|
await _db.writeTxn(() => _db.assets.deleteAll(idsToDelete));
|
2023-05-21 03:41:34 +02:00
|
|
|
await upsertAssetsWithExif(toAdd + toUpdate);
|
2023-03-04 00:38:30 +02:00
|
|
|
} on IsarError catch (e) {
|
2023-03-27 04:35:52 +02:00
|
|
|
_log.severe("Failed to sync remote assets to db: $e");
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
2023-09-10 14:51:18 +02:00
|
|
|
await _updateUserAssetsETag(user, now);
|
2023-03-04 00:38:30 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2023-09-10 14:51:18 +02:00
|
|
|
Future<void> _updateUserAssetsETag(User user, DateTime time) =>
|
|
|
|
_db.writeTxn(() => _db.eTags.put(ETag(id: user.id, time: time)));
|
|
|
|
|
2023-03-04 00:38:30 +02:00
|
|
|
/// Syncs remote albums to the database
|
|
|
|
/// returns `true` if there were any changes
|
|
|
|
Future<bool> _syncRemoteAlbumsToDb(
|
|
|
|
List<AlbumResponseDto> remote,
|
|
|
|
bool isShared,
|
|
|
|
FutureOr<AlbumResponseDto> Function(AlbumResponseDto) loadDetails,
|
|
|
|
) async {
|
|
|
|
remote.sortBy((e) => e.id);
|
|
|
|
|
|
|
|
final baseQuery = _db.albums.where().remoteIdIsNotNull().filter();
|
|
|
|
final QueryBuilder<Album, Album, QAfterFilterCondition> query;
|
|
|
|
if (isShared) {
|
|
|
|
query = baseQuery.sharedEqualTo(true);
|
|
|
|
} else {
|
|
|
|
final User me = Store.get(StoreKey.currentUser);
|
|
|
|
query = baseQuery.owner((q) => q.isarIdEqualTo(me.isarId));
|
|
|
|
}
|
|
|
|
final List<Album> dbAlbums = await query.sortByRemoteId().findAll();
|
2023-06-10 20:13:59 +02:00
|
|
|
assert(dbAlbums.isSortedBy((e) => e.remoteId!), "dbAlbums not sorted!");
|
2023-03-04 00:38:30 +02:00
|
|
|
|
|
|
|
final List<Asset> toDelete = [];
|
|
|
|
final List<Asset> existing = [];
|
|
|
|
|
|
|
|
final bool changes = await diffSortedLists(
|
|
|
|
remote,
|
|
|
|
dbAlbums,
|
|
|
|
compare: (AlbumResponseDto a, Album b) => a.id.compareTo(b.remoteId!),
|
|
|
|
both: (AlbumResponseDto a, Album b) =>
|
|
|
|
_syncRemoteAlbum(a, b, toDelete, existing, loadDetails),
|
|
|
|
onlyFirst: (AlbumResponseDto a) =>
|
|
|
|
_addAlbumFromServer(a, existing, loadDetails),
|
|
|
|
onlySecond: (Album a) => _removeAlbumFromDb(a, toDelete),
|
|
|
|
);
|
|
|
|
|
|
|
|
if (isShared && toDelete.isNotEmpty) {
|
|
|
|
final List<int> idsToRemove = sharedAssetsToRemove(toDelete, existing);
|
|
|
|
if (idsToRemove.isNotEmpty) {
|
2023-03-20 00:05:18 +02:00
|
|
|
await _db.writeTxn(() async {
|
|
|
|
await _db.assets.deleteAll(idsToRemove);
|
|
|
|
await _db.exifInfos.deleteAll(idsToRemove);
|
|
|
|
});
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
assert(toDelete.isEmpty);
|
|
|
|
}
|
|
|
|
return changes;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// syncs albums from the server to the local database (does not support
|
|
|
|
/// syncing changes from local back to server)
|
|
|
|
/// accumulates
|
|
|
|
Future<bool> _syncRemoteAlbum(
|
|
|
|
AlbumResponseDto dto,
|
|
|
|
Album album,
|
|
|
|
List<Asset> deleteCandidates,
|
|
|
|
List<Asset> existing,
|
|
|
|
FutureOr<AlbumResponseDto> Function(AlbumResponseDto) loadDetails,
|
|
|
|
) async {
|
|
|
|
if (!_hasAlbumResponseDtoChanged(dto, album)) {
|
|
|
|
return false;
|
|
|
|
}
|
2023-10-12 20:18:54 +02:00
|
|
|
// loadDetails (/api/album/:id) will not include lastModifiedAssetTimestamp,
|
|
|
|
// i.e. it will always be null. Save it here.
|
|
|
|
final originalDto = dto;
|
2023-03-04 00:38:30 +02:00
|
|
|
dto = await loadDetails(dto);
|
|
|
|
if (dto.assetCount != dto.assets.length) {
|
|
|
|
return false;
|
|
|
|
}
|
2023-06-10 20:13:59 +02:00
|
|
|
final assetsInDb =
|
|
|
|
await album.assets.filter().sortByOwnerId().thenByChecksum().findAll();
|
|
|
|
assert(assetsInDb.isSorted(Asset.compareByOwnerChecksum), "inDb unsorted!");
|
2023-03-04 00:38:30 +02:00
|
|
|
final List<Asset> assetsOnRemote = dto.getAssets();
|
2023-06-10 20:13:59 +02:00
|
|
|
assetsOnRemote.sort(Asset.compareByOwnerChecksum);
|
|
|
|
final (toAdd, toUpdate, toUnlink) = _diffAssets(
|
|
|
|
assetsOnRemote,
|
|
|
|
assetsInDb,
|
|
|
|
compare: Asset.compareByOwnerChecksum,
|
|
|
|
);
|
2023-03-04 00:38:30 +02:00
|
|
|
|
|
|
|
// update shared users
|
|
|
|
final List<User> sharedUsers = album.sharedUsers.toList(growable: false);
|
|
|
|
sharedUsers.sort((a, b) => a.id.compareTo(b.id));
|
|
|
|
dto.sharedUsers.sort((a, b) => a.id.compareTo(b.id));
|
|
|
|
final List<String> userIdsToAdd = [];
|
|
|
|
final List<User> usersToUnlink = [];
|
|
|
|
diffSortedListsSync(
|
|
|
|
dto.sharedUsers,
|
|
|
|
sharedUsers,
|
|
|
|
compare: (UserResponseDto a, User b) => a.id.compareTo(b.id),
|
|
|
|
both: (a, b) => false,
|
|
|
|
onlyFirst: (UserResponseDto a) => userIdsToAdd.add(a.id),
|
|
|
|
onlySecond: (User a) => usersToUnlink.add(a),
|
|
|
|
);
|
|
|
|
|
|
|
|
// for shared album: put missing album assets into local DB
|
2023-05-21 03:41:34 +02:00
|
|
|
final (existingInDb, updated) = await _linkWithExistingFromDb(toAdd);
|
|
|
|
await upsertAssetsWithExif(updated);
|
|
|
|
final assetsToLink = existingInDb + updated;
|
2023-03-04 00:38:30 +02:00
|
|
|
final usersToLink = (await _db.users.getAllById(userIdsToAdd)).cast<User>();
|
|
|
|
|
|
|
|
album.name = dto.albumName;
|
|
|
|
album.shared = dto.shared;
|
2023-05-30 15:15:56 +02:00
|
|
|
album.modifiedAt = dto.updatedAt;
|
2023-10-12 20:18:54 +02:00
|
|
|
album.lastModifiedAssetTimestamp = originalDto.lastModifiedAssetTimestamp;
|
2023-03-04 00:38:30 +02:00
|
|
|
if (album.thumbnail.value?.remoteId != dto.albumThumbnailAssetId) {
|
|
|
|
album.thumbnail.value = await _db.assets
|
|
|
|
.where()
|
|
|
|
.remoteIdEqualTo(dto.albumThumbnailAssetId)
|
|
|
|
.findFirst();
|
|
|
|
}
|
|
|
|
|
|
|
|
// write & commit all changes to DB
|
|
|
|
try {
|
|
|
|
await _db.writeTxn(() async {
|
|
|
|
await _db.assets.putAll(toUpdate);
|
|
|
|
await album.thumbnail.save();
|
|
|
|
await album.sharedUsers
|
|
|
|
.update(link: usersToLink, unlink: usersToUnlink);
|
|
|
|
await album.assets.update(link: assetsToLink, unlink: toUnlink.cast());
|
|
|
|
await _db.albums.put(album);
|
|
|
|
});
|
2023-06-10 20:13:59 +02:00
|
|
|
_log.info("Synced changes of remote album ${album.name} to DB");
|
2023-03-04 00:38:30 +02:00
|
|
|
} on IsarError catch (e) {
|
2023-03-27 04:35:52 +02:00
|
|
|
_log.severe("Failed to sync remote album to database $e");
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if (album.shared || dto.shared) {
|
2023-03-23 03:36:44 +02:00
|
|
|
final userId = Store.get(StoreKey.currentUser).isarId;
|
2023-03-04 00:38:30 +02:00
|
|
|
final foreign =
|
|
|
|
await album.assets.filter().not().ownerIdEqualTo(userId).findAll();
|
|
|
|
existing.addAll(foreign);
|
|
|
|
|
|
|
|
// delete assets in DB unless they belong to this user or part of some other shared album
|
|
|
|
deleteCandidates.addAll(toUnlink.where((a) => a.ownerId != userId));
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Adds a remote album to the database while making sure to add any foreign
|
|
|
|
/// (shared) assets to the database beforehand
|
|
|
|
/// accumulates assets already existing in the database
|
|
|
|
Future<void> _addAlbumFromServer(
|
|
|
|
AlbumResponseDto dto,
|
|
|
|
List<Asset> existing,
|
|
|
|
FutureOr<AlbumResponseDto> Function(AlbumResponseDto) loadDetails,
|
|
|
|
) async {
|
|
|
|
if (dto.assetCount != dto.assets.length) {
|
|
|
|
dto = await loadDetails(dto);
|
|
|
|
}
|
|
|
|
if (dto.assetCount == dto.assets.length) {
|
|
|
|
// in case an album contains assets not yet present in local DB:
|
|
|
|
// put missing album assets into local DB
|
2023-05-21 03:41:34 +02:00
|
|
|
final (existingInDb, updated) =
|
|
|
|
await _linkWithExistingFromDb(dto.getAssets());
|
|
|
|
existing.addAll(existingInDb);
|
|
|
|
await upsertAssetsWithExif(updated);
|
2023-03-04 00:38:30 +02:00
|
|
|
|
|
|
|
final Album a = await Album.remote(dto);
|
|
|
|
await _db.writeTxn(() => _db.albums.store(a));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Accumulates all suitable album assets to the `deleteCandidates` and
|
|
|
|
/// removes the album from the database.
|
|
|
|
Future<void> _removeAlbumFromDb(
|
|
|
|
Album album,
|
|
|
|
List<Asset> deleteCandidates,
|
|
|
|
) async {
|
|
|
|
if (album.isLocal) {
|
2023-03-20 00:05:18 +02:00
|
|
|
_log.info("Removing local album $album from DB");
|
2023-03-04 00:38:30 +02:00
|
|
|
// delete assets in DB unless they are remote or part of some other album
|
|
|
|
deleteCandidates.addAll(
|
|
|
|
await album.assets.filter().remoteIdIsNull().findAll(),
|
|
|
|
);
|
|
|
|
} else if (album.shared) {
|
|
|
|
final User user = Store.get(StoreKey.currentUser);
|
2023-05-25 05:52:43 +02:00
|
|
|
// delete assets in DB unless they belong to this user or are part of some other shared album or belong to a partner
|
|
|
|
final userIds = await _db.users
|
|
|
|
.filter()
|
|
|
|
.isPartnerSharedWithEqualTo(true)
|
|
|
|
.isarIdProperty()
|
|
|
|
.findAll();
|
|
|
|
userIds.add(user.isarId);
|
|
|
|
final orphanedAssets = await album.assets
|
|
|
|
.filter()
|
|
|
|
.not()
|
|
|
|
.anyOf(userIds, (q, int id) => q.ownerIdEqualTo(id))
|
|
|
|
.findAll();
|
|
|
|
deleteCandidates.addAll(orphanedAssets);
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
2023-03-20 00:05:18 +02:00
|
|
|
try {
|
|
|
|
final bool ok = await _db.writeTxn(() => _db.albums.delete(album.id));
|
|
|
|
assert(ok);
|
|
|
|
_log.info("Removed local album $album from DB");
|
|
|
|
} catch (e) {
|
2023-03-27 04:35:52 +02:00
|
|
|
_log.severe("Failed to remove local album $album from DB");
|
2023-03-20 00:05:18 +02:00
|
|
|
}
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Syncs all device albums and their assets to the database
|
|
|
|
/// Returns `true` if there were any changes
|
2023-03-20 00:05:18 +02:00
|
|
|
Future<bool> _syncLocalAlbumAssetsToDb(
|
|
|
|
List<AssetPathEntity> onDevice, [
|
|
|
|
Set<String>? excludedAssets,
|
|
|
|
]) async {
|
2023-03-04 00:38:30 +02:00
|
|
|
onDevice.sort((a, b) => a.id.compareTo(b.id));
|
2023-06-10 20:13:59 +02:00
|
|
|
final inDb =
|
2023-03-04 00:38:30 +02:00
|
|
|
await _db.albums.where().localIdIsNotNull().sortByLocalId().findAll();
|
|
|
|
final List<Asset> deleteCandidates = [];
|
|
|
|
final List<Asset> existing = [];
|
2023-06-10 20:13:59 +02:00
|
|
|
assert(inDb.isSorted((a, b) => a.localId!.compareTo(b.localId!)), "sort!");
|
2023-03-04 00:38:30 +02:00
|
|
|
final bool anyChanges = await diffSortedLists(
|
|
|
|
onDevice,
|
|
|
|
inDb,
|
|
|
|
compare: (AssetPathEntity a, Album b) => a.id.compareTo(b.localId!),
|
2023-03-20 00:05:18 +02:00
|
|
|
both: (AssetPathEntity ape, Album album) => _syncAlbumInDbAndOnDevice(
|
|
|
|
ape,
|
|
|
|
album,
|
|
|
|
deleteCandidates,
|
|
|
|
existing,
|
|
|
|
excludedAssets,
|
|
|
|
),
|
|
|
|
onlyFirst: (AssetPathEntity ape) =>
|
|
|
|
_addAlbumFromDevice(ape, existing, excludedAssets),
|
2023-03-04 00:38:30 +02:00
|
|
|
onlySecond: (Album a) => _removeAlbumFromDb(a, deleteCandidates),
|
|
|
|
);
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.fine(
|
|
|
|
"Syncing all local albums almost done. Collected ${deleteCandidates.length} asset candidates to delete",
|
|
|
|
);
|
2023-05-21 03:41:34 +02:00
|
|
|
final (toDelete, toUpdate) =
|
|
|
|
_handleAssetRemoval(deleteCandidates, existing, remote: false);
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.fine(
|
2023-05-21 03:41:34 +02:00
|
|
|
"${toDelete.length} assets to delete, ${toUpdate.length} to update",
|
2023-04-14 15:50:46 +02:00
|
|
|
);
|
2023-05-21 03:41:34 +02:00
|
|
|
if (toDelete.isNotEmpty || toUpdate.isNotEmpty) {
|
2023-03-04 00:38:30 +02:00
|
|
|
await _db.writeTxn(() async {
|
2023-05-21 03:41:34 +02:00
|
|
|
await _db.assets.deleteAll(toDelete);
|
|
|
|
await _db.exifInfos.deleteAll(toDelete);
|
|
|
|
await _db.assets.putAll(toUpdate);
|
2023-03-04 00:38:30 +02:00
|
|
|
});
|
2023-03-20 00:05:18 +02:00
|
|
|
_log.info(
|
2023-05-21 03:41:34 +02:00
|
|
|
"Removed ${toDelete.length} and updated ${toUpdate.length} local assets from DB",
|
2023-03-20 00:05:18 +02:00
|
|
|
);
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
|
|
|
return anyChanges;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Syncs the device album to the album in the database
|
|
|
|
/// returns `true` if there were any changes
|
|
|
|
/// Accumulates asset candidates to delete and those already existing in DB
|
|
|
|
Future<bool> _syncAlbumInDbAndOnDevice(
|
|
|
|
AssetPathEntity ape,
|
|
|
|
Album album,
|
|
|
|
List<Asset> deleteCandidates,
|
|
|
|
List<Asset> existing, [
|
2023-03-20 00:05:18 +02:00
|
|
|
Set<String>? excludedAssets,
|
2023-03-04 00:38:30 +02:00
|
|
|
bool forceRefresh = false,
|
|
|
|
]) async {
|
|
|
|
if (!forceRefresh && !await _hasAssetPathEntityChanged(ape, album)) {
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.fine("Local album ${ape.name} has not changed. Skipping sync.");
|
2023-03-04 00:38:30 +02:00
|
|
|
return false;
|
|
|
|
}
|
2023-03-20 00:05:18 +02:00
|
|
|
if (!forceRefresh &&
|
|
|
|
excludedAssets == null &&
|
|
|
|
await _syncDeviceAlbumFast(ape, album)) {
|
2023-03-04 00:38:30 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2023-03-20 00:05:18 +02:00
|
|
|
// general case, e.g. some assets have been deleted or there are excluded albums on iOS
|
2023-03-27 04:35:52 +02:00
|
|
|
final inDb = await album.assets
|
|
|
|
.filter()
|
|
|
|
.ownerIdEqualTo(Store.get(StoreKey.currentUser).isarId)
|
2023-06-10 20:13:59 +02:00
|
|
|
.sortByChecksum()
|
2023-03-27 04:35:52 +02:00
|
|
|
.findAll();
|
2023-06-10 20:13:59 +02:00
|
|
|
assert(inDb.isSorted(Asset.compareByChecksum), "inDb not sorted!");
|
|
|
|
final int assetCountOnDevice = await ape.assetCountAsync;
|
2023-03-20 00:05:18 +02:00
|
|
|
final List<Asset> onDevice =
|
2023-06-10 20:13:59 +02:00
|
|
|
await _hashService.getHashedAssets(ape, excludedAssets: excludedAssets);
|
|
|
|
_removeDuplicates(onDevice);
|
|
|
|
// _removeDuplicates sorts `onDevice` by checksum
|
|
|
|
final (toAdd, toUpdate, toDelete) = _diffAssets(onDevice, inDb);
|
2023-03-20 00:05:18 +02:00
|
|
|
if (toAdd.isEmpty &&
|
|
|
|
toUpdate.isEmpty &&
|
|
|
|
toDelete.isEmpty &&
|
|
|
|
album.name == ape.name &&
|
2023-04-14 16:14:14 +02:00
|
|
|
ape.lastModified != null &&
|
|
|
|
album.modifiedAt.isAtSameMomentAs(ape.lastModified!)) {
|
2023-03-20 00:05:18 +02:00
|
|
|
// changes only affeted excluded albums
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.fine(
|
|
|
|
"Only excluded assets in local album ${ape.name} changed. Stopping sync.",
|
|
|
|
);
|
2023-09-10 14:51:18 +02:00
|
|
|
if (assetCountOnDevice !=
|
|
|
|
_db.eTags.getByIdSync(ape.eTagKeyAssetCount)?.assetCount) {
|
|
|
|
await _db.writeTxn(
|
|
|
|
() => _db.eTags.put(
|
|
|
|
ETag(id: ape.eTagKeyAssetCount, assetCount: assetCountOnDevice),
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
2023-03-20 00:05:18 +02:00
|
|
|
return false;
|
|
|
|
}
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.fine(
|
|
|
|
"Syncing local album ${ape.name}. ${toAdd.length} assets to add, ${toUpdate.length} to update, ${toDelete.length} to delete",
|
|
|
|
);
|
2023-05-21 03:41:34 +02:00
|
|
|
final (existingInDb, updated) = await _linkWithExistingFromDb(toAdd);
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.fine(
|
2023-05-21 03:41:34 +02:00
|
|
|
"Linking assets to add with existing from db. ${existingInDb.length} existing, ${updated.length} to update",
|
2023-04-14 15:50:46 +02:00
|
|
|
);
|
2023-03-04 00:38:30 +02:00
|
|
|
deleteCandidates.addAll(toDelete);
|
2023-05-21 03:41:34 +02:00
|
|
|
existing.addAll(existingInDb);
|
2023-03-04 00:38:30 +02:00
|
|
|
album.name = ape.name;
|
2023-04-08 04:21:29 +02:00
|
|
|
album.modifiedAt = ape.lastModified ?? DateTime.now();
|
2023-03-04 00:38:30 +02:00
|
|
|
if (album.thumbnail.value != null &&
|
|
|
|
toDelete.contains(album.thumbnail.value)) {
|
|
|
|
album.thumbnail.value = null;
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
await _db.writeTxn(() async {
|
2023-05-21 03:41:34 +02:00
|
|
|
await _db.assets.putAll(updated);
|
2023-03-04 00:38:30 +02:00
|
|
|
await _db.assets.putAll(toUpdate);
|
|
|
|
await album.assets
|
2023-05-21 03:41:34 +02:00
|
|
|
.update(link: existingInDb + updated, unlink: toDelete);
|
2023-03-04 00:38:30 +02:00
|
|
|
await _db.albums.put(album);
|
|
|
|
album.thumbnail.value ??= await album.assets.filter().findFirst();
|
|
|
|
await album.thumbnail.save();
|
2023-06-10 20:13:59 +02:00
|
|
|
await _db.eTags.put(
|
2023-09-10 14:51:18 +02:00
|
|
|
ETag(id: ape.eTagKeyAssetCount, assetCount: assetCountOnDevice),
|
2023-06-10 20:13:59 +02:00
|
|
|
);
|
2023-03-04 00:38:30 +02:00
|
|
|
});
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.info("Synced changes of local album ${ape.name} to DB");
|
2023-03-04 00:38:30 +02:00
|
|
|
} on IsarError catch (e) {
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.severe("Failed to update synced album ${ape.name} in DB: $e");
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// fast path for common case: only new assets were added to device album
|
|
|
|
/// returns `true` if successfull, else `false`
|
|
|
|
Future<bool> _syncDeviceAlbumFast(AssetPathEntity ape, Album album) async {
|
2023-06-10 20:13:59 +02:00
|
|
|
if (!(ape.lastModified ?? DateTime.now()).isAfter(album.modifiedAt)) {
|
|
|
|
return false;
|
|
|
|
}
|
2023-03-04 00:38:30 +02:00
|
|
|
final int totalOnDevice = await ape.assetCountAsync;
|
2023-06-10 20:13:59 +02:00
|
|
|
final int lastKnownTotal =
|
2023-09-10 14:51:18 +02:00
|
|
|
(await _db.eTags.getById(ape.eTagKeyAssetCount))?.assetCount ?? 0;
|
2023-06-10 20:13:59 +02:00
|
|
|
final AssetPathEntity? modified = totalOnDevice > lastKnownTotal
|
2023-03-04 00:38:30 +02:00
|
|
|
? await ape.fetchPathProperties(
|
|
|
|
filterOptionGroup: FilterOptionGroup(
|
|
|
|
updateTimeCond: DateTimeCond(
|
|
|
|
min: album.modifiedAt.add(const Duration(seconds: 1)),
|
2023-04-14 16:14:14 +02:00
|
|
|
max: ape.lastModified ?? DateTime.now(),
|
2023-03-04 00:38:30 +02:00
|
|
|
),
|
|
|
|
),
|
|
|
|
)
|
|
|
|
: null;
|
|
|
|
if (modified == null) {
|
|
|
|
return false;
|
|
|
|
}
|
2023-06-10 20:13:59 +02:00
|
|
|
final List<Asset> newAssets = await _hashService.getHashedAssets(modified);
|
|
|
|
|
|
|
|
if (totalOnDevice != lastKnownTotal + newAssets.length) {
|
2023-03-04 00:38:30 +02:00
|
|
|
return false;
|
|
|
|
}
|
2023-04-14 16:14:14 +02:00
|
|
|
album.modifiedAt = ape.lastModified ?? DateTime.now();
|
2023-06-10 20:13:59 +02:00
|
|
|
_removeDuplicates(newAssets);
|
2023-05-21 03:41:34 +02:00
|
|
|
final (existingInDb, updated) = await _linkWithExistingFromDb(newAssets);
|
2023-03-04 00:38:30 +02:00
|
|
|
try {
|
|
|
|
await _db.writeTxn(() async {
|
2023-05-21 03:41:34 +02:00
|
|
|
await _db.assets.putAll(updated);
|
|
|
|
await album.assets.update(link: existingInDb + updated);
|
2023-03-04 00:38:30 +02:00
|
|
|
await _db.albums.put(album);
|
2023-09-10 14:51:18 +02:00
|
|
|
await _db.eTags
|
|
|
|
.put(ETag(id: ape.eTagKeyAssetCount, assetCount: totalOnDevice));
|
2023-03-04 00:38:30 +02:00
|
|
|
});
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.info("Fast synced local album ${ape.name} to DB");
|
2023-03-04 00:38:30 +02:00
|
|
|
} on IsarError catch (e) {
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.severe("Failed to fast sync local album ${ape.name} to DB: $e");
|
2023-03-20 00:05:18 +02:00
|
|
|
return false;
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Adds a new album from the device to the database and Accumulates all
|
|
|
|
/// assets already existing in the database to the list of `existing` assets
|
|
|
|
Future<void> _addAlbumFromDevice(
|
|
|
|
AssetPathEntity ape,
|
2023-03-20 00:05:18 +02:00
|
|
|
List<Asset> existing, [
|
|
|
|
Set<String>? excludedAssets,
|
|
|
|
]) async {
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.info("Syncing a new local album to DB: ${ape.name}");
|
2023-03-04 00:38:30 +02:00
|
|
|
final Album a = Album.local(ape);
|
2023-06-10 20:13:59 +02:00
|
|
|
final assets =
|
|
|
|
await _hashService.getHashedAssets(ape, excludedAssets: excludedAssets);
|
|
|
|
_removeDuplicates(assets);
|
2023-05-21 03:41:34 +02:00
|
|
|
final (existingInDb, updated) = await _linkWithExistingFromDb(assets);
|
2023-03-20 00:05:18 +02:00
|
|
|
_log.info(
|
2023-05-21 03:41:34 +02:00
|
|
|
"${existingInDb.length} assets already existed in DB, to upsert ${updated.length}",
|
2023-03-20 00:05:18 +02:00
|
|
|
);
|
2023-05-21 03:41:34 +02:00
|
|
|
await upsertAssetsWithExif(updated);
|
|
|
|
existing.addAll(existingInDb);
|
|
|
|
a.assets.addAll(existingInDb);
|
|
|
|
a.assets.addAll(updated);
|
|
|
|
final thumb = existingInDb.firstOrNull ?? updated.firstOrNull;
|
2023-03-04 00:38:30 +02:00
|
|
|
a.thumbnail.value = thumb;
|
|
|
|
try {
|
|
|
|
await _db.writeTxn(() => _db.albums.store(a));
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.info("Added a new local album to DB: ${ape.name}");
|
2023-03-04 00:38:30 +02:00
|
|
|
} on IsarError catch (e) {
|
2023-04-14 15:50:46 +02:00
|
|
|
_log.severe("Failed to add new local album ${ape.name} to DB: $e");
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a tuple (existing, updated)
|
2023-05-21 03:41:34 +02:00
|
|
|
Future<(List<Asset> existing, List<Asset> updated)> _linkWithExistingFromDb(
|
2023-03-04 00:38:30 +02:00
|
|
|
List<Asset> assets,
|
|
|
|
) async {
|
2023-06-10 20:13:59 +02:00
|
|
|
if (assets.isEmpty) return ([].cast<Asset>(), [].cast<Asset>());
|
|
|
|
|
2023-09-28 05:43:55 +02:00
|
|
|
final List<Asset?> inDb = await _db.assets.getAllByOwnerIdChecksum(
|
2023-06-10 20:13:59 +02:00
|
|
|
assets.map((a) => a.ownerId).toInt64List(),
|
2023-09-28 05:43:55 +02:00
|
|
|
assets.map((a) => a.checksum).toList(growable: false),
|
2023-03-04 00:38:30 +02:00
|
|
|
);
|
2023-06-10 20:13:59 +02:00
|
|
|
assert(inDb.length == assets.length);
|
|
|
|
final List<Asset> existing = [], toUpsert = [];
|
|
|
|
for (int i = 0; i < assets.length; i++) {
|
|
|
|
final Asset? b = inDb[i];
|
|
|
|
if (b == null) {
|
|
|
|
toUpsert.add(assets[i]);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (b.canUpdate(assets[i])) {
|
|
|
|
final updated = b.updatedCopy(assets[i]);
|
|
|
|
assert(updated.id != Isar.autoIncrement);
|
|
|
|
toUpsert.add(updated);
|
|
|
|
} else {
|
|
|
|
existing.add(b);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
assert(existing.length + toUpsert.length == assets.length);
|
2023-05-21 03:41:34 +02:00
|
|
|
return (existing, toUpsert);
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Inserts or updates the assets in the database with their ExifInfo (if any)
|
2023-05-17 19:36:02 +02:00
|
|
|
Future<void> upsertAssetsWithExif(List<Asset> assets) async {
|
2023-03-04 00:38:30 +02:00
|
|
|
if (assets.isEmpty) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
final exifInfos = assets.map((e) => e.exifInfo).whereNotNull().toList();
|
|
|
|
try {
|
|
|
|
await _db.writeTxn(() async {
|
|
|
|
await _db.assets.putAll(assets);
|
|
|
|
for (final Asset added in assets) {
|
|
|
|
added.exifInfo?.id = added.id;
|
|
|
|
}
|
|
|
|
await _db.exifInfos.putAll(exifInfos);
|
|
|
|
});
|
2023-03-20 00:05:18 +02:00
|
|
|
_log.info("Upserted ${assets.length} assets into the DB");
|
2023-03-04 00:38:30 +02:00
|
|
|
} on IsarError catch (e) {
|
2023-06-10 20:13:59 +02:00
|
|
|
_log.severe(
|
2023-03-20 00:05:18 +02:00
|
|
|
"Failed to upsert ${assets.length} assets into the DB: ${e.toString()}",
|
|
|
|
);
|
2023-06-10 20:13:59 +02:00
|
|
|
// give details on the errors
|
|
|
|
assets.sort(Asset.compareByOwnerChecksum);
|
2023-09-28 05:43:55 +02:00
|
|
|
final inDb = await _db.assets.getAllByOwnerIdChecksum(
|
2023-06-10 20:13:59 +02:00
|
|
|
assets.map((e) => e.ownerId).toInt64List(),
|
2023-09-28 05:43:55 +02:00
|
|
|
assets.map((e) => e.checksum).toList(growable: false),
|
2023-06-10 20:13:59 +02:00
|
|
|
);
|
|
|
|
for (int i = 0; i < assets.length; i++) {
|
|
|
|
final Asset a = assets[i];
|
|
|
|
final Asset? b = inDb[i];
|
|
|
|
if (b == null) {
|
|
|
|
if (a.id != Isar.autoIncrement) {
|
|
|
|
_log.warning(
|
|
|
|
"Trying to update an asset that does not exist in DB:\n$a",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
} else if (a.id != b.id) {
|
|
|
|
_log.warning(
|
|
|
|
"Trying to insert another asset with the same checksum+owner. In DB:\n$b\nTo insert:\n$a",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for (int i = 1; i < assets.length; i++) {
|
|
|
|
if (Asset.compareByOwnerChecksum(assets[i - 1], assets[i]) == 0) {
|
|
|
|
_log.warning(
|
|
|
|
"Trying to insert duplicate assets:\n${assets[i - 1]}\n${assets[i]}",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
List<Asset> _removeDuplicates(List<Asset> assets) {
|
|
|
|
final int before = assets.length;
|
|
|
|
assets.sort(Asset.compareByOwnerChecksumCreatedModified);
|
|
|
|
assets.uniqueConsecutive(
|
|
|
|
compare: Asset.compareByOwnerChecksum,
|
|
|
|
onDuplicate: (a, b) =>
|
|
|
|
_log.info("Ignoring duplicate assets on device:\n$a\n$b"),
|
|
|
|
);
|
|
|
|
final int duplicates = before - assets.length;
|
|
|
|
if (duplicates > 0) {
|
|
|
|
_log.warning("Ignored $duplicates duplicate assets on device");
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
2023-06-10 20:13:59 +02:00
|
|
|
return assets;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// returns `true` if the albums differ on the surface
|
|
|
|
Future<bool> _hasAssetPathEntityChanged(AssetPathEntity a, Album b) async {
|
|
|
|
return a.name != b.name ||
|
|
|
|
a.lastModified == null ||
|
|
|
|
!a.lastModified!.isAtSameMomentAs(b.modifiedAt) ||
|
|
|
|
await a.assetCountAsync !=
|
2023-09-10 14:51:18 +02:00
|
|
|
(await _db.eTags.getById(a.eTagKeyAssetCount))?.assetCount;
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a triple(toAdd, toUpdate, toRemove)
|
2023-05-21 03:41:34 +02:00
|
|
|
(List<Asset> toAdd, List<Asset> toUpdate, List<Asset> toRemove) _diffAssets(
|
2023-03-04 00:38:30 +02:00
|
|
|
List<Asset> assets,
|
|
|
|
List<Asset> inDb, {
|
|
|
|
bool? remote,
|
2023-06-10 20:13:59 +02:00
|
|
|
int Function(Asset, Asset) compare = Asset.compareByChecksum,
|
2023-03-04 00:38:30 +02:00
|
|
|
}) {
|
|
|
|
final List<Asset> toAdd = [];
|
|
|
|
final List<Asset> toUpdate = [];
|
|
|
|
final List<Asset> toRemove = [];
|
2023-11-06 19:40:43 +02:00
|
|
|
if (assets.isEmpty || inDb.isEmpty) {
|
|
|
|
// fast path for trivial cases: halfes memory usage during initial sync
|
|
|
|
return assets.isEmpty
|
|
|
|
? (toAdd, toUpdate, inDb) // remove all from DB
|
|
|
|
: (assets, toUpdate, toRemove); // add all assets
|
|
|
|
}
|
2023-03-04 00:38:30 +02:00
|
|
|
diffSortedListsSync(
|
|
|
|
inDb,
|
|
|
|
assets,
|
|
|
|
compare: compare,
|
|
|
|
both: (Asset a, Asset b) {
|
2023-04-18 11:47:24 +02:00
|
|
|
if (a.canUpdate(b)) {
|
|
|
|
toUpdate.add(a.updatedCopy(b));
|
2023-03-04 00:38:30 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
},
|
|
|
|
onlyFirst: (Asset a) {
|
|
|
|
if (remote == true && a.isLocal) {
|
|
|
|
if (a.remoteId != null) {
|
|
|
|
a.remoteId = null;
|
|
|
|
toUpdate.add(a);
|
|
|
|
}
|
|
|
|
} else if (remote == false && a.isRemote) {
|
|
|
|
if (a.isLocal) {
|
2023-06-10 20:13:59 +02:00
|
|
|
a.localId = null;
|
2023-03-04 00:38:30 +02:00
|
|
|
toUpdate.add(a);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
toRemove.add(a);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
onlySecond: (Asset b) => toAdd.add(b),
|
|
|
|
);
|
2023-05-21 03:41:34 +02:00
|
|
|
return (toAdd, toUpdate, toRemove);
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// returns a tuple (toDelete toUpdate) when assets are to be deleted
|
2023-05-21 03:41:34 +02:00
|
|
|
(List<int> toDelete, List<Asset> toUpdate) _handleAssetRemoval(
|
2023-03-04 00:38:30 +02:00
|
|
|
List<Asset> deleteCandidates,
|
2023-03-27 04:35:52 +02:00
|
|
|
List<Asset> existing, {
|
|
|
|
bool? remote,
|
|
|
|
}) {
|
2023-03-04 00:38:30 +02:00
|
|
|
if (deleteCandidates.isEmpty) {
|
2023-05-21 03:41:34 +02:00
|
|
|
return const ([], []);
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
|
|
|
deleteCandidates.sort(Asset.compareById);
|
2023-06-10 20:13:59 +02:00
|
|
|
deleteCandidates.uniqueConsecutive(compare: Asset.compareById);
|
2023-03-04 00:38:30 +02:00
|
|
|
existing.sort(Asset.compareById);
|
2023-06-10 20:13:59 +02:00
|
|
|
existing.uniqueConsecutive(compare: Asset.compareById);
|
2023-05-21 03:41:34 +02:00
|
|
|
final (tooAdd, toUpdate, toRemove) = _diffAssets(
|
2023-03-27 04:35:52 +02:00
|
|
|
existing,
|
|
|
|
deleteCandidates,
|
|
|
|
compare: Asset.compareById,
|
|
|
|
remote: remote,
|
|
|
|
);
|
2023-05-21 03:41:34 +02:00
|
|
|
assert(tooAdd.isEmpty, "toAdd should be empty in _handleAssetRemoval");
|
|
|
|
return (toRemove.map((e) => e.id).toList(), toUpdate);
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// returns `true` if the albums differ on the surface
|
|
|
|
bool _hasAlbumResponseDtoChanged(AlbumResponseDto dto, Album a) {
|
|
|
|
return dto.assetCount != a.assetCount ||
|
|
|
|
dto.albumName != a.name ||
|
|
|
|
dto.albumThumbnailAssetId != a.thumbnail.value?.remoteId ||
|
|
|
|
dto.shared != a.shared ||
|
2023-03-12 15:43:09 +02:00
|
|
|
dto.sharedUsers.length != a.sharedUsers.length ||
|
2023-10-12 20:18:54 +02:00
|
|
|
!dto.updatedAt.isAtSameMomentAs(a.modifiedAt) ||
|
|
|
|
(dto.lastModifiedAssetTimestamp == null &&
|
|
|
|
a.lastModifiedAssetTimestamp != null) ||
|
|
|
|
(dto.lastModifiedAssetTimestamp != null &&
|
|
|
|
a.lastModifiedAssetTimestamp == null) ||
|
|
|
|
(dto.lastModifiedAssetTimestamp != null &&
|
|
|
|
a.lastModifiedAssetTimestamp != null &&
|
|
|
|
!dto.lastModifiedAssetTimestamp!
|
|
|
|
.isAtSameMomentAs(a.lastModifiedAssetTimestamp!));
|
2023-03-04 00:38:30 +02:00
|
|
|
}
|