NCNetworking.swift 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  1. //
  2. // NCNetworking.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 23/10/19.
  6. // Copyright © 2019 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. import OpenSSL
  25. import NextcloudKit
  26. import Alamofire
  27. import Photos
  28. @objc public protocol NCNetworkingDelegate {
  29. @objc optional func downloadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask)
  30. @objc optional func uploadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask)
  31. @objc optional func downloadComplete(fileName: String, serverUrl: String, etag: String?, date: NSDate?, dateLastModified: NSDate?, length: Int64, description: String?, task: URLSessionTask, error: NKError)
  32. @objc optional func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, error: NKError)
  33. }
  34. @objc class NCNetworking: NSObject, NKCommonDelegate {
  35. @objc public static let shared: NCNetworking = {
  36. let instance = NCNetworking()
  37. return instance
  38. }()
  39. weak var delegate: NCNetworkingDelegate?
  40. var lastReachability: Bool = true
  41. var networkReachability: NKCommon.typeReachability?
  42. let downloadRequest = ThreadSafeDictionary<String,DownloadRequest>()
  43. let uploadRequest = ThreadSafeDictionary<String,UploadRequest>()
  44. let uploadMetadataInBackground = ThreadSafeDictionary<String,tableMetadata>()
  45. @objc public let sessionMaximumConnectionsPerHost = 5
  46. @objc public let sessionIdentifierBackground: String = "com.nextcloud.session.upload.background"
  47. @objc public let sessionIdentifierBackgroundWWan: String = "com.nextcloud.session.upload.backgroundWWan"
  48. @objc public let sessionIdentifierBackgroundExtension: String = "com.nextcloud.session.upload.extension"
  49. @objc public lazy var sessionManagerBackground: URLSession = {
  50. let configuration = URLSessionConfiguration.background(withIdentifier: sessionIdentifierBackground)
  51. configuration.allowsCellularAccess = true
  52. configuration.sessionSendsLaunchEvents = true
  53. configuration.isDiscretionary = false
  54. configuration.httpMaximumConnectionsPerHost = sessionMaximumConnectionsPerHost
  55. configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
  56. let session = URLSession(configuration: configuration, delegate: NKBackground.shared, delegateQueue: OperationQueue.main)
  57. return session
  58. }()
  59. @objc public lazy var sessionManagerBackgroundWWan: URLSession = {
  60. let configuration = URLSessionConfiguration.background(withIdentifier: sessionIdentifierBackgroundWWan)
  61. configuration.allowsCellularAccess = false
  62. configuration.sessionSendsLaunchEvents = true
  63. configuration.isDiscretionary = false
  64. configuration.httpMaximumConnectionsPerHost = sessionMaximumConnectionsPerHost
  65. configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
  66. let session = URLSession(configuration: configuration, delegate: NKBackground.shared, delegateQueue: OperationQueue.main)
  67. return session
  68. }()
  69. #if EXTENSION
  70. @objc public lazy var sessionManagerBackgroundExtension: URLSession = {
  71. let configuration = URLSessionConfiguration.background(withIdentifier: sessionIdentifierBackgroundExtension)
  72. configuration.allowsCellularAccess = true
  73. configuration.sessionSendsLaunchEvents = true
  74. configuration.isDiscretionary = false
  75. configuration.httpMaximumConnectionsPerHost = sessionMaximumConnectionsPerHost
  76. configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
  77. configuration.sharedContainerIdentifier = NCBrandOptions.shared.capabilitiesGroups
  78. let session = URLSession(configuration: configuration, delegate: NKBackground.shared, delegateQueue: OperationQueue.main)
  79. return session
  80. }()
  81. #endif
  82. // REQUESTS
  83. var requestsUnifiedSearch: [DataRequest] = []
  84. // MARK: - init
  85. override init() {
  86. super.init()
  87. #if EXTENSION
  88. _ = sessionIdentifierBackgroundExtension
  89. #else
  90. _ = sessionManagerBackground
  91. _ = sessionManagerBackgroundWWan
  92. #endif
  93. }
  94. // MARK: - Communication Delegate
  95. func networkReachabilityObserver(_ typeReachability: NKCommon.typeReachability) {
  96. #if !EXTENSION
  97. if typeReachability == NKCommon.typeReachability.reachableCellular || typeReachability == NKCommon.typeReachability.reachableEthernetOrWiFi {
  98. if !lastReachability {
  99. NCService.shared.startRequestServicesServer()
  100. }
  101. lastReachability = true
  102. } else {
  103. if lastReachability {
  104. let error = NKError(errorCode: NCGlobal.shared.errorNetworkNotAvailable, errorDescription: "")
  105. NCContentPresenter.shared.messageNotification("_network_not_available_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info)
  106. }
  107. lastReachability = false
  108. }
  109. networkReachability = typeReachability
  110. #endif
  111. }
  112. func authenticationChallenge(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  113. DispatchQueue.global().async {
  114. self.checkTrustedChallenge(session, didReceive: challenge, completionHandler: completionHandler)
  115. }
  116. }
  117. func downloadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  118. delegate?.downloadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  119. }
  120. func downloadComplete(fileName: String, serverUrl: String, etag: String?, date: NSDate?, dateLastModified: NSDate?, length: Int64, description: String?, task: URLSessionTask, error: NKError) {
  121. delegate?.downloadComplete?(fileName: fileName, serverUrl: serverUrl, etag: etag, date: date, dateLastModified: dateLastModified, length: length, description: description, task: task, error: error)
  122. }
  123. func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
  124. #if !EXTENSION
  125. if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let completionHandler = appDelegate.backgroundSessionCompletionHandler {
  126. NKCommon.shared.writeLog("[INFO] Called urlSessionDidFinishEvents for Background URLSession")
  127. appDelegate.backgroundSessionCompletionHandler = nil
  128. completionHandler()
  129. }
  130. #endif
  131. }
  132. // MARK: - Pinning check
  133. private func checkTrustedChallenge(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  134. let protectionSpace: URLProtectionSpace = challenge.protectionSpace
  135. let directoryCertificate = CCUtility.getDirectoryCerificates()!
  136. let host = challenge.protectionSpace.host
  137. let certificateSavedPath = directoryCertificate + "/" + host + ".der"
  138. var isTrusted: Bool
  139. if let serverTrust: SecTrust = protectionSpace.serverTrust, let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
  140. // extarct certificate txt
  141. saveX509Certificate(certificate, host: host, directoryCertificate: directoryCertificate)
  142. let isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil)
  143. let certificateCopyData = SecCertificateCopyData(certificate)
  144. let data = CFDataGetBytePtr(certificateCopyData);
  145. let size = CFDataGetLength(certificateCopyData);
  146. let certificateData = NSData(bytes: data, length: size)
  147. certificateData.write(toFile: directoryCertificate + "/" + host + ".tmp", atomically: true)
  148. if isServerTrusted {
  149. isTrusted = true
  150. } else if let certificateDataSaved = NSData(contentsOfFile: certificateSavedPath), certificateData.isEqual(to: certificateDataSaved as Data) {
  151. isTrusted = true
  152. } else {
  153. isTrusted = false
  154. }
  155. } else {
  156. isTrusted = false
  157. }
  158. if isTrusted {
  159. completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
  160. } else {
  161. #if !EXTENSION
  162. DispatchQueue.main.async { (UIApplication.shared.delegate as? AppDelegate)?.trustCertificateError(host: host) }
  163. #endif
  164. completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
  165. }
  166. }
  167. func writeCertificate(host: String) {
  168. let directoryCertificate = CCUtility.getDirectoryCerificates()!
  169. let certificateAtPath = directoryCertificate + "/" + host + ".tmp"
  170. let certificateToPath = directoryCertificate + "/" + host + ".der"
  171. if !NCUtilityFileSystem.shared.copyFile(atPath: certificateAtPath, toPath: certificateToPath) {
  172. NKCommon.shared.writeLog("[ERROR] Write certificare error")
  173. }
  174. }
  175. private func saveX509Certificate(_ certificate: SecCertificate, host: String, directoryCertificate: String) {
  176. let certNamePathTXT = directoryCertificate + "/" + host + ".txt"
  177. let data: CFData = SecCertificateCopyData(certificate)
  178. let mem = BIO_new_mem_buf(CFDataGetBytePtr(data), Int32(CFDataGetLength(data)))
  179. let x509cert = d2i_X509_bio(mem, nil)
  180. if x509cert == nil {
  181. NKCommon.shared.writeLog("[ERROR] OpenSSL couldn't parse X509 Certificate")
  182. } else {
  183. // save details
  184. if FileManager.default.fileExists(atPath: certNamePathTXT) {
  185. do {
  186. try FileManager.default.removeItem(atPath: certNamePathTXT)
  187. } catch { }
  188. }
  189. let fileCertInfo = fopen(certNamePathTXT, "w")
  190. if fileCertInfo != nil {
  191. let output = BIO_new_fp(fileCertInfo, BIO_NOCLOSE)
  192. X509_print_ex(output, x509cert, UInt(XN_FLAG_COMPAT), UInt(X509_FLAG_COMPAT))
  193. BIO_free(output)
  194. }
  195. fclose(fileCertInfo)
  196. X509_free(x509cert)
  197. }
  198. BIO_free(mem)
  199. }
  200. func checkPushNotificationServerProxyCertificateUntrusted(viewController: UIViewController?, completion: @escaping (_ error: NKError) -> Void) {
  201. guard let host = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host else { return }
  202. NextcloudKit.shared.checkServer(serverUrl: NCBrandOptions.shared.pushNotificationServerProxy) { error in
  203. guard error == .success else {
  204. completion(.success)
  205. return
  206. }
  207. if error == .success {
  208. NCNetworking.shared.writeCertificate(host: host)
  209. completion(error)
  210. } else if error.errorCode == NSURLErrorServerCertificateUntrusted {
  211. let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
  212. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
  213. NCNetworking.shared.writeCertificate(host: host)
  214. completion(.success)
  215. }))
  216. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in
  217. completion(error)
  218. }))
  219. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
  220. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  221. let vcCertificateDetails = navigationController.topViewController as! NCViewCertificateDetails
  222. vcCertificateDetails.host = host
  223. viewController?.present(navigationController, animated: true)
  224. }
  225. }))
  226. viewController?.present(alertController, animated: true)
  227. }
  228. }
  229. }
  230. // MARK: - Utility
  231. func cancelTaskWithUrl(_ url: URL) {
  232. NextcloudKit.shared.getSessionManager().getAllTasks { tasks in
  233. tasks.filter { $0.state == .running }.filter { $0.originalRequest?.url == url }.first?.cancel()
  234. }
  235. }
  236. @objc func cancelAllTask() {
  237. NextcloudKit.shared.getSessionManager().getAllTasks { tasks in
  238. for task in tasks {
  239. task.cancel()
  240. }
  241. }
  242. }
  243. func isInTaskUploadBackground(fileName: String, completion: @escaping (_ exists: Bool) -> Void) {
  244. let sessions: [URLSession] = [NCNetworking.shared.sessionManagerBackground, NCNetworking.shared.sessionManagerBackgroundWWan]
  245. for session in sessions {
  246. session.getAllTasks(completionHandler: { tasks in
  247. for task in tasks {
  248. let url = task.originalRequest?.url
  249. let urlFileName = url?.lastPathComponent
  250. if urlFileName == fileName {
  251. completion(true)
  252. }
  253. }
  254. if session == sessions.last {
  255. completion(false)
  256. }
  257. })
  258. }
  259. }
  260. // MARK: - Download
  261. @objc func cancelDownload(ocId: String, serverUrl: String, fileNameView: String) {
  262. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView) else { return }
  263. if let request = downloadRequest[fileNameLocalPath] {
  264. request.cancel()
  265. } else if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  266. NCManageDatabase.shared.setMetadataSession(ocId: ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  267. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  268. }
  269. }
  270. func download(metadata: tableMetadata, selector: String, notificationCenterProgressTask: Bool = true, progressHandler: @escaping (_ progress: Progress) -> Void = { _ in }, completion: @escaping (_ afError: AFError?, _ error: NKError) -> Void) {
  271. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  272. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
  273. if NCManageDatabase.shared.getMetadataFromOcId(metadata.ocId) == nil {
  274. NCManageDatabase.shared.addMetadata(tableMetadata.init(value: metadata))
  275. }
  276. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading { return }
  277. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: NKCommon.shared.sessionIdentifierDownload, sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusInDownload)
  278. NextcloudKit.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, queue: NKCommon.shared.backgroundQueue, requestHandler: { request in
  279. self.downloadRequest[fileNameLocalPath] = request
  280. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusDownloading)
  281. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadStartFile, userInfo: ["ocId":metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  282. }, taskHandler: { (_) in
  283. }, progressHandler: { (progress) in
  284. if notificationCenterProgressTask {
  285. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterProgressTask, object: nil, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "fileName":metadata.fileName, "serverUrl":metadata.serverUrl, "status":NSNumber(value: NCGlobal.shared.metadataStatusInDownload), "progress":NSNumber(value: progress.fractionCompleted), "totalBytes":NSNumber(value: progress.totalUnitCount), "totalBytesExpected":NSNumber(value: progress.completedUnitCount)])
  286. }
  287. progressHandler(progress)
  288. }) { (account, etag, date, _, allHeaderFields, afError, error) in
  289. self.downloadRequest.removeValue(forKey:fileNameLocalPath)
  290. if afError?.isExplicitlyCancelledError ?? false {
  291. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  292. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  293. } else if error == .success {
  294. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal, etag: etag)
  295. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  296. #if !EXTENSION
  297. if let result = NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "fileNameIdentifier == %@ AND serverUrl == %@", metadata.fileName, metadata.serverUrl)) {
  298. NCEndToEndEncryption.sharedManager()?.decryptFileName(metadata.fileName, fileNameView: metadata.fileNameView, ocId: metadata.ocId, key: result.key, initializationVector: result.initializationVector, authenticationTag: result.authenticationTag)
  299. }
  300. CCUtility.setExif(metadata) { _, _, _, _, _ in }
  301. #endif
  302. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "selector": selector, "error": error])
  303. } else {
  304. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: error.errorDescription, sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusDownloadError)
  305. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "selector": selector, "error": error])
  306. }
  307. DispatchQueue.main.async { completion(afError, error) }
  308. }
  309. }
  310. // MARK: - Upload
  311. @objc func upload(metadata: tableMetadata,
  312. start: @escaping () -> () = { },
  313. completion: @escaping (_ error: NKError) -> () = { error in }) {
  314. let metadata = tableMetadata.init(value: metadata)
  315. NKCommon.shared.writeLog("[INFO] Upload file \(metadata.fileNameView) with Identifier \(metadata.assetLocalIdentifier) with size \(metadata.size) [CHUNCK \(metadata.chunk), E2EE \(metadata.e2eEncrypted)]")
  316. if metadata.e2eEncrypted {
  317. #if !EXTENSION_FILE_PROVIDER_EXTENSION && !EXTENSION_WIDGET
  318. NCNetworkingE2EE.shared.upload(metadata: metadata, start: start) { error in
  319. completion(error)
  320. }
  321. #endif
  322. } else if metadata.chunk {
  323. uploadChunkedFile(metadata: metadata, start: start) { error in
  324. completion(error)
  325. }
  326. } else if metadata.session == NKCommon.shared.sessionIdentifierUpload {
  327. uploadFile(metadata: metadata, start: start) { error in
  328. completion(error)
  329. }
  330. } else {
  331. uploadFileInBackground(metadata: metadata, start: start) { error in
  332. completion(error)
  333. }
  334. }
  335. }
  336. private func uploadFile(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ error: NKError) -> Void) {
  337. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  338. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  339. var uploadTask: URLSessionTask?
  340. let description = metadata.ocId
  341. NextcloudKit.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.creationDate as Date, dateModificationFile: metadata.date as Date, customUserAgent: nil, addCustomHeaders: nil, requestHandler: { request in
  342. self.uploadRequest[fileNameLocalPath] = request
  343. }, taskHandler: { task in
  344. uploadTask = task
  345. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  346. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "fileName": metadata.fileName, "sessionSelector": metadata.sessionSelector])
  347. start()
  348. }, progressHandler: { progress in
  349. NotificationCenter.default.postOnMainThread(
  350. name: NCGlobal.shared.notificationCenterProgressTask,
  351. userInfo: [
  352. "account": metadata.account,
  353. "ocId": metadata.ocId,
  354. "fileName": metadata.fileName,
  355. "serverUrl": metadata.serverUrl,
  356. "status": NSNumber(value: NCGlobal.shared.metadataStatusInUpload),
  357. "progress": NSNumber(value: progress.fractionCompleted),
  358. "totalBytes": NSNumber(value: progress.totalUnitCount),
  359. "totalBytesExpected": NSNumber(value: progress.completedUnitCount)])
  360. }) { _, ocId, etag, date, size, _, _, error in
  361. self.uploadRequest.removeValue(forKey: fileNameLocalPath)
  362. if let uploadTask = uploadTask {
  363. self.uploadComplete(fileName: metadata.fileName, serverUrl: metadata.serverUrl, ocId: ocId, etag: etag, date: date, size: size, description: description, task: uploadTask, error: error)
  364. }
  365. completion(error)
  366. }
  367. }
  368. private func uploadFileInBackground(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ error: NKError) -> Void) {
  369. var session: URLSession?
  370. let metadata = tableMetadata.init(value: metadata)
  371. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  372. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  373. if metadata.session == sessionIdentifierBackground || metadata.session == sessionIdentifierBackgroundExtension {
  374. session = sessionManagerBackground
  375. } else if metadata.session == sessionIdentifierBackgroundWWan {
  376. session = sessionManagerBackgroundWWan
  377. }
  378. start()
  379. // Check file dim > 0
  380. if NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath) == 0 && metadata.size != 0 {
  381. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  382. completion(NKError(errorCode: NCGlobal.shared.errorResourceNotFound, errorDescription: NSLocalizedString("_error_not_found_", value: "The requested resource could not be found", comment: "")))
  383. } else {
  384. if let task = NKBackground.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.creationDate as Date, dateModificationFile: metadata.date as Date, description: metadata.ocId, session: session!) {
  385. NKCommon.shared.writeLog("[INFO] Upload file \(metadata.fileNameView) with task with taskIdentifier \(task.taskIdentifier)")
  386. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  387. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "fileName": metadata.fileName, "sessionSelector": metadata.sessionSelector])
  388. completion(NKError())
  389. } else {
  390. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  391. completion(NKError(errorCode: NCGlobal.shared.errorResourceNotFound, errorDescription: "task null"))
  392. }
  393. }
  394. }
  395. func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, error: NKError) {
  396. DispatchQueue.global().async {
  397. guard self.delegate == nil, let metadata = NCManageDatabase.shared.getMetadataFromOcId(description) else {
  398. self.delegate?.uploadComplete?(fileName: fileName, serverUrl: serverUrl, ocId: ocId, etag: etag, date: date, size: size, description: description, task: task, error: error)
  399. return
  400. }
  401. let ocIdTemp = metadata.ocId
  402. let selector = metadata.sessionSelector
  403. if error == .success, let ocId = ocId, size == metadata.size {
  404. let metadata = tableMetadata.init(value: metadata)
  405. metadata.uploadDate = date ?? NSDate()
  406. metadata.etag = etag ?? ""
  407. metadata.ocId = ocId
  408. if let fileId = NCUtility.shared.ocIdToFileId(ocId: ocId) {
  409. metadata.fileId = fileId
  410. }
  411. metadata.session = ""
  412. metadata.sessionError = ""
  413. metadata.sessionTaskIdentifier = 0
  414. metadata.status = NCGlobal.shared.metadataStatusNormal
  415. // Delete Asset on Photos album
  416. if CCUtility.getRemovePhotoCameraRoll() && !metadata.assetLocalIdentifier.isEmpty {
  417. metadata.deleteAssetLocalIdentifier = true
  418. }
  419. NCManageDatabase.shared.addMetadata(metadata)
  420. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  421. if selector == NCGlobal.shared.selectorUploadFileNODelete {
  422. NCUtilityFileSystem.shared.moveFile(atPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
  423. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  424. } else {
  425. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp))
  426. }
  427. NKCommon.shared.writeLog("[SUCCESS] Upload complete " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)")
  428. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "fileName": metadata.fileName, "ocIdTemp": ocIdTemp, "error": error])
  429. } else {
  430. if error.errorCode == NSURLErrorCancelled || error.errorCode == NCGlobal.shared.errorRequestExplicityCancelled {
  431. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  432. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  433. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  434. } else {
  435. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: error.errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  436. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "fileName": metadata.fileName, "ocIdTemp": ocIdTemp, "error": error])
  437. }
  438. }
  439. // Update Badge
  440. 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))
  441. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUpdateBadgeNumber, userInfo: ["counter":counterBadge.count])
  442. self.uploadMetadataInBackground.removeValue(forKey: fileName + serverUrl)
  443. self.delegate?.uploadComplete?(fileName: fileName, serverUrl: serverUrl, ocId: ocId, etag: etag, date: date, size: size, description: description, task: task, error: error)
  444. }
  445. }
  446. func uploadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  447. DispatchQueue.global().async {
  448. self.delegate?.uploadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  449. var metadata: tableMetadata?
  450. let description: String = task.taskDescription ?? ""
  451. if let metadataTmp = self.uploadMetadataInBackground[fileName+serverUrl] {
  452. metadata = metadataTmp
  453. } else if let metadataTmp = NCManageDatabase.shared.getMetadataFromOcId(description) {
  454. self.uploadMetadataInBackground[fileName+serverUrl] = metadataTmp
  455. metadata = metadataTmp
  456. }
  457. if let metadata = metadata {
  458. NotificationCenter.default.postOnMainThread(
  459. name: NCGlobal.shared.notificationCenterProgressTask,
  460. userInfo: [
  461. "account": metadata.account,
  462. "ocId": metadata.ocId,
  463. "fileName": metadata.fileName,
  464. "serverUrl": serverUrl,
  465. "status": NSNumber(value: NCGlobal.shared.metadataStatusInUpload),
  466. "progress": NSNumber(value: progress),
  467. "totalBytes": NSNumber(value: totalBytes),
  468. "totalBytesExpected": NSNumber(value: totalBytesExpected)])
  469. }
  470. }
  471. }
  472. func getOcIdInBackgroundSession(queue: DispatchQueue = .main, completion: @escaping (_ listOcId: [String]) -> Void) {
  473. var listOcId: [String] = []
  474. sessionManagerBackground.getAllTasks(completionHandler: { tasks in
  475. for task in tasks {
  476. listOcId.append(task.description)
  477. }
  478. self.sessionManagerBackgroundWWan.getAllTasks(completionHandler: { tasks in
  479. for task in tasks {
  480. listOcId.append(task.description)
  481. }
  482. queue.async { completion(listOcId) }
  483. })
  484. })
  485. }
  486. // MARK: - Transfer (Download Upload)
  487. @objc func cancelTransferMetadata(_ metadata: tableMetadata, completion: @escaping () -> Void) {
  488. let metadata = tableMetadata.init(value: metadata)
  489. if metadata.session.count == 0 {
  490. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  491. return completion()
  492. }
  493. if metadata.session == NKCommon.shared.sessionIdentifierDownload {
  494. NCNetworking.shared.cancelDownload(ocId: metadata.ocId, serverUrl: metadata.serverUrl, fileNameView: metadata.fileNameView)
  495. return completion()
  496. }
  497. if metadata.session == NKCommon.shared.sessionIdentifierUpload || metadata.chunk {
  498. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else { return }
  499. if let request = uploadRequest[fileNameLocalPath] {
  500. request.cancel()
  501. } else {
  502. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  503. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  504. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  505. }
  506. return completion()
  507. }
  508. var session: URLSession?
  509. if metadata.session == NCNetworking.shared.sessionIdentifierBackground {
  510. session = NCNetworking.shared.sessionManagerBackground
  511. } else if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundWWan {
  512. session = NCNetworking.shared.sessionManagerBackgroundWWan
  513. }
  514. if session == nil {
  515. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  516. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  517. return completion()
  518. }
  519. session?.getTasksWithCompletionHandler { _, uploadTasks, _ in
  520. var cancel = false
  521. if metadata.session.count > 0 && metadata.session.contains("upload") {
  522. for task in uploadTasks {
  523. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  524. task.cancel()
  525. cancel = true
  526. }
  527. }
  528. if cancel == false {
  529. do {
  530. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  531. } catch { }
  532. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  533. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  534. }
  535. }
  536. completion()
  537. }
  538. }
  539. @objc func cancelAllTransfer(account: String, completion: @escaping () -> Void) {
  540. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", account, NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusUploadError))
  541. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status != %d", NCGlobal.shared.metadataStatusNormal))
  542. var counter = 0
  543. for metadata in metadatas {
  544. counter += 1
  545. if metadata.status == NCGlobal.shared.metadataStatusWaitDownload || metadata.status == NCGlobal.shared.metadataStatusDownloadError {
  546. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  547. }
  548. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  549. self.cancelTransferMetadata(metadata) {
  550. if counter == metadatas.count {
  551. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  552. completion()
  553. }
  554. }
  555. }
  556. }
  557. }
  558. #if !EXTENSION
  559. NCOperationQueue.shared.downloadCancelAll()
  560. #endif
  561. }
  562. func cancelAllDownloadTransfer() {
  563. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status != %d", NCGlobal.shared.metadataStatusNormal))
  564. for metadata in metadatas {
  565. if metadata.status == NCGlobal.shared.metadataStatusWaitDownload || metadata.status == NCGlobal.shared.metadataStatusDownloadError {
  566. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  567. }
  568. if metadata.status == NCGlobal.shared.metadataStatusDownloading && metadata.session == NKCommon.shared.sessionIdentifierDownload {
  569. cancelDownload(ocId: metadata.ocId, serverUrl: metadata.serverUrl, fileNameView: metadata.fileNameView)
  570. }
  571. }
  572. #if !EXTENSION
  573. NCOperationQueue.shared.downloadCancelAll()
  574. #endif
  575. }
  576. // MARK: - WebDav Read file, folder
  577. @objc func readFolder(serverUrl: String, account: String, completion: @escaping (_ account: String, _ metadataFolder: tableMetadata?, _ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ metadatasLocalUpdate: [tableMetadata]?, _ metadatasDelete: [tableMetadata]?, _ error: NKError) -> Void) {
  578. let options = NKRequestOptions(queue: NKCommon.shared.backgroundQueue)
  579. NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles(), options: options) { account, files, _, error in
  580. guard error == .success else {
  581. completion(account, nil, nil, nil, nil, nil, error)
  582. return
  583. }
  584. NCManageDatabase.shared.convertNKFilesToMetadatas(files, useMetadataFolder: true, account: account) { metadataFolder, metadatasFolder, metadatas in
  585. // Add metadata folder
  586. NCManageDatabase.shared.addMetadata(tableMetadata.init(value: metadataFolder))
  587. // Update directory
  588. NCManageDatabase.shared.addDirectory(encrypted: metadataFolder.e2eEncrypted, favorite: metadataFolder.favorite, ocId: metadataFolder.ocId, fileId: metadataFolder.fileId, etag: metadataFolder.etag, permissions: metadataFolder.permissions, serverUrl: serverUrl, account: metadataFolder.account)
  589. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, richWorkspace: metadataFolder.richWorkspace, account: metadataFolder.account)
  590. // Update sub directories NO Update richWorkspace
  591. for metadata in metadatasFolder {
  592. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  593. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: serverUrl, account: account)
  594. }
  595. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, NCGlobal.shared.metadataStatusNormal))
  596. let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareEtagLocal: true)
  597. completion(account, metadataFolder, metadatas, metadatasChanged.metadatasUpdate, metadatasChanged.metadatasLocalUpdate, metadatasChanged.metadatasDelete, error)
  598. }
  599. }
  600. }
  601. @objc func readFile(serverUrlFileName: String, showHiddenFiles: Bool = CCUtility.getShowHiddenFiles(), queue: DispatchQueue = NKCommon.shared.backgroundQueue, completion: @escaping (_ account: String, _ metadata: tableMetadata?, _ error: NKError) -> Void) {
  602. let options = NKRequestOptions(queue: queue)
  603. NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: showHiddenFiles, options: options) { account, files, _, error in
  604. guard error == .success, files.count == 1, let file = files.first else {
  605. completion(account, nil, error)
  606. return
  607. }
  608. let isEncrypted = CCUtility.isFolderEncrypted(file.serverUrl, e2eEncrypted: file.e2eEncrypted, account: account, urlBase: file.urlBase, userId: file.userId)
  609. let metadata = NCManageDatabase.shared.convertNCFileToMetadata(file, isEncrypted: isEncrypted, account: account)
  610. completion(account, metadata, error)
  611. }
  612. }
  613. //MARK: - Search
  614. /// WebDAV search
  615. @objc func searchFiles(urlBase: NCUserBaseUrl, literal: String, completion: @escaping (_ metadatas: [tableMetadata]?, _ error: NKError) -> ()) {
  616. let options = NKRequestOptions(queue: NKCommon.shared.backgroundQueue)
  617. NextcloudKit.shared.searchLiteral(serverUrl: urlBase.urlBase, depth: "infinity", literal: literal, showHiddenFiles: CCUtility.getShowHiddenFiles(), options: options) { (account, files, data, error) in
  618. guard error == .success else {
  619. return completion(nil, error)
  620. }
  621. NCManageDatabase.shared.convertNKFilesToMetadatas(files, useMetadataFolder: false, account: account) { _, metadatasFolder, metadatas in
  622. // Update sub directories
  623. for folder in metadatasFolder {
  624. let serverUrl = folder.serverUrl + "/" + folder.fileName
  625. NCManageDatabase.shared.addDirectory(encrypted: folder.e2eEncrypted, favorite: folder.favorite, ocId: folder.ocId, fileId: folder.fileId, etag: nil, permissions: folder.permissions, serverUrl: serverUrl, account: account)
  626. }
  627. NCManageDatabase.shared.addMetadatas(metadatas)
  628. let metadatas = Array(metadatas.map(tableMetadata.init))
  629. completion(metadatas, error)
  630. }
  631. }
  632. }
  633. /// Unified Search (NC>=20)
  634. ///
  635. func unifiedSearchFiles(userBaseUrl: NCUserBaseUrl, literal: String, providers: @escaping (_ accout: String, _ searchProviders: [NKSearchProvider]?) -> Void, update: @escaping (_ account: String, _ id: String, NKSearchResult?, [tableMetadata]?) -> Void, completion: @escaping (_ account: String, _ error: NKError) -> ()) {
  636. let dispatchGroup = DispatchGroup()
  637. dispatchGroup.enter()
  638. dispatchGroup.notify(queue: .main) {
  639. completion(userBaseUrl.account, NKError())
  640. }
  641. NextcloudKit.shared.unifiedSearch(term: literal, timeout: 30, timeoutProvider: 90) { provider in
  642. // example filter
  643. // ["calendar", "files", "fulltextsearch"].contains(provider.id)
  644. return true
  645. } request: { request in
  646. if let request = request {
  647. self.requestsUnifiedSearch.append(request)
  648. }
  649. } providers: { account, searchProviders in
  650. providers(account, searchProviders)
  651. } update: { account, partialResult, provider, error in
  652. guard let partialResult = partialResult else { return }
  653. var metadatas: [tableMetadata] = []
  654. switch provider.id {
  655. case "files":
  656. partialResult.entries.forEach({ entry in
  657. if let fileId = entry.fileId,
  658. let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ && fileId == %@", userBaseUrl.userAccount, String(fileId))) {
  659. metadatas.append(metadata)
  660. } else if let filePath = entry.filePath {
  661. let semaphore = DispatchSemaphore(value: 0)
  662. self.loadMetadata(userBaseUrl: userBaseUrl, filePath: filePath, dispatchGroup: dispatchGroup) { account, metadata, error in
  663. metadatas.append(metadata)
  664. semaphore.signal()
  665. }
  666. semaphore.wait()
  667. } else { print(#function, "[ERROR]: File search entry has no path: \(entry)") }
  668. })
  669. break
  670. case "fulltextsearch":
  671. // NOTE: FTS could also return attributes like files
  672. // https://github.com/nextcloud/files_fulltextsearch/issues/143
  673. partialResult.entries.forEach({ entry in
  674. let url = URLComponents(string: entry.resourceURL)
  675. guard let dir = url?.queryItems?["dir"]?.value, let filename = url?.queryItems?["scrollto"]?.value else { return }
  676. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(
  677. format: "account == %@ && path == %@ && fileName == %@",
  678. userBaseUrl.userAccount,
  679. "/remote.php/dav/files/" + userBaseUrl.user + dir,
  680. filename)) {
  681. metadatas.append(metadata)
  682. } else {
  683. let semaphore = DispatchSemaphore(value: 0)
  684. self.loadMetadata(userBaseUrl: userBaseUrl, filePath: dir + filename, dispatchGroup: dispatchGroup) { account, metadata, error in
  685. metadatas.append(metadata)
  686. semaphore.signal()
  687. }
  688. semaphore.wait()
  689. }
  690. })
  691. default:
  692. partialResult.entries.forEach({ entry in
  693. let metadata = NCManageDatabase.shared.createMetadata(account: userBaseUrl.account, user: userBaseUrl.user, userId: userBaseUrl.userId, fileName: entry.title, fileNameView: entry.title, ocId: NSUUID().uuidString, serverUrl: userBaseUrl.urlBase, urlBase: userBaseUrl.urlBase, url: entry.resourceURL, contentType: "", isUrl: true, name: partialResult.id, subline: entry.subline, iconName: entry.icon, iconUrl: entry.thumbnailURL)
  694. metadatas.append(metadata)
  695. })
  696. }
  697. update(account, provider.id, partialResult, metadatas)
  698. } completion: { account, data, error in
  699. self.requestsUnifiedSearch.removeAll()
  700. dispatchGroup.leave()
  701. }
  702. }
  703. func unifiedSearchFilesProvider(userBaseUrl: NCUserBaseUrl, id: String, term: String, limit: Int, cursor: Int, completion: @escaping (_ account: String, _ searchResult: NKSearchResult?, _ metadatas: [tableMetadata]?, _ error: NKError) -> ()) {
  704. var metadatas: [tableMetadata] = []
  705. let request = NextcloudKit.shared.searchProvider(id, account: userBaseUrl.account, term: term, limit: limit, cursor: cursor, timeout: 60) { account, searchResult, data, error in
  706. guard let searchResult = searchResult else {
  707. completion(account, nil, metadatas, error)
  708. return
  709. }
  710. switch id {
  711. case "files":
  712. searchResult.entries.forEach({ entry in
  713. if let fileId = entry.fileId, let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ && fileId == %@", userBaseUrl.userAccount, String(fileId))) {
  714. metadatas.append(metadata)
  715. } else if let filePath = entry.filePath {
  716. let semaphore = DispatchSemaphore(value: 0)
  717. self.loadMetadata(userBaseUrl: userBaseUrl, filePath: filePath, dispatchGroup: nil) { account, metadata, error in
  718. metadatas.append(metadata)
  719. semaphore.signal()
  720. }
  721. semaphore.wait()
  722. } else { print(#function, "[ERROR]: File search entry has no path: \(entry)") }
  723. })
  724. break
  725. case "fulltextsearch":
  726. // NOTE: FTS could also return attributes like files
  727. // https://github.com/nextcloud/files_fulltextsearch/issues/143
  728. searchResult.entries.forEach({ entry in
  729. let url = URLComponents(string: entry.resourceURL)
  730. guard let dir = url?.queryItems?["dir"]?.value, let filename = url?.queryItems?["scrollto"]?.value else { return }
  731. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ && path == %@ && fileName == %@", userBaseUrl.userAccount, "/remote.php/dav/files/" + userBaseUrl.user + dir, filename)) {
  732. metadatas.append(metadata)
  733. } else {
  734. let semaphore = DispatchSemaphore(value: 0)
  735. self.loadMetadata(userBaseUrl: userBaseUrl, filePath: dir + filename, dispatchGroup: nil) { account, metadata, error in
  736. metadatas.append(metadata)
  737. semaphore.signal()
  738. }
  739. semaphore.wait()
  740. }
  741. })
  742. default:
  743. searchResult.entries.forEach({ entry in
  744. let newMetadata = NCManageDatabase.shared.createMetadata(account: userBaseUrl.account, user: userBaseUrl.user, userId: userBaseUrl.userId, fileName: entry.title, fileNameView: entry.title, ocId: NSUUID().uuidString, serverUrl: userBaseUrl.urlBase, urlBase: userBaseUrl.urlBase, url: entry.resourceURL, contentType: "", isUrl: true, name: searchResult.name.lowercased(), subline: entry.subline, iconName: entry.icon, iconUrl: entry.thumbnailURL)
  745. metadatas.append(newMetadata)
  746. })
  747. }
  748. completion(account, searchResult, metadatas, error)
  749. }
  750. if let request = request {
  751. requestsUnifiedSearch.append(request)
  752. }
  753. }
  754. func cancelUnifiedSearchFiles() {
  755. for request in requestsUnifiedSearch {
  756. request.cancel()
  757. }
  758. requestsUnifiedSearch.removeAll()
  759. }
  760. private func loadMetadata(userBaseUrl: NCUserBaseUrl, filePath: String, dispatchGroup: DispatchGroup? = nil, completion: @escaping (String, tableMetadata, NKError) -> Void) {
  761. let urlPath = userBaseUrl.urlBase + "/remote.php/dav/files/" + userBaseUrl.user + filePath
  762. dispatchGroup?.enter()
  763. self.readFile(serverUrlFileName: urlPath) { account, metadata, error in
  764. defer { dispatchGroup?.leave() }
  765. guard let metadata = metadata else { return }
  766. let returnMetadata = tableMetadata.init(value: metadata)
  767. NCManageDatabase.shared.addMetadata(metadata)
  768. completion(account, returnMetadata, error)
  769. }
  770. }
  771. // MARK: - WebDav Create Folder
  772. @objc func createFolder(fileName: String, serverUrl: String, account: String, urlBase: String, userId: String, overwrite: Bool = false, completion: @escaping (_ error: NKError) -> Void) {
  773. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: false, account: account, urlBase: urlBase, userId: userId)
  774. let fileName = fileName.trimmingCharacters(in: .whitespacesAndNewlines)
  775. if isDirectoryEncrypted {
  776. #if !EXTENSION
  777. NCNetworkingE2EE.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, userId: userId, completion: completion)
  778. #endif
  779. } else {
  780. createFolderPlain(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: overwrite, completion: completion)
  781. }
  782. }
  783. private func createFolderPlain(fileName: String, serverUrl: String, account: String, urlBase: String, overwrite: Bool, completion: @escaping (_ error: NKError) -> Void) {
  784. var fileNameFolder = CCUtility.removeForbiddenCharactersServer(fileName)!
  785. if !overwrite {
  786. fileNameFolder = NCUtilityFileSystem.shared.createFileName(fileNameFolder, serverUrl: serverUrl, account: account)
  787. }
  788. if fileNameFolder.count == 0 {
  789. return completion(NKError())
  790. }
  791. let fileNameFolderUrl = serverUrl + "/" + fileNameFolder
  792. NextcloudKit.shared.createFolder(fileNameFolderUrl) { account, ocId, _, error in
  793. guard error == .success else {
  794. if error.errorCode == NCGlobal.shared.errordMethodNotSupported && overwrite {
  795. completion(NKError())
  796. } else {
  797. completion(error)
  798. }
  799. return
  800. }
  801. self.readFile(serverUrlFileName: fileNameFolderUrl) { (account, metadataFolder, error) in
  802. if error == .success {
  803. if let metadata = metadataFolder {
  804. NCManageDatabase.shared.addMetadata(metadata)
  805. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: fileNameFolderUrl, account: account)
  806. }
  807. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(metadataFolder?.ocId) {
  808. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCreateFolder, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "e2ee": false])
  809. }
  810. }
  811. completion(error)
  812. }
  813. }
  814. }
  815. func createFolder(assets: [PHAsset], selector: String, useSubFolder: Bool, account: String, urlBase: String, userId: String) -> Bool {
  816. let serverUrl = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: urlBase, userId: userId, account: account)
  817. let fileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  818. let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: urlBase, userId: userId, account: account)
  819. var result = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, userId: userId)
  820. if useSubFolder && result {
  821. for dateSubFolder in createNameSubFolder(assets: assets) {
  822. let fileName = (dateSubFolder as NSString).lastPathComponent
  823. let serverUrl = ((autoUploadPath + "/" + dateSubFolder) as NSString).deletingLastPathComponent
  824. result = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, userId: userId)
  825. if !result { break }
  826. }
  827. }
  828. return result
  829. }
  830. private func createFolderWithSemaphore(fileName: String, serverUrl: String, account: String, urlBase: String, userId: String) -> Bool {
  831. var result: Bool = false
  832. let semaphore = DispatchSemaphore(value: 0)
  833. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, userId: userId, overwrite: true) { error in
  834. if error == .success { result = true }
  835. semaphore.signal()
  836. }
  837. semaphore.wait()
  838. return result
  839. }
  840. func createNameSubFolder(assets: [PHAsset]) -> [String] {
  841. var datesSubFolder: [String] = []
  842. let dateFormatter = DateFormatter()
  843. for asset in assets {
  844. let date = asset.creationDate ?? Date()
  845. dateFormatter.dateFormat = "yyyy"
  846. let year = dateFormatter.string(from: date)
  847. dateFormatter.dateFormat = "MM"
  848. let month = dateFormatter.string(from: date)
  849. datesSubFolder.append("\(year)/\(month)")
  850. }
  851. return Array(Set(datesSubFolder))
  852. }
  853. // MARK: - WebDav Delete
  854. @objc func deleteMetadata(_ metadata: tableMetadata, onlyLocalCache: Bool, completion: @escaping (_ error: NKError) -> Void) {
  855. if onlyLocalCache {
  856. var metadatas = [metadata]
  857. if metadata.directory {
  858. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  859. metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND directory == false", metadata.account, serverUrl))
  860. }
  861. for metadata in metadatas {
  862. NCManageDatabase.shared.deleteVideo(metadata: metadata)
  863. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  864. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  865. if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  866. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadataLivePhoto.ocId))
  867. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadataLivePhoto.ocId))
  868. }
  869. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "serverUrl": metadata.serverUrl, "account": metadata.account, "classFile": metadata.classFile, "onlyLocalCache": true])
  870. }
  871. return completion(NKError())
  872. }
  873. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase, userId: metadata.userId)
  874. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  875. if isDirectoryEncrypted {
  876. #if !EXTENSION
  877. if metadataLive == nil {
  878. NCNetworkingE2EE.shared.deleteMetadata(metadata, completion: completion)
  879. } else {
  880. NCNetworkingE2EE.shared.deleteMetadata(metadataLive!) { error in
  881. if error == .success {
  882. NCNetworkingE2EE.shared.deleteMetadata(metadata, completion: completion)
  883. } else {
  884. completion(error)
  885. }
  886. }
  887. }
  888. #endif
  889. } else {
  890. if metadataLive == nil {
  891. self.deleteMetadataPlain(metadata, customHeader: nil, completion: completion)
  892. } else {
  893. self.deleteMetadataPlain(metadataLive!, customHeader: nil) { error in
  894. if error == .success {
  895. self.deleteMetadataPlain(metadata, customHeader: nil, completion: completion)
  896. } else {
  897. completion(error)
  898. }
  899. }
  900. }
  901. }
  902. }
  903. func deleteMetadataPlain(_ metadata: tableMetadata, customHeader: [String: String]?, completion: @escaping (_ error: NKError) -> Void) {
  904. // verify permission
  905. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanDelete)
  906. if metadata.permissions != "" && permission == false {
  907. return completion(NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_delete_file_"))
  908. }
  909. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  910. let options = NKRequestOptions(customHeader: customHeader)
  911. NextcloudKit.shared.deleteFileOrFolder(serverUrlFileName, options: options) { account, error in
  912. if error == .success || error.errorCode == NCGlobal.shared.errorResourceNotFound {
  913. do {
  914. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  915. } catch { }
  916. NCManageDatabase.shared.deleteVideo(metadata: metadata)
  917. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  918. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  919. if metadata.directory {
  920. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account)
  921. }
  922. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "serverUrl": metadata.serverUrl, "account": metadata.account, "classFile": metadata.classFile, "onlyLocalCache": false])
  923. }
  924. completion(error)
  925. }
  926. }
  927. // MARK: - WebDav Favorite
  928. @objc func favoriteMetadata(_ metadata: tableMetadata, completion: @escaping (_ error: NKError) -> Void) {
  929. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  930. favoriteMetadataPlain(metadataLive) { error in
  931. if error == .success {
  932. self.favoriteMetadataPlain(metadata, completion: completion)
  933. } else {
  934. completion(error)
  935. }
  936. }
  937. } else {
  938. favoriteMetadataPlain(metadata, completion: completion)
  939. }
  940. }
  941. private func favoriteMetadataPlain(_ metadata: tableMetadata, completion: @escaping (_ error: NKError) -> Void) {
  942. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)!
  943. let favorite = !metadata.favorite
  944. let ocId = metadata.ocId
  945. NextcloudKit.shared.setFavorite(fileName: fileName, favorite: favorite) { account, error in
  946. if error == .success && metadata.account == account {
  947. NCManageDatabase.shared.setMetadataFavorite(ocId: metadata.ocId, favorite: favorite)
  948. #if !EXTENSION
  949. if favorite {
  950. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorReadFile)
  951. }
  952. #endif
  953. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterFavoriteFile, userInfo: ["ocId": ocId, "serverUrl": metadata.serverUrl])
  954. }
  955. completion(error)
  956. }
  957. }
  958. @objc func listingFavoritescompletion(selector: String, completion: @escaping (_ account: String, _ metadatas: [tableMetadata]?, _ error: NKError) -> Void) {
  959. let options = NKRequestOptions(queue: NKCommon.shared.backgroundQueue)
  960. NextcloudKit.shared.listingFavorites(showHiddenFiles: CCUtility.getShowHiddenFiles(), options: options) { account, files, data, error in
  961. guard error == .success else {
  962. completion(account, nil, error)
  963. return
  964. }
  965. NCManageDatabase.shared.convertNKFilesToMetadatas(files, useMetadataFolder: false, account: account) { _, _, metadatas in
  966. NCManageDatabase.shared.updateMetadatasFavorite(account: account, metadatas: metadatas)
  967. if selector != NCGlobal.shared.selectorListingFavorite {
  968. #if !EXTENSION
  969. for metadata in metadatas {
  970. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: selector)
  971. }
  972. #endif
  973. }
  974. completion(account, metadatas, error)
  975. }
  976. }
  977. }
  978. // MARK: - Lock Files
  979. @objc func lockUnlockFile(_ metadata: tableMetadata, shoulLock: Bool) {
  980. NextcloudKit.shared.lockUnlockFile(serverUrlFileName: metadata.serverUrl + "/" + metadata.fileName, shouldLock: shoulLock) { account, error in
  981. // 0: lock was successful; 412: lock did not change, no error, refresh
  982. guard error == .success || error.errorCode == NCGlobal.shared.errorPreconditionFailed else {
  983. let error = NKError(errorCode: error.errorCode, errorDescription: "_files_lock_error_")
  984. NCContentPresenter.shared.messageNotification(metadata.fileName, error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  985. return
  986. }
  987. NCNetworking.shared.readFile(serverUrlFileName: metadata.serverUrl + "/" + metadata.fileName) { account, metadata, error in
  988. guard error == .success, let metadata = metadata else { return }
  989. NCManageDatabase.shared.addMetadata(metadata)
  990. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource)
  991. }
  992. }
  993. }
  994. // MARK: - WebDav Rename
  995. @objc func renameMetadata(_ metadata: tableMetadata, fileNameNew: String, viewController: UIViewController?, completion: @escaping (_ error: NKError) -> Void) {
  996. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase, userId: metadata.userId)
  997. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  998. let fileNameNew = fileNameNew.trimmingCharacters(in: .whitespacesAndNewlines)
  999. let fileNameNewLive = (fileNameNew as NSString).deletingPathExtension + ".mov"
  1000. if isDirectoryEncrypted {
  1001. #if !EXTENSION
  1002. if metadataLive == nil {
  1003. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, completion: completion)
  1004. } else {
  1005. NCNetworkingE2EE.shared.renameMetadata(metadataLive!, fileNameNew: fileNameNewLive) { error in
  1006. if error == .success {
  1007. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, completion: completion)
  1008. } else {
  1009. completion(error)
  1010. }
  1011. }
  1012. }
  1013. #endif
  1014. } else {
  1015. if metadataLive == nil {
  1016. renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  1017. } else {
  1018. renameMetadataPlain(metadataLive!, fileNameNew: fileNameNewLive) { error in
  1019. if error == .success {
  1020. self.renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  1021. } else {
  1022. completion(error)
  1023. }
  1024. }
  1025. }
  1026. }
  1027. }
  1028. private func renameMetadataPlain(_ metadata: tableMetadata, fileNameNew: String, completion: @escaping (_ error: NKError) -> Void) {
  1029. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  1030. if !(metadata.permissions == "") && !permission {
  1031. return completion(NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_modify_file_"))
  1032. }
  1033. guard let fileNameNew = CCUtility.removeForbiddenCharactersServer(fileNameNew) else {
  1034. return completion(NKError())
  1035. }
  1036. if fileNameNew.count == 0 || fileNameNew == metadata.fileNameView {
  1037. return completion(NKError())
  1038. }
  1039. let fileNamePath = metadata.serverUrl + "/" + metadata.fileName
  1040. let fileNameToPath = metadata.serverUrl + "/" + fileNameNew
  1041. let ocId = metadata.ocId
  1042. NextcloudKit.shared.moveFileOrFolder(serverUrlFileNameSource: fileNamePath, serverUrlFileNameDestination: fileNameToPath, overwrite: false) { account, error in
  1043. if error == .success {
  1044. NCManageDatabase.shared.renameMetadata(fileNameTo: fileNameNew, ocId: ocId)
  1045. if metadata.directory {
  1046. let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1047. let serverUrlTo = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: fileNameNew)!
  1048. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  1049. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, serverUrlTo: serverUrlTo, etag: "", ocId: nil, fileId: nil, encrypted: directory.e2eEncrypted, richWorkspace: nil, account: metadata.account)
  1050. }
  1051. } else {
  1052. let ext = (metadata.fileName as NSString).pathExtension
  1053. let extNew = (fileNameNew as NSString).pathExtension
  1054. if ext != extNew {
  1055. if let path = CCUtility.getDirectoryProviderStorageOcId(ocId) {
  1056. NCUtilityFileSystem.shared.deleteFile(filePath: path)
  1057. }
  1058. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": metadata.serverUrl])
  1059. } else {
  1060. NCManageDatabase.shared.setLocalFile(ocId: ocId, fileName: fileNameNew, etag: nil)
  1061. // Move file system
  1062. let atPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + metadata.fileName
  1063. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + fileNameNew
  1064. do {
  1065. try FileManager.default.moveItem(atPath: atPath, toPath: toPath)
  1066. } catch { }
  1067. }
  1068. }
  1069. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  1070. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRenameFile, userInfo: ["ocId": metadata.ocId, "account": metadata.account])
  1071. }
  1072. }
  1073. completion(error)
  1074. }
  1075. }
  1076. // MARK: - WebDav Move
  1077. @objc func moveMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ error: NKError) -> Void) {
  1078. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  1079. moveMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { error in
  1080. if error == .success {
  1081. self.moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1082. } else {
  1083. completion(error)
  1084. }
  1085. }
  1086. } else {
  1087. moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1088. }
  1089. }
  1090. private func moveMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ error: NKError) -> Void) {
  1091. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  1092. if !(metadata.permissions == "") && !permission {
  1093. return completion(NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_modify_file_"))
  1094. }
  1095. let serverUrlFrom = metadata.serverUrl
  1096. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  1097. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  1098. NextcloudKit.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { account, error in
  1099. if error == .success {
  1100. if metadata.directory {
  1101. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: account)
  1102. }
  1103. NCManageDatabase.shared.moveMetadata(ocId: metadata.ocId, serverUrlTo: serverUrlTo)
  1104. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMoveFile, userInfo: ["ocId": metadata.ocId, "account": metadata.account, "serverUrlFrom": serverUrlFrom])
  1105. }
  1106. completion(error)
  1107. }
  1108. }
  1109. // MARK: - WebDav Copy
  1110. @objc func copyMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ error: NKError) -> Void) {
  1111. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  1112. copyMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { error in
  1113. if error == .success {
  1114. self.copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1115. } else {
  1116. completion(error)
  1117. }
  1118. }
  1119. } else {
  1120. copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1121. }
  1122. }
  1123. private func copyMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ error: NKError) -> Void) {
  1124. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  1125. if !(metadata.permissions == "") && !permission {
  1126. return completion(NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_modify_file_"))
  1127. }
  1128. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  1129. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  1130. NextcloudKit.shared.copyFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { _, error in
  1131. if error == .success {
  1132. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCopyFile, userInfo: ["ocId": metadata.ocId, "serverUrlTo": serverUrlTo])
  1133. }
  1134. completion(error)
  1135. }
  1136. }
  1137. // MARK: - Direct Download
  1138. func getVideoUrl(metadata: tableMetadata, completition: @escaping (_ url: URL?) -> Void) {
  1139. if CCUtility.fileProviderStorageExists(metadata) {
  1140. completition(URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)))
  1141. } else {
  1142. NextcloudKit.shared.getDirectDownload(fileId: metadata.fileId) { account, url, data, error in
  1143. if error == .success && url != nil {
  1144. if let url = URL(string: url!) {
  1145. completition(url)
  1146. } else {
  1147. completition(nil)
  1148. }
  1149. } else {
  1150. completition(nil)
  1151. }
  1152. }
  1153. }
  1154. }
  1155. // MARK: - [NextcloudKit wrapper] convert completion handlers into async functions
  1156. func getPreview(url: URL,
  1157. options: NKRequestOptions = NKRequestOptions()) async -> (account: String, data: Data?, error: NKError) {
  1158. await withUnsafeContinuation({ continuation in
  1159. NextcloudKit.shared.getPreview(url: url, options: options) { account, data, error in
  1160. continuation.resume(returning: (account: account, data: data, error: error))
  1161. }
  1162. })
  1163. }
  1164. func downloadPreview(fileNamePathOrFileId: String,
  1165. fileNamePreviewLocalPath: String,
  1166. widthPreview: Int,
  1167. heightPreview: Int,
  1168. fileNameIconLocalPath: String? = nil,
  1169. sizeIcon: Int = 0,
  1170. etag: String? = nil,
  1171. endpointTrashbin: Bool = false,
  1172. useInternalEndpoint: Bool = true,
  1173. options: NKRequestOptions = NKRequestOptions()) async -> (account: String, imagePreview: UIImage?, imageIcon: UIImage?, imageOriginal: UIImage?, etag: String?, error: NKError) {
  1174. await withUnsafeContinuation({ continuation in
  1175. NextcloudKit.shared.downloadPreview(fileNamePathOrFileId: fileNamePathOrFileId, fileNamePreviewLocalPath: fileNamePreviewLocalPath, widthPreview: widthPreview, heightPreview: heightPreview, fileNameIconLocalPath: fileNameIconLocalPath, sizeIcon: sizeIcon, etag: etag, options: options) { account, imagePreview, imageIcon, imageOriginal, etag, error in
  1176. continuation.resume(returning: (account: account, imagePreview: imagePreview, imageIcon: imageIcon, imageOriginal: imageOriginal, etag: etag, error: error))
  1177. }
  1178. })
  1179. }
  1180. }
  1181. extension Array where Element == URLQueryItem {
  1182. subscript(name: String) -> URLQueryItem? {
  1183. first(where: { $0.name == name })
  1184. }
  1185. }