2023-03-03 22:38:30 +00:00
|
|
|
import 'dart:async';
|
|
|
|
|
|
|
|
import 'package:collection/collection.dart';
|
|
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
2024-05-01 02:36:40 +00:00
|
|
|
import 'package:immich_mobile/entities/album.entity.dart';
|
|
|
|
import 'package:immich_mobile/entities/asset.entity.dart';
|
|
|
|
import 'package:immich_mobile/entities/etag.entity.dart';
|
|
|
|
import 'package:immich_mobile/entities/user.entity.dart';
|
2024-09-30 14:37:30 +00:00
|
|
|
import 'package:immich_mobile/interfaces/album.interface.dart';
|
2024-09-20 13:32:37 +00:00
|
|
|
import 'package:immich_mobile/interfaces/album_api.interface.dart';
|
2024-09-18 15:15:52 +00:00
|
|
|
import 'package:immich_mobile/interfaces/album_media.interface.dart';
|
2024-09-30 14:37:30 +00:00
|
|
|
import 'package:immich_mobile/interfaces/asset.interface.dart';
|
|
|
|
import 'package:immich_mobile/interfaces/etag.interface.dart';
|
|
|
|
import 'package:immich_mobile/interfaces/exif_info.interface.dart';
|
|
|
|
import 'package:immich_mobile/interfaces/user.interface.dart';
|
|
|
|
import 'package:immich_mobile/repositories/album.repository.dart';
|
2024-09-20 13:32:37 +00:00
|
|
|
import 'package:immich_mobile/repositories/album_api.repository.dart';
|
2024-09-18 15:15:52 +00:00
|
|
|
import 'package:immich_mobile/repositories/album_media.repository.dart';
|
2024-09-30 14:37:30 +00:00
|
|
|
import 'package:immich_mobile/repositories/asset.repository.dart';
|
|
|
|
import 'package:immich_mobile/repositories/etag.repository.dart';
|
|
|
|
import 'package:immich_mobile/repositories/exif_info.repository.dart';
|
|
|
|
import 'package:immich_mobile/repositories/user.repository.dart';
|
2024-09-20 13:32:37 +00:00
|
|
|
import 'package:immich_mobile/services/entity.service.dart';
|
2024-05-02 20:59:14 +00:00
|
|
|
import 'package:immich_mobile/services/hash.service.dart';
|
2023-03-03 22:38:30 +00:00
|
|
|
import 'package:immich_mobile/utils/async_mutex.dart';
|
2023-11-09 16:19:53 +00:00
|
|
|
import 'package:immich_mobile/extensions/collection_extensions.dart';
|
2024-04-02 05:22:15 +00:00
|
|
|
import 'package:immich_mobile/utils/datetime_comparison.dart';
|
2023-03-03 22:38:30 +00:00
|
|
|
import 'package:immich_mobile/utils/diff.dart';
|
2023-03-19 22:05:18 +00:00
|
|
|
import 'package:logging/logging.dart';
|
2023-03-03 22:38:30 +00:00
|
|
|
|
2023-06-10 18:13:59 +00:00
|
|
|
final syncServiceProvider = Provider(
|
2024-09-18 15:15:52 +00:00
|
|
|
(ref) => SyncService(
|
|
|
|
ref.watch(hashServiceProvider),
|
2024-09-20 13:32:37 +00:00
|
|
|
ref.watch(entityServiceProvider),
|
2024-09-18 15:15:52 +00:00
|
|
|
ref.watch(albumMediaRepositoryProvider),
|
2024-09-20 13:32:37 +00:00
|
|
|
ref.watch(albumApiRepositoryProvider),
|
2024-09-30 14:37:30 +00:00
|
|
|
ref.watch(albumRepositoryProvider),
|
|
|
|
ref.watch(assetRepositoryProvider),
|
|
|
|
ref.watch(exifInfoRepositoryProvider),
|
|
|
|
ref.watch(userRepositoryProvider),
|
|
|
|
ref.watch(etagRepositoryProvider),
|
2024-09-18 15:15:52 +00:00
|
|
|
),
|
2023-06-10 18:13:59 +00:00
|
|
|
);
|
2023-03-03 22:38:30 +00:00
|
|
|
|
|
|
|
class SyncService {
|
2023-06-10 18:13:59 +00:00
|
|
|
final HashService _hashService;
|
2024-09-20 13:32:37 +00:00
|
|
|
final EntityService _entityService;
|
2024-09-18 15:15:52 +00:00
|
|
|
final IAlbumMediaRepository _albumMediaRepository;
|
2024-09-20 13:32:37 +00:00
|
|
|
final IAlbumApiRepository _albumApiRepository;
|
2024-09-30 14:37:30 +00:00
|
|
|
final IAlbumRepository _albumRepository;
|
|
|
|
final IAssetRepository _assetRepository;
|
|
|
|
final IExifInfoRepository _exifInfoRepository;
|
|
|
|
final IUserRepository _userRepository;
|
|
|
|
final IETagRepository _eTagRepository;
|
2023-03-03 22:38:30 +00:00
|
|
|
final AsyncMutex _lock = AsyncMutex();
|
2023-03-19 22:05:18 +00:00
|
|
|
final Logger _log = Logger('SyncService');
|
2023-03-03 22:38:30 +00:00
|
|
|
|
2024-09-20 13:32:37 +00:00
|
|
|
SyncService(
|
|
|
|
this._hashService,
|
|
|
|
this._entityService,
|
|
|
|
this._albumMediaRepository,
|
|
|
|
this._albumApiRepository,
|
2024-09-30 14:37:30 +00:00
|
|
|
this._albumRepository,
|
|
|
|
this._assetRepository,
|
|
|
|
this._exifInfoRepository,
|
|
|
|
this._userRepository,
|
|
|
|
this._eTagRepository,
|
2024-09-20 13:32:37 +00:00
|
|
|
);
|
2023-03-03 22:38:30 +00:00
|
|
|
|
|
|
|
// public methods:
|
|
|
|
|
|
|
|
/// Syncs users from the server to the local database
|
|
|
|
/// Returns `true`if there were any changes
|
2023-11-12 16:35:08 +00:00
|
|
|
Future<bool> syncUsersFromServer(List<User> users) =>
|
|
|
|
_lock.run(() => _syncUsersFromServer(users));
|
2023-03-03 22:38:30 +00:00
|
|
|
|
|
|
|
/// Syncs remote assets owned by the logged-in user to the DB
|
|
|
|
/// Returns `true` if there were any changes
|
2024-05-14 15:35:37 +00:00
|
|
|
Future<bool> syncRemoteAssetsToDb({
|
|
|
|
required List<User> users,
|
|
|
|
required Future<(List<Asset>? toUpsert, List<String>? toDelete)> Function(
|
|
|
|
List<User> users,
|
2023-09-10 12:51:18 +00:00
|
|
|
DateTime since,
|
|
|
|
) getChangedAssets,
|
2024-05-14 15:35:37 +00:00
|
|
|
required FutureOr<List<Asset>?> Function(User user, DateTime until)
|
|
|
|
loadAssets,
|
|
|
|
required FutureOr<List<User>?> Function() refreshUsers,
|
|
|
|
}) =>
|
2023-09-10 12:51:18 +00:00
|
|
|
_lock.run(
|
|
|
|
() async =>
|
2024-05-14 15:35:37 +00:00
|
|
|
await _syncRemoteAssetChanges(users, getChangedAssets) ??
|
|
|
|
await _syncRemoteAssetsFull(refreshUsers, loadAssets),
|
2023-09-10 12:51:18 +00:00
|
|
|
);
|
2023-03-03 22:38:30 +00:00
|
|
|
|
|
|
|
/// Syncs remote albums to the database
|
|
|
|
/// returns `true` if there were any changes
|
|
|
|
Future<bool> syncRemoteAlbumsToDb(
|
2024-10-10 08:44:14 +00:00
|
|
|
List<Album> remote,
|
|
|
|
) =>
|
|
|
|
_lock.run(() => _syncRemoteAlbumsToDb(remote));
|
2023-03-03 22:38:30 +00:00
|
|
|
|
|
|
|
/// Syncs all device albums and their assets to the database
|
|
|
|
/// Returns `true` if there were any changes
|
2023-03-19 22:05:18 +00:00
|
|
|
Future<bool> syncLocalAlbumAssetsToDb(
|
2024-09-18 15:15:52 +00:00
|
|
|
List<Album> onDevice, [
|
2024-07-02 19:01:54 +00:00
|
|
|
Set<String>? excludedAssets,
|
|
|
|
]) =>
|
|
|
|
_lock.run(() => _syncLocalAlbumAssetsToDb(onDevice, excludedAssets));
|
2023-03-03 22:38:30 +00: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 01:41:34 +00:00
|
|
|
.$3
|
2023-03-03 22:38:30 +00:00
|
|
|
.map((e) => e.id)
|
|
|
|
.toList();
|
|
|
|
}
|
|
|
|
|
2023-03-27 02:35:52 +00:00
|
|
|
/// Syncs a new asset to the db. Returns `true` if successful
|
|
|
|
Future<bool> syncNewAssetToDb(Asset newAsset) =>
|
|
|
|
_lock.run(() => _syncNewAssetToDb(newAsset));
|
|
|
|
|
2023-11-14 20:30:27 +00:00
|
|
|
Future<bool> removeAllLocalAlbumsAndAssets() =>
|
|
|
|
_lock.run(_removeAllLocalAlbumsAndAssets);
|
|
|
|
|
2023-03-03 22:38:30 +00:00
|
|
|
// private methods:
|
|
|
|
|
2023-11-12 16:35:08 +00:00
|
|
|
/// 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);
|
2024-09-30 14:37:30 +00:00
|
|
|
final dbUsers = await _userRepository.getAll(sortBy: UserSort.id);
|
2023-11-12 16:35:08 +00: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) {
|
|
|
|
if (!a.updatedAt.isAtSameMomentAs(b.updatedAt) ||
|
|
|
|
a.isPartnerSharedBy != b.isPartnerSharedBy ||
|
2024-05-14 15:35:37 +00:00
|
|
|
a.isPartnerSharedWith != b.isPartnerSharedWith ||
|
|
|
|
a.inTimeline != b.inTimeline) {
|
2023-11-12 16:35:08 +00:00
|
|
|
toUpsert.add(a);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
},
|
|
|
|
onlyFirst: (User a) => toUpsert.add(a),
|
|
|
|
onlySecond: (User b) => toDelete.add(b.isarId),
|
|
|
|
);
|
|
|
|
if (changes) {
|
2024-09-30 14:37:30 +00:00
|
|
|
await _userRepository.transaction(() async {
|
|
|
|
await _userRepository.deleteById(toDelete);
|
|
|
|
await _userRepository.upsertAll(toUpsert);
|
2023-11-12 16:35:08 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
return changes;
|
|
|
|
}
|
|
|
|
|
2023-03-27 02:35:52 +00:00
|
|
|
/// Syncs a new asset to the db. Returns `true` if successful
|
2023-06-10 18:13:59 +00:00
|
|
|
Future<bool> _syncNewAssetToDb(Asset a) async {
|
|
|
|
final Asset? inDb =
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.getByOwnerIdChecksum(a.ownerId, a.checksum);
|
2023-06-10 18:13:59 +00:00
|
|
|
if (inDb != null) {
|
2023-03-27 02:35:52 +00:00
|
|
|
// unify local/remote assets by replacing the
|
|
|
|
// local-only asset in the DB with a local&remote asset
|
2023-06-10 18:13:59 +00:00
|
|
|
a = inDb.updatedCopy(a);
|
2023-03-27 02:35:52 +00:00
|
|
|
}
|
|
|
|
try {
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.update(a);
|
|
|
|
} catch (e) {
|
2024-02-24 03:38:57 +00:00
|
|
|
_log.severe("Failed to put new asset into db", e);
|
2023-03-27 02:35:52 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2023-09-10 12:51:18 +00:00
|
|
|
/// Efficiently syncs assets via changes. Returns `null` when a full sync is required.
|
|
|
|
Future<bool?> _syncRemoteAssetChanges(
|
2024-05-14 15:35:37 +00:00
|
|
|
List<User> users,
|
2023-09-10 12:51:18 +00:00
|
|
|
Future<(List<Asset>? toUpsert, List<String>? toDelete)> Function(
|
2024-05-14 15:35:37 +00:00
|
|
|
List<User> users,
|
2023-09-10 12:51:18 +00:00
|
|
|
DateTime since,
|
|
|
|
) getChangedAssets,
|
2023-03-27 02:35:52 +00:00
|
|
|
) async {
|
2024-09-30 14:37:30 +00:00
|
|
|
final currentUser = await _userRepository.me();
|
2024-05-14 15:35:37 +00:00
|
|
|
final DateTime? since =
|
2024-09-30 14:37:30 +00:00
|
|
|
(await _eTagRepository.get(currentUser.isarId))?.time?.toUtc();
|
2023-09-10 12:51:18 +00:00
|
|
|
if (since == null) return null;
|
|
|
|
final DateTime now = DateTime.now();
|
2024-05-14 15:35:37 +00:00
|
|
|
final (toUpsert, toDelete) = await getChangedAssets(users, since);
|
|
|
|
if (toUpsert == null || toDelete == null) {
|
|
|
|
await _clearUserAssetsETag(users);
|
|
|
|
return null;
|
|
|
|
}
|
2023-09-10 12:51:18 +00:00
|
|
|
try {
|
|
|
|
if (toDelete.isNotEmpty) {
|
2023-10-16 18:01:38 +00:00
|
|
|
await handleRemoteAssetRemoval(toDelete);
|
2023-09-10 12:51:18 +00:00
|
|
|
}
|
|
|
|
if (toUpsert.isNotEmpty) {
|
|
|
|
final (_, updated) = await _linkWithExistingFromDb(toUpsert);
|
|
|
|
await upsertAssetsWithExif(updated);
|
|
|
|
}
|
|
|
|
if (toUpsert.isNotEmpty || toDelete.isNotEmpty) {
|
2024-05-14 15:35:37 +00:00
|
|
|
await _updateUserAssetsETag(users, now);
|
2023-09-10 12:51:18 +00:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
2024-09-30 14:37:30 +00:00
|
|
|
} catch (e) {
|
2024-02-24 03:38:57 +00:00
|
|
|
_log.severe("Failed to sync remote assets to db", e);
|
2023-09-10 12:51:18 +00:00
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Deletes remote-only assets, updates merged assets to be local-only
|
2023-10-16 18:01:38 +00:00
|
|
|
Future<void> handleRemoteAssetRemoval(List<String> idsToDelete) {
|
2024-09-30 14:37:30 +00:00
|
|
|
return _assetRepository.transaction(() async {
|
|
|
|
await _assetRepository.deleteAllByRemoteId(
|
|
|
|
idsToDelete,
|
|
|
|
state: AssetState.remote,
|
|
|
|
);
|
|
|
|
final merged = await _assetRepository.getAllByRemoteId(
|
|
|
|
idsToDelete,
|
|
|
|
state: AssetState.merged,
|
|
|
|
);
|
|
|
|
if (merged.isEmpty) return;
|
|
|
|
for (final Asset asset in merged) {
|
|
|
|
asset.remoteId = null;
|
|
|
|
asset.isTrashed = false;
|
2023-09-10 12:51:18 +00:00
|
|
|
}
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.updateAll(merged);
|
2023-09-10 12:51:18 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Syncs assets by loading and comparing all assets from the server.
|
|
|
|
Future<bool> _syncRemoteAssetsFull(
|
2024-05-14 15:35:37 +00:00
|
|
|
FutureOr<List<User>?> Function() refreshUsers,
|
|
|
|
FutureOr<List<Asset>?> Function(User user, DateTime until) loadAssets,
|
|
|
|
) async {
|
|
|
|
final serverUsers = await refreshUsers();
|
|
|
|
if (serverUsers == null) {
|
|
|
|
_log.warning("_syncRemoteAssetsFull aborted because user refresh failed");
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
await _syncUsersFromServer(serverUsers);
|
2024-09-30 14:37:30 +00:00
|
|
|
final List<User> users = await _userRepository.getAllAccessible();
|
2024-05-14 15:35:37 +00:00
|
|
|
bool changes = false;
|
|
|
|
for (User u in users) {
|
|
|
|
changes |= await _syncRemoteAssetsForUser(u, loadAssets);
|
|
|
|
}
|
|
|
|
return changes;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<bool> _syncRemoteAssetsForUser(
|
2023-09-10 12:51:18 +00:00
|
|
|
User user,
|
2024-05-14 15:35:37 +00:00
|
|
|
FutureOr<List<Asset>?> Function(User user, DateTime until) loadAssets,
|
2023-09-10 12:51:18 +00:00
|
|
|
) async {
|
2023-11-06 17:40:43 +00:00
|
|
|
final DateTime now = DateTime.now().toUtc();
|
2024-05-14 15:35:37 +00:00
|
|
|
final List<Asset>? remote = await loadAssets(user, now);
|
2023-03-27 02:35:52 +00:00
|
|
|
if (remote == null) {
|
|
|
|
return false;
|
|
|
|
}
|
2024-09-30 14:37:30 +00:00
|
|
|
final List<Asset> inDb = await _assetRepository.getAll(
|
|
|
|
ownerId: user.isarId,
|
|
|
|
sortBy: AssetSort.checksum,
|
|
|
|
);
|
2023-06-10 18:13:59 +00:00
|
|
|
assert(inDb.isSorted(Asset.compareByChecksum), "inDb not sorted!");
|
|
|
|
|
|
|
|
remote.sort(Asset.compareByChecksum);
|
2023-11-06 17:40:43 +00:00
|
|
|
|
|
|
|
// filter our duplicates that might be introduced by the chunked retrieval
|
|
|
|
remote.uniqueConsecutive(compare: Asset.compareByChecksum);
|
|
|
|
|
2023-05-21 01:41:34 +00:00
|
|
|
final (toAdd, toUpdate, toRemove) = _diffAssets(remote, inDb, remote: true);
|
|
|
|
if (toAdd.isEmpty && toUpdate.isEmpty && toRemove.isEmpty) {
|
2024-05-14 15:35:37 +00:00
|
|
|
await _updateUserAssetsETag([user], now);
|
2023-03-03 22:38:30 +00:00
|
|
|
return false;
|
|
|
|
}
|
2023-05-21 01:41:34 +00:00
|
|
|
final idsToDelete = toRemove.map((e) => e.id).toList();
|
2023-03-03 22:38:30 +00:00
|
|
|
try {
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.deleteById(idsToDelete);
|
2023-05-21 01:41:34 +00:00
|
|
|
await upsertAssetsWithExif(toAdd + toUpdate);
|
2024-09-30 14:37:30 +00:00
|
|
|
} catch (e) {
|
2024-02-24 03:38:57 +00:00
|
|
|
_log.severe("Failed to sync remote assets to db", e);
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
2024-05-14 15:35:37 +00:00
|
|
|
await _updateUserAssetsETag([user], now);
|
2023-03-03 22:38:30 +00:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2024-05-14 15:35:37 +00:00
|
|
|
Future<void> _updateUserAssetsETag(List<User> users, DateTime time) {
|
|
|
|
final etags = users.map((u) => ETag(id: u.id, time: time)).toList();
|
2024-09-30 14:37:30 +00:00
|
|
|
return _eTagRepository.upsertAll(etags);
|
2024-05-14 15:35:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> _clearUserAssetsETag(List<User> users) {
|
|
|
|
final ids = users.map((u) => u.id).toList();
|
2024-09-30 14:37:30 +00:00
|
|
|
return _eTagRepository.deleteByIds(ids);
|
2024-05-14 15:35:37 +00:00
|
|
|
}
|
2023-09-10 12:51:18 +00:00
|
|
|
|
2023-03-03 22:38:30 +00:00
|
|
|
/// Syncs remote albums to the database
|
|
|
|
/// returns `true` if there were any changes
|
|
|
|
Future<bool> _syncRemoteAlbumsToDb(
|
2024-09-20 13:32:37 +00:00
|
|
|
List<Album> remoteAlbums,
|
2023-03-03 22:38:30 +00:00
|
|
|
) async {
|
2024-09-20 13:32:37 +00:00
|
|
|
remoteAlbums.sortBy((e) => e.remoteId!);
|
2023-03-03 22:38:30 +00:00
|
|
|
|
2024-09-30 14:37:30 +00:00
|
|
|
final List<Album> dbAlbums = await _albumRepository.getAll(
|
|
|
|
remote: true,
|
|
|
|
sortBy: AlbumSort.remoteId,
|
|
|
|
);
|
2024-10-10 08:44:14 +00:00
|
|
|
|
2023-03-03 22:38:30 +00:00
|
|
|
final List<Asset> toDelete = [];
|
|
|
|
final List<Asset> existing = [];
|
|
|
|
|
|
|
|
final bool changes = await diffSortedLists(
|
2024-09-20 13:32:37 +00:00
|
|
|
remoteAlbums,
|
2023-03-03 22:38:30 +00:00
|
|
|
dbAlbums,
|
2024-09-20 13:32:37 +00:00
|
|
|
compare: (remoteAlbum, dbAlbum) =>
|
|
|
|
remoteAlbum.remoteId!.compareTo(dbAlbum.remoteId!),
|
|
|
|
both: (remoteAlbum, dbAlbum) =>
|
|
|
|
_syncRemoteAlbum(remoteAlbum, dbAlbum, toDelete, existing),
|
|
|
|
onlyFirst: (remoteAlbum) => _addAlbumFromServer(remoteAlbum, existing),
|
|
|
|
onlySecond: (dbAlbum) => _removeAlbumFromDb(dbAlbum, toDelete),
|
2023-03-03 22:38:30 +00:00
|
|
|
);
|
|
|
|
|
2024-10-10 08:44:14 +00:00
|
|
|
if (toDelete.isNotEmpty) {
|
2023-03-03 22:38:30 +00:00
|
|
|
final List<int> idsToRemove = sharedAssetsToRemove(toDelete, existing);
|
|
|
|
if (idsToRemove.isNotEmpty) {
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.deleteById(idsToRemove);
|
2023-03-03 22:38:30 +00: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(
|
2024-09-20 13:32:37 +00:00
|
|
|
Album dto,
|
2023-03-03 22:38:30 +00:00
|
|
|
Album album,
|
|
|
|
List<Asset> deleteCandidates,
|
|
|
|
List<Asset> existing,
|
|
|
|
) async {
|
2024-09-20 13:32:37 +00:00
|
|
|
if (!_hasRemoteAlbumChanged(dto, album)) {
|
2023-03-03 22:38:30 +00:00
|
|
|
return false;
|
|
|
|
}
|
2023-10-12 18:18:54 +00:00
|
|
|
// loadDetails (/api/album/:id) will not include lastModifiedAssetTimestamp,
|
|
|
|
// i.e. it will always be null. Save it here.
|
|
|
|
final originalDto = dto;
|
2024-09-20 13:32:37 +00:00
|
|
|
dto = await _albumApiRepository.get(dto.remoteId!);
|
2024-09-30 14:37:30 +00:00
|
|
|
|
|
|
|
final assetsInDb = await _assetRepository.getByAlbum(
|
|
|
|
album,
|
|
|
|
sortBy: AssetSort.ownerIdChecksum,
|
|
|
|
);
|
2023-06-10 18:13:59 +00:00
|
|
|
assert(assetsInDb.isSorted(Asset.compareByOwnerChecksum), "inDb unsorted!");
|
2024-09-20 13:32:37 +00:00
|
|
|
final List<Asset> assetsOnRemote = dto.remoteAssets.toList();
|
2023-06-10 18:13:59 +00:00
|
|
|
assetsOnRemote.sort(Asset.compareByOwnerChecksum);
|
|
|
|
final (toAdd, toUpdate, toUnlink) = _diffAssets(
|
|
|
|
assetsOnRemote,
|
|
|
|
assetsInDb,
|
|
|
|
compare: Asset.compareByOwnerChecksum,
|
|
|
|
);
|
2023-03-03 22:38:30 +00:00
|
|
|
|
|
|
|
// update shared users
|
|
|
|
final List<User> sharedUsers = album.sharedUsers.toList(growable: false);
|
|
|
|
sharedUsers.sort((a, b) => a.id.compareTo(b.id));
|
2024-09-20 13:32:37 +00:00
|
|
|
final List<User> users = dto.remoteUsers.toList()
|
|
|
|
..sort((a, b) => a.id.compareTo(b.id));
|
2023-03-03 22:38:30 +00:00
|
|
|
final List<String> userIdsToAdd = [];
|
|
|
|
final List<User> usersToUnlink = [];
|
|
|
|
diffSortedListsSync(
|
2024-09-20 13:32:37 +00:00
|
|
|
users,
|
2023-03-03 22:38:30 +00:00
|
|
|
sharedUsers,
|
2024-09-20 13:32:37 +00:00
|
|
|
compare: (User a, User b) => a.id.compareTo(b.id),
|
2023-03-03 22:38:30 +00:00
|
|
|
both: (a, b) => false,
|
2024-09-20 13:32:37 +00:00
|
|
|
onlyFirst: (User a) => userIdsToAdd.add(a.id),
|
2023-03-03 22:38:30 +00:00
|
|
|
onlySecond: (User a) => usersToUnlink.add(a),
|
|
|
|
);
|
|
|
|
|
|
|
|
// for shared album: put missing album assets into local DB
|
2023-05-21 01:41:34 +00:00
|
|
|
final (existingInDb, updated) = await _linkWithExistingFromDb(toAdd);
|
|
|
|
await upsertAssetsWithExif(updated);
|
|
|
|
final assetsToLink = existingInDb + updated;
|
2024-09-30 14:37:30 +00:00
|
|
|
final usersToLink = await _userRepository.getByIds(userIdsToAdd);
|
2023-03-03 22:38:30 +00:00
|
|
|
|
2024-09-20 13:32:37 +00:00
|
|
|
album.name = dto.name;
|
2023-03-03 22:38:30 +00:00
|
|
|
album.shared = dto.shared;
|
2024-04-02 05:22:15 +00:00
|
|
|
album.createdAt = dto.createdAt;
|
2024-09-20 13:32:37 +00:00
|
|
|
album.modifiedAt = dto.modifiedAt;
|
2024-04-02 05:22:15 +00:00
|
|
|
album.startDate = dto.startDate;
|
|
|
|
album.endDate = dto.endDate;
|
2023-10-12 18:18:54 +00:00
|
|
|
album.lastModifiedAssetTimestamp = originalDto.lastModifiedAssetTimestamp;
|
2024-04-02 05:22:15 +00:00
|
|
|
album.shared = dto.shared;
|
2024-09-20 13:32:37 +00:00
|
|
|
album.activityEnabled = dto.activityEnabled;
|
2024-12-16 16:11:48 +00:00
|
|
|
album.sortOrder = dto.sortOrder;
|
|
|
|
|
2024-09-30 14:37:30 +00:00
|
|
|
final remoteThumbnailAssetId = dto.remoteThumbnailAssetId;
|
|
|
|
if (remoteThumbnailAssetId != null &&
|
|
|
|
album.thumbnail.value?.remoteId != remoteThumbnailAssetId) {
|
|
|
|
album.thumbnail.value =
|
|
|
|
await _assetRepository.getByRemoteId(remoteThumbnailAssetId);
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// write & commit all changes to DB
|
|
|
|
try {
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.transaction(() async {
|
|
|
|
await _assetRepository.updateAll(toUpdate);
|
|
|
|
await _albumRepository.addUsers(album, usersToLink);
|
|
|
|
await _albumRepository.removeUsers(album, usersToUnlink);
|
|
|
|
await _albumRepository.addAssets(album, assetsToLink);
|
|
|
|
await _albumRepository.removeAssets(album, toUnlink);
|
|
|
|
await _albumRepository.recalculateMetadata(album);
|
|
|
|
await _albumRepository.update(album);
|
2023-03-03 22:38:30 +00:00
|
|
|
});
|
2023-06-10 18:13:59 +00:00
|
|
|
_log.info("Synced changes of remote album ${album.name} to DB");
|
2024-09-30 14:37:30 +00:00
|
|
|
} catch (e) {
|
2024-02-24 03:38:57 +00:00
|
|
|
_log.severe("Failed to sync remote album to database", e);
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (album.shared || dto.shared) {
|
2024-09-30 14:37:30 +00:00
|
|
|
final userId = (await _userRepository.me()).isarId;
|
2023-03-03 22:38:30 +00:00
|
|
|
final foreign =
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.getByAlbum(album, notOwnedBy: [userId]);
|
2023-03-03 22:38:30 +00:00
|
|
|
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(
|
2024-09-20 13:32:37 +00:00
|
|
|
Album album,
|
2023-03-03 22:38:30 +00:00
|
|
|
List<Asset> existing,
|
|
|
|
) async {
|
2024-09-20 13:32:37 +00:00
|
|
|
if (album.remoteAssetCount != album.remoteAssets.length) {
|
|
|
|
album = await _albumApiRepository.get(album.remoteId!);
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
2024-09-20 13:32:37 +00:00
|
|
|
if (album.remoteAssetCount == album.remoteAssets.length) {
|
2023-03-03 22:38:30 +00:00
|
|
|
// in case an album contains assets not yet present in local DB:
|
|
|
|
// put missing album assets into local DB
|
2023-05-21 01:41:34 +00:00
|
|
|
final (existingInDb, updated) =
|
2024-09-20 13:32:37 +00:00
|
|
|
await _linkWithExistingFromDb(album.remoteAssets.toList());
|
2023-05-21 01:41:34 +00:00
|
|
|
existing.addAll(existingInDb);
|
|
|
|
await upsertAssetsWithExif(updated);
|
2023-03-03 22:38:30 +00:00
|
|
|
|
2024-09-20 13:32:37 +00:00
|
|
|
await _entityService.fillAlbumWithDatabaseEntities(album);
|
2024-09-30 14:37:30 +00:00
|
|
|
await _albumRepository.create(album);
|
2023-12-04 16:21:05 +00:00
|
|
|
} else {
|
|
|
|
_log.warning(
|
2024-09-20 13:32:37 +00:00
|
|
|
"Failed to add album from server: assetCount ${album.remoteAssetCount} != "
|
|
|
|
"asset array length ${album.remoteAssets.length} for album ${album.name}");
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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-19 22:05:18 +00:00
|
|
|
_log.info("Removing local album $album from DB");
|
2023-03-03 22:38:30 +00:00
|
|
|
// delete assets in DB unless they are remote or part of some other album
|
|
|
|
deleteCandidates.addAll(
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.getByAlbum(album, state: AssetState.local),
|
2023-03-03 22:38:30 +00:00
|
|
|
);
|
|
|
|
} else if (album.shared) {
|
2023-05-25 03:52:43 +00:00
|
|
|
// delete assets in DB unless they belong to this user or are part of some other shared album or belong to a partner
|
2024-09-30 14:37:30 +00:00
|
|
|
final userIds =
|
|
|
|
(await _userRepository.getAllAccessible()).map((user) => user.isarId);
|
|
|
|
final orphanedAssets =
|
|
|
|
await _assetRepository.getByAlbum(album, notOwnedBy: userIds);
|
2023-05-25 03:52:43 +00:00
|
|
|
deleteCandidates.addAll(orphanedAssets);
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
2023-03-19 22:05:18 +00:00
|
|
|
try {
|
2024-09-30 14:37:30 +00:00
|
|
|
await _albumRepository.delete(album.id);
|
2023-03-19 22:05:18 +00:00
|
|
|
_log.info("Removed local album $album from DB");
|
|
|
|
} catch (e) {
|
2024-02-24 03:38:57 +00:00
|
|
|
_log.severe("Failed to remove local album $album from DB", e);
|
2023-03-19 22:05:18 +00:00
|
|
|
}
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Syncs all device albums and their assets to the database
|
|
|
|
/// Returns `true` if there were any changes
|
2023-03-19 22:05:18 +00:00
|
|
|
Future<bool> _syncLocalAlbumAssetsToDb(
|
2024-09-18 15:15:52 +00:00
|
|
|
List<Album> onDevice, [
|
2024-07-02 19:01:54 +00:00
|
|
|
Set<String>? excludedAssets,
|
|
|
|
]) async {
|
2024-10-02 13:09:34 +00:00
|
|
|
onDevice.sort((a, b) => a.localId!.compareTo(b.localId!));
|
2023-06-10 18:13:59 +00:00
|
|
|
final inDb =
|
2024-09-30 14:37:30 +00:00
|
|
|
await _albumRepository.getAll(remote: false, sortBy: AlbumSort.localId);
|
2023-03-03 22:38:30 +00:00
|
|
|
final List<Asset> deleteCandidates = [];
|
|
|
|
final List<Asset> existing = [];
|
|
|
|
final bool anyChanges = await diffSortedLists(
|
|
|
|
onDevice,
|
|
|
|
inDb,
|
2024-09-18 15:15:52 +00:00
|
|
|
compare: (Album a, Album b) => a.localId!.compareTo(b.localId!),
|
|
|
|
both: (Album a, Album b) => _syncAlbumInDbAndOnDevice(
|
|
|
|
a,
|
|
|
|
b,
|
2023-03-19 22:05:18 +00:00
|
|
|
deleteCandidates,
|
|
|
|
existing,
|
2024-07-02 19:01:54 +00:00
|
|
|
excludedAssets,
|
2023-03-19 22:05:18 +00:00
|
|
|
),
|
2024-09-18 15:15:52 +00:00
|
|
|
onlyFirst: (Album a) => _addAlbumFromDevice(a, existing, excludedAssets),
|
2023-03-03 22:38:30 +00:00
|
|
|
onlySecond: (Album a) => _removeAlbumFromDb(a, deleteCandidates),
|
|
|
|
);
|
2023-04-14 13:50:46 +00:00
|
|
|
_log.fine(
|
|
|
|
"Syncing all local albums almost done. Collected ${deleteCandidates.length} asset candidates to delete",
|
|
|
|
);
|
2023-05-21 01:41:34 +00:00
|
|
|
final (toDelete, toUpdate) =
|
|
|
|
_handleAssetRemoval(deleteCandidates, existing, remote: false);
|
2023-04-14 13:50:46 +00:00
|
|
|
_log.fine(
|
2023-05-21 01:41:34 +00:00
|
|
|
"${toDelete.length} assets to delete, ${toUpdate.length} to update",
|
2023-04-14 13:50:46 +00:00
|
|
|
);
|
2023-05-21 01:41:34 +00:00
|
|
|
if (toDelete.isNotEmpty || toUpdate.isNotEmpty) {
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.transaction(() async {
|
|
|
|
await _assetRepository.deleteById(toDelete);
|
|
|
|
await _assetRepository.updateAll(toUpdate);
|
2023-03-03 22:38:30 +00:00
|
|
|
});
|
2023-03-19 22:05:18 +00:00
|
|
|
_log.info(
|
2023-05-21 01:41:34 +00:00
|
|
|
"Removed ${toDelete.length} and updated ${toUpdate.length} local assets from DB",
|
2023-03-19 22:05:18 +00:00
|
|
|
);
|
2023-03-03 22:38:30 +00: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(
|
2024-09-18 15:15:52 +00:00
|
|
|
Album deviceAlbum,
|
|
|
|
Album dbAlbum,
|
2023-03-03 22:38:30 +00:00
|
|
|
List<Asset> deleteCandidates,
|
|
|
|
List<Asset> existing, [
|
2024-07-02 19:01:54 +00:00
|
|
|
Set<String>? excludedAssets,
|
2023-03-03 22:38:30 +00:00
|
|
|
bool forceRefresh = false,
|
|
|
|
]) async {
|
2024-09-18 15:15:52 +00:00
|
|
|
if (!forceRefresh && !await _hasAlbumChangeOnDevice(deviceAlbum, dbAlbum)) {
|
|
|
|
_log.fine(
|
|
|
|
"Local album ${deviceAlbum.name} has not changed. Skipping sync.",
|
|
|
|
);
|
2023-03-03 22:38:30 +00:00
|
|
|
return false;
|
|
|
|
}
|
2024-07-02 19:01:54 +00:00
|
|
|
if (!forceRefresh &&
|
|
|
|
excludedAssets == null &&
|
2024-09-18 15:15:52 +00:00
|
|
|
await _syncDeviceAlbumFast(deviceAlbum, dbAlbum)) {
|
2023-03-03 22:38:30 +00:00
|
|
|
return true;
|
|
|
|
}
|
2023-03-19 22:05:18 +00:00
|
|
|
// general case, e.g. some assets have been deleted or there are excluded albums on iOS
|
2024-09-30 14:37:30 +00:00
|
|
|
final inDb = await _assetRepository.getByAlbum(
|
|
|
|
dbAlbum,
|
|
|
|
ownerId: (await _userRepository.me()).isarId,
|
|
|
|
sortBy: AssetSort.checksum,
|
|
|
|
);
|
|
|
|
|
2023-06-10 18:13:59 +00:00
|
|
|
assert(inDb.isSorted(Asset.compareByChecksum), "inDb not sorted!");
|
2024-09-18 15:15:52 +00:00
|
|
|
final int assetCountOnDevice =
|
|
|
|
await _albumMediaRepository.getAssetCount(deviceAlbum.localId!);
|
|
|
|
final List<Asset> onDevice = await _hashService.getHashedAssets(
|
|
|
|
deviceAlbum,
|
|
|
|
excludedAssets: excludedAssets,
|
|
|
|
);
|
2023-06-10 18:13:59 +00:00
|
|
|
_removeDuplicates(onDevice);
|
|
|
|
// _removeDuplicates sorts `onDevice` by checksum
|
|
|
|
final (toAdd, toUpdate, toDelete) = _diffAssets(onDevice, inDb);
|
2023-03-19 22:05:18 +00:00
|
|
|
if (toAdd.isEmpty &&
|
|
|
|
toUpdate.isEmpty &&
|
|
|
|
toDelete.isEmpty &&
|
2024-09-18 15:15:52 +00:00
|
|
|
dbAlbum.name == deviceAlbum.name &&
|
|
|
|
dbAlbum.modifiedAt.isAtSameMomentAs(deviceAlbum.modifiedAt)) {
|
2023-03-19 22:05:18 +00:00
|
|
|
// changes only affeted excluded albums
|
2023-04-14 13:50:46 +00:00
|
|
|
_log.fine(
|
2024-09-18 15:15:52 +00:00
|
|
|
"Only excluded assets in local album ${deviceAlbum.name} changed. Stopping sync.",
|
2023-04-14 13:50:46 +00:00
|
|
|
);
|
2023-09-10 12:51:18 +00:00
|
|
|
if (assetCountOnDevice !=
|
2024-09-30 14:37:30 +00:00
|
|
|
(await _eTagRepository.getById(deviceAlbum.eTagKeyAssetCount))
|
|
|
|
?.assetCount) {
|
|
|
|
await _eTagRepository.upsertAll([
|
|
|
|
ETag(
|
|
|
|
id: deviceAlbum.eTagKeyAssetCount,
|
|
|
|
assetCount: assetCountOnDevice,
|
2023-09-10 12:51:18 +00:00
|
|
|
),
|
2024-09-30 14:37:30 +00:00
|
|
|
]);
|
2023-09-10 12:51:18 +00:00
|
|
|
}
|
2023-03-19 22:05:18 +00:00
|
|
|
return false;
|
|
|
|
}
|
2023-04-14 13:50:46 +00:00
|
|
|
_log.fine(
|
2024-09-18 15:15:52 +00:00
|
|
|
"Syncing local album ${deviceAlbum.name}. ${toAdd.length} assets to add, ${toUpdate.length} to update, ${toDelete.length} to delete",
|
2023-04-14 13:50:46 +00:00
|
|
|
);
|
2023-05-21 01:41:34 +00:00
|
|
|
final (existingInDb, updated) = await _linkWithExistingFromDb(toAdd);
|
2023-04-14 13:50:46 +00:00
|
|
|
_log.fine(
|
2023-05-21 01:41:34 +00:00
|
|
|
"Linking assets to add with existing from db. ${existingInDb.length} existing, ${updated.length} to update",
|
2023-04-14 13:50:46 +00:00
|
|
|
);
|
2023-03-03 22:38:30 +00:00
|
|
|
deleteCandidates.addAll(toDelete);
|
2023-05-21 01:41:34 +00:00
|
|
|
existing.addAll(existingInDb);
|
2024-09-18 15:15:52 +00:00
|
|
|
dbAlbum.name = deviceAlbum.name;
|
|
|
|
dbAlbum.modifiedAt = deviceAlbum.modifiedAt;
|
|
|
|
if (dbAlbum.thumbnail.value != null &&
|
|
|
|
toDelete.contains(dbAlbum.thumbnail.value)) {
|
|
|
|
dbAlbum.thumbnail.value = null;
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
|
|
|
try {
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.transaction(() async {
|
|
|
|
await _assetRepository.updateAll(updated + toUpdate);
|
|
|
|
await _albumRepository.addAssets(dbAlbum, existingInDb + updated);
|
|
|
|
await _albumRepository.removeAssets(dbAlbum, toDelete);
|
|
|
|
await _albumRepository.recalculateMetadata(dbAlbum);
|
|
|
|
await _albumRepository.update(dbAlbum);
|
|
|
|
await _eTagRepository.upsertAll([
|
2024-09-18 15:15:52 +00:00
|
|
|
ETag(
|
|
|
|
id: deviceAlbum.eTagKeyAssetCount,
|
|
|
|
assetCount: assetCountOnDevice,
|
|
|
|
),
|
2024-09-30 14:37:30 +00:00
|
|
|
]);
|
2023-03-03 22:38:30 +00:00
|
|
|
});
|
2024-09-18 15:15:52 +00:00
|
|
|
_log.info("Synced changes of local album ${deviceAlbum.name} to DB");
|
2024-09-30 14:37:30 +00:00
|
|
|
} catch (e) {
|
2024-09-18 15:15:52 +00:00
|
|
|
_log.severe("Failed to update synced album ${deviceAlbum.name} in DB", e);
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// fast path for common case: only new assets were added to device album
|
|
|
|
/// returns `true` if successfull, else `false`
|
2024-09-18 15:15:52 +00:00
|
|
|
Future<bool> _syncDeviceAlbumFast(Album deviceAlbum, Album dbAlbum) async {
|
|
|
|
if (!deviceAlbum.modifiedAt.isAfter(dbAlbum.modifiedAt)) {
|
2023-06-10 18:13:59 +00:00
|
|
|
return false;
|
|
|
|
}
|
2024-09-18 15:15:52 +00:00
|
|
|
final int totalOnDevice =
|
|
|
|
await _albumMediaRepository.getAssetCount(deviceAlbum.localId!);
|
2023-06-10 18:13:59 +00:00
|
|
|
final int lastKnownTotal =
|
2024-09-30 14:37:30 +00:00
|
|
|
(await _eTagRepository.getById(deviceAlbum.eTagKeyAssetCount))
|
|
|
|
?.assetCount ??
|
2024-09-18 15:15:52 +00:00
|
|
|
0;
|
|
|
|
if (totalOnDevice <= lastKnownTotal) {
|
2023-03-03 22:38:30 +00:00
|
|
|
return false;
|
|
|
|
}
|
2024-09-18 15:15:52 +00:00
|
|
|
final List<Asset> newAssets = await _hashService.getHashedAssets(
|
|
|
|
deviceAlbum,
|
|
|
|
modifiedFrom: dbAlbum.modifiedAt.add(const Duration(seconds: 1)),
|
|
|
|
modifiedUntil: deviceAlbum.modifiedAt,
|
|
|
|
);
|
2023-06-10 18:13:59 +00:00
|
|
|
|
|
|
|
if (totalOnDevice != lastKnownTotal + newAssets.length) {
|
2023-03-03 22:38:30 +00:00
|
|
|
return false;
|
|
|
|
}
|
2024-09-18 15:15:52 +00:00
|
|
|
dbAlbum.modifiedAt = deviceAlbum.modifiedAt;
|
2023-06-10 18:13:59 +00:00
|
|
|
_removeDuplicates(newAssets);
|
2023-05-21 01:41:34 +00:00
|
|
|
final (existingInDb, updated) = await _linkWithExistingFromDb(newAssets);
|
2023-03-03 22:38:30 +00:00
|
|
|
try {
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.transaction(() async {
|
|
|
|
await _assetRepository.updateAll(updated);
|
|
|
|
await _albumRepository.addAssets(dbAlbum, existingInDb + updated);
|
|
|
|
await _albumRepository.recalculateMetadata(dbAlbum);
|
|
|
|
await _albumRepository.update(dbAlbum);
|
|
|
|
await _eTagRepository.upsertAll(
|
|
|
|
[ETag(id: deviceAlbum.eTagKeyAssetCount, assetCount: totalOnDevice)],
|
2024-09-18 15:15:52 +00:00
|
|
|
);
|
2023-03-03 22:38:30 +00:00
|
|
|
});
|
2024-09-18 15:15:52 +00:00
|
|
|
_log.info("Fast synced local album ${deviceAlbum.name} to DB");
|
2024-09-30 14:37:30 +00:00
|
|
|
} catch (e) {
|
2024-09-18 15:15:52 +00:00
|
|
|
_log.severe(
|
|
|
|
"Failed to fast sync local album ${deviceAlbum.name} to DB",
|
|
|
|
e,
|
|
|
|
);
|
2023-03-19 22:05:18 +00:00
|
|
|
return false;
|
2023-03-03 22:38:30 +00: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(
|
2024-09-18 15:15:52 +00:00
|
|
|
Album album,
|
2024-07-02 19:01:54 +00:00
|
|
|
List<Asset> existing, [
|
|
|
|
Set<String>? excludedAssets,
|
|
|
|
]) async {
|
2024-09-18 15:15:52 +00:00
|
|
|
_log.info("Syncing a new local album to DB: ${album.name}");
|
|
|
|
final assets = await _hashService.getHashedAssets(
|
|
|
|
album,
|
|
|
|
excludedAssets: excludedAssets,
|
|
|
|
);
|
2023-06-10 18:13:59 +00:00
|
|
|
_removeDuplicates(assets);
|
2023-05-21 01:41:34 +00:00
|
|
|
final (existingInDb, updated) = await _linkWithExistingFromDb(assets);
|
2023-03-19 22:05:18 +00:00
|
|
|
_log.info(
|
2023-05-21 01:41:34 +00:00
|
|
|
"${existingInDb.length} assets already existed in DB, to upsert ${updated.length}",
|
2023-03-19 22:05:18 +00:00
|
|
|
);
|
2023-05-21 01:41:34 +00:00
|
|
|
await upsertAssetsWithExif(updated);
|
|
|
|
existing.addAll(existingInDb);
|
2024-09-18 15:15:52 +00:00
|
|
|
album.assets.addAll(existingInDb);
|
|
|
|
album.assets.addAll(updated);
|
2023-05-21 01:41:34 +00:00
|
|
|
final thumb = existingInDb.firstOrNull ?? updated.firstOrNull;
|
2024-09-18 15:15:52 +00:00
|
|
|
album.thumbnail.value = thumb;
|
2023-03-03 22:38:30 +00:00
|
|
|
try {
|
2024-09-30 14:37:30 +00:00
|
|
|
await _albumRepository.create(album);
|
2024-09-18 15:15:52 +00:00
|
|
|
_log.info("Added a new local album to DB: ${album.name}");
|
2024-09-30 14:37:30 +00:00
|
|
|
} catch (e) {
|
2024-09-18 15:15:52 +00:00
|
|
|
_log.severe("Failed to add new local album ${album.name} to DB", e);
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a tuple (existing, updated)
|
2023-05-21 01:41:34 +00:00
|
|
|
Future<(List<Asset> existing, List<Asset> updated)> _linkWithExistingFromDb(
|
2023-03-03 22:38:30 +00:00
|
|
|
List<Asset> assets,
|
|
|
|
) async {
|
2023-06-10 18:13:59 +00:00
|
|
|
if (assets.isEmpty) return ([].cast<Asset>(), [].cast<Asset>());
|
|
|
|
|
2024-09-30 14:37:30 +00:00
|
|
|
final List<Asset?> inDb = await _assetRepository.getAllByOwnerIdChecksum(
|
2023-06-10 18:13:59 +00:00
|
|
|
assets.map((a) => a.ownerId).toInt64List(),
|
2023-09-28 03:43:55 +00:00
|
|
|
assets.map((a) => a.checksum).toList(growable: false),
|
2023-03-03 22:38:30 +00:00
|
|
|
);
|
2023-06-10 18:13:59 +00: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]);
|
2024-09-30 14:37:30 +00:00
|
|
|
assert(updated.isInDb);
|
2023-06-10 18:13:59 +00:00
|
|
|
toUpsert.add(updated);
|
|
|
|
} else {
|
|
|
|
existing.add(b);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
assert(existing.length + toUpsert.length == assets.length);
|
2023-05-21 01:41:34 +00:00
|
|
|
return (existing, toUpsert);
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Inserts or updates the assets in the database with their ExifInfo (if any)
|
2023-05-17 17:36:02 +00:00
|
|
|
Future<void> upsertAssetsWithExif(List<Asset> assets) async {
|
2024-09-30 14:37:30 +00:00
|
|
|
if (assets.isEmpty) return;
|
|
|
|
final exifInfos = assets.map((e) => e.exifInfo).nonNulls.toList();
|
2023-03-03 22:38:30 +00:00
|
|
|
try {
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.transaction(() async {
|
|
|
|
await _assetRepository.updateAll(assets);
|
2023-03-03 22:38:30 +00:00
|
|
|
for (final Asset added in assets) {
|
|
|
|
added.exifInfo?.id = added.id;
|
|
|
|
}
|
2024-09-30 14:37:30 +00:00
|
|
|
await _exifInfoRepository.updateAll(exifInfos);
|
2023-03-03 22:38:30 +00:00
|
|
|
});
|
2023-03-19 22:05:18 +00:00
|
|
|
_log.info("Upserted ${assets.length} assets into the DB");
|
2024-09-30 14:37:30 +00:00
|
|
|
} catch (e) {
|
2024-02-24 03:38:57 +00:00
|
|
|
_log.severe("Failed to upsert ${assets.length} assets into the DB", e);
|
2023-06-10 18:13:59 +00:00
|
|
|
// give details on the errors
|
|
|
|
assets.sort(Asset.compareByOwnerChecksum);
|
2024-09-30 14:37:30 +00:00
|
|
|
final inDb = await _assetRepository.getAllByOwnerIdChecksum(
|
2023-06-10 18:13:59 +00:00
|
|
|
assets.map((e) => e.ownerId).toInt64List(),
|
2023-09-28 03:43:55 +00:00
|
|
|
assets.map((e) => e.checksum).toList(growable: false),
|
2023-06-10 18:13:59 +00:00
|
|
|
);
|
|
|
|
for (int i = 0; i < assets.length; i++) {
|
|
|
|
final Asset a = assets[i];
|
|
|
|
final Asset? b = inDb[i];
|
|
|
|
if (b == null) {
|
2024-09-30 14:37:30 +00:00
|
|
|
if (!a.isInDb) {
|
2023-06-10 18:13:59 +00:00
|
|
|
_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,
|
2024-10-10 09:53:20 +00:00
|
|
|
onDuplicate: (a, b) => {},
|
2023-06-10 18:13:59 +00:00
|
|
|
);
|
|
|
|
final int duplicates = before - assets.length;
|
|
|
|
if (duplicates > 0) {
|
|
|
|
_log.warning("Ignored $duplicates duplicate assets on device");
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
2023-06-10 18:13:59 +00:00
|
|
|
return assets;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// returns `true` if the albums differ on the surface
|
2024-09-18 15:15:52 +00:00
|
|
|
Future<bool> _hasAlbumChangeOnDevice(
|
|
|
|
Album deviceAlbum,
|
|
|
|
Album dbAlbum,
|
|
|
|
) async {
|
|
|
|
return deviceAlbum.name != dbAlbum.name ||
|
|
|
|
!deviceAlbum.modifiedAt.isAtSameMomentAs(dbAlbum.modifiedAt) ||
|
|
|
|
await _albumMediaRepository.getAssetCount(deviceAlbum.localId!) !=
|
2024-09-30 14:37:30 +00:00
|
|
|
(await _eTagRepository.getById(deviceAlbum.eTagKeyAssetCount))
|
2024-09-18 15:15:52 +00:00
|
|
|
?.assetCount;
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
2023-11-14 20:30:27 +00:00
|
|
|
|
|
|
|
Future<bool> _removeAllLocalAlbumsAndAssets() async {
|
|
|
|
try {
|
2024-09-30 14:37:30 +00:00
|
|
|
final assets = await _assetRepository.getAllLocal();
|
2023-11-14 20:30:27 +00:00
|
|
|
final (toDelete, toUpdate) =
|
|
|
|
_handleAssetRemoval(assets, [], remote: false);
|
2024-09-30 14:37:30 +00:00
|
|
|
await _assetRepository.transaction(() async {
|
|
|
|
await _assetRepository.deleteById(toDelete);
|
|
|
|
await _assetRepository.updateAll(toUpdate);
|
|
|
|
await _albumRepository.deleteAllLocal();
|
2023-11-14 20:30:27 +00:00
|
|
|
});
|
|
|
|
return true;
|
|
|
|
} catch (e) {
|
2024-02-24 03:38:57 +00:00
|
|
|
_log.severe("Failed to remove all local albums and assets", e);
|
2023-11-14 20:30:27 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a triple(toAdd, toUpdate, toRemove)
|
2023-05-21 01:41:34 +00:00
|
|
|
(List<Asset> toAdd, List<Asset> toUpdate, List<Asset> toRemove) _diffAssets(
|
2023-03-03 22:38:30 +00:00
|
|
|
List<Asset> assets,
|
|
|
|
List<Asset> inDb, {
|
|
|
|
bool? remote,
|
2023-06-10 18:13:59 +00:00
|
|
|
int Function(Asset, Asset) compare = Asset.compareByChecksum,
|
2023-03-03 22:38:30 +00:00
|
|
|
}) {
|
2023-11-17 21:35:57 +00:00
|
|
|
// fast paths for trivial cases: reduces memory usage during initial sync etc.
|
|
|
|
if (assets.isEmpty && inDb.isEmpty) {
|
|
|
|
return const ([], [], []);
|
|
|
|
} else if (assets.isEmpty && remote == null) {
|
|
|
|
// remove all from database
|
|
|
|
return (const [], const [], inDb);
|
|
|
|
} else if (inDb.isEmpty) {
|
|
|
|
// add all assets
|
|
|
|
return (assets, const [], const []);
|
|
|
|
}
|
|
|
|
|
2023-03-03 22:38:30 +00:00
|
|
|
final List<Asset> toAdd = [];
|
|
|
|
final List<Asset> toUpdate = [];
|
|
|
|
final List<Asset> toRemove = [];
|
|
|
|
diffSortedListsSync(
|
|
|
|
inDb,
|
|
|
|
assets,
|
|
|
|
compare: compare,
|
|
|
|
both: (Asset a, Asset b) {
|
2023-04-18 09:47:24 +00:00
|
|
|
if (a.canUpdate(b)) {
|
|
|
|
toUpdate.add(a.updatedCopy(b));
|
2023-03-03 22:38:30 +00: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 18:13:59 +00:00
|
|
|
a.localId = null;
|
2023-03-03 22:38:30 +00:00
|
|
|
toUpdate.add(a);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
toRemove.add(a);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
onlySecond: (Asset b) => toAdd.add(b),
|
|
|
|
);
|
2023-05-21 01:41:34 +00:00
|
|
|
return (toAdd, toUpdate, toRemove);
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// returns a tuple (toDelete toUpdate) when assets are to be deleted
|
2023-05-21 01:41:34 +00:00
|
|
|
(List<int> toDelete, List<Asset> toUpdate) _handleAssetRemoval(
|
2023-03-03 22:38:30 +00:00
|
|
|
List<Asset> deleteCandidates,
|
2023-03-27 02:35:52 +00:00
|
|
|
List<Asset> existing, {
|
|
|
|
bool? remote,
|
|
|
|
}) {
|
2023-03-03 22:38:30 +00:00
|
|
|
if (deleteCandidates.isEmpty) {
|
2023-05-21 01:41:34 +00:00
|
|
|
return const ([], []);
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
|
|
|
deleteCandidates.sort(Asset.compareById);
|
2023-06-10 18:13:59 +00:00
|
|
|
deleteCandidates.uniqueConsecutive(compare: Asset.compareById);
|
2023-03-03 22:38:30 +00:00
|
|
|
existing.sort(Asset.compareById);
|
2023-06-10 18:13:59 +00:00
|
|
|
existing.uniqueConsecutive(compare: Asset.compareById);
|
2023-05-21 01:41:34 +00:00
|
|
|
final (tooAdd, toUpdate, toRemove) = _diffAssets(
|
2023-03-27 02:35:52 +00:00
|
|
|
existing,
|
|
|
|
deleteCandidates,
|
|
|
|
compare: Asset.compareById,
|
|
|
|
remote: remote,
|
|
|
|
);
|
2023-05-21 01:41:34 +00:00
|
|
|
assert(tooAdd.isEmpty, "toAdd should be empty in _handleAssetRemoval");
|
|
|
|
return (toRemove.map((e) => e.id).toList(), toUpdate);
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// returns `true` if the albums differ on the surface
|
2024-09-20 13:32:37 +00:00
|
|
|
bool _hasRemoteAlbumChanged(Album remoteAlbum, Album dbAlbum) {
|
|
|
|
return remoteAlbum.remoteAssetCount != dbAlbum.assetCount ||
|
|
|
|
remoteAlbum.name != dbAlbum.name ||
|
|
|
|
remoteAlbum.remoteThumbnailAssetId != dbAlbum.thumbnail.value?.remoteId ||
|
|
|
|
remoteAlbum.shared != dbAlbum.shared ||
|
|
|
|
remoteAlbum.remoteUsers.length != dbAlbum.sharedUsers.length ||
|
|
|
|
!remoteAlbum.modifiedAt.isAtSameMomentAs(dbAlbum.modifiedAt) ||
|
|
|
|
!isAtSameMomentAs(remoteAlbum.startDate, dbAlbum.startDate) ||
|
|
|
|
!isAtSameMomentAs(remoteAlbum.endDate, dbAlbum.endDate) ||
|
2024-04-02 05:22:15 +00:00
|
|
|
!isAtSameMomentAs(
|
2024-09-20 13:32:37 +00:00
|
|
|
remoteAlbum.lastModifiedAssetTimestamp,
|
|
|
|
dbAlbum.lastModifiedAssetTimestamp,
|
2024-04-02 05:22:15 +00:00
|
|
|
);
|
2023-03-03 22:38:30 +00:00
|
|
|
}
|