From 58b2df8d1a810a04ef235749820448d82ed29fe3 Mon Sep 17 00:00:00 2001 From: Marino Faggiana Date: Mon, 16 Nov 2026 16:26:04 +0100 Subject: [PATCH 1/4] fix: reduce widget image memory usage and support external icons Downsample dashboard icons and file previews, cache smaller thumbnails, and download widget icons directly to disk. Share dashboard icon downloading across targets and restrict account headers to the server origin. Signed-off-by: Marino Faggiana --- Nextcloud.xcodeproj/project.pbxproj | 6 ++ Widget/Dashboard/DashboardData.swift | 11 ++- .../Dashboard/DashboardIconDownloader.swift | 76 +++++++++++++++++++ Widget/Files/FilesData.swift | 75 ++++++++++++------ iOSClient/Networking/NCService.swift | 2 +- iOSClient/Utility/NCUtility+Image.swift | 32 -------- 6 files changed, 142 insertions(+), 60 deletions(-) create mode 100644 Widget/Dashboard/DashboardIconDownloader.swift diff --git a/Nextcloud.xcodeproj/project.pbxproj b/Nextcloud.xcodeproj/project.pbxproj index b7eca39393..72b988d527 100644 --- a/Nextcloud.xcodeproj/project.pbxproj +++ b/Nextcloud.xcodeproj/project.pbxproj @@ -1002,6 +1002,8 @@ F7DF7B422F1A36C100514020 /* HelperBanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7DF7B412F1A36B600514020 /* HelperBanner.swift */; }; F7DF7B432F1A373E00514020 /* HelperBanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7DF7B412F1A36B600514020 /* HelperBanner.swift */; }; F7E0710128B13BB00001B882 /* DashboardData.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7E0710028B13BB00001B882 /* DashboardData.swift */; }; + B3DD1800F0A0406C96253201 /* DashboardIconDownloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3DD1800F0A0406C96253200 /* DashboardIconDownloader.swift */; }; + B3DD1800F0A0406C96253202 /* DashboardIconDownloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3DD1800F0A0406C96253200 /* DashboardIconDownloader.swift */; }; F7E250002FE1000000000002 /* NCDocumentEditorSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7E250002FE1000000000001 /* NCDocumentEditorSupport.swift */; }; F7E250002FE1000000000003 /* NCDocumentEditorSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7E250002FE1000000000001 /* NCDocumentEditorSupport.swift */; }; F7E250002FE1000000000004 /* NCDocumentEditorSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7E250002FE1000000000001 /* NCDocumentEditorSupport.swift */; }; @@ -2048,6 +2050,7 @@ F7DF7B3E2F1A2EE400514020 /* WarningBannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WarningBannerView.swift; sourceTree = ""; }; F7DF7B412F1A36B600514020 /* HelperBanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HelperBanner.swift; sourceTree = ""; }; F7E0710028B13BB00001B882 /* DashboardData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardData.swift; sourceTree = ""; }; + B3DD1800F0A0406C96253200 /* DashboardIconDownloader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardIconDownloader.swift; sourceTree = ""; }; F7E250002FE1000000000001 /* NCDocumentEditorSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCDocumentEditorSupport.swift; sourceTree = ""; }; F7E2B64E2DDCC5C30075B4D0 /* NCMedia+TransferDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NCMedia+TransferDelegate.swift"; sourceTree = ""; }; F7E402282BA85D1D007E5609 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; @@ -2698,6 +2701,7 @@ isa = PBXGroup; children = ( F7E0710028B13BB00001B882 /* DashboardData.swift */, + B3DD1800F0A0406C96253200 /* DashboardIconDownloader.swift */, F72EA95128B7BA2A00C88F0C /* DashboardWidgetProvider.swift */, F72A17D728B221E300F3F159 /* DashboardWidgetView.swift */, ); @@ -4893,6 +4897,7 @@ F76DEE9928F808AF0041B1C9 /* LockscreenWidgetView.swift in Sources */, F78302F928B4C3E600B84583 /* NCManageDatabase+Account.swift in Sources */, F7E0710128B13BB00001B882 /* DashboardData.swift in Sources */, + B3DD1800F0A0406C96253201 /* DashboardIconDownloader.swift in Sources */, F783030328B4C4DD00B84583 /* ThreadSafeDictionary.swift in Sources */, F7CAFE1E2F17A37C00DB35A5 /* ProgressQuantizer.swift in Sources */, F78302F728B4C3C900B84583 /* NCManageDatabase.swift in Sources */, @@ -5294,6 +5299,7 @@ AF93471227E2341B002537EE /* NCContextMenuShare.swift in Sources */, F7EFA47825ADBA500083159A /* NCViewerProviderContextMenu.swift in Sources */, F755BD9B20594AC7008C5FBB /* NCService.swift in Sources */, + B3DD1800F0A0406C96253202 /* DashboardIconDownloader.swift in Sources */, F74B91E92F51D45A0050813D /* ErrorBannerView.swift in Sources */, F7E8A391295DC5E0006CB2D0 /* View+Extension.swift in Sources */, F7CB77642F5843E500DE649A /* UIFont+Extension.swift in Sources */, diff --git a/Widget/Dashboard/DashboardData.swift b/Widget/Dashboard/DashboardData.swift index 59da003dce..9c6b3e0463 100644 --- a/Widget/Dashboard/DashboardData.swift +++ b/Widget/Dashboard/DashboardData.swift @@ -183,10 +183,11 @@ func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) } let titleImage: UIImage? + let iconSize = CGSize(width: DashboardWidgetLayout.iconSize, height: DashboardWidgetLayout.iconSize) if let iconClass = module?.iconClass { let fileSystem = NCUtilityFileSystem() let path = fileSystem.createServerUrl(serverUrl: fileSystem.directoryUserData, fileName: iconClass + ".png") - titleImage = UIImage(contentsOfFile: path) + titleImage = UIImage.downsample(imageAt: URL(fileURLWithPath: path), to: iconSize, scale: 3) } else { titleImage = nil } @@ -236,8 +237,12 @@ func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) isRound = false } else if iconURL.pathComponents.contains("getCalendarDotSvg") { calendarColor = UIColor(hex: (iconURL.lastPathComponent as NSString).deletingPathExtension) - } else if let data = await utility.downloadDashboardIcon(from: iconURL, account: account.account) { - icon = UIImage(data: data) + } else { + let destination = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: destination) } + if let iconFile = await DashboardIconDownloader.download(from: iconURL, account: account.account, to: destination) { + icon = UIImage.downsample(imageAt: iconFile, to: iconSize, scale: 3) + } } } diff --git a/Widget/Dashboard/DashboardIconDownloader.swift b/Widget/Dashboard/DashboardIconDownloader.swift new file mode 100644 index 0000000000..61a9289617 --- /dev/null +++ b/Widget/Dashboard/DashboardIconDownloader.swift @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Marino Faggiana +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation +import Alamofire +import NextcloudKit + +nonisolated enum DashboardIconDownloader { + static func download(from url: URL, account: String) async -> Data? { + guard let (session, headers, redirector) = dashboardIconRequest(for: url, account: account) else { return nil } + let response = await session.request(url, headers: headers) + .redirect(using: redirector) + .validate(statusCode: 200..<300) + .serializingData() + .response + guard headers != nil, let destination = Self.dashboardIconRedirect(from: response.response) else { return response.value } + return try? await AF.request(destination) + .validate(statusCode: 200..<300) + .serializingData() + .value + } + + static func download(from url: URL, account: String, to destination: URL) async -> URL? { + guard let (session, headers, redirector) = dashboardIconRequest(for: url, account: account) else { return nil } + let target: DownloadRequest.Destination = { _, _ in (destination, [.removePreviousFile]) } + let response = await session.download(url, headers: headers, to: target) + .redirect(using: redirector) + .validate(statusCode: 200..<300) + .serializingDownloadedFileURL() + .response + guard headers != nil, let redirectedURL = Self.dashboardIconRedirect(from: response.response) else { return response.value } + return try? await AF.download(redirectedURL, to: target) + .validate(statusCode: 200..<300) + .serializingDownloadedFileURL() + .value + } + + private static func dashboardIconRequest(for url: URL, account: String) -> (Session, HTTPHeaders?, Redirector)? { + let networking = NextcloudKit.shared.nkCommonInstance + guard let session = networking.nksessions.session(forAccount: account), + let serverURL = URL(string: session.urlBase), + let serverOrigin = Self.dashboardCredentialOrigin(serverURL), + let iconOrigin = Self.dashboardCredentialOrigin(url) else { return nil } + + // External icons can be public. Only attach account headers to the account's origin. + guard iconOrigin == serverOrigin else { + return (.default, nil, Redirector(behavior: .follow)) + } + guard let headers = networking.getStandardHeaders(account: account) else { return nil } + + let redirector = Redirector(behavior: .modify { _, request, _ in + request.url.flatMap(Self.dashboardCredentialOrigin) == serverOrigin ? request : nil + }) + + return (session.sessionData, headers, redirector) + } + + private nonisolated static func dashboardIconRedirect(from response: HTTPURLResponse?) -> URL? { + guard let response, (300..<400).contains(response.statusCode), + let location = response.value(forHTTPHeaderField: "Location"), + let destination = URL(string: location, relativeTo: response.url)?.absoluteURL, + dashboardCredentialOrigin(destination) != nil else { return nil } + return destination + } + + private nonisolated static func dashboardCredentialOrigin(_ url: URL) -> URLComponents? { + guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", + let host = url.host?.lowercased(), !host.isEmpty else { return nil } + var origin = URLComponents() + origin.scheme = scheme + origin.host = host + origin.port = url.port ?? (scheme == "https" ? 443 : 80) + return origin + } +} diff --git a/Widget/Files/FilesData.swift b/Widget/Files/FilesData.swift index fdcf4d26f5..8b448559e8 100644 --- a/Widget/Files/FilesData.swift +++ b/Widget/Files/FilesData.swift @@ -5,6 +5,7 @@ import UIKit import WidgetKit import Intents +import ImageIO import NextcloudKit struct FilesDataEntry: TimelineEntry { @@ -172,30 +173,7 @@ func getFilesDataEntry(configuration: AccountIntent, displaySize: CGSize) async ] guard let url = components.url else { continue } - // IMAGE - image = utility.getImage(ocId: file.ocId, - etag: file.etag, - ext: NCGlobal.shared.previewExt512, - userId: activeTableAccount.userId, - urlBase: activeTableAccount.urlBase) - if image == nil, file.hasPreview { - let result = await NextcloudKit.shared.downloadPreviewAsync(fileId: file.fileId, - etag: file.etag, - account: activeTableAccount.account, - options: options) - if result.error == .success, let data = result.responseData?.data { - utility.createImageFileFrom(data: data, - ocId: file.ocId, - etag: file.etag, - userId: activeTableAccount.userId, - urlBase: activeTableAccount.urlBase) - image = utility.getImage(ocId: file.ocId, - etag: file.etag, - ext: NCGlobal.shared.previewExt256, - userId: activeTableAccount.userId, - urlBase: activeTableAccount.urlBase) - } - } + image = await loadFilesWidgetPreview(for: file, account: activeTableAccount, fileSystem: utilityFileSystem, options: options) if image == nil { image = utility.loadImage(named: file.iconName, useTypeIconFile: true, account: file.account) useTypeIconFile = true @@ -217,3 +195,52 @@ func getFilesDataEntry(configuration: AccountIntent, displaySize: CGSize) async return(FilesDataEntry(date: Date(), datas: datas, isPlaceholder: false, isEmpty: datas.isEmpty, allowsRefresh: true, footerImage: "checkmark.icloud", footerText: footerText)) } } + +private func loadFilesWidgetPreview(for file: NKFile, + account: tableAccount, + fileSystem: NCUtilityFileSystem, + options: NKRequestOptions) async -> UIImage? { + let thumbnailSize = NCGlobal.shared.size256 + let thumbnailPath = fileSystem.getDirectoryProviderStorageImageOcId(file.ocId, + etag: file.etag, + ext: NCGlobal.shared.previewExt256, + userId: account.userId, + urlBase: account.urlBase) + let thumbnailURL = URL(fileURLWithPath: thumbnailPath) + if let image = UIImage.downsample(imageAt: thumbnailURL, to: thumbnailSize, scale: 1) { + return image + } + + let largerPath = fileSystem.getDirectoryProviderStorageImageOcId(file.ocId, + etag: file.etag, + ext: NCGlobal.shared.previewExt512, + userId: account.userId, + urlBase: account.urlBase) + if let image = UIImage.downsample(imageAt: URL(fileURLWithPath: largerPath), to: thumbnailSize, scale: 1) { + return image + } + + let result = await NextcloudKit.shared.downloadPreviewAsync(fileId: file.fileId, + width: Int(thumbnailSize.width), + height: Int(thumbnailSize.height), + etag: file.etag, + account: account.account, + options: options) + guard result.error == .success, + let data = result.responseData?.data else { return nil } + + let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary + guard let source = CGImageSourceCreateWithData(data as CFData, sourceOptions) else { return nil } + + let thumbnailOptions = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: Int(thumbnailSize.width) + ] as CFDictionary + guard let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, thumbnailOptions) else { return nil } + let image = UIImage(cgImage: thumbnail) + if let jpeg = image.jpegData(compressionQuality: 0.7) { + try? jpeg.write(to: thumbnailURL, options: .atomic) + } + return image +} diff --git a/iOSClient/Networking/NCService.swift b/iOSClient/Networking/NCService.swift index c2727eaee0..28fdbd470c 100644 --- a/iOSClient/Networking/NCService.swift +++ b/iOSClient/Networking/NCService.swift @@ -125,7 +125,7 @@ class NCService: NSObject { for widget in dashboardWidgets { guard let url = URL(string: widget.iconUrl), let fileName = widget.iconClass, - let data = await utility.downloadDashboardIcon(from: url, account: account) else { continue } + let data = await DashboardIconDownloader.download(from: url, account: account) else { continue } let size = CGSize(width: 256, height: 256) let image: UIImage? diff --git a/iOSClient/Utility/NCUtility+Image.swift b/iOSClient/Utility/NCUtility+Image.swift index b715e7196a..94e9dc459d 100644 --- a/iOSClient/Utility/NCUtility+Image.swift +++ b/iOSClient/Utility/NCUtility+Image.swift @@ -5,44 +5,12 @@ import Foundation import UIKit import NextcloudKit -import Alamofire import PDFKit import Accelerate import CoreMedia import Photos extension NCUtility { - func downloadDashboardIcon(from url: URL, account: String) async -> Data? { - let networking = NextcloudKit.shared.nkCommonInstance - guard let session = networking.nksessions.session(forAccount: account), - let serverURL = URL(string: session.urlBase), - Self.isDashboardIconOnServer(url, serverURL: serverURL), - let headers = networking.getStandardHeaders(account: account) else { return nil } - - let redirector = Redirector(behavior: .modify { _, request, _ in - guard let destination = request.url, - Self.isDashboardIconOnServer(destination, serverURL: serverURL) else { return nil } - return request - }) - - return try? await session.sessionData.request(url, headers: headers) - .redirect(using: redirector) - .validate(statusCode: 200..<300) - .serializingData() - .value - } - - private nonisolated static func isDashboardIconOnServer(_ url: URL, serverURL: URL) -> Bool { - guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", - scheme == serverURL.scheme?.lowercased(), - let host = url.host?.lowercased(), !host.isEmpty, - host == serverURL.host?.lowercased(), - url.user == nil, url.password == nil else { return false } - - let defaultPort = scheme == "https" ? 443 : 80 - return (url.port ?? defaultPort) == (serverURL.port ?? defaultPort) - } - func loadImage(named imageName: String, colors: [UIColor]? = nil, size: CGFloat? = nil, From e10534874c56b726f961924c0f317586fedb9f54 Mon Sep 17 00:00:00 2001 From: Marino Faggiana Date: Mon, 16 Nov 2026 17:01:07 +0100 Subject: [PATCH 2/4] refactor: simplify widget preview and thumbnail handling Use NextcloudKit for dashboard icon downloads and share thumbnail creation for files and data. Avoid writing widget-only thumbnails to the shared preview cache. Signed-off-by: Marino Faggiana --- Nextcloud.xcodeproj/project.pbxproj | 6 -- Widget/Dashboard/DashboardData.swift | 9 +-- .../Dashboard/DashboardIconDownloader.swift | 76 ------------------- Widget/Files/FilesData.swift | 11 +-- iOSClient/Extensions/UIImage+Extension.swift | 23 +++--- .../Create/NCCreateFormUploadConflict.swift | 2 +- iOSClient/Networking/NCService.swift | 6 +- 7 files changed, 25 insertions(+), 108 deletions(-) delete mode 100644 Widget/Dashboard/DashboardIconDownloader.swift diff --git a/Nextcloud.xcodeproj/project.pbxproj b/Nextcloud.xcodeproj/project.pbxproj index 72b988d527..b7eca39393 100644 --- a/Nextcloud.xcodeproj/project.pbxproj +++ b/Nextcloud.xcodeproj/project.pbxproj @@ -1002,8 +1002,6 @@ F7DF7B422F1A36C100514020 /* HelperBanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7DF7B412F1A36B600514020 /* HelperBanner.swift */; }; F7DF7B432F1A373E00514020 /* HelperBanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7DF7B412F1A36B600514020 /* HelperBanner.swift */; }; F7E0710128B13BB00001B882 /* DashboardData.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7E0710028B13BB00001B882 /* DashboardData.swift */; }; - B3DD1800F0A0406C96253201 /* DashboardIconDownloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3DD1800F0A0406C96253200 /* DashboardIconDownloader.swift */; }; - B3DD1800F0A0406C96253202 /* DashboardIconDownloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3DD1800F0A0406C96253200 /* DashboardIconDownloader.swift */; }; F7E250002FE1000000000002 /* NCDocumentEditorSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7E250002FE1000000000001 /* NCDocumentEditorSupport.swift */; }; F7E250002FE1000000000003 /* NCDocumentEditorSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7E250002FE1000000000001 /* NCDocumentEditorSupport.swift */; }; F7E250002FE1000000000004 /* NCDocumentEditorSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7E250002FE1000000000001 /* NCDocumentEditorSupport.swift */; }; @@ -2050,7 +2048,6 @@ F7DF7B3E2F1A2EE400514020 /* WarningBannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WarningBannerView.swift; sourceTree = ""; }; F7DF7B412F1A36B600514020 /* HelperBanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HelperBanner.swift; sourceTree = ""; }; F7E0710028B13BB00001B882 /* DashboardData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardData.swift; sourceTree = ""; }; - B3DD1800F0A0406C96253200 /* DashboardIconDownloader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardIconDownloader.swift; sourceTree = ""; }; F7E250002FE1000000000001 /* NCDocumentEditorSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCDocumentEditorSupport.swift; sourceTree = ""; }; F7E2B64E2DDCC5C30075B4D0 /* NCMedia+TransferDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NCMedia+TransferDelegate.swift"; sourceTree = ""; }; F7E402282BA85D1D007E5609 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; @@ -2701,7 +2698,6 @@ isa = PBXGroup; children = ( F7E0710028B13BB00001B882 /* DashboardData.swift */, - B3DD1800F0A0406C96253200 /* DashboardIconDownloader.swift */, F72EA95128B7BA2A00C88F0C /* DashboardWidgetProvider.swift */, F72A17D728B221E300F3F159 /* DashboardWidgetView.swift */, ); @@ -4897,7 +4893,6 @@ F76DEE9928F808AF0041B1C9 /* LockscreenWidgetView.swift in Sources */, F78302F928B4C3E600B84583 /* NCManageDatabase+Account.swift in Sources */, F7E0710128B13BB00001B882 /* DashboardData.swift in Sources */, - B3DD1800F0A0406C96253201 /* DashboardIconDownloader.swift in Sources */, F783030328B4C4DD00B84583 /* ThreadSafeDictionary.swift in Sources */, F7CAFE1E2F17A37C00DB35A5 /* ProgressQuantizer.swift in Sources */, F78302F728B4C3C900B84583 /* NCManageDatabase.swift in Sources */, @@ -5299,7 +5294,6 @@ AF93471227E2341B002537EE /* NCContextMenuShare.swift in Sources */, F7EFA47825ADBA500083159A /* NCViewerProviderContextMenu.swift in Sources */, F755BD9B20594AC7008C5FBB /* NCService.swift in Sources */, - B3DD1800F0A0406C96253202 /* DashboardIconDownloader.swift in Sources */, F74B91E92F51D45A0050813D /* ErrorBannerView.swift in Sources */, F7E8A391295DC5E0006CB2D0 /* View+Extension.swift in Sources */, F7CB77642F5843E500DE649A /* UIFont+Extension.swift in Sources */, diff --git a/Widget/Dashboard/DashboardData.swift b/Widget/Dashboard/DashboardData.swift index 9c6b3e0463..2de33f8288 100644 --- a/Widget/Dashboard/DashboardData.swift +++ b/Widget/Dashboard/DashboardData.swift @@ -187,7 +187,7 @@ func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) if let iconClass = module?.iconClass { let fileSystem = NCUtilityFileSystem() let path = fileSystem.createServerUrl(serverUrl: fileSystem.directoryUserData, fileName: iconClass + ".png") - titleImage = UIImage.downsample(imageAt: URL(fileURLWithPath: path), to: iconSize, scale: 3) + titleImage = UIImage.thumbnail(imageAt: URL(fileURLWithPath: path), to: iconSize, scale: 3) } else { titleImage = nil } @@ -238,10 +238,9 @@ func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) } else if iconURL.pathComponents.contains("getCalendarDotSvg") { calendarColor = UIColor(hex: (iconURL.lastPathComponent as NSString).deletingPathExtension) } else { - let destination = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: destination) } - if let iconFile = await DashboardIconDownloader.download(from: iconURL, account: account.account, to: destination) { - icon = UIImage.downsample(imageAt: iconFile, to: iconSize, scale: 3) + let result = await NextcloudKit.shared.downloadPreviewAsync(url: iconURL, account: account.account) + if result.error == .success, let data = result.responseData?.data { + icon = UIImage.thumbnail(from: data, to: iconSize, scale: 3) } } } diff --git a/Widget/Dashboard/DashboardIconDownloader.swift b/Widget/Dashboard/DashboardIconDownloader.swift deleted file mode 100644 index 61a9289617..0000000000 --- a/Widget/Dashboard/DashboardIconDownloader.swift +++ /dev/null @@ -1,76 +0,0 @@ -// SPDX-FileCopyrightText: Nextcloud GmbH -// SPDX-FileCopyrightText: 2026 Marino Faggiana -// SPDX-License-Identifier: GPL-3.0-or-later - -import Foundation -import Alamofire -import NextcloudKit - -nonisolated enum DashboardIconDownloader { - static func download(from url: URL, account: String) async -> Data? { - guard let (session, headers, redirector) = dashboardIconRequest(for: url, account: account) else { return nil } - let response = await session.request(url, headers: headers) - .redirect(using: redirector) - .validate(statusCode: 200..<300) - .serializingData() - .response - guard headers != nil, let destination = Self.dashboardIconRedirect(from: response.response) else { return response.value } - return try? await AF.request(destination) - .validate(statusCode: 200..<300) - .serializingData() - .value - } - - static func download(from url: URL, account: String, to destination: URL) async -> URL? { - guard let (session, headers, redirector) = dashboardIconRequest(for: url, account: account) else { return nil } - let target: DownloadRequest.Destination = { _, _ in (destination, [.removePreviousFile]) } - let response = await session.download(url, headers: headers, to: target) - .redirect(using: redirector) - .validate(statusCode: 200..<300) - .serializingDownloadedFileURL() - .response - guard headers != nil, let redirectedURL = Self.dashboardIconRedirect(from: response.response) else { return response.value } - return try? await AF.download(redirectedURL, to: target) - .validate(statusCode: 200..<300) - .serializingDownloadedFileURL() - .value - } - - private static func dashboardIconRequest(for url: URL, account: String) -> (Session, HTTPHeaders?, Redirector)? { - let networking = NextcloudKit.shared.nkCommonInstance - guard let session = networking.nksessions.session(forAccount: account), - let serverURL = URL(string: session.urlBase), - let serverOrigin = Self.dashboardCredentialOrigin(serverURL), - let iconOrigin = Self.dashboardCredentialOrigin(url) else { return nil } - - // External icons can be public. Only attach account headers to the account's origin. - guard iconOrigin == serverOrigin else { - return (.default, nil, Redirector(behavior: .follow)) - } - guard let headers = networking.getStandardHeaders(account: account) else { return nil } - - let redirector = Redirector(behavior: .modify { _, request, _ in - request.url.flatMap(Self.dashboardCredentialOrigin) == serverOrigin ? request : nil - }) - - return (session.sessionData, headers, redirector) - } - - private nonisolated static func dashboardIconRedirect(from response: HTTPURLResponse?) -> URL? { - guard let response, (300..<400).contains(response.statusCode), - let location = response.value(forHTTPHeaderField: "Location"), - let destination = URL(string: location, relativeTo: response.url)?.absoluteURL, - dashboardCredentialOrigin(destination) != nil else { return nil } - return destination - } - - private nonisolated static func dashboardCredentialOrigin(_ url: URL) -> URLComponents? { - guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", - let host = url.host?.lowercased(), !host.isEmpty else { return nil } - var origin = URLComponents() - origin.scheme = scheme - origin.host = host - origin.port = url.port ?? (scheme == "https" ? 443 : 80) - return origin - } -} diff --git a/Widget/Files/FilesData.swift b/Widget/Files/FilesData.swift index 8b448559e8..c684185ad8 100644 --- a/Widget/Files/FilesData.swift +++ b/Widget/Files/FilesData.swift @@ -207,7 +207,7 @@ private func loadFilesWidgetPreview(for file: NKFile, userId: account.userId, urlBase: account.urlBase) let thumbnailURL = URL(fileURLWithPath: thumbnailPath) - if let image = UIImage.downsample(imageAt: thumbnailURL, to: thumbnailSize, scale: 1) { + if let image = UIImage.thumbnail(imageAt: thumbnailURL, to: thumbnailSize, scale: 1) { return image } @@ -216,7 +216,7 @@ private func loadFilesWidgetPreview(for file: NKFile, ext: NCGlobal.shared.previewExt512, userId: account.userId, urlBase: account.urlBase) - if let image = UIImage.downsample(imageAt: URL(fileURLWithPath: largerPath), to: thumbnailSize, scale: 1) { + if let image = UIImage.thumbnail(imageAt: URL(fileURLWithPath: largerPath), to: thumbnailSize, scale: 1) { return image } @@ -238,9 +238,6 @@ private func loadFilesWidgetPreview(for file: NKFile, kCGImageSourceThumbnailMaxPixelSize: Int(thumbnailSize.width) ] as CFDictionary guard let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, thumbnailOptions) else { return nil } - let image = UIImage(cgImage: thumbnail) - if let jpeg = image.jpegData(compressionQuality: 0.7) { - try? jpeg.write(to: thumbnailURL, options: .atomic) - } - return image + // The shared preview cache expects all three sizes. Use this thumbnail only for the widget entry. + return UIImage(cgImage: thumbnail) } diff --git a/iOSClient/Extensions/UIImage+Extension.swift b/iOSClient/Extensions/UIImage+Extension.swift index c3b6094eea..c1aef55d5b 100644 --- a/iOSClient/Extensions/UIImage+Extension.swift +++ b/iOSClient/Extensions/UIImage+Extension.swift @@ -163,25 +163,29 @@ extension UIImage { return newImage } - /// Downsamles a image using ImageIO. Has better memory perfomance than redrawing using UIKit + /// Creates a thumbnail from an image file using Image I/O. /// /// - [Source](https://swiftsenpai.com/development/reduce-uiimage-memory-footprint/) /// - [Original Source, WWDC18](https://developer.apple.com/videos/play/wwdc2018/416/?time=1352) /// - Parameters: /// - imageURL: The URL path of the image /// - pointSize: The target point size - /// - scale: The point to pixel scale (Pixeld per point) - /// - Returns: The downsampled image, if successful - static func downsample(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat) -> UIImage? { - - // Create an CGImageSource that represent an image + /// - scale: The number of pixels per point + /// - Returns: The thumbnail, if successful + static func thumbnail(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat) -> UIImage? { let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions) else { return nil } + return thumbnail(from: imageSource, to: pointSize, scale: scale) + } - // Calculate the desired dimension - let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale + static func thumbnail(from data: Data, to pointSize: CGSize, scale: CGFloat) -> UIImage? { + let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary + guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else { return nil } + return thumbnail(from: imageSource, to: pointSize, scale: scale) + } - // Perform downsampling + private static func thumbnail(from imageSource: CGImageSource, to pointSize: CGSize, scale: CGFloat) -> UIImage? { + let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale let downsampleOptions = [ kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceShouldCacheImmediately: true, @@ -190,7 +194,6 @@ extension UIImage { ] as CFDictionary guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else { return nil } - // Return the downsampled image as UIImage return UIImage(cgImage: downsampledImage) } diff --git a/iOSClient/Main/Create/NCCreateFormUploadConflict.swift b/iOSClient/Main/Create/NCCreateFormUploadConflict.swift index 59d55f3918..32275b2d75 100644 --- a/iOSClient/Main/Create/NCCreateFormUploadConflict.swift +++ b/iOSClient/Main/Create/NCCreateFormUploadConflict.swift @@ -445,7 +445,7 @@ extension NCCreateFormUploadConflict: UITableViewDataSource { do { if metadataNewFile.classFile == NKTypeClassFile.image.rawValue { // preserver memory especially for very large files in Share extension - if let image = UIImage.downsample( + if let image = UIImage.thumbnail( imageAt: URL(fileURLWithPath: filePathNewFile), to: cell.imageNewFile.frame.size, scale: cell.imageNewFile.traitCollection.displayScale diff --git a/iOSClient/Networking/NCService.swift b/iOSClient/Networking/NCService.swift index 28fdbd470c..189ad38a3d 100644 --- a/iOSClient/Networking/NCService.swift +++ b/iOSClient/Networking/NCService.swift @@ -123,9 +123,9 @@ class NCService: NSObject { dashboardWidgets: dashboardWidgets, preferredItemAPIVersions: catalog?.preferredItemAPIVersions ?? [:]) for widget in dashboardWidgets { - guard let url = URL(string: widget.iconUrl), - let fileName = widget.iconClass, - let data = await DashboardIconDownloader.download(from: url, account: account) else { continue } + guard let url = URL(string: widget.iconUrl), let fileName = widget.iconClass else { continue } + let result = await NextcloudKit.shared.downloadPreviewAsync(url: url, account: account) + guard result.error == .success, let data = result.responseData?.data else { continue } let size = CGSize(width: 256, height: 256) let image: UIImage? From 3615e738be7f13e384253e0b9d4b52ee59ab8f4f Mon Sep 17 00:00:00 2001 From: Marino Faggiana Date: Mon, 16 Nov 2026 17:02:01 +0100 Subject: [PATCH 3/4] chore: bump build number to 4 Signed-off-by: Marino Faggiana --- Nextcloud.xcodeproj/project.pbxproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Nextcloud.xcodeproj/project.pbxproj b/Nextcloud.xcodeproj/project.pbxproj index b7eca39393..c417bfcbcf 100644 --- a/Nextcloud.xcodeproj/project.pbxproj +++ b/Nextcloud.xcodeproj/project.pbxproj @@ -6618,7 +6618,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 3; + CURRENT_PROJECT_VERSION = 4; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; DEVELOPMENT_TEAM = NKUJUXUJ3B; @@ -6685,7 +6685,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 3; + CURRENT_PROJECT_VERSION = 4; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEVELOPMENT_TEAM = NKUJUXUJ3B; From 813a8b117ca31b5d8f774fa16e4ffc3c1a3cef36 Mon Sep 17 00:00:00 2001 From: Marino Faggiana Date: Mon, 16 Nov 2026 17:39:43 +0100 Subject: [PATCH 4/4] fix: enable Notes dashboard widget actions Route Notes new and more actions through browser deep links and keep the more action visible when all rows fit. Signed-off-by: Marino Faggiana --- Widget/Dashboard/DashboardData.swift | 19 ++++++++++++------- Widget/Dashboard/DashboardWidgetView.swift | 10 +--------- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/Widget/Dashboard/DashboardData.swift b/Widget/Dashboard/DashboardData.swift index 2de33f8288..aacf86c022 100644 --- a/Widget/Dashboard/DashboardData.swift +++ b/Widget/Dashboard/DashboardData.swift @@ -159,12 +159,7 @@ func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) let title = module?.title ?? moduleId let baseURL = URL(string: account.urlBase) let actions = (moduleButtons ?? []).compactMap { button -> DashboardAction? in - switch (moduleId, button.type) { - case ("notes", "new"), ("notes", "more"), ("circles", "setup"): - return nil - default: - break - } + if moduleId == "circles", button.type == "setup" { return nil } let isMore = button.type == "more" let url: URL? @@ -174,11 +169,13 @@ func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) components.host = "openFavorites" components.queryItems = [URLQueryItem(name: "account", value: account.account)] url = components.url + } else if moduleId == "notes", button.type == "new" || isMore { + url = dashboardWebURL(button.link, relativeTo: baseURL).flatMap(dashboardBrowserDeepLink(for:)) } else { url = dashboardWebURL(button.link, relativeTo: baseURL) } guard let url else { return nil } - let hidesWhenAllRowsFit = isMore && moduleId != "files-favorites" && moduleId != "circles" + let hidesWhenAllRowsFit = isMore && !["files-favorites", "circles", "notes"].contains(moduleId) return DashboardAction(id: button.index, title: button.text, url: url, hidesWhenAllRowsFit: hidesWhenAllRowsFit) } @@ -315,6 +312,14 @@ private func getDashboardModuleItems(_ moduleId: String, return (payload.ocs.data[moduleId]?.items ?? [], .success) } +func dashboardBrowserDeepLink(for webURL: URL) -> URL? { + var components = URLComponents() + components.scheme = NCGlobal.shared.appScheme + components.host = "openUrl" + components.queryItems = [URLQueryItem(name: "url", value: webURL.absoluteString)] + return components.url +} + private func dashboardWebURL(_ value: String?, relativeTo baseURL: URL?) -> URL? { guard let value, !value.isEmpty else { return nil } let url = value.hasPrefix("/") ? URL(string: value, relativeTo: baseURL)?.absoluteURL : URL(string: value) diff --git a/Widget/Dashboard/DashboardWidgetView.swift b/Widget/Dashboard/DashboardWidgetView.swift index a6a813e518..ec74aca665 100644 --- a/Widget/Dashboard/DashboardWidgetView.swift +++ b/Widget/Dashboard/DashboardWidgetView.swift @@ -49,7 +49,7 @@ struct DashboardWidgetView: View { VStack(alignment: .leading, spacing: DashboardWidgetLayout.sectionSpacing) { header - if let webURL = entry.webURL, let browserURL = browserDeepLink(for: webURL) { + if let webURL = entry.webURL, let browserURL = dashboardBrowserDeepLink(for: webURL) { VStack(spacing: 10) { Text(NSLocalizedString("_widget_dashboard_available_on_web_", value: "Available on the web", comment: "")) .font(.subheadline) @@ -97,14 +97,6 @@ struct DashboardWidgetView: View { .containerBackground(.background, for: .widget) } - private func browserDeepLink(for webURL: URL) -> URL? { - var components = URLComponents() - components.scheme = NCGlobal.shared.appScheme - components.host = "openUrl" - components.queryItems = [URLQueryItem(name: "url", value: webURL.absoluteString)] - return components.url - } - private var header: some View { HStack(spacing: 8) { Image(uiImage: entry.titleImage)