ソースを参照

Merge pull request #2244 from nextcloud/ImprovedRealmProcess

Improved realm process
Marino Faggiana 2 年 前
コミット
4f49e2df22

+ 2 - 2
Nextcloud.xcodeproj/project.pbxproj

@@ -3619,7 +3619,7 @@
 				CLANG_WARN_UNREACHABLE_CODE = YES;
 				CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
 				COPY_PHASE_STRIP = NO;
-				CURRENT_PROJECT_VERSION = 0;
+				CURRENT_PROJECT_VERSION = 1;
 				DEVELOPMENT_TEAM = NKUJUXUJ3B;
 				ENABLE_STRICT_OBJC_MSGSEND = YES;
 				ENABLE_TESTABILITY = YES;
@@ -3682,7 +3682,7 @@
 				CLANG_WARN_UNREACHABLE_CODE = YES;
 				CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
 				COPY_PHASE_STRIP = NO;
-				CURRENT_PROJECT_VERSION = 0;
+				CURRENT_PROJECT_VERSION = 1;
 				DEVELOPMENT_TEAM = NKUJUXUJ3B;
 				ENABLE_STRICT_OBJC_MSGSEND = YES;
 				ENABLE_TESTABILITY = YES;

+ 2 - 2
Widget/Dashboard/DashboardData.swift

@@ -140,7 +140,6 @@ func getDashboardDataEntry(configuration: DashboardIntent?, isPreview: Bool, dis
     
     let (tableDashboard, tableButton) = NCManageDatabase.shared.getDashboardWidget(account: account.account, id: id)
     let existsButton = (tableButton?.isEmpty ?? true) ? false : true
-    let options = NKRequestOptions(timeout: 15, queue: NKCommon.shared.backgroundQueue)
     let title = tableDashboard?.title ?? id
 
     var imagetmp = UIImage(named: "widget")!
@@ -151,7 +150,8 @@ func getDashboardDataEntry(configuration: DashboardIntent?, isPreview: Bool, dis
         }
     }
     let titleImage = imagetmp
-        
+
+    let options = NKRequestOptions(timeout: 90, queue: NKCommon.shared.backgroundQueue)
     NextcloudKit.shared.getDashboardWidgetsApplication(id, options: options) { _, results, data, error in
 
         Task {

+ 1 - 1
Widget/Dashboard/DashboardWidgetView.swift

@@ -168,7 +168,7 @@ struct DashboardWidgetView: View {
                                     .background(brandColor)
                                     .foregroundColor(brandTextColor)
                                     .border(brandColor, width: 1)
-                                    .cornerRadius(16)
+                                    .cornerRadius(.infinity)
                             })
                         }
                     }

+ 2 - 2
Widget/Files/FilesData.swift

@@ -197,7 +197,7 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi
         NKCommon.shared.writeLog("[INFO] Start \(NCBrandOptions.shared.brand) widget session with level \(levelLog) " + versionNextcloudiOS)
     }
     
-    let options = NKRequestOptions(timeout: 15)
+    let options = NKRequestOptions(timeout: 90, queue: NKCommon.shared.backgroundQueue)
     NextcloudKit.shared.searchBodyRequest(serverUrl: account.urlBase, requestBody: requestBody, showHiddenFiles: CCUtility.getShowHiddenFiles(), options: options) { _, files, data, error in
         Task {
             var datas: [FilesData] = []
@@ -230,7 +230,7 @@ func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySi
                     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 (_, _, imageIcon, _, _, _) = await NextcloudKit.shared.downloadPreview(fileNamePathOrFileId: fileNamePathOrFileId, fileNamePreviewLocalPath: fileNamePreviewLocalPath, widthPreview: NCGlobal.shared.sizePreview, heightPreview: NCGlobal.shared.sizePreview, fileNameIconLocalPath: fileNameIconLocalPath, sizeIcon: NCGlobal.shared.sizeIcon)
+                    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
                     }

+ 1 - 1
Widget/Lockscreen/LockscreenData.swift

@@ -39,7 +39,6 @@ func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, fami
 
     var account: tableAccount?
     var quotaRelative: Float = 0
-    let options = NKRequestOptions(timeout: 15, queue: NKCommon.shared.backgroundQueue)
 
     if isPreview {
         return completion(LockscreenData(date: Date(), isPlaceholder: true, activity: "", link: URL(string: "https://")!, quotaRelative: 0, quotaUsed: "", quotaTotal: "", error: false))
@@ -73,6 +72,7 @@ func getLockscreenDataEntry(configuration: AccountIntent?, isPreview: Bool, fami
         nextcloudVersion: 0,
         delegate: NCNetworking.shared)
 
+    let options = NKRequestOptions(timeout: 90, queue: NKCommon.shared.backgroundQueue)
     if #available(iOSApplicationExtension 16.0, *) {
         if family == .accessoryCircular {
             NextcloudKit.shared.getUserProfile(options: options) { _, userProfile, _, error in

+ 8 - 3
Widget/Lockscreen/LockscreenWidgetView.swift

@@ -46,8 +46,13 @@ struct LockscreenWidgetView: View {
             } else {
                 Gauge(
                     value: entry.quotaRelative,
-                    label: { Text("  " + entry.quotaTotal + "  ") },
-                    currentValueLabel: { Text(entry.quotaUsed) }
+                    label: {
+                        Text(" " + entry.quotaTotal + " ")
+                            .font(.system(size: 8.0))
+                    },
+                    currentValueLabel: {
+                        Text(entry.quotaUsed)
+                    }
                 )
                 .gaugeStyle(.accessoryCircular)
                 .redacted(reason: entry.isPlaceholder ? .placeholder : [])
@@ -88,7 +93,7 @@ struct LockscreenWidgetView: View {
 @available(iOSApplicationExtension 16.0, *)
 struct LockscreenWidgetView_Previews: PreviewProvider {
     static var previews: some View {
-        let entry = LockscreenData(date: Date(), isPlaceholder: false, activity: "Alba Mayoral changed Marketing / Regional Marketing / Agenda Meetings / Q4 2022 / OCTOBER / 13.11 Afrah Kahlid.md", link: URL(string: "https://")!, quotaRelative: 0.5, quotaUsed: "22 GB", quotaTotal: "50 GB", error: true)
+        let entry = LockscreenData(date: Date(), isPlaceholder: false, activity: "Alba Mayoral changed Marketing / Regional Marketing / Agenda Meetings / Q4 2022 / OCTOBER / 13.11 Afrah Kahlid.md", link: URL(string: "https://")!, quotaRelative: 0.5, quotaUsed: "999 GB", quotaTotal: "999 GB", error: false)
         LockscreenWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .accessoryRectangular)).previewDisplayName("Rectangular")
         LockscreenWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .accessoryCircular)).previewDisplayName("Circular")
     }

+ 10 - 9
iOSClient/AppDelegate.swift

@@ -48,7 +48,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
     @objc var activeViewController: UIViewController?
     var mainTabBar: NCMainTabBar?
     var activeMetadata: tableMetadata?
-    var isSearchingMode: Bool = false
 
     let listFilesVC = ThreadSafeDictionary<String,NCFiles>()
     let listFavoriteVC = ThreadSafeDictionary<String,NCFavorite>()
@@ -189,6 +188,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
 
         NKCommon.shared.writeLog("[INFO] Application did become active")
 
+        // START OBSERVE/TIMER UPLOAD PROCESS
+        NCNetworkingProcessUpload.shared.observeTableMetadata()
+        NCNetworkingProcessUpload.shared.startTimer()
+
         self.deletePasswordSession = false
 
         if !NCAskAuthorization.shared.isRequesting {
@@ -206,9 +209,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
             NKCommon.shared.writeLog("[INFO] Initialize Auto upload with \(items) uploads")
         }
 
-        // START UPLOAD PROCESS
-        NCNetworkingProcessUpload.shared.startTimer()
-
         NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidBecomeActive)
     }
 
@@ -243,14 +243,15 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
 
         NKCommon.shared.writeLog("[INFO] Application will resign active")
 
+        // STOP OBSERVE/TIMER UPLOAD PROCESS
+        NCNetworkingProcessUpload.shared.invalidateObserveTableMetadata()
+        NCNetworkingProcessUpload.shared.stopTimer()
+
         if CCUtility.getPrivacyScreenEnabled() {
             // Privacy
             showPrivacyProtectionWindow()
         }
 
-        // STOP UPLOAD PROCESS
-        NCNetworkingProcessUpload.shared.stopTimer()
-
         // Reload Widget
         WidgetCenter.shared.reloadAllTimelines()
 
@@ -371,7 +372,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
 
         NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
             NKCommon.shared.writeLog("[INFO] Refresh task auto upload with \(items) uploads")
-            NCNetworkingProcessUpload.shared.process { items in
+            NCNetworkingProcessUpload.shared.start { items in
                 NKCommon.shared.writeLog("[INFO] Refresh task upload process with \(items) uploads")
                 task.setTaskCompleted(success: true)
             }
@@ -864,7 +865,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
 
         else if scheme == "nextcloud" && action == "open-file" {
 
-            if !isSearchingMode, let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
+            if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
 
                 let queryItems = urlComponents.queryItems
                 guard let userScheme = CCUtility.value(forKey: "user", fromQueryItems: queryItems) else { return false }

+ 6 - 4
iOSClient/BrowserWeb/NCBrowserWeb.swift

@@ -110,10 +110,12 @@ class NCBrowserWeb: UIViewController {
 extension NCBrowserWeb: WKNavigationDelegate {
 
     public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
-        if let serverTrust = challenge.protectionSpace.serverTrust {
-            completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
-        } else {
-            completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
+        DispatchQueue.global().async {
+            if let serverTrust = challenge.protectionSpace.serverTrust {
+                completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
+            } else {
+                completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
+            }
         }
     }
 

+ 2 - 2
iOSClient/Files/NCFiles.swift

@@ -94,7 +94,7 @@ class NCFiles: NCCollectionViewCommon {
 
         DispatchQueue.main.async { self.refreshControl.endRefreshing() }
         DispatchQueue.global().async {
-            guard !self.appDelegate.isSearchingMode, !self.appDelegate.account.isEmpty, !self.appDelegate.urlBase.isEmpty, !self.serverUrl.isEmpty else { return }
+            guard !self.isSearchingMode, !self.appDelegate.account.isEmpty, !self.appDelegate.urlBase.isEmpty, !self.serverUrl.isEmpty else { return }
 
             let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
             if self.metadataFolder == nil {
@@ -136,7 +136,7 @@ class NCFiles: NCCollectionViewCommon {
 
     override func reloadDataSourceNetwork(forced: Bool = false) {
         super.reloadDataSourceNetwork(forced: forced)
-        guard !appDelegate.isSearchingMode else {
+        guard !isSearchingMode else {
             networkSearch()
             return
         }

+ 25 - 24
iOSClient/Main/Collection Common/NCCollectionViewCommon.swift

@@ -44,6 +44,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
     internal var dataSource = NCDataSource()
     internal var richWorkspaceText: String?
     internal var headerMenu: NCSectionHeaderMenu?
+    internal var isSearchingMode: Bool = false
 
     internal var layoutForView: NCGlobal.layoutForViewType?
     internal var selectableDataSource: [RealmSwiftObject] { dataSource.getMetadataSourceForAllSections() }
@@ -216,7 +217,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
         setNavigationItem()
 
         reloadDataSource(forced: false)
-        if !appDelegate.isSearchingMode {
+        if !isSearchingMode {
             reloadDataSourceNetwork()
         }
 
@@ -291,9 +292,9 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
         guard !appDelegate.account.isEmpty else { return }
 
         // Search
-        if searchController?.isActive ?? false || appDelegate.isSearchingMode {
+        if searchController?.isActive ?? false || isSearchingMode {
             searchController?.isActive = false
-            appDelegate.isSearchingMode = false
+            isSearchingMode = false
         }
 
         // Select
@@ -343,7 +344,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
 
     @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
 
-        if !appDelegate.isSearchingMode {
+        if !isSearchingMode {
             reloadDataSourceNetwork(forced: true)
         }
     }
@@ -426,7 +427,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
 
     @objc func renameFile(_ notification: NSNotification) {
 
-        if appDelegate.isSearchingMode {
+        if isSearchingMode {
             reloadDataSourceNetwork()
         } else {
             reloadDataSource()
@@ -545,7 +546,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
               account == appDelegate.account
         else { return }
 
-        guard !appDelegate.isSearchingMode, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return }
+        guard !isSearchingMode, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return }
         dataSource.addMetadata(metadata)
         self.collectionView?.reloadData()
     }
@@ -741,7 +742,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
     func emptyDataSetView(_ view: NCEmptyView) {
 
         self.emptyDataSet?.setOffset(getHeaderHeight())
-        if appDelegate.isSearchingMode {
+        if isSearchingMode {
             view.emptyImage.image = UIImage(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
             if isReloadDataSourceNetworkInProgress {
                 view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
@@ -774,7 +775,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
 
     func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
 
-        appDelegate.isSearchingMode = true
+        isSearchingMode = true
         self.providers?.removeAll()
         self.dataSource.clearDataSource()
         self.collectionView.reloadData()
@@ -785,7 +786,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
 
     func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
 
-        if appDelegate.isSearchingMode && self.literalSearch?.count ?? 0 >= 2 {
+        if isSearchingMode && self.literalSearch?.count ?? 0 >= 2 {
             reloadDataSourceNetwork()
         }
     }
@@ -795,7 +796,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
         DispatchQueue.global().async {
             NCNetworking.shared.cancelUnifiedSearchFiles()
 
-            self.appDelegate.isSearchingMode = false
+            self.isSearchingMode = false
             self.literalSearch = ""
             self.providers?.removeAll()
             self.dataSource.clearDataSource()
@@ -845,7 +846,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
             headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
             layoutForView?.layout = NCGlobal.shared.layoutGrid
             NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
-            if appDelegate.isSearchingMode {
+            if isSearchingMode {
                 self.groupByField = "name"
             } else {
                 self.groupByField = "classFile"
@@ -1016,7 +1017,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
         layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
 
         // set GroupField for Grid
-        if !appDelegate.isSearchingMode && layoutForView?.layout == NCGlobal.shared.layoutGrid {
+        if !isSearchingMode && layoutForView?.layout == NCGlobal.shared.layoutGrid {
             groupByField = "classFile"
         } else {
             groupByField = "name"
@@ -1053,7 +1054,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
                     providers: self.providers,
                     searchResults: self.searchResults)
             } update: { account, id, searchResult, metadatas in
-                guard let metadatas = metadatas, metadatas.count > 0, self.appDelegate.isSearchingMode , let searchResult = searchResult else { return }
+                guard let metadatas = metadatas, metadatas.count > 0, self.isSearchingMode , let searchResult = searchResult else { return }
                 NCOperationQueue.shared.unifiedSearchAddSection(collectionViewCommon: self, metadatas: metadatas, searchResult: searchResult)
             } completion: { account, error in
                 self.refreshControl.endRefreshing()
@@ -1066,7 +1067,7 @@ class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UIS
                     self.refreshControl.endRefreshing()
                     self.collectionView.reloadData()
                 }
-                guard let metadatas = metadatas, error == .success, self.appDelegate.isSearchingMode else { return }
+                guard let metadatas = metadatas, error == .success, self.isSearchingMode else { return }
                 self.dataSource = NCDataSource(
                     metadatas: metadatas,
                     account: self.appDelegate.account,
@@ -1498,7 +1499,7 @@ extension NCCollectionViewCommon: UICollectionViewDataSource {
         cell.hideButtonMore(false)
         cell.titleInfoTrailingDefault()
 
-        if appDelegate.isSearchingMode {
+        if isSearchingMode {
             cell.fileTitleLabel?.text = metadata.fileName
             cell.fileTitleLabel?.lineBreakMode = .byTruncatingTail
             if metadata.name == NCGlobal.shared.appName {
@@ -1649,7 +1650,7 @@ extension NCCollectionViewCommon: UICollectionViewDataSource {
         }
 
         // Separator
-        if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 || appDelegate.isSearchingMode {
+        if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 || isSearchingMode {
             cell.cellSeparatorView?.isHidden = true
         } else {
             cell.cellSeparatorView?.isHidden = false
@@ -1672,7 +1673,7 @@ extension NCCollectionViewCommon: UICollectionViewDataSource {
         cell.setAccessibility(label: metadata.fileNameView + ", " + (cell.fileInfoLabel?.text ?? ""), value: a11yValues.joined(separator: ", "))
 
         // Color string find in search
-        if appDelegate.isSearchingMode, let literalSearch = self.literalSearch, let title = cell.fileTitleLabel?.text {
+        if isSearchingMode, let literalSearch = self.literalSearch, let title = cell.fileTitleLabel?.text {
             let longestWordRange = (title.lowercased() as NSString).range(of: literalSearch)
             let attributedString = NSMutableAttributedString(string: title, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15)])
             attributedString.setAttributes([NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15), NSAttributedString.Key.foregroundColor : UIColor.systemBlue], range: longestWordRange)
@@ -1701,7 +1702,7 @@ extension NCCollectionViewCommon: UICollectionViewDataSource {
                 }
 
                 header.delegate = self
-                if headerMenuButtonsCommand && !appDelegate.isSearchingMode {
+                if headerMenuButtonsCommand && !isSearchingMode {
                     header.setButtonsCommand(heigt: NCGlobal.shared.heightButtonsCommand, imageButton1: UIImage(named: "addImage"), titleButton1: NSLocalizedString("_upload_", comment: ""), imageButton2: UIImage(named: "folder"), titleButton2: NSLocalizedString("_create_folder_", comment: ""), imageButton3: UIImage(named: "scan"), titleButton3: NSLocalizedString("_scan_", comment: ""))
                 } else {
                     header.setButtonsCommand(heigt: 0)
@@ -1756,11 +1757,11 @@ extension NCCollectionViewCommon: UICollectionViewDataSource {
             footer.buttonIsHidden(true)
             footer.hideActivityIndicatorSection()
 
-            if appDelegate.isSearchingMode {
+            if isSearchingMode {
                 if sections > 1 && section != sections - 1 {
                     footer.separatorIsHidden(false)
                 }
-                if appDelegate.isSearchingMode && isPaginated && metadatasCount > 0 {
+                if isSearchingMode && isPaginated && metadatasCount > 0 {
                     footer.buttonIsHidden(false)
                 }
                 if unifiedSearchInProgress {
@@ -1786,7 +1787,7 @@ extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
 
         var size: CGFloat = 0
 
-        if headerMenuButtonsCommand && !appDelegate.isSearchingMode {
+        if headerMenuButtonsCommand && !isSearchingMode {
             size += NCGlobal.shared.heightButtonsCommand
         }
         if headerMenuButtonsView {
@@ -1802,12 +1803,12 @@ extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
 
         if let richWorkspaceText = richWorkspaceText, !headerRichWorkspaceDisable {
             let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
-            if trimmed.count > 0 && !appDelegate.isSearchingMode {
+            if trimmed.count > 0 && !isSearchingMode {
                 headerRichWorkspace = UIScreen.main.bounds.size.height / 6
             }
         }
 
-        if appDelegate.isSearchingMode || layoutForView?.layout == NCGlobal.shared.layoutGrid || dataSource.numberOfSections() > 1 {
+        if isSearchingMode || layoutForView?.layout == NCGlobal.shared.layoutGrid || dataSource.numberOfSections() > 1 {
             if section == 0 {
                 return (getHeaderHeight(), headerRichWorkspace, NCGlobal.shared.heightSection)
             } else {
@@ -1840,7 +1841,7 @@ extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
             size.height += NCGlobal.shared.heightFooter
         }
 
-        if appDelegate.isSearchingMode && isPaginated && metadatasCount > 0 {
+        if isSearchingMode && isPaginated && metadatasCount > 0 {
             size.height += NCGlobal.shared.heightFooterButton
         }
 

+ 0 - 2
iOSClient/Main/NCFunctionCenter.swift

@@ -462,8 +462,6 @@ import Photos
 
     func openFileViewInFolder(serverUrl: String, fileNameBlink: String?, fileNameOpen: String?) {
 
-        appDelegate.isSearchingMode = false
-        
         DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
             var topNavigationController: UINavigationController?
             var pushServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: self.appDelegate.urlBase, userId: self.appDelegate.userId)

+ 12 - 16
iOSClient/Networking/NCNetworking.swift

@@ -129,11 +129,8 @@ import Photos
     }
 
     func authenticationChallenge(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
-
-        if checkTrustedChallenge(session, didReceive: challenge) {
-            completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
-        } else {
-            completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
+        DispatchQueue.global().async {
+            self.checkTrustedChallenge(session, didReceive: challenge, completionHandler: completionHandler)
         }
     }
 
@@ -158,7 +155,7 @@ import Photos
 
     // MARK: - Pinning check
 
-    private func checkTrustedChallenge(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge) -> Bool {
+    private func checkTrustedChallenge(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
 
         let protectionSpace: URLProtectionSpace = challenge.protectionSpace
         let directoryCertificate = CCUtility.getDirectoryCerificates()!
@@ -166,14 +163,6 @@ import Photos
         let certificateSavedPath = directoryCertificate + "/" + host + ".der"
         var isTrusted: Bool
 
-        #if !EXTENSION
-        defer {
-            if !isTrusted {
-                DispatchQueue.main.async { (UIApplication.shared.delegate as? AppDelegate)?.trustCertificateError(host: host) }
-            }
-        }
-        #endif
-
         if let serverTrust: SecTrust = protectionSpace.serverTrust, let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
 
             // extarct certificate txt
@@ -197,8 +186,15 @@ import Photos
         } else {
             isTrusted = false
         }
-        
-        return isTrusted
+
+        if isTrusted {
+            completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
+        } else {
+            #if !EXTENSION
+            DispatchQueue.main.async { (UIApplication.shared.delegate as? AppDelegate)?.trustCertificateError(host: host) }
+            #endif
+            completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
+        }
     }
 
     func writeCertificate(host: String) {

+ 73 - 52
iOSClient/Networking/NCNetworkingProcessUpload.swift

@@ -25,6 +25,7 @@ import UIKit
 import NextcloudKit
 import Photos
 import JGProgressHUD
+import RealmSwift
 
 class NCNetworkingProcessUpload: NSObject {
     public static let shared: NCNetworkingProcessUpload = {
@@ -32,12 +33,43 @@ class NCNetworkingProcessUpload: NSObject {
         return instance
     }()
 
-    var timerProcess: Timer?
+    private let appDelegate = UIApplication.shared.delegate as! AppDelegate
+    private var notificationToken: NotificationToken?
+    private var timerProcess: Timer?
+    private var pauseProcess: Bool = false
+
+    func observeTableMetadata() {
+        let realm = try! Realm()
+        let results = realm.objects(tableMetadata.self).filter("session != '' || sessionError != ''")
+        notificationToken = results.observe { [weak self] (changes: RealmCollectionChange) in
+            switch changes {
+            case .initial:
+                print("Initial")
+            case .update(_, let deletions, let insertions, let modifications):
+                if (deletions.count > 0 || insertions.count > 0 || modifications.count > 0) {
+                    self?.invalidateObserveTableMetadata()
+                    self?.start(completition: { items in
+                        print("[LOG] PROCESS-UPLOAD-OBSERVE \(items)")
+                        DispatchQueue.main.async {
+                            self?.observeTableMetadata()
+                        }
+                    })
+                }
+            case .error(let error):
+                NKCommon.shared.writeLog("[ERROR] Could not write to TableMetadata: \(error)")
+            }
+        }
+    }
+
+    func invalidateObserveTableMetadata() {
+        notificationToken?.invalidate()
+        notificationToken = nil
+    }
 
     func startTimer() {
         DispatchQueue.main.async {
             self.timerProcess?.invalidate()
-            self.timerProcess = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.processTimer), userInfo: nil, repeats: true)
+            self.timerProcess = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.processTimer), userInfo: nil, repeats: true)
         }
     }
 
@@ -47,19 +79,21 @@ class NCNetworkingProcessUpload: NSObject {
         }
     }
 
-    @objc func processTimer() {
-        process { _ in }
+    @objc private func processTimer() {
+        start { items in
+            print("[LOG] PROCESS-UPLOAD-TIMER \(items)")
+        }
     }
 
-    func process(completition: @escaping (_ items: Int) -> Void) {
-
-        guard let account = NCManageDatabase.shared.getActiveAccount() else { return }
+    func start(completition: @escaping (_ items: Int) -> Void) {
 
-        stopTimer()
+        if appDelegate.account.isEmpty || pauseProcess {
+            return completition(0)
+        } else {
+            pauseProcess = true
+        }
 
-        let appDelegate = UIApplication.shared.delegate as! AppDelegate
         let applicationState = UIApplication.shared.applicationState
-        let isPasscodePresented = appDelegate.isPasscodePresented()
         let queue = DispatchQueue.global()
         var maxConcurrentOperationUpload = 10
         let viewController = appDelegate.window?.rootViewController
@@ -67,17 +101,15 @@ class NCNetworkingProcessUpload: NSObject {
 
         queue.async {
 
-            let metadatasUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status == %d OR status == %d", NCGlobal.shared.metadataStatusInUpload, NCGlobal.shared.metadataStatusUploading))
+            let metadatasUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND (status == %d OR status == %d)", self.appDelegate.account, NCGlobal.shared.metadataStatusInUpload, NCGlobal.shared.metadataStatusUploading))
             let isWiFi = NCNetworking.shared.networkReachability == NKCommon.typeReachability.reachableEthernetOrWiFi
             var counterUpload: Int = 0
             let sessionSelectors = [NCGlobal.shared.selectorUploadFileNODelete, NCGlobal.shared.selectorUploadFile, NCGlobal.shared.selectorUploadAutoUpload, NCGlobal.shared.selectorUploadAutoUploadAll]
 
             counterUpload = metadatasUpload.count
 
-            print("[LOG] PROCESS-UPLOAD \(counterUpload)")
-
             // Update Badge
-            let counterBadge = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status == %d OR status == %d OR status == %d", NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusInUpload, NCGlobal.shared.metadataStatusUploading))
+            let counterBadge = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND (status == %d OR status == %d OR status == %d)", self.appDelegate.account, NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusInUpload, NCGlobal.shared.metadataStatusUploading))
             NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUpdateBadgeNumber, userInfo: ["counter":counterBadge.count])
 
             NCNetworking.shared.getOcIdInBackgroundSession(queue: queue, completion: { listOcId in
@@ -85,19 +117,13 @@ class NCNetworkingProcessUpload: NSObject {
                 for sessionSelector in sessionSelectors where counterUpload < maxConcurrentOperationUpload {
 
                     let limit = maxConcurrentOperationUpload - counterUpload
-                    let metadatas = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "sessionSelector == %@ AND status == %d", sessionSelector, NCGlobal.shared.metadataStatusWaitUpload), page: 1, limit: limit, sorted: "date", ascending: true)
+                    let metadatas = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "account == %@ AND sessionSelector == %@ AND status == %d", self.appDelegate.account, sessionSelector, NCGlobal.shared.metadataStatusWaitUpload), page: 1, limit: limit, sorted: "date", ascending: true)
                     if metadatas.count > 0 {
                         NKCommon.shared.writeLog("[INFO] PROCESS-UPLOAD find \(metadatas.count) items")
                     }
 
                     for metadata in metadatas where counterUpload < maxConcurrentOperationUpload {
 
-                        // Different account
-                        if account.account != metadata.account {
-                            NKCommon.shared.writeLog("[INFO] Process auto upload skipped file: \(metadata.serverUrl)/\(metadata.fileNameView) on account: \(metadata.account), because the actual account is \(account.account).")
-                            continue
-                        }
-
                         // Is already in upload background? skipped
                         if listOcId.contains(metadata.ocId) {
                             NKCommon.shared.writeLog("[INFO] Process auto upload skipped file: \(metadata.serverUrl)/\(metadata.fileNameView), because is already in session.")
@@ -147,49 +173,44 @@ class NCNetworkingProcessUpload: NSObject {
 
                 // No upload available ? --> Retry Upload in Error
                 if counterUpload == 0 {
-                    let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status == %d", NCGlobal.shared.metadataStatusUploadError))
+                    let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND status == %d", self.appDelegate.account, NCGlobal.shared.metadataStatusUploadError))
                     for metadata in metadatas {
                         NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: NCNetworking.shared.sessionIdentifierBackground, sessionError: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusWaitUpload)
                     }
-                }
 
-                // verify delete Asset Local Identifiers in auto upload (DELETE Photos album)
-                if applicationState == .active && counterUpload == 0 && !isPasscodePresented {
-                    self.deleteAssetLocalIdentifiers(account: account.account) {
-                        self.startTimer()
+                    // verify delete Asset Local Identifiers in auto upload (DELETE Photos album)
+                    if applicationState == .active && metadatas.isEmpty && !self.appDelegate.isPasscodePresented() {
+                        self.deleteAssetLocalIdentifiers {
+                            self.pauseProcess = false
+                        }
+                    } else {
+                        self.pauseProcess = false
                     }
-                } else if applicationState == .active {
-                    self.startTimer()
+                } else {
+                    self.pauseProcess = false
                 }
+
                 completition(counterUpload)
             })
         }
     }
 
-    private func deleteAssetLocalIdentifiers(account: String, completition: @escaping () -> Void) {
+    private func deleteAssetLocalIdentifiers(completition: @escaping () -> Void) {
 
-        DispatchQueue.main.async {
-            let metadatasSessionUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND session CONTAINS[cd] %@", account, "upload"))
-            if !metadatasSessionUpload.isEmpty {
-                completition()
-                return
-            }
-            let localIdentifiers = NCManageDatabase.shared.getAssetLocalIdentifiersUploaded(account: account)
-            if localIdentifiers.isEmpty {
-                completition()
-                return
-            }
-            let assets = PHAsset.fetchAssets(withLocalIdentifiers: localIdentifiers, options: nil)
-
-            PHPhotoLibrary.shared().performChanges({
-                PHAssetChangeRequest.deleteAssets(assets as NSFastEnumeration)
-            }, completionHandler: { _, _ in
-                DispatchQueue.main.async {
-                    NCManageDatabase.shared.clearAssetLocalIdentifiers(localIdentifiers, account: account)
-                    completition()
-                }
-            })
-        }
+        let metadatasSessionUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND session CONTAINS[cd] %@", appDelegate.account, "upload"))
+        if !metadatasSessionUpload.isEmpty { return completition() }
+
+        let localIdentifiers = NCManageDatabase.shared.getAssetLocalIdentifiersUploaded(account: appDelegate.account)
+        if localIdentifiers.isEmpty { return completition() }
+
+        let assets = PHAsset.fetchAssets(withLocalIdentifiers: localIdentifiers, options: nil)
+
+        PHPhotoLibrary.shared().performChanges({
+            PHAssetChangeRequest.deleteAssets(assets as NSFastEnumeration)
+        }, completionHandler: { _, _ in
+            NCManageDatabase.shared.clearAssetLocalIdentifiers(localIdentifiers, account: self.appDelegate.account)
+            completition()
+        })
     }
 
     // MARK: -

+ 6 - 4
iOSClient/RichWorkspace/NCViewerRichWorkspaceWebView.swift

@@ -103,10 +103,12 @@ class NCViewerRichWorkspaceWebView: UIViewController, WKNavigationDelegate, WKSc
     // MARK: -
 
     public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
-        if let serverTrust = challenge.protectionSpace.serverTrust {
-            completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
-        } else {
-            completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
+        DispatchQueue.global().async {
+            if let serverTrust = challenge.protectionSpace.serverTrust {
+                completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
+            } else {
+                completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
+            }
         }
     }
 

+ 6 - 4
iOSClient/Viewer/NCViewerNextcloudText/NCViewerNextcloudText.swift

@@ -178,10 +178,12 @@ class NCViewerNextcloudText: UIViewController, WKNavigationDelegate, WKScriptMes
     // MARK: -
 
     public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
-        if let serverTrust = challenge.protectionSpace.serverTrust {
-            completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
-        } else {
-            completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
+        DispatchQueue.global().async {
+            if let serverTrust = challenge.protectionSpace.serverTrust {
+                completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
+            } else {
+                completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
+            }
         }
     }
 

+ 6 - 4
iOSClient/Viewer/NCViewerRichdocument/NCViewerRichdocument.swift

@@ -316,10 +316,12 @@ class NCViewerRichdocument: UIViewController, WKNavigationDelegate, WKScriptMess
     // MARK: -
 
     public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
-        if let serverTrust = challenge.protectionSpace.serverTrust {
-            completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
-        } else {
-            completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
+        DispatchQueue.global().async {
+            if let serverTrust = challenge.protectionSpace.serverTrust {
+                completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
+            } else {
+                completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
+            }
         }
     }