From 59cc3ef19aa6de23f6dbbea675704aeb72c3dcab Mon Sep 17 00:00:00 2001 From: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Date: Wed, 21 Oct 2026 00:40:44 -0700 Subject: [PATCH 1/3] fix: make photo editing available from the viewer menu The viewer menu now shows Edit for an image Quick Look can modify when the device is online or the file is already stored locally, and the file context menu uses that same Edit title. A file already on the device still opens through the downloaded-file notification; otherwise, while online, the photo is marked for download with the Quick Look selector and the download is started. Unit tests check that an online preview-only image offers one Edit action and that building the menu leaves it undownloaded, and that a web view, a non-image, and an encrypted photo offer none. The new test file is included in the unit test target. Fixes #4332 Assisted-by: AI Signed-off-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> --- Nextcloud.xcodeproj/project.pbxproj | 4 + .../NCContextMenuViewerTests.swift | 131 ++++++++++++++++++ iOSClient/Menu/NCContextMenuMain.swift | 2 +- iOSClient/Menu/NCContextMenuViewer.swift | 38 +++-- 4 files changed, 161 insertions(+), 14 deletions(-) create mode 100644 Tests/NextcloudUnitTests/NCContextMenuViewerTests.swift diff --git a/Nextcloud.xcodeproj/project.pbxproj b/Nextcloud.xcodeproj/project.pbxproj index 6f72f1e2c2..d7243cd62f 100644 --- a/Nextcloud.xcodeproj/project.pbxproj +++ b/Nextcloud.xcodeproj/project.pbxproj @@ -71,6 +71,7 @@ AB7000042F70000100FE2776 /* NCShareDetailsGovernanceModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB7000032F70000100FE2776 /* NCShareDetailsGovernanceModel.swift */; }; AB7000062F70000100FE2776 /* NCGovernanceLabelSelectorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB7000052F70000100FE2776 /* NCGovernanceLabelSelectorView.swift */; }; AC13ADAF2026101300000002 /* NCMediaAdaptiveLayoutViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC13ADAF2026101300000001 /* NCMediaAdaptiveLayoutViewTests.swift */; }; + B1E071012026102100000002 /* NCContextMenuViewerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1E071012026102100000001 /* NCContextMenuViewerTests.swift */; }; AC14ADAF2026101400000002 /* NCMediaAdaptiveControlsLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC14ADAF2026101400000001 /* NCMediaAdaptiveControlsLayout.swift */; }; AC14ADAF2026101400000012 /* NCMediaViewerPreviewLoader.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC14ADAF2026101400000011 /* NCMediaViewerPreviewLoader.swift */; }; AF1A9B6427D0CA1E00F17A9E /* UIAlertController+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF1A9B6327D0CA1E00F17A9E /* UIAlertController+Extension.swift */; }; @@ -1442,6 +1443,7 @@ AB7000032F70000100FE2776 /* NCShareDetailsGovernanceModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NCShareDetailsGovernanceModel.swift; sourceTree = ""; }; AB7000052F70000100FE2776 /* NCGovernanceLabelSelectorView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NCGovernanceLabelSelectorView.swift; sourceTree = ""; }; AC13ADAF2026101300000001 /* NCMediaAdaptiveLayoutViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCMediaAdaptiveLayoutViewTests.swift; sourceTree = ""; }; + B1E071012026102100000001 /* NCContextMenuViewerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCContextMenuViewerTests.swift; sourceTree = ""; }; AC14ADAF2026101400000001 /* NCMediaAdaptiveControlsLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCMediaAdaptiveControlsLayout.swift; sourceTree = ""; }; AC14ADAF2026101400000011 /* NCMediaViewerPreviewLoader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCMediaViewerPreviewLoader.swift; sourceTree = ""; }; AF1A9B6327D0CA1E00F17A9E /* UIAlertController+Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIAlertController+Extension.swift"; sourceTree = ""; }; @@ -2401,6 +2403,7 @@ 439616AAA50F4360A761E5EF /* NCAlbumsPersistenceTests.swift */, C0DECA012F65000100C0D001 /* NCCameraRollTests.swift */, 4B74B947E07444CC9CFE0A6C /* NCDocumentEditorSupportTests.swift */, + B1E071012026102100000001 /* NCContextMenuViewerTests.swift */, ); path = NextcloudUnitTests; sourceTree = ""; @@ -4866,6 +4869,7 @@ 63563FE53573412998852DD3 /* NCAlbumsPersistenceTests.swift in Sources */, C0DECA022F65000100C0D001 /* NCCameraRollTests.swift in Sources */, 22BA14432CF44BDBA2E6C291 /* NCDocumentEditorSupportTests.swift in Sources */, + B1E071012026102100000002 /* NCContextMenuViewerTests.swift in Sources */, F372087D2BAB4C0F006B5430 /* TestConstants.swift in Sources */, F78E2D6C29AF02DB0024D4F3 /* Database.swift in Sources */, ); diff --git a/Tests/NextcloudUnitTests/NCContextMenuViewerTests.swift b/Tests/NextcloudUnitTests/NCContextMenuViewerTests.swift new file mode 100644 index 0000000000..20404cb0c0 --- /dev/null +++ b/Tests/NextcloudUnitTests/NCContextMenuViewerTests.swift @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Marino Faggiana +// SPDX-License-Identifier: GPL-3.0-or-later + +import Testing +import UIKit +import NextcloudKit +@testable import Nextcloud + +@Suite("Photo viewer edit menu", .serialized) +@MainActor +struct NCContextMenuViewerTests { + private let account = "viewer-edit-menu" + + @Test("An online preview-only image offers one Edit action without downloading") + func previewOnlyImageOffersEdit() async throws { + try await performOnline { + let metadata = makeImage(fileName: "photo.jpg") + #expect(metadata.isImage) + #expect(metadata.isModifiableWithQuickLook) + #expect(metadata.session.isEmpty) + #expect(metadata.status == NCGlobal.shared.metadataStatusNormal) + + let menu = try #require(viewMenu(for: metadata, webView: false)) + + #expect(editActions(in: menu).count == 1) + #expect(metadata.session.isEmpty) + #expect(metadata.status == NCGlobal.shared.metadataStatusNormal) + let stored = await NCManageDatabase.shared.getMetadataFromOcIdAsync(metadata.ocId) + #expect(stored?.ocId == nil) + } + } + + @Test("Web view, non-images, and encrypted photos omit Edit") + func ineligibleItemsOmitEdit() async throws { + try await performOnline { + let webPhoto = makeImage(fileName: "web.jpg") + let webMenu = try #require(viewMenu(for: webPhoto, webView: true)) + #expect(editActions(in: webMenu).isEmpty) + + let video = makeImage(fileName: "clip.mov") + video.classFile = NKTypeClassFile.video.rawValue + video.contentType = "video/mp4" + let videoMenu = try #require(viewMenu(for: video, webView: false)) + #expect(editActions(in: videoMenu).isEmpty) + + let folder = encryptedFolder() + await NCManageDatabase.shared.addMetadataAsync(folder) + let photo = makeImage(fileName: "secret.jpg", serverUrl: folder.serverUrlFileName) + photo.e2eEncrypted = true + let isImage = photo.isImage + let quickLookEligible = photo.isModifiableWithQuickLook + let encryptedMenu = viewMenu(for: photo, webView: false) + await NCManageDatabase.shared.deleteMetadataAsync(ocId: folder.ocId) + + #expect(isImage) + #expect(!quickLookEligible) + #expect(editActions(in: try #require(encryptedMenu)).isEmpty) + } + } + + private func performOnline(_ body: () async throws -> Void) async throws { + let networking = NCNetworking.shared + let previousReachability = networking.networkReachability + let previousCapabilities = networking.capabilities[account] + networking.networkReachability = NKTypeReachability.reachableEthernetOrWiFi + networking.capabilities[account] = NKCapabilities.Capabilities() + defer { + networking.networkReachability = previousReachability + networking.capabilities[account] = previousCapabilities + } + try await body() + } + + private func viewMenu(for metadata: tableMetadata, webView: Bool) -> UIMenu? { + NCContextMenuViewer( + metadata: metadata, + controller: NCMainTabBarController(), + viewController: nil, + webView: webView, + sender: nil + ).viewMenu() + } + + private func editActions(in menu: UIMenu) -> [UIAction] { + let title = NSLocalizedString("_edit_", comment: "") + return actions(in: menu).filter { $0.title == title } + } + + private func actions(in element: UIMenuElement) -> [UIAction] { + if let action = element as? UIAction { + return [action] + } + guard let menu = element as? UIMenu else { + return [] + } + return menu.children.flatMap(actions(in:)) + } + + private func makeImage(fileName: String, serverUrl: String? = nil) -> tableMetadata { + let metadata = tableMetadata() + metadata.account = account + metadata.ocId = "viewer-edit-\(fileName)" + metadata.fileName = fileName + metadata.fileNameView = fileName + metadata.classFile = NKTypeClassFile.image.rawValue + metadata.contentType = "image/jpeg" + metadata.size = 2048 + metadata.urlBase = "https://example.com" + metadata.userId = "user" + metadata.serverUrl = serverUrl ?? "https://example.com/remote.php/dav/files/user/Photos" + metadata.serverUrlFileName = metadata.serverUrl + "/" + fileName + return metadata + } + + private func encryptedFolder() -> tableMetadata { + let folder = tableMetadata() + folder.account = account + folder.ocId = "viewer-edit-e2ee-folder" + folder.fileName = "Secret" + folder.fileNameView = folder.fileName + folder.directory = true + folder.e2eEncrypted = true + folder.classFile = NKTypeClassFile.directory.rawValue + folder.urlBase = "https://example.com" + folder.userId = "user" + folder.serverUrl = "https://example.com/remote.php/dav/files/user" + folder.serverUrlFileName = folder.serverUrl + "/" + folder.fileName + return folder + } +} diff --git a/iOSClient/Menu/NCContextMenuMain.swift b/iOSClient/Menu/NCContextMenuMain.swift index 30b9617ce8..a92335cd98 100644 --- a/iOSClient/Menu/NCContextMenuMain.swift +++ b/iOSClient/Menu/NCContextMenuMain.swift @@ -279,7 +279,7 @@ class NCContextMenuMain: NSObject { private func makeModifyWithQuickLookAction(metadata: tableMetadata) -> UIAction { return UIAction( - title: NSLocalizedString("_modify_", comment: ""), + title: NSLocalizedString("_edit_", comment: ""), image: utility.loadImage(named: "pencil.tip.crop.circle", colors: [NCBrandColor.shared.iconImageColor]) ) { _ in Task { diff --git a/iOSClient/Menu/NCContextMenuViewer.swift b/iOSClient/Menu/NCContextMenuViewer.swift index 416d769838..a7cc941b5d 100644 --- a/iOSClient/Menu/NCContextMenuViewer.swift +++ b/iOSClient/Menu/NCContextMenuViewer.swift @@ -116,7 +116,8 @@ class NCContextMenuViewer: NSObject { if !webView, metadata.isImage, - utilityFileSystem.fileSizeIfExists(metadata) { + metadata.isModifiableWithQuickLook, + (NCNetworking.shared.isOnline || utilityFileSystem.fileProviderStorageExists(metadata)) { menuElements.append(makeModifyPhoto()) } @@ -316,22 +317,33 @@ class NCContextMenuViewer: NSObject { } private func makeModifyPhoto() -> UIAction { + let metadata = self.metadata return UIAction( - title: NSLocalizedString("_modify_", comment: ""), + title: NSLocalizedString("_edit_", comment: ""), image: utility.loadImage(named: "pencil.tip.crop.circle", colors: [NCBrandColor.shared.iconImageColor]) ) { _ in Task { - await NCNetworking.shared.transferDispatcher.notifyAllDelegates { delegate in - delegate.transferChange( - networkingStatus: NCGlobal.shared.networkingStatusDownloaded, - account: self.metadata.account, - fileName: self.metadata.fileName, - serverUrl: self.metadata.serverUrl, - selector: NCGlobal.shared.selectorLoadFileQuickLook, - ocId: self.metadata.ocId, - destination: nil, - error: .success - ) + if self.utilityFileSystem.fileProviderStorageExists(metadata) { + await NCNetworking.shared.transferDispatcher.notifyAllDelegates { delegate in + delegate.transferChange( + networkingStatus: NCGlobal.shared.networkingStatusDownloaded, + account: metadata.account, + fileName: metadata.fileName, + serverUrl: metadata.serverUrl, + selector: NCGlobal.shared.selectorLoadFileQuickLook, + ocId: metadata.ocId, + destination: nil, + error: .success + ) + } + } else if NCNetworking.shared.isOnline, + let metadata = await NCManageDatabase.shared.setMetadataSessionInWaitDownloadAsync( + ocId: metadata.ocId, + session: NCNetworking.shared.sessionDownload, + selector: NCGlobal.shared.selectorLoadFileQuickLook, + sceneIdentifier: self.controller?.sceneIdentifier + ) { + await NCNetworking.shared.downloadFile(metadata: metadata) } } } From 8ce96c7ca1031deb709039cb86d9d9dcb65c4b74 Mon Sep 17 00:00:00 2001 From: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Date: Tue, 10 Nov 2026 05:01:43 -0800 Subject: [PATCH 2/3] fix: isolate photo edit sessions and tie Edit to its viewer Each Quick Look editor now owns its change flag, so opening a second editor no longer clears the first one's save prompt. Editors also get a temporary copy in their own directory, keeping the file name, so two photos with the same name never overwrite the file the other uploads. The download-then-open code moved into NCViewerQuickLook.presentEditor, which the Quick Look transfer selector now uses as well. Edit from the media viewer goes through the viewer's loader. The loader shares a download that is already running for the same photo, so Edit while Info downloads the original neither resets the transfer state nor starts a second download to the same path. Quick Look opens only if the viewer is still on screen and showing that photo when the download ends. New unit tests cover separate change flags, separate temporary files for same-name photos, joining a running download, and not opening the editor after the viewer moved on, closed, or the download failed. Signed-off-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> --- Nextcloud.xcodeproj/project.pbxproj | 8 + .../MockViewerPhotoEditSource.swift | 54 +++++ .../NCViewerPhotoEditTests.swift | 206 ++++++++++++++++++ iOSClient/Menu/NCContextMenuViewer.swift | 54 ++++- .../NCNetworking+TransferDelegate.swift | 23 +- .../NCMediaViewerHostingController.swift | 12 + .../NCNextcloudMediaViewerLoader.swift | 38 ++++ .../NCViewerQuickLook/NCViewerQuickLook.swift | 63 +++++- 8 files changed, 422 insertions(+), 36 deletions(-) create mode 100644 Tests/NextcloudUnitTests/MockViewerPhotoEditSource.swift create mode 100644 Tests/NextcloudUnitTests/NCViewerPhotoEditTests.swift diff --git a/Nextcloud.xcodeproj/project.pbxproj b/Nextcloud.xcodeproj/project.pbxproj index 3893cf2f58..60a1231205 100644 --- a/Nextcloud.xcodeproj/project.pbxproj +++ b/Nextcloud.xcodeproj/project.pbxproj @@ -77,6 +77,8 @@ AB7000062F70000100FE2776 /* NCGovernanceLabelSelectorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB7000052F70000100FE2776 /* NCGovernanceLabelSelectorView.swift */; }; AC13ADAF2026101300000002 /* NCMediaAdaptiveLayoutViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC13ADAF2026101300000001 /* NCMediaAdaptiveLayoutViewTests.swift */; }; B1E071012026102100000002 /* NCContextMenuViewerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1E071012026102100000001 /* NCContextMenuViewerTests.swift */; }; + B1E071012026111000000002 /* NCViewerPhotoEditTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1E071012026111000000001 /* NCViewerPhotoEditTests.swift */; }; + B1E071012026111000000004 /* MockViewerPhotoEditSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1E071012026111000000003 /* MockViewerPhotoEditSource.swift */; }; AC14ADAF2026101400000002 /* NCMediaAdaptiveControlsLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC14ADAF2026101400000001 /* NCMediaAdaptiveControlsLayout.swift */; }; AC14ADAF2026101400000012 /* NCMediaViewerPreviewLoader.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC14ADAF2026101400000011 /* NCMediaViewerPreviewLoader.swift */; }; AF1A9B6427D0CA1E00F17A9E /* UIAlertController+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF1A9B6327D0CA1E00F17A9E /* UIAlertController+Extension.swift */; }; @@ -1415,6 +1417,8 @@ AB7000052F70000100FE2776 /* NCGovernanceLabelSelectorView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NCGovernanceLabelSelectorView.swift; sourceTree = ""; }; AC13ADAF2026101300000001 /* NCMediaAdaptiveLayoutViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCMediaAdaptiveLayoutViewTests.swift; sourceTree = ""; }; B1E071012026102100000001 /* NCContextMenuViewerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCContextMenuViewerTests.swift; sourceTree = ""; }; + B1E071012026111000000001 /* NCViewerPhotoEditTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCViewerPhotoEditTests.swift; sourceTree = ""; }; + B1E071012026111000000003 /* MockViewerPhotoEditSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockViewerPhotoEditSource.swift; sourceTree = ""; }; AC14ADAF2026101400000001 /* NCMediaAdaptiveControlsLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCMediaAdaptiveControlsLayout.swift; sourceTree = ""; }; AC14ADAF2026101400000011 /* NCMediaViewerPreviewLoader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCMediaViewerPreviewLoader.swift; sourceTree = ""; }; AF1A9B6327D0CA1E00F17A9E /* UIAlertController+Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIAlertController+Extension.swift"; sourceTree = ""; }; @@ -2340,6 +2344,8 @@ C0DECA012F65000100C0D001 /* NCCameraRollTests.swift */, 4B74B947E07444CC9CFE0A6C /* NCDocumentEditorSupportTests.swift */, B1E071012026102100000001 /* NCContextMenuViewerTests.swift */, + B1E071012026111000000001 /* NCViewerPhotoEditTests.swift */, + B1E071012026111000000003 /* MockViewerPhotoEditSource.swift */, ); path = NextcloudUnitTests; sourceTree = ""; @@ -4725,6 +4731,8 @@ C0DECA022F65000100C0D001 /* NCCameraRollTests.swift in Sources */, 22BA14432CF44BDBA2E6C291 /* NCDocumentEditorSupportTests.swift in Sources */, B1E071012026102100000002 /* NCContextMenuViewerTests.swift in Sources */, + B1E071012026111000000002 /* NCViewerPhotoEditTests.swift in Sources */, + B1E071012026111000000004 /* MockViewerPhotoEditSource.swift in Sources */, F372087D2BAB4C0F006B5430 /* TestConstants.swift in Sources */, F78E2D6C29AF02DB0024D4F3 /* Database.swift in Sources */, ); diff --git a/Tests/NextcloudUnitTests/MockViewerPhotoEditSource.swift b/Tests/NextcloudUnitTests/MockViewerPhotoEditSource.swift new file mode 100644 index 0000000000..0895d3c329 --- /dev/null +++ b/Tests/NextcloudUnitTests/MockViewerPhotoEditSource.swift @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Matt Van Horn +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation +@testable import Nextcloud + +/// A viewer stand-in for photo editing tests. The download stays pending +/// until the test calls `finishDownload(error:)`, and the shown photo can be +/// changed while it waits. `present(_:)` records each editor it would open. +@MainActor +final class MockViewerPhotoEditSource: NCViewerPhotoEditSource { + var shownOcId: String? + var isOnScreen = true + private(set) var downloadRequests: [String] = [] + private(set) var presentedOcIds: [String] = [] + private var pendingDownloads: [CheckedContinuation] = [] + + init(shownOcId: String?) { + self.shownOcId = shownOcId + } + + var hasPendingDownload: Bool { + !pendingDownloads.isEmpty + } + + func downloadOriginalForEditing(_ metadata: tableMetadata) async throws { + downloadRequests.append(metadata.ocId) + try await withCheckedThrowingContinuation { continuation in + pendingDownloads.append(continuation) + } + } + + func finishDownload(error: Error? = nil) { + let continuations = pendingDownloads + pendingDownloads.removeAll() + for continuation in continuations { + if let error { + continuation.resume(throwing: error) + } else { + continuation.resume() + } + } + } + + /// Records that the editor was opened for this photo. + func present(_ metadata: tableMetadata) { + presentedOcIds.append(metadata.ocId) + } + + func isShowingMedia(ocId: String) -> Bool { + isOnScreen && shownOcId == ocId + } +} diff --git a/Tests/NextcloudUnitTests/NCViewerPhotoEditTests.swift b/Tests/NextcloudUnitTests/NCViewerPhotoEditTests.swift new file mode 100644 index 0000000000..267e8cb4ab --- /dev/null +++ b/Tests/NextcloudUnitTests/NCViewerPhotoEditTests.swift @@ -0,0 +1,206 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Matt Van Horn +// SPDX-License-Identifier: GPL-3.0-or-later + +import Testing +import UIKit +import QuickLook +import NextcloudKit +@testable import Nextcloud + +@Suite("Photo viewer edit session", .serialized) +@MainActor +struct NCViewerPhotoEditTests { + + // MARK: - Quick Look session isolation + + @Test("A second editor does not clear the first editor's changes") + func editorsKeepSeparateChangeFlags() throws { + let firstURL = try #require(NCViewerQuickLook.makeEditingFileURL(fileName: "photo.jpg")) + try Data("original".utf8).write(to: firstURL) + let first = NCViewerQuickLook(with: firstURL, isEditingEnabled: true, metadata: makeImage(ocId: "edit-first")) + + let editedURL = try #require(NCViewerQuickLook.makeEditingFileURL(fileName: "edited.jpg")) + try Data("edited".utf8).write(to: editedURL) + let item = PreviewItem() + item.previewItemURL = firstURL + first.previewController(first, didSaveEditedCopyOf: item, at: editedURL) + #expect(first.hasChangesQuickLook) + + let secondURL = try #require(NCViewerQuickLook.makeEditingFileURL(fileName: "photo.jpg")) + let second = NCViewerQuickLook(with: secondURL, isEditingEnabled: true, metadata: makeImage(ocId: "edit-second")) + + #expect(first.hasChangesQuickLook) + #expect(!second.hasChangesQuickLook) + } + + @Test("Editors of files with the same name get separate temporary files") + func sameNameEditorsDoNotShareTheTemporaryFile() throws { + let first = try #require(NCViewerQuickLook.makeEditingFileURL(fileName: "photo.jpg")) + let second = try #require(NCViewerQuickLook.makeEditingFileURL(fileName: "photo.jpg")) + + #expect(first != second) + #expect(first.lastPathComponent == "photo.jpg") + #expect(second.lastPathComponent == "photo.jpg") + + try Data("first edit".utf8).write(to: first) + try Data("second edit".utf8).write(to: second) + + #expect(try Data(contentsOf: first) == Data("first edit".utf8)) + #expect(try Data(contentsOf: second) == Data("second edit".utf8)) + } + + // MARK: - Shared download + + @Test("A request for a download already running joins it") + func inFlightDownloadIsReused() async throws { + let registry = NCInFlightTaskRegistry() + let counter = Counter() + let gate = Gate() + + async let first = registry.value(for: "photo") { + await counter.increment() + await gate.wait() + return 1 + } + await counter.waitUntil(1) + async let second = registry.value(for: "photo") { + await counter.increment() + return 2 + } + while await registry.joinedCount < 1 { + await Task.yield() + } + await gate.open() + + let results = try await [first, second] + #expect(results == [1, 1]) + #expect(await counter.value == 1) + + let next = try await registry.value(for: "photo") { + await counter.increment() + return 3 + } + #expect(next == 3) + #expect(await counter.value == 2) + } + + // MARK: - Edit tied to the originating viewer + + @Test("Edit opens Quick Look when the viewer still shows the photo") + func editOpensWhenPhotoIsStillShown() async { + let metadata = makeImage(ocId: "edit-shown") + let source = MockViewerPhotoEditSource(shownOcId: metadata.ocId) + + let edit = Task { @MainActor in + await NCViewerPhotoEdit.edit(metadata: metadata, source: source) { source.present($0) } + } + await waitForDownload(source) + source.finishDownload() + + #expect(await edit.value) + #expect(source.presentedOcIds == [metadata.ocId]) + #expect(source.downloadRequests == [metadata.ocId]) + } + + @Test("Edit does not open Quick Look after the viewer moved to another photo") + func editSkipsWhenViewerShowsAnotherPhoto() async { + let metadata = makeImage(ocId: "edit-swiped") + let source = MockViewerPhotoEditSource(shownOcId: metadata.ocId) + + let edit = Task { @MainActor in + await NCViewerPhotoEdit.edit(metadata: metadata, source: source) { source.present($0) } + } + await waitForDownload(source) + source.shownOcId = "edit-other" + source.finishDownload() + + #expect(await edit.value == false) + #expect(source.presentedOcIds.isEmpty) + } + + @Test("Edit does not open Quick Look after the viewer closed") + func editSkipsWhenViewerClosed() async { + let metadata = makeImage(ocId: "edit-closed") + let source = MockViewerPhotoEditSource(shownOcId: metadata.ocId) + + let edit = Task { @MainActor in + await NCViewerPhotoEdit.edit(metadata: metadata, source: source) { source.present($0) } + } + await waitForDownload(source) + source.isOnScreen = false + source.finishDownload() + + #expect(await edit.value == false) + #expect(source.presentedOcIds.isEmpty) + } + + @Test("Edit does not open Quick Look when the download fails") + func editSkipsWhenDownloadFails() async { + let metadata = makeImage(ocId: "edit-failed") + let source = MockViewerPhotoEditSource(shownOcId: metadata.ocId) + + let edit = Task { @MainActor in + await NCViewerPhotoEdit.edit(metadata: metadata, source: source) { source.present($0) } + } + await waitForDownload(source) + source.finishDownload(error: URLError(.notConnectedToInternet)) + + #expect(await edit.value == false) + #expect(source.presentedOcIds.isEmpty) + } + + // MARK: - Helpers + + private func waitForDownload(_ source: MockViewerPhotoEditSource) async { + while !source.hasPendingDownload { + await Task.yield() + } + } + + private func makeImage(ocId: String) -> tableMetadata { + let metadata = tableMetadata() + metadata.account = "viewer-edit-session" + metadata.ocId = ocId + metadata.fileName = "photo.jpg" + metadata.fileNameView = "photo.jpg" + metadata.classFile = NKTypeClassFile.image.rawValue + metadata.contentType = "image/jpeg" + metadata.urlBase = "https://example.com" + metadata.userId = "user" + metadata.serverUrl = "https://example.com/remote.php/dav/files/user/Photos" + return metadata + } +} + +private actor Counter { + private(set) var value = 0 + + func increment() { + value += 1 + } + + func waitUntil(_ target: Int) async { + while value < target { + await Task.yield() + } + } +} + +private actor Gate { + private var isOpen = false + private var waiters: [CheckedContinuation] = [] + + func wait() async { + if isOpen { + return + } + await withCheckedContinuation { waiters.append($0) } + } + + func open() { + isOpen = true + waiters.forEach { $0.resume() } + waiters.removeAll() + } +} diff --git a/iOSClient/Menu/NCContextMenuViewer.swift b/iOSClient/Menu/NCContextMenuViewer.swift index a2cadb42eb..2126a61d84 100644 --- a/iOSClient/Menu/NCContextMenuViewer.swift +++ b/iOSClient/Menu/NCContextMenuViewer.swift @@ -103,7 +103,7 @@ class NCContextMenuViewer: NSObject { if !webView, metadata.isImage, metadata.isModifiableWithQuickLook, - (NCNetworking.shared.isOnline || utilityFileSystem.fileProviderStorageExists(metadata)) { + NCNetworking.shared.isOnline || utilityFileSystem.fileProviderStorageExists(metadata) { editingActions.append(makeModifyPhoto()) } @@ -294,9 +294,17 @@ class NCContextMenuViewer: NSObject { return UIAction( title: NSLocalizedString("_edit_", comment: ""), image: utility.loadImage(named: "pencil.tip.crop.circle", colors: [NCBrandColor.shared.iconImageColor]) - ) { _ in - Task { - if self.utilityFileSystem.fileProviderStorageExists(metadata) { + ) { [weak viewController = self.viewController, weak controller = self.controller] _ in + Task { @MainActor in + if let source = viewController as? NCViewerPhotoEditSource { + await NCViewerPhotoEdit.edit(metadata: metadata, source: source) { metadata in + guard let controller else { + return + } + let current = await NCManageDatabase.shared.getMetadataFromOcIdAsync(metadata.ocId) ?? metadata + NCViewerQuickLook.presentEditor(metadata: current, from: controller) + } + } else if self.utilityFileSystem.fileProviderStorageExists(metadata) { await NCNetworking.shared.transferDispatcher.notifyAllDelegates { delegate in delegate.transferChange( networkingStatus: NCGlobal.shared.networkingStatusDownloaded, @@ -314,7 +322,7 @@ class NCContextMenuViewer: NSObject { ocId: metadata.ocId, session: NCNetworking.shared.sessionDownload, selector: NCGlobal.shared.selectorLoadFileQuickLook, - sceneIdentifier: self.controller?.sceneIdentifier + sceneIdentifier: controller?.sceneIdentifier ) { await NCNetworking.shared.downloadFile(metadata: metadata) } @@ -322,3 +330,39 @@ class NCContextMenuViewer: NSObject { } } } + +/// A viewer that can provide the original of the photo it shows for editing. +@MainActor +protocol NCViewerPhotoEditSource: AnyObject { + /// Returns once the original is stored on the device. Joins a download + /// already running for the same photo instead of starting another one. + func downloadOriginalForEditing(_ metadata: tableMetadata) async throws + + /// Whether the viewer is still on screen and showing this photo. + func isShowingMedia(ocId: String) -> Bool +} + +/// Ties an Edit request to the viewer it came from. +@MainActor +enum NCViewerPhotoEdit { + /// Downloads the original if needed, then opens the editor only if the + /// originating viewer still shows the same photo. + /// - Returns: `true` when the editor was opened. + @discardableResult + static func edit(metadata: tableMetadata, + source: NCViewerPhotoEditSource, + present: @MainActor (tableMetadata) async -> Void) async -> Bool { + let ocId = metadata.ocId + do { + try await source.downloadOriginalForEditing(metadata) + } catch { + return false + } + guard !Task.isCancelled, + source.isShowingMedia(ocId: ocId) else { + return false + } + await present(metadata) + return true + } +} diff --git a/iOSClient/Networking/NCNetworking+TransferDelegate.swift b/iOSClient/Networking/NCNetworking+TransferDelegate.swift index 5ebe490f74..dbaf7d22e2 100644 --- a/iOSClient/Networking/NCNetworking+TransferDelegate.swift +++ b/iOSClient/Networking/NCNetworking+TransferDelegate.swift @@ -58,28 +58,7 @@ extension NCNetworking: NCTransferDelegate { switch selector { case NCGlobal.shared.selectorLoadFileQuickLook: - - let fileNamePath = self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, - fileName: metadata.fileNameView, - userId: metadata.userId, - urlBase: metadata.urlBase) - let fileNameTemp = NSTemporaryDirectory() + metadata.fileNameView - let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNameTemp), isEditingEnabled: true, metadata: metadata) - if let image = UIImage(contentsOfFile: fileNamePath) { - if let data = image.jpegData(compressionQuality: 1) { - do { - try data.write(to: URL(fileURLWithPath: fileNameTemp)) - } catch { - return - } - } - let navigationController = UINavigationController(rootViewController: viewerQuickLook) - navigationController.modalPresentationStyle = .fullScreen - controller.present(navigationController, animated: true) - } else { - self.utilityFileSystem.copyFile(atPath: fileNamePath, toPath: fileNameTemp) - controller.present(viewerQuickLook, animated: true) - } + NCViewerQuickLook.presentEditor(metadata: metadata, from: controller) case NCGlobal.shared.selectorLoadFileView: guard !isAppInBackground diff --git a/iOSClient/Viewer/NCViewerMedia/NCMediaViewerHostingController.swift b/iOSClient/Viewer/NCViewerMedia/NCMediaViewerHostingController.swift index 5da48c36ef..6d901438e0 100644 --- a/iOSClient/Viewer/NCViewerMedia/NCMediaViewerHostingController.swift +++ b/iOSClient/Viewer/NCViewerMedia/NCMediaViewerHostingController.swift @@ -560,3 +560,15 @@ final class NCMediaViewerTransferDelegate: NSObject, NCTransferDelegate { } } } + +// MARK: - Photo Editing + +extension NCMediaViewerHostingController: NCViewerPhotoEditSource { + func downloadOriginalForEditing(_ metadata: tableMetadata) async throws { + try await model.downloadOriginalImage(for: metadata) + } + + func isShowingMedia(ocId: String) -> Bool { + viewIfLoaded?.window != nil && model.selectedMetadata?.ocId == ocId + } +} diff --git a/iOSClient/Viewer/NCViewerMedia/NCNextcloudMediaViewerLoader.swift b/iOSClient/Viewer/NCViewerMedia/NCNextcloudMediaViewerLoader.swift index 9c45931160..ab067ce7e4 100644 --- a/iOSClient/Viewer/NCViewerMedia/NCNextcloudMediaViewerLoader.swift +++ b/iOSClient/Viewer/NCViewerMedia/NCNextcloudMediaViewerLoader.swift @@ -37,12 +37,41 @@ private actor NCMediaViewerDownloadTaskRegistry { } } +/// Runs at most one operation per key at a time. A caller that asks for a key +/// while its operation is still running awaits that same operation instead of +/// starting a second one. +actor NCInFlightTaskRegistry { + private var tasks: [Key: (id: UUID, task: Task)] = [:] + /// How many callers joined an operation that was already running. + private(set) var joinedCount = 0 + + func value(for key: Key, operation: @escaping @Sendable () async throws -> Value) async throws -> Value { + if let running = tasks[key] { + joinedCount += 1 + return try await running.task.value + } + + let id = UUID() + let task = Task { try await operation() } + tasks[key] = (id, task) + + defer { + if tasks[key]?.id == id { + tasks[key] = nil + } + } + + return try await task.value + } +} + // MARK: - Media Viewer Loader final class NCMediaViewerLoader: NCMediaViewerLoading, @unchecked Sendable { private let database = NCManageDatabase.shared private let utilityFileSystem = NCUtilityFileSystem() private let fileManager = FileManager.default private let downloadTaskRegistry = NCMediaViewerDownloadTaskRegistry() + private let inFlightDownloads = NCInFlightTaskRegistry() // MARK: - NCMediaViewerLoading func metadata(for ocId: String, account: String) async -> tableMetadata? { @@ -118,6 +147,15 @@ final class NCMediaViewerLoader: NCMediaViewerLoading, @unchecked Sendable { await onDownloadStarted?() + // Info and Edit can ask for the same original while it is downloading. + // Share the running download so its transfer state is not reset and + // a second download to the same path is never started. + return try await inFlightDownloads.value(for: metadata.ocId) { [self] in + try await self.performMediaDownload(for: metadata) + } + } + + private func performMediaDownload(for metadata: tableMetadata) async throws -> URL { guard let downloadMetadata = await database.setMetadataSessionInWaitDownloadAsync( ocId: metadata.ocId, session: NCNetworking.shared.sessionDownload, diff --git a/iOSClient/Viewer/NCViewerQuickLook/NCViewerQuickLook.swift b/iOSClient/Viewer/NCViewerQuickLook/NCViewerQuickLook.swift index 36dab8777f..01aabbae90 100644 --- a/iOSClient/Viewer/NCViewerQuickLook/NCViewerQuickLook.swift +++ b/iOSClient/Viewer/NCViewerQuickLook/NCViewerQuickLook.swift @@ -19,11 +19,10 @@ public extension NCViewerQuickLookDelegate { func dismissQuickLook(fileNameSource: String, hasChangesQuickLook: Bool) {} } -/// Flag indicating If the document has any changes -private var hasChangesQuickLook: Bool = false - @objc class NCViewerQuickLook: QLPreviewController { private let url: URL + /// Whether this editor's document has unsaved changes. Each editor owns its flag. + private(set) var hasChangesQuickLook: Bool = false private let fileNameSource: String private var previewItems: [PreviewItem] = [] private var isEditingEnabled: Bool @@ -58,7 +57,6 @@ private var hasChangesQuickLook: Bool = false self.dataSource = self self.delegate = self self.currentPreviewItemIndex = 0 - hasChangesQuickLook = false } override func viewDidLoad() { @@ -130,7 +128,7 @@ private var hasChangesQuickLook: Bool = false } else { alertController.addAction(UIAlertAction(title: NSLocalizedString("_overwrite_original_", comment: ""), style: .default) { _ in self.saveModifiedFile(override: true) - self.delegateQuickLook?.dismissQuickLook(fileNameSource: self.fileNameSource, hasChangesQuickLook: hasChangesQuickLook) + self.delegateQuickLook?.dismissQuickLook(fileNameSource: self.fileNameSource, hasChangesQuickLook: self.hasChangesQuickLook) }) } @@ -139,7 +137,7 @@ private var hasChangesQuickLook: Bool = false if saveAsCopyAlert { alertController.addAction(UIAlertAction(title: NSLocalizedString("_save_as_copy_", comment: ""), style: .default) { _ in self.saveModifiedFile(override: false) - self.delegateQuickLook?.dismissQuickLook(fileNameSource: self.fileNameSource, hasChangesQuickLook: hasChangesQuickLook) + self.delegateQuickLook?.dismissQuickLook(fileNameSource: self.fileNameSource, hasChangesQuickLook: self.hasChangesQuickLook) }) } alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { _ in @@ -153,7 +151,7 @@ private var hasChangesQuickLook: Bool = false @objc private func dismissView(_ sender: Any?) { dismiss(animated: true) { - if hasChangesQuickLook { + if self.hasChangesQuickLook { self.showSaveAlert() } } @@ -288,7 +286,7 @@ extension NCViewerQuickLook: QLPreviewControllerDataSource, QLPreviewControllerD func previewController(_ controller: QLPreviewController, didSaveEditedCopyOf previewItem: QLPreviewItem, at modifiedContentsURL: URL) { guard utilityFileSystem.copyFile(atPath: modifiedContentsURL.path, toPath: url.path) else { return } - hasChangesQuickLook = true + self.hasChangesQuickLook = true } } @@ -298,7 +296,7 @@ extension NCViewerQuickLook: CropViewControllerDelegate { guard let data = cropped.jpegData(compressionQuality: 0.9) else { return } do { try data.write(to: self.url) - hasChangesQuickLook = true + self.hasChangesQuickLook = true reloadData() } catch { print(error) @@ -310,6 +308,53 @@ extension NCViewerQuickLook: CropViewControllerDelegate { } } +extension NCViewerQuickLook { + /// Returns a temporary file URL that belongs to one editing session only. + /// The file keeps its original name inside a directory created for the session, + /// so two editors of files with the same name never share the copy they upload. + static func makeEditingFileURL(fileName: String, temporaryDirectory: URL = FileManager.default.temporaryDirectory) -> URL? { + let directory = temporaryDirectory.appendingPathComponent("QuickLookEdit-" + UUID().uuidString, isDirectory: true) + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } catch { + return nil + } + return directory.appendingPathComponent(fileName, isDirectory: false) + } + + /// Opens an editing session for a file already stored on the device. + @MainActor + @discardableResult + static func presentEditor(metadata: tableMetadata, from controller: UIViewController) -> NCViewerQuickLook? { + let fileNamePath = NCUtilityFileSystem().getDirectoryProviderStorageOcId(metadata.ocId, + fileName: metadata.fileNameView, + userId: metadata.userId, + urlBase: metadata.urlBase) + guard let fileURL = makeEditingFileURL(fileName: metadata.fileNameView) else { + return nil + } + let viewerQuickLook = NCViewerQuickLook(with: fileURL, isEditingEnabled: true, metadata: metadata) + + if let image = UIImage(contentsOfFile: fileNamePath) { + if let data = image.jpegData(compressionQuality: 1) { + do { + try data.write(to: fileURL) + } catch { + return nil + } + } + let navigationController = UINavigationController(rootViewController: viewerQuickLook) + navigationController.modalPresentationStyle = .fullScreen + controller.present(navigationController, animated: true) + } else { + NCUtilityFileSystem().copyFile(atPath: fileNamePath, toPath: fileURL.path) + controller.present(viewerQuickLook, animated: true) + } + + return viewerQuickLook + } +} + class PreviewItem: NSObject, QLPreviewItem { var previewItemURL: URL? } From b0a1f4c6d2db2a8fce9620e218b1f1ed2d08cac6 Mon Sep 17 00:00:00 2001 From: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:46:05 -0800 Subject: [PATCH 3/3] fix: cancel a shared media download once no caller is waiting The shared download ran in an unstructured task, so cancelling the viewer while it waited for a transfer slot left it queued. Each caller now registers on the shared operation; when the last one is cancelled the operation is cancelled too. cancelDownload(for:) and cancelAllDownloads() also cancel queued shared operations. Signed-off-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> --- .../NCViewerPhotoEditTests.swift | 51 +++++++++++++ .../NCNextcloudMediaViewerLoader.swift | 73 ++++++++++++++++--- 2 files changed, 113 insertions(+), 11 deletions(-) diff --git a/Tests/NextcloudUnitTests/NCViewerPhotoEditTests.swift b/Tests/NextcloudUnitTests/NCViewerPhotoEditTests.swift index 267e8cb4ab..7bf9813c37 100644 --- a/Tests/NextcloudUnitTests/NCViewerPhotoEditTests.swift +++ b/Tests/NextcloudUnitTests/NCViewerPhotoEditTests.swift @@ -85,6 +85,57 @@ struct NCViewerPhotoEditTests { #expect(await counter.value == 2) } + @Test("Cancelling the only caller cancels the shared operation") + func cancellingLastCallerCancelsOperation() async { + let registry = NCInFlightTaskRegistry() + let counter = Counter() + + let caller = Task { + try await registry.value(for: "photo") { + await counter.increment() + try await Task.sleep(nanoseconds: 60_000_000_000) + return 1 + } + } + await counter.waitUntil(1) + caller.cancel() + + let result = await caller.result + #expect(throws: CancellationError.self) { try result.get() } + } + + @Test("Cancelling one caller keeps the shared operation for the others") + func cancellingOneCallerKeepsOperation() async throws { + let registry = NCInFlightTaskRegistry() + let counter = Counter() + let gate = Gate() + + let first = Task { + try await registry.value(for: "photo") { + await counter.increment() + await gate.wait() + try Task.checkCancellation() + return 1 + } + } + await counter.waitUntil(1) + let second = Task { + try await registry.value(for: "photo") { + await counter.increment() + return 2 + } + } + while await registry.joinedCount < 1 { + await Task.yield() + } + first.cancel() + try await Task.sleep(nanoseconds: 100_000_000) + await gate.open() + + #expect(try await second.value == 1) + #expect(await counter.value == 1) + } + // MARK: - Edit tied to the originating viewer @Test("Edit opens Quick Look when the viewer still shows the photo") diff --git a/iOSClient/Viewer/NCViewerMedia/NCNextcloudMediaViewerLoader.swift b/iOSClient/Viewer/NCViewerMedia/NCNextcloudMediaViewerLoader.swift index ab067ce7e4..a6b988f8f2 100644 --- a/iOSClient/Viewer/NCViewerMedia/NCNextcloudMediaViewerLoader.swift +++ b/iOSClient/Viewer/NCViewerMedia/NCNextcloudMediaViewerLoader.swift @@ -39,29 +39,78 @@ private actor NCMediaViewerDownloadTaskRegistry { /// Runs at most one operation per key at a time. A caller that asks for a key /// while its operation is still running awaits that same operation instead of -/// starting a second one. +/// starting a second one. The shared operation is cancelled only when every +/// caller waiting on it has been cancelled, or when it is cancelled by key. actor NCInFlightTaskRegistry { - private var tasks: [Key: (id: UUID, task: Task)] = [:] + private struct Entry { + let id: UUID + let task: Task + var consumers: Int + } + + private var entries: [Key: Entry] = [:] /// How many callers joined an operation that was already running. private(set) var joinedCount = 0 func value(for key: Key, operation: @escaping @Sendable () async throws -> Value) async throws -> Value { - if let running = tasks[key] { + let id: UUID + let task: Task + + if var running = entries[key] { joinedCount += 1 - return try await running.task.value + running.consumers += 1 + entries[key] = running + id = running.id + task = running.task + } else { + id = UUID() + task = Task { try await operation() } + entries[key] = Entry(id: id, task: task, consumers: 1) } - let id = UUID() - let task = Task { try await operation() } - tasks[key] = (id, task) - defer { - if tasks[key]?.id == id { - tasks[key] = nil + if entries[key]?.id == id { + entries[key] = nil + } + } + + return try await withTaskCancellationHandler { + try await task.value + } onCancel: { + Task { + await self.consumerCancelled(for: key, id: id) } } + } - return try await task.value + /// Cancels the operation running for the key, whoever is waiting on it. + func cancel(for key: Key) { + entries.removeValue(forKey: key)?.task.cancel() + } + + /// Cancels every running operation. + func cancelAll() { + let running = entries.values + entries.removeAll() + + running.forEach { $0.task.cancel() } + } + + /// A waiting caller was cancelled: drop it, and cancel the shared + /// operation once no other caller is waiting on it. + private func consumerCancelled(for key: Key, id: UUID) { + guard var entry = entries[key], entry.id == id else { + return + } + + entry.consumers -= 1 + + if entry.consumers <= 0 { + entries[key] = nil + entry.task.cancel() + } else { + entries[key] = entry + } } } @@ -262,6 +311,7 @@ final class NCMediaViewerLoader: NCMediaViewerLoading, @unchecked Sendable { } func cancelDownload(for ocId: String) async { + await inFlightDownloads.cancel(for: ocId) await downloadTaskRegistry.cancelTask(for: ocId) } @@ -274,6 +324,7 @@ final class NCMediaViewerLoader: NCMediaViewerLoading, @unchecked Sendable { } func cancelAllDownloads() async { + await inFlightDownloads.cancelAll() await downloadTaskRegistry.cancelAllTasks() }