Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #4296 + download UI improvement + fixes #4369

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 51 additions & 38 deletions mobile/lib/services/local_sync_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import "package:photos/utils/debouncer.dart";
import "package:photos/utils/photo_manager_util.dart";
import "package:photos/utils/sqlite_util.dart";
import 'package:shared_preferences/shared_preferences.dart';
import 'package:synchronized/synchronized.dart';
import 'package:tuple/tuple.dart';

class LocalSyncService {
Expand All @@ -31,6 +32,7 @@ class LocalSyncService {
late SharedPreferences _prefs;
Completer<void>? _existingSync;
late Debouncer _changeCallbackDebouncer;
final Lock _lock = Lock();

static const kDbUpdationTimeKey = "db_updation_time";
static const kHasCompletedFirstImportKey = "has_completed_firstImport";
Expand Down Expand Up @@ -77,50 +79,57 @@ class LocalSyncService {
}
_existingSync = Completer<void>();
final int ownerID = Configuration.instance.getUserID()!;
final existingLocalFileIDs = await _db.getExistingLocalFileIDs(ownerID);
_logger.info("${existingLocalFileIDs.length} localIDs were discovered");

// We use a lock to prevent synchronisation to occur while it is downloading
// as this introduces wrong entry in FilesDB due to race condition
// This is a fix for https://github.com/ente-io/ente/issues/4296
await _lock.synchronized(() async {
final existingLocalFileIDs = await _db.getExistingLocalFileIDs(ownerID);
_logger.info("${existingLocalFileIDs.length} localIDs were discovered");

final syncStartTime = DateTime.now().microsecondsSinceEpoch;
final lastDBUpdationTime = _prefs.getInt(kDbUpdationTimeKey) ?? 0;
final startTime = DateTime.now().microsecondsSinceEpoch;
if (lastDBUpdationTime != 0) {
await _loadAndStoreDiff(
existingLocalFileIDs,
fromTime: lastDBUpdationTime,
toTime: syncStartTime,
);
} else {
// Load from 0 - 01.01.2010
Bus.instance.fire(SyncStatusUpdate(SyncStatus.startedFirstGalleryImport));
var startTime = 0;
var toYear = 2010;
var toTime = DateTime(toYear).microsecondsSinceEpoch;
while (toTime < syncStartTime) {
final syncStartTime = DateTime.now().microsecondsSinceEpoch;
final lastDBUpdationTime = _prefs.getInt(kDbUpdationTimeKey) ?? 0;
final startTime = DateTime.now().microsecondsSinceEpoch;
if (lastDBUpdationTime != 0) {
await _loadAndStoreDiff(
existingLocalFileIDs,
fromTime: lastDBUpdationTime,
toTime: syncStartTime,
);
} else {
// Load from 0 - 01.01.2010
Bus.instance.fire(SyncStatusUpdate(SyncStatus.startedFirstGalleryImport));
var startTime = 0;
var toYear = 2010;
var toTime = DateTime(toYear).microsecondsSinceEpoch;
while (toTime < syncStartTime) {
await _loadAndStoreDiff(
existingLocalFileIDs,
fromTime: startTime,
toTime: toTime,
);
startTime = toTime;
toYear++;
toTime = DateTime(toYear).microsecondsSinceEpoch;
}
await _loadAndStoreDiff(
existingLocalFileIDs,
fromTime: startTime,
toTime: toTime,
toTime: syncStartTime,
);
startTime = toTime;
toYear++;
toTime = DateTime(toYear).microsecondsSinceEpoch;
}
await _loadAndStoreDiff(
existingLocalFileIDs,
fromTime: startTime,
toTime: syncStartTime,
);
}
if (!hasCompletedFirstImport()) {
await _prefs.setBool(kHasCompletedFirstImportKey, true);
await _refreshDeviceFolderCountAndCover(isFirstSync: true);
_logger.fine("first gallery import finished");
Bus.instance
.fire(SyncStatusUpdate(SyncStatus.completedFirstGalleryImport));
}
final endTime = DateTime.now().microsecondsSinceEpoch;
final duration = Duration(microseconds: endTime - startTime);
_logger.info("Load took " + duration.inMilliseconds.toString() + "ms");
if (!hasCompletedFirstImport()) {
await _prefs.setBool(kHasCompletedFirstImportKey, true);
await _refreshDeviceFolderCountAndCover(isFirstSync: true);
_logger.fine("first gallery import finished");
Bus.instance
.fire(SyncStatusUpdate(SyncStatus.completedFirstGalleryImport));
}
final endTime = DateTime.now().microsecondsSinceEpoch;
final duration = Duration(microseconds: endTime - startTime);
_logger.info("Load took " + duration.inMilliseconds.toString() + "ms");
});

_existingSync?.complete();
_existingSync = null;
}
Expand Down Expand Up @@ -240,6 +249,10 @@ class LocalSyncService {
}
}

Lock getLock() {
return _lock;
}

bool hasGrantedPermissions() {
return _prefs.getBool(kHasGrantedPermissionsKey) ?? false;
}
Expand Down
2 changes: 2 additions & 0 deletions mobile/lib/ui/tools/editor/video_editor_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,8 @@ class _VideoEditorPageState extends State<VideoEditorPage> {
);
} catch (_) {
await dialog.hide();
} finally {
await PhotoManager.startChangeNotify();
}
}
}
12 changes: 10 additions & 2 deletions mobile/lib/ui/viewer/actions/file_selection_actions_widget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -822,17 +822,25 @@ class _FileSelectionActionsWidgetState
}

Future<void> _download(List<EnteFile> files) async {
final totalFiles = files.length;
int downloadedFiles = 0;

final dialog = createProgressDialog(
context,
S.of(context).downloading,
S.of(context).downloading + " ($downloadedFiles/$totalFiles)",
isDismissible: true,
);
await dialog.show();
try {
final futures = <Future>[];
for (final file in files) {
if (file.localID == null) {
futures.add(downloadToGallery(file));
futures.add(
downloadToGallery(file).then((_) {
downloadedFiles++;
dialog.update(message: S.of(context).downloading + " ($downloadedFiles/$totalFiles)");
}),
);
}
}
await Future.wait(futures);
Expand Down
77 changes: 41 additions & 36 deletions mobile/lib/utils/file_download_util.dart
Original file line number Diff line number Diff line change
Expand Up @@ -189,45 +189,50 @@ Future<void> downloadToGallery(EnteFile file) async {
final bool downloadLivePhotoOnDroid =
type == FileType.livePhoto && Platform.isAndroid;
AssetEntity? savedAsset;
final File? fileToSave = await getFile(file);
//Disabling notifications for assets changing to insert the file into
//files db before triggering a sync.
await PhotoManager.stopChangeNotify();
if (type == FileType.image) {
savedAsset = await PhotoManager.editor
.saveImageWithPath(fileToSave!.path, title: file.title!);
} else if (type == FileType.video) {
savedAsset =
await PhotoManager.editor.saveVideo(fileToSave!, title: file.title!);
} else if (type == FileType.livePhoto) {
final File? liveVideoFile =
await getFileFromServer(file, liveVideo: true);
if (liveVideoFile == null) {
throw AssertionError("Live video can not be null");
// We use a lock to prevent synchronisation to occur while it is downloading
// as this introduces wrong entry in FilesDB due to race condition
// This is a fix for https://github.com/ente-io/ente/issues/4296
await LocalSyncService.instance.getLock().synchronized(() async {
final File? fileToSave = await getFile(file);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can move this outside. This will fetch the file from remote, and decrypt it.

Copy link
Contributor Author

@simondubrulle simondubrulle Dec 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried moving it outside, and it is technically working (it is not triggering this specific issue), but it starts all selected downloads at same time with following effects:

  • app gets very laggy
  • likely to have network issues (I have had time outs and network errors because of too many parallel/open requests). Issues which I did not get with the sequential approach.
  • it should be faster but in my opinion less robust when dowloading lots of files/complete collection.

At the moment I kept it inside as it is solving the issue while not introducing other ones but I leave it up to you to decide based on this feedback.

A further improvement might be to move it outside and limit the number of concurrent downloads, but maybe not part of this fix/PR?

//Disabling notifications for assets changing to insert the file into
//files db before triggering a sync.
await PhotoManager.stopChangeNotify();
if (type == FileType.image) {
savedAsset = await PhotoManager.editor
.saveImageWithPath(fileToSave!.path, title: file.title!);
} else if (type == FileType.video) {
savedAsset =
await PhotoManager.editor.saveVideo(fileToSave!, title: file.title!);
} else if (type == FileType.livePhoto) {
final File? liveVideoFile =
await getFileFromServer(file, liveVideo: true);
if (liveVideoFile == null) {
throw AssertionError("Live video can not be null");
}
if (downloadLivePhotoOnDroid) {
await _saveLivePhotoOnDroid(fileToSave!, liveVideoFile, file);
} else {
savedAsset = await PhotoManager.editor.darwin.saveLivePhoto(
imageFile: fileToSave!,
videoFile: liveVideoFile,
title: file.title!,
);
}
}
if (downloadLivePhotoOnDroid) {
await _saveLivePhotoOnDroid(fileToSave!, liveVideoFile, file);
} else {
savedAsset = await PhotoManager.editor.darwin.saveLivePhoto(
imageFile: fileToSave!,
videoFile: liveVideoFile,
title: file.title!,

if (savedAsset != null) {
file.localID = savedAsset!.id;
await FilesDB.instance.insert(file);
Bus.instance.fire(
LocalPhotosUpdatedEvent(
[file],
source: "download",
),
);
} else if (!downloadLivePhotoOnDroid && savedAsset == null) {
_logger.severe('Failed to save assert of type $type');
}
}

if (savedAsset != null) {
file.localID = savedAsset.id;
await FilesDB.instance.insert(file);
Bus.instance.fire(
LocalPhotosUpdatedEvent(
[file],
source: "download",
),
);
} else if (!downloadLivePhotoOnDroid && savedAsset == null) {
_logger.severe('Failed to save assert of type $type');
}
});
} catch (e) {
_logger.severe("Failed to save file", e);
rethrow;
Expand Down
Loading