NCNetworking.swift 77 KB

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