Skip to content

Commit

Permalink
fix(mobile): Fix minor issues with downloading assets (#13609)
Browse files Browse the repository at this point in the history
* improve download asset

* fix: download motion photos on ios

---------

Co-authored-by: dvbthien <dvbthien@gmail.com>
Co-authored-by: Alex <alex.tran1502@gmail.com>
  • Loading branch information
3 people authored Oct 20, 2024
1 parent 62e55f3 commit ee0130a
Show file tree
Hide file tree
Showing 8 changed files with 118 additions and 56 deletions.
6 changes: 6 additions & 0 deletions mobile/lib/interfaces/file_media.interface.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ abstract interface class IFileMediaRepository {
String? relativePath,
});

Future<Asset?> saveImageWithFile(
String filePath, {
String? title,
String? relativePath,
});

Future<Asset?> saveVideo(
File file, {
required String title,
Expand Down
2 changes: 1 addition & 1 deletion mobile/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ Future<void> initApp() async {
};

PlatformDispatcher.instance.onError = (error, stack) {
debugPrint("FlutterError - Catch all: $error");
debugPrint("FlutterError - Catch all: $error \n $stack");
log.severe('PlatformDispatcher - Catch all', error, stack);
return true;
};
Expand Down
7 changes: 6 additions & 1 deletion mobile/lib/providers/asset_viewer/download.provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:immich_mobile/extensions/build_context_extensions.dart';
import 'package:immich_mobile/models/download/download_state.model.dart';
import 'package:immich_mobile/models/download/livephotos_medatada.model.dart';
import 'package:immich_mobile/services/album.service.dart';
import 'package:immich_mobile/services/download.service.dart';
import 'package:immich_mobile/entities/asset.entity.dart';
import 'package:immich_mobile/services/share.service.dart';
Expand All @@ -15,10 +16,12 @@ import 'package:immich_mobile/widgets/common/share_dialog.dart';
class DownloadStateNotifier extends StateNotifier<DownloadState> {
final DownloadService _downloadService;
final ShareService _shareService;
final AlbumService _albumService;

DownloadStateNotifier(
this._downloadService,
this._shareService,
this._albumService,
) : super(
DownloadState(
downloadStatus: TaskStatus.complete,
Expand Down Expand Up @@ -76,7 +79,7 @@ class DownloadStateNotifier extends StateNotifier<DownloadState> {

switch (update.status) {
case TaskStatus.complete:
_downloadService.saveImage(update.task);
_downloadService.saveImageWithPath(update.task);
_onDownloadComplete(update.task.taskId);
break;

Expand Down Expand Up @@ -133,6 +136,7 @@ class DownloadStateNotifier extends StateNotifier<DownloadState> {
showProgress: false,
);
}
_albumService.refreshDeviceAlbums();
});
}

Expand Down Expand Up @@ -187,5 +191,6 @@ final downloadStateProvider =
((ref) => DownloadStateNotifier(
ref.watch(downloadServiceProvider),
ref.watch(shareServiceProvider),
ref.watch(albumServiceProvider),
)),
);
14 changes: 14 additions & 0 deletions mobile/lib/repositories/file_media.repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,20 @@ class FileMediaRepository implements IFileMediaRepository {
return AssetMediaRepository.toAsset(entity);
}

@override
Future<Asset?> saveImageWithFile(
String filePath, {
String? title,
String? relativePath,
}) async {
final entity = await PhotoManager.editor.saveImageWithPath(
filePath,
title: title,
relativePath: relativePath,
);
return AssetMediaRepository.toAsset(entity);
}

@override
Future<Asset?> saveLivePhoto({
required File image,
Expand Down
131 changes: 84 additions & 47 deletions mobile/lib/services/download.service.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'dart:io';

import 'package:background_downloader/background_downloader.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:immich_mobile/entities/store.entity.dart';
import 'package:immich_mobile/entities/asset.entity.dart';
Expand All @@ -12,6 +12,7 @@ import 'package:immich_mobile/repositories/download.repository.dart';
import 'package:immich_mobile/repositories/file_media.repository.dart';
import 'package:immich_mobile/services/api.service.dart';
import 'package:immich_mobile/utils/download.dart';
import 'package:logging/logging.dart';

final downloadServiceProvider = Provider(
(ref) => DownloadService(
Expand All @@ -23,6 +24,7 @@ final downloadServiceProvider = Provider(
class DownloadService {
final IDownloadRepository _downloadRepository;
final IFileMediaRepository _fileMediaRepository;
final Logger _log = Logger("DownloadService");
void Function(TaskStatusUpdate)? onImageDownloadStatus;
void Function(TaskStatusUpdate)? onVideoDownloadStatus;
void Function(TaskStatusUpdate)? onLivePhotoDownloadStatus;
Expand Down Expand Up @@ -55,78 +57,100 @@ class DownloadService {
onLivePhotoDownloadStatus?.call(update);
}

Future<bool> saveImage(Task task) async {
Future<bool> saveImageWithPath(Task task) async {
final filePath = await task.filePath();
final title = task.filename;
final relativePath = Platform.isAndroid ? 'DCIM/Immich' : null;
final data = await File(filePath).readAsBytes();

final Asset? resultAsset = await _fileMediaRepository.saveImage(
data,
title: title,
relativePath: relativePath,
);

return resultAsset != null;
try {
final Asset? resultAsset = await _fileMediaRepository.saveImageWithFile(
filePath,
title: title,
relativePath: relativePath,
);
return resultAsset != null;
} catch (error, stack) {
_log.severe("Error saving image", error, stack);
return false;
} finally {
if (await File(filePath).exists()) {
await File(filePath).delete();
}
}
}

Future<bool> saveVideo(Task task) async {
final filePath = await task.filePath();
final title = task.filename;
final relativePath = Platform.isAndroid ? 'DCIM/Immich' : null;
final file = File(filePath);

final Asset? resultAsset = await _fileMediaRepository.saveVideo(
file,
title: title,
relativePath: relativePath,
);

return resultAsset != null;
try {
final Asset? resultAsset = await _fileMediaRepository.saveVideo(
file,
title: title,
relativePath: relativePath,
);
return resultAsset != null;
} catch (error, stack) {
_log.severe("Error saving video", error, stack);
return false;
} finally {
if (await file.exists()) {
await file.delete();
}
}
}

Future<bool> saveLivePhotos(
Task task,
String livePhotosId,
) async {
try {
final records = await _downloadRepository.getLiveVideoTasks();
if (records.length < 2) {
return false;
}

final imageRecord = records.firstWhere(
(record) {
final metadata = LivePhotosMetadata.fromJson(record.task.metaData);
return metadata.id == livePhotosId &&
metadata.part == LivePhotosPart.image;
},
);

final videoRecord = records.firstWhere((record) {
final metadata = LivePhotosMetadata.fromJson(record.task.metaData);
return metadata.id == livePhotosId &&
metadata.part == LivePhotosPart.video;
});
final records = await _downloadRepository.getLiveVideoTasks();
if (records.length < 2) {
return false;
}

final imageFilePath = await imageRecord.task.filePath();
final videoFilePath = await videoRecord.task.filePath();
final imageRecord =
_findTaskRecord(records, livePhotosId, LivePhotosPart.image);
final videoRecord =
_findTaskRecord(records, livePhotosId, LivePhotosPart.video);
final imageFilePath = await imageRecord.task.filePath();
final videoFilePath = await videoRecord.task.filePath();

final resultAsset = await _fileMediaRepository.saveLivePhoto(
try {
final result = await _fileMediaRepository.saveLivePhoto(
image: File(imageFilePath),
video: File(videoFilePath),
title: task.filename,
);

return result != null;
} on PlatformException catch (error, stack) {
// Handle saving MotionPhotos on iOS
if (error.code == 'PHPhotosErrorDomain (-1)') {
final result = await _fileMediaRepository
.saveImageWithFile(imageFilePath, title: task.filename);
return result != null;
}
_log.severe("Error saving live photo", error, stack);
return false;
} catch (error, stack) {
_log.severe("Error saving live photo", error, stack);
return false;
} finally {
final imageFile = File(imageFilePath);
if (await imageFile.exists()) {
await imageFile.delete();
}

final videoFile = File(videoFilePath);
if (await videoFile.exists()) {
await videoFile.delete();
}

await _downloadRepository.deleteRecordsWithIds([
imageRecord.task.taskId,
videoRecord.task.taskId,
]);

return resultAsset != null;
} catch (error) {
debugPrint("Error saving live photo: $error");
return false;
}
}

Expand All @@ -151,7 +175,9 @@ class DownloadService {
await _downloadRepository.download(
_buildDownloadTask(
asset.livePhotoVideoId!,
asset.fileName.toUpperCase().replaceAll(".HEIC", '.MOV'),
asset.fileName
.toUpperCase()
.replaceAll(RegExp(r"\.(JPG|HEIC)$"), '.MOV'),
group: downloadGroupLivePhoto,
metadata: LivePhotosMetadata(
part: LivePhotosPart.video,
Expand Down Expand Up @@ -191,3 +217,14 @@ class DownloadService {
);
}
}

TaskRecord _findTaskRecord(
List<TaskRecord> records,
String livePhotosId,
LivePhotosPart part,
) {
return records.firstWhere((record) {
final metadata = LivePhotosMetadata.fromJson(record.task.metaData);
return metadata.id == livePhotosId && metadata.part == part;
});
}
2 changes: 1 addition & 1 deletion mobile/lib/widgets/forms/login/login_form.dart
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ class LoginForm extends HookConsumerWidget {
populateTestLoginInfo1() {
usernameController.text = 'testuser@email.com';
passwordController.text = 'password';
serverEndpointController.text = 'http://192.168.1.118:2283/api';
serverEndpointController.text = 'http://10.1.15.216:2283/api';
}

login() async {
Expand Down
8 changes: 4 additions & 4 deletions mobile/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1211,18 +1211,18 @@ packages:
dependency: "direct main"
description:
name: photo_manager
sha256: "32a1ce1095aeaaa792a29f28c1f74613aa75109f21c2d4ab85be3ad9964230a4"
sha256: "70159eee32203e8162d49d588232f0299ed3f383c63eef1e899cb6b83dee6b26"
url: "https://pub.dev"
source: hosted
version: "3.5.0"
version: "3.5.1"
photo_manager_image_provider:
dependency: "direct main"
description:
name: photo_manager_image_provider
sha256: "38ef1023dc11de3a8669f16e7c981673b3c5cfee715d17120f4b87daa2cdd0af"
sha256: b6015b67b32f345f57cf32c126f871bced2501236c405aafaefa885f7c821e4f
url: "https://pub.dev"
source: hosted
version: "2.1.1"
version: "2.2.0"
platform:
dependency: transitive
description:
Expand Down
4 changes: 2 additions & 2 deletions mobile/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ dependencies:
sdk: flutter

path_provider_ios:
photo_manager: ^3.5.0
photo_manager_image_provider: ^2.1.1
photo_manager: ^3.5.1
photo_manager_image_provider: ^2.2.0
flutter_hooks: ^0.20.4
hooks_riverpod: ^2.4.9
riverpod_annotation: ^2.3.3
Expand Down

0 comments on commit ee0130a

Please sign in to comment.