Skip to content

Commit 2f1ec5b

Browse files
fix: prune stale assets
1 parent 00ce635 commit 2f1ec5b

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

mobile/lib/domain/services/sync_stream.service.dart

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,9 +130,9 @@ class SyncStreamService {
130130
// to acknowledge that the client has processed all the backfill events
131131
case SyncEntityType.syncAckV1:
132132
return;
133-
// No-op. SyncCompleteV1 is used to signal the completion of the sync process
133+
// SyncCompleteV1 is used to signal the completion of the sync process. Cleanup stale assets and signal completion
134134
case SyncEntityType.syncCompleteV1:
135-
return;
135+
return _syncStreamRepository.pruneAssets();
136136
// Request to reset the client state. Clear everything related to remote entities
137137
case SyncEntityType.syncResetV1:
138138
return _syncStreamRepository.reset();

mobile/lib/infrastructure/repositories/sync_stream.repository.dart

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -591,6 +591,40 @@ class SyncStreamRepository extends DriftDatabaseRepository {
591591
rethrow;
592592
}
593593
}
594+
595+
Future<void> pruneAssets() async {
596+
try {
597+
await _db.transaction(() async {
598+
final authQuery = _db.authUserEntity.selectOnly()
599+
..addColumns([_db.authUserEntity.id])
600+
..limit(1);
601+
final currentUserId = await authQuery.map((row) => row.read(_db.authUserEntity.id)).getSingleOrNull();
602+
if (currentUserId == null) {
603+
_logger.warning('No authenticated user found during pruneAssets. Skipping asset pruning.');
604+
return;
605+
}
606+
607+
final partnerQuery = _db.partnerEntity.selectOnly()
608+
..addColumns([_db.partnerEntity.sharedById])
609+
..where(_db.partnerEntity.sharedWithId.equals(currentUserId));
610+
final partnerIds = await partnerQuery.map((row) => row.read(_db.partnerEntity.sharedById)).get();
611+
612+
final validUsers = {currentUserId, ...partnerIds.nonNulls};
613+
614+
// Asset is not owned by the current user or any of their partners and is not part of any (shared) album
615+
// Likely a stale asset that was previously shared but has been removed
616+
await _db.remoteAssetEntity.deleteWhere((asset) {
617+
return asset.ownerId.isNotIn(validUsers) &
618+
asset.id.isNotInQuery(
619+
_db.remoteAlbumAssetEntity.selectOnly()..addColumns([_db.remoteAlbumAssetEntity.assetId]),
620+
);
621+
});
622+
});
623+
} catch (error, stack) {
624+
_logger.severe('Error: pruneAssets', error, stack);
625+
// We do not rethrow here as this is a client-only cleanup and should not affect the sync process
626+
}
627+
}
594628
}
595629

596630
extension on AssetTypeEnum {

0 commit comments

Comments
 (0)