ente/lib/services/sync_service.dart

309 lines
10 KiB
Dart
Raw Normal View History

2020-03-30 14:28:46 +00:00
import 'dart:async';
import 'dart:math';
2020-03-30 14:28:46 +00:00
2020-05-02 16:28:54 +00:00
import 'package:logging/logging.dart';
import 'package:photos/core/event_bus.dart';
2020-07-20 11:03:09 +00:00
import 'package:photos/db/files_db.dart';
import 'package:photos/events/photo_upload_event.dart';
import 'package:photos/events/user_authenticated_event.dart';
import 'package:photos/services/collections_service.dart';
2020-10-03 17:58:26 +00:00
import 'package:photos/utils/file_downloader.dart';
import 'package:photos/repositories/file_repository.dart';
2020-03-24 19:59:36 +00:00
import 'package:photo_manager/photo_manager.dart';
2020-10-03 17:58:26 +00:00
import 'package:photos/utils/file_uploader.dart';
import 'package:photos/models/file_type.dart';
import 'package:photos/utils/file_name_util.dart';
2020-03-24 19:59:36 +00:00
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
2020-06-19 23:03:26 +00:00
import 'package:photos/models/file.dart';
2020-03-26 14:39:31 +00:00
import 'package:photos/core/configuration.dart';
2020-04-30 15:09:41 +00:00
2020-10-03 17:58:26 +00:00
class SyncService {
2020-05-02 16:28:54 +00:00
final _logger = Logger("PhotoSyncManager");
2020-03-28 13:56:06 +00:00
final _dio = Dio();
2020-07-20 11:03:09 +00:00
final _db = FilesDB.instance;
2020-10-21 16:20:41 +00:00
final _uploader = FileUploader.instance;
2020-10-28 15:45:05 +00:00
final _collectionsService = CollectionsService.instance;
final _downloader = DiffFetcher();
2020-04-30 15:09:41 +00:00
bool _isSyncInProgress = false;
bool _syncStopRequested = false;
Future<void> _existingSync;
SharedPreferences _prefs;
2020-04-27 13:02:29 +00:00
2020-10-28 15:45:05 +00:00
static final _collectionSyncTimeKeyPrefix = "collection_sync_time_";
2020-08-11 23:04:16 +00:00
static final _dbUpdationTimeKey = "db_updation_time";
2020-05-17 10:18:09 +00:00
static final _diffLimit = 100;
2020-03-24 19:59:36 +00:00
2020-10-03 17:58:26 +00:00
SyncService._privateConstructor() {
2020-04-30 15:09:41 +00:00
Bus.instance.on<UserAuthenticatedEvent>().listen((event) {
sync();
});
}
2020-10-03 17:58:26 +00:00
static final SyncService instance = SyncService._privateConstructor();
2020-03-28 13:56:06 +00:00
Future<void> init() async {
_prefs = await SharedPreferences.getInstance();
}
2020-04-30 15:09:41 +00:00
Future<void> sync() async {
_syncStopRequested = false;
2020-04-30 15:09:41 +00:00
if (_isSyncInProgress) {
2020-05-02 16:28:54 +00:00
_logger.warning("Sync already in progress, skipping.");
return _existingSync;
2020-04-27 13:02:29 +00:00
}
2020-04-30 15:09:41 +00:00
_isSyncInProgress = true;
_existingSync = Future<void>(() async {
_logger.info("Syncing...");
try {
await _doSync();
2020-10-28 15:25:32 +00:00
} catch (e, s) {
_logger.severe(e, s);
} finally {
_isSyncInProgress = false;
}
});
return _existingSync;
}
2020-04-30 15:09:41 +00:00
void stopSync() {
_logger.info("Sync stop requested");
_syncStopRequested = true;
}
bool shouldStopSync() {
return _syncStopRequested;
}
bool hasScannedDisk() {
2020-08-11 23:04:16 +00:00
return _prefs.containsKey(_dbUpdationTimeKey);
2020-06-15 19:57:48 +00:00
}
Future<void> _doSync() async {
2020-07-27 21:07:56 +00:00
final result = await PhotoManager.requestPermission();
if (!result) {
_logger.severe("Did not get permission");
}
final syncStartTime = DateTime.now().microsecondsSinceEpoch;
2020-08-11 23:04:16 +00:00
var lastDBUpdationTime = _prefs.getInt(_dbUpdationTimeKey);
if (lastDBUpdationTime == null) {
lastDBUpdationTime = 0;
2020-03-30 14:28:46 +00:00
}
2020-04-24 12:40:24 +00:00
2020-06-17 11:52:31 +00:00
final pathEntities =
await _getGalleryList(lastDBUpdationTime, syncStartTime);
2020-06-19 23:03:26 +00:00
final files = List<File>();
AssetPathEntity recents;
2020-04-24 12:40:24 +00:00
for (AssetPathEntity pathEntity in pathEntities) {
if (pathEntity.name == "Recent" || pathEntity.name == "Recents") {
recents = pathEntity;
} else {
await _addToPhotos(pathEntity, lastDBUpdationTime, files);
2020-03-30 14:28:46 +00:00
}
2020-03-28 13:56:06 +00:00
}
if (recents != null) {
await _addToPhotos(recents, lastDBUpdationTime, files);
}
2020-07-27 20:43:11 +00:00
files.sort(
(first, second) => first.creationTime.compareTo(second.creationTime));
await _insertFilesToDB(files, syncStartTime);
await FileRepository.instance.reloadFiles();
2020-10-30 20:37:21 +00:00
await syncWithRemote();
2020-04-24 12:40:24 +00:00
}
2020-06-17 11:52:31 +00:00
Future<List<AssetPathEntity>> _getGalleryList(
final int fromTimestamp, final int toTimestamp) async {
final filterOptionGroup = FilterOptionGroup();
filterOptionGroup.setOption(AssetType.image, FilterOption(needTitle: true));
2020-06-19 23:03:26 +00:00
filterOptionGroup.setOption(AssetType.video, FilterOption(needTitle: true));
2020-10-30 18:10:45 +00:00
filterOptionGroup.createTimeCond = DateTimeCond(
2020-06-17 11:52:31 +00:00
min: DateTime.fromMicrosecondsSinceEpoch(fromTimestamp),
max: DateTime.fromMicrosecondsSinceEpoch(toTimestamp),
);
2020-07-27 18:01:42 +00:00
final galleryList = await PhotoManager.getAssetPathList(
2020-06-17 11:52:31 +00:00
hasAll: true,
2020-06-19 23:03:26 +00:00
type: RequestType.common,
2020-06-17 11:52:31 +00:00
filterOption: filterOptionGroup,
);
galleryList.sort((s1, s2) {
return s2.assetCount.compareTo(s1.assetCount);
});
return galleryList;
}
Future _addToPhotos(AssetPathEntity pathEntity, int lastDBUpdationTime,
2020-06-19 23:03:26 +00:00
List<File> files) async {
final assetList = await pathEntity.assetList;
for (AssetEntity entity in assetList) {
if (max(entity.createDateTime.microsecondsSinceEpoch,
entity.modifiedDateTime.microsecondsSinceEpoch) >
lastDBUpdationTime) {
try {
2020-06-19 23:03:26 +00:00
final file = await File.fromAsset(pathEntity, entity);
if (!files.contains(file)) {
files.add(file);
}
} catch (e) {
_logger.severe(e);
}
}
}
}
2020-10-30 20:37:21 +00:00
Future<void> syncWithRemote() async {
if (!Configuration.instance.hasConfiguredAccount()) {
return Future.error("Account not configured yet");
}
2020-10-28 15:45:05 +00:00
await _collectionsService.sync();
final collections = _collectionsService.getCollections();
for (final collection in collections) {
await _fetchEncryptedFilesDiff(collection.id);
}
await _uploadDiff();
await _deletePhotosOnServer();
}
2020-10-28 15:45:05 +00:00
Future<void> _fetchEncryptedFilesDiff(int collectionID) async {
final diff = await _downloader.getEncryptedFilesDiff(
2020-10-28 15:45:05 +00:00
collectionID,
_getCollectionSyncTime(collectionID),
_diffLimit,
);
2020-09-03 16:50:26 +00:00
if (diff.isNotEmpty) {
2020-10-28 15:45:05 +00:00
await _storeDiff(diff, collectionID);
2020-08-11 23:04:16 +00:00
FileRepository.instance.reloadFiles();
if (diff.length == _diffLimit) {
2020-10-28 15:45:05 +00:00
return await _fetchEncryptedFilesDiff(collectionID);
2020-08-11 23:04:16 +00:00
}
}
}
2020-10-28 15:45:05 +00:00
int _getCollectionSyncTime(int collectionID) {
var syncTime =
_prefs.getInt(_collectionSyncTimeKeyPrefix + collectionID.toString());
2020-08-11 23:04:16 +00:00
if (syncTime == null) {
syncTime = 0;
}
return syncTime;
}
2020-10-28 15:45:05 +00:00
Future<void> _setCollectionSyncTime(int collectionID, int time) async {
return _prefs.setInt(
_collectionSyncTimeKeyPrefix + collectionID.toString(), time);
}
Future<void> _uploadDiff() async {
final foldersToBackUp = Configuration.instance.getPathsToBackUp();
2020-09-17 18:48:25 +00:00
List<File> filesToBeUploaded =
await _db.getFilesToBeUploadedWithinFolders(foldersToBackUp);
for (int i = 0; i < filesToBeUploaded.length; i++) {
if (_syncStopRequested) {
_syncStopRequested = false;
Bus.instance.fire(PhotoUploadEvent(wasStopped: true));
return;
}
2020-09-17 18:48:25 +00:00
File file = filesToBeUploaded[i];
if (file.fileType == FileType.video) {
continue;
}
2020-05-17 12:39:38 +00:00
try {
2020-10-21 16:20:41 +00:00
file.collectionID = (await CollectionsService.instance
.getOrCreateForPath(file.deviceFolder))
.id;
final existingFile = await _db.getFile(file.generatedID);
if (existingFile.uploadedFileID != null) {
// The file was uploaded outside this loop
// Eg: Addition to an album or favorites
await CollectionsService.instance
.addToCollection(file.collectionID, [existingFile]);
2020-10-24 20:12:14 +00:00
} else if (_uploader.getCurrentUploadStatus(file.generatedID) != null) {
// The file is currently being uploaded outside this loop
// Eg: Addition to an album or favorites
await _uploader.getCurrentUploadStatus(file.generatedID);
await CollectionsService.instance
.addToCollection(file.collectionID, [existingFile]);
2020-08-10 23:47:22 +00:00
} else {
final uploadedFile = await _uploader.encryptAndUploadFile(file);
await _db.update(uploadedFile);
2020-08-10 23:47:22 +00:00
}
Bus.instance.fire(PhotoUploadEvent(
2020-09-17 18:48:25 +00:00
completed: i + 1, total: filesToBeUploaded.length));
2020-05-17 12:39:38 +00:00
} catch (e) {
Bus.instance.fire(PhotoUploadEvent(hasError: true));
throw e;
2020-04-13 15:01:27 +00:00
}
2020-03-26 14:39:31 +00:00
}
}
2020-10-28 15:45:05 +00:00
Future _storeDiff(List<File> diff, int collectionID) async {
2020-06-19 23:03:26 +00:00
for (File file in diff) {
final existingFiles = await _db.getMatchingFiles(file.title,
file.deviceFolder, file.creationTime, file.modificationTime,
alternateTitle: getHEICFileNameForJPG(file));
if (existingFiles == null) {
// File uploaded from a different device
file.localID = null;
await _db.insert(file);
} else {
// File exists on device
bool wasUploadedOnAPreviousInstallation =
existingFiles.length == 1 && existingFiles[0].collectionID == null;
file.localID = existingFiles[0]
.localID; // File should ideally have the same localID
if (wasUploadedOnAPreviousInstallation) {
file.generatedID = existingFiles[0].generatedID;
await _db.update(file);
} else {
bool wasUpdatedInExistingCollection = false;
for (final existingFile in existingFiles) {
if (file.collectionID == existingFile.collectionID) {
file.generatedID = existingFile.generatedID;
wasUpdatedInExistingCollection = true;
break;
}
}
if (wasUpdatedInExistingCollection) {
await _db.update(file);
} else {
// Added to a new collection
await _db.insert(file);
}
}
}
2020-10-28 15:45:05 +00:00
await _setCollectionSyncTime(collectionID, file.updationTime);
2020-03-28 13:56:06 +00:00
}
}
2020-03-26 14:39:31 +00:00
Future<void> _deletePhotosOnServer() async {
2020-06-19 23:03:26 +00:00
return _db.getAllDeleted().then((deletedPhotos) async {
for (File deletedPhoto in deletedPhotos) {
await _deleteFileOnServer(deletedPhoto);
await _db.delete(deletedPhoto);
2020-04-12 12:38:49 +00:00
}
});
}
2020-06-19 23:03:26 +00:00
Future<void> _deleteFileOnServer(File file) async {
2020-05-17 10:18:09 +00:00
return _dio
.delete(
Configuration.instance.getHttpEndpoint() +
"/files/" +
2020-08-09 22:34:59 +00:00
file.uploadedFileID.toString(),
2020-05-17 10:18:09 +00:00
options: Options(
headers: {"X-Auth-Token": Configuration.instance.getToken()}),
)
.catchError((e) => _logger.severe(e));
2020-03-29 14:04:26 +00:00
}
2020-04-11 22:29:09 +00:00
Future<bool> _insertFilesToDB(List<File> files, int timestamp) async {
2020-06-19 23:03:26 +00:00
await _db.insertMultiple(files);
_logger.info("Inserted " + files.length.toString() + " files.");
2020-08-11 23:04:16 +00:00
return await _prefs.setInt(_dbUpdationTimeKey, timestamp);
2020-04-11 22:29:09 +00:00
}
2020-03-24 19:59:36 +00:00
}