π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
fix: Cancel streaming FFmpeg and network requests on logout
Prateek Sunal0d4bfd1a766e
diff --git a/mobile/apps/photos/lib/core/configuration.dart b/mobile/apps/photos/lib/core/configuration.dartindex e0ed91a61b..d5cc2ef1b6 100644--- a/mobile/apps/photos/lib/core/configuration.dart+++ b/mobile/apps/photos/lib/core/configuration.dart@@ -191,10 +191,7 @@ class Configuration {Future<void> logout({bool autoLogout = false}) async {_logger.info("Logging out, autoLogout: $autoLogout");-- // Stop streaming service on logoutunawaited(VideoPreviewService.instance.stopForLogout());-if (!autoLogout) {if (SyncService.instance.isSyncInProgress()) {SyncService.instance.stopSync();diff --git a/mobile/apps/photos/lib/services/home_widget_service.dart b/mobile/apps/photos/lib/services/home_widget_service.dartindex 7ab95330be..cb08bab415 100644--- a/mobile/apps/photos/lib/services/home_widget_service.dart+++ b/mobile/apps/photos/lib/services/home_widget_service.dart@@ -235,10 +235,8 @@ class HomeWidgetService {final String widgetPath = '$widgetParent/$WIDGET_DIRECTORY';final dir = Directory(widgetPath);- if (await dir.exists()) {- await dir.delete(recursive: true);- _logger.info("Widget directory cleared successfully");- }+ await dir.delete(recursive: true);+ _logger.info("Widget directory cleared successfully");} catch (e) {_logger.severe("Failed to clear widget directory", e);}diff --git a/mobile/apps/photos/lib/services/isolated_ffmpeg_service.dart b/mobile/apps/photos/lib/services/isolated_ffmpeg_service.dartindex d7aada39bf..5be63483fc 100644--- a/mobile/apps/photos/lib/services/isolated_ffmpeg_service.dart+++ b/mobile/apps/photos/lib/services/isolated_ffmpeg_service.dart@@ -12,46 +12,34 @@ class IsolatedFfmpegService {static final IsolatedFfmpegService instance =IsolatedFfmpegService._privateConstructor();- /// Legacy helper for FFmpeg without session tracking.Future<Map> runFfmpeg(String command) async {final rootIsolateToken = RootIsolateToken.instance!;return await Isolate.run<Map>(() => _ffmpegRun(command, rootIsolateToken));}- /// Run FFmpeg in an isolate with session ID callback for cancellation support.- /// The [onSessionStarted] callback is called immediately when FFmpeg starts,- /// allowing the caller to track the session ID for potential cancellation.- Future<Map> runFfmpegWithSessionTracking(- String command, {- required void Function(int sessionId) onSessionStarted,- }) async {+ /// Run FFmpeg with session ID callback for cancellation support.+ Future<Map> runFfmpegCancellable(+ String command,+ void Function(int sessionId) onSessionStarted,+ ) async {final rootIsolateToken = RootIsolateToken.instance!;- final receivePort = ReceivePort();-- await Isolate.spawn(- _ffmpegRunWithPort,- _FfmpegPortParams(- command: command,- sendPort: receivePort.sendPort,- rootIsolateToken: rootIsolateToken,- ),- );-+ final port = ReceivePort();final completer = Completer<Map>();- receivePort.listen((message) {- if (message is _SessionStartedMessage) {- // Session ID received - notify caller for tracking- onSessionStarted(message.sessionId);- } else if (message is _FfmpegResultMessage) {- // FFmpeg completed - return result and close port- if (!completer.isCompleted) {- completer.complete(message.result);- }- receivePort.close();+ port.listen((msg) {+ if (msg is int) {+ onSessionStarted(msg);+ } else if (msg is Map) {+ completer.complete(msg);+ port.close();}});+ await Isolate.spawn(+ _ffmpegRunCancellable,+ (command, port.sendPort, rootIsolateToken),+ );+return completer.future;}@@ -61,31 +49,6 @@ class IsolatedFfmpegService {}}-/// Parameters for FFmpeg execution with port communication-class _FfmpegPortParams {- final String command;- final SendPort sendPort;- final RootIsolateToken rootIsolateToken;-- _FfmpegPortParams({- required this.command,- required this.sendPort,- required this.rootIsolateToken,- });-}--/// Message sent when FFmpeg session starts-class _SessionStartedMessage {- final int sessionId;- _SessionStartedMessage(this.sessionId);-}--/// Message sent when FFmpeg completes-class _FfmpegResultMessage {- final Map result;- _FfmpegResultMessage(this.result);-}-@pragma('vm:entry-point')Future<Map> _getVideoProps(String filePath,@@ -113,42 +76,25 @@ Future<Map> _ffmpegRun(String value, RootIsolateToken rootIsolateToken) async {return {"returnCode": returnCode?.getValue(),"output": output,- "sessionId": session.getSessionId(),};}-/// FFmpeg execution with port-based session ID communication.-/// Sends session ID immediately when FFmpeg starts, then sends result when done.@pragma('vm:entry-point')-Future<void> _ffmpegRunWithPort(_FfmpegPortParams params) async {- BackgroundIsolateBinaryMessenger.ensureInitialized(params.rootIsolateToken);+Future<void> _ffmpegRunCancellable(+ (String, SendPort, RootIsolateToken) params,+) async {+ final (command, sendPort, token) = params;+ BackgroundIsolateBinaryMessenger.ensureInitialized(token);final completer = Completer<Map>();+ final session = await FFmpegKit.executeAsync(command, (s) async {+ completer.complete({+ "returnCode": (await s.getReturnCode())?.getValue(),+ "output": await s.getOutput(),+ });+ });- // Use executeAsync to get session ID immediately- final session = await FFmpegKit.executeAsync(- params.command,- (completedSession) async {- final returnCode = await completedSession.getReturnCode();- final output = await completedSession.getOutput();-- completer.complete({- "returnCode": returnCode?.getValue(),- "output": output,- "sessionId": completedSession.getSessionId(),- });- },- );-- // Send session ID immediately for tracking/cancellationfinal sessionId = session.getSessionId();- if (sessionId != null) {- params.sendPort.send(_SessionStartedMessage(sessionId));- }-- // Wait for FFmpeg to complete- final result = await completer.future;-- // Send result back to main isolate- params.sendPort.send(_FfmpegResultMessage(result));+ if (sessionId != null) sendPort.send(sessionId);+ sendPort.send(await completer.future);}diff --git a/mobile/apps/photos/lib/services/video_preview_service.dart b/mobile/apps/photos/lib/services/video_preview_service.dartindex 3712c0a4ca..123a3c547e 100644--- a/mobile/apps/photos/lib/services/video_preview_service.dart+++ b/mobile/apps/photos/lib/services/video_preview_service.dart@@ -95,13 +95,9 @@ class VideoPreviewService {VideoPreviewService._privateConstructor();int uploadingFileId = -1;-- // Streaming cancellation fieldsCancelToken? _streamingCancelToken;bool _stopRequested = false;-- // Track active streaming FFmpeg sessions for targeted cancellation- final Set<int> _activeStreamingSessionIds = {};+ int? _currentFfmpegSessionId;final Configuration config;final ServiceLocator serviceLocator;@@ -143,33 +139,14 @@ class VideoPreviewService {_items.clear();}- /// Stop streaming for logoutFuture<void> stopForLogout() async {- _logger.info(- "Stopping streaming for logout - "- "uploading: ${uploadingFileId >= 0}, "- "queue: ${fileQueue.length}",- );_stopRequested = true;- _streamingCancelToken?.cancel("logout");+ _streamingCancelToken?.cancel();_streamingCancelToken = null;-- // Cancel only streaming FFmpeg sessions (not video editor, etc.)- if (_activeStreamingSessionIds.isNotEmpty) {- _logger.info(- "Cancelling ${_activeStreamingSessionIds.length} streaming FFmpeg session(s): $_activeStreamingSessionIds",- );-- for (final sessionId in _activeStreamingSessionIds.toList()) {- await FFmpegKit.cancel(sessionId);- _logger.info("Sent cancel to FFmpeg session $sessionId");- }-- _activeStreamingSessionIds.clear();- } else {- _logger.info("No active streaming FFmpeg sessions to cancel");+ if (_currentFfmpegSessionId != null) {+ await FFmpegKit.cancel(_currentFfmpegSessionId!);+ _currentFfmpegSessionId = null;}-uploadingFileId = -1;clearQueue();computeController.releaseCompute(stream: true);@@ -179,27 +156,6 @@ class VideoPreviewService {Bus.instance.fire(VideoPreviewStateChangedEvent(fileId, status));}- /// Run FFmpeg command in isolate with session tracking for targeted cancellation.- /// This ensures only streaming sessions are cancelled, not video editor etc.- /// Uses isolate-based execution for performance while tracking session IDs.- Future<Map<String, dynamic>> _runStreamingFfmpeg(String command) async {- final result = await ffmpegService.runFfmpegWithSessionTracking(- command,- onSessionStarted: (sessionId) {- _activeStreamingSessionIds.add(sessionId);- _logger.fine("Started streaming FFmpeg session $sessionId (isolate)");- },- );-- // Remove session ID when FFmpeg completes- final sessionId = result["sessionId"] as int?;- if (sessionId != null) {- _activeStreamingSessionIds.remove(sessionId);- }-- return Map<String, dynamic>.from(result);- }-// Return value indicates file was successfully added to queue or notFuture<bool> addToManualQueue(EnteFile file, String queueType) async {if (file.uploadedFileID == null) return false;@@ -364,11 +320,7 @@ class VideoPreviewService {// not used currentlybool forceUpload = false,}) async {- if (_stopRequested) {- _logger.fine("Aborting streaming - stop was requested");- return;- }-+ if (_stopRequested) return;_streamingCancelToken ??= CancelToken();// Check if file upload is happening before processing video for streaming@@ -573,25 +525,24 @@ class VideoPreviewService {_logger.info(command);- final playlistGenResult = await _runStreamingFfmpeg(- '-i "${file.path}" ' +- // main params for streaming- command +- // output file path- '$prefix/output.m3u8',- ).onError((error, stackTrace) {+ final playlistGenResult = await ffmpegService+ .runFfmpegCancellable(+ '-i "${file.path}" $command$prefix/output.m3u8',+ (id) => _currentFfmpegSessionId = id,+ )+ .onError((error, stackTrace) {_logger.warning("FFmpeg command failed", error, stackTrace);- return <String, dynamic>{};+ return {};});-- final playlistGenReturnCode = playlistGenResult["returnCode"] as int?;+ _currentFfmpegSessionId = null;if (_stopRequested) {- _logger.fine("Aborting streaming - stop requested after FFmpeg");Directory(prefix).delete(recursive: true).ignore();return;}+ final playlistGenReturnCode = playlistGenResult["returnCode"] as int?;+String? objectId;int? objectSize;@@ -618,15 +569,17 @@ class VideoPreviewService {objectSize = result.$2;// Fetch resolution of generated stream by decrypting a single frame- final playlistFrameResult = await _runStreamingFfmpeg(+ final playlistFrameResult = await ffmpegService+ .runFfmpeg('-allowed_extensions ALL -i "$prefix/output.m3u8" -frames:v 1 -c copy "$prefix/frame.ts"',- ).onError((error, stackTrace) {+ )+ .onError((error, stackTrace) {_logger.warning(- "FFmpeg command failed for frame",+ "FFmpeg frame extraction failed",error,stackTrace,);- return <String, dynamic>{};+ return {};});final playlistFrameReturnCode =playlistFrameResult["returnCode"] as int?;@@ -840,7 +793,6 @@ class VideoPreviewService {}) async {_logger.fine("Pushing playlist for ${file.uploadedFileID}");try {- final token = _streamingCancelToken;final encryptionKey = getFileKey(file);final playlistContent = playlist.readAsStringSync();final result = await gzipAndEncryptJson(@@ -862,7 +814,7 @@ class VideoPreviewService {"playlist": result.encData,"playlistHeader": result.header,},- cancelToken: token,+ cancelToken: _streamingCancelToken,);} catch (e, s) {_logger.severe("Failed to report video preview", e, s);@@ -873,14 +825,13 @@ class VideoPreviewService {Future<(String, int)> _uploadPreviewVideo(EnteFile file, File preview) async {_logger.fine("Pushing preview for $file");try {- final token = _streamingCancelToken;final response = await serviceLocator.enteDio.get("/files/data/preview-upload-url",queryParameters: {"fileID": file.uploadedFileID!,"type": "vid_preview",},- cancelToken: token,+ cancelToken: _streamingCancelToken,);final uploadURL = response.data["url"];final String objectID = response.data["objectID"];@@ -889,7 +840,7 @@ class VideoPreviewService {uploadURL,data: preview.openRead(),options: Options(headers: {Headers.contentLengthHeader: objectSize}),- cancelToken: token,+ cancelToken: _streamingCancelToken,);return (objectID, objectSize);} catch (e) {@@ -1350,9 +1301,7 @@ class VideoPreviewService {bool forceProcess = false,}) {Future.delayed(duration, () async {- // Reset stop flag for new streaming session_stopRequested = false;-if (_hasQueuedFile && !forceProcess) return;// Don't start streaming if file uploads are in progress