diff --git a/Brand/Database.swift b/Brand/Database.swift index ed6d77c874..677a635792 100644 --- a/Brand/Database.swift +++ b/Brand/Database.swift @@ -26,4 +26,4 @@ import Foundation // Database Realm // let databaseName = "nextcloud.realm" -let databaseSchemaVersion: UInt64 = 320 +let databaseSchemaVersion: UInt64 = 321 diff --git a/File Provider Extension/FileProviderData.swift b/File Provider Extension/FileProviderData.swift index 8e66267604..de7ddbb03e 100644 --- a/File Provider Extension/FileProviderData.swift +++ b/File Provider Extension/FileProviderData.swift @@ -72,13 +72,11 @@ class fileProviderData: NSObject { } // LOG - if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path { - NextcloudKit.shared.nkCommonInstance.pathLog = pathDirectoryGroup - let levelLog = CCUtility.getLogLevel() - NextcloudKit.shared.nkCommonInstance.levelLog = levelLog - let version = NSString(format: NCBrandOptions.shared.textCopyrightNextcloudiOS as NSString, NCUtility.shared.getVersionApp()) as String - NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start File Provider session with level \(levelLog) " + version + " (File Provider Extension)") - } + NextcloudKit.shared.nkCommonInstance.pathLog = NCUtilityFileSystem.shared.directoryGroup + let levelLog = NCKeychain().logLevel + NextcloudKit.shared.nkCommonInstance.levelLog = levelLog + let version = NSString(format: NCBrandOptions.shared.textCopyrightNextcloudiOS as NSString, NCUtility.shared.getVersionApp()) as String + NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start File Provider session with level \(levelLog) " + version + " (File Provider Extension)") // NO DOMAIN -> Set default account if domain == nil { @@ -93,7 +91,7 @@ class fileProviderData: NSObject { NCManageDatabase.shared.setCapabilities(account: account) - NextcloudKit.shared.setup(account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account), urlBase: activeAccount.urlBase, userAgent: userAgent, nextcloudVersion: NCGlobal.shared.capabilityServerVersionMajor, delegate: NCNetworking.shared) + NextcloudKit.shared.setup(account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, password: NCKeychain().getPassword(account: activeAccount.account), urlBase: activeAccount.urlBase, userAgent: userAgent, nextcloudVersion: NCGlobal.shared.capabilityServerVersionMajor, delegate: NCNetworking.shared) NCNetworking.shared.delegate = providerExtension as? NCNetworkingDelegate return tableAccount.init(value: activeAccount) @@ -117,7 +115,7 @@ class fileProviderData: NSObject { NCManageDatabase.shared.setCapabilities(account: account) - NextcloudKit.shared.setup(account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account), urlBase: activeAccount.urlBase, userAgent: userAgent, nextcloudVersion: NCGlobal.shared.capabilityServerVersionMajor, delegate: NCNetworking.shared) + NextcloudKit.shared.setup(account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, password: NCKeychain().getPassword(account: activeAccount.account), urlBase: activeAccount.urlBase, userAgent: userAgent, nextcloudVersion: NCGlobal.shared.capabilityServerVersionMajor, delegate: NCNetworking.shared) NCNetworking.shared.delegate = providerExtension as? NCNetworkingDelegate return tableAccount.init(value: activeAccount) diff --git a/File Provider Extension/FileProviderEnumerator.swift b/File Provider Extension/FileProviderEnumerator.swift index 116dc9418a..9030370dc0 100644 --- a/File Provider Extension/FileProviderEnumerator.swift +++ b/File Provider Extension/FileProviderEnumerator.swift @@ -203,11 +203,11 @@ class FileProviderEnumerator: NSObject, NSFileProviderEnumerator { directoryEtag = tableDirectory.etag } - NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { account, files, _, error in + NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "0", showHiddenFiles: NCKeychain().showHiddenFiles) { account, files, _, error in if directoryEtag != files.first?.etag { - NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles()) { account, files, _, error in + NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: NCKeychain().showHiddenFiles) { account, files, _, error in if error == .success { DispatchQueue.global().async { diff --git a/File Provider Extension/FileProviderExtension+Actions.swift b/File Provider Extension/FileProviderExtension+Actions.swift index 71f04437ab..02867648b3 100644 --- a/File Provider Extension/FileProviderExtension+Actions.swift +++ b/File Provider Extension/FileProviderExtension+Actions.swift @@ -41,7 +41,7 @@ extension FileProviderExtension { if error == .success { - NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { _, files, _, error in + NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: NCKeychain().showHiddenFiles) { _, files, _, error in if error == .success, let file = files.first { @@ -92,7 +92,7 @@ extension FileProviderExtension { if error == .success { // || error == kOCErrorServerPathNotFound { - let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(itemIdentifier.rawValue)! + let fileNamePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(itemIdentifier.rawValue) do { try fileProviderUtility.shared.fileManager.removeItem(atPath: fileNamePath) } catch let error { @@ -100,8 +100,8 @@ extension FileProviderExtension { } if isDirectory { - let dirForDelete = CCUtility.stringAppendServerUrl(serverUrl, addFileName: fileName) - NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: dirForDelete!, account: account) + let dirForDelete = NCUtilityFileSystem.shared.stringAppendServerUrl(serverUrl, addFileName: fileName) + NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: dirForDelete, account: account) } NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) @@ -201,11 +201,11 @@ extension FileProviderExtension { let itemIdentifier = fileProviderUtility.shared.getItemIdentifier(metadata: metadata) // rename file - _ = fileProviderUtility.shared.moveFile(CCUtility.getDirectoryProviderStorageOcId(itemIdentifier.rawValue, fileNameView: fileNameFrom), toPath: CCUtility.getDirectoryProviderStorageOcId(itemIdentifier.rawValue, fileNameView: itemName)) + _ = fileProviderUtility.shared.moveFile(NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(itemIdentifier.rawValue, fileNameView: fileNameFrom), toPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(itemIdentifier.rawValue, fileNameView: itemName)) - _ = fileProviderUtility.shared.moveFile(CCUtility.getDirectoryProviderStoragePreviewOcId(itemIdentifier.rawValue, etag: metadata.etag), toPath: CCUtility.getDirectoryProviderStoragePreviewOcId(itemIdentifier.rawValue, etag: metadata.etag)) + _ = fileProviderUtility.shared.moveFile(NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(itemIdentifier.rawValue, etag: metadata.etag), toPath: NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(itemIdentifier.rawValue, etag: metadata.etag)) - _ = fileProviderUtility.shared.moveFile(CCUtility.getDirectoryProviderStorageIconOcId(itemIdentifier.rawValue, etag: metadata.etag), toPath: CCUtility.getDirectoryProviderStorageIconOcId(itemIdentifier.rawValue, etag: metadata.etag)) + _ = fileProviderUtility.shared.moveFile(NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(itemIdentifier.rawValue, etag: metadata.etag), toPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(itemIdentifier.rawValue, etag: metadata.etag)) NCManageDatabase.shared.setLocalFile(ocId: ocId, fileName: itemName, etag: nil) } @@ -245,7 +245,7 @@ extension FileProviderExtension { } if (favorite == true && metadata.favorite == false) || (favorite == false && metadata.favorite == true) { - let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)! + let fileNamePath = NCUtilityFileSystem.shared.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId) NextcloudKit.shared.setFavorite(fileName: fileNamePath, favorite: favorite) { _, error in diff --git a/File Provider Extension/FileProviderExtension+Thumbnail.swift b/File Provider Extension/FileProviderExtension+Thumbnail.swift index 48a4c1930a..fcc4e63e55 100644 --- a/File Provider Extension/FileProviderExtension+Thumbnail.swift +++ b/File Provider Extension/FileProviderExtension+Thumbnail.swift @@ -42,8 +42,8 @@ extension FileProviderExtension { if metadata.hasPreview { - let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)! - let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)! + let fileNamePath = NCUtilityFileSystem.shared.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId) + let fileNameIconLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag) if let urlBase = metadata.urlBase.urlEncoded, let fileNamePath = fileNamePath.urlEncoded, diff --git a/File Provider Extension/FileProviderExtension.swift b/File Provider Extension/FileProviderExtension.swift index 5e7c5a469f..27859708af 100644 --- a/File Provider Extension/FileProviderExtension.swift +++ b/File Provider Extension/FileProviderExtension.swift @@ -60,7 +60,7 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate { super.init() // Create directory File Provider Storage - CCUtility.getDirectoryProviderStorage() + _ = NCUtilityFileSystem.shared.directoryProviderStorage // Configure URLSession _ = NCNetworking.shared.sessionManagerBackgroundExtension } @@ -78,9 +78,9 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate { if containerItemIdentifier != NSFileProviderItemIdentifier.workingSet { if fileProviderData.shared.setupAccount(domain: domain, providerExtension: self) == nil { throw NSError(domain: NSFileProviderErrorDomain, code: NSFileProviderError.notAuthenticated.rawValue, userInfo: [:]) - } else if let passcode = CCUtility.getPasscode(), !passcode.isEmpty, CCUtility.isPasscodeAtStartEnabled() { + } else if NCKeychain().passcode != nil, NCKeychain().requestPasscodeAtStart { throw NSError(domain: NSFileProviderErrorDomain, code: NSFileProviderError.notAuthenticated.rawValue, userInfo: ["code": NSNumber(value: NCGlobal.shared.errorUnauthorizedFilesPasscode)]) - } else if CCUtility.getDisableFilesApp() || NCBrandOptions.shared.disable_openin_file { + } else if NCKeychain().disableFilesApp || NCBrandOptions.shared.disable_openin_file { throw NSError(domain: NSFileProviderErrorDomain, code: NSFileProviderError.notAuthenticated.rawValue, userInfo: ["code": NSNumber(value: NCGlobal.shared.errorDisableFilesApp)]) } } @@ -204,12 +204,12 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate { } let tableLocalFile = NCManageDatabase.shared.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) - if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata) && tableLocalFile?.etag == metadata.etag { + if tableLocalFile != nil && NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) && tableLocalFile?.etag == metadata.etag { return completionHandler(nil) } let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)! + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName) // Update status NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusDownloading) @@ -274,9 +274,9 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate { // Temp ocId ? if outstandingOcIdTemp[ocId] != nil && outstandingOcIdTemp[ocId] != ocId { ocId = outstandingOcIdTemp[ocId]! - let atPath = CCUtility.getDirectoryProviderStorageOcId(itemIdentifier.rawValue, fileNameView: fileName) - let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName) - CCUtility.copyFile(atPath: atPath, toPath: toPath) + let atPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(itemIdentifier.rawValue, fileNameView: fileName) + let toPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName) + NCUtilityFileSystem.shared.copyFile(atPath: atPath, toPath: toPath) } guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return } @@ -348,7 +348,7 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate { let ocIdTemp = NSUUID().uuidString.lowercased() NSFileCoordinator().coordinate(readingItemAt: fileURL, options: .withoutChanges, error: &error) { url in - _ = fileProviderUtility.shared.copyFile(url.path, toPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: fileName)) + _ = fileProviderUtility.shared.copyFile(url.path, toPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: fileName)) } fileURL.stopAccessingSecurityScopedResource() @@ -361,7 +361,7 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate { NCManageDatabase.shared.addMetadata(metadata) let serverUrlFileName = tableDirectory.serverUrl + "/" + fileName - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: fileName)! + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: fileName) if let task = NKBackground(nkCommonInstance: NextcloudKit.shared.nkCommonInstance).upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: nil, dateModificationFile: nil, description: ocIdTemp, session: NCNetworking.shared.sessionManagerBackgroundExtension) { @@ -383,7 +383,7 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate { guard let metadataTemp = NCManageDatabase.shared.getMetadataFromOcId(ocIdTemp) else { return } let metadata = tableMetadata.init(value: metadataTemp) - let url = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: fileName)) + let url = URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: fileName)) DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.outstandingSessionTasks.removeValue(forKey: url) } @@ -411,14 +411,14 @@ class FileProviderExtension: NSFileProviderExtension, NCNetworkingDelegate { NCManageDatabase.shared.addLocalFile(metadata: metadata) // New file - if ocId != ocIdTemp { + if let ocId, ocId != ocIdTemp { NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp)) // File system - let atPath = CCUtility.getDirectoryProviderStorageOcId(ocIdTemp) - let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId) - CCUtility.copyFile(atPath: atPath, toPath: toPath) + let atPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocIdTemp) + let toPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId) + NCUtilityFileSystem.shared.copyFile(atPath: atPath, toPath: toPath) } fileProviderData.shared.signalEnumerator(ocId: metadata.ocId, update: true) diff --git a/File Provider Extension/FileProviderItem.swift b/File Provider Extension/FileProviderItem.swift index a6b3fc9df6..af03f660dc 100644 --- a/File Provider Extension/FileProviderItem.swift +++ b/File Provider Extension/FileProviderItem.swift @@ -105,7 +105,7 @@ class FileProviderItem: NSObject, NSFileProviderItem { if metadata.directory { return true } - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { return true } else { return false diff --git a/File Provider Extension/FileProviderUtility.swift b/File Provider Extension/FileProviderUtility.swift index 6ba2c717c6..da3b6dc88d 100644 --- a/File Provider Extension/FileProviderUtility.swift +++ b/File Provider Extension/FileProviderUtility.swift @@ -53,9 +53,9 @@ class fileProviderUtility: NSObject { let itemIdentifier = getItemIdentifier(metadata: metadata) if metadata.directory { - CCUtility.getDirectoryProviderStorageOcId(itemIdentifier.rawValue) + _ = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(itemIdentifier.rawValue) } else { - CCUtility.getDirectoryProviderStorageOcId(itemIdentifier.rawValue, fileNameView: metadata.fileNameView) + NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(itemIdentifier.rawValue, fileNameView: metadata.fileNameView) } } diff --git a/Nextcloud.xcodeproj/project.pbxproj b/Nextcloud.xcodeproj/project.pbxproj index a7ccbc39f3..855601c002 100644 --- a/Nextcloud.xcodeproj/project.pbxproj +++ b/Nextcloud.xcodeproj/project.pbxproj @@ -70,9 +70,7 @@ AFCE353927E5DE0500FEA6C2 /* NCShare+Helper.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFCE353827E5DE0400FEA6C2 /* NCShare+Helper.swift */; }; C0046CDD2A17B98400D87C9D /* LoginUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0046CDC2A17B98400D87C9D /* LoginUITests.swift */; }; C03BA14A2A17BC57002C8BA3 /* XLForm in Frameworks */ = {isa = PBXBuildFile; productRef = C03BA1492A17BC57002C8BA3 /* XLForm */; }; - C03BA14C2A17BC60002C8BA3 /* UICKeyChainStore in Frameworks */ = {isa = PBXBuildFile; productRef = C03BA14B2A17BC60002C8BA3 /* UICKeyChainStore */; }; C04E2F192A17BA78001BAD85 /* XLForm in Frameworks */ = {isa = PBXBuildFile; productRef = C04E2F182A17BA78001BAD85 /* XLForm */; }; - C04E2F1B2A17BAAB001BAD85 /* UICKeyChainStore in Frameworks */ = {isa = PBXBuildFile; productRef = C04E2F1A2A17BAAB001BAD85 /* UICKeyChainStore */; }; C04E2F232A17BB4D001BAD85 /* FilesIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C04E2F222A17BB4D001BAD85 /* FilesIntegrationTests.swift */; }; D575039F27146F93008DC9DC /* String+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7A0D1342591FBC5008F8A13 /* String+Extension.swift */; }; D5B6AA7827200C7200D49C24 /* NCActivityTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5B6AA7727200C7200D49C24 /* NCActivityTableViewCell.swift */; }; @@ -107,7 +105,6 @@ F31F69542A2F89C400162F76 /* SwiftRichString in Frameworks */ = {isa = PBXBuildFile; productRef = F31F69532A2F89C400162F76 /* SwiftRichString */; }; F31F69562A2F89C400162F76 /* FirebaseDatabase in Frameworks */ = {isa = PBXBuildFile; productRef = F31F69552A2F89C400162F76 /* FirebaseDatabase */; }; F31F69582A2F89C400162F76 /* XLForm in Frameworks */ = {isa = PBXBuildFile; productRef = F31F69572A2F89C400162F76 /* XLForm */; }; - F31F695A2A2F89C400162F76 /* UICKeyChainStore in Frameworks */ = {isa = PBXBuildFile; productRef = F31F69592A2F89C400162F76 /* UICKeyChainStore */; }; F31F695C2A2F89C400162F76 /* Realm in Frameworks */ = {isa = PBXBuildFile; productRef = F31F695B2A2F89C400162F76 /* Realm */; }; F31F695E2A2F89C400162F76 /* JGProgressHUD in Frameworks */ = {isa = PBXBuildFile; productRef = F31F695D2A2F89C400162F76 /* JGProgressHUD */; }; F31F69612A2F907800162F76 /* __Snapshots__ in Resources */ = {isa = PBXBuildFile; fileRef = F31F69602A2F907800162F76 /* __Snapshots__ */; }; @@ -173,7 +170,6 @@ F70716E62987F81500E72C1D /* DocumentActionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F70716E52987F81500E72C1D /* DocumentActionViewController.swift */; }; F70716E92987F81500E72C1D /* MainInterface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = F70716E72987F81500E72C1D /* MainInterface.storyboard */; }; F70716ED2987F81500E72C1D /* File Provider Extension UI.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = F70716E32987F81500E72C1D /* File Provider Extension UI.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; - F70716F929881CFA00E72C1D /* UICKeyChainStore in Frameworks */ = {isa = PBXBuildFile; productRef = F70716F829881CFA00E72C1D /* UICKeyChainStore */; }; F70753EB2542A99800972D44 /* NCViewerMediaPage.swift in Sources */ = {isa = PBXBuildFile; fileRef = F70753EA2542A99800972D44 /* NCViewerMediaPage.swift */; }; F70753F12542A9A200972D44 /* NCViewerMedia.swift in Sources */ = {isa = PBXBuildFile; fileRef = F70753F02542A9A200972D44 /* NCViewerMedia.swift */; }; F70753F72542A9C000972D44 /* NCViewerMediaPage.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = F70753F62542A9C000972D44 /* NCViewerMediaPage.storyboard */; }; @@ -259,7 +255,6 @@ 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 */; }; - F7346E2528B0FEFA006CE2D2 /* UICKeyChainStore in Frameworks */ = {isa = PBXBuildFile; productRef = F7346E2428B0FEFA006CE2D2 /* UICKeyChainStore */; }; F7346E2928B0FFF2006CE2D2 /* RealmSwift in Frameworks */ = {isa = PBXBuildFile; productRef = F7346E2828B0FFF2006CE2D2 /* RealmSwift */; }; F734B06628E75C0100E180D5 /* TLPhotoPicker in Frameworks */ = {isa = PBXBuildFile; productRef = F734B06528E75C0100E180D5 /* TLPhotoPicker */; }; F7362A1F220C853A005101B5 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = F7362A1E220C853A005101B5 /* LaunchScreen.storyboard */; }; @@ -341,6 +336,8 @@ F74E7720277A2EF40013B958 /* XLForm in Frameworks */ = {isa = PBXBuildFile; productRef = F74E771F277A2EF40013B958 /* XLForm */; }; F7501C322212E57500FB1415 /* NCMedia.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = F7501C302212E57400FB1415 /* NCMedia.storyboard */; }; F7501C332212E57500FB1415 /* NCMedia.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7501C312212E57400FB1415 /* NCMedia.swift */; }; + F75379202AE2AD9400C0250E /* JGProgressHUD in Frameworks */ = {isa = PBXBuildFile; productRef = F753791F2AE2AD9400C0250E /* JGProgressHUD */; }; + F75379222AE2ADA100C0250E /* JGProgressHUD in Frameworks */ = {isa = PBXBuildFile; productRef = F75379212AE2ADA100C0250E /* JGProgressHUD */; }; F753BA93281FD8020015BFB6 /* EasyTipView in Frameworks */ = {isa = PBXBuildFile; productRef = F753BA92281FD8020015BFB6 /* EasyTipView */; }; F755BD9B20594AC7008C5FBB /* NCService.swift in Sources */ = {isa = PBXBuildFile; fileRef = F755BD9A20594AC7008C5FBB /* NCService.swift */; }; F757CC8229E7F88B00F31428 /* NCManageDatabase+Groupfolders.swift in Sources */ = {isa = PBXBuildFile; fileRef = F757CC8129E7F88B00F31428 /* NCManageDatabase+Groupfolders.swift */; }; @@ -372,6 +369,23 @@ F75EAED826D2552E00F4320E /* MarqueeLabel in Frameworks */ = {isa = PBXBuildFile; productRef = F75EAED726D2552E00F4320E /* MarqueeLabel */; }; F760329F252F0F8E0015A421 /* NCTransferCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = F760329D252F0F8E0015A421 /* NCTransferCell.swift */; }; F76032A0252F0F8E0015A421 /* NCTransferCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = F760329E252F0F8E0015A421 /* NCTransferCell.xib */; }; + F760DE032AE66EA80027D78A /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = F760DE022AE66EA80027D78A /* KeychainAccess */; }; + F760DE052AE66EBE0027D78A /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = F760DE042AE66EBE0027D78A /* KeychainAccess */; }; + F760DE072AE66EC70027D78A /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = F760DE062AE66EC70027D78A /* KeychainAccess */; }; + F760DE092AE66ED00027D78A /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = F760DE082AE66ED00027D78A /* KeychainAccess */; }; + F760DE0B2AE66ED80027D78A /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = F760DE0A2AE66ED80027D78A /* KeychainAccess */; }; + F760DE0D2AE66EDF0027D78A /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = F760DE0C2AE66EDF0027D78A /* KeychainAccess */; }; + F760DE0F2AE66EE60027D78A /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = F760DE0E2AE66EE60027D78A /* KeychainAccess */; }; + F760DE112AE66EF00027D78A /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = F760DE102AE66EF00027D78A /* KeychainAccess */; }; + F760DE132AE66EF80027D78A /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = F760DE122AE66EF80027D78A /* KeychainAccess */; }; + F760DE152AE66F020027D78A /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = F760DE142AE66F020027D78A /* KeychainAccess */; }; + F760DE172AE66F350027D78A /* NCKeychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = F760DE162AE66F350027D78A /* NCKeychain.swift */; }; + F760DE182AE66F350027D78A /* NCKeychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = F760DE162AE66F350027D78A /* NCKeychain.swift */; }; + F760DE192AE66F350027D78A /* NCKeychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = F760DE162AE66F350027D78A /* NCKeychain.swift */; }; + F760DE1A2AE66F350027D78A /* NCKeychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = F760DE162AE66F350027D78A /* NCKeychain.swift */; }; + F760DE1B2AE66F350027D78A /* NCKeychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = F760DE162AE66F350027D78A /* NCKeychain.swift */; }; + F760DE1C2AE66F350027D78A /* NCKeychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = F760DE162AE66F350027D78A /* NCKeychain.swift */; }; + F760DE1D2AE66F350027D78A /* NCKeychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = F760DE162AE66F350027D78A /* NCKeychain.swift */; }; F761856A29E98543006EB3B0 /* NCIntro.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = F761856629E98543006EB3B0 /* NCIntro.storyboard */; }; F761856B29E98543006EB3B0 /* NCIntroViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F761856729E98543006EB3B0 /* NCIntroViewController.swift */; }; F761856C29E98543006EB3B0 /* NCIntroCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = F761856829E98543006EB3B0 /* NCIntroCollectionViewCell.swift */; }; @@ -414,7 +428,6 @@ F76DA95B277B75A90082465B /* TOPasscodeViewController.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = F70B86822642CF5500ED5349 /* TOPasscodeViewController.xcframework */; }; F76DA95C277B75A90082465B /* TOPasscodeViewController.xcframework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = F70B86822642CF5500ED5349 /* TOPasscodeViewController.xcframework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; F76DA963277B760E0082465B /* Queuer in Frameworks */ = {isa = PBXBuildFile; productRef = F76DA962277B760E0082465B /* Queuer */; }; - F76DA966277B76F30082465B /* UICKeyChainStore in Frameworks */ = {isa = PBXBuildFile; productRef = F76DA965277B76F30082465B /* UICKeyChainStore */; }; F76DA969277B77EA0082465B /* DropDown in Frameworks */ = {isa = PBXBuildFile; productRef = F76DA968277B77EA0082465B /* DropDown */; }; F76DEE9728F808AF0041B1C9 /* LockscreenData.swift in Sources */ = {isa = PBXBuildFile; fileRef = F76DEE9428F808AF0041B1C9 /* LockscreenData.swift */; }; F76DEE9828F808AF0041B1C9 /* LockscreenWidgetProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = F76DEE9528F808AF0041B1C9 /* LockscreenWidgetProvider.swift */; }; @@ -575,7 +588,6 @@ F7A7FA6329265CF4000603EF /* NCManageE2EE.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7A7FA6229265CF4000603EF /* NCManageE2EE.swift */; }; F7A8D72428F1771B008BBE1C /* NextcloudKit in Frameworks */ = {isa = PBXBuildFile; productRef = F7A8D72328F1771B008BBE1C /* NextcloudKit */; }; F7A8D72828F17728008BBE1C /* RealmSwift in Frameworks */ = {isa = PBXBuildFile; productRef = F7A8D72728F17728008BBE1C /* RealmSwift */; }; - F7A8D72E28F17764008BBE1C /* UICKeyChainStore in Frameworks */ = {isa = PBXBuildFile; productRef = F7A8D72D28F17764008BBE1C /* UICKeyChainStore */; }; F7A8D73428F17E12008BBE1C /* NCDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7BAADB41ED5A87C00B7EAD4 /* NCDatabase.swift */; }; F7A8D73528F17E16008BBE1C /* NCManageDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7BAADB51ED5A87C00B7EAD4 /* NCManageDatabase.swift */; }; F7A8D73628F17E1A008BBE1C /* NCManageDatabase+Activity.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF4BF61D27562B3F0081CEEF /* NCManageDatabase+Activity.swift */; }; @@ -658,9 +670,6 @@ F7E98C1727E0D0FC001F9F19 /* NCManageDatabase+Video.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7E98C1527E0D0FC001F9F19 /* NCManageDatabase+Video.swift */; }; F7E98C1827E0D0FC001F9F19 /* NCManageDatabase+Video.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7E98C1527E0D0FC001F9F19 /* NCManageDatabase+Video.swift */; }; F7E98C1927E0D0FC001F9F19 /* NCManageDatabase+Video.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7E98C1527E0D0FC001F9F19 /* NCManageDatabase+Video.swift */; }; - F7EBCDCF277B81FF00A4EF67 /* UICKeyChainStore in Frameworks */ = {isa = PBXBuildFile; productRef = F7EBCDCE277B81FF00A4EF67 /* UICKeyChainStore */; }; - F7EBCDD1277B820D00A4EF67 /* UICKeyChainStore in Frameworks */ = {isa = PBXBuildFile; productRef = F7EBCDD0277B820D00A4EF67 /* UICKeyChainStore */; }; - F7EBCDD3277B821700A4EF67 /* UICKeyChainStore in Frameworks */ = {isa = PBXBuildFile; productRef = F7EBCDD2277B821700A4EF67 /* UICKeyChainStore */; }; F7ED547C25EEA65400956C55 /* QRCodeReader in Frameworks */ = {isa = PBXBuildFile; productRef = F7ED547B25EEA65400956C55 /* QRCodeReader */; }; F7EDE4CC262D7B6F00414FE6 /* NCEmptyDataSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7239870253D86B600257F49 /* NCEmptyDataSet.swift */; }; F7EDE4D1262D7B8400414FE6 /* NCDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7C1EEA425053A9C00866ACC /* NCDataSource.swift */; }; @@ -1078,6 +1087,7 @@ F75EDFBE1E8C116D00E6F369 /* libstdc++.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = "libstdc++.tbd"; path = "usr/lib/libstdc++.tbd"; sourceTree = SDKROOT; }; F760329D252F0F8E0015A421 /* NCTransferCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NCTransferCell.swift; path = iOSClient/Transfers/NCTransferCell.swift; sourceTree = SOURCE_ROOT; }; F760329E252F0F8E0015A421 /* NCTransferCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = NCTransferCell.xib; path = iOSClient/Transfers/NCTransferCell.xib; sourceTree = SOURCE_ROOT; }; + F760DE162AE66F350027D78A /* NCKeychain.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCKeychain.swift; sourceTree = ""; }; F761856629E98543006EB3B0 /* NCIntro.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = NCIntro.storyboard; sourceTree = ""; }; F761856729E98543006EB3B0 /* NCIntroViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NCIntroViewController.swift; sourceTree = ""; }; F761856829E98543006EB3B0 /* NCIntroCollectionViewCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NCIntroCollectionViewCell.swift; sourceTree = ""; }; @@ -1403,7 +1413,7 @@ F72AD71128C24BBB006CB92D /* NextcloudKit in Frameworks */, F314F1112A30C11200BC7FAB /* PreviewSnapshots in Frameworks */, F710FC88277B7D3F00AA9FBF /* RealmSwift in Frameworks */, - F7EBCDD3277B821700A4EF67 /* UICKeyChainStore in Frameworks */, + F760DE0F2AE66EE60027D78A /* KeychainAccess in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1418,8 +1428,8 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - C04E2F1B2A17BAAB001BAD85 /* UICKeyChainStore in Frameworks */, C04E2F192A17BA78001BAD85 /* XLForm in Frameworks */, + F760DE152AE66F020027D78A /* KeychainAccess in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1431,7 +1441,7 @@ F30A963C2A2DFD3600D7BCFE /* SVGKit in Frameworks */, F30A96362A2DFCD000D7BCFE /* RealmSwift in Frameworks */, F30A96342A2DFCD000D7BCFE /* Realm in Frameworks */, - C03BA14C2A17BC60002C8BA3 /* UICKeyChainStore in Frameworks */, + F760DE112AE66EF00027D78A /* KeychainAccess in Frameworks */, F30A963A2A2DFD3100D7BCFE /* JGProgressHUD in Frameworks */, C03BA14A2A17BC57002C8BA3 /* XLForm in Frameworks */, ); @@ -1442,9 +1452,9 @@ buildActionMask = 2147483647; files = ( F31F695C2A2F89C400162F76 /* Realm in Frameworks */, - F31F695A2A2F89C400162F76 /* UICKeyChainStore in Frameworks */, F31F69582A2F89C400162F76 /* XLForm in Frameworks */, F31F69542A2F89C400162F76 /* SwiftRichString in Frameworks */, + F760DE132AE66EF80027D78A /* KeychainAccess in Frameworks */, F31F69662A2F929600162F76 /* PreviewSnapshotsTesting in Frameworks */, F31F695E2A2F89C400162F76 /* JGProgressHUD in Frameworks */, F31F69522A2F89C400162F76 /* SVGKit in Frameworks */, @@ -1461,7 +1471,7 @@ F7490E8B29882CE4009DCE94 /* NextcloudKit in Frameworks */, F7490E8929882CC8009DCE94 /* SwiftEntryKit in Frameworks */, F7490E7229882BB4009DCE94 /* RealmSwift in Frameworks */, - F70716F929881CFA00E72C1D /* UICKeyChainStore in Frameworks */, + F760DE0D2AE66EDF0027D78A /* KeychainAccess in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1473,9 +1483,9 @@ F72AD70F28C24BA1006CB92D /* NextcloudKit in Frameworks */, F72CD01227A7E92400E59476 /* JGProgressHUD in Frameworks */, F77CB6A92AA08053000C3CA4 /* OpenSSL in Frameworks */, + F760DE092AE66ED00027D78A /* KeychainAccess in Frameworks */, F73ADD2126554F8E0069EA0D /* SwiftEntryKit in Frameworks */, F7A560482AE15D5000BE8FD6 /* Queuer in Frameworks */, - F7EBCDCF277B81FF00A4EF67 /* UICKeyChainStore in Frameworks */, F70821D829E59E6D001CA2D7 /* TagListView in Frameworks */, F7F623B72A5EFA0C0022D3D4 /* Gzip in Frameworks */, F72D7EB7263B1207000B3DFC /* MarkdownKit in Frameworks */, @@ -1487,12 +1497,13 @@ buildActionMask = 2147483647; files = ( F787AC0B298BCB540001BB00 /* SVGKitSwift in Frameworks */, - F7346E2528B0FEFA006CE2D2 /* UICKeyChainStore in Frameworks */, F783034428B5142B00B84583 /* NextcloudKit in Frameworks */, F7346E1328B0EF5B006CE2D2 /* SwiftUI.framework in Frameworks */, + F760DE052AE66EBE0027D78A /* KeychainAccess in Frameworks */, F7346E2928B0FFF2006CE2D2 /* RealmSwift in Frameworks */, F7A560462AE15D3D00BE8FD6 /* Queuer in Frameworks */, F783030D28B4C59A00B84583 /* SwiftEntryKit in Frameworks */, + F75379222AE2ADA100C0250E /* JGProgressHUD in Frameworks */, F7346E1228B0EF5B006CE2D2 /* WidgetKit.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -1502,9 +1513,10 @@ buildActionMask = 2147483647; files = ( F7A560442AE15D2900BE8FD6 /* Queuer in Frameworks */, - F7EBCDD1277B820D00A4EF67 /* UICKeyChainStore in Frameworks */, + F760DE0B2AE66ED80027D78A /* KeychainAccess in Frameworks */, F73ADD2426554FE20069EA0D /* SwiftEntryKit in Frameworks */, F710FC84277B7D3500AA9FBF /* RealmSwift in Frameworks */, + F75379202AE2AD9400C0250E /* JGProgressHUD in Frameworks */, F72AD71328C24BCC006CB92D /* NextcloudKit in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -1522,11 +1534,11 @@ F7BB7E4727A18C56009B9F29 /* Parchment in Frameworks */, F734B06628E75C0100E180D5 /* TLPhotoPicker in Frameworks */, F787AC09298BCB4A0001BB00 /* SVGKitSwift in Frameworks */, + F760DE032AE66EA80027D78A /* KeychainAccess in Frameworks */, F770768E263A8C3400A1BA94 /* FloatingPanel in Frameworks */, F710FC7C277B7D0000AA9FBF /* RealmSwift in Frameworks */, F758A01227A7F03E0069468B /* JGProgressHUD in Frameworks */, F77333882927A72100466E35 /* OpenSSL in Frameworks */, - F76DA966277B76F30082465B /* UICKeyChainStore in Frameworks */, F7792DE529EEE02D005930CE /* MobileVLCKit.xcframework in Frameworks */, F753BA93281FD8020015BFB6 /* EasyTipView in Frameworks */, F76DA95B277B75A90082465B /* TOPasscodeViewController.xcframework in Frameworks */, @@ -1552,9 +1564,9 @@ buildActionMask = 2147483647; files = ( F7A8D72828F17728008BBE1C /* RealmSwift in Frameworks */, - F7A8D72E28F17764008BBE1C /* UICKeyChainStore in Frameworks */, F7A8D72428F1771B008BBE1C /* NextcloudKit in Frameworks */, F7C9739228F17131002C43E2 /* Intents.framework in Frameworks */, + F760DE072AE66EC70027D78A /* KeychainAccess in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2296,6 +2308,7 @@ F765608E23BF813500765969 /* NCContentPresenter.swift */, F70968A324212C4E00ED60E5 /* NCLivePhoto.swift */, F702F30725EE5D47008F8E80 /* NCPopupViewController.swift */, + F760DE162AE66F350027D78A /* NCKeychain.swift */, F707C26421A2DC5200F6181E /* NCStoreReview.swift */, AF817EF0274BC781009ED85B /* NCUserBaseUrl.swift */, F70BFC7320E0FA7C00C67599 /* NCUtility.swift */, @@ -2705,9 +2718,9 @@ name = "Notification Service Extension"; packageProductDependencies = ( F710FC87277B7D3F00AA9FBF /* RealmSwift */, - F7EBCDD2277B821700A4EF67 /* UICKeyChainStore */, F72AD71028C24BBB006CB92D /* NextcloudKit */, F314F1102A30C11200BC7FAB /* PreviewSnapshots */, + F760DE0E2AE66EE60027D78A /* KeychainAccess */, ); productName = "Notification Service Extension"; productReference = 2C33C47F23E2C475005F963B /* Notification Service Extension.appex */; @@ -2747,7 +2760,7 @@ name = NextcloudUITests; packageProductDependencies = ( C04E2F182A17BA78001BAD85 /* XLForm */, - C04E2F1A2A17BAAB001BAD85 /* UICKeyChainStore */, + F760DE142AE66F020027D78A /* KeychainAccess */, ); productName = NextcloudUITests; productReference = C0046CDA2A17B98400D87C9D /* NextcloudUITests.xctest */; @@ -2769,12 +2782,12 @@ name = NextcloudIntegrationTests; packageProductDependencies = ( C03BA1492A17BC57002C8BA3 /* XLForm */, - C03BA14B2A17BC60002C8BA3 /* UICKeyChainStore */, F30A96332A2DFCD000D7BCFE /* Realm */, F30A96352A2DFCD000D7BCFE /* RealmSwift */, F30A96372A2DFD2900D7BCFE /* FirebaseDatabase */, F30A96392A2DFD3100D7BCFE /* JGProgressHUD */, F30A963B2A2DFD3600D7BCFE /* SVGKit */, + F760DE102AE66EF00027D78A /* KeychainAccess */, ); productName = NextcloudIntegrationTests; productReference = C04E2F202A17BB4D001BAD85 /* NextcloudIntegrationTests.xctest */; @@ -2800,11 +2813,11 @@ F31F69532A2F89C400162F76 /* SwiftRichString */, F31F69552A2F89C400162F76 /* FirebaseDatabase */, F31F69572A2F89C400162F76 /* XLForm */, - F31F69592A2F89C400162F76 /* UICKeyChainStore */, F31F695B2A2F89C400162F76 /* Realm */, F31F695D2A2F89C400162F76 /* JGProgressHUD */, F31F69652A2F929600162F76 /* PreviewSnapshotsTesting */, F31F69682A2F92F000162F76 /* SnapshotTestingHEIC */, + F760DE122AE66EF80027D78A /* KeychainAccess */, ); productName = NextcloudSnapshotTests; productReference = F31F69422A2F6D4500162F76 /* NextcloudSnapshotTests.xctest */; @@ -2824,10 +2837,10 @@ ); name = "File Provider Extension UI"; packageProductDependencies = ( - F70716F829881CFA00E72C1D /* UICKeyChainStore */, F7490E7129882BB4009DCE94 /* RealmSwift */, F7490E8829882CC8009DCE94 /* SwiftEntryKit */, F7490E8A29882CE4009DCE94 /* NextcloudKit */, + F760DE0C2AE66EDF0027D78A /* KeychainAccess */, ); productName = "File Provider Extension UI"; productReference = F70716E32987F81500E72C1D /* File Provider Extension UI.appex */; @@ -2850,13 +2863,13 @@ F72D7EB6263B1207000B3DFC /* MarkdownKit */, F73ADD2026554F8E0069EA0D /* SwiftEntryKit */, F710FC7F277B7D2700AA9FBF /* RealmSwift */, - F7EBCDCE277B81FF00A4EF67 /* UICKeyChainStore */, F72CD01127A7E92400E59476 /* JGProgressHUD */, F72AD70E28C24BA1006CB92D /* NextcloudKit */, F70821D729E59E6D001CA2D7 /* TagListView */, F7F623B62A5EFA0C0022D3D4 /* Gzip */, F77CB6A82AA08053000C3CA4 /* OpenSSL */, F7A560472AE15D5000BE8FD6 /* Queuer */, + F760DE082AE66ED00027D78A /* KeychainAccess */, ); productName = "Share Ext"; productReference = F7CE8AFB1DC1F8D8009CAE48 /* Share.appex */; @@ -2876,12 +2889,13 @@ ); name = Widget; packageProductDependencies = ( - F7346E2428B0FEFA006CE2D2 /* UICKeyChainStore */, F7346E2828B0FFF2006CE2D2 /* RealmSwift */, F783030C28B4C59A00B84583 /* SwiftEntryKit */, F783034328B5142B00B84583 /* NextcloudKit */, F787AC0A298BCB540001BB00 /* SVGKitSwift */, F7A560452AE15D3D00BE8FD6 /* Queuer */, + F75379212AE2ADA100C0250E /* JGProgressHUD */, + F760DE042AE66EBE0027D78A /* KeychainAccess */, ); productName = DashboardWidgetExtension; productReference = F7346E1028B0EF5B006CE2D2 /* Widget.appex */; @@ -2903,9 +2917,10 @@ packageProductDependencies = ( F73ADD2326554FE20069EA0D /* SwiftEntryKit */, F710FC83277B7D3500AA9FBF /* RealmSwift */, - F7EBCDD0277B820D00A4EF67 /* UICKeyChainStore */, F72AD71228C24BCC006CB92D /* NextcloudKit */, F7A560432AE15D2900BE8FD6 /* Queuer */, + F753791F2AE2AD9400C0250E /* JGProgressHUD */, + F760DE0A2AE66ED80027D78A /* KeychainAccess */, ); productName = "File Provider Extension"; productReference = F771E3D020E2392D00AFB62D /* File Provider Extension.appex */; @@ -2944,7 +2959,6 @@ F75EAED726D2552E00F4320E /* MarqueeLabel */, F74E771F277A2EF40013B958 /* XLForm */, F76DA962277B760E0082465B /* Queuer */, - F76DA965277B76F30082465B /* UICKeyChainStore */, F76DA968277B77EA0082465B /* DropDown */, F710FC79277B7D0000AA9FBF /* Realm */, F710FC7B277B7D0000AA9FBF /* RealmSwift */, @@ -2963,6 +2977,7 @@ F3EFBF5E2AB2100E00B5724C /* Shimmer */, F3077B7B2ABDA06A0013BA13 /* SwiftUIIntrospect */, F76B649D2ADFFDEC00014640 /* LRUCache */, + F760DE022AE66EA80027D78A /* KeychainAccess */, ); productName = "Crypto Cloud"; productReference = F7CE8AFA1DC1F8D8009CAE48 /* Nextcloud.app */; @@ -2984,7 +2999,7 @@ packageProductDependencies = ( F7A8D72328F1771B008BBE1C /* NextcloudKit */, F7A8D72728F17728008BBE1C /* RealmSwift */, - F7A8D72D28F17764008BBE1C /* UICKeyChainStore */, + F760DE062AE66EC70027D78A /* KeychainAccess */, ); productName = WidgetDashboardIntentHandler; productReference = F7C9739028F17131002C43E2 /* WidgetDashboardIntentHandler.appex */; @@ -3122,7 +3137,6 @@ F75EAED626D2552E00F4320E /* XCRemoteSwiftPackageReference "MarqueeLabel" */, F74E771E277A2EF40013B958 /* XCRemoteSwiftPackageReference "XLForm" */, F76DA961277B760E0082465B /* XCRemoteSwiftPackageReference "Queuer" */, - F76DA964277B76F10082465B /* XCRemoteSwiftPackageReference "UICKeyChainStore" */, F76DA967277B77E90082465B /* XCRemoteSwiftPackageReference "DropDown" */, F710FC78277B7CFF00AA9FBF /* XCRemoteSwiftPackageReference "realm-swift" */, F7BB7E4527A18C56009B9F29 /* XCRemoteSwiftPackageReference "Parchment" */, @@ -3141,6 +3155,7 @@ F3EFBF5D2AB20B9100B5724C /* XCRemoteSwiftPackageReference "SwiftUI-Shimmer" */, F3718CC02ABD9A76009BC4C2 /* XCRemoteSwiftPackageReference "SwiftUI-Introspect" */, F76B649A2ADFFAD200014640 /* XCRemoteSwiftPackageReference "LRUCache" */, + F760DE012AE66E860027D78A /* XCRemoteSwiftPackageReference "KeychainAccess" */, ); productRefGroup = F7F67B9F1A24D27800EE80DA; projectDirPath = ""; @@ -3412,6 +3427,7 @@ F343A4C12A1E734600DDA874 /* Optional+Extension.swift in Sources */, F7245927289BB59300474787 /* ThreadSafeDictionary.swift in Sources */, 2C33C48223E2C475005F963B /* NotificationService.swift in Sources */, + F760DE1D2AE66F350027D78A /* NCKeychain.swift in Sources */, AF4BF617275629E20081CEEF /* NCManageDatabase+Account.swift in Sources */, F7BF9D872934CA21009EE9A6 /* NCManageDatabase+LayoutForView.swift in Sources */, F749B64F297B0CBB00087535 /* NCManageDatabase+Share.swift in Sources */, @@ -3485,6 +3501,7 @@ F78E2D6A29AF02DB0024D4F3 /* Database.swift in Sources */, F7490E7429882BCC009DCE94 /* NCManageDatabase.swift in Sources */, F7490E6E29882B56009DCE94 /* NCBrand.swift in Sources */, + F760DE1C2AE66F350027D78A /* NCKeychain.swift in Sources */, F7490E8129882C79009DCE94 /* NCManageDatabase+DashboardWidget.swift in Sources */, F7490E8629882C99009DCE94 /* NCUtilityFileSystem.swift in Sources */, F763D2A22A249C4500A3C901 /* NCManageDatabase+Capabilities.swift in Sources */, @@ -3560,6 +3577,7 @@ F71459D21D12E3B700CAFEEC /* CCUtility.m in Sources */, F75A9EE723796C6F0044CFCE /* NCNetworking.swift in Sources */, AF730AFA27843E4C00B7520E /* NCShareExtension+NCDelegate.swift in Sources */, + F760DE1A2AE66F350027D78A /* NCKeychain.swift in Sources */, F749B64D297B0CBB00087535 /* NCManageDatabase+Share.swift in Sources */, F72FD3B8297ED49A00075D28 /* NCManageDatabase+E2EE.swift in Sources */, F7EDE4E0262D7BAF00414FE6 /* NCGridCell.swift in Sources */, @@ -3591,6 +3609,7 @@ buildActionMask = 2147483647; files = ( F78302FD28B4C42B00B84583 /* NCUserBaseUrl.swift in Sources */, + F760DE182AE66F350027D78A /* NCKeychain.swift in Sources */, F793E5A128B76541005E4B02 /* NotificationCenter+MainThread.swift in Sources */, F76DEE9928F808AF0041B1C9 /* LockscreenWidgetView.swift in Sources */, F7817D0029802D3D00FFBC65 /* NCViewCertificateDetails.swift in Sources */, @@ -3671,6 +3690,7 @@ F7D68FCF28CB9051009139F3 /* NCManageDatabase+DashboardWidget.swift in Sources */, F359D86B2A7D03420023F405 /* NCUtility+Exif.swift in Sources */, F7864AD02A78FE73004870E0 /* NCManageDatabase+LocalFile.swift in Sources */, + F760DE1B2AE66F350027D78A /* NCKeychain.swift in Sources */, AF4BF61B27562A4B0081CEEF /* NCManageDatabase+Metadata.swift in Sources */, F70460542499095400BB98A7 /* NotificationCenter+MainThread.swift in Sources */, F78A10C329322E8A008499B8 /* NCManageDatabase+Directory.swift in Sources */, @@ -3878,6 +3898,7 @@ F7CBC31C24F78E79004D3812 /* NCSortMenu.swift in Sources */, F769454822E9F20D000A798A /* NCShareNetworking.swift in Sources */, F749B64A297B0CBB00087535 /* NCManageDatabase+Share.swift in Sources */, + F760DE172AE66F350027D78A /* NCKeychain.swift in Sources */, F7C9555521F0C5470024296E /* NCActivity.swift in Sources */, F7725A60251F33BB00D125E0 /* NCFiles.swift in Sources */, F3BB46522A39EC4900461F6E /* NCMoreAppSuggestionsCell.swift in Sources */, @@ -3941,6 +3962,7 @@ F7A8D73828F17E21008BBE1C /* NCManageDatabase+DashboardWidget.swift in Sources */, F7A8D73928F17E25008BBE1C /* NCManageDatabase+Metadata.swift in Sources */, F343A4B52A1E084200DDA874 /* PHAsset+Extension.swift in Sources */, + F760DE192AE66F350027D78A /* NCKeychain.swift in Sources */, F72FD3B7297ED49A00075D28 /* NCManageDatabase+E2EE.swift in Sources */, F7A8D74128F18254008BBE1C /* UIColor+Extension.swift in Sources */, F7A8D73428F17E12008BBE1C /* NCDatabase.swift in Sources */, @@ -4761,7 +4783,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 2; + CURRENT_PROJECT_VERSION = 6; DEBUG_INFORMATION_FORMAT = dwarf; DEVELOPMENT_TEAM = NKUJUXUJ3B; ENABLE_STRICT_OBJC_MSGSEND = YES; @@ -4826,7 +4848,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 2; + CURRENT_PROJECT_VERSION = 6; DEVELOPMENT_TEAM = NKUJUXUJ3B; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; @@ -5104,6 +5126,14 @@ minimumVersion = 4.3.0; }; }; + F760DE012AE66E860027D78A /* XCRemoteSwiftPackageReference "KeychainAccess" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/kishikawakatsumi/KeychainAccess"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 4.0.0; + }; + }; F76B649A2ADFFAD200014640 /* XCRemoteSwiftPackageReference "LRUCache" */ = { isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/nicklockwood/LRUCache"; @@ -5120,14 +5150,6 @@ minimumVersion = 2.0.0; }; }; - F76DA964277B76F10082465B /* XCRemoteSwiftPackageReference "UICKeyChainStore" */ = { - isa = XCRemoteSwiftPackageReference; - repositoryURL = "https://github.com/kishikawakatsumi/UICKeyChainStore"; - requirement = { - branch = master; - kind = branch; - }; - }; F76DA967277B77E90082465B /* XCRemoteSwiftPackageReference "DropDown" */ = { isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/AssistoLab/DropDown"; @@ -5164,8 +5186,8 @@ isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/nextcloud/NextcloudKit"; requirement = { - branch = develop; - kind = branch; + kind = exactVersion; + version = 2.9.0; }; }; F788ECC5263AAAF900ADC67F /* XCRemoteSwiftPackageReference "MarkdownKit" */ = { @@ -5224,21 +5246,11 @@ package = F74E771E277A2EF40013B958 /* XCRemoteSwiftPackageReference "XLForm" */; productName = XLForm; }; - C03BA14B2A17BC60002C8BA3 /* UICKeyChainStore */ = { - isa = XCSwiftPackageProductDependency; - package = F76DA964277B76F10082465B /* XCRemoteSwiftPackageReference "UICKeyChainStore" */; - productName = UICKeyChainStore; - }; C04E2F182A17BA78001BAD85 /* XLForm */ = { isa = XCSwiftPackageProductDependency; package = F74E771E277A2EF40013B958 /* XCRemoteSwiftPackageReference "XLForm" */; productName = XLForm; }; - C04E2F1A2A17BAAB001BAD85 /* UICKeyChainStore */ = { - isa = XCSwiftPackageProductDependency; - package = F76DA964277B76F10082465B /* XCRemoteSwiftPackageReference "UICKeyChainStore" */; - productName = UICKeyChainStore; - }; F3077B7B2ABDA06A0013BA13 /* SwiftUIIntrospect */ = { isa = XCSwiftPackageProductDependency; package = F3718CC02ABD9A76009BC4C2 /* XCRemoteSwiftPackageReference "SwiftUI-Introspect" */; @@ -5299,11 +5311,6 @@ package = F74E771E277A2EF40013B958 /* XCRemoteSwiftPackageReference "XLForm" */; productName = XLForm; }; - F31F69592A2F89C400162F76 /* UICKeyChainStore */ = { - isa = XCSwiftPackageProductDependency; - package = F76DA964277B76F10082465B /* XCRemoteSwiftPackageReference "UICKeyChainStore" */; - productName = UICKeyChainStore; - }; F31F695B2A2F89C400162F76 /* Realm */ = { isa = XCSwiftPackageProductDependency; package = F710FC78277B7CFF00AA9FBF /* XCRemoteSwiftPackageReference "realm-swift" */; @@ -5339,11 +5346,6 @@ package = F3EFBF5D2AB20B9100B5724C /* XCRemoteSwiftPackageReference "SwiftUI-Shimmer" */; productName = Shimmer; }; - F70716F829881CFA00E72C1D /* UICKeyChainStore */ = { - isa = XCSwiftPackageProductDependency; - package = F76DA964277B76F10082465B /* XCRemoteSwiftPackageReference "UICKeyChainStore" */; - productName = UICKeyChainStore; - }; F70821D729E59E6D001CA2D7 /* TagListView */ = { isa = XCSwiftPackageProductDependency; package = F7A1050C29E587AF00FFD92B /* XCRemoteSwiftPackageReference "TagListView" */; @@ -5414,11 +5416,6 @@ package = F72DA9B225F53E4E00B87DB1 /* XCRemoteSwiftPackageReference "SwiftRichString" */; productName = SwiftRichString; }; - F7346E2428B0FEFA006CE2D2 /* UICKeyChainStore */ = { - isa = XCSwiftPackageProductDependency; - package = F76DA964277B76F10082465B /* XCRemoteSwiftPackageReference "UICKeyChainStore" */; - productName = UICKeyChainStore; - }; F7346E2828B0FFF2006CE2D2 /* RealmSwift */ = { isa = XCSwiftPackageProductDependency; package = F710FC78277B7CFF00AA9FBF /* XCRemoteSwiftPackageReference "realm-swift" */; @@ -5464,6 +5461,16 @@ package = F74E771E277A2EF40013B958 /* XCRemoteSwiftPackageReference "XLForm" */; productName = XLForm; }; + F753791F2AE2AD9400C0250E /* JGProgressHUD */ = { + isa = XCSwiftPackageProductDependency; + package = F72CD01027A7E92400E59476 /* XCRemoteSwiftPackageReference "JGProgressHUD" */; + productName = JGProgressHUD; + }; + F75379212AE2ADA100C0250E /* JGProgressHUD */ = { + isa = XCSwiftPackageProductDependency; + package = F72CD01027A7E92400E59476 /* XCRemoteSwiftPackageReference "JGProgressHUD" */; + productName = JGProgressHUD; + }; F753BA92281FD8020015BFB6 /* EasyTipView */ = { isa = XCSwiftPackageProductDependency; package = F753BA91281FD8010015BFB6 /* XCRemoteSwiftPackageReference "EasyTipView" */; @@ -5479,6 +5486,56 @@ package = F75EAED626D2552E00F4320E /* XCRemoteSwiftPackageReference "MarqueeLabel" */; productName = MarqueeLabel; }; + F760DE022AE66EA80027D78A /* KeychainAccess */ = { + isa = XCSwiftPackageProductDependency; + package = F760DE012AE66E860027D78A /* XCRemoteSwiftPackageReference "KeychainAccess" */; + productName = KeychainAccess; + }; + F760DE042AE66EBE0027D78A /* KeychainAccess */ = { + isa = XCSwiftPackageProductDependency; + package = F760DE012AE66E860027D78A /* XCRemoteSwiftPackageReference "KeychainAccess" */; + productName = KeychainAccess; + }; + F760DE062AE66EC70027D78A /* KeychainAccess */ = { + isa = XCSwiftPackageProductDependency; + package = F760DE012AE66E860027D78A /* XCRemoteSwiftPackageReference "KeychainAccess" */; + productName = KeychainAccess; + }; + F760DE082AE66ED00027D78A /* KeychainAccess */ = { + isa = XCSwiftPackageProductDependency; + package = F760DE012AE66E860027D78A /* XCRemoteSwiftPackageReference "KeychainAccess" */; + productName = KeychainAccess; + }; + F760DE0A2AE66ED80027D78A /* KeychainAccess */ = { + isa = XCSwiftPackageProductDependency; + package = F760DE012AE66E860027D78A /* XCRemoteSwiftPackageReference "KeychainAccess" */; + productName = KeychainAccess; + }; + F760DE0C2AE66EDF0027D78A /* KeychainAccess */ = { + isa = XCSwiftPackageProductDependency; + package = F760DE012AE66E860027D78A /* XCRemoteSwiftPackageReference "KeychainAccess" */; + productName = KeychainAccess; + }; + F760DE0E2AE66EE60027D78A /* KeychainAccess */ = { + isa = XCSwiftPackageProductDependency; + package = F760DE012AE66E860027D78A /* XCRemoteSwiftPackageReference "KeychainAccess" */; + productName = KeychainAccess; + }; + F760DE102AE66EF00027D78A /* KeychainAccess */ = { + isa = XCSwiftPackageProductDependency; + package = F760DE012AE66E860027D78A /* XCRemoteSwiftPackageReference "KeychainAccess" */; + productName = KeychainAccess; + }; + F760DE122AE66EF80027D78A /* KeychainAccess */ = { + isa = XCSwiftPackageProductDependency; + package = F760DE012AE66E860027D78A /* XCRemoteSwiftPackageReference "KeychainAccess" */; + productName = KeychainAccess; + }; + F760DE142AE66F020027D78A /* KeychainAccess */ = { + isa = XCSwiftPackageProductDependency; + package = F760DE012AE66E860027D78A /* XCRemoteSwiftPackageReference "KeychainAccess" */; + productName = KeychainAccess; + }; F76B649D2ADFFDEC00014640 /* LRUCache */ = { isa = XCSwiftPackageProductDependency; package = F76B649A2ADFFAD200014640 /* XCRemoteSwiftPackageReference "LRUCache" */; @@ -5489,11 +5546,6 @@ package = F76DA961277B760E0082465B /* XCRemoteSwiftPackageReference "Queuer" */; productName = Queuer; }; - F76DA965277B76F30082465B /* UICKeyChainStore */ = { - isa = XCSwiftPackageProductDependency; - package = F76DA964277B76F10082465B /* XCRemoteSwiftPackageReference "UICKeyChainStore" */; - productName = UICKeyChainStore; - }; F76DA968277B77EA0082465B /* DropDown */ = { isa = XCSwiftPackageProductDependency; package = F76DA967277B77E90082465B /* XCRemoteSwiftPackageReference "DropDown" */; @@ -5574,11 +5626,6 @@ package = F710FC78277B7CFF00AA9FBF /* XCRemoteSwiftPackageReference "realm-swift" */; productName = RealmSwift; }; - F7A8D72D28F17764008BBE1C /* UICKeyChainStore */ = { - isa = XCSwiftPackageProductDependency; - package = F76DA964277B76F10082465B /* XCRemoteSwiftPackageReference "UICKeyChainStore" */; - productName = UICKeyChainStore; - }; F7BB7E4627A18C56009B9F29 /* Parchment */ = { isa = XCSwiftPackageProductDependency; package = F7BB7E4527A18C56009B9F29 /* XCRemoteSwiftPackageReference "Parchment" */; @@ -5589,21 +5636,6 @@ package = F7D56B182972405400FA46C4 /* XCRemoteSwiftPackageReference "Mantis" */; productName = Mantis; }; - F7EBCDCE277B81FF00A4EF67 /* UICKeyChainStore */ = { - isa = XCSwiftPackageProductDependency; - package = F76DA964277B76F10082465B /* XCRemoteSwiftPackageReference "UICKeyChainStore" */; - productName = UICKeyChainStore; - }; - F7EBCDD0277B820D00A4EF67 /* UICKeyChainStore */ = { - isa = XCSwiftPackageProductDependency; - package = F76DA964277B76F10082465B /* XCRemoteSwiftPackageReference "UICKeyChainStore" */; - productName = UICKeyChainStore; - }; - F7EBCDD2277B821700A4EF67 /* UICKeyChainStore */ = { - isa = XCSwiftPackageProductDependency; - package = F76DA964277B76F10082465B /* XCRemoteSwiftPackageReference "UICKeyChainStore" */; - productName = UICKeyChainStore; - }; F7ED547B25EEA65400956C55 /* QRCodeReader */ = { isa = XCSwiftPackageProductDependency; package = F7ED547A25EEA65400956C55 /* XCRemoteSwiftPackageReference "QRCodeReader" */; diff --git a/Notification Service Extension/NotificationService.swift b/Notification Service Extension/NotificationService.swift index 55e927aca9..24efbc8e92 100644 --- a/Notification Service Extension/NotificationService.swift +++ b/Notification Service Extension/NotificationService.swift @@ -38,7 +38,7 @@ class NotificationService: UNNotificationServiceExtension { if let message = bestAttemptContent.userInfo["subject"] as? String { let tableAccounts = NCManageDatabase.shared.getAllAccount() for tableAccount in tableAccounts { - guard let privateKey = CCUtility.getPushNotificationPrivateKey(tableAccount.account), + guard let privateKey = NCKeychain().getPushNotificationPrivateKey(account: tableAccount.account), let decryptedMessage = NCPushNotificationEncryption.shared().decryptPushNotification(message, withDevicePrivateKey: privateKey), let data = decryptedMessage.data(using: .utf8) else { continue diff --git a/Share/NCShareCell.swift b/Share/NCShareCell.swift index 286ea4f729..39d68c4d15 100644 --- a/Share/NCShareCell.swift +++ b/Share/NCShareCell.swift @@ -59,7 +59,7 @@ class NCShareCell: UITableViewCell { fileNameCell?.text = fileName let fileSize = NCUtilityFileSystem.shared.getFileSize(filePath: (NSTemporaryDirectory() + fileName)) - sizeCell?.text = CCUtility.transformedSize(fileSize) + sizeCell?.text = NCUtilityFileSystem.shared.transformedSize(fileSize) moreButton?.setImage(NCUtility.shared.loadImage(named: "more").image(color: .label, size: 15), for: .normal) } diff --git a/Share/NCShareExtension+DataSource.swift b/Share/NCShareExtension+DataSource.swift index 8aef98fbed..2570dca9df 100644 --- a/Share/NCShareExtension+DataSource.swift +++ b/Share/NCShareExtension+DataSource.swift @@ -29,12 +29,9 @@ import NextcloudKit extension NCShareExtension: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { - guard let metadata = dataSource.cellForItemAt(indexPath: indexPath), - let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { - return showAlert(description: "_invalid_url_") - } - - if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: activeAccount.account) { + guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return showAlert(description: "_invalid_url_") } + let serverUrl = NCUtilityFileSystem.shared.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) + if metadata.e2eEncrypted && !NCKeychain().isEndToEndEnabled(account: activeAccount.account) { showAlert(title: "_info_", description: "_e2e_goto_settings_for_enable_") } @@ -138,7 +135,7 @@ extension NCShareExtension: UICollectionViewDataSource { cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) - let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)! + let lockServerUrl = NCUtilityFileSystem.shared.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, lockServerUrl)) // Local image: offline diff --git a/Share/NCShareExtension+Files.swift b/Share/NCShareExtension+Files.swift index 8b9d76d161..28a7e7c6b8 100644 --- a/Share/NCShareExtension+Files.swift +++ b/Share/NCShareExtension+Files.swift @@ -99,7 +99,7 @@ class NCFilesExtensionHandler { @discardableResult init(items: [NSExtensionItem], completion: @escaping ([String]) -> Void) { - CCUtility.emptyTemporaryDirectory() + NCUtilityFileSystem.shared.emptyTemporaryDirectory() var counter = 0 self.itemsProvider = items.compactMap({ $0.attachments }).flatMap { $0.filter({ @@ -118,7 +118,8 @@ class NCFilesExtensionHandler { if let url = item as? URL, url.isFileURL, !url.lastPathComponent.isEmpty { originalName = url.lastPathComponent - if fileNames.contains(originalName), let incrementalNumber = CCUtility.getIncrementalNumber() { + if fileNames.contains(originalName) { + let incrementalNumber = NCKeychain().incrementalNumber originalName = "\(url.deletingPathExtension().lastPathComponent) \(incrementalNumber).\(url.pathExtension)" } } diff --git a/Share/NCShareExtension+NCDelegate.swift b/Share/NCShareExtension+NCDelegate.swift index 88bb9b4eff..1aff747636 100644 --- a/Share/NCShareExtension+NCDelegate.swift +++ b/Share/NCShareExtension+NCDelegate.swift @@ -88,7 +88,7 @@ extension NCShareExtension: NCEmptyDataSetDelegate, NCAccountRequestDelegate { account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, - password: CCUtility.getPassword(activeAccount.account), + password: NCKeychain().getPassword(account: activeAccount.account), urlBase: activeAccount.urlBase, userAgent: userAgent, nextcloudVersion: 0, diff --git a/Share/NCShareExtension.swift b/Share/NCShareExtension.swift index 6405d46e8f..148b2c5e5a 100644 --- a/Share/NCShareExtension.swift +++ b/Share/NCShareExtension.swift @@ -111,14 +111,12 @@ class NCShareExtension: UIViewController { uploadView.addGestureRecognizer(uploadGesture) // LOG - let levelLog = CCUtility.getLogLevel() + let levelLog = NCKeychain().logLevel let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight() let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp()) NextcloudKit.shared.nkCommonInstance.levelLog = levelLog - if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path { - NextcloudKit.shared.nkCommonInstance.pathLog = pathDirectoryGroup - } + NextcloudKit.shared.nkCommonInstance.pathLog = NCUtilityFileSystem.shared.directoryGroup if isSimulatorOrTestFlight { NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start Share session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)") } else { @@ -297,7 +295,7 @@ extension NCShareExtension { var conflicts: [tableMetadata] = [] for fileName in filesName { let ocId = NSUUID().uuidString - let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)! + let toPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName) guard NCUtilityFileSystem.shared.copyFile(atPath: (NSTemporaryDirectory() + fileName), toPath: toPath) else { continue } let metadata = NCManageDatabase.shared.createMetadata( account: activeAccount.account, user: activeAccount.user, userId: activeAccount.userId, @@ -358,9 +356,8 @@ extension NCShareExtension { self.hud.progress = Float(fractionCompleted) } completion: { error in if error != .success { - let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)! NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) - NCUtilityFileSystem.shared.deleteFile(filePath: path) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId)) self.uploadErrors.append(metadata) } self.counterUploaded += 1 diff --git a/Widget/Dashboard/DashboardData.swift b/Widget/Dashboard/DashboardData.swift index 5e5924c43b..3b63e39778 100644 --- a/Widget/Dashboard/DashboardData.swift +++ b/Widget/Dashboard/DashboardData.swift @@ -90,7 +90,7 @@ func convertDataToImage(data: Data?, size: CGSize, fileNameToWrite: String?) -> } if let fileName = fileNameToWrite, let image = imageData { do { - let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png" + let fileNamePath: String = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName + ".png" try image.pngData()?.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic) } catch { } } @@ -130,7 +130,7 @@ func getDashboardDataEntry(configuration: DashboardIntent?, isPreview: Bool, dis } // NETWORKING - let password = CCUtility.getPassword(account.account)! + let password = NCKeychain().getPassword(account: account.account) NextcloudKit.shared.setup( account: account.account, user: account.user, @@ -142,14 +142,12 @@ func getDashboardDataEntry(configuration: DashboardIntent?, isPreview: Bool, dis delegate: NCNetworking.shared) // LOG - let levelLog = CCUtility.getLogLevel() + let levelLog = NCKeychain().logLevel let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight() let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp()) NextcloudKit.shared.nkCommonInstance.levelLog = levelLog - if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path { - NextcloudKit.shared.nkCommonInstance.pathLog = pathDirectoryGroup - } + NextcloudKit.shared.nkCommonInstance.pathLog = NCUtilityFileSystem.shared.directoryGroup if isSimulatorOrTestFlight { NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start \(NCBrandOptions.shared.brand) dashboard widget session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)") } else { @@ -162,7 +160,7 @@ func getDashboardDataEntry(configuration: DashboardIntent?, isPreview: Bool, dis var imagetmp = UIImage(named: "widget")! if let fileName = tableDashboard?.iconClass { - let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png" + let fileNamePath: String = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName + ".png" if let image = UIImage(contentsOfFile: fileNamePath) { imagetmp = image.withTintColor(.label, renderingMode: .alwaysOriginal) } @@ -206,7 +204,7 @@ func getDashboardDataEntry(configuration: DashboardIntent?, isPreview: Bool, dis if (pathComponents.last as? NSString)?.pathExtension.lowercased() == "svg" { imageTemplate = true } - if let item = CCUtility.value(forKey: "fileId", fromQueryItems: queryItems) { + if let item = queryItems?.filter({ $0.name == "fileId" }).first?.value { iconFileName = item } else if pathComponents.contains("avatar") { iconFileName = pathComponents[pathComponents.count - 2] @@ -224,7 +222,7 @@ func getDashboardDataEntry(configuration: DashboardIntent?, isPreview: Bool, dis imageColor = UIColor(hex: colorString) icon = UIImage(systemName: "circle.fill")! } else if let fileName = iconFileName { - let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png" + let fileNamePath: String = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName + ".png" if FileManager().fileExists(atPath: fileNamePath), let image = UIImage(contentsOfFile: fileNamePath) { icon = image } else { diff --git a/Widget/Files/FilesData.swift b/Widget/Files/FilesData.swift index 9dc8dfe82b..9fee549f12 100644 --- a/Widget/Files/FilesData.swift +++ b/Widget/Files/FilesData.swift @@ -124,7 +124,7 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi } // NETWORKING - let password = CCUtility.getPassword(account.account)! + let password = NCKeychain().getPassword(account: account.account) NextcloudKit.shared.setup( account: account.account, user: account.user, @@ -192,14 +192,13 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi let requestBody = String(format: requestBodyRecent, "/files/" + account.userId, lessDateString) // LOG - let levelLog = CCUtility.getLogLevel() + let levelLog = NCKeychain().logLevel let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight() let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp()) NextcloudKit.shared.nkCommonInstance.levelLog = levelLog - if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path { - NextcloudKit.shared.nkCommonInstance.pathLog = pathDirectoryGroup - } + NextcloudKit.shared.nkCommonInstance.pathLog = NCUtilityFileSystem.shared.directoryGroup + if isSimulatorOrTestFlight { NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start \(NCBrandOptions.shared.brand) widget session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)") } else { @@ -207,7 +206,7 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi } let options = NKRequestOptions(timeout: 90, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue) - NextcloudKit.shared.searchBodyRequest(serverUrl: account.urlBase, requestBody: requestBody, showHiddenFiles: CCUtility.getShowHiddenFiles(), options: options) { _, files, data, error in + NextcloudKit.shared.searchBodyRequest(serverUrl: account.urlBase, requestBody: requestBody, showHiddenFiles: NCKeychain().showHiddenFiles, options: options) { _, files, data, error in Task { var datas: [FilesData] = [] var imageRecent = UIImage(named: "file")! @@ -219,7 +218,7 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi guard !isLive(file: file, files: files) else { continue } // SUBTITLE - let subTitle = CCUtility.dateDiff(file.date as Date) + " · " + CCUtility.transformedSize(file.size) + let subTitle = CCUtility.dateDiff(file.date as Date) + " · " + NCUtilityFileSystem.shared.transformedSize(file.size) // URL: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123 guard var path = NCUtilityFileSystem.shared.getPath(path: file.path, user: file.user, fileName: file.fileName).urlEncoded else { continue } @@ -236,9 +235,9 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi if let image = NCUtility.shared.createFilePreviewImage(ocId: file.ocId, etag: file.etag, fileNameView: file.fileName, classFile: file.classFile, status: 0, createPreviewMedia: false) { imageRecent = image } else if file.hasPreview { - let fileNamePathOrFileId = CCUtility.returnFileNamePath(fromFileName: file.fileName, serverUrl: file.serverUrl, urlBase: file.urlBase, userId: file.userId, account: account.account)! - let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(file.ocId, etag: file.etag)! - let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(file.ocId, etag: file.etag)! + let fileNamePathOrFileId = NCUtilityFileSystem.shared.getFileNamePath(file.fileName, serverUrl: file.serverUrl, urlBase: file.urlBase, userId: file.userId) + let fileNamePreviewLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(file.ocId, etag: file.etag) + let fileNameIconLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(file.ocId, etag: file.etag) let (_, _, imageIcon, _, _, _) = await NextcloudKit.shared.downloadPreview(fileNamePathOrFileId: fileNamePathOrFileId, fileNamePreviewLocalPath: fileNamePreviewLocalPath, widthPreview: NCGlobal.shared.sizePreview, heightPreview: NCGlobal.shared.sizePreview, fileNameIconLocalPath: fileNameIconLocalPath, sizeIcon: NCGlobal.shared.sizeIcon, options: options) if let image = imageIcon { imageRecent = image diff --git a/Widget/Lockscreen/LockscreenData.swift b/Widget/Lockscreen/LockscreenData.swift index df05f282df..9e5a8c7c34 100644 --- a/Widget/Lockscreen/LockscreenData.swift +++ b/Widget/Lockscreen/LockscreenData.swift @@ -63,7 +63,7 @@ func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, fami } // NETWORKING - let password = CCUtility.getPassword(account.account)! + let password = NCKeychain().getPassword(account: account.account) NextcloudKit.shared.setup( account: account.account, user: account.user, @@ -82,7 +82,7 @@ func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, fami if userProfile.quotaRelative > 0 { quotaRelative = Float(userProfile.quotaRelative) / 100 } - let quotaUsed: String = CCUtility.transformedSize(userProfile.quotaUsed) + let quotaUsed: String = NCUtilityFileSystem.shared.transformedSize(userProfile.quotaUsed) var quotaTotal: String = "" switch userProfile.quotaTotal { @@ -93,7 +93,7 @@ func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, fami case -3: quotaTotal = "" default: - quotaTotal = CCUtility.transformedSize(userProfile.quotaTotal) + quotaTotal = NCUtilityFileSystem.shared.transformedSize(userProfile.quotaTotal) } completion(LockscreenData(date: Date(), isPlaceholder: false, activity: "", link: URL(string: "https://")!, quotaRelative: quotaRelative, quotaUsed: quotaUsed, quotaTotal: quotaTotal, error: false)) } else { diff --git a/iOSClient/Activity/NCActivity.swift b/iOSClient/Activity/NCActivity.swift index 97bea2299c..4fe57f8d91 100644 --- a/iOSClient/Activity/NCActivity.swift +++ b/iOSClient/Activity/NCActivity.swift @@ -39,9 +39,7 @@ class NCActivity: UIViewController, NCSharePagingContent { var metadata: tableMetadata? var showComments: Bool = false - // swiftlint:disable force_cast - private let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! var allItems: [DateCompareable] = [] var sectionDates: [Date] = [] @@ -252,7 +250,7 @@ extension NCActivity: UITableViewDataSource { if !activity.icon.isEmpty { let fileNameIcon = (activity.icon as NSString).lastPathComponent - let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + fileNameIcon + let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + fileNameIcon if FileManager.default.fileExists(atPath: fileNameLocalPath) { if let image = UIImage(contentsOfFile: fileNameLocalPath) { diff --git a/iOSClient/Activity/NCActivityCommentView.swift b/iOSClient/Activity/NCActivityCommentView.swift index 768006b135..054067a747 100644 --- a/iOSClient/Activity/NCActivityCommentView.swift +++ b/iOSClient/Activity/NCActivityCommentView.swift @@ -36,7 +36,7 @@ class NCActivityCommentView: UIView, UITextFieldDelegate { newCommentField.delegate = self let fileName = urlBase.userBaseUrl + "-" + urlBase.user + ".png" - let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName + let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName if let image = UIImage(contentsOfFile: fileNameLocalPath) { imageItem.image = image } else { diff --git a/iOSClient/Activity/NCActivityTableViewCell.swift b/iOSClient/Activity/NCActivityTableViewCell.swift index 410870aa35..2b0537151d 100644 --- a/iOSClient/Activity/NCActivityTableViewCell.swift +++ b/iOSClient/Activity/NCActivityTableViewCell.swift @@ -41,10 +41,6 @@ class NCActivityCollectionViewCell: UICollectionViewCell { class NCActivityTableViewCell: UITableViewCell, NCCellProtocol { - // swiftlint:disable force_cast - private let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var icon: UIImageView! @IBOutlet weak var avatar: UIImageView! @@ -52,6 +48,7 @@ class NCActivityTableViewCell: UITableViewCell, NCCellProtocol { @IBOutlet weak var subjectTrailingConstraint: NSLayoutConstraint! @IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint! + private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! private var user: String = "" private var index = IndexPath() @@ -190,7 +187,7 @@ extension NCActivityTableViewCell: UICollectionViewDataSource { if let activitySubjectRich = NCManageDatabase.shared.getActivitySubjectRich(account: activityPreview.account, idActivity: idActivity, id: fileId) { - let fileNamePath = CCUtility.getDirectoryUserData() + "/" + activitySubjectRich.name + let fileNamePath = NCUtilityFileSystem.shared.directoryUserData + "/" + activitySubjectRich.name if FileManager.default.fileExists(atPath: fileNamePath), let image = UIImage(contentsOfFile: fileNamePath) { cell.imageView.image = image diff --git a/iOSClient/AppDelegate.swift b/iOSClient/AppDelegate.swift index 63faeb543e..8ffb2df577 100644 --- a/iOSClient/AppDelegate.swift +++ b/iOSClient/AppDelegate.swift @@ -80,12 +80,13 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp()) UserDefaults.standard.register(defaults: ["UserAgent": userAgent]) - if !CCUtility.getDisableCrashservice() && !NCBrandOptions.shared.disable_crash_service { + if !NCKeychain().disableCrashservice, !NCBrandOptions.shared.disable_crash_service { FirebaseApp.configure() } - CCUtility.createDirectoryStandard() - CCUtility.emptyTemporaryDirectory() + NCUtilityFileSystem.shared.createDirectoryStandard() + NCUtilityFileSystem.shared.emptyTemporaryDirectory() + NCUtilityFileSystem.shared.clearCacheDirectory("com.limit-point.LivePhoto") // Activated singleton _ = NCActionCenter.shared @@ -97,18 +98,16 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD startTimerErrorNetworking() var levelLog = 0 - if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path { - NextcloudKit.shared.nkCommonInstance.pathLog = pathDirectoryGroup - } + NextcloudKit.shared.nkCommonInstance.pathLog = NCUtilityFileSystem.shared.directoryGroup if NCBrandOptions.shared.disable_log { - NCUtilityFileSystem.shared.deleteFile(filePath: NextcloudKit.shared.nkCommonInstance.filenamePathLog) - NCUtilityFileSystem.shared.deleteFile(filePath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/" + NextcloudKit.shared.nkCommonInstance.filenameLog) + NCUtilityFileSystem.shared.removeFile(atPath: NextcloudKit.shared.nkCommonInstance.filenamePathLog) + NCUtilityFileSystem.shared.removeFile(atPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/" + NextcloudKit.shared.nkCommonInstance.filenameLog) } else { - levelLog = CCUtility.getLogLevel() + levelLog = NCKeychain().logLevel NextcloudKit.shared.nkCommonInstance.levelLog = levelLog NextcloudKit.shared.nkCommonInstance.copyLogToDocumentDirectory = true NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start session with level \(levelLog) " + versionNextcloudiOS) @@ -116,7 +115,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD if let account = NCManageDatabase.shared.getActiveAccount() { NextcloudKit.shared.nkCommonInstance.writeLog("Account active \(account.account)") - if CCUtility.getPassword(account.account).isEmpty { + if NCKeychain().getPassword(account: account.account).isEmpty { NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] PASSWORD NOT FOUND for \(account.account)") } } @@ -127,18 +126,18 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD urlBase = activeAccount.urlBase user = activeAccount.user userId = activeAccount.userId - password = CCUtility.getPassword(account) + password = NCKeychain().getPassword(account: account) NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase) NCManageDatabase.shared.setCapabilities(account: account) NCBrandColor.shared.settingThemingColor(account: activeAccount.account) - DispatchQueue.global().async { NCMediaCache.shared.createCache(account: self.account) } + DispatchQueue.global().async { NCMediaCache.shared.createCache(account: activeAccount.account) } } else { - CCUtility.deleteAllChainStore() + NCKeychain().removeAll() if let bundleID = Bundle.main.bundleIdentifier { UserDefaults.standard.removePersistentDomain(forName: bundleID) } @@ -169,12 +168,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD // Intro if NCBrandOptions.shared.disable_intro { - CCUtility.setIntro(true) + NCKeychain().intro = true if account.isEmpty { openLogin(viewController: nil, selector: NCGlobal.shared.introLogin, openLoginWeb: false) } } else { - if !CCUtility.getIntro() { + if !NCKeychain().intro { if let viewController = UIStoryboard(name: "NCIntro", bundle: nil).instantiateInitialViewController() { let navigationController = NCLoginNavigationController(rootViewController: viewController) window?.rootViewController = navigationController @@ -228,7 +227,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD NCNetworkingProcessUpload.shared.invalidateObserveTableMetadata() NCNetworkingProcessUpload.shared.stopTimer() - if CCUtility.getPrivacyScreenEnabled() { + if NCKeychain().privacyScreenEnabled { showPrivacyProtectionWindow() } @@ -236,10 +235,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD WidgetCenter.shared.reloadAllTimelines() // Clear older files - let days = CCUtility.getCleanUpDay() - if let directory = CCUtility.getDirectoryProviderStorage() { - NCUtilityFileSystem.shared.cleanUp(directory: directory, days: TimeInterval(days)) - } + let days = NCKeychain().cleanUpDay + NCUtilityFileSystem.shared.cleanUp(directory: NCUtilityFileSystem.shared.directoryProviderStorage, days: TimeInterval(days)) NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationWillResignActive) } @@ -268,7 +265,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Create share accounts \(error.localizedDescription)") } - NCNetworking.shared.cancelSessions(inBackground: false) + NCNetworking.shared.cancel(inBackground: false) presentPasscode { } @@ -278,7 +275,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD // L'applicazione terminerà func applicationWillTerminate(_ application: UIApplication) { - NCNetworking.shared.cancelSessions(inBackground: false) + NCNetworking.shared.cancel(inBackground: false) if UIApplication.shared.backgroundRefreshStatus == .available { @@ -528,7 +525,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD } @objc private func checkErrorNetworking() { - guard !account.isEmpty, CCUtility.getPassword(account)!.isEmpty else { return } + guard !account.isEmpty, NCKeychain().getPassword(account: account).isEmpty else { return } openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: true) } @@ -540,7 +537,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD host == currentHost else { return } - let certificateHostSavedPath = CCUtility.getDirectoryCerificates()! + "/" + host + ".der" + let certificateHostSavedPath = NCUtilityFileSystem.shared.directoryCertificates + "/" + host + ".der" var title = NSLocalizedString("_ssl_certificate_changed_", comment: "") if !FileManager.default.fileExists(atPath: certificateHostSavedPath) { @@ -575,15 +572,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD @objc func changeAccount(_ account: String, userProfile: NKUserProfile?) { + NCNetworking.shared.cancel(inBackground: false) guard let tableAccount = NCManageDatabase.shared.setAccountActive(account) else { return } - NCNetworking.shared.cancelSessions(inBackground: false) - self.account = tableAccount.account self.urlBase = tableAccount.urlBase self.user = tableAccount.user self.userId = tableAccount.userId - self.password = CCUtility.getPassword(tableAccount.account) + self.password = NCKeychain().getPassword(account: tableAccount.account) NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase) NCManageDatabase.shared.setCapabilities(account: account) @@ -604,7 +600,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(items) uploads") } - DispatchQueue.global().async { NCMediaCache.shared.createCache(account: account) } + DispatchQueue.global().async { NCMediaCache.shared.createCache(account: self.account) } NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeUser) } @@ -617,13 +613,13 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD let results = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@", account), sorted: "ocId", ascending: false) for result in results { - CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(result.ocId)) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(result.ocId)) } NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true) - CCUtility.clearAllKeysEnd(toEnd: account) - CCUtility.clearAllKeysPushNotification(account) - CCUtility.setPassword(account, password: nil) + NCKeychain().clearAllKeysEndToEnd(account: account) + NCKeychain().clearAllKeysPushNotification(account: account) + NCKeychain().setPassword(account: account, password: nil) self.account = "" self.urlBase = "" @@ -659,7 +655,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD let name = account.alias.isEmpty ? account.displayName : account.alias let userBaseUrl = account.user + "-" + (URL(string: account.urlBase)?.host ?? "") let avatarFileName = userBaseUrl + "-\(account.user).png" - let pathAvatarFileName = String(CCUtility.getDirectoryUserData()) + "/" + avatarFileName + let pathAvatarFileName = NCUtilityFileSystem.shared.directoryUserData + "/" + avatarFileName let image = UIImage(contentsOfFile: pathAvatarFileName) accounts.append(NKShareAccounts.DataAccounts(withUrl: account.urlBase, user: account.user, name: name, image: image)) } @@ -675,7 +671,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD func requestAccount() { if isPasscodePresented() { return } - if !CCUtility.getAccountRequest() { return } + if !NCKeychain().accountRequest { return } let accounts = NCManageDatabase.shared.getAllAccount() @@ -714,7 +710,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD defer { self.requestAccount() } let presentedViewController = window?.rootViewController?.presentedViewController - guard !account.isEmpty, CCUtility.isPasscodeAtStartEnabled(), !(presentedViewController is NCLoginNavigationController) else { return } + guard !account.isEmpty, NCKeychain().passcode != nil, NCKeychain().requestPasscodeAtStart, !(presentedViewController is NCLoginNavigationController) else { return } // Make sure we have a privacy window (in case it's not enabled) showPrivacyProtectionWindow() @@ -722,7 +718,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD let passcodeViewController = TOPasscodeViewController(passcodeType: .sixDigits, allowCancel: false) passcodeViewController.delegate = self passcodeViewController.keypadButtonShowLettering = false - if CCUtility.getEnableTouchFaceID() && laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { + if NCKeychain().touchFaceID, laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { if error == nil { if laContext.biometryType == .faceID { passcodeViewController.biometryType = .faceID @@ -746,8 +742,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD func enableTouchFaceID() { guard !account.isEmpty, - CCUtility.getEnableTouchFaceID(), - CCUtility.isPasscodeAtStartEnabled(), + NCKeychain().touchFaceID, + NCKeychain().passcode != nil, + NCKeychain().requestPasscodeAtStart, let passcodeViewController = privacyProtectionWindow?.rootViewController?.presentedViewController as? TOPasscodeViewController else { return } @@ -775,7 +772,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD } func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool { - return code == CCUtility.getPasscode() + return code == NCKeychain().passcode } func didPerformBiometricValidationRequest(in passcodeViewController: TOPasscodeViewController) { @@ -840,8 +837,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD var serverUrl: String = "" /* - Example: - nextcloud://open-action?action=create-voice-memo&&user=marinofaggiana&url=https://cloud.nextcloud.com + Example: nextcloud://open-action?action=create-voice-memo&&user=marinofaggiana&url=https://cloud.nextcloud.com */ if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-action" { @@ -849,16 +845,16 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) { let queryItems = urlComponents.queryItems - guard let actionScheme = CCUtility.value(forKey: "action", fromQueryItems: queryItems), let rootViewController = window?.rootViewController else { return false } - guard let userScheme = CCUtility.value(forKey: "user", fromQueryItems: queryItems) else { return false } - guard let urlScheme = CCUtility.value(forKey: "url", fromQueryItems: queryItems) else { return false } + guard let actionScheme = queryItems?.filter({ $0.name == "action" }).first?.value, + let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value, + let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value, + let rootViewController = window?.rootViewController else { return false } if getMatchedAccount(userId: userScheme, url: urlScheme) == nil { let message = NSLocalizedString("_the_account_", comment: "") + " " + userScheme + NSLocalizedString("_of_", comment: "") + " " + urlScheme + " " + NSLocalizedString("_does_not_exist_", comment: "") let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in })) window?.rootViewController?.present(alertController, animated: true, completion: { }) - return false } @@ -896,7 +892,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD NCAskAuthorization.shared.askAuthorizationAudioRecord(viewController: rootViewController) { hasPermission in if hasPermission { - let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")! + let fileName = NCUtilityFileSystem.shared.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), ext: "m4a") if let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as? NCAudioRecorderViewController { viewController.delegate = self @@ -917,8 +913,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD } /* - Example: - nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123 + Example: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123 */ else if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-file" { @@ -926,19 +921,18 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) { let queryItems = urlComponents.queryItems - guard let userScheme = CCUtility.value(forKey: "user", fromQueryItems: queryItems) else { return false } - guard let pathScheme = CCUtility.value(forKey: "path", fromQueryItems: queryItems) else { return false } - guard let linkScheme = CCUtility.value(forKey: "link", fromQueryItems: queryItems) else { return false } + 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 false} + guard let matchedAccount = getMatchedAccount(userId: userScheme, url: linkScheme) else { guard let domain = URL(string: linkScheme)?.host else { return true } fileName = (pathScheme as NSString).lastPathComponent let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain, fileName) - let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in })) window?.rootViewController?.present(alertController, animated: true, completion: { }) - return false } @@ -958,22 +952,18 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD return true /* - Example: - nextcloud://open-and-switch-account?user=marinofaggiana&url=https://cloud.nextcloud.com + Example: nextcloud://open-and-switch-account?user=marinofaggiana&url=https://cloud.nextcloud.com */ } else if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-and-switch-account" { guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false } let queryItems = urlComponents.queryItems - - guard let userScheme = CCUtility.value(forKey: "user", fromQueryItems: queryItems) else { return false } - guard let urlScheme = CCUtility.value(forKey: "url", fromQueryItems: queryItems) else { return false } - + guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value, + let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value else { return false} // If the account doesn't exist, return false which will open the app without switching if getMatchedAccount(userId: userScheme, url: urlScheme) == nil { return false } - // Otherwise open the app and switch accounts return true } else { diff --git a/iOSClient/Data/NCManageDatabase+Account.swift b/iOSClient/Data/NCManageDatabase+Account.swift index abfa7f1450..10b3b850dc 100644 --- a/iOSClient/Data/NCManageDatabase+Account.swift +++ b/iOSClient/Data/NCManageDatabase+Account.swift @@ -106,7 +106,7 @@ extension NCManageDatabase { addObject.autoUploadWWAnVideo = true } - CCUtility.setPassword(account, password: password) + NCKeychain().setPassword(account: account, password: password) addObject.urlBase = urlBase addObject.user = user @@ -263,8 +263,7 @@ extension NCManageDatabase { let cameraFileName = self.getAccountAutoUploadFileName() let cameraDirectory = self.getAccountAutoUploadDirectory(urlBase: urlBase, userId: userId, account: account) - - let folderPhotos = CCUtility.stringAppendServerUrl(cameraDirectory, addFileName: cameraFileName)! + let folderPhotos = NCUtilityFileSystem.shared.stringAppendServerUrl(cameraDirectory, addFileName: cameraFileName) return folderPhotos } diff --git a/iOSClient/Data/NCManageDatabase+Avatar.swift b/iOSClient/Data/NCManageDatabase+Avatar.swift index 6d6ce1cf9e..d3b2e2536d 100644 --- a/iOSClient/Data/NCManageDatabase+Avatar.swift +++ b/iOSClient/Data/NCManageDatabase+Avatar.swift @@ -89,7 +89,7 @@ extension NCManageDatabase { @discardableResult func setAvatarLoaded(fileName: String) -> UIImage? { - let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName + let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName var image: UIImage? do { @@ -113,14 +113,14 @@ extension NCManageDatabase { func getImageAvatarLoaded(fileName: String) -> UIImage? { - let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName + let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName do { let realm = try Realm() realm.refresh() let result = realm.objects(tableAvatar.self).filter("fileName == %@", fileName).first if result == nil { - NCUtilityFileSystem.shared.deleteFile(filePath: fileNameLocalPath) + NCUtilityFileSystem.shared.removeFile(atPath: fileNameLocalPath) return nil } else if result?.loaded == false { return nil @@ -130,7 +130,7 @@ extension NCManageDatabase { NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)") } - NCUtilityFileSystem.shared.deleteFile(filePath: fileNameLocalPath) + NCUtilityFileSystem.shared.removeFile(atPath: fileNameLocalPath) return nil } } diff --git a/iOSClient/Data/NCManageDatabase+Chunk.swift b/iOSClient/Data/NCManageDatabase+Chunk.swift index bc2bad06f3..72e216c32b 100644 --- a/iOSClient/Data/NCManageDatabase+Chunk.swift +++ b/iOSClient/Data/NCManageDatabase+Chunk.swift @@ -100,7 +100,7 @@ extension NCManageDatabase { let result = realm.objects(tableChunk.self).filter(NSPredicate(format: "account == %@ AND ocId == %@ AND fileName == %d", account, ocId, Int(fileChunk.fileName) ?? 0)) realm.delete(result) let filePath = directory + "/\(fileChunk.fileName)" - NCUtilityFileSystem.shared.deleteFile(filePath: filePath) + NCUtilityFileSystem.shared.removeFile(atPath: filePath) } } catch let error { NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)") @@ -115,7 +115,7 @@ extension NCManageDatabase { let results = realm.objects(tableChunk.self).filter(NSPredicate(format: "account == %@ AND ocId == %@", account, ocId)) for result in results { let filePath = directory + "/\(result.fileName)" - NCUtilityFileSystem.shared.deleteFile(filePath: filePath) + NCUtilityFileSystem.shared.removeFile(atPath: filePath) } realm.delete(results) } diff --git a/iOSClient/Data/NCManageDatabase+Metadata.swift b/iOSClient/Data/NCManageDatabase+Metadata.swift index 340550c53f..a520a27795 100644 --- a/iOSClient/Data/NCManageDatabase+Metadata.swift +++ b/iOSClient/Data/NCManageDatabase+Metadata.swift @@ -202,11 +202,11 @@ extension tableMetadata { } var isDirectoySettableE2EE: Bool { - return directory && size == 0 && !e2eEncrypted && CCUtility.isEnd(toEndEnabled: account) + return directory && size == 0 && !e2eEncrypted && NCKeychain().isEndToEndEnabled(account: account) } var isDirectoryUnsettableE2EE: Bool { - return !isDirectoryE2EE && directory && size == 0 && e2eEncrypted && CCUtility.isEnd(toEndEnabled: account) + return !isDirectoryE2EE && directory && size == 0 && e2eEncrypted && NCKeychain().isEndToEndEnabled(account: account) } var canOpenExternalEditor: Bool { @@ -1057,7 +1057,7 @@ extension NCManageDatabase { var classFile = metadata.classFile var fileName = (metadata.fileNameView as NSString).deletingPathExtension - if !metadata.livePhoto || !CCUtility.getLivePhoto() { + if !metadata.livePhoto || !NCKeychain().livePhoto { return nil } @@ -1148,7 +1148,7 @@ extension NCManageDatabase { func isDownloadMetadata(_ metadata: tableMetadata, download: Bool) -> Bool { let localFile = getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) - let fileSize = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView) + let fileSize = NCUtilityFileSystem.shared.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView) if (localFile != nil || download) && (localFile?.etag != metadata.etag || fileSize == 0) { return true } @@ -1162,7 +1162,7 @@ extension NCManageDatabase { let fileNameNoExtension = (fileNameView as NSString).deletingPathExtension var fileNameConflict = fileNameView - if fileNameExtension == "heic" && CCUtility.getFormatCompatibility() { + if fileNameExtension == "heic", NCKeychain().formatCompatibility { fileNameConflict = fileNameNoExtension + ".jpg" } return getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account, serverUrl, fileNameConflict)) @@ -1250,21 +1250,4 @@ extension NCManageDatabase { NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)") } } - - func getMediaOcIdEtag(account: String) -> [String: String] { - - let predicate = NSPredicate(format: "account == %@ AND (classFile == %@ OR classFile == %@)", account, NKCommon.TypeClassFile.image.rawValue, NKCommon.TypeClassFile.video.rawValue) - var results: [String: String] = [:] - - do { - let realm = try Realm() - for result in realm.objects(tableMetadata.self).filter(predicate) { - results[result.ocId] = result.etag - } - } catch let error { - NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)") - } - - return results - } } diff --git a/iOSClient/Extensions/PHAsset+Extension.swift b/iOSClient/Extensions/PHAsset+Extension.swift index c2031dc57e..cefb6b0080 100644 --- a/iOSClient/Extensions/PHAsset+Extension.swift +++ b/iOSClient/Extensions/PHAsset+Extension.swift @@ -30,7 +30,7 @@ extension PHAsset { return resource.originalFilename as NSString } else { return self.value(forKey: "filename") as? NSString - ?? ("IMG_" + CCUtility.getIncrementalNumber() + getExtension()) as NSString + ?? ("IMG_" + NCKeychain().incrementalNumber + getExtension()) as NSString } } diff --git a/iOSClient/Extensions/UIAlertController+Extension.swift b/iOSClient/Extensions/UIAlertController+Extension.swift index 55cdcf96c2..cae04e82f2 100644 --- a/iOSClient/Extensions/UIAlertController+Extension.swift +++ b/iOSClient/Extensions/UIAlertController+Extension.swift @@ -73,8 +73,8 @@ extension UIAlertController { forName: UITextField.textDidChangeNotification, object: alertController.textFields?.first, queue: .main) { _ in - guard let text = alertController.textFields?.first?.text, - let folderName = CCUtility.removeForbiddenCharactersServer(text)?.trimmingCharacters(in: .whitespaces) else { return } + guard let text = alertController.textFields?.first?.text else { return } + let folderName = NCUtility.shared.removeForbiddenCharacters(text).trimmingCharacters(in: .whitespaces) okAction.isEnabled = !folderName.isEmpty && folderName != "." && folderName != ".." } diff --git a/iOSClient/Extensions/UIImage+Extension.swift b/iOSClient/Extensions/UIImage+Extension.swift index 23d4b4e259..80ca865c3c 100644 --- a/iOSClient/Extensions/UIImage+Extension.swift +++ b/iOSClient/Extensions/UIImage+Extension.swift @@ -232,4 +232,35 @@ extension UIImage { } return image } + + var heic: Data? { heic() } + var cgImageOrientation: CGImagePropertyOrientation { .init(imageOrientation) } + + func heic(compressionQuality: CGFloat = 1) -> Data? { + guard + let mutableData = CFDataCreateMutable(nil, 0), + let destination = CGImageDestinationCreateWithData(mutableData, "public.heic" as CFString, 1, nil), + let cgImage = cgImage + else { return nil } + CGImageDestinationAddImage(destination, cgImage, [kCGImageDestinationLossyCompressionQuality: compressionQuality, kCGImagePropertyOrientation: cgImageOrientation.rawValue] as CFDictionary) + guard CGImageDestinationFinalize(destination) else { return nil } + return mutableData as Data + } +} + +extension CGImagePropertyOrientation { + init(_ uiOrientation: UIImage.Orientation) { + switch uiOrientation { + case .up: self = .up + case .upMirrored: self = .upMirrored + case .down: self = .down + case .downMirrored: self = .downMirrored + case .left: self = .left + case .leftMirrored: self = .leftMirrored + case .right: self = .right + case .rightMirrored: self = .rightMirrored + @unknown default: + fatalError() + } + } } diff --git a/iOSClient/Favorites/NCFavorite.swift b/iOSClient/Favorites/NCFavorite.swift index d3abf80c6d..56021de211 100644 --- a/iOSClient/Favorites/NCFavorite.swift +++ b/iOSClient/Favorites/NCFavorite.swift @@ -91,7 +91,7 @@ class NCFavorite: NCCollectionViewCommon { isReloadDataSourceNetworkInProgress = true collectionView?.reloadData() - NextcloudKit.shared.listingFavorites(showHiddenFiles: CCUtility.getShowHiddenFiles(), + NextcloudKit.shared.listingFavorites(showHiddenFiles: NCKeychain().showHiddenFiles, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, files, _, error in self.isReloadDataSourceNetworkInProgress = false diff --git a/iOSClient/Groupfolders/NCGroupfolders.swift b/iOSClient/Groupfolders/NCGroupfolders.swift index 71cd4f9d9c..e8fa0053cb 100644 --- a/iOSClient/Groupfolders/NCGroupfolders.swift +++ b/iOSClient/Groupfolders/NCGroupfolders.swift @@ -102,7 +102,7 @@ class NCGroupfolders: NCCollectionViewCommon { let mountPoint = groupfolder.mountPoint.hasPrefix("/") ? groupfolder.mountPoint : "/" + groupfolder.mountPoint let serverUrlFileName = homeServerUrl + mountPoint if NCManageDatabase.shared.getMetadataFromDirectory(account: self.appDelegate.account, serverUrl: serverUrlFileName) == nil { - let results = await NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) + let results = await NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: NCKeychain().showHiddenFiles) if results.error == .success, let file = results.files.first { let isDirectoryE2EE = NCUtility.shared.isDirectoryE2EE(file: file) let metadata = NCManageDatabase.shared.convertFileToMetadata(file, isDirectoryE2EE: isDirectoryE2EE) diff --git a/iOSClient/Login/NCLogin.swift b/iOSClient/Login/NCLogin.swift index 4e8822568f..22c1e98ed0 100644 --- a/iOSClient/Login/NCLogin.swift +++ b/iOSClient/Login/NCLogin.swift @@ -36,10 +36,7 @@ class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate { @IBOutlet weak var qrCode: UIButton! @IBOutlet weak var certificate: UIButton! - // swiftlint:disable force_cast - private let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! private var textColor: UIColor = .white private var textColorOpponent: UIColor = .black private var activeTextfieldDiff: CGFloat = 0 @@ -407,10 +404,10 @@ class NCLogin: UIViewController, UITextFieldDelegate, NCLoginQRCodeDelegate { self.appDelegate.changeAccount(account, userProfile: userProfile) - if CCUtility.getIntro() { + if NCKeychain().intro { self.dismiss(animated: true) } else { - CCUtility.setIntro(true) + NCKeychain().intro = true if self.presentingViewController == nil { let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() viewController?.modalPresentationStyle = .fullScreen diff --git a/iOSClient/Login/NCLoginWeb.swift b/iOSClient/Login/NCLoginWeb.swift index 6d98d3e3cf..07cd75ac23 100644 --- a/iOSClient/Login/NCLoginWeb.swift +++ b/iOSClient/Login/NCLoginWeb.swift @@ -30,9 +30,7 @@ class NCLoginWeb: UIViewController { var webView: WKWebView? - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! var titleView: String = "" @@ -131,7 +129,7 @@ class NCLoginWeb: UIViewController { // TITLE if let host = URL(string: urlBase)?.host { titleView = host - if let account = NCManageDatabase.shared.getActiveAccount(), CCUtility.getPassword(account.account).isEmpty { + if let account = NCManageDatabase.shared.getActiveAccount(), NCKeychain().getPassword(account: account.account).isEmpty { titleView = NSLocalizedString("_user_", comment: "") + " " + account.userId + " " + NSLocalizedString("_in_", comment: "") + " " + host } } @@ -144,7 +142,7 @@ class NCLoginWeb: UIViewController { // Stop timer error network appDelegate.timerErrorNetworking?.invalidate() - if let account = NCManageDatabase.shared.getActiveAccount(), CCUtility.getPassword(account.account).isEmpty { + if let account = NCManageDatabase.shared.getActiveAccount(), NCKeychain().getPassword(account: account.account).isEmpty { let message = "\n" + NSLocalizedString("_password_not_present_", comment: "") let alertController = UIAlertController(title: titleView, message: message, preferredStyle: .alert) @@ -303,10 +301,10 @@ extension NCLoginWeb: WKNavigationDelegate { self.appDelegate.changeAccount(account, userProfile: userProfile) - if CCUtility.getIntro() { + if NCKeychain().intro { self.dismiss(animated: true) } else { - CCUtility.setIntro(true) + NCKeychain().intro = true if self.presentingViewController == nil { if let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() { viewController.modalPresentationStyle = .fullScreen diff --git a/iOSClient/Login/NCViewCertificateDetails.swift b/iOSClient/Login/NCViewCertificateDetails.swift index bf9befd44c..07dca1b5f3 100644 --- a/iOSClient/Login/NCViewCertificateDetails.swift +++ b/iOSClient/Login/NCViewCertificateDetails.swift @@ -53,7 +53,7 @@ class NCViewCertificateDetails: UIViewController { buttonCancel.title = NSLocalizedString("_close_", comment: "") if fileNamePath.isEmpty { - fileNamePath = CCUtility.getDirectoryCerificates()! + "/" + host + ".txt" + fileNamePath = NCUtilityFileSystem.shared.directoryCertificates + "/" + host + ".txt" } if FileManager.default.fileExists(atPath: fileNamePath) { diff --git a/iOSClient/Main/Collection Common/NCCollectionViewCommon.swift b/iOSClient/Main/Collection Common/NCCollectionViewCommon.swift index 1657a774b8..a637994edb 100644 --- a/iOSClient/Main/Collection Common/NCCollectionViewCommon.swift +++ b/iOSClient/Main/Collection Common/NCCollectionViewCommon.swift @@ -32,10 +32,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS @IBOutlet weak var collectionView: UICollectionView! - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + internal let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! internal let refreshControl = UIRefreshControl() internal var searchController: UISearchController? internal var emptyDataSet: NCEmptyDataSet? @@ -542,12 +539,12 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS cell.fileProgressView?.progress = progressNumber.floatValue cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop) if status == NCGlobal.shared.metadataStatusInDownload { - cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes) + cell.fileInfoLabel?.text = NCUtilityFileSystem.shared.transformedSize(totalBytesExpected) + " - ↓ " + NCUtilityFileSystem.shared.transformedSize(totalBytes) } else if status == NCGlobal.shared.metadataStatusInUpload { if totalBytes > 0 { - cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes) + cell.fileInfoLabel?.text = NCUtilityFileSystem.shared.transformedSize(totalBytesExpected) + " - ↑ " + NCUtilityFileSystem.shared.transformedSize(totalBytes) } else { - cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ …" + cell.fileInfoLabel?.text = NCUtilityFileSystem.shared.transformedSize(totalBytesExpected) + " - ↑ …" } } } @@ -1015,8 +1012,8 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS self.metadataFolder = metadataFolder // E2EE if let metadataFolder = metadataFolder, - metadataFolder.e2eEncrypted, - CCUtility.isEnd(toEndEnabled: self.appDelegate.account), + metadataFolder.e2eEncrypted, + NCKeychain().isEndToEndEnabled(account: self.appDelegate.account), !NCNetworkingE2EE.shared.isInUpload(account: self.appDelegate.account, serverUrl: self.serverUrl) { let lock = NCManageDatabase.shared.getE2ETokenLock(account: self.appDelegate.account, serverUrl: self.serverUrl) NextcloudKit.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: lock?.e2eToken) { _, e2eMetadata, signature, _, error in @@ -1055,7 +1052,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS func pushMetadata(_ metadata: tableMetadata) { - guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return } + let serverUrlPush = NCUtilityFileSystem.shared.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) appDelegate.activeMetadata = metadata if let viewController = appDelegate.listFilesVC[serverUrlPush], viewController.isViewLoaded { @@ -1108,7 +1105,7 @@ extension NCCollectionViewCommon: UICollectionViewDelegate { if metadata.e2eEncrypted { if NCGlobal.shared.capabilityE2EEEnabled { - if !CCUtility.isEnd(toEndEnabled: appDelegate.account) { + if !NCKeychain().isEndToEndEnabled(account: appDelegate.account) { let e2ee = NCEndToEndInitialize() e2ee.delegate = self e2ee.initEndToEndEncryption() @@ -1126,7 +1123,7 @@ extension NCCollectionViewCommon: UICollectionViewDelegate { } else { - let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) + let imageIcon = UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) if !metadata.isDirectoryE2EE && (metadata.isImage || metadata.isAudioOrVideo) { var metadatas: [tableMetadata] = [] @@ -1139,7 +1136,7 @@ extension NCCollectionViewCommon: UICollectionViewDelegate { return } - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon) } else if NextcloudKit.shared.isNetworkReachable() { NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileView) { _, _ in } @@ -1207,9 +1204,9 @@ extension NCCollectionViewCommon: UICollectionViewDataSource { } else { (cell as? NCCellProtocol)?.filePreviewImageView?.image = UIImage(named: metadata.iconName) } - if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) { + if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!NCUtilityFileSystem.shared.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) { for case let operation as NCCollectionViewDownloadThumbnail in appDelegate.downloadThumbnailQueue.operations where operation.metadata.ocId == metadata.ocId { return } - appDelegate.downloadThumbnailQueue.addOperation(NCCollectionViewDownloadThumbnail(metadata: metadata, cell: (cell as? NCCellProtocol), view: view)) + appDelegate.downloadThumbnailQueue.addOperation(NCCollectionViewDownloadThumbnail(metadata: metadata, cell: (cell as? NCCellProtocol), collectionView: collectionView)) } } } else { @@ -1236,7 +1233,7 @@ extension NCCollectionViewCommon: UICollectionViewDataSource { } if !metadata.iconUrl.isEmpty { - if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata), let cell = cell as? NCCellProtocol { + if let ownerId = getAvatarFromIconUrl(metadata: metadata), let cell = cell as? NCCellProtocol { let fileName = metadata.userBaseUrl + "-" + ownerId + ".png" NCNetworking.shared.downloadAvatar(user: ownerId, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView) } @@ -1385,7 +1382,7 @@ extension NCCollectionViewCommon: UICollectionViewDataSource { if NCManageDatabase.shared.getTableLocalFile(ocId: metadata.ocId) != nil { a11yValues.append(NSLocalizedString("_offline_", comment: "")) cell.fileLocalImage?.image = NCBrandColor.cacheImages.offlineFlag - } else if CCUtility.fileProviderStorageExists(metadata) { + } else if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { cell.fileLocalImage?.image = NCBrandColor.cacheImages.local } } @@ -1423,19 +1420,19 @@ extension NCCollectionViewCommon: UICollectionViewDataSource { // Write status on Label Info switch metadata.status { case NCGlobal.shared.metadataStatusWaitDownload: - cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "") + cell.fileInfoLabel?.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "") case NCGlobal.shared.metadataStatusInDownload: - cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "") + cell.fileInfoLabel?.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "") case NCGlobal.shared.metadataStatusDownloading: - cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - ↓ …" + cell.fileInfoLabel?.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) + " - ↓ …" case NCGlobal.shared.metadataStatusWaitUpload: - cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "") + cell.fileInfoLabel?.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "") cell.fileLocalImage?.image = nil case NCGlobal.shared.metadataStatusInUpload: - cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "") + cell.fileInfoLabel?.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "") cell.fileLocalImage?.image = nil case NCGlobal.shared.metadataStatusUploading: - cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - ↑ …" + cell.fileInfoLabel?.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) + " - ↑ …" cell.fileLocalImage?.image = nil case NCGlobal.shared.metadataStatusUploadError: if metadata.sessionError.isEmpty { @@ -1458,7 +1455,7 @@ extension NCCollectionViewCommon: UICollectionViewDataSource { cell.fileLocalImage?.image = nil cell.hideButtonShare(true) cell.hideButtonMore(true) - if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata) { + if let ownerId = getAvatarFromIconUrl(metadata: metadata) { cell.fileUser = ownerId } } @@ -1706,6 +1703,26 @@ extension NCCollectionViewCommon: EasyTipViewDelegate { } } +extension NCCollectionViewCommon { + + func getAvatarFromIconUrl(metadata: tableMetadata) -> String? { + + var ownerId: String? + if metadata.iconUrl.contains("http") && metadata.iconUrl.contains("avatar") { + let splitIconUrl = metadata.iconUrl.components(separatedBy: "/") + var found: Bool = false + for item in splitIconUrl { + if found { + ownerId = item + break + } + if item == "avatar" { found = true} + } + } + return ownerId + } +} + // MARK: - class NCOperationUnifiedSearch: ConcurrentOperation { @@ -1745,18 +1762,18 @@ class NCCollectionViewDownloadThumbnail: ConcurrentOperation { var metadata: tableMetadata var cell: NCCellProtocol? - var view: UIView? + var collectionView: UICollectionView? var fileNamePath: String var fileNamePreviewLocalPath: String var fileNameIconLocalPath: String - init(metadata: tableMetadata, cell: NCCellProtocol?, view: UIView?) { + init(metadata: tableMetadata, cell: NCCellProtocol?, collectionView: UICollectionView?) { self.metadata = tableMetadata.init(value: metadata) self.cell = cell - self.view = view - self.fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)! - self.fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)! - self.fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)! + self.collectionView = collectionView + self.fileNamePath = NCUtilityFileSystem.shared.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId) + self.fileNamePreviewLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag) + self.fileNameIconLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag) } override func start() { @@ -1786,6 +1803,8 @@ class NCCollectionViewDownloadThumbnail: ConcurrentOperation { options: .transitionCrossDissolve, animations: { filePreviewImageView.image = image }, completion: nil) + } else { + self.collectionView?.reloadData() } } } diff --git a/iOSClient/Main/Collection Common/NCGridCell.swift b/iOSClient/Main/Collection Common/NCGridCell.swift index d7f72b8724..5a25b29fb1 100644 --- a/iOSClient/Main/Collection Common/NCGridCell.swift +++ b/iOSClient/Main/Collection Common/NCGridCell.swift @@ -209,7 +209,7 @@ class NCGridCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto dateFormatter.timeStyle = .none dateFormatter.locale = Locale.current - labelInfo.text = dateFormatter.string(from: date as Date) + " · " + CCUtility.transformedSize(size) + labelInfo.text = dateFormatter.string(from: date as Date) + " · " + NCUtilityFileSystem.shared.transformedSize(size) } func setAccessibility(label: String, value: String) { diff --git a/iOSClient/Main/Collection Common/NCListCell.swift b/iOSClient/Main/Collection Common/NCListCell.swift index af829f1959..93ef81e361 100755 --- a/iOSClient/Main/Collection Common/NCListCell.swift +++ b/iOSClient/Main/Collection Common/NCListCell.swift @@ -271,7 +271,7 @@ class NCListCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProto } func writeInfoDateSize(date: NSDate, size: Int64) { - labelInfo.text = CCUtility.dateDiff(date as Date) + " · " + CCUtility.transformedSize(size) + labelInfo.text = CCUtility.dateDiff(date as Date) + " · " + NCUtilityFileSystem.shared.transformedSize(size) } func setAccessibility(label: String, value: String) { diff --git a/iOSClient/Main/Create cloud/NCCreateFormUploadConflict.swift b/iOSClient/Main/Create cloud/NCCreateFormUploadConflict.swift index 0a847c421f..37b9ae6908 100644 --- a/iOSClient/Main/Create cloud/NCCreateFormUploadConflict.swift +++ b/iOSClient/Main/Create cloud/NCCreateFormUploadConflict.swift @@ -245,10 +245,10 @@ class NCCreateFormUploadConflict: UIViewController { var fileName = metadata.fileNameView let fileNameExtension = (fileName as NSString).pathExtension.lowercased() let fileNameNoExtension = (fileName as NSString).deletingPathExtension - if fileNameExtension == "heic" && CCUtility.getFormatCompatibility() { + if fileNameExtension == "heic" && NCKeychain().formatCompatibility { fileName = fileNameNoExtension + ".jpg" } - let oldPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) + let oldPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) let newFileName = NCUtilityFileSystem.shared.createFileName(fileName, serverUrl: metadata.serverUrl, account: metadata.account) metadata.ocId = UUID().uuidString @@ -257,8 +257,8 @@ class NCCreateFormUploadConflict: UIViewController { // This is not an asset - [file] if metadata.assetLocalIdentifier.isEmpty || metadata.isExtractFile { - let newPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: newFileName) - CCUtility.moveFile(atPath: oldPath, toPath: newPath) + let newPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: newFileName) + NCUtilityFileSystem.shared.moveFile(atPath: oldPath, toPath: newPath) } metadatasNOConflict.append(metadata) @@ -323,11 +323,11 @@ extension NCCreateFormUploadConflict: UITableViewDataSource { // -----> Already Existing File guard let metadataAlreadyExists = NCManageDatabase.shared.getMetadataConflict(account: metadataNewFile.account, serverUrl: metadataNewFile.serverUrl, fileNameView: metadataNewFile.fileNameView) else { return UITableViewCell() } - if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadataAlreadyExists.ocId, etag: metadataAlreadyExists.etag)) { - cell.imageAlreadyExistingFile.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadataAlreadyExists.ocId, etag: metadataAlreadyExists.etag)) - } else if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageOcId(metadataAlreadyExists.ocId, fileNameView: metadataAlreadyExists.fileNameView)) && metadataAlreadyExists.contentType == "application/pdf" { + if FileManager().fileExists(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadataAlreadyExists.ocId, etag: metadataAlreadyExists.etag)) { + cell.imageAlreadyExistingFile.image = UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadataAlreadyExists.ocId, etag: metadataAlreadyExists.etag)) + } else if FileManager().fileExists(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadataAlreadyExists.ocId, fileNameView: metadataAlreadyExists.fileNameView)) && metadataAlreadyExists.contentType == "application/pdf" { - let url = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataAlreadyExists.ocId, fileNameView: metadataAlreadyExists.fileNameView)) + let url = URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadataAlreadyExists.ocId, fileNameView: metadataAlreadyExists.fileNameView)) if let image = NCUtility.shared.pdfThumbnail(url: url) { cell.imageAlreadyExistingFile.image = image } else { @@ -341,7 +341,7 @@ extension NCCreateFormUploadConflict: UITableViewDataSource { cell.imageAlreadyExistingFile.image = UIImage(named: metadataAlreadyExists.iconName) } } - cell.labelDetailAlreadyExistingFile.text = CCUtility.dateDiff(metadataAlreadyExists.date as Date) + "\n" + CCUtility.transformedSize(metadataAlreadyExists.size) + cell.labelDetailAlreadyExistingFile.text = CCUtility.dateDiff(metadataAlreadyExists.date as Date) + "\n" + NCUtilityFileSystem.shared.transformedSize(metadataAlreadyExists.size) if metadatasConflictAlreadyExistingFiles.contains(metadataNewFile.ocId) { cell.switchAlreadyExistingFile.isOn = true @@ -356,7 +356,7 @@ extension NCCreateFormUploadConflict: UITableViewDataSource { } else { cell.imageNewFile.image = UIImage(named: metadataNewFile.iconName) } - let filePathNewFile = CCUtility.getDirectoryProviderStorageOcId(metadataNewFile.ocId, fileNameView: metadataNewFile.fileNameView)! + let filePathNewFile = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadataNewFile.ocId, fileNameView: metadataNewFile.fileNameView) if !metadataNewFile.assetLocalIdentifier.isEmpty { let result = PHAsset.fetchAssets(withLocalIdentifiers: [metadataNewFile.assetLocalIdentifier], options: nil) @@ -380,7 +380,7 @@ extension NCCreateFormUploadConflict: UITableViewDataSource { let fileDictionary = try FileManager.default.attributesOfItem(atPath: fileNamePath) let fileSize = fileDictionary[FileAttributeKey.size] as? Int64 ?? 0 - cell.labelDetailNewFile.text = CCUtility.dateDiff(date) + "\n" + CCUtility.transformedSize(fileSize) + cell.labelDetailNewFile.text = CCUtility.dateDiff(date) + "\n" + NCUtilityFileSystem.shared.transformedSize(fileSize) } catch { print("Error: \(error)") } @@ -404,7 +404,7 @@ extension NCCreateFormUploadConflict: UITableViewDataSource { DispatchQueue.main.async { cell.imageNewFile.image = image } } } - DispatchQueue.main.async { cell.labelDetailNewFile.text = CCUtility.dateDiff(date) + "\n" + CCUtility.transformedSize(fileSize) } + DispatchQueue.main.async { cell.labelDetailNewFile.text = CCUtility.dateDiff(date) + "\n" + NCUtilityFileSystem.shared.transformedSize(fileSize) } } catch { print("Error: \(error)") } } } @@ -423,7 +423,7 @@ extension NCCreateFormUploadConflict: UITableViewDataSource { let fileDictionary = try FileManager.default.attributesOfItem(atPath: filePathNewFile) let fileSize = fileDictionary[FileAttributeKey.size] as? Int64 ?? 0 - cell.labelDetailNewFile.text = CCUtility.dateDiff(metadataNewFile.date as Date) + "\n" + CCUtility.transformedSize(fileSize) + cell.labelDetailNewFile.text = CCUtility.dateDiff(metadataNewFile.date as Date) + "\n" + NCUtilityFileSystem.shared.transformedSize(fileSize) } catch { print("Error: \(error)") } diff --git a/iOSClient/Main/Create cloud/NCCreateFormUploadDocuments.swift b/iOSClient/Main/Create cloud/NCCreateFormUploadDocuments.swift index 629fc0d007..60f71e05a4 100644 --- a/iOSClient/Main/Create cloud/NCCreateFormUploadDocuments.swift +++ b/iOSClient/Main/Create cloud/NCCreateFormUploadDocuments.swift @@ -33,10 +33,7 @@ import XLForm @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var collectionViewHeigth: NSLayoutConstraint! - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! var editorId = "" var creatorId = "" var typeTemplate = "" @@ -169,7 +166,7 @@ import XLForm // image let imagePreview = cell.viewWithTag(100) as? UIImageView if !template.preview.isEmpty { - let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + template.name + ".png" + let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + template.name + ".png" if FileManager.default.fileExists(atPath: fileNameLocalPath) { let imageURL = URL(fileURLWithPath: fileNameLocalPath) if let image = UIImage(contentsOfFile: imageURL.path) { @@ -279,7 +276,7 @@ import XLForm } else { - let fileNamePath = CCUtility.returnFileNamePath(fromFileName: String(describing: fileNameForm), serverUrl: serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)! + let fileNamePath = NCUtilityFileSystem.shared.getFileNamePath(String(describing: fileNameForm), serverUrl: serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId) createDocument(fileNamePath: fileNamePath, fileName: String(describing: fileNameForm)) } } @@ -288,7 +285,7 @@ import XLForm if let metadatas { let fileName = metadatas[0].fileName - let fileNamePath = CCUtility.returnFileNamePath(fromFileName: fileName, serverUrl: serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)! + let fileNamePath = NCUtilityFileSystem.shared.getFileNamePath(fileName, serverUrl: serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId) createDocument(fileNamePath: fileNamePath, fileName: fileName) } else { DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { @@ -489,7 +486,7 @@ import XLForm func getImageFromTemplate(name: String, preview: String, indexPath: IndexPath) { - let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + name + ".png" + let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + name + ".png" NextcloudKit.shared.download(serverUrlFileName: preview, fileNameLocalPath: fileNameLocalPath, requestHandler: { _ in diff --git a/iOSClient/Main/Create cloud/NCCreateFormUploadVoiceNote.swift b/iOSClient/Main/Create cloud/NCCreateFormUploadVoiceNote.swift index 716c903714..7988d3f2a7 100644 --- a/iOSClient/Main/Create cloud/NCCreateFormUploadVoiceNote.swift +++ b/iOSClient/Main/Create cloud/NCCreateFormUploadVoiceNote.swift @@ -31,10 +31,7 @@ class NCCreateFormUploadVoiceNote: XLFormViewController, NCSelectDelegate, AVAud @IBOutlet weak var labelDuration: UILabel! @IBOutlet weak var progressView: UIProgressView! - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! private var serverUrl = "" private var titleServerUrl = "" private var fileName = "" @@ -170,8 +167,8 @@ class NCCreateFormUploadVoiceNote: XLFormViewController, NCSelectDelegate, AVAud self.form.delegate = nil - if let fileNameNew = formRow.value { - self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew as? String) + if let fileNameNew = formRow.value as? String { + self.fileName = NCUtility.shared.removeForbiddenCharacters(fileNameNew) } formRow.value = self.fileName @@ -259,7 +256,7 @@ class NCCreateFormUploadVoiceNote: XLFormViewController, NCSelectDelegate, AVAud func dismissAndUpload(_ metadata: tableMetadata) { - CCUtility.copyFile(atPath: self.fileNamePath, toPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) + NCUtilityFileSystem.shared.copyFile(atPath: self.fileNamePath, toPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: [metadata], completion: { _ in }) diff --git a/iOSClient/Main/Create cloud/NCUploadAssets.swift b/iOSClient/Main/Create cloud/NCUploadAssets.swift index 403feae340..63b749dc1a 100644 --- a/iOSClient/Main/Create cloud/NCUploadAssets.swift +++ b/iOSClient/Main/Create cloud/NCUploadAssets.swift @@ -147,9 +147,9 @@ class NCUploadAssets: NSObject, ObservableObject, NCCreateFormUploadConflictDele struct UploadAssetsView: View { - @State private var fileName: String = CCUtility.getFileNameMask(NCGlobal.shared.keyFileNameMask) - @State private var isMaintainOriginalFilename: Bool = CCUtility.getOriginalFileName(NCGlobal.shared.keyFileNameOriginal) - @State private var isAddFilenametype: Bool = CCUtility.getFileNameType(NCGlobal.shared.keyFileNameType) + @State private var fileName: String = NCKeychain().getFileNameMask(key: NCGlobal.shared.keyFileNameMask) + @State private var isMaintainOriginalFilename: Bool = NCKeychain().getOriginalFileName(key: NCGlobal.shared.keyFileNameOriginal) + @State private var isAddFilenametype: Bool = NCKeychain().getFileNameType(key: NCGlobal.shared.keyFileNameType) @State private var isPresentedSelect = false @State private var isPresentedUploadConflict = false @State private var isPresentedQuickLook = false @@ -185,9 +185,9 @@ struct UploadAssetsView: View { var preview: String = "" let creationDate = asset.creationDate ?? Date() - CCUtility.setOriginalFileName(isMaintainOriginalFilename, key: NCGlobal.shared.keyFileNameOriginal) - CCUtility.setFileNameType(isAddFilenametype, key: NCGlobal.shared.keyFileNameType) - CCUtility.setFileNameMask(fileName, key: NCGlobal.shared.keyFileNameMask) + NCKeychain().setOriginalFileName(key: NCGlobal.shared.keyFileNameOriginal, value: isMaintainOriginalFilename) + NCKeychain().setFileNameType(key: NCGlobal.shared.keyFileNameType, prefix: isAddFilenametype) + NCKeychain().setFileNameMask(key: NCGlobal.shared.keyFileNameMask, mask: fileName) preview = CCUtility.createFileName( getOriginalFilenameForPreview() as String, @@ -230,7 +230,7 @@ struct UploadAssetsView: View { forcedNewFileName: false)! : (previewStore.fileName + "." + ext) - if previewStore.assetType == .livePhoto && CCUtility.getLivePhoto() && previewStore.data == nil { + if previewStore.assetType == .livePhoto && NCKeychain().livePhoto && previewStore.data == nil { livePhoto = true } @@ -271,7 +271,7 @@ struct UploadAssetsView: View { metadata.fileName = fileNameNoExtension + ".jpg" metadata.fileNameView = fileNameNoExtension + ".jpg" } - let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let fileNamePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) do { try data.write(to: URL(fileURLWithPath: fileNamePath)) metadata.isExtractFile = true @@ -323,7 +323,7 @@ struct UploadAssetsView: View { } private func getOriginalFilenameForPreview() -> NSString { - CCUtility.setOriginalFileName(isMaintainOriginalFilename, key: NCGlobal.shared.keyFileNameOriginal) + NCKeychain().setOriginalFileName(key: NCGlobal.shared.keyFileNameOriginal, value: isMaintainOriginalFilename) if let asset = uploadAssets.assets.first?.phAsset { return asset.originalFilename diff --git a/iOSClient/Main/NCActionCenter.swift b/iOSClient/Main/NCActionCenter.swift index 9000bb5904..05dc7cdb93 100644 --- a/iOSClient/Main/NCActionCenter.swift +++ b/iOSClient/Main/NCActionCenter.swift @@ -57,7 +57,7 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec // File do not exists on server, remove in local if error.errorCode == NCGlobal.shared.errorResourceNotFound || error.errorCode == NCGlobal.shared.errorBadServerResponse { do { - try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(ocId)) + try FileManager.default.removeItem(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId)) } catch { } NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", ocId)) @@ -70,7 +70,7 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec switch selector { case NCGlobal.shared.selectorLoadFileQuickLook: - let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let fileNamePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) let fileNameTemp = NSTemporaryDirectory() + metadata.fileNameView let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNameTemp), isEditingEnabled: true, metadata: metadata) if let image = UIImage(contentsOfFile: fileNamePath) { @@ -85,7 +85,7 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec navigationController.modalPresentationStyle = .fullScreen appDelegate.window?.rootViewController?.present(navigationController, animated: true) } else { - CCUtility.copyFile(atPath: fileNamePath, toPath: fileNameTemp) + NCUtilityFileSystem.shared.copyFile(atPath: fileNamePath, toPath: fileNameTemp) appDelegate.window?.rootViewController?.present(viewerQuickLook, animated: true) } @@ -98,7 +98,7 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec self.openDocumentController(metadata: metadata) } else { if let viewController = appDelegate.activeViewController { - let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) + let imageIcon = UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon) } } @@ -159,17 +159,15 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec var downloadRequest: DownloadRequest? if let metadata = NCManageDatabase.shared.getMetadataFromFileId(fileId) { - if let filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) { - do { - let attr = try FileManager.default.attributesOfItem(atPath: filePath) - let fileSize = attr[FileAttributeKey.size] as? UInt64 ?? 0 - if fileSize > 0 { - NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil) - return - } - } catch { - print("Error: \(error)") + do { + let attr = try FileManager.default.attributesOfItem(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) + let fileSize = attr[FileAttributeKey.size] as? UInt64 ?? 0 + if fileSize > 0 { + NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil) + return } + } catch { + print("Error: \(error)") } } @@ -197,7 +195,7 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec NCManageDatabase.shared.addMetadata(metadata) let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) if metadata.isAudioOrVideo { NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil) @@ -296,7 +294,7 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let mainTabBar = appDelegate.mainTabBar else { return } - let fileURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) + let fileURL = URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) documentController = UIDocumentInteractionController(url: fileURL) documentController?.presentOptionsMenu(from: mainTabBar.menuRect, in: mainTabBar, animated: true) @@ -310,8 +308,8 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec var downloadMetadata: [(tableMetadata, URL)] = [] for metadata in metadatas { - let fileURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) - if CCUtility.fileProviderStorageExists(metadata) { + let fileURL = URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { items.append(fileURL) } else { downloadMetadata.append((metadata, fileURL)) @@ -325,7 +323,7 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec } progressHandler: { progress in processor.hud?.progress = Float(progress.fractionCompleted) } completion: { _, _ in - if CCUtility.fileProviderStorageExists(metadata) { items.append(url) } + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { items.append(url) } completion() } } @@ -346,9 +344,9 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec func saveAsScan(metadata: tableMetadata) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } - let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let fileNamePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) let fileNameDestination = CCUtility.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, keyFileName: NCGlobal.shared.keyFileNameMask, keyFileNameType: NCGlobal.shared.keyFileNameType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal, forcedNewFileName: true)! - let fileNamePathDestination = CCUtility.getDirectoryScan() + "/" + fileNameDestination + let fileNamePathDestination = NCUtilityFileSystem.shared.directoryScan + "/" + fileNameDestination NCUtilityFileSystem.shared.copyFile(atPath: fileNamePath, toPath: fileNamePathDestination) @@ -364,7 +362,7 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec func printDocument(metadata: tableMetadata) { - let fileNameURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!) + let fileNameURL = URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) let printController = UIPrintInteractionController.shared let printInfo = UIPrintInfo(dictionary: nil) @@ -403,7 +401,7 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec func saveAlbum(metadata: tableMetadata) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } - let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let fileNamePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: appDelegate.mainTabBar?.window?.rootViewController) { hasPermission in guard hasPermission else { @@ -503,7 +501,7 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec } completionHandler: { account, ocId, etag, _, _, _, afError, error in NCNetworking.shared.uploadRequest.removeValue(forKey: fileNameLocalPath) if error == .success && etag != nil && ocId != nil { - let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId!, fileNameView: fileName)! + let toPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId!, fileNameView: fileName) NCUtilityFileSystem.shared.moveFile(atPath: fileNameLocalPath, toPath: toPath) NCManageDatabase.shared.addLocalFile(account: account, etag: etag!, ocId: ocId!, fileName: fileName) NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced) @@ -523,10 +521,10 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec guard !results.ext.isEmpty, let data = UIPasteboard.general.data(forPasteboardType: item.key, inItemSet: IndexSet([index]))?.first else { continue } - let fileName = results.name + "_" + CCUtility.getIncrementalNumber() + "." + results.ext + let fileName = results.name + "_" + NCKeychain().incrementalNumber + "." + results.ext let serverUrlFileName = serverUrl + "/" + fileName let ocIdUpload = UUID().uuidString - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdUpload, fileNameView: fileName)! + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocIdUpload, fileNameView: fileName) do { try data.write(to: URL(fileURLWithPath: fileNameLocalPath)) } catch { continue } processor.execute { completion in uploadPastePasteboard(fileName: fileName, serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, serverUrl: serverUrl, completion: completion) @@ -699,8 +697,8 @@ class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelec fileprivate extension tableMetadata { func toPasteBoardItem() -> [String: Any]? { // Get Data - let fileUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)) - guard CCUtility.fileProviderStorageExists(self), + let fileUrl = URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)) + guard NCUtilityFileSystem.shared.fileProviderStorageExists(self), let data = try? Data(contentsOf: fileUrl), let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil) else { return nil } diff --git a/iOSClient/Main/NCMainTabBar.swift b/iOSClient/Main/NCMainTabBar.swift index d8bc682e25..ecd827f8c1 100644 --- a/iOSClient/Main/NCMainTabBar.swift +++ b/iOSClient/Main/NCMainTabBar.swift @@ -28,11 +28,7 @@ class NCMainTabBar: UITabBar { private var fillColor: UIColor! private var shapeLayer: CALayer? - - // swiftlint:disable force_cast - private let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! private let centerButtonY: CGFloat = -28 public var menuRect: CGRect { diff --git a/iOSClient/Main/NCPickerViewController.swift b/iOSClient/Main/NCPickerViewController.swift index 0627970f07..7b5361ee59 100644 --- a/iOSClient/Main/NCPickerViewController.swift +++ b/iOSClient/Main/NCPickerViewController.swift @@ -31,10 +31,7 @@ import NextcloudKit class NCPhotosPickerViewController: NSObject { - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! var sourceViewController: UIViewController var maxSelectedAssets = 1 var singleSelectedMode = false @@ -118,10 +115,7 @@ class customPhotoPickerViewController: TLPhotosPickerViewController { class NCDocumentPickerViewController: NSObject, UIDocumentPickerDelegate { - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! var isViewerMedia: Bool var viewController: UIViewController? @@ -168,7 +162,7 @@ class NCDocumentPickerViewController: NSObject, UIDocumentPickerDelegate { let ocId = NSUUID().uuidString let fileName = urlIn.lastPathComponent - let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)! + let toPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName) let urlOut = URL(fileURLWithPath: toPath) guard self.copySecurityScopedResource(url: urlIn, urlOut: urlOut) != nil else { continue } diff --git a/iOSClient/Main/Section Header Footer/NCSectionHeaderMenu.swift b/iOSClient/Main/Section Header Footer/NCSectionHeaderMenu.swift index a682cc3944..2b8f0662aa 100644 --- a/iOSClient/Main/Section Header Footer/NCSectionHeaderMenu.swift +++ b/iOSClient/Main/Section Header Footer/NCSectionHeaderMenu.swift @@ -319,9 +319,9 @@ class NCSectionFooter: UICollectionReusableView, NCSectionFooterDelegate { } if files > 1 { - filesText = "\(files) " + NSLocalizedString("_files_", comment: "") + " " + CCUtility.transformedSize(size) + filesText = "\(files) " + NSLocalizedString("_files_", comment: "") + " " + NCUtilityFileSystem.shared.transformedSize(size) } else if files == 1 { - filesText = "1 " + NSLocalizedString("_file_", comment: "") + " " + CCUtility.transformedSize(size) + filesText = "1 " + NSLocalizedString("_file_", comment: "") + " " + NCUtilityFileSystem.shared.transformedSize(size) } if foldersText.isEmpty { diff --git a/iOSClient/Media/NCMedia.swift b/iOSClient/Media/NCMedia.swift index 7ec6d72ff4..87f224fd52 100644 --- a/iOSClient/Media/NCMedia.swift +++ b/iOSClient/Media/NCMedia.swift @@ -35,15 +35,9 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate { private var gridLayout: NCGridMediaLayout! internal var documentPickerViewController: NCDocumentPickerViewController? - // swiftlint:disable force_cast - internal let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast + internal let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! - public var metadatas: [tableMetadata] = [] - private var account: String = "" - - private var predicateDefault: NSPredicate? - private var predicate: NSPredicate? + //private var account: String = "" internal var isEditMode = false internal var selectOcId: [String] = [] @@ -60,7 +54,6 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate { private var lastContentOffsetY: CGFloat = 0 private var mediaPath = "" - private var livePhoto: Bool = false private var timeIntervalSearchNewMedia: TimeInterval = 3.0 private var timerSearchNewMedia: Timer? @@ -86,7 +79,7 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate { collectionView.backgroundColor = .systemBackground gridLayout = NCGridMediaLayout() - gridLayout.itemForLine = CGFloat(min(CCUtility.getMediaWidthImage(), 5)) + gridLayout.itemForLine = CGFloat(min(NCKeychain().mediaWidthImage, 5)) gridLayout.sectionHeadersPinToVisibleBounds = true collectionView.collectionViewLayout = gridLayout @@ -126,10 +119,10 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate { NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil) - self.reloadDataSourceWithCompletion { _ in - self.timerSearchNewMedia?.invalidate() - self.timerSearchNewMedia = Timer.scheduledTimer(timeInterval: self.timeIntervalSearchNewMedia, target: self, selector: #selector(self.searchNewMediaTimer), userInfo: nil, repeats: false) - } + timerSearchNewMedia?.invalidate() + timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchNewMediaTimer), userInfo: nil, repeats: false) + + collectionView.reloadData() } override func viewDidAppear(_ animated: Bool) { @@ -166,7 +159,7 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate { let error = userInfo["error"] as? NKError else { return } let onlyLocalCache: Bool = userInfo["onlyLocalCache"] as? Bool ?? false - self.queryDB(isForced: true) + NCMediaCache.shared.getMetadatasMedia(account: appDelegate.account, filterClassTypeImage: filterClassTypeImage, filterClassTypeVideo: filterClassTypeVideo) if error == .success, let indexPath = userInfo["indexPath"] as? [IndexPath], !indexPath.isEmpty, !onlyLocalCache { collectionView?.performBatchUpdates({ @@ -248,7 +241,7 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate { } self.collectionView.collectionViewLayout.invalidateLayout() - CCUtility.setMediaWidthImage(Int(self.gridLayout.itemForLine)) + NCKeychain().mediaWidthImage = Int(self.gridLayout.itemForLine) }) } @@ -264,7 +257,7 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate { } self.collectionView.collectionViewLayout.invalidateLayout() - CCUtility.setMediaWidthImage(Int(self.gridLayout.itemForLine)) + NCKeychain().mediaWidthImage = Int(self.gridLayout.itemForLine) }) } @@ -278,8 +271,9 @@ class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate { func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], indexPath: [IndexPath], overwrite: Bool, copy: Bool, move: Bool) { guard let serverUrl = serverUrl else { return } - let path = CCUtility.returnPathfromServerUrl(serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account) ?? "" - NCManageDatabase.shared.setAccountMediaPath(path, account: appDelegate.account) + let home = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) + let path = serverUrl.replacingOccurrences(of: home, with: "") + NCManageDatabase.shared.setAccountMediaPath(path, account: appDelegate.account) reloadDataSourceWithCompletion { _ in self.searchNewMedia() } @@ -305,7 +299,7 @@ extension NCMedia: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { - let metadata = metadatas[indexPath.row] + let metadata = NCMediaCache.shared.metadatas[indexPath.row] if isEditMode { if let index = selectOcId.firstIndex(of: metadata.ocId) { selectOcId.remove(at: index) @@ -321,14 +315,14 @@ extension NCMedia: UICollectionViewDelegate { // ACTIVE SERVERURL appDelegate.activeServerUrl = metadata.serverUrl let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridMediaCell - NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: cell?.imageItem.image) + NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: NCMediaCache.shared.metadatas, imageIcon: cell?.imageItem.image) } } func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { guard let cell = collectionView.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil } - let metadata = metadatas[indexPath.row] + let metadata = NCMediaCache.shared.metadatas[indexPath.row] let identifier = indexPath as NSCopying let image = cell.imageItem.image @@ -364,33 +358,13 @@ extension NCMedia: UICollectionViewDataSource { } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - emptyDataSet?.numberOfItemsInSection(metadatas.count, section: section) - return metadatas.count - } - - func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { - guard let cell = (cell as? NCGridMediaCell), indexPath.row < self.metadatas.count else { return } - let metadata = self.metadatas[indexPath.row] - if let image = NCMediaCache.shared.getImage(ocId: metadata.ocId) { - cell.imageItem.backgroundColor = nil - cell.imageItem.image = image - } else if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) { - if let image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) { - cell.imageItem.backgroundColor = nil - cell.imageItem.image = image - NCMediaCache.shared.setImage(ocId: metadata.ocId, image: image) - } - } else { - if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) { - for case let operation as NCMediaDownloadThumbnaill in appDelegate.downloadThumbnailQueue.operations where operation.metadata.ocId == metadata.ocId { return } - appDelegate.downloadThumbnailQueue.addOperation(NCMediaDownloadThumbnaill(metadata: metadata, cell: cell, view: view)) - } - } + emptyDataSet?.numberOfItemsInSection(NCMediaCache.shared.metadatas.count, section: section) + return NCMediaCache.shared.metadatas.count } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { - if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count { - let metadata = metadatas[indexPath.row] + if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < NCMediaCache.shared.metadatas.count { + let metadata = NCMediaCache.shared.metadatas[indexPath.row] for case let operation as NCMediaDownloadThumbnaill in appDelegate.downloadThumbnailQueue.operations where operation.metadata.ocId == metadata.ocId { operation.cancel() } @@ -401,9 +375,9 @@ extension NCMedia: UICollectionViewDataSource { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridMediaCell else { return UICollectionViewCell() } - if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) && indexPath.row < metadatas.count { + if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) && indexPath.row < NCMediaCache.shared.metadatas.count { - let metadata = metadatas[indexPath.row] + let metadata = NCMediaCache.shared.metadatas[indexPath.row] self.cellHeigth = cell.frame.size.height @@ -412,9 +386,26 @@ extension NCMedia: UICollectionViewDataSource { cell.indexPath = indexPath cell.fileUser = metadata.ownerId + if let image = NCMediaCache.shared.getImage(ocId: metadata.ocId) { + cell.imageItem.backgroundColor = nil + cell.imageItem.image = image + } else if FileManager().fileExists(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) { + if let image = UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) { + cell.imageItem.backgroundColor = nil + cell.imageItem.image = image + NCMediaCache.shared.setImage(ocId: metadata.ocId, image: image) + } + } else { + if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!NCUtilityFileSystem.shared.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) { + if appDelegate.downloadThumbnailQueue.operations.filter({ ($0 as? NCMediaDownloadThumbnaill)?.metadata.ocId == metadata.ocId }).isEmpty { + appDelegate.downloadThumbnailQueue.addOperation(NCMediaDownloadThumbnaill(metadata: metadata, cell: cell, collectionView: collectionView)) + } + } + } + if metadata.isAudioOrVideo { cell.imageStatus.image = cacheImages.cellPlayImage - } else if metadata.livePhoto && livePhoto { + } else if metadata.livePhoto && NCMediaCache.shared.livePhoto { cell.imageStatus.image = cacheImages.cellLivePhotoImage } @@ -451,59 +442,16 @@ extension NCMedia: UICollectionViewDelegateFlowLayout { extension NCMedia { - // MARK: - Datasource - - func queryDB(isForced: Bool) { - - livePhoto = CCUtility.getLivePhoto() - - if let activeAccount = NCManageDatabase.shared.getActiveAccount() { - self.mediaPath = activeAccount.mediaPath - } - let startServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) + mediaPath - - predicateDefault = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND (classFile == %@ OR classFile == %@) AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NKCommon.TypeClassFile.image.rawValue, NKCommon.TypeClassFile.video.rawValue) - - if filterClassTypeImage { - predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND classFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NKCommon.TypeClassFile.video.rawValue) - } else if filterClassTypeVideo { - predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND classFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NKCommon.TypeClassFile.image.rawValue) - } else { - predicate = predicateDefault - } - - guard let predicate = predicate else { return } - - self.metadatas = NCManageDatabase.shared.getMetadatasMedia(predicate: predicate, livePhoto: self.livePhoto) - - switch CCUtility.getMediaSortDate() { - case "date": - self.metadatas = self.metadatas.sorted(by: {($0.date as Date) > ($1.date as Date)}) - case "creationDate": - self.metadatas = self.metadatas.sorted(by: {($0.creationDate as Date) > ($1.creationDate as Date)}) - case "uploadDate": - self.metadatas = self.metadatas.sorted(by: {($0.uploadDate as Date) > ($1.uploadDate as Date)}) - default: - break - } - } - @objc func reloadDataSourceWithCompletion(_ completion: @escaping (_ metadatas: [tableMetadata]) -> Void) { guard !appDelegate.account.isEmpty else { return } - if account != appDelegate.account { - self.metadatas = [] - account = appDelegate.account - DispatchQueue.main.async { self.collectionView?.reloadData() } - } - DispatchQueue.global().async { - self.queryDB(isForced: true) + NCMediaCache.shared.getMetadatasMedia(account: self.appDelegate.account, filterClassTypeImage: self.filterClassTypeImage, filterClassTypeVideo: self.filterClassTypeVideo) DispatchQueue.main.sync { self.reloadDataThenPerform { self.updateMediaControlVisibility() self.mediaCommandTitle() - completion(self.metadatas) + completion(NCMediaCache.shared.metadatas) } } } @@ -511,7 +459,7 @@ extension NCMedia { func updateMediaControlVisibility() { - if self.metadatas.isEmpty { + if NCMediaCache.shared.metadatas.isEmpty { if !self.filterClassTypeImage && !self.filterClassTypeVideo { self.mediaCommandView?.toggleEmptyView(isEmpty: true) self.mediaCommandView?.isHidden = false @@ -540,10 +488,8 @@ extension NCMedia { } var lessDate = Date() - if predicateDefault != nil { - if let metadata = NCManageDatabase.shared.getMetadata(predicate: predicateDefault!, sorted: "date", ascending: true) { - lessDate = metadata.date as Date - } + if let predicate = NCMediaCache.shared.predicateDefault, let metadata = NCManageDatabase.shared.getMetadata(predicate: predicate, sorted: "date", ascending: true) { + lessDate = metadata.date as Date } var greaterDate: Date @@ -555,7 +501,7 @@ extension NCMedia { let options = NKRequestOptions(timeout: 300, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue) - NextcloudKit.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), options: options) { account, files, _, error in + NextcloudKit.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: NCKeychain().showHiddenFiles, options: options) { account, files, _, error in self.oldInProgress = false DispatchQueue.main.async { @@ -567,7 +513,7 @@ extension NCMedia { if !files.isEmpty { NCManageDatabase.shared.convertFilesToMetadatas(files, useMetadataFolder: false) { _, _, metadatas in let predicateDate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate) - let predicateResult = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateDate, self.predicateDefault!]) + let predicateResult = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateDate, NCMediaCache.shared.predicateDefault!]) let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult) let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false) if metadatasChanged.metadatasUpdate.isEmpty { @@ -621,7 +567,7 @@ extension NCMedia { if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) { if let cell = visibleCells.first as? NCGridMediaCell { if cell.date != nil { - if cell.date != self.metadatas.first?.date as Date? { + if cell.date != NCMediaCache.shared.metadatas.first?.date as Date? { lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)! limit = 0 } @@ -638,7 +584,7 @@ extension NCMedia { let options = NKRequestOptions(timeout: 300, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue) - NextcloudKit.shared.searchMedia(path: self.mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), options: options) { account, files, _, error in + NextcloudKit.shared.searchMedia(path: self.mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: NCKeychain().showHiddenFiles, options: options) { account, files, _, error in self.newInProgress = false DispatchQueue.main.async { @@ -648,14 +594,14 @@ extension NCMedia { if error == .success, account == self.appDelegate.account, !files.isEmpty { NCManageDatabase.shared.convertFilesToMetadatas(files, useMetadataFolder: false) { _, _, metadatas in let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate) - let predicateResult = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, self.predicate!]) + let predicateResult = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, NCMediaCache.shared.predicate!]) let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult) let updateMetadatas = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false) if !updateMetadatas.metadatasUpdate.isEmpty || !updateMetadatas.metadatasDelete.isEmpty { self.reloadDataSourceWithCompletion { _ in } } } - } else if error == .success, files.isEmpty, self.metadatas.isEmpty { + } else if error == .success, files.isEmpty, NCMediaCache.shared.metadatas.isEmpty { self.searchOldMedia() } else if error != .success { NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Media search new media error code \(error.errorCode) " + error.errorDescription) @@ -861,18 +807,18 @@ class NCMediaDownloadThumbnaill: ConcurrentOperation { var metadata: tableMetadata var cell: NCCellProtocol? - var view: UIView? + var collectionView: UICollectionView? var fileNamePath: String var fileNamePreviewLocalPath: String var fileNameIconLocalPath: String - init(metadata: tableMetadata, cell: NCCellProtocol?, view: UIView?) { + init(metadata: tableMetadata, cell: NCCellProtocol?, collectionView: UICollectionView?) { self.metadata = tableMetadata.init(value: metadata) self.cell = cell - self.view = view - self.fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)! - self.fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)! - self.fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)! + self.collectionView = collectionView + self.fileNamePath = NCUtilityFileSystem.shared.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId) + self.fileNamePreviewLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag) + self.fileNameIconLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag) } override func start() { @@ -902,6 +848,8 @@ class NCMediaDownloadThumbnaill: ConcurrentOperation { options: .transitionCrossDissolve, animations: { filePreviewImageView.image = image }, completion: nil) + } else { + self.collectionView?.reloadData() } } NCMediaCache.shared.setImage(ocId: self.metadata.ocId, image: image) diff --git a/iOSClient/Media/NCMediaCache.swift b/iOSClient/Media/NCMediaCache.swift index 861c246d69..e24cca3c6e 100644 --- a/iOSClient/Media/NCMediaCache.swift +++ b/iOSClient/Media/NCMediaCache.swift @@ -32,18 +32,23 @@ import NextcloudKit return instance }() - let limit: Int = 2000 + private let limit: Int = 1500 private typealias ThumbnailLRUCache = LRUCache private lazy var cache: ThumbnailLRUCache = { return ThumbnailLRUCache(countLimit: limit) }() + private var ocIdEtag: [String: String] = [:] + public var metadatas: [tableMetadata] = [] + public var predicateDefault: NSPredicate? + public var predicate: NSPredicate? + public var livePhoto: Bool = false func createCache(account: String) { - let resultsMedia = NCManageDatabase.shared.getMediaOcIdEtag(account: account) - guard !resultsMedia.isEmpty, - let directory = CCUtility.getDirectoryProviderStorage() else { return } + metadatas.removeAll() + getMetadatasMedia(account: account) + guard !metadatas.isEmpty else { return } let ext = ".preview.ico" let manager = FileManager.default let resourceKeys = Set([.nameKey, .pathKey, .fileSizeKey, .creationDateKey]) @@ -55,7 +60,11 @@ import NextcloudKit var files: [FileInfo] = [] let startDate = Date() - if let enumerator = manager.enumerator(at: URL(fileURLWithPath: directory), includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles]) { + for metadata in metadatas { + ocIdEtag[metadata.ocId] = metadata.etag + } + + if let enumerator = manager.enumerator(at: URL(fileURLWithPath: NCUtilityFileSystem.shared.directoryProviderStorage), includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles]) { for case let fileURL as URL in enumerator where fileURL.lastPathComponent.hasSuffix(ext) { let fileName = fileURL.lastPathComponent let ocId = fileURL.deletingLastPathComponent().lastPathComponent @@ -63,7 +72,7 @@ import NextcloudKit let size = resourceValues.fileSize, size > 0, let date = resourceValues.creationDate, - let etag = resultsMedia[ocId], + let etag = ocIdEtag[ocId], fileName == etag + ext else { continue } files.append(FileInfo(path: fileURL, ocId: ocId, date: date)) } @@ -106,4 +115,36 @@ import NextcloudKit @objc func clearCache() { cache.removeAllValues() } + + func getMetadatasMedia(account: String, filterClassTypeImage: Bool = false, filterClassTypeVideo: Bool = false) { + + guard let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) else { return } + let startServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: account.urlBase, userId: account.userId) + account.mediaPath + + predicateDefault = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND (classFile == %@ OR classFile == %@) AND NOT (session CONTAINS[c] 'upload')", account.account, startServerUrl, NKCommon.TypeClassFile.image.rawValue, NKCommon.TypeClassFile.video.rawValue) + + if filterClassTypeImage { + predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND classFile == %@ AND NOT (session CONTAINS[c] 'upload')", account.account, startServerUrl, NKCommon.TypeClassFile.video.rawValue) + } else if filterClassTypeVideo { + predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND classFile == %@ AND NOT (session CONTAINS[c] 'upload')", account.account, startServerUrl, NKCommon.TypeClassFile.image.rawValue) + } else { + predicate = predicateDefault + } + + guard let predicate = predicate else { return } + + livePhoto = NCKeychain().livePhoto + metadatas = NCManageDatabase.shared.getMetadatasMedia(predicate: predicate, livePhoto: livePhoto) + + switch NCKeychain().mediaSortDate { + case "date": + metadatas = self.metadatas.sorted(by: {($0.date as Date) > ($1.date as Date)}) + case "creationDate": + metadatas = self.metadatas.sorted(by: {($0.creationDate as Date) > ($1.creationDate as Date)}) + case "uploadDate": + metadatas = self.metadatas.sorted(by: {($0.uploadDate as Date) > ($1.uploadDate as Date)}) + default: + break + } + } } diff --git a/iOSClient/Menu/AppDelegate+Menu.swift b/iOSClient/Menu/AppDelegate+Menu.swift index dd5855357a..3fdf05ff2c 100644 --- a/iOSClient/Menu/AppDelegate+Menu.swift +++ b/iOSClient/Menu/AppDelegate+Menu.swift @@ -32,11 +32,7 @@ extension AppDelegate { func toggleMenu(viewController: UIViewController) { var actions: [NCMenuAction] = [] - - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! let directEditingCreators = NCManageDatabase.shared.getDirectEditingCreators(account: appDelegate.account) let isDirectoryE2EE = NCUtility.shared.isDirectoryE2EE(serverUrl: appDelegate.activeServerUrl, userBase: appDelegate) let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, appDelegate.activeServerUrl)) @@ -99,7 +95,7 @@ extension AppDelegate { title: NSLocalizedString("_create_voice_memo_", comment: ""), icon: UIImage(named: "microphone")!.image(color: UIColor.systemGray, size: 50), action: { _ in NCAskAuthorization.shared.askAuthorizationAudioRecord(viewController: viewController) { hasPermission in if hasPermission { - let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")! + let fileName = NCUtilityFileSystem.shared.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), ext: "m4a") if let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as? NCAudioRecorderViewController { viewController.delegate = self @@ -115,7 +111,7 @@ extension AppDelegate { ) ) - if CCUtility.isEnd(toEndEnabled: appDelegate.account) { + if NCKeychain().isEndToEndEnabled(account: appDelegate.account) { actions.append(.seperator(order: 0)) } @@ -132,7 +128,7 @@ extension AppDelegate { ) // Folder encrypted - if !isDirectoryE2EE && CCUtility.isEnd(toEndEnabled: appDelegate.account) { + if !isDirectoryE2EE && NCKeychain().isEndToEndEnabled(account: appDelegate.account) { actions.append( NCMenuAction(title: NSLocalizedString("_create_folder_e2ee_", comment: ""), icon: UIImage(named: "folderEncrypted")!.image(color: NCBrandColor.shared.brandElement, size: 50), @@ -144,7 +140,7 @@ extension AppDelegate { ) } - if CCUtility.isEnd(toEndEnabled: appDelegate.account) { + if NCKeychain().isEndToEndEnabled(account: appDelegate.account) { actions.append(.seperator(order: 0)) } diff --git a/iOSClient/Menu/NCCollectionViewCommon+Menu.swift b/iOSClient/Menu/NCCollectionViewCommon+Menu.swift index e06cc952c8..40edcd81d2 100644 --- a/iOSClient/Menu/NCCollectionViewCommon+Menu.swift +++ b/iOSClient/Menu/NCCollectionViewCommon+Menu.swift @@ -286,7 +286,7 @@ extension NCCollectionViewCommon { icon: NCUtility.shared.loadImage(named: "viewfinder.circle"), order: 110, action: { _ in - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": NCGlobal.shared.selectorSaveAsScan, "error": NKError(), "account": metadata.account]) } else { NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorSaveAsScan) { _, _ in } @@ -346,7 +346,7 @@ extension NCCollectionViewCommon { icon: NCUtility.shared.loadImage(named: "pencil.tip.crop.circle"), order: 150, action: { _ in - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": NCGlobal.shared.selectorLoadFileQuickLook, "error": NKError(), "account": metadata.account]) } else { NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileQuickLook) { _, _ in } diff --git a/iOSClient/Menu/NCContextMenu.swift b/iOSClient/Menu/NCContextMenu.swift index 9775bde74c..ba08c049b7 100644 --- a/iOSClient/Menu/NCContextMenu.swift +++ b/iOSClient/Menu/NCContextMenu.swift @@ -70,7 +70,7 @@ class NCContextMenu: NSObject { let openIn = UIAction(title: NSLocalizedString("_open_in_", comment: ""), image: UIImage(systemName: "square.and.arrow.up") ) { _ in - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": NCGlobal.shared.selectorOpenIn, "error": NKError(), "account": metadata.account]) } else { hud.show(in: viewController.view) @@ -102,7 +102,7 @@ class NCContextMenu: NSObject { appDelegate.saveLivePhotoQueue.addOperation(NCOperationSaveLivePhoto(metadata: metadata, metadataMOV: metadataMOV)) } } else { - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { NCActionCenter.shared.saveAlbum(metadata: metadata) } else { hud.show(in: viewController.view) @@ -125,7 +125,7 @@ class NCContextMenu: NSObject { let modify = UIAction(title: NSLocalizedString("_modify_", comment: ""), image: UIImage(systemName: "pencil.tip.crop.circle")) { _ in - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": NCGlobal.shared.selectorLoadFileQuickLook, "error": NKError(), "account": metadata.account]) } else { hud.show(in: viewController.view) diff --git a/iOSClient/Menu/NCMedia+Menu.swift b/iOSClient/Menu/NCMedia+Menu.swift index 66f6cde695..a93e25cc14 100644 --- a/iOSClient/Menu/NCMedia+Menu.swift +++ b/iOSClient/Menu/NCMedia+Menu.swift @@ -40,7 +40,7 @@ extension NCMedia { defer { presentMenu(with: actions) } if !isEditMode { - if !metadatas.isEmpty { + if !NCMediaCache.shared.metadatas.isEmpty { actions.append( NCMenuAction( title: NSLocalizedString("_select_", comment: ""), @@ -146,10 +146,10 @@ extension NCMedia { NCMenuAction( title: NSLocalizedString("_media_by_modified_date_", comment: ""), icon: NCUtility.shared.loadImage(named: "circle.grid.cross.up.fill"), - selected: CCUtility.getMediaSortDate() == "date", + selected: NCKeychain().mediaSortDate == "date", on: true, action: { _ in - CCUtility.setMediaSortDate("date") + NCKeychain().mediaSortDate = "date" self.reloadDataSourceWithCompletion { _ in } } ) @@ -159,10 +159,10 @@ extension NCMedia { NCMenuAction( title: NSLocalizedString("_media_by_created_date_", comment: ""), icon: NCUtility.shared.loadImage(named: "circle.grid.cross.down.fill"), - selected: CCUtility.getMediaSortDate() == "creationDate", + selected: NCKeychain().mediaSortDate == "creationDate", on: true, action: { _ in - CCUtility.setMediaSortDate("creationDate") + NCKeychain().mediaSortDate = "creationDate" self.reloadDataSourceWithCompletion { _ in } } ) @@ -172,10 +172,10 @@ extension NCMedia { NCMenuAction( title: NSLocalizedString("_media_by_upload_date_", comment: ""), icon: NCUtility.shared.loadImage(named: "circle.grid.cross.right.fill"), - selected: CCUtility.getMediaSortDate() == "uploadDate", + selected: NCKeychain().mediaSortDate == "uploadDate", on: true, action: { _ in - CCUtility.setMediaSortDate("uploadDate") + NCKeychain().mediaSortDate = "uploadDate" self.reloadDataSourceWithCompletion { _ in } } ) diff --git a/iOSClient/Menu/NCMenuAction.swift b/iOSClient/Menu/NCMenuAction.swift index 7d4dc88400..310c825ec8 100644 --- a/iOSClient/Menu/NCMenuAction.swift +++ b/iOSClient/Menu/NCMenuAction.swift @@ -226,7 +226,7 @@ extension NCMenuAction { appDelegate.saveLivePhotoQueue.addOperation(NCOperationSaveLivePhoto(metadata: metadata, metadataMOV: metadataMOV)) } } else { - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { NCActionCenter.shared.saveAlbum(metadata: metadata) } else { if let appDelegate = (UIApplication.shared.delegate as? AppDelegate), appDelegate.downloadQueue.operations.filter({ ($0 as? NCOperationDownload)?.metadata.ocId == metadata.ocId }).isEmpty { @@ -286,7 +286,7 @@ extension NCMenuAction { icon: NCUtility.shared.loadImage(named: "printer"), order: order, action: { _ in - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": NCGlobal.shared.selectorPrint, "error": NKError(), "account": metadata.account]) } else { NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorPrint) { _, _ in } diff --git a/iOSClient/Menu/NCOperationSaveLivePhoto.swift b/iOSClient/Menu/NCOperationSaveLivePhoto.swift index d7eb485480..1f1cae293c 100644 --- a/iOSClient/Menu/NCOperationSaveLivePhoto.swift +++ b/iOSClient/Menu/NCOperationSaveLivePhoto.swift @@ -1,5 +1,5 @@ // -// NCooo.swift +// NCOperationSaveLivePhoto.swift // Nextcloud // // Created by Marino Faggiana on 19/10/23. @@ -21,7 +21,6 @@ // along with this program. If not, see . // - import UIKit import Queuer import JGProgressHUD @@ -86,8 +85,8 @@ class NCOperationSaveLivePhoto: ConcurrentOperation { func saveLivePhotoToDisk(metadata: tableMetadata, metadataMov: tableMetadata) { - let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!) - let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!) + let fileNameImage = URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) + let fileNameMov = URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)) DispatchQueue.main.async { self.hud.textLabel.text = NSLocalizedString("_livephoto_save_", comment: "") @@ -97,8 +96,8 @@ class NCOperationSaveLivePhoto: ConcurrentOperation { NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in self.hud.progress = Float(progress) }, completion: { _, resources in - if resources != nil { - NCLivePhoto.saveToLibrary(resources!) { result in + if let resources { + NCLivePhoto.saveToLibrary(resources) { result in DispatchQueue.main.async { if !result { self.hud.indicatorView = JGProgressHUDErrorIndicatorView() diff --git a/iOSClient/Menu/NCTrash+Menu.swift b/iOSClient/Menu/NCTrash+Menu.swift index cdd99e5dce..b7e06ccfc8 100644 --- a/iOSClient/Menu/NCTrash+Menu.swift +++ b/iOSClient/Menu/NCTrash+Menu.swift @@ -121,7 +121,7 @@ extension NCTrash { var actions: [NCMenuAction] = [] var iconHeader: UIImage! - if let icon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)) { + if let icon = UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)) { iconHeader = icon } else { if tableTrash.directory { diff --git a/iOSClient/Menu/NCViewer+Menu.swift b/iOSClient/Menu/NCViewer+Menu.swift index 5775857c01..bc8961e0c5 100644 --- a/iOSClient/Menu/NCViewer+Menu.swift +++ b/iOSClient/Menu/NCViewer+Menu.swift @@ -110,7 +110,7 @@ extension NCViewer { title: NSLocalizedString("_print_", comment: ""), icon: NCUtility.shared.loadImage(named: "printer"), action: { _ in - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": NCGlobal.shared.selectorPrint, "error": NKError(), "account": metadata.account]) } else { NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorPrint) { _, _ in } @@ -157,7 +157,7 @@ extension NCViewer { title: NSLocalizedString("_save_as_scan_", comment: ""), icon: NCUtility.shared.loadImage(named: "viewfinder.circle"), action: { _ in - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": NCGlobal.shared.selectorSaveAsScan, "error": NKError(), "account": metadata.account]) } else { NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorSaveAsScan) { _, _ in } @@ -210,7 +210,7 @@ extension NCViewer { // // DOWNLOAD LOCALLY // - if !webView, metadata.session.isEmpty, !CCUtility.fileProviderStorageExists(metadata) { + if !webView, metadata.session.isEmpty, !NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { actions.append( NCMenuAction( title: NSLocalizedString("_download_locally_", comment: ""), @@ -256,7 +256,7 @@ extension NCViewer { title: NSLocalizedString("_modify_", comment: ""), icon: NCUtility.shared.loadImage(named: "pencil.tip.crop.circle"), action: { _ in - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": NCGlobal.shared.selectorLoadFileQuickLook, "error": NKError(), "account": metadata.account]) } else { NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileQuickLook) { _, _ in } diff --git a/iOSClient/More/NCMore.swift b/iOSClient/More/NCMore.swift index 93c3f7c952..ef428e1cf3 100644 --- a/iOSClient/More/NCMore.swift +++ b/iOSClient/More/NCMore.swift @@ -37,13 +37,8 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource { private var externalSiteMenu: [NKExternalSite] = [] private var settingsMenu: [NKExternalSite] = [] private var quotaMenu: [NKExternalSite] = [] - - // swiftlint:disable force_cast - private let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! private let applicationHandle = NCApplicationHandle() - private var tabAccount: tableAccount? private struct Section { @@ -213,10 +208,10 @@ class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource { case -3: quota = NSLocalizedString("_quota_space_unlimited_", comment: "") default: - quota = CCUtility.transformedSize(activeAccount.quotaTotal) + quota = NCUtilityFileSystem.shared.transformedSize(activeAccount.quotaTotal) } - let quotaUsed: String = CCUtility.transformedSize(activeAccount.quotaUsed) + let quotaUsed: String = NCUtilityFileSystem.shared.transformedSize(activeAccount.quotaUsed) labelQuota.text = String.localizedStringWithFormat(NSLocalizedString("_quota_using_", comment: ""), quotaUsed, quota) } diff --git a/iOSClient/NCGlobal.swift b/iOSClient/NCGlobal.swift index 257b577638..51d93927a8 100644 --- a/iOSClient/NCGlobal.swift +++ b/iOSClient/NCGlobal.swift @@ -61,6 +61,13 @@ class NCGlobal: NSObject { return result.reduce(0, { $0 + $1 }) % maximum } + // ENUM + // + public enum TypeFilterScanDocument: String { + case document = "document" + case original = "original" + } + // Directory on Group // @objc let directoryProviderStorage = "File Provider Storage" @@ -72,7 +79,6 @@ class NCGlobal: NSObject { // Service // - @objc let serviceShareKeyChain = "Crypto Cloud" let metadataKeyedUnarchiver = "it.twsweb.nextcloud.metadata" let refreshTask = "com.nextcloud.refreshTask" let processingTask = "com.nextcloud.processingTask" diff --git a/iOSClient/Networking/E2EE/NCEndToEndEncryption.m b/iOSClient/Networking/E2EE/NCEndToEndEncryption.m index 6fb55970b0..bfaa52e514 100644 --- a/iOSClient/Networking/E2EE/NCEndToEndEncryption.m +++ b/iOSClient/Networking/E2EE/NCEndToEndEncryption.m @@ -564,7 +564,7 @@ - (BOOL)decryptFile:(NSString *)fileName fileNameView:(NSString *)fileNameView o NSData *initializationVectorData = [[NSData alloc] initWithBase64EncodedString:initializationVector options:0]; NSData *authenticationTagData = [[NSData alloc] initWithBase64EncodedString:authenticationTag options:0]; - return [self decryptFile:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileName] fileNamePlain:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView] key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData]; + return [self decryptFile:[[NCUtilityFileSystem shared] getDirectoryProviderStorageOcId:ocId fileNameView:fileName] fileNamePlain:[[NCUtilityFileSystem shared] getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView] key:keyData keyLen:AES_KEY_128_LENGTH initializationVector:initializationVectorData authenticationTag:authenticationTagData]; } // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/iOSClient/Networking/E2EE/NCEndToEndMetadataV1.swift b/iOSClient/Networking/E2EE/NCEndToEndMetadataV1.swift index 979282eb9a..99ca9b7dcf 100644 --- a/iOSClient/Networking/E2EE/NCEndToEndMetadataV1.swift +++ b/iOSClient/Networking/E2EE/NCEndToEndMetadataV1.swift @@ -95,7 +95,7 @@ extension NCEndToEndMetadata { var filesCodable: [String: E2eeV12.Files]? var filedrop: [String: E2eeV12.Filedrop] = [:] var filedropCodable: [String: E2eeV12.Filedrop]? - let privateKey = CCUtility.getEndToEndPrivateKey(account) + let privateKey = NCKeychain().getEndToEndPrivateKey(account: account) var fileNameIdentifiers: [String] = [] let e2eEncryptions = NCManageDatabase.shared.getE2eEncryptions(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl)) @@ -166,7 +166,7 @@ extension NCEndToEndMetadata { } // Create checksum - let passphrase = CCUtility.getEndToEndPassphrase(account).replacingOccurrences(of: " ", with: "") + let passphrase = NCKeychain().getEndToEndPassphrase(account: account)?.replacingOccurrences(of: " ", with: "") ?? "" let dataChecksum = (passphrase + fileNameIdentifiers.sorted().joined() + metadataKey).data(using: .utf8) let checksum = NCEndToEndEncryption.sharedManager().createSHA256(dataChecksum) @@ -200,7 +200,7 @@ extension NCEndToEndMetadata { } let decoder = JSONDecoder() - let privateKey = CCUtility.getEndToEndPrivateKey(account) + let privateKey = NCKeychain().getEndToEndPrivateKey(account: account) var metadataVersion: Double = 0 var metadataKey = "" @@ -345,7 +345,7 @@ extension NCEndToEndMetadata { } // verify checksum - let passphrase = CCUtility.getEndToEndPassphrase(account).replacingOccurrences(of: " ", with: "") + let passphrase = NCKeychain().getEndToEndPassphrase(account: account)?.replacingOccurrences(of: " ", with: "") ?? "" let dataChecksum = (passphrase + fileNameIdentifiers.sorted().joined() + metadata.metadataKey).data(using: .utf8) let checksum = NCEndToEndEncryption.sharedManager().createSHA256(dataChecksum) if metadata.checksum != checksum { @@ -369,7 +369,7 @@ extension NCEndToEndMetadata { } let decoder = JSONDecoder() - let privateKey = CCUtility.getEndToEndPrivateKey(account) + let privateKey = NCKeychain().getEndToEndPrivateKey(account: account) var metadataVersion: Double = 0 do { diff --git a/iOSClient/Networking/E2EE/NCEndToEndMetadataV20.swift b/iOSClient/Networking/E2EE/NCEndToEndMetadataV20.swift index 5ca3980542..2ac5eabdc6 100644 --- a/iOSClient/Networking/E2EE/NCEndToEndMetadataV20.swift +++ b/iOSClient/Networking/E2EE/NCEndToEndMetadataV20.swift @@ -100,7 +100,7 @@ extension NCEndToEndMetadata { func encodeMetadataV20(account: String, serverUrl: String, ocIdServerUrl: String, userId: String, addUserId: String?, addCertificate: String?, removeUserId: String?) -> (metadata: String?, signature: String?, counter: Int, error: NKError) { - guard let directoryTop = NCUtility.shared.getDirectoryE2EETop(serverUrl: serverUrl, account: account) else { + guard let directoryTop = NCUtility.shared.getDirectoryE2EETop(serverUrl: serverUrl, account: account), let certificate = NCKeychain().getEndToEndCertificate(account: account) else { return (nil, nil, 0, NKError(errorCode: NCGlobal.shared.errorUnexpectedResponseFromDB, errorDescription: "_e2e_error_")) } @@ -134,7 +134,7 @@ extension NCEndToEndMetadata { let metadataKey = tableUserId.metadataKey { key = metadataKey } else { - addUser(userId: userId, certificate: CCUtility.getEndToEndCertificate(account), key: key) + addUser(userId: userId, certificate: certificate, key: key) } // ADDUSERID if let addUserId { @@ -237,7 +237,7 @@ extension NCEndToEndMetadata { e2eeData.printJson() let e2eeJson = String(data: e2eeData, encoding: .utf8) - let signature = createSignature(account: account, userId: userId, metadata: metadataCodable, users: usersCodable, version: NCGlobal.shared.e2eeVersionV20, certificate: CCUtility.getEndToEndCertificate(account)) + let signature = createSignature(account: account, userId: userId, metadata: metadataCodable, users: usersCodable, version: NCGlobal.shared.e2eeVersionV20, certificate: certificate) return (e2eeJson, signature, counter, NKError()) @@ -303,7 +303,7 @@ extension NCEndToEndMetadata { var metadataKey: Data? if let encryptedMetadataKey = user.encryptedMetadataKey { let data = Data(base64Encoded: encryptedMetadataKey) - if let decrypted = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(data, privateKey: CCUtility.getEndToEndPrivateKey(account)) { + if let decrypted = NCEndToEndEncryption.sharedManager().decryptAsymmetricData(data, privateKey: NCKeychain().getEndToEndPrivateKey(account: account)) { metadataKey = decrypted } } @@ -447,7 +447,7 @@ extension NCEndToEndMetadata { let decoded = try? JSONSerialization.data(withJSONObject: dataSerialization, options: [.sortedKeys, .withoutEscapingSlashes]) let base64 = decoded!.base64EncodedString() if let base64Data = base64.data(using: .utf8), - let signatureData = NCEndToEndEncryption.sharedManager().generateSignatureCMS(base64Data, certificate: certificate, privateKey: CCUtility.getEndToEndPrivateKey(account), userId: userId) { + let signatureData = NCEndToEndEncryption.sharedManager().generateSignatureCMS(base64Data, certificate: certificate, privateKey: NCKeychain().getEndToEndPrivateKey(account: account), userId: userId) { return signatureData.base64EncodedString() } } catch { diff --git a/iOSClient/Networking/E2EE/NCNetworkingE2EE.swift b/iOSClient/Networking/E2EE/NCNetworkingE2EE.swift index d5b724b3af..e7eaa5e117 100644 --- a/iOSClient/Networking/E2EE/NCNetworkingE2EE.swift +++ b/iOSClient/Networking/E2EE/NCNetworkingE2EE.swift @@ -191,7 +191,7 @@ class NCNetworkingE2EE: NSObject { func unlockAll(account: String) { - guard CCUtility.isEnd(toEndEnabled: account) else { return } + guard NCKeychain().isEndToEndEnabled(account: account) else { return } Task { for result in NCManageDatabase.shared.getE2EAllTokenLock(account: account) { diff --git a/iOSClient/Networking/E2EE/NCNetworkingE2EECreateFolder.swift b/iOSClient/Networking/E2EE/NCNetworkingE2EECreateFolder.swift index a417f24998..351df5be1f 100644 --- a/iOSClient/Networking/E2EE/NCNetworkingE2EECreateFolder.swift +++ b/iOSClient/Networking/E2EE/NCNetworkingE2EECreateFolder.swift @@ -32,7 +32,7 @@ class NCNetworkingE2EECreateFolder: NSObject { let fileNameIdentifier = NCNetworkingE2EE.shared.generateRandomIdentifier() let serverUrlFileName = serverUrl + "/" + fileNameIdentifier - let fileNameFolder = NCUtilityFileSystem.shared.createFileName(CCUtility.removeForbiddenCharactersServer(fileName)!, serverUrl: serverUrl, account: account) + let fileNameFolder = NCUtilityFileSystem.shared.createFileName(NCUtility.shared.removeForbiddenCharacters(fileName), serverUrl: serverUrl, account: account) if fileNameFolder.isEmpty { return NKError(errorCode: NCGlobal.shared.errorUnexpectedResponseFromDB, errorDescription: NSLocalizedString("_e2e_error_", comment: "")) } diff --git a/iOSClient/Networking/E2EE/NCNetworkingE2EERename.swift b/iOSClient/Networking/E2EE/NCNetworkingE2EERename.swift index 718c433bcb..67c2c6b021 100644 --- a/iOSClient/Networking/E2EE/NCNetworkingE2EERename.swift +++ b/iOSClient/Networking/E2EE/NCNetworkingE2EERename.swift @@ -55,7 +55,8 @@ class NCNetworkingE2EERename: NSObject { // DB RENAME // - NCManageDatabase.shared.renameFileE2eEncryption(account: metadata.account, serverUrl: metadata.serverUrl, fileNameIdentifier: metadata.fileName, newFileName: fileNameNew, newFileNamePath: CCUtility.returnFileNamePath(fromFileName: fileNameNew, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)) + let newFileNamePath = NCUtilityFileSystem.shared.getFileNamePath(fileNameNew, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId) + NCManageDatabase.shared.renameFileE2eEncryption(account: metadata.account, serverUrl: metadata.serverUrl, fileNameIdentifier: metadata.fileName, newFileName: fileNameNew, newFileNamePath: newFileNamePath) // UPLOAD METADATA // @@ -77,8 +78,8 @@ class NCNetworkingE2EERename: NSObject { // MOVE FILE SYSTEM // - let atPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView - let toPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + fileNameNew + let atPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView + let toPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + fileNameNew do { try FileManager.default.moveItem(atPath: atPath, toPath: toPath) } catch { } diff --git a/iOSClient/Networking/E2EE/NCNetworkingE2EEUpload.swift b/iOSClient/Networking/E2EE/NCNetworkingE2EEUpload.swift index fba8c37720..fd46053c15 100644 --- a/iOSClient/Networking/E2EE/NCNetworkingE2EEUpload.swift +++ b/iOSClient/Networking/E2EE/NCNetworkingE2EEUpload.swift @@ -25,6 +25,7 @@ import NextcloudKit import CFNetwork import Alamofire import Foundation +import JGProgressHUD protocol uploadE2EEDelegate: AnyObject { func start() @@ -38,6 +39,8 @@ extension uploadE2EEDelegate { class NCNetworkingE2EEUpload: NSObject { + let hud = JGProgressHUD() + func upload(metadata: tableMetadata, uploadE2EEDelegate: uploadE2EEDelegate? = nil) async -> NKError { var metadata = metadata @@ -63,7 +66,7 @@ class NCNetworkingE2EEUpload: NSObject { // ENCRYPT FILE // - if NCEndToEndEncryption.sharedManager()?.encryptFile(metadata.fileNameView, fileNameIdentifier: metadata.fileName, directory: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), key: &key, initializationVector: &initializationVector, authenticationTag: &authenticationTag) == false { + if NCEndToEndEncryption.sharedManager()?.encryptFile(metadata.fileNameView, fileNameIdentifier: metadata.fileName, directory: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId), key: &key, initializationVector: &initializationVector, authenticationTag: &authenticationTag) == false { return NKError(errorCode: NCGlobal.shared.errorE2EEEncryptFile, errorDescription: NSLocalizedString("_e2e_error_", comment: "")) } guard let key = key as? String, let initializationVector = initializationVector as? String else { @@ -123,10 +126,23 @@ class NCNetworkingE2EEUpload: NSObject { return NKError(errorCode: NCGlobal.shared.errorE2EELock, errorDescription: NSLocalizedString("_e2e_error_", comment: "")) } + // HUD + // +#if !EXTENSION + DispatchQueue.main.async { + guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let hudView = appDelegate.window?.rootViewController?.view else { + return + } + self.hud.textLabel.text = NSLocalizedString("_wait_file_preparation_", comment: "") + self.hud.show(in: hudView) + } +#endif + // SEND NEW METADATA // let sendE2eeError = await sendE2ee(e2eToken: e2eToken, fileId: fileId) guard sendE2eeError == .success else { + DispatchQueue.main.async { self.hud.dismiss() } NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp)) NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "fileName": metadata.fileName, "ocIdTemp": ocIdTemp, "error": sendE2eeError]) await NCNetworkingE2EE.shared.unlock(account: metadata.account, serverUrl: metadata.serverUrl) @@ -143,14 +159,14 @@ class NCNetworkingE2EEUpload: NSObject { if let afError = resultsSendFile.afError, afError.isExplicitlyCancelledError { - CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId)) NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "fileName": metadata.fileName, "ocIdTemp": ocIdTemp, "error": resultsSendFile.error]) } else if resultsSendFile.error == .success, let ocId = resultsSendFile.ocId { NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) - NCUtilityFileSystem.shared.moveFileInBackground(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId)) + NCUtilityFileSystem.shared.moveFileInBackground(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId), toPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId)) metadata.date = resultsSendFile.date ?? NSDate() metadata.etag = resultsSendFile.etag ?? "" @@ -181,9 +197,11 @@ class NCNetworkingE2EEUpload: NSObject { private func sendFile(metadata: tableMetadata, e2eToken: String, uploadE2EEDelegate: uploadE2EEDelegate? = nil) async -> (ocId: String?, etag: String?, date: NSDate?, afError: AFError?, error: NKError) { if metadata.chunk > 0 { - return await withCheckedContinuation({ continuation in NCNetworking.shared.uploadChunkFile(metadata: metadata, withUploadComplete: false, addCustomHeaders: ["e2e-token": e2eToken]) { +#if !EXTENSION + DispatchQueue.main.async { self.hud.dismiss() } +#endif uploadE2EEDelegate?.start() } progressHandler: { totalBytesExpected, totalBytes, fractionCompleted in uploadE2EEDelegate?.uploadE2EEProgress(totalBytesExpected, totalBytes, fractionCompleted) @@ -194,9 +212,12 @@ class NCNetworkingE2EEUpload: NSObject { } else { - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)! + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName) return await withCheckedContinuation({ continuation in NCNetworking.shared.uploadFile(metadata: metadata, fileNameLocalPath: fileNameLocalPath, withUploadComplete: false, addCustomHeaders: ["e2e-token": e2eToken]) { +#if !EXTENSION + DispatchQueue.main.async { self.hud.dismiss() } +#endif uploadE2EEDelegate?.start() } progressHandler: { totalBytesExpected, totalBytes, fractionCompleted in uploadE2EEDelegate?.uploadE2EEProgress(totalBytesExpected, totalBytes, fractionCompleted) diff --git a/iOSClient/Networking/NCAutoUpload.swift b/iOSClient/Networking/NCAutoUpload.swift index 39869e28f1..d2bf2139a7 100644 --- a/iOSClient/Networking/NCAutoUpload.swift +++ b/iOSClient/Networking/NCAutoUpload.swift @@ -117,7 +117,7 @@ class NCAutoUpload: NSObject { var serverUrl: String = "" let fileName = CCUtility.createFileName(asset.originalFilename as String, fileDate: assetDate, fileType: assetMediaType, keyFileName: NCGlobal.shared.keyFileNameAutoUploadMask, keyFileNameType: NCGlobal.shared.keyFileNameAutoUploadType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginalAutoUpload, forcedNewFileName: false)! - if asset.mediaSubtypes.contains(.photoLive) && CCUtility.getLivePhoto() { + if asset.mediaSubtypes.contains(.photoLive), NCKeychain().livePhoto { livePhoto = true } @@ -151,7 +151,7 @@ class NCAutoUpload: NSObject { var fileNameSearchMetadata = fileName let ext = (fileNameSearchMetadata as NSString).pathExtension.uppercased() - if ext == "HEIC" && CCUtility.getFormatCompatibility() { + if ext == "HEIC", NCKeychain().formatCompatibility { fileNameSearchMetadata = (fileNameSearchMetadata as NSString).deletingPathExtension + ".jpg" } diff --git a/iOSClient/Networking/NCNetworking.swift b/iOSClient/Networking/NCNetworking.swift index 0a7e3ea45d..0d0e07fe17 100644 --- a/iOSClient/Networking/NCNetworking.swift +++ b/iOSClient/Networking/NCNetworking.swift @@ -27,6 +27,7 @@ import NextcloudKit import Alamofire import Photos import Queuer +import JGProgressHUD @objc public protocol NCNetworkingDelegate { @objc optional func downloadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) @@ -173,7 +174,7 @@ class NCNetworking: NSObject, NKCommonDelegate { public func checkTrustedChallenge(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { let protectionSpace: URLProtectionSpace = challenge.protectionSpace - let directoryCertificate = CCUtility.getDirectoryCerificates()! + let directoryCertificate = NCUtilityFileSystem.shared.directoryCertificates let host = challenge.protectionSpace.host let certificateSavedPath = directoryCertificate + "/" + host + ".der" var isTrusted: Bool @@ -214,7 +215,7 @@ class NCNetworking: NSObject, NKCommonDelegate { func writeCertificate(host: String) { - let directoryCertificate = CCUtility.getDirectoryCerificates()! + let directoryCertificate = NCUtilityFileSystem.shared.directoryCertificates let certificateAtPath = directoryCertificate + "/" + host + ".tmp" let certificateToPath = directoryCertificate + "/" + host + ".der" @@ -293,12 +294,12 @@ class NCNetworking: NSObject, NKCommonDelegate { completion: @escaping (_ afError: AFError?, _ error: NKError) -> Void) { guard !metadata.isInTransfer else { return completion(nil, NKError()) } - if checkfileProviderStorageExists, CCUtility.fileProviderStorageExists(metadata) { + if checkfileProviderStorageExists, NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { return completion(nil, NKError()) } let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)! + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName) if NCManageDatabase.shared.getMetadataFromOcId(metadata.ocId) == nil { NCManageDatabase.shared.addMetadata(tableMetadata.init(value: metadata)) @@ -357,7 +358,7 @@ class NCNetworking: NSObject, NKCommonDelegate { #if !EXTENSION func downloadAvatar(user: String, dispalyName: String?, fileName: String, cell: NCCellProtocol, view: UIView?, cellImageView: UIImageView?) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } - let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName + let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName if let image = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) { cellImageView?.image = image @@ -382,6 +383,7 @@ class NCNetworking: NSObject, NKCommonDelegate { progressHandler: @escaping (_ totalBytesExpected: Int64, _ totalBytes: Int64, _ fractionCompleted: Double) -> Void = { _, _, _ in }, completion: @escaping (_ error: NKError) -> Void = { _ in }) { + let hud = JGProgressHUD() let metadata = tableMetadata.init(value: metadata) NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Upload file \(metadata.fileNameView) with Identifier \(metadata.assetLocalIdentifier) with size \(metadata.size) [CHUNK \(metadata.chunk), E2EE \(metadata.isDirectoryE2EE)]") @@ -393,11 +395,24 @@ class NCNetworking: NSObject, NKCommonDelegate { } #endif } else if metadata.chunk > 0 { - uploadChunkFile(metadata: metadata, start: start, progressHandler: progressHandler) { _, _, _, error in +#if !EXTENSION + DispatchQueue.main.async { + guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let hudView = appDelegate.window?.rootViewController?.view else { + return completion(.success) + } + hud.textLabel.text = NSLocalizedString("_wait_file_preparation_", comment: "") + hud.show(in: hudView) + } +#endif + uploadChunkFile(metadata: metadata) { +#if !EXTENSION + DispatchQueue.main.async { hud.dismiss() } +#endif + } completion: { _, _, _, error in completion(error) } } else if metadata.session == NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload { - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) uploadFile(metadata: metadata, fileNameLocalPath: fileNameLocalPath, start: start, progressHandler: progressHandler) { _, _, _, _, _, _, _, error in completion(error) } @@ -464,8 +479,8 @@ class NCNetworking: NSObject, NKCommonDelegate { progressHandler: @escaping (_ totalBytesExpected: Int64, _ totalBytes: Int64, _ fractionCompleted: Double) -> Void = { _, _, _ in }, completion: @escaping (_ account: String, _ file: NKFile?, _ afError: AFError?, _ error: NKError) -> Void) { - let directory = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)! - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let directory = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId) + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) let chunkFolder = NCManageDatabase.shared.getChunkFolder(account: metadata.account, ocId: metadata.ocId) let filesChunk = NCManageDatabase.shared.getChunks(account: metadata.account, ocId: metadata.ocId) var uploadTask: URLSessionTask? @@ -567,7 +582,7 @@ class NCNetworking: NSObject, NKCommonDelegate { var session: URLSession? let metadata = tableMetadata.init(value: metadata) let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) if metadata.session == sessionIdentifierBackground || metadata.session == sessionIdentifierBackgroundExtension { session = sessionManagerBackground @@ -633,7 +648,7 @@ class NCNetworking: NSObject, NKCommonDelegate { metadata.status = NCGlobal.shared.metadataStatusNormal // Delete Asset on Photos album - if CCUtility.getRemovePhotoCameraRoll() && !metadata.assetLocalIdentifier.isEmpty { + if NCKeychain().removePhotoCameraRoll, !metadata.assetLocalIdentifier.isEmpty { metadata.deleteAssetLocalIdentifier = true } @@ -641,10 +656,10 @@ class NCNetworking: NSObject, NKCommonDelegate { NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp)) if selector == NCGlobal.shared.selectorUploadFileNODelete { - NCUtilityFileSystem.shared.moveFile(atPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId)) + NCUtilityFileSystem.shared.moveFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocIdTemp), toPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId)) NCManageDatabase.shared.addLocalFile(metadata: metadata) } else { - NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp)) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocIdTemp)) } NextcloudKit.shared.nkCommonInstance.writeLog("[SUCCESS] Upload complete " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)") @@ -654,7 +669,7 @@ class NCNetworking: NSObject, NKCommonDelegate { if error.errorCode == NSURLErrorCancelled || error.errorCode == NCGlobal.shared.errorRequestExplicityCancelled { - CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId)) NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account]) @@ -664,21 +679,18 @@ class NCNetworking: NSObject, NKCommonDelegate { let newFileName = NCUtilityFileSystem.shared.createFileName(metadata.fileName, serverUrl: metadata.serverUrl, account: metadata.account) let alertController = UIAlertController(title: error.errorDescription, message: NSLocalizedString("_change_upload_filename_", comment: ""), preferredStyle: .alert) alertController.addAction(UIAlertAction(title: String(format: NSLocalizedString("_save_file_as_", comment: ""), newFileName), style: .default, handler: { _ in - let atpath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileName - let toPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + newFileName + let atpath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileName + let toPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + newFileName NCUtilityFileSystem.shared.moveFile(atPath: atpath, toPath: toPath) NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, newFileName: newFileName, session: nil, sessionError: "", sessionSelector: nil, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusWaitUpload, errorCode: error.errorCode) })) alertController.addAction(UIAlertAction(title: NSLocalizedString("_discard_changes_", comment: ""), style: .destructive, handler: { _ in - CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId)) NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account]) })) - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! appDelegate.window?.rootViewController?.present(alertController, animated: true) } #endif @@ -756,17 +768,11 @@ class NCNetworking: NSObject, NKCommonDelegate { // sessionIdentifierBackgroundWWan: String = "com.nextcloud.session.upload.backgroundWWan" // sessionIdentifierBackgroundExtension: String = "com.nextcloud.session.upload.extension" - func cancelSessions(inBackground: Bool) { - Task { - await cancel(inBackground: inBackground) - } - } - - func cancel(inBackground: Bool) async { + func cancel(inBackground: Bool) { #if !EXTENSION - if let appDelegate = await UIApplication.shared.delegate as? AppDelegate { - await appDelegate.cancelAllQueue() + if let appDelegate = UIApplication.shared.delegate as? AppDelegate { + appDelegate.cancelAllQueue() } #endif @@ -781,12 +787,12 @@ class NCNetworking: NSObject, NKCommonDelegate { // DOWNLOAD for metadata in metadatasDownload { - CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId)) NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal, errorCode: 0) } // UPLOAD for metadata in metadatasUpload { - CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId)) NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) } @@ -794,26 +800,27 @@ class NCNetworking: NSObject, NKCommonDelegate { // BACKGROUND for metadata in metadatasUploadBackground { - CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId)) NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) } - let tasksBackground = await NCNetworking.shared.sessionManagerBackground.tasks - for task in tasksBackground.1 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask]) - task.cancel() - } - let tasksBackgroundWWan = await NCNetworking.shared.sessionManagerBackgroundWWan.tasks - for task in tasksBackgroundWWan.1 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask]) - task.cancel() + Task { + let tasksBackground = await NCNetworking.shared.sessionManagerBackground.tasks + for task in tasksBackground.1 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask]) + task.cancel() + } + let tasksBackgroundWWan = await NCNetworking.shared.sessionManagerBackgroundWWan.tasks + for task in tasksBackgroundWWan.1 { // ([URLSessionDataTask], [URLSessionUploadTask], [URLSessionDownloadTask]) + task.cancel() + } + NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource) } - - NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource) } func cancel(metadata: tableMetadata) async { - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! - CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)) + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId)) // No session found if metadata.session.isEmpty { @@ -870,7 +877,7 @@ class NCNetworking: NSObject, NKCommonDelegate { NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", - showHiddenFiles: CCUtility.getShowHiddenFiles(), + showHiddenFiles: NCKeychain().showHiddenFiles, includeHiddenFiles: NCGlobal.shared.includeHiddenFiles, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, files, _, error in @@ -902,7 +909,7 @@ class NCNetworking: NSObject, NKCommonDelegate { } } - func readFile(serverUrlFileName: String, showHiddenFiles: Bool = CCUtility.getShowHiddenFiles(), queue: DispatchQueue = NextcloudKit.shared.nkCommonInstance.backgroundQueue, completion: @escaping (_ account: String, _ metadata: tableMetadata?, _ error: NKError) -> Void) { + func readFile(serverUrlFileName: String, showHiddenFiles: Bool = NCKeychain().showHiddenFiles, queue: DispatchQueue = NextcloudKit.shared.nkCommonInstance.backgroundQueue, completion: @escaping (_ account: String, _ metadata: tableMetadata?, _ error: NKError) -> Void) { let options = NKRequestOptions(queue: queue) @@ -967,7 +974,7 @@ class NCNetworking: NSObject, NKCommonDelegate { #if !EXTENSION NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "infinity", - showHiddenFiles: CCUtility.getShowHiddenFiles(), + showHiddenFiles: NCKeychain().showHiddenFiles, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, files, _, error in if error == .success { @@ -1000,7 +1007,7 @@ class NCNetworking: NSObject, NKCommonDelegate { NextcloudKit.shared.searchLiteral(serverUrl: urlBase.urlBase, depth: "infinity", literal: literal, - showHiddenFiles: CCUtility.getShowHiddenFiles(), + showHiddenFiles: NCKeychain().showHiddenFiles, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, files, _, error in guard error == .success else { @@ -1190,7 +1197,7 @@ class NCNetworking: NSObject, NKCommonDelegate { private func createFolderPlain(fileName: String, serverUrl: String, account: String, urlBase: String, overwrite: Bool, withPush: Bool, completion: @escaping (_ error: NKError) -> Void) { - var fileNameFolder = CCUtility.removeForbiddenCharactersServer(fileName)! + var fileNameFolder = NCUtility.shared.removeForbiddenCharacters(fileName) if !overwrite { fileNameFolder = NCUtilityFileSystem.shared.createFileName(fileNameFolder, serverUrl: serverUrl, account: account) @@ -1311,11 +1318,11 @@ class NCNetworking: NSObject, NKCommonDelegate { NCManageDatabase.shared.deleteVideo(metadata: metadata) NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) - NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId)) if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) { NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadataLivePhoto.ocId)) - NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadataLivePhoto.ocId)) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadataLivePhoto.ocId)) } } return NKError() @@ -1368,7 +1375,7 @@ class NCNetworking: NSObject, NKCommonDelegate { if result.error == .success || result.error.errorCode == NCGlobal.shared.errorResourceNotFound { do { - try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)) + try FileManager.default.removeItem(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId)) } catch { } NCManageDatabase.shared.deleteVideo(metadata: metadata) @@ -1376,7 +1383,7 @@ class NCNetworking: NSObject, NKCommonDelegate { NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) if metadata.directory { - NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account) + NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: NCUtilityFileSystem.shared.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account) } } @@ -1402,7 +1409,7 @@ class NCNetworking: NSObject, NKCommonDelegate { private func favoriteMetadataPlain(_ metadata: tableMetadata, completion: @escaping (_ error: NKError) -> Void) { - let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)! + let fileName = NCUtilityFileSystem.shared.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId) let favorite = !metadata.favorite let ocId = metadata.ocId @@ -1483,9 +1490,7 @@ class NCNetworking: NSObject, NKCommonDelegate { if !metadata.permissions.isEmpty && !permission { return completion(NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_modify_file_")) } - guard let fileNameNew = CCUtility.removeForbiddenCharactersServer(fileNameNew) else { - return completion(NKError()) - } + let fileNameNew = NCUtility.shared.removeForbiddenCharacters(fileNameNew) if fileNameNew.isEmpty || fileNameNew == metadata.fileNameView { return completion(NKError()) } @@ -1502,8 +1507,8 @@ class NCNetworking: NSObject, NKCommonDelegate { if metadata.directory { - let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)! - let serverUrlTo = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: fileNameNew)! + let serverUrl = NCUtilityFileSystem.shared.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) + let serverUrlTo = NCUtilityFileSystem.shared.stringAppendServerUrl(metadata.serverUrl, addFileName: fileNameNew) if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) { NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, serverUrlTo: serverUrlTo, etag: "", ocId: nil, fileId: nil, encrypted: directory.e2eEncrypted, richWorkspace: nil, account: metadata.account) @@ -1516,17 +1521,15 @@ class NCNetworking: NSObject, NKCommonDelegate { if ext != extNew { - if let path = CCUtility.getDirectoryProviderStorageOcId(ocId) { - NCUtilityFileSystem.shared.deleteFile(filePath: path) - } + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId)) NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced) } else { NCManageDatabase.shared.setLocalFile(ocId: ocId, fileName: fileNameNew, etag: nil) // Move file system - let atPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + metadata.fileName - let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + fileNameNew + let atPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId) + "/" + metadata.fileName + let toPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId) + "/" + fileNameNew do { try FileManager.default.moveItem(atPath: atPath, toPath: toPath) } catch { } @@ -1570,7 +1573,7 @@ class NCNetworking: NSObject, NKCommonDelegate { let result = await NextcloudKit.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) if result.error == .success { if metadata.directory { - NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: result.account) + NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: NCUtilityFileSystem.shared.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: result.account) } NCManageDatabase.shared.moveMetadata(ocId: metadata.ocId, serverUrlTo: serverUrlTo) } @@ -1617,8 +1620,8 @@ class NCNetworking: NSObject, NKCommonDelegate { } else { completition(URL(string: metadata.url), true, .success) } - } else if CCUtility.fileProviderStorageExists(metadata) { - completition(URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)), false, .success) + } else if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { + completition(URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)), false, .success) } else { NextcloudKit.shared.getDirectDownload(fileId: metadata.fileId) { _, url, _, error in if error == .success && url != nil { diff --git a/iOSClient/Networking/NCNetworkingCheckRemoteUser.swift b/iOSClient/Networking/NCNetworkingCheckRemoteUser.swift index cc83771d23..6338004cb6 100644 --- a/iOSClient/Networking/NCNetworkingCheckRemoteUser.swift +++ b/iOSClient/Networking/NCNetworkingCheckRemoteUser.swift @@ -28,11 +28,12 @@ class NCNetworkingCheckRemoteUser { func checkRemoteUser(account: String, error: NKError) { + let token = NCKeychain().getPassword(account: account) guard let tableAccount = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)), - let token = CCUtility.getPassword(account), !token.isEmpty, + !token.isEmpty, let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } - NCNetworking.shared.cancelSessions(inBackground: true) + NCNetworking.shared.cancel(inBackground: true) if NCGlobal.shared.capabilityServerVersionMajor >= NCGlobal.shared.nextcloudVersion17 { @@ -51,7 +52,7 @@ class NCNetworkingCheckRemoteUser { let description = String.localizedStringWithFormat(NSLocalizedString("_error_check_remote_user_", comment: ""), tableAccount.user, tableAccount.urlBase) let error = NKError(errorCode: error.errorCode, errorDescription: description) NCContentPresenter.shared.showError(error: error, priority: .max) - CCUtility.setPassword(account, password: nil) + NCKeychain().setPassword(account: account, password: nil) NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Password removed.") } } @@ -63,7 +64,7 @@ class NCNetworkingCheckRemoteUser { let description = String.localizedStringWithFormat(NSLocalizedString("_error_check_remote_user_", comment: ""), tableAccount.user, tableAccount.urlBase) let error = NKError(errorCode: error.errorCode, errorDescription: description) NCContentPresenter.shared.showError(error: error, priority: .max) - CCUtility.setPassword(account, password: nil) + NCKeychain().setPassword(account: account, password: nil) } } } diff --git a/iOSClient/Networking/NCNetworkingProcessUpload.swift b/iOSClient/Networking/NCNetworkingProcessUpload.swift index b03b9a7041..14cebab08e 100644 --- a/iOSClient/Networking/NCNetworkingProcessUpload.swift +++ b/iOSClient/Networking/NCNetworkingProcessUpload.swift @@ -33,10 +33,7 @@ class NCNetworkingProcessUpload: NSObject { return instance }() - // swiftlint:disable force_cast - private let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! private var notificationToken: NotificationToken? private var timerProcess: Timer? private var pauseProcess: Bool = false @@ -274,9 +271,8 @@ class NCNetworkingProcessUpload: NSObject { // remove leaning upload share extension let metadatasUploadShareExtension = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "session == %@ AND sessionSelector == %@", NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload, NCGlobal.shared.selectorUploadFileShareExtension)) for metadata in metadatasUploadShareExtension { - let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)! NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) - NCUtilityFileSystem.shared.deleteFile(filePath: path) + NCUtilityFileSystem.shared.removeFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId)) } // verify metadataStatusInUpload (BACKGROUND) @@ -328,7 +324,7 @@ class NCNetworkingProcessUpload: NSObject { NCNetworking.shared.transferInForegorund = nil } for metadata in metadatasUploading { - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) if NCNetworking.shared.uploadRequest[fileNameLocalPath] == nil { NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: "", sessionSelector: nil, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusWaitUpload, errorCode: nil) } diff --git a/iOSClient/Networking/NCService.swift b/iOSClient/Networking/NCService.swift index 8dccd34e03..a868ffb783 100644 --- a/iOSClient/Networking/NCService.swift +++ b/iOSClient/Networking/NCService.swift @@ -32,9 +32,7 @@ class NCService: NSObject { return instance }() - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! // MARK: - @@ -139,7 +137,7 @@ class NCService: NSObject { func synchronize() { NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] start synchronize Favorite") - NextcloudKit.shared.listingFavorites(showHiddenFiles: CCUtility.getShowHiddenFiles(), + NextcloudKit.shared.listingFavorites(showHiddenFiles: NCKeychain().showHiddenFiles, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, files, _, error in guard error == .success else { return } @@ -155,7 +153,7 @@ class NCService: NSObject { func getAvatar() { let fileName = appDelegate.userBaseUrl + "-" + self.appDelegate.user + ".png" - let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName + let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName let etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag NextcloudKit.shared.downloadAvatar(user: appDelegate.userId, @@ -271,7 +269,7 @@ class NCService: NSObject { } if let fileName = fileNameToWrite, let image = imageData { do { - let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png" + let fileNamePath = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName + ".png" try image.pngData()?.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic) } catch { } } diff --git a/iOSClient/Notification/NCNotification.swift b/iOSClient/Notification/NCNotification.swift index ce8c306d57..3a76500caf 100644 --- a/iOSClient/Notification/NCNotification.swift +++ b/iOSClient/Notification/NCNotification.swift @@ -29,10 +29,7 @@ import JGProgressHUD class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmptyDataSetDelegate { - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! var notifications: [NKNotifications] = [] var emptyDataSet: NCEmptyDataSet? var isReloadDataSourceNetworkInProgress: Bool = false @@ -128,7 +125,7 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty var image: UIImage? if let urlIcon = urlIcon { - let pathFileName = String(CCUtility.getDirectoryUserData()) + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png" + let pathFileName = NCUtilityFileSystem.shared.directoryUserData + "/" + urlIcon.deletingPathExtension().lastPathComponent + ".png" image = UIImage(contentsOfFile: pathFileName) } @@ -148,7 +145,7 @@ class NCNotification: UITableViewController, NCNotificationCellDelegate, NCEmpty cell.avatarLeadingMargin.constant = 50 let fileName = appDelegate.userBaseUrl + "-" + user + ".png" - let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName + let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName if let image = UIImage(contentsOfFile: fileNameLocalPath) { cell.avatar.image = image diff --git a/iOSClient/PushNotification/NCPushNotification.m b/iOSClient/PushNotification/NCPushNotification.m index 8c188de91a..9b9b44a15e 100644 --- a/iOSClient/PushNotification/NCPushNotification.m +++ b/iOSClient/PushNotification/NCPushNotification.m @@ -54,8 +54,8 @@ - (void)pushNotification for (tableAccount *result in [[NCManageDatabase shared] getAllAccount]) { - NSString *token = [CCUtility getPushNotificationToken:result.account]; - + NSString *token = [[[NCKeychain alloc] init] getPushNotificationTokenWithAccount:result.account]; + if (![token isEqualToString:self.pushKitToken]) { if (token != nil) { // unsubscribing + subscribing @@ -73,8 +73,8 @@ - (void)applicationdidReceiveRemoteNotification:(NSDictionary *)userInfo fetchCo if (message) { NSArray *results = [[NCManageDatabase shared] getAllAccount]; for (tableAccount *result in results) { - if ([CCUtility getPushNotificationPrivateKey:result.account]) { - NSData *decryptionKey = [CCUtility getPushNotificationPrivateKey:result.account]; + if ([[[NCKeychain alloc] init] getPushNotificationPrivateKeyWithAccount:result.account]) { + NSData *decryptionKey = [[[NCKeychain alloc] init] getPushNotificationPrivateKeyWithAccount:result.account]; NSString *decryptedMessage = [[NCPushNotificationEncryption shared] decryptPushNotification:message withDevicePrivateKey:decryptionKey]; if (decryptedMessage) { NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding]; @@ -102,11 +102,11 @@ - (void)subscribingNextcloudServerPushNotification:(NSString *)account urlBase:( [[NCPushNotificationEncryption shared] generatePushNotificationsKeyPair:account]; NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:self.pushKitToken]; - NSData *pushPublicKey = [CCUtility getPushNotificationPublicKey:account]; + NSData *pushPublicKey = [[[NCKeychain alloc] init] getPushNotificationPublicKeyWithAccount:account]; NSString *pushDevicePublicKey = [[NSString alloc] initWithData:pushPublicKey encoding:NSUTF8StringEncoding]; NSString *proxyServerPath = [NCBrandOptions shared].pushNotificationServerProxy; - [[NextcloudKit shared] subscribingPushNotificationWithServerUrl:urlBase account:account user:user password:[CCUtility getPassword:account] pushTokenHash:pushTokenHash devicePublicKey:pushDevicePublicKey proxyServerUrl:proxyServerPath customUserAgent:nil addCustomHeaders:nil queue:dispatch_get_main_queue() completion:^(NSString *account, NSString *deviceIdentifier, NSString *signature, NSString *publicKey, NSData *data, NKError *error) { + [[NextcloudKit shared] subscribingPushNotificationWithServerUrl:urlBase account:account user:user password:[[[NCKeychain alloc] init] getPasswordWithAccount:account] pushTokenHash:pushTokenHash devicePublicKey:pushDevicePublicKey proxyServerUrl:proxyServerPath customUserAgent:nil addCustomHeaders:nil queue:dispatch_get_main_queue() completion:^(NSString *account, NSString *deviceIdentifier, NSString *signature, NSString *publicKey, NSData *data, NKError *error) { if (error == NKError.success) { NSString *userAgent = [NSString stringWithFormat:@"%@ (Strict VoIP)", [[NCBrandOptions shared] getUserAgent]]; [[NextcloudKit shared] subscribingPushProxyWithProxyServerUrl:proxyServerPath pushToken:self.pushKitToken deviceIdentifier:deviceIdentifier signature:signature publicKey:publicKey userAgent:userAgent queue:dispatch_get_main_queue() completion:^(NKError *error) { @@ -114,10 +114,10 @@ - (void)subscribingNextcloudServerPushNotification:(NSString *)account urlBase:( [[[NextcloudKit shared] nkCommonInstance] writeLog:@"[INFO] Subscribed to Push Notification server & proxy successfully"]; - [CCUtility setPushNotificationToken:account token:self.pushKitToken]; - [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:deviceIdentifier]; - [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:signature]; - [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:publicKey]; + [[[NCKeychain alloc] init] setPushNotificationTokenWithAccount:account token:self.pushKitToken]; + [[[NCKeychain alloc] init] setPushNotificationDeviceIdentifierWithAccount:account deviceIdentifier:deviceIdentifier]; + [[[NCKeychain alloc] init] setPushNotificationDeviceIdentifierSignatureWithAccount:account deviceIdentifierSignature:signature]; + [[[NCKeychain alloc] init] setPushNotificationSubscribingPublicKeyWithAccount:account publicKey:publicKey]; } }]; } @@ -128,11 +128,11 @@ - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account urlBase { if (appDelegate.account == nil || appDelegate.account.length == 0) { return; } - NSString *deviceIdentifier = [CCUtility getPushNotificationDeviceIdentifier:account]; - NSString *signature = [CCUtility getPushNotificationDeviceIdentifierSignature:account]; - NSString *publicKey = [CCUtility getPushNotificationSubscribingPublicKey:account]; + NSString *deviceIdentifier = [[[NCKeychain alloc] init] getPushNotificationDeviceIdentifierWithAccount:account]; + NSString *signature = [[[NCKeychain alloc] init] getPushNotificationDeviceIdentifierSignatureWithAccount:account]; + NSString *publicKey = [[[NCKeychain alloc] init] getPushNotificationSubscribingPublicKeyWithAccount:account]; - [[NextcloudKit shared] unsubscribingPushNotificationWithServerUrl:urlBase account:account user:user password:[CCUtility getPassword:account] customUserAgent:nil addCustomHeaders:nil queue:dispatch_get_main_queue() completion:^(NSString *account, NKError *error) { + [[NextcloudKit shared] unsubscribingPushNotificationWithServerUrl:urlBase account:account user:user password:[[[NCKeychain alloc] init] getPasswordWithAccount:account] customUserAgent:nil addCustomHeaders:nil queue:dispatch_get_main_queue() completion:^(NSString *account, NKError *error) { if (error == NKError.success) { NSString *userAgent = [NSString stringWithFormat:@"%@ (Strict VoIP)", [[NCBrandOptions shared] getUserAgent]]; NSString *proxyServerPath = [NCBrandOptions shared].pushNotificationServerProxy; @@ -141,13 +141,13 @@ - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account urlBase [[[NextcloudKit shared] nkCommonInstance] writeLog:@"[INFO] Unsubscribed to Push Notification server & proxy successfully."]; - [CCUtility setPushNotificationPublicKey:account data:nil]; - [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:nil]; - [CCUtility setPushNotificationPrivateKey:account data:nil]; - [CCUtility setPushNotificationToken:account token:nil]; - [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:nil]; - [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil]; - + [[[NCKeychain alloc] init] setPushNotificationPublicKeyWithAccount:account data:nil]; + [[[NCKeychain alloc] init] setPushNotificationSubscribingPublicKeyWithAccount:account publicKey:nil]; + [[[NCKeychain alloc] init] setPushNotificationPrivateKeyWithAccount:account data:nil]; + [[[NCKeychain alloc] init] setPushNotificationTokenWithAccount:account token:nil]; + [[[NCKeychain alloc] init] setPushNotificationDeviceIdentifierWithAccount:account deviceIdentifier:nil]; + [[[NCKeychain alloc] init] setPushNotificationDeviceIdentifierSignatureWithAccount:account deviceIdentifierSignature:nil]; + if (self.pushKitToken != nil && subscribing) { [self subscribingNextcloudServerPushNotification:account urlBase:urlBase user:user]; } diff --git a/iOSClient/PushNotification/NCPushNotificationEncryption.h b/iOSClient/PushNotification/NCPushNotificationEncryption.h index 6c476d0f7a..6d20a79a12 100644 --- a/iOSClient/PushNotification/NCPushNotificationEncryption.h +++ b/iOSClient/PushNotification/NCPushNotificationEncryption.h @@ -23,7 +23,7 @@ // This code derived from : Nextcloud Talk - NCSettingsController Created by Ivan Sein on 26.06.17. Copyright © 2017 struktur AG. All rights reserved. // -#import +#import @interface NCPushNotificationEncryption : NSObject diff --git a/iOSClient/PushNotification/NCPushNotificationEncryption.m b/iOSClient/PushNotification/NCPushNotificationEncryption.m index 119c3962bf..91d96fe3a5 100644 --- a/iOSClient/PushNotification/NCPushNotificationEncryption.m +++ b/iOSClient/PushNotification/NCPushNotificationEncryption.m @@ -24,10 +24,9 @@ // #import "NCPushNotificationEncryption.h" - +#import "NCBridgeSwift.h" #import #import - #import "NCEndToEndEncryption.h" #import "CCUtility.h" @@ -75,7 +74,8 @@ - (BOOL)generatePushNotificationsKeyPair:(NSString *)account BIO_read(publicKeyBIO, keyBytes, len); NSData *ncPNPublicKey = [NSData dataWithBytes:keyBytes length:len]; - [CCUtility setPushNotificationPublicKey:account data:ncPNPublicKey]; + + [[[NCKeychain alloc] init] setPushNotificationPublicKeyWithAccount:account data:ncPNPublicKey]; NSLog(@"Push Notifications Key Pair generated: \n%@", [[NSString alloc] initWithData:ncPNPublicKey encoding:NSUTF8StringEncoding]); // PrivateKey @@ -87,7 +87,7 @@ - (BOOL)generatePushNotificationsKeyPair:(NSString *)account BIO_read(privateKeyBIO, keyBytes, len); NSData *ncPNPrivateKey = [NSData dataWithBytes:keyBytes length:len]; - [CCUtility setPushNotificationPrivateKey:account data:ncPNPrivateKey]; + [[[NCKeychain alloc] init] setPushNotificationPrivateKeyWithAccount:account data:ncPNPrivateKey]; RSA_free(rsa); BN_free(bigNumber); diff --git a/iOSClient/Recent/NCRecent.swift b/iOSClient/Recent/NCRecent.swift index 380d69bac7..49a02c5981 100644 --- a/iOSClient/Recent/NCRecent.swift +++ b/iOSClient/Recent/NCRecent.swift @@ -151,7 +151,7 @@ class NCRecent: NCCollectionViewCommon { NextcloudKit.shared.searchBodyRequest(serverUrl: appDelegate.urlBase, requestBody: requestBody, - showHiddenFiles: CCUtility.getShowHiddenFiles(), + showHiddenFiles: NCKeychain().showHiddenFiles, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, files, _, error in self.isReloadDataSourceNetworkInProgress = false diff --git a/iOSClient/RichWorkspace/NCRichWorkspaceCommon.swift b/iOSClient/RichWorkspace/NCRichWorkspaceCommon.swift index e69bcad6db..870ff3933d 100644 --- a/iOSClient/RichWorkspace/NCRichWorkspaceCommon.swift +++ b/iOSClient/RichWorkspace/NCRichWorkspaceCommon.swift @@ -26,9 +26,7 @@ import NextcloudKit @objc class NCRichWorkspaceCommon: NSObject { - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! @objc func createViewerNextcloudText(serverUrl: String, viewController: UIViewController) { @@ -42,7 +40,7 @@ import NextcloudKit NCActivityIndicator.shared.start(backgroundView: viewController.view) - let fileNamePath = CCUtility.returnFileNamePath(fromFileName: NCGlobal.shared.fileNameRichWorkspace, serverUrl: serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)! + let fileNamePath = NCUtilityFileSystem.shared.getFileNamePath(NCGlobal.shared.fileNameRichWorkspace, serverUrl: serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId) NextcloudKit.shared.NCTextCreateFile(fileNamePath: fileNamePath, editorId: directEditingCreator.editor, creatorId: directEditingCreator.identifier, templateId: "") { account, url, _, error in NCActivityIndicator.shared.stop() @@ -77,7 +75,7 @@ import NextcloudKit NCActivityIndicator.shared.start(backgroundView: viewController.view) - let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)! + let fileNamePath = NCUtilityFileSystem.shared.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId) NextcloudKit.shared.NCTextOpenFile(fileNamePath: fileNamePath, editor: "text") { account, url, _, error in NCActivityIndicator.shared.stop() diff --git a/iOSClient/RichWorkspace/NCViewerRichWorkspace.swift b/iOSClient/RichWorkspace/NCViewerRichWorkspace.swift index 4cbf9dc772..dbcf4763b4 100644 --- a/iOSClient/RichWorkspace/NCViewerRichWorkspace.swift +++ b/iOSClient/RichWorkspace/NCViewerRichWorkspace.swift @@ -29,10 +29,7 @@ import MarkdownKit @IBOutlet weak var textView: UITextView! - // swiftlint:disable force_cast - private let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! private let richWorkspaceCommon = NCRichWorkspaceCommon() private var markdownParser = MarkdownParser() private var textViewColor: UIColor? diff --git a/iOSClient/Scan document/NCDocumentCamera.swift b/iOSClient/Scan document/NCDocumentCamera.swift index 74489f3bb0..f0694d3962 100644 --- a/iOSClient/Scan document/NCDocumentCamera.swift +++ b/iOSClient/Scan document/NCDocumentCamera.swift @@ -54,7 +54,7 @@ class NCDocumentCamera: NSObject, VNDocumentCameraViewControllerDelegate { keyFileNameType: NCGlobal.shared.keyFileNameType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal, forcedNewFileName: true)! - let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName + let fileNamePath = NCUtilityFileSystem.shared.directoryScan + "/" + fileName let image = scan.imageOfPage(at: pageNumber) do { try image.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath)) diff --git a/iOSClient/Scan document/NCScan+CollectionView.swift b/iOSClient/Scan document/NCScan+CollectionView.swift index 6ae419f5ce..84a585897b 100644 --- a/iOSClient/Scan document/NCScan+CollectionView.swift +++ b/iOSClient/Scan document/NCScan+CollectionView.swift @@ -36,7 +36,7 @@ extension NCScan: UICollectionViewDataSource { let cell = (collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as? NCScanCell)! - let fileNamePath = CCUtility.getDirectoryScan() + "/" + itemsSource[indexPath.row] + let fileNamePath = NCUtilityFileSystem.shared.directoryScan + "/" + itemsSource[indexPath.row] guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePath)), var image = UIImage(data: data) else { return cell } @@ -55,8 +55,8 @@ extension NCScan: UICollectionViewDataSource { let buttonPosition: CGPoint = (sender as? UIButton)!.convert(.zero, to: self.collectionViewSource) if let indexPath = self.collectionViewSource.indexPathForItem(at: buttonPosition) { - let fileNameAtPath = CCUtility.getDirectoryScan() + "/" + self.itemsSource[indexPath.row] - CCUtility.removeFile(atPath: fileNameAtPath) + let fileNameAtPath = NCUtilityFileSystem.shared.directoryScan + "/" + self.itemsSource[indexPath.row] + NCUtilityFileSystem.shared.removeFile(atPath: fileNameAtPath) self.itemsSource.remove(at: indexPath.row) self.collectionViewSource.deleteItems(at: [indexPath]) diff --git a/iOSClient/Scan document/NCScan.swift b/iOSClient/Scan document/NCScan.swift index 9d817b1ed2..c86e1bc7c2 100755 --- a/iOSClient/Scan document/NCScan.swift +++ b/iOSClient/Scan document/NCScan.swift @@ -44,14 +44,8 @@ class NCScan: UIViewController, NCScanCellCellDelegate { internal var itemsDestination: [String] = [] internal let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! - private var tipView: EasyTipView? - - enum TypeFilter { - case document - case original - } - internal var filter: TypeFilter = TypeFilter.document + internal var filter: NCGlobal.TypeFilterScanDocument = NCKeychain().typeFilterScanDocument // MARK: - View Life Cycle @@ -81,6 +75,11 @@ class NCScan: UIViewController, NCScanCellCellDelegate { segmentControlFilter.setTitle(NSLocalizedString("_filter_document_", comment: ""), forSegmentAt: 0) segmentControlFilter.setTitle(NSLocalizedString("_filter_original_", comment: ""), forSegmentAt: 1) + if filter == .document { + segmentControlFilter.selectedSegmentIndex = 0 + } else if filter == .original { + segmentControlFilter.selectedSegmentIndex = 1 + } add.setImage(UIImage(systemName: "plus")?.image(color: .label, size: 25), for: .normal) transferDown.setImage(UIImage(systemName: "arrow.down")?.image(color: .label, size: 25), for: .normal) @@ -192,7 +191,7 @@ class NCScan: UIViewController, NCScanCellCellDelegate { for fileName in itemsSource where !itemsDestination.contains(fileName) { - let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName + let fileNamePathAt = NCUtilityFileSystem.shared.directoryScan + "/" + fileName guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePathAt)), let image = UIImage(data: data) else { return } imagesDestination.append(image) @@ -220,6 +219,7 @@ class NCScan: UIViewController, NCScanCellCellDelegate { break } + NCKeychain().typeFilterScanDocument = filter collectionViewDestination.reloadData() } @@ -228,7 +228,7 @@ class NCScan: UIViewController, NCScanCellCellDelegate { itemsSource.removeAll() do { - let atPath = CCUtility.getDirectoryScan()! + let atPath = NCUtilityFileSystem.shared.directoryScan let directoryContents = try FileManager.default.contentsOfDirectory(atPath: atPath) for fileName in directoryContents where fileName.first != "." { itemsSource.append(fileName) @@ -329,7 +329,7 @@ class NCScan: UIViewController, NCScanCellCellDelegate { if collectionView === collectionViewDestination { let fileName = (item.dragItem.localObject as? String)! - let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName + let fileNamePathAt = NCUtilityFileSystem.shared.directoryScan + "/" + fileName guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePathAt)), let image = UIImage(data: data) else { return } @@ -382,7 +382,7 @@ class NCScan: UIViewController, NCScanCellCellDelegate { keyFileNameType: NCGlobal.shared.keyFileNameType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal, forcedNewFileName: true)! - let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName + let fileNamePath = NCUtilityFileSystem.shared.directoryScan + "/" + fileName do { try image.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath), options: .atomic) diff --git a/iOSClient/Scan document/NCUploadScanDocument.swift b/iOSClient/Scan document/NCUploadScanDocument.swift index bb0116186c..c50a5ecd2e 100644 --- a/iOSClient/Scan document/NCUploadScanDocument.swift +++ b/iOSClient/Scan document/NCUploadScanDocument.swift @@ -99,7 +99,7 @@ class NCUploadScanDocument: ObservableObject { func createPDF(metadata: tableMetadata, completion: @escaping (_ error: Bool) -> Void) { DispatchQueue.global().async { - let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let fileNamePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) let pdfData = NSMutableData() if self.password.isEmpty { @@ -127,7 +127,7 @@ class NCUploadScanDocument: ObservableObject { metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath) NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: [metadata], completion: { _ in }) if self.removeAllFiles { - let path = CCUtility.getDirectoryScan()! + let path = NCUtilityFileSystem.shared.directoryScan let filePaths = try FileManager.default.contentsOfDirectory(atPath: path) for filePath in filePaths { try FileManager.default.removeItem(atPath: path + "/" + filePath) @@ -319,7 +319,6 @@ extension NCUploadScanDocument: NCSelectDelegate { func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], indexPath: [IndexPath], overwrite: Bool, copy: Bool, move: Bool) { if let serverUrl = serverUrl { - CCUtility.setDirectoryScanDocument(serverUrl) self.serverUrl = serverUrl } } @@ -345,12 +344,12 @@ extension NCUploadScanDocument: NCCreateFormUploadConflictDelegate { struct UploadScanDocumentView: View { - @State var fileName = CCUtility.createFileNameDate("scan", extension: "") ?? "scan" + @State var fileName = NCUtilityFileSystem.shared.createFileNameDate("scan", ext: "") @State var password: String = "" @State var isSecuredPassword: Bool = true - @State var isTextRecognition: Bool = CCUtility.getTextRecognitionStatus() - @State var quality = CCUtility.getQualityScanDocument() - @State var removeAllFiles: Bool = CCUtility.getDeleteAllScanImages() + @State var isTextRecognition: Bool = NCKeychain().textRecognitionStatus + @State var quality = NCKeychain().qualityScanDocument + @State var removeAllFiles: Bool = NCKeychain().deleteAllScanImages @State var isPresentedSelect = false @State var isPresentedUploadConflict = false @@ -437,7 +436,7 @@ struct UploadScanDocumentView: View { Toggle(NSLocalizedString("_text_recognition_", comment: ""), isOn: $isTextRecognition) .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand))) .onChange(of: isTextRecognition) { newValue in - CCUtility.setTextRecognitionStatus(newValue) + NCKeychain().textRecognitionStatus = newValue } } } @@ -450,8 +449,7 @@ struct UploadScanDocumentView: View { Toggle(NSLocalizedString("_delete_all_scanned_images_", comment: ""), isOn: $removeAllFiles) .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand))) .onChange(of: removeAllFiles) { newValue in - CCUtility.setDeleteAllScanImages(newValue) - + NCKeychain().deleteAllScanImages = newValue } Button(NSLocalizedString("_save_", comment: "")) { @@ -478,7 +476,7 @@ struct UploadScanDocumentView: View { VStack { Slider(value: $quality, in: 0...4, step: 1, onEditingChanged: { touch in if !touch { - CCUtility.setQualityScanDocument(quality) + NCKeychain().qualityScanDocument = quality } }) .accentColor(Color(NCBrandColor.shared.brand)) diff --git a/iOSClient/Select/NCSelect.swift b/iOSClient/Select/NCSelect.swift index 861790e533..52922befe4 100644 --- a/iOSClient/Select/NCSelect.swift +++ b/iOSClient/Select/NCSelect.swift @@ -249,7 +249,7 @@ class NCSelect: UIViewController, UIGestureRecognizerDelegate, UIAdaptivePresent func pushMetadata(_ metadata: tableMetadata) { - guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return } + let serverUrlPush = NCUtilityFileSystem.shared.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) guard let viewController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect else { return } self.serverUrlPush = serverUrlPush @@ -298,17 +298,17 @@ extension NCSelect: UICollectionViewDataSource { // Thumbnail if !metadata.directory { - if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) { - (cell as? NCCellProtocol)?.filePreviewImageView?.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) + if FileManager().fileExists(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) { + (cell as? NCCellProtocol)?.filePreviewImageView?.image = UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) } else { if metadata.iconName.isEmpty { (cell as? NCCellProtocol)?.filePreviewImageView?.image = NCBrandColor.cacheImages.file } else { (cell as? NCCellProtocol)?.filePreviewImageView?.image = UIImage(named: metadata.iconName) } - if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) { + if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!NCUtilityFileSystem.shared.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) { for case let operation as NCCollectionViewDownloadThumbnail in appDelegate.downloadThumbnailQueue.operations where operation.metadata.ocId == metadata.ocId { return } - appDelegate.downloadThumbnailQueue.addOperation(NCCollectionViewDownloadThumbnail(metadata: metadata, cell: (cell as? NCCellProtocol), view: view)) + appDelegate.downloadThumbnailQueue.addOperation(NCCollectionViewDownloadThumbnail(metadata: metadata, cell: (cell as? NCCellProtocol), collectionView: collectionView)) } } } @@ -391,12 +391,12 @@ extension NCSelect: UICollectionViewDataSource { } else { - cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size) + cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + NCUtilityFileSystem.shared.transformedSize(metadata.size) // image local if NCManageDatabase.shared.getTableLocalFile(ocId: metadata.ocId) != nil { cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag - } else if CCUtility.fileProviderStorageExists(metadata) { + } else if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { cell.imageLocal.image = NCBrandColor.cacheImages.local } } diff --git a/iOSClient/Settings/Acknowledgements.rtf b/iOSClient/Settings/Acknowledgements.rtf index 0a8ff4e085..93c804f78d 100644 --- a/iOSClient/Settings/Acknowledgements.rtf +++ b/iOSClient/Settings/Acknowledgements.rtf @@ -1,4 +1,4 @@ -{\rtf1\ansi\ansicpg1252\cocoartf2708 +{\rtf1\ansi\ansicpg1252\cocoartf2757 \cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fswiss\fcharset0 Helvetica-Bold;} {\colortbl;\red255\green255\blue255;} {\*\expandedcolortbl;;} @@ -57,7 +57,7 @@ Copyright (c) 2014-2017 https://realm.io\ __________________________________\ \ -\f1\b UICKeyChainStore +\f1\b KeychainAccess \f0\b0 \ \ MIT License\ diff --git a/iOSClient/Settings/CCAdvanced.m b/iOSClient/Settings/CCAdvanced.m index f2aabfe1b8..dbe608391d 100755 --- a/iOSClient/Settings/CCAdvanced.m +++ b/iOSClient/Settings/CCAdvanced.m @@ -48,7 +48,7 @@ - (void)initializeForm row = [XLFormRowDescriptor formRowDescriptorWithTag:@"showHiddenFiles" rowType:XLFormRowDescriptorTypeBooleanSwitch title:NSLocalizedString(@"_show_hidden_files_", nil)]; row.cellConfigAtConfigure[@"backgroundColor"] = UIColor.secondarySystemGroupedBackgroundColor; - if ([CCUtility getShowHiddenFiles]) row.value = @"1"; + if ([[[NCKeychain alloc] init] showHiddenFiles]) row.value = @"1"; else row.value = @"0"; [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"]; [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"]; @@ -62,7 +62,7 @@ - (void)initializeForm row = [XLFormRowDescriptor formRowDescriptorWithTag:@"formatCompatibility" rowType:XLFormRowDescriptorTypeBooleanSwitch title:NSLocalizedString(@"_format_compatibility_", nil)]; row.cellConfigAtConfigure[@"backgroundColor"] = UIColor.secondarySystemGroupedBackgroundColor; - if ([CCUtility getFormatCompatibility]) row.value = @"1"; + if ([[[NCKeychain alloc] init] formatCompatibility]) row.value = @"1"; else row.value = @"0"; [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"]; [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"]; @@ -70,7 +70,7 @@ - (void)initializeForm row = [XLFormRowDescriptor formRowDescriptorWithTag:@"livePhoto" rowType:XLFormRowDescriptorTypeBooleanSwitch title:NSLocalizedString(@"_upload_mov_livephoto_", nil)]; row.cellConfigAtConfigure[@"backgroundColor"] = UIColor.secondarySystemGroupedBackgroundColor; - if ([CCUtility getLivePhoto]) row.value = @"1"; + if ([[[NCKeychain alloc] init] livePhoto]) row.value = @"1"; else row.value = @"0"; [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"]; [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"]; @@ -78,7 +78,7 @@ - (void)initializeForm row = [XLFormRowDescriptor formRowDescriptorWithTag:@"removePhotoCameraRoll" rowType:XLFormRowDescriptorTypeBooleanSwitch title:NSLocalizedString(@"_remove_photo_CameraRoll_", nil)]; row.cellConfigAtConfigure[@"backgroundColor"] = UIColor.secondarySystemGroupedBackgroundColor; - if ([CCUtility getRemovePhotoCameraRoll]) row.value = @"1"; + if ([[[NCKeychain alloc] init] removePhotoCameraRoll]) row.value = @"1"; else row.value = @0; [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"]; [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"]; @@ -95,7 +95,7 @@ - (void)initializeForm // Disable Files App row = [XLFormRowDescriptor formRowDescriptorWithTag:@"disablefilesapp" rowType:XLFormRowDescriptorTypeBooleanSwitch title:NSLocalizedString(@"_disable_files_app_", nil)]; row.cellConfigAtConfigure[@"backgroundColor"] = UIColor.secondarySystemGroupedBackgroundColor; - if ([CCUtility getDisableFilesApp]) row.value = @"1"; + if ([[NCKeychain alloc] init].disableFilesApp) row.value = @"1"; else row.value = @"0"; [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"]; [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"]; @@ -115,7 +115,7 @@ - (void)initializeForm [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"]; [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"]; [row.cellConfig setObject:[[UIImage imageNamed:@"crashservice"] imageWithColor:UIColor.systemGrayColor size:25] forKey:@"imageView.image"]; - if ([CCUtility getDisableCrashservice]) row.value = @"1"; + if ([[[NCKeychain alloc] init] disableCrashservice]) row.value = @"1"; else row.value = @"0"; [section addFormRow:row]; } @@ -153,7 +153,7 @@ - (void)initializeForm [[[NextcloudKit shared] nkCommonInstance] clearFileLog]; - NSInteger logLevel = [CCUtility getLogLevel]; + NSInteger logLevel = [[NCKeychain alloc] init].logLevel; BOOL isSimulatorOrTestFlight = [[NCUtility shared] isSimulatorOrTestFlight]; NSString *versionNextcloudiOS = [NSString stringWithFormat:[NCBrandOptions shared].textCopyrightNextcloudiOS, [[NCUtility shared] getVersionAppWithBuild:true]]; if (isSimulatorOrTestFlight) { @@ -169,7 +169,7 @@ - (void)initializeForm [row.cellConfig setObject:@(NSTextAlignmentCenter) forKey:@"textLabel.textAlignment"]; [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"]; [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"]; - NSInteger logLevel = [CCUtility getLogLevel]; + NSInteger logLevel = [[NCKeychain alloc] init].logLevel; row.value = @(logLevel); [row.cellConfigAtConfigure setObject:@(2) forKey:@"slider.maximumValue"]; [row.cellConfigAtConfigure setObject:@(0) forKey:@"slider.minimumValue"]; @@ -200,7 +200,7 @@ - (void)initializeForm row = [XLFormRowDescriptor formRowDescriptorWithTag:@"deleteoldfiles" rowType:XLFormRowDescriptorTypeSelectorPush title:NSLocalizedString(@"_delete_old_files_", nil)]; - switch (CCUtility.getCleanUpDay) { + switch ([[NCKeychain alloc] init].cleanUpDay) { case 0: row.value = [XLFormOptionsObject formOptionsObjectWithValue:@(0) displayText:NSLocalizedString(@"_never_", nil)]; break; @@ -313,33 +313,33 @@ - (void)formRowDescriptorValueHasChanged:(XLFormRowDescriptor *)rowDescriptor ol if ([rowDescriptor.tag isEqualToString:@"showHiddenFiles"]) { - [CCUtility setShowHiddenFiles:[[rowDescriptor.value valueData] boolValue]]; + [[NCKeychain alloc] init].showHiddenFiles = [[rowDescriptor.value valueData] boolValue]; } if ([rowDescriptor.tag isEqualToString:@"formatCompatibility"]) { - [CCUtility setFormatCompatibility:[[rowDescriptor.value valueData] boolValue]]; + [[NCKeychain alloc] init].formatCompatibility = [[rowDescriptor.value valueData] boolValue]; } if ([rowDescriptor.tag isEqualToString:@"livePhoto"]) { - [CCUtility setLivePhoto:[[rowDescriptor.value valueData] boolValue]]; + [[NCKeychain alloc] init].livePhoto = [[rowDescriptor.value valueData] boolValue]; } if ([rowDescriptor.tag isEqualToString:@"removePhotoCameraRoll"]) { - [CCUtility setRemovePhotoCameraRoll:[[rowDescriptor.value valueData] boolValue]]; + [[NCKeychain alloc] init].removePhotoCameraRoll = [[rowDescriptor.value valueData] boolValue]; } if ([rowDescriptor.tag isEqualToString:@"disablefilesapp"]) { - [CCUtility setDisableFilesApp:[[rowDescriptor.value valueData] boolValue]]; + [[NCKeychain alloc] init].disableFilesApp = [[rowDescriptor.value valueData] boolValue]; } if ([rowDescriptor.tag isEqualToString:@"crashservice"]) { - [CCUtility setDisableCrashservice:[[rowDescriptor.value valueData] boolValue]]; - + [[NCKeychain alloc] init].disableCrashservice = [[rowDescriptor.value valueData] boolValue]; + UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_crashservice_title_", nil) message:NSLocalizedString(@"_crashservice_alert_", nil) preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { exit(0); @@ -352,14 +352,14 @@ - (void)formRowDescriptorValueHasChanged:(XLFormRowDescriptor *)rowDescriptor ol if ([rowDescriptor.tag isEqualToString:@"logLevel"]) { NSInteger levelLog = [[rowDescriptor.value valueData] intValue]; - [CCUtility setLogLevel:levelLog]; + [[NCKeychain alloc] init].logLevel = levelLog; [[[NextcloudKit shared] nkCommonInstance] setLevelLog:levelLog]; } if ([rowDescriptor.tag isEqualToString:@"deleteoldfiles"]) { NSInteger days = [[rowDescriptor.value valueData] intValue]; - [CCUtility setCleanUpDay:days]; + [[NCKeychain alloc] init].cleanUpDay = days; } } @@ -367,7 +367,7 @@ - (void)formRowDescriptorValueHasChanged:(XLFormRowDescriptor *)rowDescriptor ol - (void)clearCache:(NSString *)account { - [[NCNetworking shared] cancelSessionsInBackground:true]; + [[NCNetworking shared] cancelInBackground:true]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) { @@ -376,13 +376,13 @@ - (void)clearCache:(NSString *)account [[NCManageDatabase shared] clearDatabaseWithAccount:account removeAccount:false]; - [CCUtility removeGroupDirectoryProviderStorage]; - [CCUtility removeGroupLibraryDirectory]; + [[NCUtilityFileSystem shared] removeGroupDirectoryProviderStorage]; + [[NCUtilityFileSystem shared] removeGroupLibraryDirectory]; - [CCUtility removeDocumentsDirectory]; - [CCUtility removeTemporaryDirectory]; + [[NCUtilityFileSystem shared] removeDocumentsDirectory]; + [[NCUtilityFileSystem shared] removeTemporaryDirectory]; - [CCUtility createDirectoryStandard]; + [[NCUtilityFileSystem shared] createDirectoryStandard]; [[NCAutoUpload shared] alignPhotoLibraryWithViewController:self]; @@ -430,10 +430,10 @@ - (void)clearAllCacheRequest:(XLFormRowDescriptor *)sender - (void)calculateSize { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - NSString *directory = CCUtility.getDirectoryProviderStorage; + NSString *directory = [[NCUtilityFileSystem shared] directoryProviderStorage]; int64_t totalSize = [[NCUtilityFileSystem shared] getDirectorySizeWithDirectory:directory]; - sectionSize.footerTitle = [NSString stringWithFormat:@"%@. (%@ %@)", NSLocalizedString(@"_clear_cache_footer_", nil), NSLocalizedString(@"_used_space_", nil), [CCUtility transformedSize:totalSize]]; - + sectionSize.footerTitle = [NSString stringWithFormat:@"%@. (%@ %@)", NSLocalizedString(@"_clear_cache_footer_", nil), NSLocalizedString(@"_used_space_", nil), [[NCUtilityFileSystem shared] transformedSize:totalSize]]; + dispatch_async(dispatch_get_main_queue(), ^{ [self.tableView reloadData]; }); @@ -450,7 +450,7 @@ - (void)exitNextcloud:(XLFormRowDescriptor *)sender [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) { - [[NCNetworking shared] cancelSessionsInBackground:true]; + [[NCNetworking shared] cancelInBackground:true]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) { @@ -459,13 +459,13 @@ - (void)exitNextcloud:(XLFormRowDescriptor *)sender [[NSURLCache sharedURLCache] setMemoryCapacity:0]; [[NSURLCache sharedURLCache] setDiskCapacity:0]; - [CCUtility removeGroupDirectoryProviderStorage]; - [CCUtility removeGroupApplicationSupport]; + [[NCUtilityFileSystem shared] removeGroupDirectoryProviderStorage]; + [[NCUtilityFileSystem shared] removeGroupApplicationSupport]; - [CCUtility removeDocumentsDirectory]; - [CCUtility removeTemporaryDirectory]; + [[NCUtilityFileSystem shared] removeDocumentsDirectory]; + [[NCUtilityFileSystem shared] removeTemporaryDirectory]; - [CCUtility deleteAllChainStore]; + [[[NCKeychain alloc] init] removeAll]; exit(0); }); diff --git a/iOSClient/Settings/CCManageAccount.m b/iOSClient/Settings/CCManageAccount.m index f2fc78d47c..425d42758f 100644 --- a/iOSClient/Settings/CCManageAccount.m +++ b/iOSClient/Settings/CCManageAccount.m @@ -123,7 +123,7 @@ - (void)initializeForm [row.cellConfig setObject:[[UIImage imageNamed:@"users"] imageWithColor:UIColor.systemGrayColor size:25] forKey:@"imageView.image"]; [row.cellConfig setObject:[UIFont systemFontOfSize:15.0] forKey:@"textLabel.font"]; [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"]; - if ([CCUtility getAccountRequest]) row.value = @1; + if ([[NCKeychain alloc] init].accountRequest) row.value = @1; else row.value = @0; [section addFormRow:row]; } @@ -205,7 +205,6 @@ - (void)initializeForm [row.cellConfig setObject:UIColor.labelColor forKey:@"textLabel.textColor"]; [row.cellConfig setObject:[[UIImage imageNamed:@"country"] imageWithColor:UIColor.systemGrayColor size:25] forKey:@"imageView.image"]; row.value = [[NSLocale systemLocale] displayNameForKey:NSLocaleCountryCode value:activeAccount.country]; - //NSArray *countryCodes = [NSLocale ISOCountryCodes]; [section addFormRow:row]; } @@ -306,9 +305,9 @@ -(void)formRowDescriptorValueHasChanged:(XLFormRowDescriptor *)rowDescriptor old if ([rowDescriptor.tag isEqualToString:@"accountRequest"]) { if ([[rowDescriptor.value valueData] boolValue] == YES) { - [CCUtility setAccountRequest:true]; + [[NCKeychain alloc] init].accountRequest = true; } else { - [CCUtility setAccountRequest:false]; + [[NCKeychain alloc] init].accountRequest = false; } } diff --git a/iOSClient/Settings/CCManageAutoUpload.m b/iOSClient/Settings/CCManageAutoUpload.m index e7888eee6b..cbb2d98c33 100644 --- a/iOSClient/Settings/CCManageAutoUpload.m +++ b/iOSClient/Settings/CCManageAutoUpload.m @@ -399,7 +399,7 @@ - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInte sectionName = NSLocalizedString(@"_autoupload_description_", nil); break; case 1: - if (activeAccount.autoUpload) sectionName = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"_autoupload_current_folder_", nil), [CCUtility returnPathfromServerUrl:autoUploadPath urlBase:appDelegate.urlBase userId:appDelegate.userId account:appDelegate.account]]; + if (activeAccount.autoUpload) sectionName = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"_autoupload_current_folder_", nil), [self returnPathfromServerUrl:autoUploadPath urlBase:appDelegate.urlBase userId:appDelegate.userId account:appDelegate.account]]; else sectionName = @""; break; case 4: @@ -453,4 +453,11 @@ - (void)selectAutomaticUploadFolder }]; } +- (NSString *)returnPathfromServerUrl:(NSString *)serverUrl urlBase:(NSString *)urlBase userId:(NSString *)userId account:(NSString *)account +{ + NSString *homeServer = [[NCUtilityFileSystem shared] getHomeServerWithUrlBase:urlBase userId:userId]; + NSString *path = [serverUrl stringByReplacingOccurrencesOfString:homeServer withString:@""]; + return path; +} + @end diff --git a/iOSClient/Settings/NCEndToEndInitialize.swift b/iOSClient/Settings/NCEndToEndInitialize.swift index 9d7bc810fe..0363b89b1c 100644 --- a/iOSClient/Settings/NCEndToEndInitialize.swift +++ b/iOSClient/Settings/NCEndToEndInitialize.swift @@ -32,11 +32,7 @@ import NextcloudKit class NCEndToEndInitialize: NSObject { @objc weak var delegate: NCEndToEndInitializeDelegate? - - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! var extractedPublicKey: String? override init() { @@ -49,7 +45,7 @@ class NCEndToEndInitialize: NSObject { @objc func initEndToEndEncryption() { // Clear all keys - CCUtility.clearAllKeysEnd(toEnd: appDelegate.account) + NCKeychain().clearAllKeysEndToEnd(account: appDelegate.account) self.getPublicKey() } @@ -65,9 +61,9 @@ class NCEndToEndInitialize: NSObject { NextcloudKit.shared.getE2EECertificate { account, certificate, _, _, error in - if error == .success && account == self.appDelegate.account { + if error == .success, account == self.appDelegate.account, let certificate { - CCUtility.setEndToEndCertificate(account, certificate: certificate) + NCKeychain().setEndToEndCertificate(account: account, certificate: certificate) self.extractedPublicKey = NCEndToEndEncryption.sharedManager().extractPublicKey(fromCertificate: certificate) @@ -83,7 +79,7 @@ class NCEndToEndInitialize: NSObject { NCContentPresenter.shared.messageNotification("E2E get publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max) case NCGlobal.shared.errorResourceNotFound: - guard let csr = NCEndToEndEncryption.sharedManager().createCSR(self.appDelegate.userId, directory: CCUtility.getDirectoryUserData()) else { + guard let csr = NCEndToEndEncryption.sharedManager().createCSR(self.appDelegate.userId, directory: NCUtilityFileSystem.shared.directoryUserData) else { let error = NKError(errorCode: error.errorCode, errorDescription: "Error to create Csr") NCContentPresenter.shared.messageNotification("E2E Csr", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max) @@ -92,7 +88,7 @@ class NCEndToEndInitialize: NSObject { NextcloudKit.shared.signE2EECertificate(certificate: csr) { account, certificate, _, error in - if error == .success && account == self.appDelegate.account { + if error == .success, account == self.appDelegate.account, let certificate { // TEST publicKey let extractedPublicKey = NCEndToEndEncryption.sharedManager().extractPublicKey(fromCertificate: certificate) @@ -102,7 +98,7 @@ class NCEndToEndInitialize: NSObject { } else { - CCUtility.setEndToEndCertificate(account, certificate: certificate) + NCKeychain().setEndToEndCertificate(account: account, certificate: certificate) // Request PrivateKey chiper to Server self.getPrivateKeyCipher() @@ -152,14 +148,14 @@ class NCEndToEndInitialize: NSObject { let ok = UIAlertAction(title: "OK", style: .default, handler: { _ -> Void in - let passphrase = passphraseTextField?.text + let passphrase = passphraseTextField?.text ?? "" - let publicKey = CCUtility.getEndToEndCertificate(self.appDelegate.account) + let publicKey = NCKeychain().getEndToEndCertificate(account: self.appDelegate.account) if let privateKeyData = (NCEndToEndEncryption.sharedManager().decryptPrivateKey(privateKeyChiper, passphrase: passphrase, publicKey: publicKey, iterationCount: 1024)), - let keyData = Data(base64Encoded: privateKeyData) { - let privateKey = String(data: keyData, encoding: .utf8) - CCUtility.setEndToEndPrivateKey(self.appDelegate.account, privateKey: privateKey) + let keyData = Data(base64Encoded: privateKeyData), + let privateKey = String(data: keyData, encoding: .utf8) { + NCKeychain().setEndToEndPrivateKey(account: self.appDelegate.account, privateKey: privateKey) } else { let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "Serious internal error to decrypt Private Key") @@ -169,14 +165,14 @@ class NCEndToEndInitialize: NSObject { } // Save to keychain - CCUtility.setEndToEndPassphrase(self.appDelegate.account, passphrase: passphrase) + NCKeychain().setEndToEndPassphrase(account: self.appDelegate.account, passphrase: passphrase) // request server publicKey NextcloudKit.shared.getE2EEPublicKey { account, publicKey, _, error in - if error == .success && account == self.appDelegate.account { + if error == .success, account == self.appDelegate.account, let publicKey { - CCUtility.setEndToEndPublicKey(account, publicKey: publicKey) + NCKeychain().setEndToEndPublicKey(account: account, publicKey: publicKey) NCManageDatabase.shared.clearTablesE2EE(account: account) self.delegate?.endToEndInitializeSuccess() @@ -259,7 +255,7 @@ class NCEndToEndInitialize: NSObject { var privateKeyString: NSString? - guard let privateKeyChiper = NCEndToEndEncryption.sharedManager().encryptPrivateKey(self.appDelegate.userId, directory: CCUtility.getDirectoryUserData(), passphrase: e2ePassphrase, privateKey: &privateKeyString, iterationCount: 1024) else { + guard let privateKeyChiper = NCEndToEndEncryption.sharedManager().encryptPrivateKey(self.appDelegate.userId, directory: NCUtilityFileSystem.shared.directoryUserData, passphrase: e2ePassphrase, privateKey: &privateKeyString, iterationCount: 1024) else { let error = NKError(errorCode: error.errorCode, errorDescription: "Serious internal error to create PrivateKey chiper") NCContentPresenter.shared.messageNotification("E2E privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max) return @@ -270,17 +266,17 @@ class NCEndToEndInitialize: NSObject { NextcloudKit.shared.storeE2EEPrivateKey(privateKey: privateKeyChiper) { account, _, _, error in - if error == .success && account == self.appDelegate.account { + if error == .success, account == self.appDelegate.account, let privateKey = privateKeyString { - CCUtility.setEndToEndPrivateKey(account, privateKey: privateKeyString! as String) - CCUtility.setEndToEndPassphrase(account, passphrase: e2ePassphrase) + NCKeychain().setEndToEndPrivateKey(account: account, privateKey: String(privateKey)) + NCKeychain().setEndToEndPassphrase(account: account, passphrase: e2ePassphrase) // request server publicKey NextcloudKit.shared.getE2EEPublicKey { account, publicKey, _, error in - if error == .success && account == self.appDelegate.account { + if error == .success, account == self.appDelegate.account, let publicKey { - CCUtility.setEndToEndPublicKey(account, publicKey: publicKey) + NCKeychain().setEndToEndPublicKey(account: account, publicKey: publicKey) NCManageDatabase.shared.clearTablesE2EE(account: account) if copyPassphrase { diff --git a/iOSClient/Settings/NCManageAutoUploadFileName.swift b/iOSClient/Settings/NCManageAutoUploadFileName.swift index 90335789fa..649de835eb 100644 --- a/iOSClient/Settings/NCManageAutoUploadFileName.swift +++ b/iOSClient/Settings/NCManageAutoUploadFileName.swift @@ -27,10 +27,7 @@ import NextcloudKit class NCManageAutoUploadFileName: XLFormViewController { - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! let dateExample = Date() func initializeForm() { @@ -49,7 +46,7 @@ class NCManageAutoUploadFileName: XLFormViewController { // Maintain the original fileName row = XLFormRowDescriptor(tag: "maintainOriginalFileName", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_maintain_original_filename_", comment: "")) - row.value = CCUtility.getOriginalFileName(NCGlobal.shared.keyFileNameOriginalAutoUpload) + row.value = NCKeychain().getOriginalFileName(key: NCGlobal.shared.keyFileNameOriginalAutoUpload) row.cellConfig["backgroundColor"] = UIColor.secondarySystemGroupedBackground row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0) @@ -60,7 +57,7 @@ class NCManageAutoUploadFileName: XLFormViewController { // Add File Name Type row = XLFormRowDescriptor(tag: "addFileNameType", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_add_filenametype_", comment: "")) - row.value = CCUtility.getFileNameType(NCGlobal.shared.keyFileNameAutoUploadType) + row.value = NCKeychain().getFileNameType(key: NCGlobal.shared.keyFileNameAutoUploadType) row.hidden = "$\("maintainOriginalFileName") == 1" row.cellConfig["backgroundColor"] = UIColor.secondarySystemGroupedBackground @@ -75,7 +72,7 @@ class NCManageAutoUploadFileName: XLFormViewController { form.addFormSection(section) row = XLFormRowDescriptor(tag: "maskFileName", rowType: XLFormRowDescriptorTypeText, title: (NSLocalizedString("_filename_", comment: ""))) - let fileNameMask: String = CCUtility.getFileNameMask(NCGlobal.shared.keyFileNameAutoUploadMask) + let fileNameMask: String = NCKeychain().getFileNameMask(key: NCGlobal.shared.keyFileNameAutoUploadMask) if !fileNameMask.isEmpty { row.value = fileNameMask } @@ -147,10 +144,10 @@ class NCManageAutoUploadFileName: XLFormViewController { super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue) if formRow.tag == "addFileNameType" { - CCUtility.setFileNameType((formRow.value! as AnyObject).boolValue, key: NCGlobal.shared.keyFileNameAutoUploadType) + NCKeychain().setFileNameType(key: NCGlobal.shared.keyFileNameAutoUploadType, prefix: (formRow.value! as AnyObject).boolValue) self.reloadForm() } else if formRow.tag == "maintainOriginalFileName" { - CCUtility.setOriginalFileName((formRow.value! as AnyObject).boolValue, key: NCGlobal.shared.keyFileNameOriginalAutoUpload) + NCKeychain().setOriginalFileName(key: NCGlobal.shared.keyFileNameOriginalAutoUpload, value: (formRow.value! as AnyObject).boolValue) self.reloadForm() } else if formRow.tag == "maskFileName" { @@ -159,7 +156,7 @@ class NCManageAutoUploadFileName: XLFormViewController { self.form.delegate = nil if let fileName = fileName { - formRow.value = CCUtility.removeForbiddenCharactersServer(fileName) + formRow.value = NCUtility.shared.removeForbiddenCharacters(fileName) } self.form.delegate = self @@ -189,7 +186,7 @@ class NCManageAutoUploadFileName: XLFormViewController { var returnString: String = "" - if CCUtility.getOriginalFileName(NCGlobal.shared.keyFileNameOriginalAutoUpload) { + if NCKeychain().getOriginalFileName(key: NCGlobal.shared.keyFileNameOriginalAutoUpload) { return (NSLocalizedString("_filename_", comment: "") + ": IMG_0001.JPG") @@ -199,13 +196,13 @@ class NCManageAutoUploadFileName: XLFormViewController { if valueRenameTrimming.isEmpty { - CCUtility.setFileNameMask("", key: NCGlobal.shared.keyFileNameAutoUploadMask) + NCKeychain().setFileNameMask(key: NCGlobal.shared.keyFileNameAutoUploadMask, mask: "") returnString = CCUtility.createFileName("IMG_0001.JPG", fileDate: dateExample, fileType: PHAssetMediaType.image, keyFileName: nil, keyFileNameType: NCGlobal.shared.keyFileNameAutoUploadType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginalAutoUpload, forcedNewFileName: false) } else { self.form.delegate = nil - CCUtility.setFileNameMask(valueRename, key: NCGlobal.shared.keyFileNameAutoUploadMask) + NCKeychain().setFileNameMask(key: NCGlobal.shared.keyFileNameAutoUploadMask, mask: valueRename) self.form.delegate = self returnString = CCUtility.createFileName("IMG_0001.JPG", fileDate: dateExample, fileType: PHAssetMediaType.image, keyFileName: NCGlobal.shared.keyFileNameAutoUploadMask, keyFileNameType: NCGlobal.shared.keyFileNameAutoUploadType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginalAutoUpload, forcedNewFileName: false) @@ -213,7 +210,7 @@ class NCManageAutoUploadFileName: XLFormViewController { } else { - CCUtility.setFileNameMask("", key: NCGlobal.shared.keyFileNameAutoUploadMask) + NCKeychain().setFileNameMask(key: NCGlobal.shared.keyFileNameAutoUploadMask, mask: "") returnString = CCUtility.createFileName("IMG_0001.JPG", fileDate: dateExample, fileType: PHAssetMediaType.image, keyFileName: nil, keyFileNameType: NCGlobal.shared.keyFileNameAutoUploadType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginalAutoUpload, forcedNewFileName: false) } diff --git a/iOSClient/Settings/NCManageE2EE.swift b/iOSClient/Settings/NCManageE2EE.swift index 77b3bd38c8..588615d715 100644 --- a/iOSClient/Settings/NCManageE2EE.swift +++ b/iOSClient/Settings/NCManageE2EE.swift @@ -30,10 +30,6 @@ import LocalAuthentication @objc func makeShipDetailsUI(account: String) -> UIViewController { - // swiftlint:disable force_cast - let account = (UIApplication.shared.delegate as! AppDelegate).account - // swiftlint:enable force_cast - let details = NCViewE2EE(account: account) let vc = UIHostingController(rootView: details) vc.title = NSLocalizedString("_e2e_settings_", comment: "") @@ -44,11 +40,7 @@ import LocalAuthentication class NCManageE2EE: NSObject, ObservableObject, NCEndToEndInitializeDelegate, TOPasscodeViewControllerDelegate { let endToEndInitialize = NCEndToEndInitialize() - - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! var passcodeType = "" @Published var isEndToEndEnabled: Bool = false @@ -58,7 +50,7 @@ class NCManageE2EE: NSObject, ObservableObject, NCEndToEndInitializeDelegate, TO super.init() endToEndInitialize.delegate = self - isEndToEndEnabled = CCUtility.isEnd(toEndEnabled: appDelegate.account) + isEndToEndEnabled = NCKeychain().isEndToEndEnabled(account: appDelegate.account) if isEndToEndEnabled { statusOfService = NSLocalizedString("_status_e2ee_configured_", comment: "") } else { @@ -88,7 +80,7 @@ class NCManageE2EE: NSObject, ObservableObject, NCEndToEndInitializeDelegate, TO let passcodeViewController = TOPasscodeViewController(passcodeType: .sixDigits, allowCancel: true) passcodeViewController.delegate = self passcodeViewController.keypadButtonShowLettering = false - if CCUtility.getEnableTouchFaceID() && laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { + if NCKeychain().touchFaceID, laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { if error == nil { if laContext.biometryType == .faceID { passcodeViewController.biometryType = .faceID @@ -111,7 +103,7 @@ class NCManageE2EE: NSObject, ObservableObject, NCEndToEndInitializeDelegate, TO case "startE2E": endToEndInitialize.initEndToEndEncryption() case "readPassphrase": - if let e2ePassphrase = CCUtility.getEndToEndPassphrase(appDelegate.account) { + if let e2ePassphrase = NCKeychain().getEndToEndPassphrase(account: appDelegate.account) { print("[LOG]Passphrase: " + e2ePassphrase) let message = "\n" + NSLocalizedString("_e2e_settings_the_passphrase_is_", comment: "") + "\n\n\n" + e2ePassphrase let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert) @@ -124,8 +116,8 @@ class NCManageE2EE: NSObject, ObservableObject, NCEndToEndInitializeDelegate, TO case "removeLocallyEncryption": let alertController = UIAlertController(title: NSLocalizedString("_e2e_settings_remove_", comment: ""), message: NSLocalizedString("_e2e_settings_remove_message_", comment: ""), preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("_remove_", comment: ""), style: .default, handler: { _ in - CCUtility.clearAllKeysEnd(toEnd: self.appDelegate.account) - self.isEndToEndEnabled = CCUtility.isEnd(toEndEnabled: self.appDelegate.account) + NCKeychain().clearAllKeysEndToEnd(account: self.appDelegate.account) + self.isEndToEndEnabled = NCKeychain().isEndToEndEnabled(account: self.appDelegate.account) })) alertController.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .default, handler: { _ in })) appDelegate.window?.rootViewController?.present(alertController, animated: true) @@ -136,7 +128,7 @@ class NCManageE2EE: NSObject, ObservableObject, NCEndToEndInitializeDelegate, TO func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool { - if code == CCUtility.getPasscode() { + if code == NCKeychain().passcode { DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { self.correctPasscode() } @@ -202,7 +194,7 @@ struct NCViewE2EE: View { } .contentShape(Rectangle()) .onTapGesture { - if let passcode = CCUtility.getPasscode(), !passcode.isEmpty { + if NCKeychain().passcode != nil { manageE2EE.requestPasscodeType("readPassphrase") } else { NCContentPresenter.shared.showInfo(error: NKError(errorCode: 0, errorDescription: "_e2e_settings_lock_not_active_")) @@ -222,7 +214,7 @@ struct NCViewE2EE: View { } .contentShape(Rectangle()) .onTapGesture { - if let passcode = CCUtility.getPasscode(), !passcode.isEmpty { + if let passcode = NCKeychain().passcode { manageE2EE.requestPasscodeType("removeLocallyEncryption") } else { NCContentPresenter.shared.showInfo(error: NKError(errorCode: 0, errorDescription: "_e2e_settings_lock_not_active_")) @@ -252,7 +244,7 @@ struct NCViewE2EE: View { } .contentShape(Rectangle()) .onTapGesture { - if let passcode = CCUtility.getPasscode(), !passcode.isEmpty { + if let passcode = NCKeychain().passcode { manageE2EE.requestPasscodeType("startE2E") } else { NCContentPresenter.shared.showInfo(error: NKError(errorCode: 0, errorDescription: "_e2e_settings_lock_not_active_")) diff --git a/iOSClient/Settings/NCSettings.m b/iOSClient/Settings/NCSettings.m index 2a1bfdc896..e3e0c0804e 100644 --- a/iOSClient/Settings/NCSettings.m +++ b/iOSClient/Settings/NCSettings.m @@ -265,7 +265,7 @@ - (void)reloadForm // ------------------------------------------------------------------ - if ([[CCUtility getPasscode] length]) { + if ([[NCKeychain alloc] init].passcode) { rowBloccoPasscode.title = NSLocalizedString(@"_lock_active_", nil); [rowBloccoPasscode.cellConfig setObject:[[UIImage imageNamed:@"lock"] imageWithColor:UIColor.systemGrayColor size:25] forKey:@"imageView.image"]; } else { @@ -273,9 +273,9 @@ - (void)reloadForm [rowBloccoPasscode.cellConfig setObject:[[UIImage imageNamed:@"lock_open"] imageWithColor:UIColor.systemGrayColor size:25] forKey:@"imageView.image"]; } - if ([CCUtility getEnableTouchFaceID]) [rowEnableTouchDaceID setValue:@1]; else [rowEnableTouchDaceID setValue:@0]; - if ([CCUtility getNotPasscodeAtStart]) [rowNotPasscodeAtStart setValue:@1]; else [rowNotPasscodeAtStart setValue:@0]; - if ([CCUtility getPrivacyScreenEnabled]) [rowPrivacyScreen setValue:@1]; else [rowPrivacyScreen setValue:@0]; + if ([[NCKeychain alloc] init].touchFaceID) [rowEnableTouchDaceID setValue:@1]; else [rowEnableTouchDaceID setValue:@0]; + if ([[NCKeychain alloc] init].requestPasscodeAtStart) [rowNotPasscodeAtStart setValue:@0]; else [rowNotPasscodeAtStart setValue:@1]; + if ([[NCKeychain alloc] init].privacyScreenEnabled) [rowPrivacyScreen setValue:@1]; else [rowPrivacyScreen setValue:@0]; // ----------------------------------------------------------------- @@ -292,27 +292,27 @@ - (void)formRowDescriptorValueHasChanged:(XLFormRowDescriptor *)rowDescriptor ol if ([rowDescriptor.tag isEqualToString:@"notPasscodeAtStart"]) { if ([[rowDescriptor.value valueData] boolValue] == YES) { - [CCUtility setNotPasscodeAtStart:true]; + [[NCKeychain alloc] init].requestPasscodeAtStart = false; } else { - [CCUtility setNotPasscodeAtStart:false]; + [[NCKeychain alloc] init].requestPasscodeAtStart = true; } } if ([rowDescriptor.tag isEqualToString:@"enableTouchDaceID"]) { if ([[rowDescriptor.value valueData] boolValue] == YES) { - [CCUtility setEnableTouchFaceID:true]; + [[NCKeychain alloc] init].touchFaceID = true; } else { - [CCUtility setEnableTouchFaceID:false]; + [[NCKeychain alloc] init].touchFaceID = false; } } if ([rowDescriptor.tag isEqualToString:@"privacyScreen"]) { if ([[rowDescriptor.value valueData] boolValue] == YES) { - [CCUtility setPrivacyScreenEnabled:true]; + [[NCKeychain alloc] init].privacyScreenEnabled = true; } else { - [CCUtility setPrivacyScreenEnabled:false]; + [[NCKeychain alloc] init].privacyScreenEnabled = false; } } } @@ -370,7 +370,7 @@ - (void)didPerformBiometricValidationRequestInPasscodeViewController:(TOPasscode [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions shared] brand] reply:^(BOOL success, NSError * _Nullable error) { if (success) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) { - [CCUtility setPasscode:@""]; + [[NCKeychain alloc] init].passcode = nil; [passcodeViewController dismissViewControllerAnimated:YES completion:nil]; [self reloadForm]; }); @@ -380,7 +380,7 @@ - (void)didPerformBiometricValidationRequestInPasscodeViewController:(TOPasscode - (void)passcodeSettingsViewController:(TOPasscodeSettingsViewController *)passcodeSettingsViewController didChangeToNewPasscode:(NSString *)passcode ofType:(TOPasscodeType)type { - [CCUtility setPasscode:passcode]; + [[NCKeychain alloc] init].passcode = passcode; [passcodeSettingsViewController dismissViewControllerAnimated:YES completion:nil]; [self reloadForm]; @@ -393,8 +393,8 @@ - (void)didTapCancelInPasscodeViewController:(TOPasscodeViewController *)passcod - (BOOL)passcodeViewController:(TOPasscodeViewController *)passcodeViewController isCorrectCode:(NSString *)code { - if ([code isEqualToString:[CCUtility getPasscode]]) { - [CCUtility setPasscode:@""]; + if ([code isEqualToString:[[NCKeychain alloc] init].passcode]) { + [[NCKeychain alloc] init].passcode = nil; [self reloadForm]; return YES; @@ -410,23 +410,13 @@ - (void)passcode:(XLFormRowDescriptor *)sender [self deselectFormRow:sender]; - if ([[CCUtility getPasscode] length] == 0) { - - passcodeSettingsViewController = [[TOPasscodeSettingsViewController alloc] init]; - passcodeSettingsViewController.hideOptionsButton = YES; - passcodeSettingsViewController.requireCurrentPasscode = NO; - passcodeSettingsViewController.passcodeType = TOPasscodeTypeSixDigits; - passcodeSettingsViewController.delegate = self; - - [self presentViewController:passcodeSettingsViewController animated:YES completion:nil]; - - } else { - + if ([[NCKeychain alloc] init].passcode) { + passcodeViewController = [[TOPasscodeViewController alloc] initPasscodeType:TOPasscodeTypeSixDigits allowCancel:true]; passcodeViewController.delegate = self; passcodeViewController.keypadButtonShowLettering = false; - - if (CCUtility.getEnableTouchFaceID && [laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) { + + if ([[NCKeychain alloc] init].touchFaceID && [laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) { if (error == NULL) { if (laContext.biometryType == LABiometryTypeFaceID) { passcodeViewController.biometryType = TOPasscodeBiometryTypeFaceID; @@ -443,6 +433,16 @@ - (void)passcode:(XLFormRowDescriptor *)sender } [self presentViewController:passcodeViewController animated:YES completion:nil]; + + } else { + + passcodeSettingsViewController = [[TOPasscodeSettingsViewController alloc] init]; + passcodeSettingsViewController.hideOptionsButton = YES; + passcodeSettingsViewController.requireCurrentPasscode = NO; + passcodeSettingsViewController.passcodeType = TOPasscodeTypeSixDigits; + passcodeSettingsViewController.delegate = self; + + [self presentViewController:passcodeSettingsViewController animated:YES completion:nil]; } } diff --git a/iOSClient/Settings/NCSettingsBundleHelper.swift b/iOSClient/Settings/NCSettingsBundleHelper.swift index 6af3636074..b2f6c40d29 100644 --- a/iOSClient/Settings/NCSettingsBundleHelper.swift +++ b/iOSClient/Settings/NCSettingsBundleHelper.swift @@ -42,12 +42,12 @@ class NCSettingsBundleHelper: NSObject { URLCache.shared.memoryCapacity = 0 URLCache.shared.diskCapacity = 0 - CCUtility.removeGroupDirectoryProviderStorage() - CCUtility.removeGroupApplicationSupport() - CCUtility.removeDocumentsDirectory() - CCUtility.removeTemporaryDirectory() + NCUtilityFileSystem.shared.removeGroupDirectoryProviderStorage() + NCUtilityFileSystem.shared.removeGroupApplicationSupport() + NCUtilityFileSystem.shared.removeDocumentsDirectory() + NCUtilityFileSystem.shared.removeTemporaryDirectory() - CCUtility.deleteAllChainStore() + NCKeychain().removeAll() NCManageDatabase.shared.removeDB() DispatchQueue.main.asyncAfter(deadline: .now() + delay) { diff --git a/iOSClient/Share/Advanced/NCShareAdvancePermissionHeader.swift b/iOSClient/Share/Advanced/NCShareAdvancePermissionHeader.swift index e5291e8c2d..f7d849c105 100644 --- a/iOSClient/Share/Advanced/NCShareAdvancePermissionHeader.swift +++ b/iOSClient/Share/Advanced/NCShareAdvancePermissionHeader.swift @@ -30,7 +30,7 @@ class NCShareAdvancePermissionHeader: UIView { @IBOutlet weak var fullWidthImageView: UIImageView! func setupUI(with metadata: tableMetadata) { - if FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) { + if FileManager.default.fileExists(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) { fullWidthImageView.image = NCUtility.shared.getImageMetadata(metadata, for: frame.height) fullWidthImageView.contentMode = .scaleAspectFill imageView.isHidden = true @@ -46,6 +46,6 @@ class NCShareAdvancePermissionHeader: UIView { fileName.text = metadata.fileNameView fileName.textColor = .label info.textColor = .secondaryLabel - info.text = CCUtility.transformedSize(metadata.size) + ", " + CCUtility.dateDiff(metadata.date as Date) + info.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) + ", " + CCUtility.dateDiff(metadata.date as Date) } } diff --git a/iOSClient/Share/NCShare.swift b/iOSClient/Share/NCShare.swift index 88ac281538..b93e8ed9ae 100644 --- a/iOSClient/Share/NCShare.swift +++ b/iOSClient/Share/NCShare.swift @@ -166,7 +166,7 @@ class NCShare: UIViewController, NCShareNetworkingDelegate, NCSharePagingContent let fileName = appDelegate.userBaseUrl + "-" + metadata.ownerId + ".png" if NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) == nil { - let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName + let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName let etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag NextcloudKit.shared.downloadAvatar( @@ -204,8 +204,15 @@ class NCShare: UIViewController, NCShareNetworkingDelegate, NCSharePagingContent // MARK: - IBAction @IBAction func searchFieldDidEndOnExit(textField: UITextField) { + // https://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift + func isValidEmail(_ email: String) -> Bool { + + let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" + let emailPred = NSPredicate(format: "SELF MATCHES %@", emailRegEx) + return emailPred.evaluate(with: email) + } guard let searchString = textField.text, !searchString.isEmpty else { return } - if searchString.contains("@"), !NCUtility.shared.isValidEmail(searchString) { return } + if searchString.contains("@"), !isValidEmail(searchString) { return } networking?.getSharees(searchString: searchString) } diff --git a/iOSClient/Share/NCShareNetworking.swift b/iOSClient/Share/NCShareNetworking.swift index e17da597c9..b0b92a010e 100644 --- a/iOSClient/Share/NCShareNetworking.swift +++ b/iOSClient/Share/NCShareNetworking.swift @@ -25,10 +25,7 @@ import NextcloudKit class NCShareNetworking: NSObject { - // swiftlint:disable force_cast - private let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! weak var delegate: NCShareNetworkingDelegate? var view: UIView var metadata: tableMetadata @@ -47,7 +44,7 @@ class NCShareNetworking: NSObject { NCActivityIndicator.shared.start(backgroundView: view) } - let filenamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)! + let filenamePath = NCUtilityFileSystem.shared.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId) let parameter = NKShareParameter(path: filenamePath) NextcloudKit.shared.readShares(parameters: parameter) { account, shares, _, error in @@ -83,7 +80,7 @@ class NCShareNetworking: NSObject { // https://github.com/nextcloud/ios-communication-library/pull/104 NCActivityIndicator.shared.start(backgroundView: view) - let filenamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)! + let filenamePath = NCUtilityFileSystem.shared.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId) NextcloudKit.shared.createShare(path: filenamePath, shareType: option.shareType, shareWith: option.shareWith, password: option.password, note: option.note, permissions: option.permissions, attributes: option.attributes) { _, share, _, error in NCActivityIndicator.shared.stop() diff --git a/iOSClient/Share/NCSharePaging.swift b/iOSClient/Share/NCSharePaging.swift index 64bde1f20f..9cf4bc2543 100644 --- a/iOSClient/Share/NCSharePaging.swift +++ b/iOSClient/Share/NCSharePaging.swift @@ -276,8 +276,8 @@ class NCSharePagingView: PagingView { dateFormatter.timeStyle = .short dateFormatter.locale = Locale.current - if FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) { - headerView.imageView.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) + if FileManager.default.fileExists(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) { + headerView.imageView.image = UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) } else { if metadata.directory { let image = metadata.e2eEncrypted ? UIImage(named: "folderEncrypted") : UIImage(named: "folder") @@ -297,7 +297,7 @@ class NCSharePagingView: PagingView { } else { headerView.favorite.setImage(NCUtility.shared.loadImage(named: "star.fill", color: .systemGray, size: 20), for: .normal) } - headerView.info.text = CCUtility.transformedSize(metadata.size) + ", " + NSLocalizedString("_modified_", comment: "") + " " + dateFormatter.string(from: metadata.date as Date) + headerView.info.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) + ", " + NSLocalizedString("_modified_", comment: "") + " " + dateFormatter.string(from: metadata.date as Date) headerView.info.textColor = .systemGray headerView.creation.text = NSLocalizedString("_creation_", comment: "") + " " + dateFormatter.string(from: metadata.creationDate as Date) headerView.creation.textColor = .systemGray diff --git a/iOSClient/Share/NCShareUserCell.swift b/iOSClient/Share/NCShareUserCell.swift index 2e4efffdff..163b244ecd 100644 --- a/iOSClient/Share/NCShareUserCell.swift +++ b/iOSClient/Share/NCShareUserCell.swift @@ -171,7 +171,7 @@ class NCSearchUserDropDownCell: DropDownCell, NCCellProtocol { let fileName = baseUrl.userBaseUrl + "-" + sharee.shareWith + ".png" if NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) == nil { - let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName + let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName let etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag NextcloudKit.shared.downloadAvatar( diff --git a/iOSClient/Supporting Files/af.lproj/Localizable.strings b/iOSClient/Supporting Files/af.lproj/Localizable.strings index 3397f6ebc4..b7a5be2b14 100644 Binary files a/iOSClient/Supporting Files/af.lproj/Localizable.strings and b/iOSClient/Supporting Files/af.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/an.lproj/Localizable.strings b/iOSClient/Supporting Files/an.lproj/Localizable.strings index 4dba1b320f..473c0c90b1 100644 Binary files a/iOSClient/Supporting Files/an.lproj/Localizable.strings and b/iOSClient/Supporting Files/an.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ar.lproj/Localizable.strings b/iOSClient/Supporting Files/ar.lproj/Localizable.strings index acca7429d0..872a7dc250 100644 Binary files a/iOSClient/Supporting Files/ar.lproj/Localizable.strings and b/iOSClient/Supporting Files/ar.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ast.lproj/Localizable.strings b/iOSClient/Supporting Files/ast.lproj/Localizable.strings index 0ef22878bc..185354a161 100644 Binary files a/iOSClient/Supporting Files/ast.lproj/Localizable.strings and b/iOSClient/Supporting Files/ast.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/az.lproj/Localizable.strings b/iOSClient/Supporting Files/az.lproj/Localizable.strings index 77d3345c37..1a57931cbb 100644 Binary files a/iOSClient/Supporting Files/az.lproj/Localizable.strings and b/iOSClient/Supporting Files/az.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/be.lproj/Localizable.strings b/iOSClient/Supporting Files/be.lproj/Localizable.strings index c495635d06..0806a599aa 100644 Binary files a/iOSClient/Supporting Files/be.lproj/Localizable.strings and b/iOSClient/Supporting Files/be.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/bg_BG.lproj/Localizable.strings b/iOSClient/Supporting Files/bg_BG.lproj/Localizable.strings index d16a3e19ff..dd2780f7ff 100644 Binary files a/iOSClient/Supporting Files/bg_BG.lproj/Localizable.strings and b/iOSClient/Supporting Files/bg_BG.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/bn_BD.lproj/Localizable.strings b/iOSClient/Supporting Files/bn_BD.lproj/Localizable.strings index e09dfa972f..7c07d1f42f 100644 Binary files a/iOSClient/Supporting Files/bn_BD.lproj/Localizable.strings and b/iOSClient/Supporting Files/bn_BD.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/br.lproj/Localizable.strings b/iOSClient/Supporting Files/br.lproj/Localizable.strings index 0919d3744b..9b1a22c69c 100644 Binary files a/iOSClient/Supporting Files/br.lproj/Localizable.strings and b/iOSClient/Supporting Files/br.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/bs.lproj/Localizable.strings b/iOSClient/Supporting Files/bs.lproj/Localizable.strings index 2aa4d12c46..eaf11bb555 100644 Binary files a/iOSClient/Supporting Files/bs.lproj/Localizable.strings and b/iOSClient/Supporting Files/bs.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ca.lproj/Localizable.strings b/iOSClient/Supporting Files/ca.lproj/Localizable.strings index 3d49bc5705..e464de7074 100644 Binary files a/iOSClient/Supporting Files/ca.lproj/Localizable.strings and b/iOSClient/Supporting Files/ca.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/cs-CZ.lproj/Localizable.strings b/iOSClient/Supporting Files/cs-CZ.lproj/Localizable.strings index fbe318f761..a918565f42 100644 Binary files a/iOSClient/Supporting Files/cs-CZ.lproj/Localizable.strings and b/iOSClient/Supporting Files/cs-CZ.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/cy_GB.lproj/Localizable.strings b/iOSClient/Supporting Files/cy_GB.lproj/Localizable.strings index 9185b34ea6..c558df118b 100644 Binary files a/iOSClient/Supporting Files/cy_GB.lproj/Localizable.strings and b/iOSClient/Supporting Files/cy_GB.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/da.lproj/Localizable.strings b/iOSClient/Supporting Files/da.lproj/Localizable.strings index 986b7609d1..5d2a857f02 100644 Binary files a/iOSClient/Supporting Files/da.lproj/Localizable.strings and b/iOSClient/Supporting Files/da.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/de.lproj/Localizable.strings b/iOSClient/Supporting Files/de.lproj/Localizable.strings index fd350f43b5..12479b0dff 100644 Binary files a/iOSClient/Supporting Files/de.lproj/Localizable.strings and b/iOSClient/Supporting Files/de.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/el.lproj/Localizable.strings b/iOSClient/Supporting Files/el.lproj/Localizable.strings index dc0eb70d13..a02aab717b 100644 Binary files a/iOSClient/Supporting Files/el.lproj/Localizable.strings and b/iOSClient/Supporting Files/el.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/en-GB.lproj/Localizable.strings b/iOSClient/Supporting Files/en-GB.lproj/Localizable.strings index 62644831bb..fa058f9bf6 100644 Binary files a/iOSClient/Supporting Files/en-GB.lproj/Localizable.strings and b/iOSClient/Supporting Files/en-GB.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/en.lproj/Localizable.strings b/iOSClient/Supporting Files/en.lproj/Localizable.strings index 46aefb6e2f..5e5eeac3f2 100644 --- a/iOSClient/Supporting Files/en.lproj/Localizable.strings +++ b/iOSClient/Supporting Files/en.lproj/Localizable.strings @@ -215,6 +215,7 @@ "_replace_all_action_title_" = "Replace all"; "_keep_both_for_all_action_title_" = "Keep both for all"; "_more_action_title_" = "More Details"; +"_wait_file_preparation_" = "Please wait, upload file in preparation …"; /* Background of the file listing view */ "_use_as_background_" = "Use it as a background"; diff --git a/iOSClient/Supporting Files/eo.lproj/Localizable.strings b/iOSClient/Supporting Files/eo.lproj/Localizable.strings index 2bb8b29c42..d4de65fbc8 100644 Binary files a/iOSClient/Supporting Files/eo.lproj/Localizable.strings and b/iOSClient/Supporting Files/eo.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-419.lproj/Localizable.strings b/iOSClient/Supporting Files/es-419.lproj/Localizable.strings index bdb1281312..a032cafb4e 100644 Binary files a/iOSClient/Supporting Files/es-419.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-419.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-AR.lproj/Localizable.strings b/iOSClient/Supporting Files/es-AR.lproj/Localizable.strings index 7cb58d9f42..dcfdab7326 100644 Binary files a/iOSClient/Supporting Files/es-AR.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-AR.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-CL.lproj/Localizable.strings b/iOSClient/Supporting Files/es-CL.lproj/Localizable.strings index 66577b1896..96a984ba36 100644 Binary files a/iOSClient/Supporting Files/es-CL.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-CL.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-CO.lproj/Localizable.strings b/iOSClient/Supporting Files/es-CO.lproj/Localizable.strings index 7811fb79b0..e6e0de6c49 100644 Binary files a/iOSClient/Supporting Files/es-CO.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-CO.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-CR.lproj/Localizable.strings b/iOSClient/Supporting Files/es-CR.lproj/Localizable.strings index 1e791e1699..548fd2ea37 100644 Binary files a/iOSClient/Supporting Files/es-CR.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-CR.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-DO.lproj/Localizable.strings b/iOSClient/Supporting Files/es-DO.lproj/Localizable.strings index 764ec7db29..50aa35b8c4 100644 Binary files a/iOSClient/Supporting Files/es-DO.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-DO.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-EC.lproj/Localizable.strings b/iOSClient/Supporting Files/es-EC.lproj/Localizable.strings index a92fc7177e..1f2ba0a8a7 100644 Binary files a/iOSClient/Supporting Files/es-EC.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-EC.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-GT.lproj/Localizable.strings b/iOSClient/Supporting Files/es-GT.lproj/Localizable.strings index d1fbd3312f..8d11bc6664 100644 Binary files a/iOSClient/Supporting Files/es-GT.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-GT.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-HN.lproj/Localizable.strings b/iOSClient/Supporting Files/es-HN.lproj/Localizable.strings index 578ed4eb0f..f94012b4fd 100644 Binary files a/iOSClient/Supporting Files/es-HN.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-HN.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-MX.lproj/Localizable.strings b/iOSClient/Supporting Files/es-MX.lproj/Localizable.strings index 3419d9c802..53df6bdb22 100644 Binary files a/iOSClient/Supporting Files/es-MX.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-MX.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-NI.lproj/Localizable.strings b/iOSClient/Supporting Files/es-NI.lproj/Localizable.strings index 4cd45b7995..a25a1e3b6d 100644 Binary files a/iOSClient/Supporting Files/es-NI.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-NI.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-PA.lproj/Localizable.strings b/iOSClient/Supporting Files/es-PA.lproj/Localizable.strings index 4cd45b7995..a25a1e3b6d 100644 Binary files a/iOSClient/Supporting Files/es-PA.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-PA.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-PE.lproj/Localizable.strings b/iOSClient/Supporting Files/es-PE.lproj/Localizable.strings index 4cd45b7995..a25a1e3b6d 100644 Binary files a/iOSClient/Supporting Files/es-PE.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-PE.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-PR.lproj/Localizable.strings b/iOSClient/Supporting Files/es-PR.lproj/Localizable.strings index 4cd45b7995..a25a1e3b6d 100644 Binary files a/iOSClient/Supporting Files/es-PR.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-PR.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-PY.lproj/Localizable.strings b/iOSClient/Supporting Files/es-PY.lproj/Localizable.strings index 093c966f84..44a53bab65 100644 Binary files a/iOSClient/Supporting Files/es-PY.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-PY.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-SV.lproj/Localizable.strings b/iOSClient/Supporting Files/es-SV.lproj/Localizable.strings index 1e791e1699..548fd2ea37 100644 Binary files a/iOSClient/Supporting Files/es-SV.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-SV.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es-UY.lproj/Localizable.strings b/iOSClient/Supporting Files/es-UY.lproj/Localizable.strings index 5e0c37df5c..5010c4ee60 100644 Binary files a/iOSClient/Supporting Files/es-UY.lproj/Localizable.strings and b/iOSClient/Supporting Files/es-UY.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/es.lproj/Localizable.strings b/iOSClient/Supporting Files/es.lproj/Localizable.strings index 3075ad8e40..93faf081e3 100644 Binary files a/iOSClient/Supporting Files/es.lproj/Localizable.strings and b/iOSClient/Supporting Files/es.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/et_EE.lproj/Localizable.strings b/iOSClient/Supporting Files/et_EE.lproj/Localizable.strings index 858c078437..b1301cca7d 100644 Binary files a/iOSClient/Supporting Files/et_EE.lproj/Localizable.strings and b/iOSClient/Supporting Files/et_EE.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/eu.lproj/Localizable.strings b/iOSClient/Supporting Files/eu.lproj/Localizable.strings index 893d3c8718..5ad0ee1036 100644 Binary files a/iOSClient/Supporting Files/eu.lproj/Localizable.strings and b/iOSClient/Supporting Files/eu.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/fa.lproj/Localizable.strings b/iOSClient/Supporting Files/fa.lproj/Localizable.strings index a3012c776d..899c553ace 100644 Binary files a/iOSClient/Supporting Files/fa.lproj/Localizable.strings and b/iOSClient/Supporting Files/fa.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/fi-FI.lproj/Localizable.strings b/iOSClient/Supporting Files/fi-FI.lproj/Localizable.strings index f81abaf166..3f811371ef 100644 Binary files a/iOSClient/Supporting Files/fi-FI.lproj/Localizable.strings and b/iOSClient/Supporting Files/fi-FI.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/fo.lproj/Localizable.strings b/iOSClient/Supporting Files/fo.lproj/Localizable.strings index 5eb6ea0447..b6a7ccf4c6 100644 Binary files a/iOSClient/Supporting Files/fo.lproj/Localizable.strings and b/iOSClient/Supporting Files/fo.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/fr.lproj/Localizable.strings b/iOSClient/Supporting Files/fr.lproj/Localizable.strings index ef1b6185ef..5ad778ab02 100644 Binary files a/iOSClient/Supporting Files/fr.lproj/Localizable.strings and b/iOSClient/Supporting Files/fr.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/gd.lproj/Localizable.strings b/iOSClient/Supporting Files/gd.lproj/Localizable.strings index f40aae1ca0..d830947b46 100644 Binary files a/iOSClient/Supporting Files/gd.lproj/Localizable.strings and b/iOSClient/Supporting Files/gd.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/gl.lproj/Localizable.strings b/iOSClient/Supporting Files/gl.lproj/Localizable.strings index 7797d0ffc3..9763a3d9f8 100644 Binary files a/iOSClient/Supporting Files/gl.lproj/Localizable.strings and b/iOSClient/Supporting Files/gl.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/he.lproj/Localizable.strings b/iOSClient/Supporting Files/he.lproj/Localizable.strings index 57d7d5ed1e..0aa268e6df 100644 Binary files a/iOSClient/Supporting Files/he.lproj/Localizable.strings and b/iOSClient/Supporting Files/he.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/hi_IN.lproj/Localizable.strings b/iOSClient/Supporting Files/hi_IN.lproj/Localizable.strings index 94689da437..489732df4d 100644 Binary files a/iOSClient/Supporting Files/hi_IN.lproj/Localizable.strings and b/iOSClient/Supporting Files/hi_IN.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/hr.lproj/Localizable.strings b/iOSClient/Supporting Files/hr.lproj/Localizable.strings index e350b397e5..680df3b6b3 100644 Binary files a/iOSClient/Supporting Files/hr.lproj/Localizable.strings and b/iOSClient/Supporting Files/hr.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/hsb.lproj/Localizable.strings b/iOSClient/Supporting Files/hsb.lproj/Localizable.strings index e8f1422922..1fb3c405b9 100644 Binary files a/iOSClient/Supporting Files/hsb.lproj/Localizable.strings and b/iOSClient/Supporting Files/hsb.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/hu.lproj/Localizable.strings b/iOSClient/Supporting Files/hu.lproj/Localizable.strings index bfea7e6e6c..92010c41ef 100644 Binary files a/iOSClient/Supporting Files/hu.lproj/Localizable.strings and b/iOSClient/Supporting Files/hu.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/hy.lproj/Localizable.strings b/iOSClient/Supporting Files/hy.lproj/Localizable.strings index 0eda4a71e0..9f7c17c0ed 100644 Binary files a/iOSClient/Supporting Files/hy.lproj/Localizable.strings and b/iOSClient/Supporting Files/hy.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ia.lproj/Localizable.strings b/iOSClient/Supporting Files/ia.lproj/Localizable.strings index f1a515512f..ecfcdc40cf 100644 Binary files a/iOSClient/Supporting Files/ia.lproj/Localizable.strings and b/iOSClient/Supporting Files/ia.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/id.lproj/Localizable.strings b/iOSClient/Supporting Files/id.lproj/Localizable.strings index 69f770d815..3c4b65efb2 100644 Binary files a/iOSClient/Supporting Files/id.lproj/Localizable.strings and b/iOSClient/Supporting Files/id.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ig.lproj/Localizable.strings b/iOSClient/Supporting Files/ig.lproj/Localizable.strings index bbef6e7470..319bf27546 100644 Binary files a/iOSClient/Supporting Files/ig.lproj/Localizable.strings and b/iOSClient/Supporting Files/ig.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/is.lproj/Localizable.strings b/iOSClient/Supporting Files/is.lproj/Localizable.strings index aa5210cd8e..e27d12ab81 100644 Binary files a/iOSClient/Supporting Files/is.lproj/Localizable.strings and b/iOSClient/Supporting Files/is.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/it.lproj/Localizable.strings b/iOSClient/Supporting Files/it.lproj/Localizable.strings index ebe6345756..b31fdb1c52 100644 Binary files a/iOSClient/Supporting Files/it.lproj/Localizable.strings and b/iOSClient/Supporting Files/it.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ja-JP.lproj/Localizable.strings b/iOSClient/Supporting Files/ja-JP.lproj/Localizable.strings index 794bc1a7a6..83843699e9 100644 Binary files a/iOSClient/Supporting Files/ja-JP.lproj/Localizable.strings and b/iOSClient/Supporting Files/ja-JP.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ka-GE.lproj/Localizable.strings b/iOSClient/Supporting Files/ka-GE.lproj/Localizable.strings index 1eeae4fa54..b5923c6881 100644 Binary files a/iOSClient/Supporting Files/ka-GE.lproj/Localizable.strings and b/iOSClient/Supporting Files/ka-GE.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ka.lproj/Localizable.strings b/iOSClient/Supporting Files/ka.lproj/Localizable.strings index bb159f83c9..158dd73944 100644 Binary files a/iOSClient/Supporting Files/ka.lproj/Localizable.strings and b/iOSClient/Supporting Files/ka.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/kab.lproj/Localizable.strings b/iOSClient/Supporting Files/kab.lproj/Localizable.strings index 500ff97760..19ccc1b385 100644 Binary files a/iOSClient/Supporting Files/kab.lproj/Localizable.strings and b/iOSClient/Supporting Files/kab.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/km.lproj/Localizable.strings b/iOSClient/Supporting Files/km.lproj/Localizable.strings index 75fa223795..f0bab550db 100644 Binary files a/iOSClient/Supporting Files/km.lproj/Localizable.strings and b/iOSClient/Supporting Files/km.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/kn.lproj/Localizable.strings b/iOSClient/Supporting Files/kn.lproj/Localizable.strings index e19e3ddf3b..7be75526f1 100644 Binary files a/iOSClient/Supporting Files/kn.lproj/Localizable.strings and b/iOSClient/Supporting Files/kn.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ko.lproj/Localizable.strings b/iOSClient/Supporting Files/ko.lproj/Localizable.strings index 7b5993b9e6..6b65063cc2 100644 Binary files a/iOSClient/Supporting Files/ko.lproj/Localizable.strings and b/iOSClient/Supporting Files/ko.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/la.lproj/Localizable.strings b/iOSClient/Supporting Files/la.lproj/Localizable.strings index 7e1c21e48c..9034994d83 100644 Binary files a/iOSClient/Supporting Files/la.lproj/Localizable.strings and b/iOSClient/Supporting Files/la.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/lb.lproj/Localizable.strings b/iOSClient/Supporting Files/lb.lproj/Localizable.strings index 5999c05288..cfe273873e 100644 Binary files a/iOSClient/Supporting Files/lb.lproj/Localizable.strings and b/iOSClient/Supporting Files/lb.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/lo.lproj/Localizable.strings b/iOSClient/Supporting Files/lo.lproj/Localizable.strings index 9877876098..18c89bda7d 100644 Binary files a/iOSClient/Supporting Files/lo.lproj/Localizable.strings and b/iOSClient/Supporting Files/lo.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/lt_LT.lproj/Localizable.strings b/iOSClient/Supporting Files/lt_LT.lproj/Localizable.strings index b9fea53c94..50a1bc547f 100644 Binary files a/iOSClient/Supporting Files/lt_LT.lproj/Localizable.strings and b/iOSClient/Supporting Files/lt_LT.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/lv.lproj/Localizable.strings b/iOSClient/Supporting Files/lv.lproj/Localizable.strings index b1fa73e868..e756a540fb 100644 Binary files a/iOSClient/Supporting Files/lv.lproj/Localizable.strings and b/iOSClient/Supporting Files/lv.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/mk.lproj/Localizable.strings b/iOSClient/Supporting Files/mk.lproj/Localizable.strings index 124ccd8e60..7cf158a243 100644 Binary files a/iOSClient/Supporting Files/mk.lproj/Localizable.strings and b/iOSClient/Supporting Files/mk.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/mn.lproj/Localizable.strings b/iOSClient/Supporting Files/mn.lproj/Localizable.strings index bc9e93ba56..c8309250e9 100644 Binary files a/iOSClient/Supporting Files/mn.lproj/Localizable.strings and b/iOSClient/Supporting Files/mn.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/mr.lproj/Localizable.strings b/iOSClient/Supporting Files/mr.lproj/Localizable.strings index dcabcaebe8..1e042147ca 100644 Binary files a/iOSClient/Supporting Files/mr.lproj/Localizable.strings and b/iOSClient/Supporting Files/mr.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ms_MY.lproj/Localizable.strings b/iOSClient/Supporting Files/ms_MY.lproj/Localizable.strings index 70ced56a97..8189e8c9c8 100644 Binary files a/iOSClient/Supporting Files/ms_MY.lproj/Localizable.strings and b/iOSClient/Supporting Files/ms_MY.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/my.lproj/Localizable.strings b/iOSClient/Supporting Files/my.lproj/Localizable.strings index 647959e43b..7d5cc70173 100644 Binary files a/iOSClient/Supporting Files/my.lproj/Localizable.strings and b/iOSClient/Supporting Files/my.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/nb-NO.lproj/Localizable.strings b/iOSClient/Supporting Files/nb-NO.lproj/Localizable.strings index 1cd413821c..556d0128bb 100644 Binary files a/iOSClient/Supporting Files/nb-NO.lproj/Localizable.strings and b/iOSClient/Supporting Files/nb-NO.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ne.lproj/Localizable.strings b/iOSClient/Supporting Files/ne.lproj/Localizable.strings index 6b95eaef01..e5324021fe 100644 Binary files a/iOSClient/Supporting Files/ne.lproj/Localizable.strings and b/iOSClient/Supporting Files/ne.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/nl.lproj/Localizable.strings b/iOSClient/Supporting Files/nl.lproj/Localizable.strings index e296ab78f2..30cfe9e3e2 100644 Binary files a/iOSClient/Supporting Files/nl.lproj/Localizable.strings and b/iOSClient/Supporting Files/nl.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/nn_NO.lproj/Localizable.strings b/iOSClient/Supporting Files/nn_NO.lproj/Localizable.strings index e393f68823..aff4c0327c 100644 Binary files a/iOSClient/Supporting Files/nn_NO.lproj/Localizable.strings and b/iOSClient/Supporting Files/nn_NO.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/oc.lproj/Localizable.strings b/iOSClient/Supporting Files/oc.lproj/Localizable.strings index 5a7021fc22..d6fb47b79f 100644 Binary files a/iOSClient/Supporting Files/oc.lproj/Localizable.strings and b/iOSClient/Supporting Files/oc.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/pl.lproj/Localizable.strings b/iOSClient/Supporting Files/pl.lproj/Localizable.strings index ab42d53c5a..4ea3650460 100644 Binary files a/iOSClient/Supporting Files/pl.lproj/Localizable.strings and b/iOSClient/Supporting Files/pl.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ps.lproj/Localizable.strings b/iOSClient/Supporting Files/ps.lproj/Localizable.strings index 9305fc5e2a..7cba89ea85 100644 Binary files a/iOSClient/Supporting Files/ps.lproj/Localizable.strings and b/iOSClient/Supporting Files/ps.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/pt-BR.lproj/Localizable.strings b/iOSClient/Supporting Files/pt-BR.lproj/Localizable.strings index ef16ea09b3..5442621558 100644 Binary files a/iOSClient/Supporting Files/pt-BR.lproj/Localizable.strings and b/iOSClient/Supporting Files/pt-BR.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/pt-PT.lproj/Localizable.strings b/iOSClient/Supporting Files/pt-PT.lproj/Localizable.strings index be0856a6e9..6766e38876 100644 Binary files a/iOSClient/Supporting Files/pt-PT.lproj/Localizable.strings and b/iOSClient/Supporting Files/pt-PT.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ro.lproj/Localizable.strings b/iOSClient/Supporting Files/ro.lproj/Localizable.strings index c706e28a7a..9317d22482 100644 Binary files a/iOSClient/Supporting Files/ro.lproj/Localizable.strings and b/iOSClient/Supporting Files/ro.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ru.lproj/Localizable.strings b/iOSClient/Supporting Files/ru.lproj/Localizable.strings index 614b3dcd2a..1d13ba1f50 100644 Binary files a/iOSClient/Supporting Files/ru.lproj/Localizable.strings and b/iOSClient/Supporting Files/ru.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/sc.lproj/Localizable.strings b/iOSClient/Supporting Files/sc.lproj/Localizable.strings index 8ff6b0a5ba..f54f1e93ad 100644 Binary files a/iOSClient/Supporting Files/sc.lproj/Localizable.strings and b/iOSClient/Supporting Files/sc.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/si.lproj/Localizable.strings b/iOSClient/Supporting Files/si.lproj/Localizable.strings index faced2ebaa..8d4b18ce70 100644 Binary files a/iOSClient/Supporting Files/si.lproj/Localizable.strings and b/iOSClient/Supporting Files/si.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/sk-SK.lproj/Localizable.strings b/iOSClient/Supporting Files/sk-SK.lproj/Localizable.strings index 032f1ba077..d198beb08d 100644 Binary files a/iOSClient/Supporting Files/sk-SK.lproj/Localizable.strings and b/iOSClient/Supporting Files/sk-SK.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/sl.lproj/Localizable.strings b/iOSClient/Supporting Files/sl.lproj/Localizable.strings index 29ac11cdf6..1def6054de 100644 Binary files a/iOSClient/Supporting Files/sl.lproj/Localizable.strings and b/iOSClient/Supporting Files/sl.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/sq.lproj/Localizable.strings b/iOSClient/Supporting Files/sq.lproj/Localizable.strings index 8c76dd46c5..104e85b414 100644 Binary files a/iOSClient/Supporting Files/sq.lproj/Localizable.strings and b/iOSClient/Supporting Files/sq.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/sr.lproj/Localizable.strings b/iOSClient/Supporting Files/sr.lproj/Localizable.strings index 4f91b0535b..76fb8ee55f 100644 Binary files a/iOSClient/Supporting Files/sr.lproj/Localizable.strings and b/iOSClient/Supporting Files/sr.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/sr@latin.lproj/Localizable.strings b/iOSClient/Supporting Files/sr@latin.lproj/Localizable.strings index f4d5af123d..3c1a71485e 100644 Binary files a/iOSClient/Supporting Files/sr@latin.lproj/Localizable.strings and b/iOSClient/Supporting Files/sr@latin.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/sv.lproj/Localizable.strings b/iOSClient/Supporting Files/sv.lproj/Localizable.strings index a6bc2d7fea..f7bfacebba 100644 Binary files a/iOSClient/Supporting Files/sv.lproj/Localizable.strings and b/iOSClient/Supporting Files/sv.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/sw.lproj/Localizable.strings b/iOSClient/Supporting Files/sw.lproj/Localizable.strings index 94689da437..489732df4d 100644 Binary files a/iOSClient/Supporting Files/sw.lproj/Localizable.strings and b/iOSClient/Supporting Files/sw.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ta.lproj/Localizable.strings b/iOSClient/Supporting Files/ta.lproj/Localizable.strings index 57ceee17aa..a2d9f0b058 100644 Binary files a/iOSClient/Supporting Files/ta.lproj/Localizable.strings and b/iOSClient/Supporting Files/ta.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/th_TH.lproj/Localizable.strings b/iOSClient/Supporting Files/th_TH.lproj/Localizable.strings index 6a988af33d..4064ae134f 100644 Binary files a/iOSClient/Supporting Files/th_TH.lproj/Localizable.strings and b/iOSClient/Supporting Files/th_TH.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/tk.lproj/Localizable.strings b/iOSClient/Supporting Files/tk.lproj/Localizable.strings index f5cf625859..1eb111186f 100644 Binary files a/iOSClient/Supporting Files/tk.lproj/Localizable.strings and b/iOSClient/Supporting Files/tk.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/tr.lproj/Localizable.strings b/iOSClient/Supporting Files/tr.lproj/Localizable.strings index ef7dd3b79b..39c5f80afe 100644 Binary files a/iOSClient/Supporting Files/tr.lproj/Localizable.strings and b/iOSClient/Supporting Files/tr.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ug.lproj/Localizable.strings b/iOSClient/Supporting Files/ug.lproj/Localizable.strings index 4c3435276a..095926929a 100644 Binary files a/iOSClient/Supporting Files/ug.lproj/Localizable.strings and b/iOSClient/Supporting Files/ug.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/uk.lproj/Localizable.strings b/iOSClient/Supporting Files/uk.lproj/Localizable.strings index eb340db7a9..6e38a2e689 100644 Binary files a/iOSClient/Supporting Files/uk.lproj/Localizable.strings and b/iOSClient/Supporting Files/uk.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/ur_PK.lproj/Localizable.strings b/iOSClient/Supporting Files/ur_PK.lproj/Localizable.strings index 226e3b3aed..531b7e156f 100644 Binary files a/iOSClient/Supporting Files/ur_PK.lproj/Localizable.strings and b/iOSClient/Supporting Files/ur_PK.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/uz.lproj/Localizable.strings b/iOSClient/Supporting Files/uz.lproj/Localizable.strings index 94689da437..489732df4d 100644 Binary files a/iOSClient/Supporting Files/uz.lproj/Localizable.strings and b/iOSClient/Supporting Files/uz.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/vi.lproj/Localizable.strings b/iOSClient/Supporting Files/vi.lproj/Localizable.strings index b6b0ba9550..208e3bbddc 100644 Binary files a/iOSClient/Supporting Files/vi.lproj/Localizable.strings and b/iOSClient/Supporting Files/vi.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/zh-Hans.lproj/Localizable.strings b/iOSClient/Supporting Files/zh-Hans.lproj/Localizable.strings index f37c368ead..a9e8fe5466 100644 Binary files a/iOSClient/Supporting Files/zh-Hans.lproj/Localizable.strings and b/iOSClient/Supporting Files/zh-Hans.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/zh-Hant-TW.lproj/Localizable.strings b/iOSClient/Supporting Files/zh-Hant-TW.lproj/Localizable.strings index ee89163c63..8ce0265011 100644 Binary files a/iOSClient/Supporting Files/zh-Hant-TW.lproj/Localizable.strings and b/iOSClient/Supporting Files/zh-Hant-TW.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/zh_HK.lproj/Localizable.strings b/iOSClient/Supporting Files/zh_HK.lproj/Localizable.strings index fbbfb8129d..23bf4d2355 100644 Binary files a/iOSClient/Supporting Files/zh_HK.lproj/Localizable.strings and b/iOSClient/Supporting Files/zh_HK.lproj/Localizable.strings differ diff --git a/iOSClient/Supporting Files/zu_ZA.lproj/Localizable.strings b/iOSClient/Supporting Files/zu_ZA.lproj/Localizable.strings index 94689da437..489732df4d 100644 Binary files a/iOSClient/Supporting Files/zu_ZA.lproj/Localizable.strings and b/iOSClient/Supporting Files/zu_ZA.lproj/Localizable.strings differ diff --git a/iOSClient/Transfers/NCTransferCell.swift b/iOSClient/Transfers/NCTransferCell.swift index d761b1d3b6..4b764e9350 100755 --- a/iOSClient/Transfers/NCTransferCell.swift +++ b/iOSClient/Transfers/NCTransferCell.swift @@ -141,7 +141,7 @@ class NCTransferCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellP } func writeInfoDateSize(date: NSDate, size: Int64) { - labelInfo.text = CCUtility.dateDiff(date as Date) + " · " + CCUtility.transformedSize(size) + labelInfo.text = CCUtility.dateDiff(date as Date) + " · " + NCUtilityFileSystem.shared.transformedSize(size) } } diff --git a/iOSClient/Transfers/NCTransfers.swift b/iOSClient/Transfers/NCTransfers.swift index 694de0d188..a60d188762 100644 --- a/iOSClient/Transfers/NCTransfers.swift +++ b/iOSClient/Transfers/NCTransfers.swift @@ -196,7 +196,7 @@ class NCTransfers: NCCollectionViewCommon, NCTransferCellDelegate { } else { cell.imageItem.image = UIImage(named: "file") } - cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size) + cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + NCUtilityFileSystem.shared.transformedSize(metadata.size) if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading { cell.progressView.isHidden = false } else { @@ -206,22 +206,22 @@ class NCTransfers: NCCollectionViewCommon, NCTransferCellDelegate { switch metadata.status { case NCGlobal.shared.metadataStatusWaitDownload: cell.labelStatus.text = NSLocalizedString("_status_wait_download_", comment: "") - cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + cell.labelInfo.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) case NCGlobal.shared.metadataStatusInDownload: cell.labelStatus.text = NSLocalizedString("_status_in_download_", comment: "") - cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + cell.labelInfo.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) case NCGlobal.shared.metadataStatusDownloading: cell.labelStatus.text = NSLocalizedString("_status_downloading_", comment: "") - cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ …" + cell.labelInfo.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) + " - ↓ …" case NCGlobal.shared.metadataStatusWaitUpload: cell.labelStatus.text = NSLocalizedString("_status_wait_upload_", comment: "") cell.labelInfo.text = "" case NCGlobal.shared.metadataStatusInUpload: cell.labelStatus.text = NSLocalizedString("_status_in_upload_", comment: "") - cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + cell.labelInfo.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) case NCGlobal.shared.metadataStatusUploading: cell.labelStatus.text = NSLocalizedString("_status_uploading_", comment: "") - cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ …" + cell.labelInfo.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) + " - ↑ …" case NCGlobal.shared.metadataStatusUploadError: cell.labelStatus.text = NSLocalizedString("_status_upload_error_", comment: "") cell.labelInfo.text = metadata.sessionError diff --git a/iOSClient/Trash/Cell/NCTrashListCell+NCTrashCellProtocol.swift b/iOSClient/Trash/Cell/NCTrashListCell+NCTrashCellProtocol.swift index 145c6f103f..bbb65a20a6 100644 --- a/iOSClient/Trash/Cell/NCTrashListCell+NCTrashCellProtocol.swift +++ b/iOSClient/Trash/Cell/NCTrashListCell+NCTrashCellProtocol.swift @@ -162,7 +162,7 @@ extension NCTrashCellProtocol where Self: UICollectionViewCell { self.imageItem.image = NCBrandColor.cacheImages.folder } else { self.imageItem.image = image - self.labelInfo?.text = (self.labelInfo?.text ?? "") + " · " + CCUtility.transformedSize(tableTrash.size) + self.labelInfo?.text = (self.labelInfo?.text ?? "") + " · " + NCUtilityFileSystem.shared.transformedSize(tableTrash.size) } self.accessibilityLabel = tableTrash.trashbinFileName + ", " + (self.labelInfo?.text ?? "") } diff --git a/iOSClient/Trash/NCTrash+CollectionView.swift b/iOSClient/Trash/NCTrash+CollectionView.swift index 48ba4202fc..01df7bfd74 100644 --- a/iOSClient/Trash/NCTrash+CollectionView.swift +++ b/iOSClient/Trash/NCTrash+CollectionView.swift @@ -68,10 +68,10 @@ extension NCTrash: UICollectionViewDataSource { image = UIImage(named: tableTrash.iconName) } - if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)) { - image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)) + if FileManager().fileExists(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)) { + image = UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)) } else { - if tableTrash.hasPreview && !CCUtility.fileProviderStoragePreviewIconExists(tableTrash.fileId, etag: tableTrash.fileName) { + if tableTrash.hasPreview && !NCUtilityFileSystem.shared.fileProviderStoragePreviewIconExists(tableTrash.fileId, etag: tableTrash.fileName) { downloadThumbnail(with: tableTrash, indexPath: indexPath) } } @@ -123,9 +123,9 @@ extension NCTrash: UICollectionViewDataSource { } if files > 1 { - filesText = "\(files) " + NSLocalizedString("_files_", comment: "") + " " + CCUtility.transformedSize(size) + filesText = "\(files) " + NSLocalizedString("_files_", comment: "") + " " + NCUtilityFileSystem.shared.transformedSize(size) } else if files == 1 { - filesText = "1 " + NSLocalizedString("_file_", comment: "") + " " + CCUtility.transformedSize(size) + filesText = "1 " + NSLocalizedString("_file_", comment: "") + " " + NCUtilityFileSystem.shared.transformedSize(size) } if foldersText.isEmpty { diff --git a/iOSClient/Trash/NCTrash.swift b/iOSClient/Trash/NCTrash.swift index 45c9eb9ac1..70fcb1f452 100644 --- a/iOSClient/Trash/NCTrash.swift +++ b/iOSClient/Trash/NCTrash.swift @@ -347,8 +347,8 @@ extension NCTrash { func downloadThumbnail(with tableTrash: tableTrash, indexPath: IndexPath) { - let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(tableTrash.fileId, etag: tableTrash.fileName)! - let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName)! + let fileNamePreviewLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(tableTrash.fileId, etag: tableTrash.fileName) + let fileNameIconLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(tableTrash.fileId, etag: tableTrash.fileName) NextcloudKit.shared.downloadPreview(fileNamePathOrFileId: tableTrash.fileId, fileNamePreviewLocalPath: fileNamePreviewLocalPath, diff --git a/iOSClient/Utility/CCUtility.h b/iOSClient/Utility/CCUtility.h index 51f7516cac..a8859b23c5 100644 --- a/iOSClient/Utility/CCUtility.h +++ b/iOSClient/Utility/CCUtility.h @@ -27,7 +27,6 @@ #import #import #import -#import #import #import @@ -35,200 +34,9 @@ @interface CCUtility : NSObject -// ===== KeyChainStore ===== - -// GET/SET - -+ (void)deleteAllChainStore; -+ (void)storeAllChainInService; - -+ (NSString *)getPasscode; -+ (void)setPasscode:(NSString *)passcode; - -+ (BOOL)getNotPasscodeAtStart; -+ (void)setNotPasscodeAtStart:(BOOL)set; - -+ (BOOL)getEnableTouchFaceID; -+ (void)setEnableTouchFaceID:(BOOL)set; - -+ (BOOL)isPasscodeAtStartEnabled; - -+ (NSString *)getGroupBySettings; -+ (void)setGroupBySettings:(NSString *)groupby; - -+ (BOOL)getIntro; -+ (void)setIntro:(BOOL)set; - -+ (NSString *)getIncrementalNumber; - -+ (NSString *)getAccountExt; -+ (void)setAccountExt:(NSString *)account; - -+ (NSString *)getServerUrlExt; -+ (void)setServerUrlExt:(NSString *)serverUrl; - -+ (NSString *)getTitleServerUrlExt; -+ (void)setTitleServerUrlExt:(NSString *)titleServerUrl; - -+ (NSString *)getFileNameExt; -+ (void)setFileNameExt:(NSString *)fileName; - -+ (NSString *)getEmail; -+ (void)setEmail:(NSString *)email; - -+ (NSString *)getHint; -+ (void)setHint:(NSString *)hint; - -+ (BOOL)getOriginalFileName:(NSString *)key; -+ (void)setOriginalFileName:(BOOL)value key:(NSString *)key; - -+ (NSString *)getFileNameMask:(NSString *)key; -+ (void)setFileNameMask:(NSString *)mask key:(NSString *)key; - -+ (BOOL)getFileNameType:(NSString *)key; -+ (void)setFileNameType:(BOOL)prefix key:(NSString *)key; - -+ (BOOL)getActivityVerboseHigh; -+ (void)setActivityVerboseHigh:(BOOL)debug; - -+ (BOOL)getShowHiddenFiles; -+ (void)setShowHiddenFiles:(BOOL)show; - -+ (BOOL)getFormatCompatibility; -+ (void)setFormatCompatibility:(BOOL)set; - -// E2EE ------------------------------------------- - -+ (NSString *)getEndToEndCertificate:(NSString *)account; -+ (void)setEndToEndCertificate:(NSString *)account certificate:(NSString *)certificate; - -+ (NSString *)getEndToEndPrivateKey:(NSString *)account; -+ (void)setEndToEndPrivateKey:(NSString *)account privateKey:(NSString *)privateKey; - -+ (NSString *)getEndToEndPublicKey:(NSString *)account; -+ (void)setEndToEndPublicKey:(NSString *)account publicKey:(NSString *)publicKey; - -+ (NSString *)getEndToEndPassphrase:(NSString *)account; -+ (void)setEndToEndPassphrase:(NSString *)account passphrase:(NSString *)passphrase; - -+ (BOOL)isEndToEndEnabled:(NSString *)account; - -// E2EE ------------------------------------------- - -+ (void)clearAllKeysEndToEnd:(NSString *)account; - -+ (BOOL)getDisableFilesApp; -+ (void)setDisableFilesApp:(BOOL)disable; - -+ (void)setPushNotificationPublicKey:(NSString *)account data:(NSData *)data; -+ (NSData *)getPushNotificationPublicKey:(NSString *)account; -+ (void)setPushNotificationSubscribingPublicKey:(NSString *)account publicKey:(NSString *)publicKey; -+ (NSString *)getPushNotificationSubscribingPublicKey:(NSString *)account; -+ (void)setPushNotificationPrivateKey:(NSString *)account data:(NSData *)data; -+ (NSData *)getPushNotificationPrivateKey:(NSString *)account; -+ (void)setPushNotificationToken:(NSString *)account token:(NSString *)token; -+ (NSString *)getPushNotificationToken:(NSString *)account; -+ (void)setPushNotificationDeviceIdentifier:(NSString *)account deviceIdentifier:(NSString *)deviceIdentifier; -+ (NSString *)getPushNotificationDeviceIdentifier:(NSString *)account; -+ (void)setPushNotificationDeviceIdentifierSignature:(NSString *)account deviceIdentifierSignature:(NSString *)deviceIdentifierSignature; -+ (NSString *)getPushNotificationDeviceIdentifierSignature:(NSString *)account; -+ (void)clearAllKeysPushNotification:(NSString *)account; - -+ (NSInteger)getMediaWidthImage; -+ (void)setMediaWidthImage:(NSInteger)width; - -+ (BOOL)getDisableCrashservice; -+ (void)setDisableCrashservice:(BOOL)disable; - -+ (void)setPassword:(NSString *)account password:(NSString *)password; -+ (NSString *)getPassword:(NSString *)account; - -+ (void)setHCBusinessType:(NSString *)professions; -+ (NSString *)getHCBusinessType; - -+ (NSData *)getDatabaseEncryptionKey; - -+ (BOOL)getLivePhoto; -+ (void)setLivePhoto:(BOOL)set; - -+ (NSString *)getMediaSortDate; -+ (void)setMediaSortDate:(NSString *)value; - -+ (BOOL)getTextRecognitionStatus; -+ (void)setTextRecognitionStatus:(BOOL)value; -+ (BOOL)getDeleteAllScanImages; -+ (void)setDeleteAllScanImages:(BOOL)value; -+ (NSString *)getDirectoryScanDocument; -+ (void)setDirectoryScanDocument:(NSString *)value; -+ (double)getQualityScanDocument; -+ (void)setQualityScanDocument:(double)value; - -+ (NSInteger)getLogLevel; -+ (void)setLogLevel:(NSInteger)value; - -+ (BOOL)getAccountRequest; -+ (void)setAccountRequest:(BOOL)set; - -+ (NSInteger)getCleanUpDay; -+ (void)setCleanUpDay:(NSInteger)days; - -+ (BOOL)getPrivacyScreenEnabled; -+ (void)setPrivacyScreenEnabled:(BOOL)set; - -+ (BOOL)getRemovePhotoCameraRoll; -+ (void)setRemovePhotoCameraRoll:(BOOL)set; - -// ===== Varius ===== - -+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL; - + (NSString *)dateDiff:(NSDate *)convertedDate; -+ (NSString *)transformedSize:(int64_t)value; - -+ (NSString *)removeForbiddenCharactersServer:(NSString *)fileName; -+ (NSString *)removeForbiddenCharactersFileSystem:(NSString *)fileName; - -+ (NSString *)stringAppendServerUrl:(NSString *)serverUrl addFileName:(NSString *)addFileName; - -+ (NSString *)createFileNameDate:(NSString *)fileName extension:(NSString *)extension; + (NSString *)createFileName:(NSString *)fileName fileDate:(NSDate *)fileDate fileType:(PHAssetMediaType)fileType keyFileName:(NSString *)keyFileName keyFileNameType:(NSString *)keyFileNameType keyFileNameOriginal:(NSString *)keyFileNameOriginal forcedNewFileName:(BOOL)forcedNewFileName; - -+ (void)createDirectoryStandard; - -+ (NSURL *)getDirectoryGroup; -+ (NSString *)getDirectoryDocuments; -+ (NSString *)getDirectoryReaderMetadata; -+ (NSString *)getDirectoryAudio; -+ (NSString *)getDirectoryCerificates; -+ (NSString *)getDirectoryUserData; -+ (NSString *)getDirectoryProviderStorage; -+ (NSString *)getDirectoryProviderStorageOcId:(NSString *)ocId; -+ (NSString *)getDirectoryProviderStorageOcId:(NSString *)ocId fileNameView:(NSString *)fileNameView; -+ (NSString *)getDirectoryProviderStorageIconOcId:(NSString *)ocId etag:(NSString *)etag; -+ (NSString *)getDirectoryProviderStoragePreviewOcId:(NSString *)ocId etag:(NSString *)etag; -+ (BOOL)fileProviderStorageExists:(tableMetadata *)metadata; -+ (int64_t)fileProviderStorageSize:(NSString *)ocId fileNameView:(NSString *)fileNameView; -+ (BOOL)fileProviderStoragePreviewIconExists:(NSString *)ocId etag:(NSString *)etag; - -+ (void)removeGroupApplicationSupport; -+ (void)removeGroupLibraryDirectory; -+ (void)removeGroupDirectoryProviderStorage; -+ (void)removeDocumentsDirectory; -+ (void)removeTemporaryDirectory; -+ (void)emptyTemporaryDirectory; - + (NSString *)getTitleSectionDate:(NSDate *)date; - -+ (void)moveFileAtPath:(NSString *)atPath toPath:(NSString *)toPath; -+ (void)copyFileAtPath:(NSString *)atPath toPath:(NSString *)toPath; -+ (void)removeFileAtPath:(NSString *)atPath; -+ (void)createDirectoryAtPath:(NSString *)atPath; - -+ (NSString *)returnPathfromServerUrl:(NSString *)serverUrl urlBase:(NSString *)urlBase userId:(NSString *)userId account:(NSString *)account; -+ (NSString *)returnFileNamePathFromFileName:(NSString *)metadataFileName serverUrl:(NSString *)serverUrl urlBase:(NSString *)urlBase userId:(NSString *)userId account:(NSString *)account; - -+ (NSString *)getDirectoryScan; - + (NSString *)getMimeType:(NSString *)fileNameView; // ===== Share Permissions ===== @@ -246,7 +54,6 @@ + (NSString *)getExtension:(NSString*)fileName; + (NSDate *)datetimeWithOutTime:(NSDate *)datDate; -+ (NSString *)valueForKey:(NSString *)key fromQueryItems:(NSArray *)queryItems; + (NSDate *)getATime:(const char *)path; @end diff --git a/iOSClient/Utility/CCUtility.m b/iOSClient/Utility/CCUtility.m index 94497fcded..e5f8045b6d 100644 --- a/iOSClient/Utility/CCUtility.m +++ b/iOSClient/Utility/CCUtility.m @@ -28,701 +28,12 @@ #import #include - -#define INTRO_MessageType @"MessageType_" - -#define E2E_certificate @"EndToEndCertificate_" -#define E2E_PrivateKey @"EndToEndPrivateKey_" -#define E2E_Passphrase @"EndToEndPassphrase_" -#define E2E_PublicKey @"EndToEndPublicKeyServer_" - @implementation CCUtility -#pragma -------------------------------------------------------------------------------------------- -#pragma mark ======================= KeyChainStore ================================== -#pragma -------------------------------------------------------------------------------------------- - -+ (void)deleteAllChainStore -{ - [UICKeyChainStore removeAllItems]; - [UICKeyChainStore removeAllItemsForService:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)storeAllChainInService -{ - UICKeyChainStore *store = [UICKeyChainStore keyChainStore]; - - NSArray *items = store.allItems; - - for (NSDictionary *item in items) { - - [UICKeyChainStore setString:[item objectForKey:@"value"] forKey:[item objectForKey:@"key"] service:NCGlobal.shared.serviceShareKeyChain]; - [UICKeyChainStore removeItemForKey:[item objectForKey:@"key"]]; - } -} - -#pragma ------------------------------ GET/SET - -+ (NSString *)getPasscode -{ - return [UICKeyChainStore stringForKey:@"passcodeBlock" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setPasscode:(NSString *)passcode -{ - [UICKeyChainStore setString:passcode forKey:@"passcodeBlock" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getNotPasscodeAtStart -{ - return [[UICKeyChainStore stringForKey:@"notPasscodeAtStart" service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setNotPasscodeAtStart:(BOOL)set -{ - NSString *sSet = (set) ? @"true" : @"false"; - [UICKeyChainStore setString:sSet forKey:@"notPasscodeAtStart" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getEnableTouchFaceID -{ - NSString *valueString = [UICKeyChainStore stringForKey:@"enableTouchFaceID" service:NCGlobal.shared.serviceShareKeyChain]; - - // Default TRUE - if (valueString == nil) { - [self setEnableTouchFaceID:YES]; - return true; - } - - return [valueString boolValue]; -} - -+ (void)setEnableTouchFaceID:(BOOL)set -{ - NSString *sSet = (set) ? @"true" : @"false"; - [UICKeyChainStore setString:sSet forKey:@"enableTouchFaceID" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)isPasscodeAtStartEnabled -{ - if ([self getPasscode].length > 0 && ![self getNotPasscodeAtStart]) return true; - else return false; -} - -+ (NSString *)getGroupBySettings -{ - NSString *groupby = [UICKeyChainStore stringForKey:@"groupby" service:NCGlobal.shared.serviceShareKeyChain]; - - if (groupby == nil) { - - [self setGroupBySettings:@"none"]; - return @"none"; - } - - return @"none"; - - //return groupby; -} - -+ (void)setGroupBySettings:(NSString *)groupby -{ - [UICKeyChainStore setString:groupby forKey:@"groupby" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getIntro -{ - // Set compatibility old version don't touch me - if ([[UICKeyChainStore stringForKey:[INTRO_MessageType stringByAppendingString:@"Intro"] service:NCGlobal.shared.serviceShareKeyChain] boolValue] == YES) { - [CCUtility setIntro:YES]; - return YES; - } - - return [[UICKeyChainStore stringForKey:@"intro" service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (BOOL)getIntroMessageOldVersion -{ - NSString *key = [INTRO_MessageType stringByAppendingString:@"Intro"]; - - return [[UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setIntro:(BOOL)set -{ - NSString *sIntro = (set) ? @"true" : @"false"; - [UICKeyChainStore setString:sIntro forKey:@"intro" service:NCGlobal.shared.serviceShareKeyChain]; - -} - -+ (NSString *)getIncrementalNumber -{ - long number = [[UICKeyChainStore stringForKey:@"incrementalnumber" service:NCGlobal.shared.serviceShareKeyChain] intValue]; - - number++; - if (number >= 9999) number = 1; - - [UICKeyChainStore setString:[NSString stringWithFormat:@"%ld", number] forKey:@"incrementalnumber" service:NCGlobal.shared.serviceShareKeyChain]; - - return [NSString stringWithFormat:@"%04ld", number]; -} - -+ (NSString *)getAccountExt -{ - return [UICKeyChainStore stringForKey:@"accountExt" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setAccountExt:(NSString *)account -{ - [UICKeyChainStore setString:account forKey:@"accountExt" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getServerUrlExt -{ - return [UICKeyChainStore stringForKey:@"serverUrlExt" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setServerUrlExt:(NSString *)serverUrl -{ - [UICKeyChainStore setString:serverUrl forKey:@"serverUrlExt" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getTitleServerUrlExt -{ - return [UICKeyChainStore stringForKey:@"titleServerUrlExt" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setTitleServerUrlExt:(NSString *)titleServerUrl -{ - [UICKeyChainStore setString:titleServerUrl forKey:@"titleServerUrlExt" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getFileNameExt -{ - return [UICKeyChainStore stringForKey:@"fileNameExt" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setFileNameExt:(NSString *)fileName -{ - [UICKeyChainStore setString:fileName forKey:@"fileNameExt" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getEmail -{ - return [UICKeyChainStore stringForKey:@"email" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setEmail:(NSString *)email -{ - [UICKeyChainStore setString:email forKey:@"email" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getHint -{ - return [UICKeyChainStore stringForKey:@"hint" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setHint:(NSString *)hint -{ - [UICKeyChainStore setString:hint forKey:@"hint" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getOriginalFileName:(NSString *)key -{ - return [[UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setOriginalFileName:(BOOL)value key:(NSString *)key -{ - NSString *sValue = (value) ? @"true" : @"false"; - [UICKeyChainStore setString:sValue forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getFileNameMask:(NSString *)key -{ - NSString *mask = [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain]; - - if (mask == nil) - mask = @""; - - return mask; -} - -+ (void)setFileNameMask:(NSString *)mask key:(NSString *)key -{ - [UICKeyChainStore setString:mask forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getFileNameType:(NSString *)key -{ - return [[UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setFileNameType:(BOOL)prefix key:(NSString *)key -{ - NSString *sPrefix = (prefix) ? @"true" : @"false"; - [UICKeyChainStore setString:sPrefix forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getActivityVerboseHigh -{ - return [[UICKeyChainStore stringForKey:@"activityVerboseHigh" service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setActivityVerboseHigh:(BOOL)high -{ - NSString *sHigh = (high) ? @"true" : @"false"; - [UICKeyChainStore setString:sHigh forKey:@"activityVerboseHigh" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getShowHiddenFiles -{ - return [[UICKeyChainStore stringForKey:@"showHiddenFiles" service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setShowHiddenFiles:(BOOL)show -{ - NSString *sShow = (show) ? @"true" : @"false"; - [UICKeyChainStore setString:sShow forKey:@"showHiddenFiles" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getFormatCompatibility -{ - NSString *valueString = [UICKeyChainStore stringForKey:@"formatCompatibility" service:NCGlobal.shared.serviceShareKeyChain]; - - // Default TRUE - if (valueString == nil) { - [self setFormatCompatibility:YES]; - return true; - } - - return [valueString boolValue]; -} - -+ (void)setFormatCompatibility:(BOOL)set -{ - NSString *sSet = (set) ? @"true" : @"false"; - [UICKeyChainStore setString:sSet forKey:@"formatCompatibility" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getEndToEndCertificate:(NSString *)account -{ - NSString *key, *certificate; - - key = [E2E_certificate stringByAppendingString:account]; - certificate = [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain]; - - // OLD VERSION - if (certificate == nil) { - key = [@"EndToEndPublicKey_" stringByAppendingString:account]; - certificate = [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain]; - } - - return certificate; -} - -+ (void)setEndToEndCertificate:(NSString *)account certificate:(NSString *)certificate -{ - NSString *key = [E2E_certificate stringByAppendingString:account]; - [UICKeyChainStore setString:certificate forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getEndToEndPrivateKey:(NSString *)account -{ - NSString *key = [E2E_PrivateKey stringByAppendingString:account]; - return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setEndToEndPrivateKey:(NSString *)account privateKey:(NSString *)privateKey -{ - NSString *key = [E2E_PrivateKey stringByAppendingString:account]; - [UICKeyChainStore setString:privateKey forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getEndToEndPublicKey:(NSString *)account -{ - NSString *key = [E2E_PublicKey stringByAppendingString:account]; - return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setEndToEndPublicKey:(NSString *)account publicKey:(NSString *)publicKey -{ - NSString *key = [E2E_PublicKey stringByAppendingString:account]; - [UICKeyChainStore setString:publicKey forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getEndToEndPassphrase:(NSString *)account -{ - NSString *key = [E2E_Passphrase stringByAppendingString:account]; - return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setEndToEndPassphrase:(NSString *)account passphrase:(NSString *)passphrase -{ - NSString *key = [E2E_Passphrase stringByAppendingString:account]; - [UICKeyChainStore setString:passphrase forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)isEndToEndEnabled:(NSString *)account -{ - NSString* versionE2EE = [[NCGlobal shared] capabilityE2EEApiVersion]; - - NSString *certificate = [self getEndToEndCertificate:account]; - NSString *publicKey = [self getEndToEndPublicKey:account]; - NSString *privateKey = [self getEndToEndPrivateKey:account]; - NSString *passphrase = [self getEndToEndPassphrase:account]; - - if (passphrase.length > 0 && privateKey.length > 0 && certificate.length > 0 && publicKey.length > 0 && [NCGlobal.shared.e2eeVersions containsObject:versionE2EE]) { - return YES; - } else { - return NO; - } -} - -+ (void)clearAllKeysEndToEnd:(NSString *)account -{ - [self setEndToEndCertificate:account certificate:nil]; - [self setEndToEndPrivateKey:account privateKey:nil]; - [self setEndToEndPublicKey:account publicKey:nil]; - [self setEndToEndPassphrase:account passphrase:nil]; - - // OLD - [UICKeyChainStore setString:nil forKey:[@"EndToEndPublicKey_" stringByAppendingString:account] service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getDisableFilesApp -{ - return [[UICKeyChainStore stringForKey:@"disablefilesapp" service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setDisableFilesApp:(BOOL)disable -{ - NSString *sDisable = (disable) ? @"true" : @"false"; - [UICKeyChainStore setString:sDisable forKey:@"disablefilesapp" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setPushNotificationPublicKey:(NSString *)account data:(NSData *)data -{ - NSString *key = [@"PNPublicKey" stringByAppendingString:account]; - [UICKeyChainStore setData:data forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSData *)getPushNotificationPublicKey:(NSString *)account -{ - NSString *key = [@"PNPublicKey" stringByAppendingString:account]; - return [UICKeyChainStore dataForKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setPushNotificationSubscribingPublicKey:(NSString *)account publicKey:(NSString *)publicKey -{ - NSString *key = [@"PNSubscribingPublicKey" stringByAppendingString:account]; - [UICKeyChainStore setString:publicKey forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getPushNotificationSubscribingPublicKey:(NSString *)account -{ - NSString *key = [@"PNSubscribingPublicKey" stringByAppendingString:account]; - return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setPushNotificationPrivateKey:(NSString *)account data:(NSData *)data -{ - NSString *key = [@"PNPrivateKey" stringByAppendingString:account]; - [UICKeyChainStore setData:data forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSData *)getPushNotificationPrivateKey:(NSString *)account -{ - NSString *key = [@"PNPrivateKey" stringByAppendingString:account]; - return [UICKeyChainStore dataForKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setPushNotificationToken:(NSString *)account token:(NSString *)token -{ - NSString *key = [@"PNToken" stringByAppendingString:account]; - [UICKeyChainStore setString:token forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getPushNotificationToken:(NSString *)account -{ - NSString *key = [@"PNToken" stringByAppendingString:account]; - return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setPushNotificationDeviceIdentifier:(NSString *)account deviceIdentifier:(NSString *)deviceIdentifier -{ - NSString *key = [@"PNDeviceIdentifier" stringByAppendingString:account]; - [UICKeyChainStore setString:deviceIdentifier forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getPushNotificationDeviceIdentifier:(NSString *)account -{ - NSString *key = [@"PNDeviceIdentifier" stringByAppendingString:account]; - return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setPushNotificationDeviceIdentifierSignature:(NSString *)account deviceIdentifierSignature:(NSString *)deviceIdentifierSignature -{ - NSString *key = [@"PNDeviceIdentifierSignature" stringByAppendingString:account]; - [UICKeyChainStore setString:deviceIdentifierSignature forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getPushNotificationDeviceIdentifierSignature:(NSString *)account -{ - NSString *key = [@"PNDeviceIdentifierSignature" stringByAppendingString:account]; - return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)clearAllKeysPushNotification:(NSString *)account -{ - [self setPushNotificationPublicKey:account data:nil]; - [self setPushNotificationSubscribingPublicKey:account publicKey:nil]; - [self setPushNotificationPrivateKey:account data:nil]; - [self setPushNotificationToken:account token:nil]; - [self setPushNotificationDeviceIdentifier:account deviceIdentifier:nil]; - [self setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil]; -} - -+ (NSInteger)getMediaWidthImage -{ - NSString *width = [UICKeyChainStore stringForKey:@"mediaWidthImage" service:NCGlobal.shared.serviceShareKeyChain]; - - if (width == nil) { - return 80; - } else { - return [width integerValue]; - } -} - -+ (void)setMediaWidthImage:(NSInteger)width -{ - NSString *widthString = [@(width) stringValue]; - [UICKeyChainStore setString:widthString forKey:@"mediaWidthImage" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getDisableCrashservice -{ - return [[UICKeyChainStore stringForKey:@"crashservice" service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setDisableCrashservice:(BOOL)disable -{ - NSString *sDisable = (disable) ? @"true" : @"false"; - [UICKeyChainStore setString:sDisable forKey:@"crashservice" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setPassword:(NSString *)account password:(NSString *)password -{ - NSString *key = [@"password" stringByAppendingString:account]; - [UICKeyChainStore setString:password forKey:key service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getPassword:(NSString *)account -{ - NSString *key = [@"password" stringByAppendingString:account]; - NSString *result = [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain]; - if (result == nil) { result = @""; } - return result; -} - -+ (void)setHCBusinessType:(NSString *)professions -{ - [UICKeyChainStore setString:professions forKey:@"businessType" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getHCBusinessType -{ - return [UICKeyChainStore stringForKey:@"businessType" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSData *)getDatabaseEncryptionKey -{ - NSData *key = [UICKeyChainStore dataForKey:@"databaseEncryptionKey" service:NCGlobal.shared.serviceShareKeyChain]; - if (key == nil) { - NSMutableData *key = [NSMutableData dataWithLength:64]; - (void)SecRandomCopyBytes(kSecRandomDefault, key.length, (uint8_t *)key.mutableBytes); - [UICKeyChainStore setData:key forKey:@"databaseEncryptionKey" service:NCGlobal.shared.serviceShareKeyChain]; - return key; - } else { - return key; - } -} - -+ (void)setDatabaseEncryptionKey:(NSData *)data -{ - [UICKeyChainStore setData:data forKey:@"databaseEncryptionKey" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getLivePhoto -{ - NSString *valueString = [UICKeyChainStore stringForKey:@"livePhoto" service:NCGlobal.shared.serviceShareKeyChain]; - - // Default TRUE - if (valueString == nil) { - [self setLivePhoto:YES]; - return true; - } - - return [valueString boolValue]; -} - -+ (void)setLivePhoto:(BOOL)set -{ - NSString *sSet = (set) ? @"true" : @"false"; - [UICKeyChainStore setString:sSet forKey:@"livePhoto" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getMediaSortDate -{ - NSString *valueString = [UICKeyChainStore stringForKey:@"mediaSortDate" service:NCGlobal.shared.serviceShareKeyChain]; - - // Default TRUE - if (valueString == nil) { - [self setMediaSortDate:@"date"]; - return @"date"; - } - - return valueString; -} - -+ (void)setMediaSortDate:(NSString *)value -{ - [UICKeyChainStore setString:value forKey:@"mediaSortDate" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getTextRecognitionStatus -{ - return [[UICKeyChainStore stringForKey:@"textRecognitionStatus" service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setTextRecognitionStatus:(BOOL)value -{ - NSString *valueString = (value) ? @"true" : @"false"; - [UICKeyChainStore setString:valueString forKey:@"textRecognitionStatus" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getDeleteAllScanImages -{ - return [[UICKeyChainStore stringForKey:@"deleteAllScanImages" service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setDeleteAllScanImages:(BOOL)value -{ - NSString *valueString = (value) ? @"true" : @"false"; - [UICKeyChainStore setString:valueString forKey:@"deleteAllScanImages" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSString *)getDirectoryScanDocument -{ - return [UICKeyChainStore stringForKey:@"directoryScanDocuments" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (void)setDirectoryScanDocument:(NSString *)value -{ - [UICKeyChainStore setString:value forKey:@"directoryScanDocuments" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (double)getQualityScanDocument -{ - NSString *value = [UICKeyChainStore stringForKey:@"qualityScanDocument" service:NCGlobal.shared.serviceShareKeyChain]; - - if (value == nil) { - return 2; - } else { - return [value doubleValue]; - } -} - -+ (void)setQualityScanDocument:(double)value -{ - NSString *valueString = [@(value) stringValue]; - [UICKeyChainStore setString:valueString forKey:@"qualityScanDocument" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSInteger)getLogLevel -{ - NSString *value = [UICKeyChainStore stringForKey:@"logLevel" service:NCGlobal.shared.serviceShareKeyChain]; - - if (value == nil) { - return 1; - } else { - return [value integerValue]; - } -} - -+ (void)setLogLevel:(NSInteger)value -{ - NSString *valueString = [@(value) stringValue]; - [UICKeyChainStore setString:valueString forKey:@"logLevel" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getAccountRequest -{ - return [[UICKeyChainStore stringForKey:@"accountRequest" service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setAccountRequest:(BOOL)set -{ - NSString *sSet = (set) ? @"true" : @"false"; - [UICKeyChainStore setString:sSet forKey:@"accountRequest" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (NSInteger)getCleanUpDay -{ - NSString *size = [UICKeyChainStore stringForKey:@"cleanUpDay" service:NCGlobal.shared.serviceShareKeyChain]; - - if (size == nil) { - NSInteger days = [[NCBrandOptions shared] cleanUpDay]; - return days; - } else { - return [size integerValue]; - } -} - -+ (void)setCleanUpDay:(NSInteger)days -{ - NSString *daysString = [@(days) stringValue]; - [UICKeyChainStore setString:daysString forKey:@"cleanUpDay" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getPrivacyScreenEnabled -{ - return [[UICKeyChainStore stringForKey:@"privacyScreen" service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setPrivacyScreenEnabled:(BOOL)set -{ - NSString *sSet = (set) ? @"true" : @"false"; - [UICKeyChainStore setString:sSet forKey:@"privacyScreen" service:NCGlobal.shared.serviceShareKeyChain]; -} - -+ (BOOL)getRemovePhotoCameraRoll -{ - return [[UICKeyChainStore stringForKey:@"removePhotoCameraRoll" service:NCGlobal.shared.serviceShareKeyChain] boolValue]; -} - -+ (void)setRemovePhotoCameraRoll:(BOOL)set -{ - NSString *sSet = (set) ? @"true" : @"false"; - [UICKeyChainStore setString:sSet forKey:@"removePhotoCameraRoll" service:NCGlobal.shared.serviceShareKeyChain]; -} - #pragma -------------------------------------------------------------------------------------------- #pragma mark ===== Various ===== #pragma -------------------------------------------------------------------------------------------- -+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL -{ - NSError *error = nil; - BOOL success = [URL setResourceValue:[NSNumber numberWithBool: YES] forKey: NSURLIsExcludedFromBackupKey error: &error]; - if(success) { - NSLog(@"Excluding %@ from backup", [URL lastPathComponent]); - } else { - NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error); - } - - return success; -} - + (NSString *)dateDiff:(NSDate *) convertedDate { NSDate *todayDate = [NSDate date]; @@ -760,87 +71,18 @@ + (NSString *)dateDiff:(NSDate *) convertedDate } } -+ (NSString *)transformedSize:(int64_t)value -{ - NSString *string = [NSByteCountFormatter stringFromByteCount:value countStyle:NSByteCountFormatterCountStyleBinary]; - return string; -} - -// Remove do not forbidden characters for Nextcloud Server -+ (NSString *)removeForbiddenCharactersServer:(NSString *)fileName -{ - NSArray *arrayForbiddenCharacters = [NSArray arrayWithObjects:@"/", nil]; - - for (NSString *currentCharacter in arrayForbiddenCharacters) { - fileName = [fileName stringByReplacingOccurrencesOfString:currentCharacter withString:@""]; - } - - return fileName; -} - -// Remove do not forbidden characters for File System Server -+ (NSString *)removeForbiddenCharactersFileSystem:(NSString *)fileName -{ - NSArray *arrayForbiddenCharacters = [NSArray arrayWithObjects:@"\\",@"<",@">",@":",@"\"",@"|",@"?",@"*",@"/", nil]; - - for (NSString *currentCharacter in arrayForbiddenCharacters) { - fileName = [fileName stringByReplacingOccurrencesOfString:currentCharacter withString:@""]; - } - - return fileName; -} - -+ (NSString*)stringAppendServerUrl:(NSString *)serverUrl addFileName:(NSString *)addFileName -{ - NSString *result; - - if (serverUrl == nil || addFileName == nil) return nil; - if ([addFileName isEqualToString:@""]) return serverUrl; - - if ([serverUrl isEqualToString:@"/"]) result = [serverUrl stringByAppendingString:addFileName]; - else result = [NSString stringWithFormat:@"%@/%@", serverUrl, addFileName]; - - return result; -} - -+ (NSString *)createFileNameDate:(NSString *)fileName extension:(NSString *)extension -{ - NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; - [formatter setDateFormat:@"yy-MM-dd HH-mm-ss"]; - NSString *fileNameDate = [formatter stringFromDate:[NSDate date]]; - NSString *returnFileName; - - if ([fileName isEqualToString:@""] && ![extension isEqualToString:@""]) { - returnFileName = [NSString stringWithFormat:@"%@.%@", fileNameDate, extension]; - } - - if (![fileName isEqualToString:@""] && [extension isEqualToString:@""]) { - returnFileName = [NSString stringWithFormat:@"%@ %@", fileName, fileNameDate]; - } - - if ([fileName isEqualToString:@""] && [extension isEqualToString:@""]) { - returnFileName = fileNameDate; - } - - if (![fileName isEqualToString:@""] && ![extension isEqualToString:@""]) { - returnFileName = [NSString stringWithFormat:@"%@ %@.%@", fileName, fileNameDate, extension]; - } - - return returnFileName; -} - + (NSString *)createFileName:(NSString *)fileName fileDate:(NSDate *)fileDate fileType:(PHAssetMediaType)fileType keyFileName:(NSString *)keyFileName keyFileNameType:(NSString *)keyFileNameType keyFileNameOriginal:(NSString *)keyFileNameOriginal forcedNewFileName:(BOOL)forcedNewFileName { BOOL addFileNameType = NO; // Original FileName ? - if ([self getOriginalFileName:keyFileNameOriginal] && !forcedNewFileName) { + if ([[[NCKeychain alloc] init] getOriginalFileNameWithKey:keyFileNameOriginal] && !forcedNewFileName) { return fileName; } NSString *numberFileName; if ([fileName length] > 8) numberFileName = [fileName substringWithRange:NSMakeRange(04, 04)]; - else numberFileName = [CCUtility getIncrementalNumber]; + else numberFileName = [[NCKeychain alloc] init].incrementalNumber; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; @@ -859,13 +101,13 @@ + (NSString *)createFileName:(NSString *)fileName fileDate:(NSDate *)fileDate fi // Use File Name Type if (keyFileNameType) - addFileNameType = [CCUtility getFileNameType:keyFileNameType]; + addFileNameType = [[[NCKeychain alloc] init] getFileNameTypeWithKey:keyFileNameType]; NSString *fileNameExt = [[fileName pathExtension] lowercaseString]; if (keyFileName) { - fileName = [CCUtility getFileNameMask:keyFileName]; + fileName = [[[NCKeychain alloc] init] getFileNameMaskWithKey:keyFileName]; if ([fileName length] > 0) { @@ -931,233 +173,6 @@ + (NSString *)createFileName:(NSString *)fileName fileDate:(NSDate *)fileDate fi return fileName; } -+ (void)createDirectoryStandard -{ - NSString *path; - NSURL *dirGroup = [CCUtility getDirectoryGroup]; - - NSLog(@"[LOG] Dir Group"); - NSLog(@"%@", [dirGroup path]); - NSLog(@"[LOG] Program application "); - NSLog(@"%@", [[CCUtility getDirectoryDocuments] stringByDeletingLastPathComponent]); - - // create Directory Documents - path = [CCUtility getDirectoryDocuments]; - if (![[NSFileManager defaultManager] fileExistsAtPath: path]) - [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; - - // create Directory audio => Library, Application Support, audio - path = [CCUtility getDirectoryAudio]; - if (![[NSFileManager defaultManager] fileExistsAtPath: path]) - [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; - - // create Directory database Nextcloud - path = [[dirGroup URLByAppendingPathComponent:[[NCGlobal shared] appDatabaseNextcloud]] path]; - if (![[NSFileManager defaultManager] fileExistsAtPath:path]) - [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; - - // create Directory User Data - path = [[dirGroup URLByAppendingPathComponent:NCGlobal.shared.appUserData] path]; - if (![[NSFileManager defaultManager] fileExistsAtPath:path]) - [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; - - // create Directory Provider Storage - path = [CCUtility getDirectoryProviderStorage]; - if (![[NSFileManager defaultManager] fileExistsAtPath: path]) - [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; - - // create Directory Scan - path = [[dirGroup URLByAppendingPathComponent:NCGlobal.shared.appScan] path]; - if (![[NSFileManager defaultManager] fileExistsAtPath:path]) - [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; - - // create Directory Temp - path = NSTemporaryDirectory(); - if (![[NSFileManager defaultManager] fileExistsAtPath:path]) - [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; - - // Directory Excluded From Backup - [CCUtility addSkipBackupAttributeToItemAtURL:[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]]; - [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.directoryProviderStorage]]; - [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.appApplicationSupport]]; - - [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.appCertificates]]; - [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.appDatabaseNextcloud]]; - [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.appScan]]; - [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.appUserData]]; -} - -+ (NSURL *)getDirectoryGroup -{ - NSURL *path = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:[NCBrandOptions shared].capabilitiesGroups]; - return path; -} - -// Return the path of directory Documents -> NSDocumentDirectory -+ (NSString *)getDirectoryDocuments -{ - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - - return [paths objectAtIndex:0]; -} - -+ (NSString *)getDirectoryReaderMetadata -{ - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); - - return [NSString stringWithFormat:@"%@/Reader Metadata", [paths objectAtIndex:0]]; -} - -// Return the path of directory Audio -+ (NSString *)getDirectoryAudio -{ - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); - - return [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], @"audio"]; -} - -// Return the path of directory Cetificates -+ (NSString *)getDirectoryCerificates -{ - NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.appCertificates] path]; - - if (![[NSFileManager defaultManager] fileExistsAtPath:path]) - [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; - - return path; -} - -+ (NSString *)getDirectoryUserData -{ - NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.appUserData] path]; - - if (![[NSFileManager defaultManager] fileExistsAtPath:path]) - [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; - - return path; -} - -+ (NSString *)getDirectoryProviderStorage -{ - NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.directoryProviderStorage] path]; - - if (![[NSFileManager defaultManager] fileExistsAtPath:path]) - [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; - - return path; -} - -+ (NSString *)getDirectoryProviderStorageOcId:(NSString *)ocId -{ - NSString *path = [NSString stringWithFormat:@"%@/%@", [self getDirectoryProviderStorage], ocId]; - - if (![[NSFileManager defaultManager] fileExistsAtPath:path]) - [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; - - return path; -} - -+ (NSString *)getDirectoryProviderStorageOcId:(NSString *)ocId fileNameView:(NSString *)fileNameView -{ - NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", [self getDirectoryProviderStorageOcId:ocId], fileNameView]; - - // if do not exists create file 0 length - // causes files with lenth 0 to never be downloaded, because already exist - // also makes it impossible to delete any file with length 0 (from cache) - if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath] == NO) { - [[NSFileManager defaultManager] createFileAtPath:fileNamePath contents:nil attributes:nil]; - } - - return fileNamePath; -} - -+ (NSString *)getDirectoryProviderStorageIconOcId:(NSString *)ocId etag:(NSString *)etag -{ - return [NSString stringWithFormat:@"%@/%@.small.%@", [self getDirectoryProviderStorageOcId:ocId], etag, [NCGlobal shared].extensionPreview]; -} - -+ (NSString *)getDirectoryProviderStoragePreviewOcId:(NSString *)ocId etag:(NSString *)etag -{ - return [NSString stringWithFormat:@"%@/%@.preview.%@", [self getDirectoryProviderStorageOcId:ocId], etag, [NCGlobal shared].extensionPreview]; -} - -+ (BOOL)fileProviderStorageExists:(tableMetadata *)metadata -{ - NSString *fileNameViewPath = [self getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView]; - NSString *fileNamePath = [self getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName]; - - unsigned long long fileNameViewSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNameViewPath error:nil] fileSize]; - unsigned long long fileNameSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil] fileSize]; - - if (metadata.isDirectoryE2EE == true) { - if ((fileNameSize == metadata.size || fileNameViewSize == metadata.size) && fileNameViewSize > 0) { - return true; - } else { - return false; - } - } else { - return fileNameViewSize == metadata.size; - } -} - -+ (int64_t)fileProviderStorageSize:(NSString *)ocId fileNameView:(NSString *)fileNameView -{ - NSString *fileNamePath = [self getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView]; - - int64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil] fileSize]; - - return fileSize; -} - -+ (BOOL)fileProviderStoragePreviewIconExists:(NSString *)ocId etag:(NSString *)etag -{ - NSString *fileNamePathPreview = [self getDirectoryProviderStoragePreviewOcId:ocId etag:etag]; - NSString *fileNamePathIcon = [self getDirectoryProviderStorageIconOcId:ocId etag:etag]; - - unsigned long long fileSizePreview = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePathPreview error:nil] fileSize]; - unsigned long long fileSizeIcon = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePathIcon error:nil] fileSize]; - - if (fileSizePreview > 0 && fileSizeIcon > 0) return true; - else return false; -} - -+ (void)removeGroupApplicationSupport -{ - NSURL *dirGroup = [CCUtility getDirectoryGroup]; - NSString *path = [[dirGroup URLByAppendingPathComponent:NCGlobal.shared.appApplicationSupport] path]; - - [[NSFileManager defaultManager] removeItemAtPath:path error:nil]; -} - -+ (void)removeGroupLibraryDirectory -{ - [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryScan] error:nil]; - [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryUserData] error:nil]; -} - -+ (void)removeGroupDirectoryProviderStorage -{ - [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorage] error:nil]; -} - -+ (void)removeDocumentsDirectory -{ - [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryDocuments] error:nil]; -} - -+ (void)removeTemporaryDirectory -{ - [[NSFileManager defaultManager] removeItemAtPath:NSTemporaryDirectory() error:nil]; -} - -+ (void)emptyTemporaryDirectory -{ - NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL]; - for (NSString *file in tmpDirectory) { - [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL]; - } -} - + (NSString *)getTitleSectionDate:(NSDate *)date { NSString *title; @@ -1182,50 +197,6 @@ + (NSString *)getTitleSectionDate:(NSDate *)date return title; } -+ (void)moveFileAtPath:(NSString *)atPath toPath:(NSString *)toPath -{ - [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil]; - [[NSFileManager defaultManager] copyItemAtPath:atPath toPath:toPath error:nil]; - [[NSFileManager defaultManager] removeItemAtPath:atPath error:nil]; -} - -+ (void)copyFileAtPath:(NSString *)atPath toPath:(NSString *)toPath -{ - [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil]; - [[NSFileManager defaultManager] copyItemAtPath:atPath toPath:toPath error:nil]; -} - -+ (void)removeFileAtPath:(NSString *)atPath -{ - [[NSFileManager defaultManager] removeItemAtPath:atPath error:nil]; -} - -+ (void)createDirectoryAtPath:(NSString *)atPath -{ - [[NSFileManager defaultManager] createDirectoryAtPath:atPath withIntermediateDirectories:true attributes:nil error:nil]; -} - -+ (NSString *)returnPathfromServerUrl:(NSString *)serverUrl urlBase:(NSString *)urlBase userId:(NSString *)userId account:(NSString *)account -{ - NSString *homeServer = [[NCUtilityFileSystem shared] getHomeServerWithUrlBase:urlBase userId:userId]; - NSString *path = [serverUrl stringByReplacingOccurrencesOfString:homeServer withString:@""]; - return path; -} - -+ (NSString *)returnFileNamePathFromFileName:(NSString *)metadataFileName serverUrl:(NSString *)serverUrl urlBase:(NSString *)urlBase userId:(NSString *)userId account:(NSString *)account -{ - if (metadataFileName == nil || serverUrl == nil || urlBase == nil) { - return @""; - } - - NSString *homeServer = [[NCUtilityFileSystem shared] getHomeServerWithUrlBase:urlBase userId:userId]; - NSString *fileName = [NSString stringWithFormat:@"%@/%@", [serverUrl stringByReplacingOccurrencesOfString:homeServer withString:@""], metadataFileName]; - - if ([fileName hasPrefix:@"/"]) fileName = [fileName substringFromIndex:1]; - - return fileName; -} - + (NSString *)getMimeType:(NSString *)fileNameView { CFStringRef fileUTI = nil; @@ -1250,15 +221,6 @@ + (NSString *)getMimeType:(NSString *)fileNameView return returnFileUTI; } -+ (NSString *)getDirectoryScan -{ - NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.appScan] path]; - - if (![[NSFileManager defaultManager] fileExistsAtPath:path]) - [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil]; - - return path; -} #pragma -------------------------------------------------------------------------------------------- #pragma mark ===== Share Permissions ===== @@ -1370,13 +332,6 @@ + (NSDate *)datetimeWithOutTime:(NSDate *)datDate return datDate; } -+ (NSString *)valueForKey:(NSString *)key fromQueryItems:(NSArray *)queryItems -{ - NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", key]; - NSURLQueryItem *queryItem = [[queryItems filteredArrayUsingPredicate:predicate] firstObject]; - return queryItem.value; -} - + (NSDate *)getATime:(const char *)path { struct stat st; diff --git a/iOSClient/Utility/NCCameraRoll.swift b/iOSClient/Utility/NCCameraRoll.swift index 7e48686269..b84bf1dfc9 100644 --- a/iOSClient/Utility/NCCameraRoll.swift +++ b/iOSClient/Utility/NCCameraRoll.swift @@ -38,7 +38,7 @@ class NCCameraRoll: NSObject { guard !metadata.isExtractFile else { return completition([metadataSource]) } guard !metadataSource.assetLocalIdentifier.isEmpty else { - let filePath = CCUtility.getDirectoryProviderStorageOcId(metadataSource.ocId, fileNameView: metadataSource.fileName)! + let filePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadataSource.ocId, fileNameView: metadataSource.fileName) metadataSource.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath) let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: metadataSource.fileNameView, mimeType: metadataSource.contentType, directory: false) metadataSource.contentType = results.mimeType @@ -69,7 +69,7 @@ class NCCameraRoll: NSObject { extractImageVideoFromAssetLocalIdentifier(metadata: metadataSource, modifyMetadataForUpload: true, viewController: viewController, hud: hud) { metadata, fileNamePath, error in if let metadata = metadata, let fileNamePath = fileNamePath, !error { metadatas.append(metadata) - let toPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let toPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) NCUtilityFileSystem.shared.moveFile(atPath: fileNamePath, toPath: toPath) let fetchAssets = PHAsset.fetchAssets(withLocalIdentifiers: [metadataSource.assetLocalIdentifier], options: nil) // swiftlint:disable empty_count @@ -139,7 +139,7 @@ class NCCameraRoll: NSObject { let creationDate = asset.creationDate ?? Date() let modificationDate = asset.modificationDate ?? Date() - if asset.mediaType == PHAssetMediaType.image && (extensionAsset == "HEIC" || extensionAsset == "DNG") && CCUtility.getFormatCompatibility() { + if asset.mediaType == PHAssetMediaType.image && (extensionAsset == "HEIC" || extensionAsset == "DNG") && NCKeychain().formatCompatibility { let fileName = (metadata.fileNameView as NSString).deletingPathExtension + ".jpg" metadata.contentType = "image/jpeg" fileNamePath = NSTemporaryDirectory() + fileName @@ -178,7 +178,7 @@ class NCCameraRoll: NSObject { guard let ciImage = CIImage(data: data), let colorSpace = ciImage.colorSpace, let dataJPEG = CIContext().jpegRepresentation(of: ciImage, colorSpace: colorSpace) else { return callCompletionWithError() } data = dataJPEG } - NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath) + NCUtilityFileSystem.shared.removeFile(atPath: fileNamePath) do { try data.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic) } catch { return callCompletionWithError() } @@ -200,7 +200,7 @@ class NCCameraRoll: NSObject { PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { asset, _, _ in if let asset = asset as? AVURLAsset { - NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath) + NCUtilityFileSystem.shared.removeFile(atPath: fileNamePath) do { try FileManager.default.copyItem(at: asset.url, to: URL(fileURLWithPath: fileNamePath)) metadata.creationDate = creationDate as NSDate @@ -254,7 +254,7 @@ class NCCameraRoll: NSObject { options.isNetworkAccessAllowed = true let ocId = NSUUID().uuidString let fileName = (metadata.fileName as NSString).deletingPathExtension + ".mov" - let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)! + let fileNamePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName) var chunkSize = NCGlobal.shared.chunkSizeMBCellular if NCNetworking.shared.networkReachability == NKCommon.TypeReachability.reachableEthernetOrWiFi { chunkSize = NCGlobal.shared.chunkSizeMBEthernetOrWiFi @@ -268,7 +268,7 @@ class NCCameraRoll: NSObject { break } guard let videoResource = videoResource else { return completion(nil) } - NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath) + NCUtilityFileSystem.shared.removeFile(atPath: fileNamePath) PHAssetResourceManager.default().writeData(for: videoResource, toFile: URL(fileURLWithPath: fileNamePath), options: nil) { error in if error != nil { return completion(nil) } let metadataLivePhoto = NCManageDatabase.shared.createMetadata(account: metadata.account, diff --git a/iOSClient/Utility/NCKeychain.swift b/iOSClient/Utility/NCKeychain.swift new file mode 100644 index 0000000000..97a44f3d42 --- /dev/null +++ b/iOSClient/Utility/NCKeychain.swift @@ -0,0 +1,507 @@ +// +// NCKeychain.swift +// Nextcloud +// +// Created by Marino Faggiana on 23/10/23. +// Copyright © 2023 Marino Faggiana. All rights reserved. +// +// Author Marino Faggiana +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// + +import Foundation +import KeychainAccess + +@objc class NCKeychain: NSObject { + + let keychain = Keychain(service: "com.nextcloud.keychain") + + var typeFilterScanDocument: NCGlobal.TypeFilterScanDocument { + get { + if let rawValue = try? keychain.get("ScanDocumentTypeFilter"), let value = NCGlobal.TypeFilterScanDocument(rawValue: rawValue) { + return value + } else { + return .original + } + } + set { + keychain["ScanDocumentTypeFilter"] = newValue.rawValue + } + } + + @objc var passcode: String? { + get { + migrate(key: "passcodeBlock") + if let value = try? keychain.get("passcodeBlock") { + return value + } + return nil + } + set { + keychain["passcodeBlock"] = newValue + } + } + + @objc var requestPasscodeAtStart: Bool { + get { + let keychainOLD = Keychain(service: "Crypto Cloud") + if let value = keychainOLD["notPasscodeAtStart"], !value.isEmpty { + if value == "true" { + keychain["requestPasscodeAtStart"] = "false" + } else if value == "false" { + keychain["requestPasscodeAtStart"] = "true" + } + keychainOLD["notPasscodeAtStart"] = nil + } + if let value = try? keychain.get("requestPasscodeAtStart"), let result = Bool(value) { + return result + } + return true + } + set { + keychain["requestPasscodeAtStart"] = String(newValue) + } + } + + @objc var touchFaceID: Bool { + get { + migrate(key: "enableTouchFaceID") + if let value = try? keychain.get("enableTouchFaceID"), let result = Bool(value) { + return result + } + return false + } + set { + keychain["enableTouchFaceID"] = String(newValue) + } + } + + var intro: Bool { + get { + migrate(key: "intro") + if let value = try? keychain.get("intro"), let result = Bool(value) { + return result + } + return false + } + set { + keychain["intro"] = String(newValue) + } + } + + @objc var incrementalNumber: String { + migrate(key: "incrementalnumber") + var incrementalString = String(format: "%04ld", 0) + if let value = try? keychain.get("incrementalnumber"), var result = Int(value) { + result += 1 + incrementalString = String(format: "%04ld", result) + } + keychain["incrementalnumber"] = incrementalString + return incrementalString + } + + @objc var showHiddenFiles: Bool { + get { + migrate(key: "showHiddenFiles") + if let value = try? keychain.get("showHiddenFiles"), let result = Bool(value) { + return result + } + return false + } + set { + keychain["showHiddenFiles"] = String(newValue) + } + } + + @objc var formatCompatibility: Bool { + get { + migrate(key: "formatCompatibility") + if let value = try? keychain.get("formatCompatibility"), let result = Bool(value) { + return result + } + return true + } + set { + keychain["formatCompatibility"] = String(newValue) + } + } + + @objc var disableFilesApp: Bool { + get { + migrate(key: "disablefilesapp") + if let value = try? keychain.get("disablefilesapp"), let result = Bool(value) { + return result + } + return false + } + set { + keychain["disablefilesapp"] = String(newValue) + } + } + + @objc var livePhoto: Bool { + get { + migrate(key: "livePhoto") + if let value = try? keychain.get("livePhoto"), let result = Bool(value) { + return result + } + return true + } + set { + keychain["livePhoto"] = String(newValue) + } + } + + @objc var disableCrashservice: Bool { + get { + migrate(key: "crashservice") + if let value = try? keychain.get("crashservice"), let result = Bool(value) { + return result + } + return false + } + set { + keychain["crashservice"] = String(newValue) + } + } + + @objc var logLevel: Int { + get { + migrate(key: "logLevel") + if let value = try? keychain.get("logLevel"), let result = Int(value) { + return result + } + return 1 + } + set { + keychain["logLevel"] = String(newValue) + } + } + + @objc var accountRequest: Bool { + get { + migrate(key: "accountRequest") + if let value = try? keychain.get("accountRequest"), let result = Bool(value) { + return result + } + return false + } + set { + keychain["accountRequest"] = String(newValue) + } + } + + @objc var removePhotoCameraRoll: Bool { + get { + migrate(key: "removePhotoCameraRoll") + if let value = try? keychain.get("removePhotoCameraRoll"), let result = Bool(value) { + return result + } + return false + } + set { + keychain["removePhotoCameraRoll"] = String(newValue) + } + } + + @objc var privacyScreenEnabled: Bool { + get { + migrate(key: "privacyScreen") + if let value = try? keychain.get("privacyScreen"), let result = Bool(value) { + return result + } + return false + } + set { + keychain["privacyScreen"] = String(newValue) + } + } + + @objc var cleanUpDay: Int { + get { + migrate(key: "cleanUpDay") + if let value = try? keychain.get("cleanUpDay"), let result = Int(value) { + return result + } + return NCBrandOptions.shared.cleanUpDay + } + set { + keychain["cleanUpDay"] = String(newValue) + } + } + + var mediaWidthImage: Int { + get { + migrate(key: "mediaWidthImage") + if let value = try? keychain.get("mediaWidthImage"), let result = Int(value) { + return result + } + return 80 + } + set { + keychain["mediaWidthImage"] = String(newValue) + } + } + + var mediaSortDate: String { + get { + migrate(key: "mediaSortDate") + if let value = try? keychain.get("mediaSortDate") { + return value + } + return "date" + } + set { + keychain["mediaSortDate"] = newValue + } + } + + var textRecognitionStatus: Bool { + get { + migrate(key: "textRecognitionStatus") + if let value = try? keychain.get("textRecognitionStatus"), let result = Bool(value) { + return result + } + return false + } + set { + keychain["textRecognitionStatus"] = String(newValue) + } + } + + var deleteAllScanImages: Bool { + get { + migrate(key: "deleteAllScanImages") + if let value = try? keychain.get("deleteAllScanImages"), let result = Bool(value) { + return result + } + return false + } + set { + keychain["deleteAllScanImages"] = String(newValue) + } + } + + var qualityScanDocument: Double { + get { + migrate(key: "qualityScanDocument") + if let value = try? keychain.get("qualityScanDocument"), let result = Double(value) { + return result + } + return 2 + } + set { + keychain["qualityScanDocument"] = String(newValue) + } + } + + // MARK: - + + private func migrate(key: String) { + let keychainOLD = Keychain(service: "Crypto Cloud") + if let value = keychainOLD[key], !value.isEmpty { + keychain[key] = value + keychainOLD[key] = nil + } + } + + @objc func removeAll() { + try? keychain.removeAll() + } + + // MARK: - + + @objc func getPassword(account: String) -> String { + let key = "password" + account + migrate(key: key) + return (try? keychain.get(key)) ?? "" + } + + @objc func setPassword(account: String, password: String?) { + let key = "password" + account + keychain[key] = password + } + + @objc func getOriginalFileName(key: String) -> Bool { + migrate(key: key) + if let value = try? keychain.get(key), let result = Bool(value) { + return result + } + return false + } + + @objc func setOriginalFileName(key: String, value: Bool) { + keychain[key] = String(value) + } + + @objc func getFileNameMask(key: String) -> String { + migrate(key: key) + if let value = try? keychain.get(key) { + return value + } else { + return "" + } + } + + @objc func setFileNameMask(key: String, mask: String?) { + keychain[key] = mask + } + + @objc func getFileNameType(key: String) -> Bool { + migrate(key: key) + if let value = try? keychain.get(key), let result = Bool(value) { + return result + } else { + return false + } + } + + @objc func setFileNameType(key: String, prefix: Bool) { + keychain[key] = String(prefix) + } + + // MARK: - E2EE + + func getEndToEndCertificate(account: String) -> String? { + let key = "EndToEndCertificate_" + account + migrate(key: key) + return try? keychain.get(key) + } + + func setEndToEndCertificate(account: String, certificate: String?) { + let key = "EndToEndCertificate_" + account + keychain[key] = certificate + } + + func getEndToEndPrivateKey(account: String) -> String? { + let key = "EndToEndPrivateKey_" + account + migrate(key: key) + return try? keychain.get(key) + } + + func setEndToEndPrivateKey(account: String, privateKey: String?) { + let key = "EndToEndPrivateKey_" + account + keychain[key] = privateKey + } + + func getEndToEndPublicKey(account: String) -> String? { + let key = "EndToEndPublicKeyServer_" + account + migrate(key: key) + return try? keychain.get(key) + } + + func setEndToEndPublicKey(account: String, publicKey: String?) { + let key = "EndToEndPublicKeyServer_" + account + keychain[key] = publicKey + } + + func getEndToEndPassphrase(account: String) -> String? { + let key = "EndToEndPassphrase_" + account + migrate(key: key) + return try? keychain.get(key) + } + + func setEndToEndPassphrase(account: String, passphrase: String?) { + let key = "EndToEndPassphrase_" + account + keychain[key] = passphrase + } + + func isEndToEndEnabled(account: String) -> Bool { + guard let certificate = getEndToEndCertificate(account: account), !certificate.isEmpty, + let publicKey = getEndToEndPublicKey(account: account), !publicKey.isEmpty, + let privateKey = getEndToEndPrivateKey(account: account), !privateKey.isEmpty, + let passphrase = getEndToEndPassphrase(account: account), !passphrase.isEmpty, + NCGlobal.shared.e2eeVersions.contains(NCGlobal.shared.capabilityE2EEApiVersion) else { return false } + return true + } + + func clearAllKeysEndToEnd(account: String) { + setEndToEndCertificate(account: account, certificate: nil) + setEndToEndPrivateKey(account: account, privateKey: nil) + setEndToEndPublicKey(account: account, publicKey: nil) + setEndToEndPassphrase(account: account, passphrase: nil) + } + + // MARK: - PUSHNOTIFICATION + + @objc func getPushNotificationPublicKey(account: String) -> Data? { + let key = "PNPublicKey" + account + return try? keychain.getData(key) + } + + @objc func setPushNotificationPublicKey(account: String, data: Data?) { + let key = "PNPublicKey" + account + keychain[data: key] = data + } + + @objc func getPushNotificationPrivateKey(account: String) -> Data? { + let key = "PNPrivateKey" + account + return try? keychain.getData(key) + } + + @objc func setPushNotificationPrivateKey(account: String, data: Data?) { + let key = "PNPrivateKey" + account + keychain[data: key] = data + } + + @objc func getPushNotificationSubscribingPublicKey(account: String) -> String? { + let key = "PNSubscribingPublicKey" + account + return try? keychain.get(key) + } + + @objc func setPushNotificationSubscribingPublicKey(account: String, publicKey: String?) { + let key = "PNSubscribingPublicKey" + account + keychain[key] = publicKey + } + + @objc func getPushNotificationToken(account: String) -> String? { + let key = "PNToken" + account + return try? keychain.get(key) + } + + @objc func setPushNotificationToken(account: String, token: String?) { + let key = "PNToken" + account + keychain[key] = token + } + + @objc func getPushNotificationDeviceIdentifier(account: String) -> String? { + let key = "PNDeviceIdentifier" + account + return try? keychain.get(key) + } + + @objc func setPushNotificationDeviceIdentifier(account: String, deviceIdentifier: String?) { + let key = "PNDeviceIdentifier" + account + keychain[key] = deviceIdentifier + } + + @objc func getPushNotificationDeviceIdentifierSignature(account: String) -> String? { + let key = "PNDeviceIdentifierSignature" + account + return try? keychain.get(key) + } + + @objc func setPushNotificationDeviceIdentifierSignature(account: String, deviceIdentifierSignature: String?) { + let key = "PNDeviceIdentifierSignature" + account + keychain[key] = deviceIdentifierSignature + } + + @objc func clearAllKeysPushNotification(account: String) { + setPushNotificationPublicKey(account: account, data: nil) + setPushNotificationSubscribingPublicKey(account: account, publicKey: nil) + setPushNotificationPrivateKey(account: account, data: nil) + setPushNotificationToken(account: account, token: nil) + setPushNotificationDeviceIdentifier(account: account, deviceIdentifier: nil) + setPushNotificationDeviceIdentifierSignature(account: account, deviceIdentifierSignature: nil) + } +} diff --git a/iOSClient/Utility/NCUtility+Exif.swift b/iOSClient/Utility/NCUtility+Exif.swift index 7d0da52504..139a37d3e9 100644 --- a/iOSClient/Utility/NCUtility+Exif.swift +++ b/iOSClient/Utility/NCUtility+Exif.swift @@ -72,11 +72,11 @@ extension NCUtility { } } - if metadata.classFile != "image" || !CCUtility.fileProviderStorageExists(metadata) { + if metadata.classFile != "image" || !NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { print("Storage exists or file is not an image") } - let url = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) + let url = URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) guard let originalSource = CGImageSourceCreateWithURL(url as CFURL, nil), let imageProperties = CGImageSourceCopyPropertiesAtIndex(originalSource, 0, nil) as NSDictionary? else { diff --git a/iOSClient/Utility/NCUtility+Image.swift b/iOSClient/Utility/NCUtility+Image.swift index 1443ad7b2a..2748f07120 100644 --- a/iOSClient/Utility/NCUtility+Image.swift +++ b/iOSClient/Utility/NCUtility+Image.swift @@ -36,10 +36,8 @@ extension NCUtility { NCUtility.shared.createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile) } - if CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) { - if let imagePreviewPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag) { - return UIImage(contentsOfFile: imagePreviewPath) - } + if NCUtilityFileSystem.shared.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) { + return UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)) } if metadata.isVideo { @@ -55,10 +53,10 @@ extension NCUtility { let ext = CCUtility.getExtension(metadata.fileNameView) var image: UIImage? - if CCUtility.fileProviderStorageExists(metadata) && metadata.isImage { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) && metadata.isImage { - let previewPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)! - let imagePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let previewPath = NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag) + let imagePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) if ext == "GIF" { if !FileManager().fileExists(atPath: previewPath) { diff --git a/iOSClient/Utility/NCUtility.swift b/iOSClient/Utility/NCUtility.swift index dd43e33b84..41aa466682 100644 --- a/iOSClient/Utility/NCUtility.swift +++ b/iOSClient/Utility/NCUtility.swift @@ -55,7 +55,7 @@ class NCUtility: NSObject { fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png" } - let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG + let imageNamePath = NCUtilityFileSystem.shared.directoryUserData + "/" + fileNamePNG if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true { @@ -128,14 +128,14 @@ class NCUtility: NSObject { return path.contains("CoreSimulator") || path.contains("sandboxReceipt") } - @objc func isSimulator() -> Bool { + func isSimulator() -> Bool { guard let path = Bundle.main.appStoreReceiptURL?.path else { return false } return path.contains("CoreSimulator") } - @objc func isRichDocument(_ metadata: tableMetadata) -> Bool { + func isRichDocument(_ metadata: tableMetadata) -> Bool { guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else { return false @@ -164,7 +164,7 @@ class NCUtility: NSObject { return false } - @objc func isDirectEditing(account: String, contentType: String) -> [String] { + func isDirectEditing(account: String, contentType: String) -> [String] { var editor: [String] = [] @@ -195,11 +195,6 @@ class NCUtility: NSObject { } } - // HARDCODE - // if editor.count == 0 { - // editor.append(NCGlobal.shared.editorText) - // } - return Array(Set(editor)) } @@ -211,19 +206,19 @@ class NCUtility: NSObject { NCManageDatabase.shared.clearDatabase(account: nil, removeAccount: true) - CCUtility.removeGroupDirectoryProviderStorage() - CCUtility.removeGroupLibraryDirectory() + NCUtilityFileSystem.shared.removeGroupDirectoryProviderStorage() + NCUtilityFileSystem.shared.removeGroupLibraryDirectory() - CCUtility.removeDocumentsDirectory() - CCUtility.removeTemporaryDirectory() + NCUtilityFileSystem.shared.removeDocumentsDirectory() + NCUtilityFileSystem.shared.removeTemporaryDirectory() - CCUtility.createDirectoryStandard() + NCUtilityFileSystem.shared.createDirectoryStandard() - CCUtility.deleteAllChainStore() + NCKeychain().removeAll() } #endif - @objc func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool { + func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool { for char in permissions { if metadataPermissions.contains(char) == false { @@ -233,7 +228,7 @@ class NCUtility: NSObject { return true } - @objc func getCustomUserAgentNCText() -> String { + func getCustomUserAgentNCText() -> String { if UIDevice.current.userInterfaceIdiom == .phone { // NOTE: Hardcoded (May 2022) // Tested for iPhone SE (1st), iOS 12 iPhone Pro Max, iOS 15.4 @@ -245,7 +240,7 @@ class NCUtility: NSObject { } } - @objc func getCustomUserAgentOnlyOffice() -> String { + func getCustomUserAgentOnlyOffice() -> String { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")! if UIDevice.current.userInterfaceIdiom == .pad { @@ -373,11 +368,11 @@ class NCUtility: NSObject { var originalImage, scaleImagePreview, scaleImageIcon: UIImage? - let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)! - let fileNamePathPreview = CCUtility.getDirectoryProviderStoragePreviewOcId(ocId, etag: etag)! - let fileNamePathIcon = CCUtility.getDirectoryProviderStorageIconOcId(ocId, etag: etag)! + let fileNamePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView) + let fileNamePathPreview = NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(ocId, etag: etag) + let fileNamePathIcon = NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(ocId, etag: etag) - if CCUtility.fileProviderStorageSize(ocId, fileNameView: fileNameView) > 0 && FileManager().fileExists(atPath: fileNamePathPreview) && FileManager().fileExists(atPath: fileNamePathIcon) { return } + if NCUtilityFileSystem.shared.fileProviderStorageSize(ocId, fileNameView: fileNameView) > 0 && FileManager().fileExists(atPath: fileNamePathPreview) && FileManager().fileExists(atPath: fileNamePathIcon) { return } if classFile != NKCommon.TypeClassFile.image.rawValue && classFile != NKCommon.TypeClassFile.video.rawValue { return } if classFile == NKCommon.TypeClassFile.image.rawValue { @@ -439,35 +434,24 @@ class NCUtility: NSObject { @objc func loadUserImage(for user: String, displayName: String?, userBaseUrl: NCUserBaseUrl) -> UIImage { let fileName = userBaseUrl.userBaseUrl + "-" + user + ".png" - let localFilePath = String(CCUtility.getDirectoryUserData()) + "/" + fileName - - if let localImage = UIImage(contentsOfFile: localFilePath) { - return createAvatar(image: localImage, size: 30) + let localFilePath = NCUtilityFileSystem.shared.directoryUserData + "/" + fileName + + if var localImage = UIImage(contentsOfFile: localFilePath) { + let rect = CGRect(x: 0, y: 0, width: 30, height: 30) + UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0) + UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip() + localImage.draw(in: rect) + localImage = UIGraphicsGetImageFromCurrentImageContext() ?? localImage + UIGraphicsEndImageContext() + return localImage } else if let loadedAvatar = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) { return loadedAvatar } else if let displayName = displayName, !displayName.isEmpty, let avatarImg = createAvatar(displayName: displayName, size: 30) { return avatarImg - } else { return getDefaultUserIcon() } - } - - func getDefaultUserIcon() -> UIImage { - - let config = UIImage.SymbolConfiguration(pointSize: 30) - return NCUtility.shared.loadImage(named: "person.crop.circle", symbolConfiguration: config) - } - - @objc func createAvatar(image: UIImage, size: CGFloat) -> UIImage { - - var avatarImage = image - let rect = CGRect(x: 0, y: 0, width: size, height: size) - - UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0) - UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip() - avatarImage.draw(in: rect) - avatarImage = UIGraphicsGetImageFromCurrentImageContext() ?? image - UIGraphicsEndImageContext() - - return avatarImage + } else { + let config = UIImage.SymbolConfiguration(pointSize: 30) + return NCUtility.shared.loadImage(named: "person.crop.circle", symbolConfiguration: config) + } } func createAvatar(displayName: String, size: CGFloat) -> UIImage? { @@ -580,104 +564,11 @@ class NCUtility: NSObject { return isEqual } - func stringFromTime(_ time: CMTime) -> String { - - let interval = Int(CMTimeGetSeconds(time)) - - let seconds = interval % 60 - let minutes = (interval / 60) % 60 - let hours = (interval / 3600) - - if hours > 0 { - return String(format: "%02d:%02d:%02d", hours, minutes, seconds) - } else { - return String(format: "%02d:%02d", minutes, seconds) - } - } - - func colorNavigationController(_ navigationController: UINavigationController?, backgroundColor: UIColor, titleColor: UIColor, tintColor: UIColor?, withoutShadow: Bool) { - - let appearance = UINavigationBarAppearance() - appearance.titleTextAttributes = [.foregroundColor: titleColor] - appearance.largeTitleTextAttributes = [.foregroundColor: titleColor] - - if withoutShadow { - appearance.shadowColor = .clear - appearance.shadowImage = UIImage() - } - - if let tintColor = tintColor { - navigationController?.navigationBar.tintColor = tintColor - } - - navigationController?.view.backgroundColor = backgroundColor - navigationController?.navigationBar.barTintColor = titleColor - navigationController?.navigationBar.standardAppearance = appearance - navigationController?.navigationBar.compactAppearance = appearance - navigationController?.navigationBar.scrollEdgeAppearance = appearance - } - - func getEncondingDataType(data: Data) -> String.Encoding? { - if String(data: data, encoding: .utf8) != nil { return .utf8 } - if String(data: data, encoding: .ascii) != nil { return .ascii } - if String(data: data, encoding: .isoLatin1) != nil { return .isoLatin1 } - if String(data: data, encoding: .isoLatin2) != nil { return .isoLatin2 } - if String(data: data, encoding: .windowsCP1250) != nil { return .windowsCP1250 } - if String(data: data, encoding: .windowsCP1251) != nil { return .windowsCP1251 } - if String(data: data, encoding: .windowsCP1252) != nil { return .windowsCP1252 } - if String(data: data, encoding: .windowsCP1253) != nil { return .windowsCP1253 } - if String(data: data, encoding: .windowsCP1254) != nil { return .windowsCP1254 } - if String(data: data, encoding: .macOSRoman) != nil { return .macOSRoman } - if String(data: data, encoding: .japaneseEUC) != nil { return .japaneseEUC } - if String(data: data, encoding: .nextstep) != nil { return .nextstep } - if String(data: data, encoding: .nonLossyASCII) != nil { return .nonLossyASCII } - if String(data: data, encoding: .shiftJIS) != nil { return .shiftJIS } - if String(data: data, encoding: .symbol) != nil { return .symbol } - if String(data: data, encoding: .unicode) != nil { return .unicode } - if String(data: data, encoding: .utf16) != nil { return .utf16 } - if String(data: data, encoding: .utf16BigEndian) != nil { return .utf16BigEndian } - if String(data: data, encoding: .utf16LittleEndian) != nil { return .utf16LittleEndian } - if String(data: data, encoding: .utf32) != nil { return .utf32 } - if String(data: data, encoding: .utf32BigEndian) != nil { return .utf32BigEndian } - if String(data: data, encoding: .utf32LittleEndian) != nil { return .utf32LittleEndian } - return nil - } - - func SYSTEM_VERSION_LESS_THAN(version: String) -> Bool { - return UIDevice.current.systemVersion.compare(version, - options: NSString.CompareOptions.numeric) == ComparisonResult.orderedAscending - } - - func getAvatarFromIconUrl(metadata: tableMetadata) -> String? { - - var ownerId: String? - if metadata.iconUrl.contains("http") && metadata.iconUrl.contains("avatar") { - let splitIconUrl = metadata.iconUrl.components(separatedBy: "/") - var found: Bool = false - for item in splitIconUrl { - if found { - ownerId = item - break - } - if item == "avatar" { found = true} - } - } - return ownerId - } - - // https://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift - func isValidEmail(_ email: String) -> Bool { - - let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" - let emailPred = NSPredicate(format: "SELF MATCHES %@", emailRegEx) - return emailPred.evaluate(with: email) - } - func createFilePreviewImage(ocId: String, etag: String, fileNameView: String, classFile: String, status: Int, createPreviewMedia: Bool) -> UIImage? { var imagePreview: UIImage? - let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)! - let iconImagePath = CCUtility.getDirectoryProviderStorageIconOcId(ocId, etag: etag)! + let filePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView) + let iconImagePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(ocId, etag: etag) if FileManager().fileExists(atPath: iconImagePath) { imagePreview = UIImage(contentsOfFile: iconImagePath) @@ -752,43 +643,6 @@ class NCUtility: NSObject { return top } - func createViewImageAndText(image: UIImage, title: String? = nil) -> UIView { - - let imageView = UIImageView() - let titleView = UIView() - let label = UILabel() - - if let title = title { - label.text = title + " " - } else { - label.text = " " - } - label.sizeToFit() - label.center = titleView.center - label.textAlignment = NSTextAlignment.center - - imageView.image = image - - let imageAspect = (imageView.image?.size.width ?? 0) / (imageView.image?.size.height ?? 0) - let imageX = label.frame.origin.x - label.frame.size.height * imageAspect - let imageY = label.frame.origin.y - let imageWidth = label.frame.size.height * imageAspect - let imageHeight = label.frame.size.height - - if title != nil { - imageView.frame = CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight) - titleView.addSubview(label) - } else { - imageView.frame = CGRect(x: imageX / 2, y: imageY, width: imageWidth, height: imageHeight) - } - imageView.contentMode = UIView.ContentMode.scaleAspectFit - - titleView.addSubview(imageView) - titleView.sizeToFit() - - return titleView - } - func getLocation(latitude: Double, longitude: Double, completion: @escaping (String?) -> Void) { let geocoder = CLGeocoder() let llocation = CLLocation(latitude: latitude, longitude: longitude) @@ -841,4 +695,16 @@ class NCUtility: NSObject { return (usedmegabytes, totalmegabytes) } + + func removeForbiddenCharacters(_ fileName: String) -> String { + + var fileName = fileName + let arrayForbiddenCharacters = ["/"] + + for character in arrayForbiddenCharacters { + fileName = fileName.replacingOccurrences(of: character, with: "") + } + return fileName + } + } diff --git a/iOSClient/Utility/NCUtilityFileSystem.swift b/iOSClient/Utility/NCUtilityFileSystem.swift index 9bba457cd9..f4d6c88f03 100644 --- a/iOSClient/Utility/NCUtilityFileSystem.swift +++ b/iOSClient/Utility/NCUtilityFileSystem.swift @@ -32,6 +32,188 @@ class NCUtilityFileSystem: NSObject { let fileManager = FileManager.default + // MARK: - + + var directoryGroup: String { + return fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups)?.path ?? "" + } + + var directoryDocuments: String { + return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? "" + } + + var directoryCertificates: String { + guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups) else { return "" } + let path = directoryGroup.appendingPathComponent(NCGlobal.shared.appCertificates).path + if !fileManager.fileExists(atPath: path) { + do { + try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true) + } catch { print("Error: \(error)") } + } + return path + } + + var directoryUserData: String { + guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups) else { return "" } + let path = directoryGroup.appendingPathComponent(NCGlobal.shared.appUserData).path + if !fileManager.fileExists(atPath: path) { + do { + try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true) + } catch { print("Error: \(error)") } + } + return path + } + + var directoryScan: String { + guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups) else { return "" } + let path = directoryGroup.appendingPathComponent(NCGlobal.shared.appScan).path + if !fileManager.fileExists(atPath: path) { + do { + try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true) + } catch { print("Error: \(error)") } + } + return path + } + + @objc var directoryProviderStorage: String { + guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups) else { return "" } + let path = directoryGroup.appendingPathComponent(NCGlobal.shared.directoryProviderStorage).path + if !fileManager.fileExists(atPath: path) { + do { + try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true) + } catch { print("Error: \(error)") } + } + return path + } + + @objc func getDirectoryProviderStorageOcId(_ ocId: String) -> String { + let path = directoryProviderStorage + "/" + ocId + if !fileManager.fileExists(atPath: path) { + do { + try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true) + } catch { print("Error: \(error)") } + } + return path + } + + @objc func getDirectoryProviderStorageOcId(_ ocId: String, fileNameView: String) -> String { + let path = getDirectoryProviderStorageOcId(ocId) + "/" + fileNameView + if !fileManager.fileExists(atPath: path) { + fileManager.createFile(atPath: path, contents: nil) + } + return path + } + + func getDirectoryProviderStorageIconOcId(_ ocId: String, etag: String) -> String { + return getDirectoryProviderStorageOcId(ocId) + "/" + etag + ".small." + NCGlobal.shared.extensionPreview + } + + func getDirectoryProviderStoragePreviewOcId(_ ocId: String, etag: String) -> String { + return getDirectoryProviderStorageOcId(ocId) + "/" + etag + ".preview." + NCGlobal.shared.extensionPreview + } + + func fileProviderStorageExists(_ metadata: tableMetadata) -> Bool { + let fileNamePath = getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName) + let fileNameViewPath = getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) + do { + let fileNameAttribute = try fileManager.attributesOfItem(atPath: fileNamePath) + let fileNameSize: UInt64 = fileNameAttribute[FileAttributeKey.size] as? UInt64 ?? 0 + let fileNameViewAttribute = try fileManager.attributesOfItem(atPath: fileNameViewPath) + let fileNameViewSize: UInt64 = fileNameViewAttribute[FileAttributeKey.size] as? UInt64 ?? 0 + if metadata.isDirectoryE2EE == true { + if (fileNameSize == metadata.size || fileNameViewSize == metadata.size) && fileNameViewSize > 0 { + return true + } else { + return false + } + } else { + return fileNameViewSize == metadata.size + } + } catch { print("Error: \(error)") } + return false + } + + func fileProviderStorageSize(_ ocId: String, fileNameView: String) -> UInt64 { + let fileNamePath = getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView) + do { + let fileNameAttribute = try fileManager.attributesOfItem(atPath: fileNamePath) + let fileNameSize: UInt64 = fileNameAttribute[FileAttributeKey.size] as? UInt64 ?? 0 + return fileNameSize + } catch { print("Error: \(error)") } + return 0 + } + + func fileProviderStoragePreviewIconExists(_ ocId: String, etag: String) -> Bool { + let fileNamePathPreview = getDirectoryProviderStoragePreviewOcId(ocId, etag: etag) + let fileNamePathIcon = getDirectoryProviderStorageIconOcId(ocId, etag: etag) + do { + let fileNamePathPreviewAttribute = try fileManager.attributesOfItem(atPath: fileNamePathPreview) + let fileSizePreview: UInt64 = fileNamePathPreviewAttribute[FileAttributeKey.size] as? UInt64 ?? 0 + let fileNamePathIconAttribute = try fileManager.attributesOfItem(atPath: fileNamePathIcon) + let fileSizeIcon: UInt64 = fileNamePathIconAttribute[FileAttributeKey.size] as? UInt64 ?? 0 + if fileSizePreview > 0 && fileSizeIcon > 0 { + return true + } else { + return false + } + } catch { print("Error: \(error)") } + return false + } + + @objc func createDirectoryStandard() { + guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups)?.path else { return } + if !fileManager.fileExists(atPath: directoryDocuments) { try? fileManager.createDirectory(atPath: directoryDocuments, withIntermediateDirectories: true) } + let appDatabaseNextcloud = directoryGroup + "/" + NCGlobal.shared.appDatabaseNextcloud + if !fileManager.fileExists(atPath: appDatabaseNextcloud) { try? fileManager.createDirectory(atPath: appDatabaseNextcloud, withIntermediateDirectories: true) } + if !fileManager.fileExists(atPath: directoryUserData) { try? fileManager.createDirectory(atPath: directoryUserData, withIntermediateDirectories: true) } + if !fileManager.fileExists(atPath: directoryProviderStorage) { try? fileManager.createDirectory(atPath: directoryProviderStorage, withIntermediateDirectories: true) } + let appScan = directoryGroup + "/" + NCGlobal.shared.appScan + if !fileManager.fileExists(atPath: appScan) { try? fileManager.createDirectory(atPath: appScan, withIntermediateDirectories: true) } + if !fileManager.fileExists(atPath: NSTemporaryDirectory()) { try? fileManager.createDirectory(atPath: NSTemporaryDirectory(), withIntermediateDirectories: true) } + // Directory Excluded From Backup + if let url = NSURL(string: directoryDocuments) { + try? url.setResourceValue(true, forKey: URLResourceKey.isExcludedFromBackupKey) + } + if let url = NSURL(string: directoryGroup) { + try? url.setResourceValue(true, forKey: URLResourceKey.isExcludedFromBackupKey) + } + } + + @objc func removeGroupApplicationSupport() { + let path = directoryGroup + "/" + NCGlobal.shared.appApplicationSupport + try? fileManager.removeItem(atPath: path) + } + + @objc func removeGroupLibraryDirectory() { + try? fileManager.removeItem(atPath: directoryScan) + try? fileManager.removeItem(atPath: directoryUserData) + } + + @objc func removeGroupDirectoryProviderStorage() { + try? fileManager.removeItem(atPath: directoryProviderStorage) + } + + @objc func removeDocumentsDirectory() { + try? fileManager.removeItem(atPath: directoryDocuments) + } + + @objc func removeTemporaryDirectory() { + try? fileManager.removeItem(atPath: NSTemporaryDirectory()) + } + + @objc func emptyTemporaryDirectory() { + do { + let files = try fileManager.contentsOfDirectory(atPath: NSTemporaryDirectory()) + for file in files { + do { + try fileManager.removeItem(atPath: NSTemporaryDirectory() + "/" + file) + } catch { print("Error: \(error)") } + } + } catch { print("Error: \(error)") } + } + + // MARK: - + @objc func getFileSize(filePath: String) -> Int64 { do { @@ -82,10 +264,10 @@ class NCUtilityFileSystem: NSObject { } } - @objc func deleteFile(filePath: String) { + @objc func removeFile(atPath: String) { do { - try FileManager.default.removeItem(atPath: filePath) + try FileManager.default.removeItem(atPath: atPath) } catch { print(error) } @@ -185,6 +367,27 @@ class NCUtilityFileSystem: NSObject { return returnString } + func stringAppendServerUrl(_ serverUrl: String, addFileName: String) -> String { + + if addFileName.isEmpty { + return serverUrl + } else if serverUrl.last == "/" { + return serverUrl + addFileName + } else { + return serverUrl + "/" + addFileName + } + } + + @objc func getFileNamePath(_ fileName: String, serverUrl: String, urlBase: String, userId: String) -> String { + + let home = getHomeServer(urlBase: urlBase, userId: userId) + var fileNamePath = serverUrl.replacingOccurrences(of: home, with: "") + "/" + fileName + if fileNamePath.first == "/" { + fileNamePath.removeFirst() + } + return fileNamePath + } + @objc func createFileName(_ fileName: String, serverUrl: String, account: String) -> String { var resultFileName = fileName @@ -233,6 +436,23 @@ class NCUtilityFileSystem: NSObject { return resultFileName } + func createFileNameDate(_ fileName: String, ext: String) -> String { + + let formatter = DateFormatter() + formatter.dateFormat = "yy-MM-dd HH-mm-ss" + let fileNameDate = formatter.string(from: Date()) + + if fileName.isEmpty, !ext.isEmpty { + return fileNameDate + "." + ext + } else if !fileName.isEmpty, ext.isEmpty { + return fileName + " " + fileNameDate + } else if fileName.isEmpty, ext.isEmpty { + return fileNameDate + } else { + return fileName + " " + fileNameDate + "." + ext + } + } + @objc func getDirectorySize(directory: String) -> Int64 { let url = URL(fileURLWithPath: directory) @@ -252,6 +472,12 @@ class NCUtilityFileSystem: NSObject { return totalSize } + @objc func transformedSize(_ bytes: Int64) -> String { + let formatter: ByteCountFormatter = ByteCountFormatter() + formatter.countStyle = .binary + return formatter.string(fromByteCount: bytes) + } + func cleanUp(directory: String, days: TimeInterval) { if days == 0 { return} @@ -263,13 +489,13 @@ class NCUtilityFileSystem: NSObject { if let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "offline == true"), sorted: "serverUrl", ascending: true) { for directory: tableDirectory in directories { - offlineDir.append(CCUtility.getDirectoryProviderStorageOcId(directory.ocId)) + offlineDir.append(NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(directory.ocId)) } } let files = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "offline == true"), sorted: "fileName", ascending: true) for file: tableLocalFile in files { - offlineFiles.append(CCUtility.getDirectoryProviderStorageOcId(file.ocId, fileNameView: file.fileName)) + offlineFiles.append(NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(file.ocId, fileNameView: file.fileName)) } func meetsRequirement(date: Date) -> Bool { @@ -303,4 +529,22 @@ class NCUtilityFileSystem: NSObject { } } } + + func clearCacheDirectory(_ directory: String) { + if let cacheURL = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first { + do { + let directoryURL = cacheURL.appendingPathComponent(directory, isDirectory: true) + let directoryContents = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: nil, options: []) + for file in directoryContents { + do { + try fileManager.removeItem(at: file) + } catch let error as NSError { + debugPrint("Ooops! Something went wrong: \(error)") + } + } + } catch let error as NSError { + print(error.localizedDescription) + } + } + } } diff --git a/iOSClient/Viewer/NCViewer.swift b/iOSClient/Viewer/NCViewer.swift index 46918b3408..d460c58c20 100644 --- a/iOSClient/Viewer/NCViewer.swift +++ b/iOSClient/Viewer/NCViewer.swift @@ -31,10 +31,7 @@ class NCViewer: NSObject { return instance }() - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! private var viewerQuickLook: NCViewerQuickLook? private var metadata = tableMetadata() private var metadatas: [tableMetadata] = [] @@ -171,7 +168,7 @@ class NCViewer: NSObject { if metadata.url.isEmpty { - let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)! + let fileNamePath = NCUtilityFileSystem.shared.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId) var options = NKRequestOptions() if editor == NCGlobal.shared.editorOnlyoffice { @@ -228,10 +225,10 @@ class NCViewer: NSObject { } // QLPreview - let item = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) + let item = URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) if QLPreviewController.canPreview(item as QLPreviewItem) { let fileNamePath = NSTemporaryDirectory() + metadata.fileNameView - CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: fileNamePath) + NCUtilityFileSystem.shared.copyFile(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: fileNamePath) let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNamePath), isEditingEnabled: false, metadata: metadata) viewController.present(viewerQuickLook, animated: true) } else { diff --git a/iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayer.swift b/iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayer.swift index c169d1ed2d..7f11504470 100644 --- a/iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayer.swift +++ b/iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayer.swift @@ -28,10 +28,7 @@ import MobileVLCKit class NCPlayer: NSObject { - // swiftlint:disable force_cast - internal let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + internal let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! internal var url: URL? internal var player = VLCMediaPlayer() internal var dialogProvider: VLCDialogProvider? @@ -140,7 +137,7 @@ class NCPlayer: NSObject { if metadata.isVideo { if position == 0 { - let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)! + let fileNamePreviewLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag) imageVideoContainer?.image = UIImage(contentsOfFile: fileNamePreviewLocalPath) } else { imageVideoContainer?.image = nil diff --git a/iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayerToolBar.swift b/iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayerToolBar.swift index 2c8bdfac1a..82e1d8505e 100644 --- a/iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayerToolBar.swift +++ b/iOSClient/Viewer/NCViewerMedia/NCPlayer/NCPlayerToolBar.swift @@ -463,9 +463,9 @@ extension NCPlayerToolBar: NCSelectDelegate { if let metadata = metadata, let viewerMediaPage = viewerMediaPage { let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { addPlaybackSlave(type: type, metadata: metadata) } else { var downloadRequest: DownloadRequest? @@ -503,7 +503,7 @@ extension NCPlayerToolBar: NCSelectDelegate { func addPlaybackSlave(type: String, metadata: tableMetadata) { // swiftlint:enable inclusive_language - let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let fileNameLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) if type == "subtitle" { self.ncplayer?.player.addPlaybackSlave(URL(fileURLWithPath: fileNameLocalPath), type: .subtitle, enforce: true) diff --git a/iOSClient/Viewer/NCViewerMedia/NCViewerMedia.swift b/iOSClient/Viewer/NCViewerMedia/NCViewerMedia.swift index dea29843c5..a4b95ad351 100644 --- a/iOSClient/Viewer/NCViewerMedia/NCViewerMedia.swift +++ b/iOSClient/Viewer/NCViewerMedia/NCViewerMedia.swift @@ -47,11 +47,7 @@ class NCViewerMedia: UIViewController { private var tipView: EasyTipView? private let player = VLCMediaPlayer() - - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! weak var viewerMediaPage: NCViewerMediaPage? var playerToolBar: NCPlayerToolBar? var ncplayer: NCPlayer? @@ -189,8 +185,8 @@ class NCViewerMedia: UIViewController { } completion: { _, error in if error == .success { hud.dismiss() - if CCUtility.fileProviderStorageExists(self.metadata) { - let url = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(self.metadata.ocId, fileNameView: self.metadata.fileNameView)) + if NCUtilityFileSystem.shared.fileProviderStorageExists(self.metadata) { + let url = URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(self.metadata.ocId, fileNameView: self.metadata.fileNameView)) ncplayer.openAVPlayer(url: url, autoplay: autoplay) } } else { @@ -279,17 +275,17 @@ class NCViewerMedia: UIViewController { self.metadata = metadata // Download image - if !CCUtility.fileProviderStorageExists(metadata) && metadata.isImage && metadata.session.isEmpty { + if !NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) && metadata.isImage && metadata.session.isEmpty { if metadata.livePhoto { let fileName = (metadata.fileNameView as NSString).deletingPathExtension + ".mov" - if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", metadata.account, metadata.serverUrl, fileName)), !CCUtility.fileProviderStorageExists(metadata) { + if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", metadata.account, metadata.serverUrl, fileName)), !NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { NCNetworking.shared.download(metadata: metadata, selector: "") { _, _ in } } } } - if metadata.isImage, metadata.fileExtension.lowercased() == "gif", !CCUtility.fileProviderStorageExists(metadata) { + if metadata.isImage, metadata.fileExtension.lowercased() == "gif", !NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { downloadImage() } @@ -311,10 +307,8 @@ class NCViewerMedia: UIViewController { NCUtility.shared.createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile) } - if CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) { - if let imagePreviewPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag) { - return UIImage(contentsOfFile: imagePreviewPath) - } + if NCUtilityFileSystem.shared.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) { + return UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)) } if metadata.isAudio { @@ -331,10 +325,10 @@ class NCViewerMedia: UIViewController { let ext = CCUtility.getExtension(metadata.fileNameView) var image: UIImage? - if CCUtility.fileProviderStorageExists(metadata) && metadata.isImage { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) && metadata.isImage { - let previewPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)! - let imagePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let previewPath = NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag) + let imagePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) if ext == "GIF" { if !FileManager().fileExists(atPath: previewPath) { diff --git a/iOSClient/Viewer/NCViewerMedia/NCViewerMediaDetailView.swift b/iOSClient/Viewer/NCViewerMedia/NCViewerMediaDetailView.swift index ce38e0597a..955fa4df78 100644 --- a/iOSClient/Viewer/NCViewerMedia/NCViewerMediaDetailView.swift +++ b/iOSClient/Viewer/NCViewerMedia/NCViewerMediaDetailView.swift @@ -140,7 +140,7 @@ class NCViewerMediaDetailView: UIView { } nameLabel.text = (metadata.fileNameView as NSString).deletingPathExtension - sizeLabel.text = CCUtility.transformedSize(metadata.size) + sizeLabel.text = NCUtilityFileSystem.shared.transformedSize(metadata.size) if let shutterSpeedApex = exif.shutterSpeedApex { prepareLensInfoViewsForData() @@ -207,7 +207,7 @@ class NCViewerMediaDetailView: UIView { livePhotoImageView.isHidden = false } - if metadata.isImage && !CCUtility.fileProviderStorageExists(metadata) && metadata.session.isEmpty { + if metadata.isImage && !NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) && metadata.session.isEmpty { downloadImageButton.setTitle(NSLocalizedString("_try_download_full_resolution_", comment: ""), for: .normal) downloadImageLabel.text = NSLocalizedString("_full_resolution_image_info_", comment: "") downloadImageButtonContainer.isHidden = false diff --git a/iOSClient/Viewer/NCViewerMedia/NCViewerMediaPage.swift b/iOSClient/Viewer/NCViewerMedia/NCViewerMediaPage.swift index 39ba7e8ac3..92bc9fe217 100644 --- a/iOSClient/Viewer/NCViewerMedia/NCViewerMediaPage.swift +++ b/iOSClient/Viewer/NCViewerMedia/NCViewerMediaPage.swift @@ -229,7 +229,7 @@ class NCViewerMediaPage: UIViewController { @objc private func openMenuMore() { - let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(currentViewController.metadata.ocId, etag: currentViewController.metadata.etag)) + let imageIcon = UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(currentViewController.metadata.ocId, etag: currentViewController.metadata.etag)) NCViewer.shared.toggleMenu(viewController: self, metadata: currentViewController.metadata, webView: false, imageIcon: imageIcon) } @@ -255,12 +255,12 @@ class NCViewerMediaPage: UIViewController { } if metadata.isAudioOrVideo { - NCUtility.shared.colorNavigationController(navigationController, backgroundColor: .black, titleColor: .label, tintColor: nil, withoutShadow: false) + colorNavigationController(backgroundColor: .black, titleColor: .label, tintColor: nil, withoutShadow: false) currentViewController.playerToolBar?.show() view.backgroundColor = .black textColor = .white } else { - NCUtility.shared.colorNavigationController(navigationController, backgroundColor: .systemBackground, titleColor: .label, tintColor: nil, withoutShadow: false) + colorNavigationController(backgroundColor: .systemBackground, titleColor: .label, tintColor: nil, withoutShadow: false) view.backgroundColor = .systemGray6 textColor = .label } @@ -306,6 +306,28 @@ class NCViewerMediaPage: UIViewController { } } + func colorNavigationController(backgroundColor: UIColor, titleColor: UIColor, tintColor: UIColor?, withoutShadow: Bool) { + + let appearance = UINavigationBarAppearance() + appearance.titleTextAttributes = [.foregroundColor: titleColor] + appearance.largeTitleTextAttributes = [.foregroundColor: titleColor] + + if withoutShadow { + appearance.shadowColor = .clear + appearance.shadowImage = UIImage() + } + + if let tintColor = tintColor { + navigationController?.navigationBar.tintColor = tintColor + } + + navigationController?.view.backgroundColor = backgroundColor + navigationController?.navigationBar.barTintColor = titleColor + navigationController?.navigationBar.standardAppearance = appearance + navigationController?.navigationBar.compactAppearance = appearance + navigationController?.navigationBar.scrollEdgeAppearance = appearance + } + // MARK: - NotificationCenter @objc func downloadedFile(_ notification: NSNotification) { @@ -321,9 +343,9 @@ class NCViewerMediaPage: UIViewController { if metadata.ocId == ocId, metadata.isAudioOrVideo, - CCUtility.fileProviderStorageExists(metadata), + NCUtilityFileSystem.shared.fileProviderStorageExists(metadata), let ncplayer = currentViewController.ncplayer { - let url = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!) + let url = URL(fileURLWithPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) if ncplayer.isPlay() { ncplayer.playerPause() DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { @@ -674,9 +696,9 @@ extension NCViewerMediaPage: UIGestureRecognizerDelegate { if gestureRecognizer.state == .began { let fileName = (currentViewController.metadata.fileNameView as NSString).deletingPathExtension + ".mov" - if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", currentViewController.metadata.account, currentViewController.metadata.serverUrl, fileName)), CCUtility.fileProviderStorageExists(metadata) { + if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", currentViewController.metadata.account, currentViewController.metadata.serverUrl, fileName)), NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { AudioServicesPlaySystemSound(1519) // peek feedback - currentViewController.playLivePhoto(filePath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!) + currentViewController.playLivePhoto(filePath: NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) } } else if gestureRecognizer.state == .ended { currentViewController.stopLivePhoto() diff --git a/iOSClient/Viewer/NCViewerNextcloudText/NCViewerNextcloudText.swift b/iOSClient/Viewer/NCViewerNextcloudText/NCViewerNextcloudText.swift index 3eb885f4d2..80c2a78ee5 100644 --- a/iOSClient/Viewer/NCViewerNextcloudText/NCViewerNextcloudText.swift +++ b/iOSClient/Viewer/NCViewerNextcloudText/NCViewerNextcloudText.swift @@ -26,10 +26,7 @@ import WebKit class NCViewerNextcloudText: UIViewController, WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate { - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! var webView = WKWebView() var bottomConstraint: NSLayoutConstraint? var link: String = "" diff --git a/iOSClient/Viewer/NCViewerPDF/NCViewerPDF.swift b/iOSClient/Viewer/NCViewerPDF/NCViewerPDF.swift index 4c28ceccc9..441a077fe3 100644 --- a/iOSClient/Viewer/NCViewerPDF/NCViewerPDF.swift +++ b/iOSClient/Viewer/NCViewerPDF/NCViewerPDF.swift @@ -71,7 +71,7 @@ class NCViewerPDF: UIViewController, NCViewerPDFSearchDelegate { if let url = self.url { pdfDocument = PDFDocument(url: url) } else if let metadata = self.metadata { - filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + filePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) pdfDocument = PDFDocument(url: URL(fileURLWithPath: filePath)) navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "more")!.image(color: .label, size: 25), style: .plain, target: self, action: #selector(self.openMenuMore)) } diff --git a/iOSClient/Viewer/NCViewerProviderContextMenu.swift b/iOSClient/Viewer/NCViewerProviderContextMenu.swift index b2b3bd2187..6d4ac9e208 100644 --- a/iOSClient/Viewer/NCViewerProviderContextMenu.swift +++ b/iOSClient/Viewer/NCViewerProviderContextMenu.swift @@ -70,27 +70,27 @@ class NCViewerProviderContextMenu: UIViewController { } // PREVIEW - if CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) { + if NCUtilityFileSystem.shared.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) { - if let image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)) { + if let image = UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)) { imageView.image = image imageView.frame = resize(image.size) } } // VIEW IMAGE - if metadata.isImage && CCUtility.fileProviderStorageExists(metadata) { + if metadata.isImage && NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { viewImage(metadata: metadata) } // VIEW LIVE PHOTO - if let metadataLivePhoto = metadataLivePhoto, CCUtility.fileProviderStorageExists(metadataLivePhoto) { + if let metadataLivePhoto = metadataLivePhoto, NCUtilityFileSystem.shared.fileProviderStorageExists(metadataLivePhoto) { viewVideo(metadata: metadataLivePhoto) } // VIEW VIDEO if metadata.isVideo { - if !CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) { + if !NCUtilityFileSystem.shared.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) { let newSize = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) imageView.image = nil imageView.frame = newSize @@ -104,7 +104,7 @@ class NCViewerProviderContextMenu: UIViewController { var maxDownload: UInt64 = 0 - if CCUtility.fileProviderStorageExists(metadata) { + if NCUtilityFileSystem.shared.fileProviderStorageExists(metadata) { viewVideo(metadata: metadata) @@ -125,7 +125,7 @@ class NCViewerProviderContextMenu: UIViewController { } // AUTO DOWNLOAD IMAGE GIF - if !CCUtility.fileProviderStorageExists(metadata), + if !NCUtilityFileSystem.shared.fileProviderStorageExists(metadata), metadata.contentType == "image/gif", let appDelegate = (UIApplication.shared.delegate as? AppDelegate), appDelegate.downloadQueue.operations.filter({ ($0 as? NCOperationDownload)?.metadata.ocId == metadata.ocId }).isEmpty { @@ -133,7 +133,7 @@ class NCViewerProviderContextMenu: UIViewController { } // AUTO DOWNLOAD IMAGE SVG - if !CCUtility.fileProviderStorageExists(metadata), + if !NCUtilityFileSystem.shared.fileProviderStorageExists(metadata), metadata.contentType == "image/svg+xml", let appDelegate = (UIApplication.shared.delegate as? AppDelegate), appDelegate.downloadQueue.operations.filter({ ($0 as? NCOperationDownload)?.metadata.ocId == metadata.ocId }).isEmpty { @@ -142,7 +142,7 @@ class NCViewerProviderContextMenu: UIViewController { // AUTO DOWNLOAD LIVE PHOTO if let metadataLivePhoto = self.metadataLivePhoto, - !CCUtility.fileProviderStorageExists(metadataLivePhoto), + !NCUtilityFileSystem.shared.fileProviderStorageExists(metadataLivePhoto), let appDelegate = (UIApplication.shared.delegate as? AppDelegate), appDelegate.downloadQueue.operations.filter({ ($0 as? NCOperationDownload)?.metadata.ocId == metadata.ocId }).isEmpty { appDelegate.downloadQueue.addOperation(NCOperationDownload(metadata: metadataLivePhoto, selector: "")) @@ -229,12 +229,12 @@ class NCViewerProviderContextMenu: UIViewController { var image: UIImage? - let filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let filePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) if metadata.contentType == "image/gif" { image = UIImage.animatedImage(withAnimatedGIFURL: URL(fileURLWithPath: filePath)) } else if metadata.contentType == "image/svg+xml" { - let imagePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! + let imagePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) if let svgImage = SVGKImage(contentsOfFile: imagePath) { svgImage.size = CGSize(width: NCGlobal.shared.sizePreview, height: NCGlobal.shared.sizePreview) image = svgImage.uiImage diff --git a/iOSClient/Viewer/NCViewerQuickLook/NCViewerQuickLook.swift b/iOSClient/Viewer/NCViewerQuickLook/NCViewerQuickLook.swift index 761b0ccaa7..ddb6400faa 100644 --- a/iOSClient/Viewer/NCViewerQuickLook/NCViewerQuickLook.swift +++ b/iOSClient/Viewer/NCViewerQuickLook/NCViewerQuickLook.swift @@ -215,8 +215,8 @@ extension NCViewerQuickLook: QLPreviewControllerDataSource, QLPreviewControllerD metadata.fileNameView = fileName } - guard let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: metadata.fileNameView), - NCUtilityFileSystem.shared.copyFile(atPath: url.path, toPath: fileNamePath) else { return } + let fileNamePath = NCUtilityFileSystem.shared.getDirectoryProviderStorageOcId(ocId, fileNameView: metadata.fileNameView) + guard NCUtilityFileSystem.shared.copyFile(atPath: url.path, toPath: fileNamePath) else { return } let metadataForUpload = NCManageDatabase.shared.createMetadata( account: metadata.account, diff --git a/iOSClient/Viewer/NCViewerRichdocument/NCViewerRichdocument.swift b/iOSClient/Viewer/NCViewerRichdocument/NCViewerRichdocument.swift index 16f46937ed..6c36b8ea2b 100644 --- a/iOSClient/Viewer/NCViewerRichdocument/NCViewerRichdocument.swift +++ b/iOSClient/Viewer/NCViewerRichdocument/NCViewerRichdocument.swift @@ -27,10 +27,7 @@ import NextcloudKit class NCViewerRichdocument: UIViewController, WKNavigationDelegate, WKScriptMessageHandler, NCSelectDelegate { - // swiftlint:disable force_cast - let appDelegate = UIApplication.shared.delegate as! AppDelegate - // swiftlint:enable force_cast - + let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! var webView = WKWebView() var bottomConstraint: NSLayoutConstraint? var documentController: UIDocumentInteractionController? @@ -188,7 +185,7 @@ class NCViewerRichdocument: UIViewController, WKNavigationDelegate, WKScriptMess guard let type = values["Type"] as? String else { return } guard let urlString = values["URL"] as? String else { return } guard let url = URL(string: urlString) else { return } - let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + (metadata.fileName as NSString).deletingPathExtension + let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + (metadata.fileName as NSString).deletingPathExtension if type == "slideshow" { @@ -224,7 +221,7 @@ class NCViewerRichdocument: UIViewController, WKNavigationDelegate, WKScriptMess if let disposition = allHeaderFields["Content-Disposition"] as? String { let components = disposition.components(separatedBy: "filename=") if let filename = components.last?.replacingOccurrences(of: "\"", with: "") { - item = CCUtility.getDirectoryUserData() + "/" + filename + item = NCUtilityFileSystem.shared.directoryUserData + "/" + filename _ = NCUtilityFileSystem.shared.moveFile(atPath: fileNameLocalPath, toPath: item) } } @@ -293,13 +290,13 @@ class NCViewerRichdocument: UIViewController, WKNavigationDelegate, WKScriptMess func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], indexPath: [IndexPath], overwrite: Bool, copy: Bool, move: Bool) { - if serverUrl != nil && metadata != nil { + if let serverUrl, let metadata { - let path = CCUtility.returnFileNamePath(fromFileName: metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: metadata!.account)! + let path = NCUtilityFileSystem.shared.getFileNamePath(metadata.fileName, serverUrl: serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId) NextcloudKit.shared.createAssetRichdocuments(path: path) { account, url, _, error in - if error == .success && account == self.appDelegate.account { - let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata!.fileNameView)', '\(url!)')" + if error == .success, account == self.appDelegate.account, let url { + let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url)')" self.webView.evaluateJavaScript(functionJS, completionHandler: { _, _ in }) } else if error != .success { NCContentPresenter.shared.showError(error: error) @@ -312,11 +309,11 @@ class NCViewerRichdocument: UIViewController, WKNavigationDelegate, WKScriptMess func select(_ metadata: tableMetadata!, serverUrl: String!) { - let path = CCUtility.returnFileNamePath(fromFileName: metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: metadata!.account)! + let path = NCUtilityFileSystem.shared.getFileNamePath(metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, userId: appDelegate.userId) NextcloudKit.shared.createAssetRichdocuments(path: path) { account, url, _, error in - if error == .success && account == self.appDelegate.account { - let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url!)')" + if error == .success, account == self.appDelegate.account, let url { + let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url)')" self.webView.evaluateJavaScript(functionJS, completionHandler: { _, _ in }) } else if error != .success { NCContentPresenter.shared.showError(error: error)