diff --git a/Brand/Database.swift b/Brand/Database.swift index 1ffb5a9bf2..019fbc8762 100644 --- a/Brand/Database.swift +++ b/Brand/Database.swift @@ -8,4 +8,4 @@ import Foundation // let databaseName = "nextcloud.realm" let tableAccountBackup = "tableAccountBackup.json" -let databaseSchemaVersion: UInt64 = 424 +let databaseSchemaVersion: UInt64 = 425 diff --git a/Nextcloud.xcodeproj/project.pbxproj b/Nextcloud.xcodeproj/project.pbxproj index 0fe671df9d..b7eca39393 100644 --- a/Nextcloud.xcodeproj/project.pbxproj +++ b/Nextcloud.xcodeproj/project.pbxproj @@ -380,7 +380,6 @@ F733598125C1C188002ABA72 /* NCAskAuthorization.swift in Sources */ = {isa = PBXBuildFile; fileRef = F733598025C1C188002ABA72 /* NCAskAuthorization.swift */; }; F7346E1628B0EF5C006CE2D2 /* Widget.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7346E1528B0EF5C006CE2D2 /* Widget.swift */; }; F7346E1C28B0EF5E006CE2D2 /* Widget.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = F7346E1028B0EF5B006CE2D2 /* Widget.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; - F7346E2328B0FEBA006CE2D2 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = F7346E2228B0FEBA006CE2D2 /* Assets.xcassets */; }; F734B06628E75C0100E180D5 /* TLPhotoPicker in Frameworks */ = {isa = PBXBuildFile; productRef = F734B06528E75C0100E180D5 /* TLPhotoPicker */; }; F7362A1F220C853A005101B5 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = F7362A1E220C853A005101B5 /* LaunchScreen.storyboard */; }; F7381EE1218218C9000B1560 /* NCOffline.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7381EDA218218C9000B1560 /* NCOffline.swift */; }; @@ -728,9 +727,6 @@ F77E8C232E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77E8C1E2E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift */; }; F77E8C242E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77E8C1E2E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift */; }; F77E8C252E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77E8C1E2E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift */; }; - F77ED59128C9CE9D00E24ED0 /* ToolbarData.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77ED59028C9CE9D00E24ED0 /* ToolbarData.swift */; }; - F77ED59328C9CEA000E24ED0 /* ToolbarWidgetProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77ED59228C9CEA000E24ED0 /* ToolbarWidgetProvider.swift */; }; - F77ED59528C9CEA400E24ED0 /* ToolbarWidgetView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77ED59428C9CEA300E24ED0 /* ToolbarWidgetView.swift */; }; F78026102E9CFA3700B63436 /* NCTransfersView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F780260F2E9CF9DE00B63436 /* NCTransfersView.swift */; }; F78026122E9CFA6300B63436 /* NCTransfersModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = F78026112E9CFA6000B63436 /* NCTransfersModel.swift */; }; F7802B322BD5584F00D74270 /* NCMedia+DragDrop.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7802B312BD5584F00D74270 /* NCMedia+DragDrop.swift */; }; @@ -1591,7 +1587,6 @@ F7346E1028B0EF5B006CE2D2 /* Widget.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = Widget.appex; sourceTree = BUILT_PRODUCTS_DIR; }; F7346E1528B0EF5C006CE2D2 /* Widget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Widget.swift; sourceTree = ""; }; F7346E2028B0FA3A006CE2D2 /* Widget-Brinding-header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Widget-Brinding-header.h"; sourceTree = ""; }; - F7346E2228B0FEBA006CE2D2 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; F7362A1E220C853A005101B5 /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = LaunchScreen.storyboard; sourceTree = ""; }; F7381EDA218218C9000B1560 /* NCOffline.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NCOffline.swift; sourceTree = ""; }; F7381EDE218218C9000B1560 /* NCOffline.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = NCOffline.storyboard; sourceTree = ""; }; @@ -1825,9 +1820,6 @@ F77C97382953131000FDDD09 /* NCCameraRoll.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCCameraRoll.swift; sourceTree = ""; }; F77DD6A72C5CC093009448FB /* NCSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCSession.swift; sourceTree = ""; }; F77E8C1E2E79717D00EAE68F /* NCManageDatabase+LivePhoto.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NCManageDatabase+LivePhoto.swift"; sourceTree = ""; }; - F77ED59028C9CE9D00E24ED0 /* ToolbarData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolbarData.swift; sourceTree = ""; }; - F77ED59228C9CEA000E24ED0 /* ToolbarWidgetProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolbarWidgetProvider.swift; sourceTree = ""; }; - F77ED59428C9CEA300E24ED0 /* ToolbarWidgetView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolbarWidgetView.swift; sourceTree = ""; }; F780260F2E9CF9DE00B63436 /* NCTransfersView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCTransfersView.swift; sourceTree = ""; }; F78026112E9CFA6000B63436 /* NCTransfersModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCTransfersModel.swift; sourceTree = ""; }; F7802B312BD5584F00D74270 /* NCMedia+DragDrop.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NCMedia+DragDrop.swift"; sourceTree = ""; }; @@ -2725,11 +2717,9 @@ F7346E1428B0EF5B006CE2D2 /* Widget */ = { isa = PBXGroup; children = ( - F7346E2228B0FEBA006CE2D2 /* Assets.xcassets */, F72EA95528B7BAD100C88F0C /* Dashboard */, F72EA95628B7BAE700C88F0C /* Files */, F76DEE9A28F808BC0041B1C9 /* Lockscreen */, - F77ED59628C9CEEE00E24ED0 /* Toolbar */, F75DD764290AB369002EB562 /* Intent */, F7346E2028B0FA3A006CE2D2 /* Widget-Brinding-header.h */, F7346E1528B0EF5C006CE2D2 /* Widget.swift */, @@ -3325,16 +3315,6 @@ path = Test; sourceTree = ""; }; - F77ED59628C9CEEE00E24ED0 /* Toolbar */ = { - isa = PBXGroup; - children = ( - F77ED59028C9CE9D00E24ED0 /* ToolbarData.swift */, - F77ED59228C9CEA000E24ED0 /* ToolbarWidgetProvider.swift */, - F77ED59428C9CEA300E24ED0 /* ToolbarWidgetView.swift */, - ); - path = Toolbar; - sourceTree = ""; - }; F78ACD4721903F850088454D /* Cell */ = { isa = PBXGroup; children = ( @@ -4478,7 +4458,6 @@ F7C7B25028B8AD4500E7115D /* Localizable.strings in Resources */, F7E4022A2BA85D1D007E5609 /* PrivacyInfo.xcprivacy in Resources */, AA517B832D660EFE00F8D37C /* Localizable.stringsdict in Resources */, - F7346E2328B0FEBA006CE2D2 /* Assets.xcassets in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -4916,7 +4895,6 @@ F7E0710128B13BB00001B882 /* DashboardData.swift in Sources */, F783030328B4C4DD00B84583 /* ThreadSafeDictionary.swift in Sources */, F7CAFE1E2F17A37C00DB35A5 /* ProgressQuantizer.swift in Sources */, - F77ED59128C9CE9D00E24ED0 /* ToolbarData.swift in Sources */, F78302F728B4C3C900B84583 /* NCManageDatabase.swift in Sources */, F7346E1628B0EF5C006CE2D2 /* Widget.swift in Sources */, F7D61EAA2EBF1694007F865B /* NCManageDatabase+TableCapabilities.swift in Sources */, @@ -4955,9 +4933,7 @@ F763D29E2A249C4500A3C901 /* NCManageDatabase+Capabilities.swift in Sources */, F711A4DD2AF92CAE00095DD8 /* NCUtility+Date.swift in Sources */, F724377C2C10B92200C7C68D /* NCSharePermissions.swift in Sources */, - F77ED59328C9CEA000E24ED0 /* ToolbarWidgetProvider.swift in Sources */, F72A17D828B221E300F3F159 /* DashboardWidgetView.swift in Sources */, - F77ED59528C9CEA400E24ED0 /* ToolbarWidgetView.swift in Sources */, F78302FB28B4C3EE00B84583 /* NCManageDatabase+Video.swift in Sources */, F760A4902FE95D06001B212E /* NCTransferDelegateDispatcher.swift in Sources */, F7C687EA2D22BDE5004757BC /* NCManageDatabase+RecommendedFiles.swift in Sources */, @@ -6291,8 +6267,6 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = YES; - ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; - ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground; CLANG_ANALYZER_NONNULL = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; @@ -6325,8 +6299,6 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = YES; - ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; - ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground; CLANG_ANALYZER_NONNULL = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; diff --git a/Nextcloud.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Nextcloud.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 10fc3fdd33..c60b8ec71d 100644 --- a/Nextcloud.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Nextcloud.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "7880536aedfe5f5b326df402ac666a6126ac1b325106ab3eb7b6c78a6ef725ff", + "originHash" : "5236b0018852b3d5fa374f118d9825d5acd8f4ce80430d339706d09182995ba2", "pins" : [ { "identity" : "abseil-cpp-binary", @@ -209,11 +209,11 @@ } }, { - "identity" : "openssl", + "identity" : "openssl-package", "kind" : "remoteSourceControl", - "location" : "https://github.com/krzyzanowskim/OpenSSL", + "location" : "https://github.com/krzyzanowskim/OpenSSL-Package", "state" : { - "revision" : "0a6149bff4fb00921ce0ec1811f726b166638095", + "revision" : "4ac3f9a68731cb3cf736a591814bad9a7a2008c8", "version" : "3.6.5000" } }, @@ -262,15 +262,6 @@ "version" : "20.0.6" } }, - { - "identity" : "swift-atomics", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-atomics.git", - "state" : { - "revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34", - "version" : "1.3.1" - } - }, { "identity" : "swift-collections", "kind" : "remoteSourceControl", @@ -280,33 +271,6 @@ "version" : "1.7.6" } }, - { - "identity" : "swift-nio", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-nio.git", - "state" : { - "revision" : "2f58d8ef84438d6517fc78bcea2f8527e3c72936", - "version" : "2.105.0" - } - }, - { - "identity" : "swift-nio-ssl", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-nio-ssl", - "state" : { - "revision" : "322f3c2a4a21df31c84ca416bf65ee5e9059e440", - "version" : "2.37.5" - } - }, - { - "identity" : "swift-system", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-system.git", - "state" : { - "revision" : "640e5755b5826f4437eaeedd366fd776737db62c", - "version" : "1.9.0" - } - }, { "identity" : "swifter", "kind" : "remoteSourceControl", diff --git a/REUSE.toml b/REUSE.toml index 976a6d6713..86072d894e 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -30,7 +30,7 @@ SPDX-FileCopyrightText = "2016-2026 Nextcloud GmbH and Nextcloud contributors" SPDX-License-Identifier = "GPL-3.0-or-later" [[annotations]] -path = ["iOSClient/Images.xcassets/**", "Widget/Assets.xcassets/**", "Action Assistant/Images.xcassets/**"] +path = ["iOSClient/Images.xcassets/**", "Action Assistant/Images.xcassets/**"] precedence = "aggregate" SPDX-FileCopyrightText = "2016-2026 Nextcloud GmbH and Nextcloud contributors" SPDX-License-Identifier = "GPL-3.0-or-later" @@ -56,7 +56,7 @@ SPDX-License-Identifier = "GPL-3.0-or-later" # The Nextcloud name and logo are trademarks; see LICENSES/LicenseRef-NextcloudTrademarks.txt [[annotations]] -path = ["AppIcon.icon/**", "Brand/Custom.xcassets/AppIcon.appiconset/**", "Brand/Custom.xcassets/logo.imageset/**", "Action Assistant/Images.xcassets/AppIcon.appiconset/**", "Widget/Assets.xcassets/AppIcon.imageset/**", "iOSClient/Images.xcassets/logo.imageset/**"] +path = ["AppIcon.icon/**", "Brand/Custom.xcassets/AppIcon.appiconset/**", "Brand/Custom.xcassets/logo.imageset/**", "Action Assistant/Images.xcassets/AppIcon.appiconset/**", "iOSClient/Images.xcassets/logo.imageset/**"] precedence = "aggregate" SPDX-FileCopyrightText = "Nextcloud GmbH" SPDX-License-Identifier = "LicenseRef-NextcloudTrademarks" diff --git a/Share/Model/NCShareViewModel+Folders.swift b/Share/Model/NCShareViewModel+Folders.swift index 515a6d31b9..b0db54e14a 100644 --- a/Share/Model/NCShareViewModel+Folders.swift +++ b/Share/Model/NCShareViewModel+Folders.swift @@ -24,6 +24,7 @@ extension NCShareViewModel { func resetFolderBrowser(preservingContent: Bool = false) { folderBrowserID = UUID() folderSelectionTask?.cancel() + pendingFolderSelection = nil for task in folderTasks.values { task.cancel() } for request in folderRequests.values { request.cancel() } folderTasks.removeAll() @@ -117,12 +118,16 @@ extension NCShareViewModel { let session = sessionStore.getSession() let browserID = folderBrowserID isLoading = true + if !automatically { + pendingFolderSelection = (folder.serverUrl, fromRecents) + } folderSelectionTask = Task { @MainActor in defer { if isCurrentBrowser(browserID, account: session.account) { if automatically, isAuthenticated, selectedFolder == nil { selectedFolder = rootFolder } + pendingFolderSelection = nil isLoading = false } } diff --git a/Share/Model/NCShareViewModel.swift b/Share/Model/NCShareViewModel.swift index d407b67590..1be2ed3bb4 100644 --- a/Share/Model/NCShareViewModel.swift +++ b/Share/Model/NCShareViewModel.swift @@ -21,6 +21,7 @@ final class NCShareViewModel: NSObject, ObservableObject { @Published var recentFolders: [NCShareFolderItem] = [] @Published var selectedFolder: NCShareFolderItem? @Published var isRecentFolderSelected = false + @Published var pendingFolderSelection: (serverUrl: String, fromRecents: Bool)? @Published var folderScrollTarget: String? @Published var folderChildren: [String: [NCShareFolderItem]] = [:] @Published var expandedFolderURLs: Set = [] @@ -335,6 +336,7 @@ final class NCShareViewModel: NSObject, ObservableObject { func cancel(with error: NCShareRequestError? = nil) { guard !isClosing else { return } isClosing = true + pendingFolderSelection = nil alertDismissAction = nil stopRequestWork() thumbnailRequests.removeAll() diff --git a/Share/View/NCShareView.swift b/Share/View/NCShareView.swift index 6ceb3955e4..3d1897387c 100644 --- a/Share/View/NCShareView.swift +++ b/Share/View/NCShareView.swift @@ -231,7 +231,11 @@ struct NCShareView: View { } private func folderRow(_ folder: NCShareFolderItem, depth: Int?) -> some View { - let isSelected = model.selectedFolder?.serverUrl == folder.serverUrl && model.isRecentFolderSelected == (depth == nil) + let fromRecents = depth == nil + let isSelected = model.selectedFolder?.serverUrl == folder.serverUrl && model.isRecentFolderSelected == fromRecents + let isPending = model.pendingFolderSelection?.serverUrl == folder.serverUrl && + model.pendingFolderSelection?.fromRecents == fromRecents + let highlightOpacity: Double = isSelected ? 0.1 : (isPending ? 0.05 : 0) return HStack(spacing: 4) { if let depth { Button { @@ -253,7 +257,7 @@ struct NCShareView: View { .accessibilityHidden(true) } Button { - model.selectFolder(folder, fromRecents: depth == nil) + model.selectFolder(folder, fromRecents: fromRecents) } label: { HStack(spacing: 8) { if let image = folder.image { @@ -310,7 +314,7 @@ struct NCShareView: View { .disabled(!model.canUseFolderBrowser) .background { RoundedRectangle(cornerRadius: 8) - .fill(Color.accentColor.opacity(isSelected ? 0.1 : 0)) + .fill(Color.accentColor.opacity(highlightOpacity)) .padding(.horizontal, 5) } .listRowSeparator(.hidden) diff --git a/Widget/Assets.xcassets/AccentColor.colorset/Contents.json b/Widget/Assets.xcassets/AccentColor.colorset/Contents.json deleted file mode 100644 index eb87897008..0000000000 --- a/Widget/Assets.xcassets/AccentColor.colorset/Contents.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "colors" : [ - { - "idiom" : "universal" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Widget/Assets.xcassets/AppIcon.imageset/Contents.json b/Widget/Assets.xcassets/AppIcon.imageset/Contents.json deleted file mode 100644 index 6fe332016d..0000000000 --- a/Widget/Assets.xcassets/AppIcon.imageset/Contents.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Widget/Assets.xcassets/Contents.json b/Widget/Assets.xcassets/Contents.json deleted file mode 100644 index 73c00596a7..0000000000 --- a/Widget/Assets.xcassets/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Widget/Assets.xcassets/WidgetBackground.colorset/Contents.json b/Widget/Assets.xcassets/WidgetBackground.colorset/Contents.json deleted file mode 100644 index eb87897008..0000000000 --- a/Widget/Assets.xcassets/WidgetBackground.colorset/Contents.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "colors" : [ - { - "idiom" : "universal" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Widget/Assets.xcassets/activity.imageset/Contents.json b/Widget/Assets.xcassets/activity.imageset/Contents.json deleted file mode 100644 index e507da5dc6..0000000000 --- a/Widget/Assets.xcassets/activity.imageset/Contents.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "images" : [ - { - "filename" : "activity.png", - "idiom" : "universal" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Widget/Assets.xcassets/activity.imageset/activity.png b/Widget/Assets.xcassets/activity.imageset/activity.png deleted file mode 100644 index 8c2efb6151..0000000000 Binary files a/Widget/Assets.xcassets/activity.imageset/activity.png and /dev/null differ diff --git a/Widget/Dashboard/DashboardData.swift b/Widget/Dashboard/DashboardData.swift index 0a02f54f00..59da003dce 100644 --- a/Widget/Dashboard/DashboardData.swift +++ b/Widget/Dashboard/DashboardData.swift @@ -6,207 +6,316 @@ import UIKit import WidgetKit import Intents import NextcloudKit -import RealmSwift struct DashboardDataEntry: TimelineEntry { let date: Date - let datas: [DashboardData] - let dashboard: tableDashboardWidget? - let buttons: [tableDashboardWidgetButton]? + let rows: [DashboardData] + let totalRows: Int + let buttons: [DashboardAction] + let webURL: URL? let isPlaceholder: Bool - let isEmpty: Bool + let allowsRefresh: Bool let titleImage: UIImage let title: String let footerImage: String let footerText: String - let account: String } -struct DashboardData: Identifiable, Hashable { +struct DashboardData: Identifiable { let id: Int let title: String - let subTitle: String - let link: URL - let icon: UIImage - let circle: Bool - let imageSystem: Bool - let imageColor: UIColor? + let subtitle: String + let link: URL? + let icon: UIImage? + let isRound: Bool + let calendarColor: UIColor? } -let dashboardDatasTest: [DashboardData] = [ - .init(id: 0, title: "title0", subTitle: "subTitle-description0", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "document")!, circle: false, imageSystem: true, imageColor: nil), - .init(id: 1, title: "title1", subTitle: "subTitle-description1", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "document")!, circle: false, imageSystem: true, imageColor: nil), - .init(id: 2, title: "title2", subTitle: "subTitle-description2", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "document")!, circle: true, imageSystem: false, imageColor: nil), - .init(id: 3, title: "title3", subTitle: "subTitle-description3", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "document")!, circle: false, imageSystem: false, imageColor: nil), - .init(id: 4, title: "title4", subTitle: "subTitle-description4", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "circle.fill")!, circle: false, imageSystem: false, imageColor: nil), - .init(id: 5, title: "title5", subTitle: "subTitle-description5", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "circle.fill")!, circle: false, imageSystem: false, imageColor: nil), - .init(id: 6, title: "title6", subTitle: "subTitle-description6", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "circle.fill")!, circle: false, imageSystem: false, imageColor: nil), - .init(id: 7, title: "title7", subTitle: "subTitle-description7", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "circle.fill")!, circle: false, imageSystem: false, imageColor: nil), - .init(id: 8, title: "title8", subTitle: "subTitle-description8", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "circle.fill")!, circle: false, imageSystem: false, imageColor: nil), - .init(id: 9, title: "title9", subTitle: "subTitle-description9", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(systemName: "circle.fill")!, circle: false, imageSystem: false, imageColor: nil) -] - -func getDashboardItems(displaySize: CGSize, withButton: Bool) -> Int { - if withButton { - let items = Int((displaySize.height - 90) / 55) - return items - } else { - let items = Int((displaySize.height - 50) / 55) - return items +struct DashboardAction: Identifiable, Sendable { + let id: String + let title: String + let url: URL + let hidesWhenAllRowsFit: Bool +} + +private struct DashboardModuleItem: Decodable { + let title: String? + let subtitle: String? + let link: String? + let iconUrl: String? +} + +private struct DashboardItemsResponse: Decodable { + struct OCS: Decodable { + struct Meta: Decodable { + let statuscode: Int + let message: String? + } + + struct Module: Decodable { + let items: [DashboardModuleItem] + } + + let meta: Meta + let data: [String: Module] + + private enum CodingKeys: String, CodingKey { + case meta, data + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + meta = try container.decode(Meta.self, forKey: .meta) + if !(200..<300).contains(meta.statuscode) { + data = [:] + } else if let modules = try? container.decode([Module].self, forKey: .data), modules.isEmpty { + // OCS may encode an empty module map as a JSON array. + data = [:] + } else { + data = try container.decode([String: Module].self, forKey: .data) + } + } + } + + let ocs: OCS +} + +func dashboardSampleEntry(height: CGFloat, + title: String = "Dashboard", + titleImage: UIImage? = UIImage(systemName: "rectangle.grid.2x2"), + footerText: String = NCBrandOptions.shared.brand, + isError: Bool = false, + isPlaceholder: Bool = true) -> DashboardDataEntry { + let count = DashboardWidgetLayout.rowCount(for: height, hasActions: false) + let examples = ["Project plan", "Meeting notes", "Design review", "Team agenda", "Travel itinerary"] + let rows = (0.. DashboardDataEntry { - let utilityFileSystem = NCUtilityFileSystem() +func getDashboardDataEntry(configuration: DashboardIntent, displaySize: CGSize) async -> DashboardDataEntry { + let height = displaySize.height let utility = NCUtility() - let dashboardItems = getDashboardItems(displaySize: displaySize, withButton: false) - let datasPlaceholder = Array(dashboardDatasTest[0...dashboardItems - 1]) - var activeTableAccount: tableAccount? - let versionApp = NCUtility().getVersionMaintenance() guard let groupDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup), - let lastVersion = groupDefaults.string(forKey: NCGlobal.shared.udLastVersion), - lastVersion == versionApp else { - return (DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: nil, buttons: nil, isPlaceholder: true, isEmpty: false, titleImage: UIImage(systemName: "circle.fill") ?? UIImage(), title: "Dashboard", footerImage: "checkmark.icloud", footerText: NSLocalizedString("_version_mismatch_error_", comment: ""), account: "")) + groupDefaults.string(forKey: NCGlobal.shared.udLastVersion) == utility.getVersionMaintenance() else { + return dashboardSampleEntry(height: height, + footerText: NSLocalizedString("_version_mismatch_error_", comment: ""), + isError: true) } - if isPreview, - let image = UIImage(systemName: "circle.fill") { - return (DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: nil, buttons: nil, isPlaceholder: true, isEmpty: false, titleImage: image, title: "Dashboard", footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " dashboard", account: "")) - } + let accountIdentifier = configuration.accounts?.identifier ?? "active" + let database = NCManageDatabase.shared + let selectedAccount = accountIdentifier == "active" + ? database.getActiveTableAccount() + : database.getTableAccount(account: accountIdentifier) - let accountIdentifier: String = configuration?.accounts?.identifier ?? "active" - if accountIdentifier == "active" { - activeTableAccount = NCManageDatabase.shared.getActiveTableAccount() - } else { - activeTableAccount = NCManageDatabase.shared.getTableAccount(predicate: NSPredicate(format: "account == %@", accountIdentifier)) + guard let account = selectedAccount else { + return dashboardSampleEntry(height: height, + footerText: NSLocalizedString("_no_active_account_", comment: ""), + isError: true) } - guard let activeTableAccount else { - return (DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: nil, buttons: nil, isPlaceholder: true, isEmpty: false, titleImage: UIImage(systemName: "circle.fill") ?? UIImage(), title: "Dashboard", footerImage: "xmark.icloud", footerText: NSLocalizedString("_no_active_account_", comment: ""), account: "")) - } NextcloudKit.shared.setup(groupIdentifier: NCBrandOptions.shared.capabilitiesGroup, delegate: NCNetworking.shared) - NextcloudKit.shared.appendSession(account: activeTableAccount.account, - urlBase: activeTableAccount.urlBase, - user: activeTableAccount.user, - userId: activeTableAccount.userId, - password: NCPreferences().getPassword(account: activeTableAccount.account), + NextcloudKit.shared.appendSession(account: account.account, + urlBase: account.urlBase, + user: account.user, + userId: account.userId, + password: NCPreferences().getPassword(account: account.account), userAgent: userAgent, httpMaximumConnectionsPerHost: NCBrandOptions.shared.httpMaximumConnectionsPerHost, httpMaximumConnectionsPerHostInDownload: NCBrandOptions.shared.httpMaximumConnectionsPerHostInDownload, httpMaximumConnectionsPerHostInUpload: NCBrandOptions.shared.httpMaximumConnectionsPerHostInUpload, groupIdentifier: NCBrandOptions.shared.capabilitiesGroup) - // LOG - let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionBuild()) - NextcloudKit.configureLogger( - logLevel: NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log, - logDirectory: NCPreferences.sharedLogDirectory - ) + NextcloudKit.configureLogger(logLevel: NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log, + logDirectory: NCPreferences.sharedLogDirectory) defer { NextcloudKit.flushLogger() } - nkLog(debug: "Start \(NCBrandOptions.shared.brand) dashboard widget session " + versionNextcloudiOS) + let version = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionBuild()) + nkLog(debug: "Start \(NCBrandOptions.shared.brand) dashboard widget session " + version) - // Widget - let widgetApplication = NCManageDatabase.shared.getDashboardWidgetApplications(account: activeTableAccount.account).first - let widgetApplicationId: String = configuration?.applications?.identifier ?? (widgetApplication?.id ?? "recommendations") - - let (tableDashboard, tableButton) = NCManageDatabase.shared.getDashboardWidget(account: activeTableAccount.account, id: widgetApplicationId) - let existsButton = (tableButton?.isEmpty ?? true) ? false : true - let title = tableDashboard?.title ?? widgetApplicationId + let moduleId = configuration.applications?.identifier + ?? database.getDashboardWidgetApplications(account: account.account).first?.id + ?? "recommendations" + let (module, moduleButtons) = database.getDashboardWidget(account: account.account, id: moduleId) + 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 + } - var titleImage: UIImage = UIImage(systemName: "circle.fill") ?? UIImage() - if let fileName = tableDashboard?.iconClass { - let fileNamePath: String = utilityFileSystem.createServerUrl(serverUrl: utilityFileSystem.directoryUserData, fileName: fileName + ".png") - if let image = UIImage(contentsOfFile: fileNamePath) { - titleImage = image.withTintColor(NCBrandColor.shared.iconImageColor, renderingMode: .alwaysOriginal) + let isMore = button.type == "more" + let url: URL? + if moduleId == "files-favorites", isMore { + var components = URLComponents() + components.scheme = NCGlobal.shared.appScheme + components.host = "openFavorites" + components.queryItems = [URLQueryItem(name: "account", value: account.account)] + url = components.url + } else { + url = dashboardWebURL(button.link, relativeTo: baseURL) } + guard let url else { return nil } + let hidesWhenAllRowsFit = isMore && moduleId != "files-favorites" && moduleId != "circles" + return DashboardAction(id: button.index, title: button.text, url: url, hidesWhenAllRowsFit: hidesWhenAllRowsFit) + } + + let titleImage: UIImage? + if let iconClass = module?.iconClass { + let fileSystem = NCUtilityFileSystem() + let path = fileSystem.createServerUrl(serverUrl: fileSystem.directoryUserData, fileName: iconClass + ".png") + titleImage = UIImage(contentsOfFile: path) + } else { + titleImage = nil } + let moduleImage = titleImage ?? UIImage(systemName: "rectangle.grid.2x2") ?? UIImage() + let roundIcons = module?.itemIconsRound ?? false + + let isOnThisDay = moduleId == "photos-onthisday" + let itemAPIVersion = module?.preferredItemAPIVersion ?? (isOnThisDay ? .unsupported : nil) + let webURL: URL? + if itemAPIVersion == .unsupported { + let defaultURL = isOnThisDay ? account.urlBase + "/index.php/apps/photos/thisday" : nil + webURL = dashboardWebURL(module?.widgetUrl, relativeTo: baseURL) ?? dashboardWebURL(defaultURL, relativeTo: baseURL) + } else { + webURL = nil + } + let options = NKRequestOptions(timeout: 90, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue) - let resultsDashboardWidget = await NextcloudKit.shared.getDashboardWidgetsApplicationAsync(widgetApplicationId, account: activeTableAccount.account, options: options) - - var datas = [DashboardData]() - var numberItems = 0 - - if resultsDashboardWidget.error == .success, - let dashboardApplications = resultsDashboardWidget.dashboardApplications { - for dashboardApplication in dashboardApplications { - if let items = dashboardApplication.items { - numberItems = dashboardApplication.items?.count ?? 0 - var counter: Int = 0 - let dashboardItems = getDashboardItems(displaySize: displaySize, withButton: existsButton) - for item in items { - counter += 1 - - let title = item.title ?? "" - let subtitle = item.subtitle ?? "" - - var link: URL = URL(string: "https://")! - if let entryLink = item.link, - let url = URL(string: entryLink) { - link = url - } - var iconImage = UIImage(systemName: "document") ?? UIImage() - var imageCircle: Bool = false - var imageColorized: Bool = false - var imageSystem: Bool = false - var imageColor: UIColor? - - if let iconUrl = item.iconUrl, let url = URL(string: iconUrl) { - if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) { - let path = (urlComponents.path as NSString) - let pathComponents = path.components(separatedBy: "/") - - if pathComponents.contains("avatar") { - imageCircle = true - } else if pathComponents.contains("getCalendarDotSvg") { - imageColorized = true - } - } - // Color - if imageColorized, let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) { - let path = (urlComponents.path as NSString) - let colorString = ((path.lastPathComponent) as NSString).deletingPathExtension - imageColor = UIColor(hex: colorString) - iconImage = UIImage(systemName: "circle.fill") ?? UIImage() - } else { - let results = await NextcloudKit.shared.downloadPreviewAsync(url: url, account: activeTableAccount.account) - if results.error == .success, - let data = results.responseData?.data { - if let image = UIImage(data: data) { - iconImage = image - } else { - imageSystem = true - } - /* NO MEMORY - else if let image = try? await NCSVGRenderer().renderSVGToUIImage(svgData: data) { - iconImage = image - } - */ - } - } - } - - let data = DashboardData(id: counter, title: title, subTitle: subtitle, link: link, icon: iconImage, circle: imageCircle, imageSystem: imageSystem, imageColor: imageColor) - datas.append(data) - - if datas.count == dashboardItems { break } - } + let result = await getDashboardModuleItems(moduleId, + version: itemAPIVersion, + account: account.account, + options: options) + guard result.error == .success else { + return dashboardSampleEntry(height: height, + title: title, + titleImage: moduleImage, + footerText: result.error.localizedGenericMessage, + isError: true) + } + + let items = result.items + let visibleActions = DashboardWidgetLayout.visibleActions(actions, totalRows: items.count, height: height) + let rowCount = DashboardWidgetLayout.rowCount(for: height, hasActions: !visibleActions.isEmpty) + var rows: [DashboardData] = [] + + for (index, item) in items.prefix(rowCount).enumerated() { + var icon: UIImage? + var isRound = roundIcons + var calendarColor: UIColor? + + if let iconURL = dashboardWebURL(item.iconUrl, relativeTo: baseURL) { + isRound = isRound || iconURL.pathComponents.contains("avatar") + if iconURL.pathComponents.suffix(2).elementsEqual(["filetypes", "folder.svg"]) { + icon = utility.loadImage(named: NKTypeIconFile.directory.rawValue, + size: DashboardWidgetLayout.iconSize, + useTypeIconFile: true, + account: account.account) + 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) } } + + rows.append(DashboardData(id: index, + title: item.title ?? "", + subtitle: item.subtitle ?? "", + link: dashboardWebURL(item.link, relativeTo: baseURL), + icon: icon, + isRound: isRound, + calendarColor: calendarColor)) } - var buttons = tableButton - if numberItems == datas.count, let tableButton = tableButton, tableButton.contains(where: { $0.type == "more"}) { - buttons = tableButton.filter(({ $0.type != "more" })) + let accountName = account.alias.isEmpty ? account.displayName : "\(account.displayName) (\(account.alias))" + return DashboardDataEntry(date: Date(), + rows: rows, + totalRows: items.count, + buttons: actions, + webURL: webURL, + isPlaceholder: false, + allowsRefresh: webURL == nil, + titleImage: moduleImage, + title: title, + footerImage: "checkmark.icloud", + footerText: accountName) +} + +private func getDashboardModuleItems(_ moduleId: String, + version: DashboardItemAPIVersion?, + account: String, + options: NKRequestOptions) async -> (items: [DashboardModuleItem], error: NKError) { + if version == .unsupported { + return ([], .success) } - let alias = (activeTableAccount.alias.isEmpty) ? "" : (" (" + activeTableAccount.alias + ")") - let footerText = "Dashboard " + NSLocalizedString("_of_", comment: "") + " " + activeTableAccount.displayName + alias + if version != .v2 { + let result = await NextcloudKit.shared.getDashboardWidgetsApplicationAsync(moduleId, account: account, options: options) + guard result.error == .success else { return ([], result.error) } - if resultsDashboardWidget.error != .success { - return(DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: tableDashboard, buttons: buttons, isPlaceholder: true, isEmpty: false, titleImage: titleImage, title: title, footerImage: "xmark.icloud", footerText: resultsDashboardWidget.error.localizedGenericMessage, account: activeTableAccount.account)) - } else { - return(DashboardDataEntry(date: Date(), datas: datas, dashboard: tableDashboard, buttons: buttons, isPlaceholder: false, isEmpty: datas.isEmpty, titleImage: titleImage, title: title, footerImage: "checkmark.icloud", footerText: footerText, account: activeTableAccount.account)) + if let items = result.dashboardApplications?.first(where: { $0.application == moduleId })?.items { + return (items.map { DashboardModuleItem(title: $0.title, subtitle: $0.subtitle, link: $0.link, iconUrl: $0.iconUrl) }, .success) + } + if version == .v1 { + return ([], .success) + } + } + + // A catalog without version metadata keeps the v1-to-v2 fallback. + var components = URLComponents() + components.path = "ocs/v2.php/apps/dashboard/api/v2/widget-items" + components.queryItems = [ + URLQueryItem(name: "widgets[]", value: moduleId), + URLQueryItem(name: "format", value: "json") + ] + guard let endpoint = components.string else { return ([], .urlError) } + + let response = await NextcloudKit.shared.generalWithEndpointAsync(endpoint, account: account, method: "GET", options: options) + if version == nil, response.error.errorCode == 404 { + return ([], .success) } + guard response.error == .success else { return ([], response.error) } + guard let data = response.responseData?.data, + let payload = try? JSONDecoder().decode(DashboardItemsResponse.self, from: data) else { + return ([], .invalidResponseError) + } + + let meta = payload.ocs.meta + guard (200..<300).contains(meta.statuscode) else { + return ([], NKError(errorCode: meta.statuscode, errorDescription: meta.message ?? "")) + } + + return (payload.ocs.data[moduleId]?.items ?? [], .success) +} + +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) + guard let url, let scheme = url.scheme?.lowercased(), + scheme == "https" || scheme == "http", + let host = url.host, !host.isEmpty else { return nil } + return url } diff --git a/Widget/Dashboard/DashboardWidgetProvider.swift b/Widget/Dashboard/DashboardWidgetProvider.swift index 60169bbf6c..f7192a0b6a 100644 --- a/Widget/Dashboard/DashboardWidgetProvider.swift +++ b/Widget/Dashboard/DashboardWidgetProvider.swift @@ -2,35 +2,49 @@ // SPDX-FileCopyrightText: 2022 Marino Faggiana // SPDX-License-Identifier: GPL-3.0-or-later -import UIKit +import AppIntents import WidgetKit import Intents -import SwiftUI struct DashboardWidgetProvider: IntentTimelineProvider { typealias Intent = DashboardIntent typealias Entry = DashboardDataEntry func placeholder(in context: Context) -> Entry { - let dashboardItems = getDashboardItems(displaySize: context.displaySize, withButton: false) - let datasPlaceholder = Array(dashboardDatasTest[0...dashboardItems]) - let title = "Dashboard" - let titleImage = UIImage(systemName: "circle.fill") ?? UIImage() - return Entry(date: Date(), datas: datasPlaceholder, dashboard: nil, buttons: nil, isPlaceholder: true, isEmpty: false, titleImage: titleImage, title: title, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " widget", account: "") + dashboardSampleEntry(height: context.displaySize.height) } - func getSnapshot(for configuration: DashboardIntent, in context: Context, completion: @escaping (DashboardDataEntry) -> Void) { + func getSnapshot(for configuration: DashboardIntent, in context: Context, completion: @escaping (Entry) -> Void) { + guard !context.isPreview else { + completion(dashboardSampleEntry(height: context.displaySize.height, isPlaceholder: false)) + return + } + Task { - let entry = await getDashboardDataEntry(configuration: configuration, isPreview: false, displaySize: context.displaySize) - completion(entry) + completion(await getDashboardDataEntry(configuration: configuration, displaySize: context.displaySize)) } } - func getTimeline(for configuration: DashboardIntent, in context: Context, completion: @escaping (Timeline) -> Void) { + func getTimeline(for configuration: DashboardIntent, in context: Context, completion: @escaping (Timeline) -> Void) { + guard !context.isPreview else { + let entry = dashboardSampleEntry(height: context.displaySize.height, isPlaceholder: false) + completion(Timeline(entries: [entry], policy: .never)) + return + } + Task { - let entry = await getDashboardDataEntry(configuration: configuration, isPreview: context.isPreview, displaySize: context.displaySize) - let timeLine = Timeline(entries: [entry], policy: .atEnd) - completion(timeLine) + let entry = await getDashboardDataEntry(configuration: configuration, displaySize: context.displaySize) + completion(Timeline(entries: [entry], policy: .atEnd)) } } } + +struct RefreshDashboardWidgetIntent: AppIntent { + static let title: LocalizedStringResource = "Refresh Dashboard" + static let openAppWhenRun = false + + func perform() async throws -> some IntentResult { + // WidgetKit reloads this widget's timeline after its button intent completes. + return .result() + } +} diff --git a/Widget/Dashboard/DashboardWidgetView.swift b/Widget/Dashboard/DashboardWidgetView.swift index 3ae749bdd9..a6a813e518 100644 --- a/Widget/Dashboard/DashboardWidgetView.swift +++ b/Widget/Dashboard/DashboardWidgetView.swift @@ -2,161 +2,251 @@ // SPDX-FileCopyrightText: 2022 Marino Faggiana // SPDX-License-Identifier: GPL-3.0-or-later +import AppIntents import SwiftUI import WidgetKit +nonisolated enum DashboardWidgetLayout { + static let padding: CGFloat = 12 + static let sectionSpacing: CGFloat = 4 + static let headerHeight: CGFloat = 22 + static let footerHeight: CGFloat = 44 + static let actionHeight: CGFloat = 36 + static let rowHeight: CGFloat = 44 + static let iconSize: CGFloat = 32 + static let rowSpacing: CGFloat = 10 + + static func rowCount(for height: CGFloat, hasActions: Bool) -> Int { + guard height.isFinite else { return 0 } + let reservedHeight = 2 * padding + 2 * sectionSpacing + headerHeight + footerHeight + let actionSpace = hasActions ? actionHeight + sectionSpacing : 0 + let rows = (height - reservedHeight - actionSpace) / rowHeight + return Int(min(50, max(0, rows))) + } + + static func visibleActions(_ actions: [DashboardAction], + totalRows: Int, + height: CGFloat, + loadedRows: Int = .max) -> [DashboardAction] { + let otherActions = actions.filter { !$0.hidesWhenAllRowsFit } + let rowsWithoutMore = rowCount(for: height, hasActions: !otherActions.isEmpty) + return totalRows > min(rowsWithoutMore, loadedRows) ? actions : otherActions + } +} + struct DashboardWidgetView: View { - var entry: DashboardDataEntry + let entry: DashboardDataEntry + var body: some View { - GeometryReader { geo in - if entry.isEmpty { - VStack(alignment: .center) { - Image(systemName: "checkmark") - .resizable() - .scaledToFit() - .font(Font.system(.body).weight(.light)) - .frame(width: 50, height: 50) - Text(NSLocalizedString("_no_items_", comment: "")) - .font(.system(size: 25)) - .padding() - Text(NSLocalizedString("_check_back_later_", comment: "")) - .font(.system(size: 15)) - } - .frame(width: geo.size.width, height: geo.size.height) - } + GeometryReader { geometry in + let height = geometry.size.height + let actions = DashboardWidgetLayout.visibleActions(entry.buttons, + totalRows: entry.totalRows, + height: height, + loadedRows: entry.rows.count) + let rows = entry.rows.prefix(DashboardWidgetLayout.rowCount(for: height, hasActions: !actions.isEmpty)) - ZStack(alignment: .topLeading) { - HStack { - Image(uiImage: entry.titleImage) - .renderingMode(.template) - .resizable() - .scaledToFill() - .frame(width: 20, height: 20) - - Text(entry.title) - .font(.system(size: 15)) - .fontWeight(.bold) - .multilineTextAlignment(.center) - .textCase(.uppercase) - .lineLimit(1) - } - .frame(width: geo.size.width - 20) - .padding([.top, .leading, .trailing], 10) - if !entry.isEmpty { - VStack(alignment: .leading) { - VStack(spacing: 0) { - ForEach(entry.datas, id: \.id) { element in - Link(destination: element.link) { - HStack { - let subTitleColor = Color(white: 0.5) - if entry.isPlaceholder { - Circle() - .fill(Color(.systemGray4)) - .frame(width: 35, height: 35) - } else if let color = element.imageColor { - Image(uiImage: element.icon) - .renderingMode(.template) - .resizable() - .frame(width: 35, height: 35) - .foregroundColor(Color(color)) - .scaleEffect(0.8) - } else if element.imageSystem { - Image(uiImage: element.icon) - .resizable() - .scaledToFit() - .frame(width: 35, height: 35) - .scaleEffect(0.8) - } else { - if entry.dashboard?.itemIconsRound ?? false || element.circle { - Image(uiImage: element.icon) - .resizable() - .scaledToFill() - .frame(width: 35, height: 35) - .clipShape(Circle()) - } else { - Image(uiImage: element.icon) - .resizable() - .scaledToFill() - .frame(width: 35, height: 35) - .clipped() - .cornerRadius(5) - } - } - - VStack(alignment: .leading, spacing: 2) { - - Text(element.title) - .font(.system(size: 12)) - .fontWeight(.regular) - - Text(element.subTitle) - .font(.system(size: CGFloat(10))) - .foregroundColor(subTitleColor) - } - Spacer() + VStack(alignment: .leading, spacing: DashboardWidgetLayout.sectionSpacing) { + header + + if let webURL = entry.webURL, let browserURL = browserDeepLink(for: webURL) { + VStack(spacing: 10) { + Text(NSLocalizedString("_widget_dashboard_available_on_web_", value: "Available on the web", comment: "")) + .font(.subheadline) + .foregroundStyle(.secondary) + + Link(destination: browserURL) { + Label(NSLocalizedString("_widget_dashboard_open_in_browser_", value: "Open in browser", comment: ""), systemImage: "safari") + .font(.system(size: 13, weight: .semibold)) + .padding(.horizontal, 12) + .frame(minHeight: 36) + .background(Color.accentColor.opacity(0.12), in: Capsule()) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if entry.totalRows == 0, !entry.isPlaceholder { + Text(NSLocalizedString("_no_data_available_", comment: "")) + .font(.subheadline) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + VStack(spacing: 0) { + ForEach(rows) { row in + dashboardRow(row) + .overlay(alignment: .bottomLeading) { + if row.id != rows.last?.id { + Divider() + .padding(.leading, DashboardWidgetLayout.iconSize + DashboardWidgetLayout.rowSpacing) } - .padding(.leading, 10) - .frame(height: 50) - } - if element != entry.datas.last { - Divider() - .padding(.leading, 54) } - } } } - .padding(.top, 35) .redacted(reason: entry.isPlaceholder ? .placeholder : []) + .frame(maxHeight: .infinity, alignment: .top) } - if let buttons = entry.buttons, !buttons.isEmpty, !entry.isPlaceholder { - HStack(spacing: 10) { - let brandColor = Color(NCBrandColor.shared.getElement(account: entry.account)) - let brandTextColor = Color(NCBrandColor.shared.getText(account: entry.account)) - - ForEach(buttons, id: \.index) { element in - Link(destination: URL(string: element.link)!, label: { - - Text(element.text) - .font(.system(size: 15)) - .padding(7) - .background(brandColor) - .foregroundColor(brandTextColor) - .border(brandColor, width: 1) - .cornerRadius(.infinity) - }) - } - } - .frame(width: geo.size.width - 10, height: geo.size.height - 25, alignment: .bottomTrailing) + if !actions.isEmpty { + actionRow(actions) + } + + footer + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .padding(DashboardWidgetLayout.padding) + } + .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) + .renderingMode(.template) + .resizable() + .scaledToFit() + .frame(width: 18, height: 18) + .accessibilityHidden(true) + + Text(entry.title) + .font(.system(size: 16, weight: .semibold)) + .lineLimit(1) + .accessibilityAddTraits(.isHeader) + } + .frame(height: DashboardWidgetLayout.headerHeight) + } + + private func actionRow(_ actions: [DashboardAction]) -> some View { + HStack(spacing: 8) { + ForEach(actions) { action in + Link(destination: action.url) { + Text(action.title) + .font(.system(size: 12, weight: .semibold)) + .lineLimit(1) + .padding(.horizontal, 10) + .frame(minHeight: 30) + .background(Color.accentColor.opacity(0.12), in: Capsule()) + } + } + } + .frame(maxWidth: .infinity, alignment: .trailing) + .frame(height: DashboardWidgetLayout.actionHeight) + } + + private var footer: some View { + HStack(spacing: 8) { + if entry.allowsRefresh { + Button(intent: RefreshDashboardWidgetIntent()) { + Image(systemName: "arrow.clockwise") + .font(.system(size: 19, weight: .semibold)) + .foregroundStyle(.tint) + .frame(width: DashboardWidgetLayout.footerHeight, height: DashboardWidgetLayout.footerHeight) + .contentShape(Rectangle()) } + .buttonStyle(.plain) + .accessibilityLabel(Text(NSLocalizedString("_widget_refresh_dashboard_", value: "Refresh Dashboard", comment: ""))) + } - HStack { - Image(systemName: entry.footerImage) - .resizable() - .scaledToFit() - .frame(width: 15, height: 15) - .font(Font.system(.body).weight(.light)) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) + VStack(alignment: .leading, spacing: 2) { + Label(entry.footerText, systemImage: entry.footerImage) + .truncationMode(.middle) - Text(entry.footerText) - .font(.caption2) + if !entry.isPlaceholder, entry.webURL == nil { + let updated = entry.date.formatted(.dateTime.day().month(.abbreviated).hour().minute()) + Text(String.localizedStringWithFormat( + NSLocalizedString("_widget_updated_at_", value: "Updated %@", comment: ""), + updated + )) + .invalidatableContent() + } + } + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: DashboardWidgetLayout.footerHeight) + } + + @ViewBuilder + private func dashboardRow(_ row: DashboardData) -> some View { + if let link = row.link { + Link(destination: link) { + rowContent(row) + } + } else { + rowContent(row) + } + } + + private func rowContent(_ row: DashboardData) -> some View { + HStack(spacing: DashboardWidgetLayout.rowSpacing) { + rowIcon(row) + .frame(width: DashboardWidgetLayout.iconSize, height: DashboardWidgetLayout.iconSize) + .accessibilityHidden(true) + + VStack(alignment: .leading, spacing: 2) { + Text(row.title) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(.primary) + .lineLimit(1) + + if !row.subtitle.isEmpty { + Text(row.subtitle) + .font(.system(size: 11)) + .foregroundStyle(.secondary) .lineLimit(1) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) } - .padding(.horizontal, 15.0) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom) } } - .containerBackground(.background, for: .widget) + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: DashboardWidgetLayout.rowHeight) + .contentShape(Rectangle()) + .accessibilityElement(children: .combine) + } + + @ViewBuilder + private func rowIcon(_ row: DashboardData) -> some View { + if let color = row.calendarColor { + Circle() + .fill(Color(color)) + .frame(width: 12, height: 12) + } else if let icon = row.icon { + Image(uiImage: icon) + .resizable() + .scaledToFill() + .frame(width: DashboardWidgetLayout.iconSize, height: DashboardWidgetLayout.iconSize) + .clipShape(RoundedRectangle(cornerRadius: row.isRound ? DashboardWidgetLayout.iconSize / 2 : 6)) + } else { + Image(systemName: "doc") + .font(.system(size: 19)) + .foregroundStyle(.secondary) + } } } struct DashboardWidget_Previews: PreviewProvider { static var previews: some View { - let datas = Array(dashboardDatasTest[0...4]) - let title = "Dashboard" - let titleImage = UIImage(systemName: "circle.fill")! - let entry = DashboardDataEntry(date: Date(), datas: datas, dashboard: nil, buttons: nil, isPlaceholder: false, isEmpty: false, titleImage: titleImage, title: title, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " widget", account: "") - DashboardWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .systemLarge)) + let sample = dashboardSampleEntry(height: 360) + let entry = DashboardDataEntry(date: Date(), + rows: sample.rows, + totalRows: sample.totalRows, + buttons: [], + webURL: nil, + isPlaceholder: false, + allowsRefresh: true, + titleImage: sample.titleImage, + title: sample.title, + footerImage: sample.footerImage, + footerText: sample.footerText) + + DashboardWidgetView(entry: entry) + .previewContext(WidgetPreviewContext(family: .systemLarge)) } } diff --git a/Widget/Files/FilesData.swift b/Widget/Files/FilesData.swift index 654b22d22f..fdcf4d26f5 100644 --- a/Widget/Files/FilesData.swift +++ b/Widget/Files/FilesData.swift @@ -12,10 +12,7 @@ struct FilesDataEntry: TimelineEntry { let datas: [FilesData] let isPlaceholder: Bool let isEmpty: Bool - let userId: String - let url: String - let account: String - let tile: String + let allowsRefresh: Bool let footerImage: String let footerText: String } @@ -25,61 +22,37 @@ struct FilesData: Identifiable, Hashable { var image: UIImage var title: String var subTitle: String - var url: URL + var url: URL? var useTypeIconFile: Bool = false } -let filesDatasTest: [FilesData] = [ - .init(id: "0", image: UIImage(systemName: "circle.fill")!, title: "title1", subTitle: "subTitle-description1", url: URL(string: "https://nextcloud.com/")!), - .init(id: "1", image: UIImage(systemName: "circle.fill")!, title: "title2", subTitle: "subTitle-description2", url: URL(string: "https://nextcloud.com/")!), - .init(id: "2", image: UIImage(systemName: "circle.fill")!, title: "title3", subTitle: "subTitle-description3", url: URL(string: "https://nextcloud.com/")!), - .init(id: "3", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!), - .init(id: "4", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!), - .init(id: "5", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!), - .init(id: "6", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!), - .init(id: "7", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!), - .init(id: "8", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!), - .init(id: "9", image: UIImage(systemName: "circle.fill")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!) -] - -func getTitleFilesWidget(tableAccount: tableAccount?) -> String { - let hour = Calendar.current.component(.hour, from: Date()) - var good = "" - - switch hour { - case 6..<12: good = NSLocalizedString("_good_morning_", value: "Good morning", comment: "") - case 12: good = NSLocalizedString("_good_day_", value: "Good day", comment: "") - case 13..<17: good = NSLocalizedString("_good_afternoon_", value: "Good afternoon", comment: "") - case 17..<22: good = NSLocalizedString("_good_evening_", value: "Good evening", comment: "") - default: good = NSLocalizedString("_good_night_", value: "Good night", comment: "") - } - - if let tableAccount { - return good + ", " + tableAccount.displayName - } else { - return good +func filesWidgetSampleRows(count: Int) -> [FilesData] { + let image = UIImage(systemName: "doc") ?? UIImage() + return (0.. FilesDataEntry { +func getFilesDataEntry(configuration: AccountIntent, displaySize: CGSize) async -> FilesDataEntry { let utilityFileSystem = NCUtilityFileSystem() let utility = NCUtility() - let maxItems = 5 - let datasPlaceholder = Array(filesDatasTest[0...maxItems - 1]) + let maxItems = FilesWidgetLayout.rowCount(for: displaySize.height) + let datasPlaceholder = filesWidgetSampleRows(count: maxItems) var activeTableAccount: tableAccount? let versionApp = NCUtility().getVersionMaintenance() if let groupDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup), let lastVersion = groupDefaults.string(forKey: NCGlobal.shared.udLastVersion), lastVersion != versionApp { - return (FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: "", url: "", account: "", tile: getTitleFilesWidget(tableAccount: nil), footerImage: "checkmark.icloud", footerText: NSLocalizedString("_version_mismatch_error_", comment: ""))) + return (FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, allowsRefresh: true, footerImage: "checkmark.icloud", footerText: NSLocalizedString("_version_mismatch_error_", comment: ""))) } - if isPreview { - return (FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: "", url: "", account: "", tile: getTitleFilesWidget(tableAccount: nil), footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " files")) - } - - let accountIdentifier: String = configuration?.accounts?.identifier ?? "active" + let accountIdentifier: String = configuration.accounts?.identifier ?? "active" if accountIdentifier == "active" { activeTableAccount = NCManageDatabase.shared.getActiveTableAccount() } else { @@ -87,7 +60,7 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi } guard let activeTableAccount else { - return (FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: "", url: "", account: "", tile: getTitleFilesWidget(tableAccount: nil), footerImage: "xmark.icloud", footerText: NSLocalizedString("_no_active_account_", value: "No account found", comment: ""))) + return (FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, allowsRefresh: true, footerImage: "xmark.icloud", footerText: NSLocalizedString("_no_active_account_", value: "No account found", comment: ""))) } NextcloudKit.shared.setup(groupIdentifier: NCBrandOptions.shared.capabilitiesGroup, delegate: NCNetworking.shared) @@ -174,10 +147,11 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi let results = await NextcloudKit.shared.searchBodyRequestAsync(serverUrl: activeTableAccount.urlBase, requestBody: requestBody, showHiddenFiles: showHiddenFiles, account: activeTableAccount.account, options: options) var datas: [FilesData] = [] - let title = getTitleFilesWidget(tableAccount: activeTableAccount) let files = results.files?.sorted(by: { ($0.date as Date) > ($1.date as Date) }) ?? [] for file in files { + guard datas.count < maxItems else { break } + var useTypeIconFile = false var image: UIImage? @@ -188,12 +162,15 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi // SUBTITLE let subTitle = utility.getRelativeDateTitle(file.date as Date) + " · " + utilityFileSystem.transformedSize(file.size) - // URL: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123 - guard var path = utilityFileSystem.getPath(path: file.path, user: file.user, fileName: file.fileName).urlEncoded else { continue } - if path.first == "/" { path = String(path.dropFirst())} - let link = file.urlBase + "/f/" + file.fileId - let urlString = "nextcloud://open-file?path=\(path)&user=\(file.userId)&link=\(link)&account=\(file.account)" - guard let url = URL(string: urlString) else { continue } + var components = URLComponents() + components.scheme = NCGlobal.shared.appScheme + components.host = "open-file" + components.queryItems = [ + URLQueryItem(name: "user", value: file.userId), + URLQueryItem(name: "link", value: file.urlBase + "/f/" + file.fileId), + URLQueryItem(name: "account", value: file.account) + ] + guard let url = components.url else { continue } // IMAGE image = utility.getImage(ocId: file.ocId, @@ -229,17 +206,14 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi // DATA let data = FilesData(id: metadata.ocId, image: image ?? UIImage(), title: metadata.fileNameView, subTitle: subTitle, url: url, useTypeIconFile: useTypeIconFile) datas.append(data) - if datas.count == maxItems { - break - } } let alias = (activeTableAccount.alias.isEmpty) ? "" : (" (" + activeTableAccount.alias + ")") - let footerText = "Files " + NSLocalizedString("_of_", comment: "") + " " + activeTableAccount.displayName + alias + let footerText = activeTableAccount.displayName + alias if results.error != .success { - return(FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: activeTableAccount.userId, url: activeTableAccount.urlBase, account: activeTableAccount.account, tile: title, footerImage: "xmark.icloud", footerText: results.error.localizedGenericMessage)) + return(FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, allowsRefresh: true, footerImage: "xmark.icloud", footerText: results.error.localizedGenericMessage)) } else { - return(FilesDataEntry(date: Date(), datas: datas, isPlaceholder: false, isEmpty: datas.isEmpty, userId: activeTableAccount.userId, url: activeTableAccount.urlBase, account: activeTableAccount.account, tile: title, footerImage: "checkmark.icloud", footerText: footerText)) + return(FilesDataEntry(date: Date(), datas: datas, isPlaceholder: false, isEmpty: datas.isEmpty, allowsRefresh: true, footerImage: "checkmark.icloud", footerText: footerText)) } } diff --git a/Widget/Files/FilesWidgetProvider.swift b/Widget/Files/FilesWidgetProvider.swift index 4ccce19047..24372bb7c8 100644 --- a/Widget/Files/FilesWidgetProvider.swift +++ b/Widget/Files/FilesWidgetProvider.swift @@ -2,33 +2,59 @@ // SPDX-FileCopyrightText: 2022 Marino Faggiana // SPDX-License-Identifier: GPL-3.0-or-later -import UIKit +import AppIntents import WidgetKit import Intents -import SwiftUI struct FilesWidgetProvider: IntentTimelineProvider { typealias Entry = FilesDataEntry typealias Intent = AccountIntent func placeholder(in context: Context) -> Entry { - let datasPlaceholder = Array(filesDatasTest[0...4]) - let title = getTitleFilesWidget(tableAccount: nil) - return Entry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: "", url: "", account: "", tile: title, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " files") + sampleEntry(in: context, isPlaceholder: true) + } + + private func sampleEntry(in context: Context, isPlaceholder: Bool) -> Entry { + Entry(date: Date(), + datas: filesWidgetSampleRows(count: FilesWidgetLayout.rowCount(for: context.displaySize.height)), + isPlaceholder: isPlaceholder, + isEmpty: false, + allowsRefresh: false, + footerImage: "checkmark.icloud", + footerText: NCBrandOptions.shared.brand) } func getSnapshot(for configuration: AccountIntent, in context: Context, completion: @escaping (Entry) -> Void) { + guard !context.isPreview else { + completion(sampleEntry(in: context, isPlaceholder: false)) + return + } + Task { - let entry = await getFilesDataEntry(configuration: configuration, isPreview: false, displaySize: context.displaySize) + let entry = await getFilesDataEntry(configuration: configuration, displaySize: context.displaySize) completion(entry) } } func getTimeline(for configuration: AccountIntent, in context: Context, completion: @escaping (Timeline) -> Void) { + guard !context.isPreview else { + completion(Timeline(entries: [sampleEntry(in: context, isPlaceholder: false)], policy: .never)) + return + } + Task { - let entry = await getFilesDataEntry(configuration: configuration, isPreview: context.isPreview, displaySize: context.displaySize) - let timeLine = Timeline(entries: [entry], policy: .atEnd) - completion(timeLine) + let entry = await getFilesDataEntry(configuration: configuration, displaySize: context.displaySize) + completion(Timeline(entries: [entry], policy: .atEnd)) } } } + +struct RefreshFilesWidgetIntent: AppIntent { + static let title: LocalizedStringResource = "Refresh recent files" + static let openAppWhenRun = false + + func perform() async throws -> some IntentResult { + // WidgetKit reloads this widget's timeline after its button intent completes. + return .result() + } +} diff --git a/Widget/Files/FilesWidgetView.swift b/Widget/Files/FilesWidgetView.swift index a595b4d681..0c06f7a8e6 100644 --- a/Widget/Files/FilesWidgetView.swift +++ b/Widget/Files/FilesWidgetView.swift @@ -2,176 +2,152 @@ // SPDX-FileCopyrightText: 2022 Marino Faggiana // SPDX-License-Identifier: GPL-3.0-or-later +import AppIntents import SwiftUI import WidgetKit +nonisolated enum FilesWidgetLayout { + static let padding: CGFloat = 12 + static let sectionSpacing: CGFloat = 4 + static let headerHeight: CGFloat = 22 + static let footerHeight: CGFloat = 44 + static let rowHeight: CGFloat = 44 + static let thumbnailSize: CGFloat = 32 + static let rowSpacing: CGFloat = 10 + + static func rowCount(for height: CGFloat) -> Int { + guard height.isFinite else { return 0 } + let reservedHeight = 2 * padding + 2 * sectionSpacing + headerHeight + footerHeight + // The WebDAV search returns at most 50 results. + let rows = (height - reservedHeight) / rowHeight + return Int(min(50, max(0, rows))) + } +} + struct FilesWidgetView: View { - var entry: FilesDataEntry + let entry: FilesDataEntry + var body: some View { - let parameterLink = "&user=\(entry.userId)&url=\(entry.url)" - let linkNoAction: URL = URL(string: NCGlobal.shared.widgetActionNoAction + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionNoAction + parameterLink)! : URL(string: NCGlobal.shared.widgetActionNoAction)! - let linkActionUploadAsset: URL = URL(string: NCGlobal.shared.widgetActionUploadAsset + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionUploadAsset + parameterLink)! : URL(string: NCGlobal.shared.widgetActionUploadAsset)! - let linkActionScanDocument: URL = URL(string: NCGlobal.shared.widgetActionScanDocument + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionScanDocument + parameterLink)! : URL(string: NCGlobal.shared.widgetActionScanDocument)! - let linkActionTextDocument: URL = URL(string: NCGlobal.shared.widgetActionTextDocument + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionTextDocument + parameterLink)! : URL(string: NCGlobal.shared.widgetActionTextDocument)! - let linkActionVoiceMemo: URL = URL(string: NCGlobal.shared.widgetActionVoiceMemo + parameterLink) != nil ? URL(string: NCGlobal.shared.widgetActionVoiceMemo + parameterLink)! : URL(string: NCGlobal.shared.widgetActionVoiceMemo)! - - GeometryReader { geo in - if entry.isEmpty { - VStack(alignment: .center) { - Image(systemName: "checkmark") - .resizable() - .scaledToFit() - .font(Font.system(.body).weight(.light)) - .frame(width: 50, height: 50) - Text(NSLocalizedString("_no_items_", comment: "")) - .font(.system(size: 25)) - .padding() - Text(NSLocalizedString("_check_back_later_", comment: "")) - .font(.system(size: 15)) - } - .frame(width: geo.size.width, height: geo.size.height) - } + GeometryReader { geometry in + let files = entry.datas.prefix(FilesWidgetLayout.rowCount(for: geometry.size.height)) - ZStack(alignment: .topLeading) { - HStack { - Text(entry.tile) - .font(.system(size: 12)) - .fontWeight(.bold) - .multilineTextAlignment(.center) - .textCase(.uppercase) - .lineLimit(1) - } - .frame(width: geo.size.width - 20) - .padding([.top, .leading, .trailing], 10) - - if !entry.isEmpty { - VStack(alignment: .leading) { - VStack(spacing: 0) { - ForEach(entry.datas, id: \.id) { element in - Link(destination: element.url) { - HStack(spacing: 10) { - Group { - if element.useTypeIconFile { - Image(uiImage: element.image) - .resizable() - .renderingMode(.template) - .foregroundColor(Color(NCBrandColor.shared.iconImageColor2)) - .scaledToFit() - .frame(width: 35, height: 35) - } else { - Image(uiImage: element.image) - .resizable() - .frame(width: 35, height: 35) - .background(Color(.secondarySystemBackground)) - .clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous)) - } - } - - VStack(alignment: .leading, spacing: 2) { - FilesWidgetBidiFilename(filename: element.title) - .lineLimit(1) - Text(element.subTitle) - .font(.system(size: 10)) - .foregroundColor(Color(NCBrandColor.shared.iconImageColor2)) - .lineLimit(1) - .truncationMode(.tail) - } - Spacer(minLength: 0) + VStack(alignment: .leading, spacing: FilesWidgetLayout.sectionSpacing) { + Text(NSLocalizedString("_widget_recent_files_", value: "Recent files", comment: "")) + .font(.system(size: 16, weight: .semibold)) + .lineLimit(1) + .frame(height: FilesWidgetLayout.headerHeight) + .accessibilityAddTraits(.isHeader) + + if entry.isEmpty { + Label { + Text(NSLocalizedString("_widget_no_recent_files_", value: "No recent files", comment: "")) + } icon: { + Image(systemName: "clock") + } + .font(.subheadline) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + VStack(spacing: 0) { + ForEach(files) { file in + fileRow(file) + .overlay(alignment: .bottomLeading) { + if file.id != files.last?.id { + Divider() + .padding(.leading, FilesWidgetLayout.thumbnailSize + FilesWidgetLayout.rowSpacing) } - .padding(.horizontal, 10) - .frame(height: 44) } - if element != entry.datas.last { - Divider() - .padding(.leading, 52) - } - } } } - .padding(.top, 30) .redacted(reason: entry.isPlaceholder ? .placeholder : []) + .frame(maxHeight: .infinity, alignment: .top) } - HStack(spacing: 10) { - let buttonSize: CGFloat = 40 - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionUploadAsset) { - Image(systemName: "photo.badge.plus") - .resizable() - .renderingMode(.template) - .scaledToFit() - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .frame(width: 18, height: 18) - .padding(11) - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .frame(width: buttonSize, height: buttonSize) - } - .frame(maxWidth: .infinity) - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionScanDocument) { - Image(systemName: "doc.text.viewfinder") - .resizable() - .renderingMode(.template) - .scaledToFit() - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .frame(width: 18, height: 18) - .padding(11) - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .frame(width: buttonSize, height: buttonSize) - } - .frame(maxWidth: .infinity) - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionTextDocument) { - Image("note.text") - .resizable() - .renderingMode(.template) - .scaledToFit() - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .frame(width: 18, height: 18) - .padding(11) - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .frame(width: buttonSize, height: buttonSize) - } - .frame(maxWidth: .infinity) - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionVoiceMemo) { - Image(systemName: "mic.fill") - .resizable() - .renderingMode(.template) - .scaledToFit() - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .frame(width: 18, height: 18) - .padding(11) - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .frame(width: buttonSize, height: buttonSize) - } - .frame(maxWidth: .infinity) + footer + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .padding(FilesWidgetLayout.padding) + } + .containerBackground(.background, for: .widget) + } + + private var footer: some View { + HStack(spacing: 8) { + if entry.allowsRefresh { + Button(intent: RefreshFilesWidgetIntent()) { + Image(systemName: "arrow.clockwise") + .font(.system(size: 19, weight: .semibold)) + .foregroundStyle(.tint) + .frame(width: FilesWidgetLayout.footerHeight, height: FilesWidgetLayout.footerHeight) + .contentShape(Rectangle()) } - .padding(.horizontal, 10) - .frame(maxWidth: .infinity, maxHeight: geo.size.height - 25, alignment: .bottom) - .redacted(reason: entry.isPlaceholder ? .placeholder : []) - - HStack { - Image(systemName: entry.footerImage) - .resizable() - .scaledToFit() - .frame(width: 15, height: 15) - .font(Font.system(.body).weight(.light)) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - - Text(entry.footerText) - .font(.caption2) - .lineLimit(1) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) + .buttonStyle(.plain) + .accessibilityLabel(Text(NSLocalizedString("_widget_refresh_files_", value: "Refresh recent files", comment: ""))) + } + + VStack(alignment: .leading, spacing: 2) { + Label(entry.footerText, systemImage: entry.footerImage) + .truncationMode(.middle) + + if !entry.isPlaceholder { + let updated = entry.date.formatted(.dateTime.day().month(.abbreviated).hour().minute()) + Text(String.localizedStringWithFormat( + NSLocalizedString("_widget_updated_at_", value: "Updated %@", comment: ""), + updated + )) + .invalidatableContent() } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom) } + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .lineLimit(1) } - .containerBackground(.background, for: .widget) + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: FilesWidgetLayout.footerHeight) + } + + @ViewBuilder + private func fileRow(_ file: FilesData) -> some View { + if let url = file.url { + Link(destination: url) { + rowContent(file) + } + } else { + rowContent(file) + } + } + + private func rowContent(_ file: FilesData) -> some View { + HStack(spacing: FilesWidgetLayout.rowSpacing) { + thumbnail(file) + .accessibilityHidden(true) + + VStack(alignment: .leading, spacing: 2) { + FilesWidgetBidiFilename(filename: file.title) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(.primary) + .lineLimit(1) + + Text(file.subTitle) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: FilesWidgetLayout.rowHeight) + .contentShape(Rectangle()) + .accessibilityElement(children: .combine) + } + + private func thumbnail(_ file: FilesData) -> some View { + Image(uiImage: file.image) + .renderingMode(file.useTypeIconFile ? .template : .original) + .resizable() + .aspectRatio(contentMode: file.useTypeIconFile ? .fit : .fill) + .foregroundStyle(.secondary) + .frame(width: FilesWidgetLayout.thumbnailSize, height: FilesWidgetLayout.thumbnailSize) + .clipShape(RoundedRectangle(cornerRadius: 6)) } } @@ -179,32 +155,37 @@ private struct FilesWidgetBidiFilename: View { let filename: String var body: some View { - let nsName = filename as NSString - let ext = nsName.pathExtension - let base = nsName.deletingPathExtension + let name = filename as NSString + let ext = name.pathExtension + let base = name.deletingPathExtension if ext.isEmpty || base.isEmpty { Text(filename) - .font(.system(size: 12)) + .truncationMode(.middle) } else { HStack(spacing: 0) { Text(base) - .font(.system(size: 12)) - .lineLimit(1) .truncationMode(.middle) Text("." + ext) - .font(.system(size: 12)) - .lineLimit(1) .fixedSize(horizontal: true, vertical: false) } + .accessibilityLabel(Text(filename)) } } } struct FilesWidget_Previews: PreviewProvider { static var previews: some View { - let datas = Array(filesDatasTest[0...4]) - let entry = FilesDataEntry(date: Date(), datas: datas, isPlaceholder: false, isEmpty: false, userId: "", url: "", account: "", tile: "Good afternoon, Marino Faggiana", footerImage: "checkmark.icloud", footerText: "Nextcloud files") - FilesWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .systemLarge)) + let entry = FilesDataEntry( + date: Date(), + datas: filesWidgetSampleRows(count: 8), + isPlaceholder: false, + isEmpty: false, + allowsRefresh: true, + footerImage: "checkmark.icloud", + footerText: "Nextcloud (Personal)" + ) + FilesWidgetView(entry: entry) + .previewContext(WidgetPreviewContext(family: .systemLarge)) } } diff --git a/Widget/Lockscreen/LockscreenData.swift b/Widget/Lockscreen/LockscreenData.swift index 252799d770..2c919c3af7 100644 --- a/Widget/Lockscreen/LockscreenData.swift +++ b/Widget/Lockscreen/LockscreenData.swift @@ -10,27 +10,23 @@ struct LockscreenData: TimelineEntry { let date: Date let isPlaceholder: Bool let activity: String - let link: URL - let quotaRelative: Float + let link: URL? + let quotaRelative: Double let quotaUsed: String let quotaTotal: String let error: Bool + var quotaTotalAccessibilityLabel: String? } -func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, family: WidgetFamily, completion: @escaping (_ entry: LockscreenData) -> Void) { +func getLockscreenDataEntry(configuration: AccountIntent?, family: WidgetFamily, completion: @escaping (_ entry: LockscreenData) -> Void) { let utilityFileSystem = NCUtilityFileSystem() var activeTableAccount: tableAccount? - var quotaRelative: Float = 0 let versionApp = NCUtility().getVersionMaintenance() if let groupDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup), let lastVersion = groupDefaults.string(forKey: NCGlobal.shared.udLastVersion), lastVersion != versionApp { - return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) - } - - if isPreview { - return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) + return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) } let accountIdentifier: String = configuration?.accounts?.identifier ?? "active" @@ -41,7 +37,7 @@ func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, fami } guard let activeTableAccount else { - return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) + return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) } // NETWORKING @@ -63,41 +59,66 @@ func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, fami if family == .accessoryCircular { NextcloudKit.shared.getUserMetadata(account: activeTableAccount.account, userId: activeTableAccount.userId, options: options) { _, userProfile, _, error in - if error == .success, let userProfile = userProfile { - if userProfile.quotaRelative > 0 { - quotaRelative = Float(userProfile.quotaRelative) / 100 - } - let quotaUsed: String = utilityFileSystem.transformedSize(userProfile.quotaUsed) - var quotaTotal: String = "" + guard error == .success, let userProfile else { + completion(LockscreenData(date: Date(), isPlaceholder: false, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: true)) + return + } - switch userProfile.quotaTotal { - case -1: - quotaTotal = "" - case -2: - quotaTotal = "" - case -3: - quotaTotal = "" - default: - quotaTotal = utilityFileSystem.transformedSize(userProfile.quotaTotal) - } - completion(LockscreenData(date: Date(), isPlaceholder: false, activity: "", link: URL(string: "https://")!, quotaRelative: quotaRelative, quotaUsed: quotaUsed, quotaTotal: quotaTotal, error: false)) - } else { - completion(LockscreenData(date: Date(), isPlaceholder: false, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: true)) + let percentage = userProfile.quotaRelative + let total = userProfile.quotaTotal + let progress = total > 0 && percentage.isFinite ? min(max(percentage / 100, 0), 1) : 0 + let quotaUsed = utilityFileSystem.transformedSize(userProfile.quotaUsed) + let quotaTotal: String + let quotaTotalAccessibilityLabel: String? + + switch total { + case -3: + quotaTotal = "∞" + quotaTotalAccessibilityLabel = NSLocalizedString("_quota_space_unlimited_", comment: "") + case -1: + quotaTotal = utilityFileSystem.transformedSize(0) + quotaTotalAccessibilityLabel = nil + case ..<0: + quotaTotal = "—" + quotaTotalAccessibilityLabel = NSLocalizedString("_quota_space_unknown_", comment: "") + default: + quotaTotal = utilityFileSystem.transformedSize(total) + quotaTotalAccessibilityLabel = nil } + + completion(LockscreenData(date: Date(), + isPlaceholder: false, + activity: "", + link: nil, + quotaRelative: progress, + quotaUsed: quotaUsed, + quotaTotal: quotaTotal, + error: false, + quotaTotalAccessibilityLabel: quotaTotalAccessibilityLabel)) } } else if family == .accessoryRectangular { + let baseURL = URL(string: activeTableAccount.urlBase) NextcloudKit.shared.getDashboardWidgetsApplication("activity", account: activeTableAccount.account, options: options) { _, results, _, error in - var activity: String = NSLocalizedString("_no_data_available_", comment: "") - var link = URL(string: "https://")! - if error == .success, let result = results?.first { - if let item = result.items?.first { - if let title = item.title { activity = title } - if let itemLink = item.link, let url = URL(string: itemLink) { link = url } - } - completion(LockscreenData(date: Date(), isPlaceholder: false, activity: activity, link: link, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) - } else { - completion(LockscreenData(date: Date(), isPlaceholder: false, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: true)) + guard error == .success else { + completion(LockscreenData(date: Date(), isPlaceholder: false, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: true)) + return } + + let item = results?.first(where: { $0.application == "activity" })?.items?.first + let activity = item?.title ?? NSLocalizedString("_no_data_available_", comment: "") + let link = activityURL(item?.link, relativeTo: baseURL) + completion(LockscreenData(date: Date(), isPlaceholder: false, activity: activity, link: link, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) } + } else { + completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false)) } } + +private func activityURL(_ 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) + guard let url, let scheme = url.scheme?.lowercased(), + scheme == "http" || scheme == "https", + let host = url.host, !host.isEmpty else { return nil } + return url +} diff --git a/Widget/Lockscreen/LockscreenWidgetProvider.swift b/Widget/Lockscreen/LockscreenWidgetProvider.swift index ee5c7effcb..56d8228672 100644 --- a/Widget/Lockscreen/LockscreenWidgetProvider.swift +++ b/Widget/Lockscreen/LockscreenWidgetProvider.swift @@ -12,19 +12,32 @@ struct LockscreenWidgetProvider: IntentTimelineProvider { typealias Intent = AccountIntent func placeholder(in context: Context) -> Entry { - return Entry(date: Date(), isPlaceholder: true, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false) + return Entry(date: Date(), isPlaceholder: true, activity: "", link: nil, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false) } func getSnapshot(for configuration: AccountIntent, in context: Context, completion: @escaping (Entry) -> Void) { - getLockscreenDataEntry(configuration: configuration, isPreview: false, family: context.family) { entry in + if context.isPreview { + completion(Self.previewEntry()) + return + } + getLockscreenDataEntry(configuration: configuration, family: context.family) { entry in completion(entry) } } func getTimeline(for configuration: AccountIntent, in context: Context, completion: @escaping (Timeline) -> Void) { - getLockscreenDataEntry(configuration: configuration, isPreview: context.isPreview, family: context.family) { entry in + if context.isPreview { + completion(Timeline(entries: [Self.previewEntry()], policy: .never)) + return + } + getLockscreenDataEntry(configuration: configuration, family: context.family) { entry in let timeLine = Timeline(entries: [entry], policy: .atEnd) completion(timeLine) } } + + static func previewEntry() -> Entry { + Entry(date: Date(), isPlaceholder: false, activity: "Alex updated Documents / Meeting notes.pdf", + link: nil, quotaRelative: 0.5, quotaUsed: "5 GB", quotaTotal: "10 GB", error: false) + } } diff --git a/Widget/Lockscreen/LockscreenWidgetView.swift b/Widget/Lockscreen/LockscreenWidgetView.swift index a013844ab7..7ae8b7c7bd 100644 --- a/Widget/Lockscreen/LockscreenWidgetView.swift +++ b/Widget/Lockscreen/LockscreenWidgetView.swift @@ -29,6 +29,7 @@ struct LockscreenWidgetView: View { label: { Text(" " + entry.quotaTotal + " ") .font(.system(size: 8.0)) + .accessibilityLabel(Text(entry.quotaTotalAccessibilityLabel ?? entry.quotaTotal)) }, currentValueLabel: { Text(entry.quotaUsed) @@ -59,6 +60,7 @@ struct LockscreenWidgetView: View { } else { Text(entry.activity) .font(.system(size: 12)).bold() + .privacySensitive() } } .widgetURL(entry.link) @@ -72,7 +74,7 @@ struct LockscreenWidgetView: View { struct LockscreenWidgetView_Previews: PreviewProvider { static var previews: some View { - let entry = LockscreenData(date: Date(), isPlaceholder: false, activity: "Alba Mayoral changed Marketing / Regional Marketing / Agenda Meetings / Q4 2022 / OCTOBER / 13.11 Afrah Kahlid.md", link: URL(string: "https://")!, quotaRelative: 0.5, quotaUsed: "999 GB", quotaTotal: "999 GB", error: false) + let entry = LockscreenWidgetProvider.previewEntry() LockscreenWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .accessoryRectangular)).previewDisplayName("Rectangular") LockscreenWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .accessoryCircular)).previewDisplayName("Circular") } diff --git a/Widget/Toolbar/ToolbarData.swift b/Widget/Toolbar/ToolbarData.swift deleted file mode 100644 index 0306f1d911..0000000000 --- a/Widget/Toolbar/ToolbarData.swift +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-FileCopyrightText: Nextcloud GmbH -// SPDX-FileCopyrightText: 2022 Marino Faggiana -// SPDX-License-Identifier: GPL-3.0-or-later - -import UIKit -import WidgetKit -import NextcloudKit - -struct ToolbarDataEntry: TimelineEntry { - let date: Date - let isPlaceholder: Bool - let userId: String - let url: String - let account: String - let footerImage: String - let footerText: String -} - -func getToolbarDataEntry(isPreview: Bool, completion: @escaping (_ entry: ToolbarDataEntry) -> Void) { - var userId = "" - var url = "" - var account = "" - let versionApp = NCUtility().getVersionMaintenance() - - if let groupDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup), - let lastVersion = groupDefaults.string(forKey: NCGlobal.shared.udLastVersion), - lastVersion != versionApp { - return completion(ToolbarDataEntry(date: Date(), isPlaceholder: true, userId: userId, url: url, account: account, footerImage: "xmark.icloud", footerText: NSLocalizedString("_version_mismatch_error_", comment: ""))) - } - - if isPreview { - return completion(ToolbarDataEntry(date: Date(), isPlaceholder: true, userId: userId, url: url, account: account, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " toolbar")) - } - - if let activeTableAccount = NCManageDatabase.shared.getActiveTableAccount() { - userId = activeTableAccount.userId - url = activeTableAccount.urlBase - account = activeTableAccount.account - } - - if NCManageDatabase.shared.getActiveTableAccount() == nil { - return completion(ToolbarDataEntry(date: Date(), isPlaceholder: true, userId: userId, url: url, account: account, footerImage: "xmark.icloud", footerText: NSLocalizedString("_no_active_account_", value: "No account found", comment: ""))) - } - - completion(ToolbarDataEntry(date: Date(), isPlaceholder: false, userId: userId, url: url, account: account, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " toolbar")) -} diff --git a/Widget/Toolbar/ToolbarWidgetProvider.swift b/Widget/Toolbar/ToolbarWidgetProvider.swift deleted file mode 100644 index f9bba1ba47..0000000000 --- a/Widget/Toolbar/ToolbarWidgetProvider.swift +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-FileCopyrightText: Nextcloud GmbH -// SPDX-FileCopyrightText: 2022 Marino Faggiana -// SPDX-License-Identifier: GPL-3.0-or-later - -import UIKit -import WidgetKit -import SwiftUI - -struct ToolbarWidgetProvider: TimelineProvider { - typealias Entry = ToolbarDataEntry - - func placeholder(in context: Context) -> Entry { - return Entry(date: Date(), isPlaceholder: true, userId: "", url: "", account: "", footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " toolbar") - } - - func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) { - getToolbarDataEntry(isPreview: false) { entry in - completion(entry) - } - } - - func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { - getToolbarDataEntry(isPreview: context.isPreview) { entry in - let timeLine = Timeline(entries: [entry], policy: .atEnd) - completion(timeLine) - } - } -} diff --git a/Widget/Toolbar/ToolbarWidgetView.swift b/Widget/Toolbar/ToolbarWidgetView.swift deleted file mode 100644 index f45da7637f..0000000000 --- a/Widget/Toolbar/ToolbarWidgetView.swift +++ /dev/null @@ -1,109 +0,0 @@ -// SPDX-FileCopyrightText: Nextcloud GmbH -// SPDX-FileCopyrightText: 2022 Marino Faggiana -// SPDX-License-Identifier: GPL-3.0-or-later - -import SwiftUI -import WidgetKit - -struct ToolbarWidgetView: View { - var entry: ToolbarDataEntry - - @ViewBuilder - var body: some View { - mainContent - .containerBackground(Color.black, for: .widget) - } - - private var mainContent: some View { - let parameterLink = "&user=\(entry.userId)&url=\(entry.url)" - let safeUrl = { (base: String) in - URL(string: base + parameterLink) ?? URL(string: base)! - } - let linkNoAction = safeUrl(NCGlobal.shared.widgetActionNoAction) - let linkActionUploadAsset = safeUrl(NCGlobal.shared.widgetActionUploadAsset) - let linkActionScanDocument = safeUrl(NCGlobal.shared.widgetActionScanDocument) - let linkActionTextDocument = safeUrl(NCGlobal.shared.widgetActionTextDocument) - let linkActionVoiceMemo = safeUrl(NCGlobal.shared.widgetActionVoiceMemo) - let sizeButton: CGFloat = 65 - - return GeometryReader { geo in - ZStack(alignment: .topLeading) { - HStack(spacing: 0) { - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionUploadAsset, label: { - Image(systemName: "photo.badge.plus") - .resizable() - .renderingMode(.template) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .padding() - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .scaledToFit() - .frame(width: geo.size.width / 4, height: sizeButton) - }) - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionScanDocument, label: { - Image(systemName: "doc.text.viewfinder") - .resizable() - .renderingMode(.template) - .font(Font.system(.body).weight(.light)) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .padding() - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .scaledToFit() - .frame(width: geo.size.width / 4, height: sizeButton) - }) - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionTextDocument, label: { - Image("note.text") - .resizable() - .renderingMode(.template) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .padding() - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .scaledToFit() - .frame(width: geo.size.width / 4, height: sizeButton) - }) - - Link(destination: entry.isPlaceholder ? linkNoAction : linkActionVoiceMemo, label: { - Image(systemName: "mic.fill") - .resizable() - .renderingMode(.template) - .scaledToFit() - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getText(account: entry.account))) - .frame(width: sizeButton - 32, height: sizeButton - 32) - .padding(16) - .background(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - .clipShape(Circle()) - .frame(width: geo.size.width / 4, height: sizeButton) - }) - } - .frame(width: geo.size.width, height: geo.size.height, alignment: .center) - .redacted(reason: entry.isPlaceholder ? .placeholder : []) - - HStack { - Image(systemName: entry.footerImage) - .resizable() - .font(Font.system(.body).weight(.light)) - .scaledToFit() - .frame(width: 15, height: 15) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - - Text(entry.footerText) - .font(.caption2) - .padding(.trailing, 13.0) - .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.getElement(account: entry.account))) - } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom) - } - } - } -} - -struct ToolbarWidget_Previews: PreviewProvider { - static var previews: some View { - let entry = ToolbarDataEntry(date: Date(), isPlaceholder: false, userId: "", url: "", account: "", footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " toolbar") - ToolbarWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .systemMedium)) - } -} diff --git a/Widget/Widget.swift b/Widget/Widget.swift index 469b8339d3..a81463be27 100644 --- a/Widget/Widget.swift +++ b/Widget/Widget.swift @@ -12,7 +12,6 @@ struct NextcloudWidgetBundle: WidgetBundle { var body: some Widget { DashboardWidget() FilesWidget() - ToolbarWidget() LockscreenWidget() } } @@ -27,9 +26,7 @@ struct DashboardWidget: Widget { .supportedFamilies([.systemLarge]) .configurationDisplayName("Dashboard") .description(NSLocalizedString("_description_dashboardwidget_", comment: "")) -#if !targetEnvironment(simulator) .contentMarginsDisabled() -#endif } } @@ -42,26 +39,8 @@ struct FilesWidget: Widget { } .supportedFamilies([.systemLarge]) .configurationDisplayName("Files") - .description(NSLocalizedString("_description_fileswidget_", comment: "")) -#if !targetEnvironment(simulator) + .description(NSLocalizedString("_widget_recent_files_description_", value: "View and open your recent files.", comment: "")) .contentMarginsDisabled() -#endif - } -} - -struct ToolbarWidget: Widget { - let kind: String = "ToolbarWidget" - - var body: some WidgetConfiguration { - StaticConfiguration(kind: kind, provider: ToolbarWidgetProvider()) { entry in - ToolbarWidgetView(entry: entry) - } - .supportedFamilies([.systemMedium]) - .configurationDisplayName("Toolbar") - .description(NSLocalizedString("_description_toolbarwidget_", comment: "")) -#if !targetEnvironment(simulator) - .contentMarginsDisabled() -#endif } } diff --git a/WidgetDashboardIntentHandler/IntentHandler.swift b/WidgetDashboardIntentHandler/IntentHandler.swift index 53462da12a..dc4fe5df0f 100644 --- a/WidgetDashboardIntentHandler/IntentHandler.swift +++ b/WidgetDashboardIntentHandler/IntentHandler.swift @@ -41,37 +41,30 @@ class IntentHandler: INExtension, DashboardIntentHandling, AccountIntentHandling // Application func provideApplicationsOptionsCollection(for intent: DashboardIntent, with completion: @escaping (INObjectCollection?, Error?) -> Void) { - var applications: [Applications] = [] - var activeTableAccount: tableAccount? - - let accountIdentifier: String = intent.accounts?.identifier ?? "active" - if accountIdentifier == "active" { - activeTableAccount = NCManageDatabase.shared.getActiveTableAccount() - } else { - activeTableAccount = NCManageDatabase.shared.getTableAccount(predicate: NSPredicate(format: "account == %@", accountIdentifier)) + guard let account = dashboardAccount(for: intent) else { + completion(nil, nil) + return } - guard let activeTableAccount else { - return completion(nil, nil) + let applications = NCManageDatabase.shared.getDashboardWidgetApplications(account: account.account).map { + Applications(identifier: $0.id, display: $0.title) } - - let results = NCManageDatabase.shared.getDashboardWidgetApplications(account: activeTableAccount.account) - for result in results { - let application = Applications(identifier: result.id, display: result.title) - applications.append(application) - } - completion(INObjectCollection(items: applications), nil) } func defaultApplications(for intent: DashboardIntent) -> Applications? { - guard let account = NCManageDatabase.shared.getActiveTableAccount() else { - return nil - } - if let result = NCManageDatabase.shared.getDashboardWidgetApplications(account: account.account).first { - return Applications(identifier: result.id, display: result.title) - } - return nil + guard let account = dashboardAccount(for: intent), + let module = NCManageDatabase.shared.getDashboardWidgetApplications(account: account.account).first else { return nil } + + return Applications(identifier: module.id, display: module.title) + } + + private func dashboardAccount(for intent: DashboardIntent) -> tableAccount? { + let database = NCManageDatabase.shared + let accountIdentifier = intent.accounts?.identifier ?? "active" + return accountIdentifier == "active" + ? database.getActiveTableAccount() + : database.getTableAccount(account: accountIdentifier) } // Account diff --git a/iOSClient/Data/NCManageDatabase+DashboardWidget.swift b/iOSClient/Data/NCManageDatabase+DashboardWidget.swift index fb8714c5ca..30c7abac28 100644 --- a/iOSClient/Data/NCManageDatabase+DashboardWidget.swift +++ b/iOSClient/Data/NCManageDatabase+DashboardWidget.swift @@ -7,6 +7,12 @@ import UIKit import RealmSwift import NextcloudKit +enum DashboardItemAPIVersion: Int, PersistableEnum { + case unsupported = 0 + case v1 = 1 + case v2 = 2 +} + class tableDashboardWidget: Object { @Persisted(primaryKey: true) var index = "" @Persisted var account = "" @@ -17,6 +23,7 @@ class tableDashboardWidget: Object { @Persisted var iconUrl: String? @Persisted var widgetUrl: String? @Persisted var itemIconsRound: Bool = false + @Persisted var preferredItemAPIVersion: DashboardItemAPIVersion? } class tableDashboardWidgetButton: Object { @@ -32,7 +39,9 @@ extension NCManageDatabase { // MARK: - Realm Write - func addDashboardWidgetAsync(account: String, dashboardWidgets: [NCCDashboardWidget]) async { + func addDashboardWidgetAsync(account: String, + dashboardWidgets: [NCCDashboardWidget], + preferredItemAPIVersions: [String: DashboardItemAPIVersion]) async { await core.performRealmWriteAsync { realm in // Remove existing widgets for the account realm.delete(realm.objects(tableDashboardWidget.self).filter("account == %@", account)) @@ -50,6 +59,7 @@ extension NCManageDatabase { widgetObject.iconUrl = widget.iconUrl widgetObject.widgetUrl = widget.widgetUrl widgetObject.itemIconsRound = widget.itemIconsRound + widgetObject.preferredItemAPIVersion = preferredItemAPIVersions[widget.id] realm.add(widgetObject, update: .all) diff --git a/iOSClient/NCGlobal.swift b/iOSClient/NCGlobal.swift index 3bdc3d9405..4c5ffed945 100644 --- a/iOSClient/NCGlobal.swift +++ b/iOSClient/NCGlobal.swift @@ -305,14 +305,6 @@ final class NCGlobal: Sendable { let actionTextDocument = "create-text-document" let actionVoiceMemo = "create-voice-memo" - // WIDGET ACTION - // - let widgetActionNoAction = "nextcloud://open-action?action=no-action" - let widgetActionUploadAsset = "nextcloud://open-action?action=upload-asset" - let widgetActionScanDocument = "nextcloud://open-action?action=add-scan-document" - let widgetActionTextDocument = "nextcloud://open-action?action=create-text-document" - let widgetActionVoiceMemo = "nextcloud://open-action?action=create-voice-memo" - // APPCONFIG // let configuration_brand = "brand" diff --git a/iOSClient/Networking/NCService.swift b/iOSClient/Networking/NCService.swift index 0f252a11ce..c2727eaee0 100644 --- a/iOSClient/Networking/NCService.swift +++ b/iOSClient/Networking/NCService.swift @@ -116,30 +116,31 @@ class NCService: NSObject { let resultsDashboardWidget = await NextcloudKit.shared.getDashboardWidgetAsync(account: account) if resultsDashboardWidget.error == .success, let dashboardWidgets = resultsDashboardWidget.dashboardWidgets { - await NCManageDatabase.shared.addDashboardWidgetAsync(account: account, dashboardWidgets: dashboardWidgets) + let catalog = resultsDashboardWidget.responseData?.data.flatMap { + try? JSONDecoder().decode(DashboardCatalogResponse.self, from: $0) + } + await NCManageDatabase.shared.addDashboardWidgetAsync(account: account, + dashboardWidgets: dashboardWidgets, + preferredItemAPIVersions: catalog?.preferredItemAPIVersions ?? [:]) for widget in dashboardWidgets { - if let url = URL(string: widget.iconUrl), - let fileName = widget.iconClass { - let resultsDownloadPreview = await NextcloudKit.shared.downloadPreviewAsync(url: url, account: account) - if resultsDownloadPreview.error == .success, - let data = resultsDownloadPreview.responseData?.data { - var image: UIImage? - let size = CGSize(width: 256, height: 256) - - if let uiImage = UIImage(data: data)?.resizeImage(size: size) { - image = uiImage - } else if let svgImage = try? await NCSVGRenderer().renderSVGToUIImage(svgData: data, size: size) { - image = svgImage - } - - if let image { - let filePath = (self.utilityFileSystem.directoryUserData as NSString).appendingPathComponent(fileName + ".png") - do { - try image.pngData()?.write(to: URL(fileURLWithPath: filePath), options: .atomic) - } catch { - print("Failed to write image to disk: \(error.localizedDescription)") - } - } + guard let url = URL(string: widget.iconUrl), + let fileName = widget.iconClass, + let data = await utility.downloadDashboardIcon(from: url, account: account) else { continue } + + let size = CGSize(width: 256, height: 256) + let image: UIImage? + if let raster = UIImage(data: data)?.resizeImage(size: size) { + image = raster + } else { + image = try? await NCSVGRenderer().renderSVGToUIImage(svgData: data, size: size) + } + + if let image { + let filePath = (utilityFileSystem.directoryUserData as NSString).appendingPathComponent(fileName + ".png") + do { + try image.pngData()?.write(to: URL(fileURLWithPath: filePath), options: .atomic) + } catch { + print("Failed to write image to disk: \(error.localizedDescription)") } } } @@ -394,3 +395,36 @@ class NCService: NSObject { } } } + +private struct DashboardCatalogResponse: Decodable { + struct OCS: Decodable { + struct Module: Decodable { + let id: String? + let itemAPIVersions: [Int]? + + private enum CodingKeys: String, CodingKey { + case id + case itemAPIVersions = "item_api_versions" + } + + var preferredItemAPIVersion: DashboardItemAPIVersion? { + guard let itemAPIVersions else { return nil } + if itemAPIVersions.contains(DashboardItemAPIVersion.v2.rawValue) { return .v2 } + if itemAPIVersions.contains(DashboardItemAPIVersion.v1.rawValue) { return .v1 } + return .unsupported + } + } + + let data: [String: Module] + } + + let ocs: OCS + + var preferredItemAPIVersions: [String: DashboardItemAPIVersion] { + ocs.data.values.reduce(into: [:]) { versions, module in + if let id = module.id { + versions[id] = module.preferredItemAPIVersion + } + } + } +} diff --git a/iOSClient/SceneDelegate.swift b/iOSClient/SceneDelegate.swift index ca659ef31f..43294a619b 100644 --- a/iOSClient/SceneDelegate.swift +++ b/iOSClient/SceneDelegate.swift @@ -16,6 +16,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { private let appDelegate = UIApplication.shared.delegate as? AppDelegate private var privacyProtectionWindow: UIWindow? private var passcodeWindow: NCPasscodeWindow? + private var pendingWidgetURL: URL? + private var widgetOpenTask: Task? private let global = NCGlobal.shared private let alreadyMigratedMultiDomains = UserDefaults.standard.bool(forKey: NCGlobal.shared.udMigrationMultiDomains) @@ -23,6 +25,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { guard let windowScene = (scene as? UIWindowScene) else { return } + pendingWidgetURL = connectionOptions.urlContexts.map(\.url).first(where: isWidgetURL) NotificationCenter.default.removeObserver(self, name: NCPasscodeModel.lockoutNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(passcodeLockoutStarted), name: NCPasscodeModel.lockoutNotification, object: nil) @@ -195,6 +198,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { if activateSceneForAccount { self.activateSceneForAccount(scene, account: activeTblAccount.account, controller: controller) } + openPendingWidgetURL(in: scene) } // Clean orphaned FP Domains @@ -206,6 +210,9 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneDidDisconnect(_ scene: UIScene) { guard let windowScene = scene as? UIWindowScene else { return } + widgetOpenTask?.cancel() + pendingWidgetURL = nil + passcodeWindow?.hide() passcodeWindow = nil hidePrivacyProtectionWindow() @@ -227,6 +234,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneDidBecomeActive(_ scene: UIScene) { hidePrivacyProtectionWindow() + openPendingWidgetURL(in: scene) if !NextcloudKit.shared.isNetworkReachable(), let windowScenee = SceneManager.shared.getWindow(scene: scene)?.windowScene { @@ -314,8 +322,16 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { - guard let controller = SceneManager.shared.getController(scene: scene), - let url = URLContexts.first?.url else { return } + guard let url = URLContexts.first?.url else { return } + + if isWidgetURL(url) { + widgetOpenTask?.cancel() + pendingWidgetURL = url + openPendingWidgetURL(in: scene) + return + } + + guard let controller = SceneManager.shared.getController(scene: scene) else { return } let scheme = url.scheme let action = url.host let versionApp = NCUtility().getVersionMaintenance() @@ -327,13 +343,13 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { return } - func getMatchedAccount(user: String, url: String, account: String? = nil) async -> tableAccount? { + func getMatchedAccount(user: String, url: String) async -> tableAccount? { let tblAccounts = await NCManageDatabase.shared.getAllTableAccountAsync() for tblAccount in tblAccounts { let host = URL(string: tblAccount.urlBase)?.host() ?? "" - if (account == tblAccount.account) || (url.contains(host) && user == tblAccount.userId) { + if url.contains(host), user == tblAccount.userId { await NCAccount().changeAccount(tblAccount.account, userProfile: nil, controller: controller) // wait switch account try? await Task.sleep(for: .seconds(1)) @@ -442,57 +458,6 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } } } - } - - /* - Example: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123 - */ - - else if scheme == self.global.appScheme && action == "open-file" { - if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) { - let queryItems = urlComponents.queryItems - guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value, - // let pathScheme = queryItems?.filter({ $0.name == "path" }).first?.value, - let linkScheme = queryItems?.filter({ $0.name == "link" }).first?.value else { - return - } - let domain = URL(string: linkScheme)?.host ?? "" - let accountScheme = queryItems?.filter({ $0.name == "account" }).first?.value - - Task { - guard let tblAccount = await getMatchedAccount(user: userScheme, url: linkScheme, account: accountScheme) else { - - let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain) - let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert) - alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in })) - - controller.present(alertController, animated: true) - return - } - - let results = await NextcloudKit.shared.getFileFromFileIdAsync(link: linkScheme, - account: tblAccount.account) - if results.error == .success, let file = results.file { - let metadata = await NCManageDatabaseCreateMetadata().convertFileToMetadataAsync(file) - await NCManageDatabase.shared.addMetadataAsync(metadata) - if metadata.hasPreview { - let results = await NextcloudKit.shared.downloadPreviewAsync(fileId: metadata.fileId, etag: metadata.etag, account: metadata.account) - if results.error == .success, - let data = results.responseData?.data { - NCUtility().createImageFileFrom(data: data, metadata: metadata) - } - } - await NCNetworking.shared.openFileView(serverUrl: metadata.serverUrl, - metadata: metadata, - sceneIdentifier: controller.sceneIdentifier) - } - } - } - - /* - Example: nextcloud://open-and-switch-account?user=marinofaggiana&url=https://cloud.nextcloud.com - */ - } else if scheme == self.global.appScheme && action == "open-and-switch-account" { guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return @@ -515,6 +480,142 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } } + private func isWidgetURL(_ url: URL) -> Bool { + guard url.scheme == global.appScheme else { return false } + + switch url.host { + case "open-file", DeepLink.openFavorites.rawValue, DeepLink.openUrl.rawValue: + return true + default: + return false + } + } + + private func openPendingWidgetURL(in scene: UIScene) { + guard let url = pendingWidgetURL, + passcodeWindow == nil, + scene.activationState == .foregroundActive, + let controller = window?.rootViewController as? NCMainTabBarController else { return } + + pendingWidgetURL = nil + widgetOpenTask = Task { @MainActor in + guard !Task.isCancelled else { return } + + switch url.host { + case DeepLink.openFavorites.rawValue: + await openWidgetFavorites(url, scene: scene, controller: controller) + case DeepLink.openUrl.rawValue: + NCDeepLinkHandler().parseDeepLink(url, controller: controller) + case "open-file": + await openWidgetFile(url, scene: scene, controller: controller) + default: + break + } + } + } + + private func openWidgetFavorites(_ url: URL, scene: UIScene, controller: NCMainTabBarController) async { + let account = URLComponents(url: url, resolvingAgainstBaseURL: false)? + .queryItems?.first(where: { $0.name == "account" })?.value + + if let account, account != controller.account { + let target = await NCManageDatabase.shared.getTableAccountAsync(account: account) + guard !Task.isCancelled, window?.rootViewController === controller else { return } + if passcodeWindow != nil || scene.activationState != .foregroundActive { + pendingWidgetURL = url + return + } + + guard target != nil else { + let message = String(format: NSLocalizedString("_account_does_not_exist_", comment: ""), account) + let alert = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default)) + controller.present(alert, animated: true) + return + } + + await NCAccount().changeAccount(account, userProfile: nil, controller: controller) + } + + guard !Task.isCancelled, window?.rootViewController === controller, + account == nil || controller.account == account else { return } + + if passcodeWindow != nil || scene.activationState != .foregroundActive { + pendingWidgetURL = url + return + } + + NCDeepLinkHandler().handleDeepLink(.openFavorites, controller: controller) + (controller.selectedViewController as? UINavigationController)?.popToRootViewController(animated: false) + } + + private func openWidgetFile(_ url: URL, scene: UIScene, controller: NCMainTabBarController) async { + guard let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems, + let user = queryItems.first(where: { $0.name == "user" })?.value, + let link = queryItems.first(where: { $0.name == "link" })?.value, + let fileURL = URL(string: link) else { return } + + let account = queryItems.first(where: { $0.name == "account" })?.value + let fileId = fileURL.lastPathComponent + guard !fileId.isEmpty, fileId.allSatisfy({ $0.isASCII && $0.isNumber }) else { return } + + let accounts = await NCManageDatabase.shared.getAllTableAccountAsync() + guard !Task.isCancelled, window?.rootViewController === controller else { return } + if passcodeWindow != nil || scene.activationState != .foregroundActive { + pendingWidgetURL = url + return + } + + guard let target = accounts.first(where: { candidate in + (account == nil || candidate.account == account) + && candidate.userId == user + && URL(string: candidate.urlBase + "/f/" + fileId) == fileURL + }) else { + let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), user, fileURL.host ?? "") + let alert = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default)) + controller.present(alert, animated: true) + return + } + + if controller.account != target.account { + await NCAccount().changeAccount(target.account, userProfile: nil, controller: controller) + } + guard !Task.isCancelled, controller.account == target.account else { return } + + let result = await NextcloudKit.shared.getFileFromFileIdAsync(fileId: fileId, account: target.account) + guard !Task.isCancelled, window?.rootViewController === controller, + controller.account == target.account else { return } + if passcodeWindow != nil || scene.activationState != .foregroundActive { + pendingWidgetURL = url + return + } + + if result.error != .success { + await showErrorBanner(windowScene: scene as? UIWindowScene, error: result.error) + return + } + guard let file = result.file else { + await showErrorBanner(windowScene: scene as? UIWindowScene, text: "_error_not_found_") + return + } + + let metadata = await NCManageDatabaseCreateMetadata().convertFileToMetadataAsync(file) + await NCManageDatabase.shared.addMetadataAsync(metadata) + + guard !Task.isCancelled, window?.rootViewController === controller, + controller.account == target.account else { return } + + if passcodeWindow != nil || scene.activationState != .foregroundActive { + pendingWidgetURL = url + return + } + + await NCNetworking.shared.openFileView(serverUrl: metadata.serverUrl, + metadata: metadata, + sceneIdentifier: controller.sceneIdentifier) + } + private func showPrivacyProtectionWindow() { guard privacyProtectionWindow == nil, let windowScene = self.window?.windowScene else { @@ -559,13 +660,17 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { self.passcodeWindow = nil switch result { case .authenticated: - if NCPreferences().accountRequest, + if self.pendingWidgetURL != nil, let scene = self.window?.windowScene { + self.openPendingWidgetURL(in: scene) + } else if NCPreferences().accountRequest, let controller, self.window?.rootViewController === controller, NCManageDatabase.shared.getTableAccount(account: controller.account) != nil { self.requestedAccount(controller: controller) } case .reset: + self.widgetOpenTask?.cancel() + self.pendingWidgetURL = nil self.appDelegate?.resetApplication() case .cancelled, .configured, .disabled: break @@ -590,7 +695,9 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { return } - if !requestPasscodeIfNeeded(controller: controller), NCPreferences().accountRequest { + if !requestPasscodeIfNeeded(controller: controller), + pendingWidgetURL == nil, + NCPreferences().accountRequest { requestedAccount(controller: controller) } diff --git a/iOSClient/Supporting Files/en.lproj/Localizable.strings b/iOSClient/Supporting Files/en.lproj/Localizable.strings index 9253621922..cd77e60250 100644 --- a/iOSClient/Supporting Files/en.lproj/Localizable.strings +++ b/iOSClient/Supporting Files/en.lproj/Localizable.strings @@ -520,8 +520,14 @@ "_select_color_" = "Select the color"; "_change_color_" = "Change color"; "_description_dashboardwidget_" = "Having the Dashboard always at your fingertips has never been easier."; -"_description_fileswidget_" = "View your recent files and use the toolbar to speed up your operations."; -"_description_toolbarwidget_" = "A toolbar to speed up your operations."; +"_widget_recent_files_" = "Recent files"; +"_widget_no_recent_files_" = "No recent files"; +"_widget_recent_files_description_" = "View and open your recent files."; +"_widget_refresh_files_" = "Refresh recent files"; +"_widget_refresh_dashboard_" = "Refresh Dashboard"; +"_widget_dashboard_available_on_web_" = "Available on the web"; +"_widget_dashboard_open_in_browser_" = "Open in browser"; +"_widget_updated_at_" = "Updated %@"; "_title_lockscreenwidget_" = "Status"; "_description_lockscreenwidget_" = "Keep an eye on available space and recent activity"; diff --git a/iOSClient/Utility/NCUtility+Image.swift b/iOSClient/Utility/NCUtility+Image.swift index 94e9dc459d..b715e7196a 100644 --- a/iOSClient/Utility/NCUtility+Image.swift +++ b/iOSClient/Utility/NCUtility+Image.swift @@ -5,12 +5,44 @@ 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,