NCNetworking.swift 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424
  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 NCCommunication
  26. import Alamofire
  27. import Queuer
  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, errorCode: Int, errorDescription: String)
  32. @objc optional func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String)
  33. }
  34. @objc class NCNetworking: NSObject, NCCommunicationCommonDelegate {
  35. @objc public static let shared: NCNetworking = {
  36. let instance = NCNetworking()
  37. return instance
  38. }()
  39. var delegate: NCNetworkingDelegate?
  40. var lastReachability: Bool = true
  41. var networkReachability: NCCommunicationCommon.typeReachability?
  42. var downloadRequest: [String: DownloadRequest] = [:]
  43. var uploadRequest: [String: UploadRequest] = [:]
  44. var uploadMetadataInBackground: [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: NCCommunicationBackground.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: NCCommunicationBackground.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: NCCommunicationBackground.shared, delegateQueue: OperationQueue.main)
  79. return session
  80. }()
  81. #endif
  82. //MARK: - init
  83. override init() {
  84. super.init()
  85. #if EXTENSION
  86. _ = sessionIdentifierBackgroundExtension
  87. #else
  88. _ = sessionManagerBackground
  89. _ = sessionManagerBackgroundWWan
  90. #endif
  91. // Notification
  92. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  93. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  94. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  95. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  96. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  97. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  98. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object:nil)
  99. }
  100. //MARK: - Communication Delegate
  101. func networkReachabilityObserver(_ typeReachability: NCCommunicationCommon.typeReachability) {
  102. #if !EXTENSION
  103. if typeReachability == NCCommunicationCommon.typeReachability.reachableCellular || typeReachability == NCCommunicationCommon.typeReachability.reachableEthernetOrWiFi {
  104. if !lastReachability {
  105. NCService.shared.startRequestServicesServer()
  106. }
  107. lastReachability = true
  108. } else {
  109. if lastReachability {
  110. NCContentPresenter.shared.messageNotification("_network_not_available_", description: nil, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: -1009)
  111. }
  112. lastReachability = false
  113. }
  114. networkReachability = typeReachability
  115. #endif
  116. }
  117. func authenticationChallenge(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  118. if checkTrustedChallenge(session, didReceive: challenge) {
  119. completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential.init(trust: challenge.protectionSpace.serverTrust!))
  120. } else {
  121. completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
  122. }
  123. }
  124. func downloadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  125. delegate?.downloadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  126. }
  127. func downloadComplete(fileName: String, serverUrl: String, etag: String?, date: NSDate?, dateLastModified: NSDate?, length: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  128. delegate?.downloadComplete?(fileName: fileName, serverUrl: serverUrl, etag: etag, date: date, dateLastModified: dateLastModified, length: length, description: description, task: task, errorCode: errorCode, errorDescription: errorDescription)
  129. }
  130. func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
  131. #if !EXTENSION
  132. if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let completionHandler = appDelegate.backgroundSessionCompletionHandler {
  133. NCCommunicationCommon.shared.writeLog("Called urlSessionDidFinishEvents for Background URLSession")
  134. appDelegate.backgroundSessionCompletionHandler = nil
  135. completionHandler()
  136. }
  137. #endif
  138. }
  139. // MARK: - NotificationCenter
  140. @objc func downloadStartFile(_ notification: NSNotification) {
  141. }
  142. @objc func downloadedFile(_ notification: NSNotification) {
  143. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String {
  144. #if !EXTENSION
  145. (UIApplication.shared.delegate as! AppDelegate).listProgress[ocId] = nil
  146. #endif
  147. }
  148. }
  149. @objc func downloadCancelFile(_ notification: NSNotification) {
  150. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String {
  151. #if !EXTENSION
  152. (UIApplication.shared.delegate as! AppDelegate).listProgress[ocId] = nil
  153. #endif
  154. }
  155. }
  156. @objc func uploadStartFile(_ notification: NSNotification) {
  157. }
  158. @objc func uploadedFile(_ notification: NSNotification) {
  159. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String {
  160. #if !EXTENSION
  161. (UIApplication.shared.delegate as! AppDelegate).listProgress[ocId] = nil
  162. #endif
  163. }
  164. }
  165. @objc func uploadCancelFile(_ notification: NSNotification) {
  166. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String {
  167. #if !EXTENSION
  168. (UIApplication.shared.delegate as! AppDelegate).listProgress[ocId] = nil
  169. #endif
  170. }
  171. }
  172. @objc func triggerProgressTask(_ notification: NSNotification) {
  173. if let userInfo = notification.userInfo as NSDictionary?, let progressNumber = userInfo["progress"] as? NSNumber, let totalBytes = userInfo["totalBytes"] as? Int64, let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64, let ocId = userInfo["ocId"] as? String {
  174. #if !EXTENSION
  175. let progressType = NCGlobal.progressType(progress: progressNumber.floatValue, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected)
  176. (UIApplication.shared.delegate as! AppDelegate).listProgress[ocId] = progressType
  177. #endif
  178. }
  179. }
  180. //MARK: - Pinning check
  181. private func checkTrustedChallenge(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge) -> Bool {
  182. var trusted = false
  183. var trustedV2 = false
  184. let protectionSpace: URLProtectionSpace = challenge.protectionSpace
  185. let directoryCertificate = CCUtility.getDirectoryCerificates()!
  186. let directoryCertificateUrl = URL.init(fileURLWithPath: directoryCertificate)
  187. let host = challenge.protectionSpace.host
  188. if let serverTrust: SecTrust = protectionSpace.serverTrust {
  189. saveX509Certificate(serverTrust, certName: NCGlobal.shared.certificateTmp, directoryCertificate: directoryCertificate)
  190. // OLD
  191. do {
  192. let directoryContents = try FileManager.default.contentsOfDirectory(at: directoryCertificateUrl, includingPropertiesForKeys: nil)
  193. let certTmpPath = directoryCertificate + "/" + NCGlobal.shared.certificateTmp
  194. for file in directoryContents {
  195. let certPath = file.path
  196. if certPath == certTmpPath { continue }
  197. if FileManager.default.contentsEqual(atPath:certTmpPath, andPath: certPath) {
  198. trusted = true
  199. break
  200. }
  201. }
  202. } catch {
  203. print(error)
  204. }
  205. // V2
  206. var secresult = SecTrustResultType.invalid
  207. let status = SecTrustEvaluate(serverTrust, &secresult)
  208. if (errSecSuccess == status) {
  209. if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
  210. let serverCertificateData = SecCertificateCopyData(serverCertificate)
  211. let data = CFDataGetBytePtr(serverCertificateData);
  212. let size = CFDataGetLength(serverCertificateData);
  213. let certificate = NSData(bytes: data, length: size)
  214. // write certificate tmp to disk
  215. let certificatePath = directoryCertificate + "/" + NCGlobal.shared.certificateTmpV2
  216. certificate.write(toFile: certificatePath, atomically: true)
  217. let certificateSavedPath = directoryCertificate + "/" + host + ".der"
  218. if let certificateSaved = NSData(contentsOfFile: certificateSavedPath) {
  219. if certificate.isEqual(to: certificateSaved as Data) {
  220. trustedV2 = true
  221. }
  222. }
  223. if !trusted && !trustedV2 {
  224. #if !EXTENSION
  225. DispatchQueue.main.async {
  226. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  227. CCUtility.setCertificateError(appDelegate.account)
  228. }
  229. #endif
  230. }
  231. }
  232. }
  233. }
  234. if trusted || trustedV2 {
  235. return true
  236. } else {
  237. return false
  238. }
  239. }
  240. func writeCertificate(url: String) {
  241. let directoryCertificate = CCUtility.getDirectoryCerificates()!
  242. if let url = URL(string: url) {
  243. let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
  244. if let host = urlComponents?.host {
  245. let certificateAtPath = directoryCertificate + "/" + NCGlobal.shared.certificateTmpV2
  246. let certificateToPath = directoryCertificate + "/" + host + ".der"
  247. if !NCUtilityFileSystem.shared.moveFile(atPath: certificateAtPath, toPath: certificateToPath) {
  248. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorCreationFile, forced: true)
  249. }
  250. }
  251. }
  252. }
  253. private func saveX509Certificate(_ serverTrust: SecTrust, certName: String, directoryCertificate: String) {
  254. if let currentServerCert = SecTrustGetCertificateAtIndex(serverTrust, 0) {
  255. let certNamePath = directoryCertificate + "/" + certName
  256. let certificateDetailsNamePath = directoryCertificate + "/" + NCGlobal.shared.certificateTmpV2 + ".txt"
  257. let data: CFData = SecCertificateCopyData(currentServerCert)
  258. let mem = BIO_new_mem_buf(CFDataGetBytePtr(data), Int32(CFDataGetLength(data)))
  259. let x509cert = d2i_X509_bio(mem, nil)
  260. if x509cert == nil {
  261. print("[LOG] OpenSSL couldn't parse X509 Certificate")
  262. } else {
  263. // save certificate
  264. if FileManager.default.fileExists(atPath: certNamePath) {
  265. do {
  266. try FileManager.default.removeItem(atPath: certNamePath)
  267. } catch { }
  268. }
  269. let fileCert = fopen(certNamePath, "w")
  270. if fileCert != nil {
  271. PEM_write_X509(fileCert, x509cert)
  272. }
  273. fclose(fileCert)
  274. // save details
  275. if FileManager.default.fileExists(atPath: certificateDetailsNamePath) {
  276. do {
  277. try FileManager.default.removeItem(atPath: certificateDetailsNamePath)
  278. } catch { }
  279. }
  280. let fileCertInfo = fopen(certificateDetailsNamePath, "w")
  281. if fileCertInfo != nil {
  282. let output = BIO_new_fp(fileCertInfo, BIO_NOCLOSE)
  283. X509_print_ex(output, x509cert, UInt(XN_FLAG_COMPAT), UInt(X509_FLAG_COMPAT))
  284. BIO_free(output)
  285. }
  286. fclose(fileCertInfo)
  287. X509_free(x509cert)
  288. }
  289. BIO_free(mem)
  290. }
  291. }
  292. //MARK: - Utility
  293. func cancelTaskWithUrl(_ url: URL) {
  294. NCCommunication.shared.getSessionManager().getAllTasks { tasks in
  295. tasks.filter { $0.state == .running }.filter { $0.originalRequest?.url == url }.first?.cancel()
  296. }
  297. }
  298. @objc func cancelAllTask() {
  299. NCCommunication.shared.getSessionManager().getAllTasks { tasks in
  300. for task in tasks {
  301. task.cancel()
  302. }
  303. }
  304. }
  305. //MARK: - Download
  306. @objc func cancelDownload(ocId: String, serverUrl:String, fileNameView: String) {
  307. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView) else { return }
  308. if let request = downloadRequest[fileNameLocalPath] {
  309. request.cancel()
  310. } else {
  311. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  312. NCManageDatabase.shared.setMetadataSession(ocId: ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  313. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadCancelFile, userInfo: ["ocId":metadata.ocId])
  314. }
  315. }
  316. }
  317. @objc func download(metadata: tableMetadata, selector: String, completion: @escaping (_ errorCode: Int)->()) {
  318. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  319. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
  320. if NCManageDatabase.shared.getMetadataFromOcId(metadata.ocId) == nil {
  321. NCManageDatabase.shared.addMetadata(tableMetadata.init(value: metadata))
  322. }
  323. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading { return }
  324. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: NCCommunicationCommon.shared.sessionIdentifierDownload, sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusInDownload)
  325. NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { (request) in
  326. self.downloadRequest[fileNameLocalPath] = request
  327. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusDownloading)
  328. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadStartFile, userInfo: ["ocId":metadata.ocId])
  329. }, taskHandler: { (_) in
  330. }, progressHandler: { (progress) in
  331. 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)])
  332. }) { (account, etag, date, length, allHeaderFields, error, errorCode, errorDescription) in
  333. if error?.isExplicitlyCancelledError ?? false {
  334. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  335. } else if errorCode == 0 {
  336. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal, etag: etag)
  337. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  338. #if !EXTENSION
  339. if let result = NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "fileNameIdentifier == %@ AND serverUrl == %@", metadata.fileName, metadata.serverUrl)) {
  340. NCEndToEndEncryption.sharedManager()?.decryptFileName(metadata.fileName, fileNameView: metadata.fileNameView, ocId: metadata.ocId, key: result.key, initializationVector: result.initializationVector, authenticationTag: result.authenticationTag)
  341. }
  342. CCUtility.setExif(metadata) { (latitude, longitude, location, date, lensMode) in };
  343. #endif
  344. } else {
  345. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: errorDescription, sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusDownloadError)
  346. #if !EXTENSION
  347. if errorCode == 401 || errorCode == 403 {
  348. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account, errorCode: errorCode, errorDescription: errorDescription)
  349. }
  350. #endif
  351. }
  352. self.downloadRequest[fileNameLocalPath] = nil
  353. if error?.isExplicitlyCancelledError ?? false {
  354. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadCancelFile, userInfo: ["ocId":metadata.ocId])
  355. } else {
  356. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId":metadata.ocId, "selector":selector, "errorCode":errorCode, "errorDescription":errorDescription])
  357. }
  358. completion(errorCode)
  359. }
  360. }
  361. //MARK: - Upload
  362. @objc func upload(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  363. var metadata = tableMetadata.init(value: metadata)
  364. var fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  365. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  366. let results = NCCommunicationCommon.shared.getInternalType(fileName: metadata.fileNameView, mimeType: metadata.contentType, directory: false)
  367. metadata.contentType = results.mimeType
  368. metadata.iconName = results.iconName
  369. metadata.classFile = results.classFile
  370. if let date = NCUtilityFileSystem.shared.getFileCreationDate(filePath: fileNameLocalPath) {
  371. metadata.creationDate = date
  372. }
  373. if let date = NCUtilityFileSystem.shared.getFileModificationDate(filePath: fileNameLocalPath) {
  374. metadata.date = date
  375. }
  376. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath)
  377. NCManageDatabase.shared.addMetadata(metadata)
  378. metadata = tableMetadata.init(value: metadata)
  379. if metadata.e2eEncrypted {
  380. #if !EXTENSION_FILE_PROVIDER_EXTENSION
  381. NCNetworkingE2EE.shared.upload(metadata: tableMetadata.init(value: metadata), start: { start() }, completion: completion)
  382. #endif
  383. } else if metadata.chunk {
  384. uploadChunkedFile(metadata: metadata, start: { start() }, completion: completion)
  385. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  386. uploadFile(metadata: metadata, start: { start() }, completion: completion)
  387. } else {
  388. uploadFileInBackground(metadata: metadata, start: { start() }, completion: completion)
  389. }
  390. } else {
  391. CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadata, notification: true) { (extractMetadata, fileNamePath) in
  392. guard let extractMetadata = extractMetadata else {
  393. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  394. return completion(NCGlobal.shared.errorInternalError, "Internal error")
  395. }
  396. let metadata = tableMetadata.init(value: extractMetadata)
  397. fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(extractMetadata.ocId, fileNameView: extractMetadata.fileNameView)
  398. NCUtilityFileSystem.shared.moveFileInBackground(atPath: fileNamePath!, toPath: fileNameLocalPath)
  399. NCManageDatabase.shared.addMetadata(extractMetadata)
  400. if metadata.e2eEncrypted {
  401. #if !EXTENSION_FILE_PROVIDER_EXTENSION
  402. NCNetworkingE2EE.shared.upload(metadata: extractMetadata, start: { start() }, completion: completion)
  403. #endif
  404. } else if metadata.chunk {
  405. self.uploadChunkedFile(metadata: metadata, start: { start() }, completion: completion)
  406. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  407. self.uploadFile(metadata: metadata, start: { start() }, completion: completion)
  408. } else {
  409. self.uploadFileInBackground(metadata: metadata, start: { start() }, completion: completion)
  410. }
  411. }
  412. }
  413. }
  414. private func uploadFile(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  415. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  416. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  417. var uploadTask: URLSessionTask?
  418. let description = metadata.ocId
  419. NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.creationDate as Date, dateModificationFile: metadata.date as Date, customUserAgent: nil, addCustomHeaders: nil, requestHandler: { (request) in
  420. self.uploadRequest[fileNameLocalPath] = request
  421. }, taskHandler: { (task) in
  422. uploadTask = task
  423. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  424. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId":metadata.ocId])
  425. start()
  426. }, progressHandler: { (progress) in
  427. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterProgressTask, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "fileName":metadata.fileName, "serverUrl":metadata.serverUrl, "status":NSNumber(value: NCGlobal.shared.metadataStatusInUpload), "progress":NSNumber(value: progress.fractionCompleted), "totalBytes":NSNumber(value: progress.totalUnitCount), "totalBytesExpected":NSNumber(value: progress.completedUnitCount)])
  428. }) { (account, ocId, etag, date, size, allHeaderFields, error, errorCode, errorDescription) in
  429. self.uploadRequest[fileNameLocalPath] = nil
  430. self.uploadComplete(fileName: metadata.fileName, serverUrl: metadata.serverUrl, ocId: ocId, etag: etag, date: date, size: size, description: description, task: uploadTask!, errorCode: errorCode, errorDescription: errorDescription)
  431. completion(errorCode, errorDescription)
  432. }
  433. }
  434. private func uploadFileInBackground(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  435. var session: URLSession?
  436. let metadata = tableMetadata.init(value: metadata)
  437. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  438. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  439. if metadata.session == sessionIdentifierBackground || metadata.session == sessionIdentifierBackgroundExtension {
  440. session = sessionManagerBackground
  441. } else if metadata.session == sessionIdentifierBackgroundWWan {
  442. session = sessionManagerBackgroundWWan
  443. }
  444. start()
  445. // Check file dim > 0
  446. if NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath) == 0 {
  447. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  448. completion(NCGlobal.shared.errorResourceNotFound, NSLocalizedString("_error_not_found_", value: "The requested resource could not be found", comment: ""))
  449. } else {
  450. if let task = NCCommunicationBackground.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.creationDate as Date, dateModificationFile: metadata.date as Date, description: metadata.ocId, session: session!) {
  451. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  452. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId":metadata.ocId])
  453. completion(0, "")
  454. } else {
  455. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  456. completion(NCGlobal.shared.errorInternalError, "task null")
  457. }
  458. }
  459. }
  460. func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  461. if delegate != nil {
  462. delegate?.uploadComplete?(fileName: fileName, serverUrl: serverUrl, ocId: ocId, etag: etag, date: date, size:size, description: description, task: task, errorCode: errorCode, errorDescription: errorDescription)
  463. } else {
  464. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(description) else { return }
  465. guard let tableAccount = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account)) else { return }
  466. let ocIdTemp = metadata.ocId
  467. var errorDescription = errorDescription
  468. if errorCode == 0 && ocId != nil && size > 0 {
  469. let metadata = tableMetadata.init(value: metadata)
  470. NCUtilityFileSystem.shared.moveFileInBackground(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
  471. metadata.uploadDate = date ?? NSDate()
  472. metadata.etag = etag ?? ""
  473. metadata.ocId = ocId!
  474. if let fileId = NCUtility.shared.ocIdToFileId(ocId: ocId) {
  475. metadata.fileId = fileId
  476. }
  477. metadata.session = ""
  478. metadata.sessionError = ""
  479. metadata.sessionTaskIdentifier = 0
  480. metadata.status = NCGlobal.shared.metadataStatusNormal
  481. // Delete Asset on Photos album
  482. if tableAccount.autoUploadDeleteAssetLocalIdentifier && metadata.assetLocalIdentifier != "" && metadata.sessionSelector == NCGlobal.shared.selectorUploadAutoUpload {
  483. metadata.deleteAssetLocalIdentifier = true;
  484. }
  485. if CCUtility.getDisableLocalCacheAfterUpload() {
  486. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  487. } else {
  488. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  489. }
  490. NCManageDatabase.shared.addMetadata(metadata)
  491. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  492. #if !EXTENSION
  493. self.getOcIdInBackgroundSession { (listOcId) in
  494. if listOcId.count == 0 && self.uploadRequest.count == 0 {
  495. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  496. appDelegate.networkingProcessUpload?.startProcess()
  497. }
  498. }
  499. CCUtility.setExif(metadata) { (latitude, longitude, location, date, lensMode) in };
  500. #endif
  501. NCCommunicationCommon.shared.writeLog("Upload complete " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)")
  502. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":ocIdTemp, "errorCode":errorCode, "errorDescription":""])
  503. } else {
  504. if errorCode == NSURLErrorCancelled || errorCode == NCGlobal.shared.errorRequestExplicityCancelled {
  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. } else if errorCode == 401 || errorCode == 403 {
  509. #if !EXTENSION
  510. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account, errorCode: errorCode, errorDescription: errorDescription)
  511. #endif
  512. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  513. } else {
  514. if size == 0 {
  515. errorDescription = "File length 0"
  516. NCCommunicationCommon.shared.writeLog("Upload error 0 length " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)")
  517. }
  518. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  519. }
  520. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":ocIdTemp, "errorCode":errorCode, "errorDescription":""])
  521. }
  522. // Delete
  523. self.uploadMetadataInBackground[fileName+serverUrl] = nil
  524. }
  525. }
  526. func uploadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  527. delegate?.uploadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  528. var metadata: tableMetadata?
  529. let description: String = task.taskDescription ?? ""
  530. if let metadataTmp = self.uploadMetadataInBackground[fileName+serverUrl] {
  531. metadata = metadataTmp
  532. } else if let metadataTmp = NCManageDatabase.shared.getMetadataFromOcId(description){
  533. self.uploadMetadataInBackground[fileName+serverUrl] = metadataTmp
  534. metadata = metadataTmp
  535. }
  536. if let metadata = metadata {
  537. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterProgressTask, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "fileName":metadata.fileName, "serverUrl":serverUrl, "status":NSNumber(value: NCGlobal.shared.metadataStatusInUpload), "progress":NSNumber(value: progress), "totalBytes":NSNumber(value: totalBytes), "totalBytesExpected":NSNumber(value: totalBytesExpected)])
  538. }
  539. }
  540. func getOcIdInBackgroundSession(completion: @escaping (_ listOcId: [String])->()) {
  541. var listOcId: [String] = []
  542. sessionManagerBackground.getAllTasks(completionHandler: { (tasks) in
  543. for task in tasks {
  544. listOcId.append(task.description)
  545. }
  546. self.sessionManagerBackgroundWWan.getAllTasks(completionHandler: { (tasks) in
  547. for task in tasks {
  548. listOcId.append(task.description)
  549. }
  550. completion(listOcId)
  551. })
  552. })
  553. }
  554. //MARK: - Transfer (Download Upload)
  555. @objc func cancelTransferMetadata(_ metadata: tableMetadata, completion: @escaping ()->()) {
  556. let metadata = tableMetadata.init(value: metadata)
  557. if metadata.session.count == 0 {
  558. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  559. return completion()
  560. }
  561. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierDownload {
  562. NCNetworking.shared.cancelDownload(ocId: metadata.ocId, serverUrl: metadata.serverUrl, fileNameView: metadata.fileNameView)
  563. return completion()
  564. }
  565. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  566. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else { return }
  567. if let request = uploadRequest[fileNameLocalPath] {
  568. request.cancel()
  569. } else {
  570. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  571. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  572. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
  573. }
  574. return completion()
  575. }
  576. var session: URLSession?
  577. if metadata.session == NCNetworking.shared.sessionIdentifierBackground {
  578. session = NCNetworking.shared.sessionManagerBackground
  579. } else if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundWWan {
  580. session = NCNetworking.shared.sessionManagerBackgroundWWan
  581. }
  582. if session == nil {
  583. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  584. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
  585. return completion()
  586. }
  587. session?.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  588. var cancel = false
  589. if metadata.session.count > 0 && metadata.session.contains("upload") {
  590. for task in uploadTasks {
  591. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  592. task.cancel()
  593. cancel = true
  594. }
  595. }
  596. if cancel == false {
  597. do {
  598. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  599. }
  600. catch { }
  601. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  602. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
  603. }
  604. }
  605. completion()
  606. }
  607. }
  608. @objc func cancelAllTransfer(account: String, completion: @escaping ()->()) {
  609. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", account, NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusUploadError))
  610. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status != %d", NCGlobal.shared.metadataStatusNormal))
  611. var counter = 0
  612. for metadata in metadatas {
  613. counter += 1
  614. if (metadata.status == NCGlobal.shared.metadataStatusWaitDownload || metadata.status == NCGlobal.shared.metadataStatusDownloadError) {
  615. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  616. }
  617. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  618. self.cancelTransferMetadata(metadata) {
  619. if counter == metadatas.count {
  620. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  621. completion()
  622. }
  623. }
  624. }
  625. }
  626. }
  627. #if !EXTENSION
  628. NCOperationQueue.shared.downloadCancelAll()
  629. #endif
  630. }
  631. func cancelAllDownloadTransfer() {
  632. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status != %d", NCGlobal.shared.metadataStatusNormal))
  633. for metadata in metadatas {
  634. if (metadata.status == NCGlobal.shared.metadataStatusWaitDownload || metadata.status == NCGlobal.shared.metadataStatusDownloadError) {
  635. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  636. }
  637. if metadata.status == NCGlobal.shared.metadataStatusDownloading && metadata.session == NCCommunicationCommon.shared.sessionIdentifierDownload {
  638. NCNetworking.shared.cancelDownload(ocId: metadata.ocId, serverUrl: metadata.serverUrl, fileNameView: metadata.fileNameView)
  639. }
  640. }
  641. #if !EXTENSION
  642. NCOperationQueue.shared.downloadCancelAll()
  643. #endif
  644. }
  645. //MARK: - WebDav Read file, folder
  646. @objc func readFolder(serverUrl: String, account: String, completion: @escaping (_ account: String, _ metadataFolder: tableMetadata?, _ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ metadatasLocalUpdate: [tableMetadata]?, _ metadatasDelete: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  647. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
  648. if errorCode == 0 {
  649. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: true, account: account) { (metadataFolder, metadatasFolder, metadatas) in
  650. // Add metadata folder
  651. NCManageDatabase.shared.addMetadata(tableMetadata.init(value: metadataFolder))
  652. // Update directory
  653. 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)
  654. NCManageDatabase.shared.setDirectory(richWorkspace: metadataFolder.richWorkspace, serverUrl: serverUrl, account: metadataFolder.account)
  655. // Update sub directories NO Update richWorkspace
  656. for metadata in metadatasFolder {
  657. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  658. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: serverUrl, account: account)
  659. }
  660. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, NCGlobal.shared.metadataStatusNormal))
  661. let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareEtagLocal: true)
  662. completion(account, metadataFolder, metadatas, metadatasChanged.metadatasUpdate, metadatasChanged.metadatasLocalUpdate, metadatasChanged.metadatasDelete, errorCode, "")
  663. }
  664. } else {
  665. completion(account, nil, nil, nil, nil, nil, errorCode, errorDescription)
  666. }
  667. }
  668. }
  669. @objc func readFile(serverUrlFileName: String, account: String, completion: @escaping (_ account: String, _ metadata: tableMetadata?, _ errorCode: Int, _ errorDescription: String)->()) {
  670. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
  671. if errorCode == 0 && files.count == 1 {
  672. let file = files[0]
  673. let isEncrypted = CCUtility.isFolderEncrypted(file.serverUrl, e2eEncrypted:file.e2eEncrypted, account: account, urlBase: file.urlBase)
  674. let metadata = NCManageDatabase.shared.convertNCFileToMetadata(file, isEncrypted: isEncrypted, account: account)
  675. completion(account, metadata, errorCode, errorDescription)
  676. } else {
  677. completion(account, nil, errorCode, errorDescription)
  678. }
  679. }
  680. }
  681. //MARK: - WebDav Search
  682. @objc func searchFiles(urlBase: String, user: String, literal: String, completion: @escaping (_ account: String, _ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  683. NCCommunication.shared.searchLiteral(serverUrl: urlBase, depth: "infinity", literal: literal, showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, errorCode, errorDescription) in
  684. if errorCode == 0 {
  685. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (metadataFolder, metadatasFolder, metadatas) in
  686. // Update sub directories
  687. for metadata in metadatasFolder {
  688. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  689. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: serverUrl, account: account)
  690. }
  691. NCManageDatabase.shared.addMetadatas(metadatas)
  692. let metadatas = Array(metadatas.map { tableMetadata.init(value:$0) })
  693. completion(account, metadatas, errorCode, errorDescription)
  694. }
  695. } else {
  696. completion(account, nil, errorCode, errorDescription)
  697. }
  698. }
  699. }
  700. //MARK: - WebDav Create Folder
  701. @objc func createFolder(fileName: String, serverUrl: String, account: String, urlBase: String, overwrite: Bool = false, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  702. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: false, account: account, urlBase: urlBase)
  703. if isDirectoryEncrypted {
  704. #if !EXTENSION
  705. NCNetworkingE2EE.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, completion: completion)
  706. #endif
  707. } else {
  708. createFolderPlain(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: overwrite, completion: completion)
  709. }
  710. }
  711. private func createFolderPlain(fileName: String, serverUrl: String, account: String, urlBase: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  712. var fileNameFolder = CCUtility.removeForbiddenCharactersServer(fileName)!
  713. if (!overwrite) {
  714. fileNameFolder = NCUtilityFileSystem.shared.createFileName(fileNameFolder, serverUrl: serverUrl, account: account)
  715. }
  716. if fileNameFolder.count == 0 {
  717. return completion(0, "")
  718. }
  719. let fileNameFolderUrl = serverUrl + "/" + fileNameFolder
  720. NCCommunication.shared.createFolder(fileNameFolderUrl) { (account, ocId, date, errorCode, errorDescription) in
  721. if errorCode == 0 {
  722. self.readFile(serverUrlFileName: fileNameFolderUrl, account: account) { (account, metadataFolder, errorCode, errorDescription) in
  723. if errorCode == 0 {
  724. if let metadata = metadataFolder {
  725. NCManageDatabase.shared.addMetadata(metadata)
  726. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: fileNameFolderUrl, account: account)
  727. }
  728. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(metadataFolder?.ocId) {
  729. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCreateFolder, userInfo: ["ocId": metadata.ocId])
  730. }
  731. }
  732. completion(errorCode, errorDescription)
  733. }
  734. } else if errorCode == 405 && overwrite {
  735. completion(0, "")
  736. } else {
  737. completion(errorCode, errorDescription)
  738. }
  739. }
  740. }
  741. func createFolder(assets: [PHAsset], selector: String, useSubFolder: Bool, account: String, urlBase: String) -> Bool {
  742. let serverUrl = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: urlBase, account: account)
  743. let fileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  744. let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: urlBase, account: account)
  745. var result = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase)
  746. if useSubFolder && result {
  747. for dateSubFolder in CCUtility.createNameSubFolder(assets) {
  748. let fileName = (dateSubFolder as! NSString).lastPathComponent
  749. let serverUrl = ((autoUploadPath + "/" + (dateSubFolder as! String)) as NSString).deletingLastPathComponent
  750. result = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase)
  751. if !result { break }
  752. }
  753. }
  754. return result
  755. }
  756. private func createFolderWithSemaphore(fileName: String, serverUrl: String, account: String, urlBase: String) -> Bool {
  757. var result: Bool = false
  758. let semaphore = Semaphore()
  759. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: true) { (errorCode, errorDescription) in
  760. if errorCode == 0 { result = true }
  761. semaphore.continue()
  762. }
  763. if semaphore.wait() == .success { result = true }
  764. return result
  765. }
  766. //MARK: - WebDav Delete
  767. @objc func deleteMetadata(_ metadata: tableMetadata, onlyLocalCache: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  768. if (onlyLocalCache) {
  769. var metadatas = [metadata]
  770. if metadata.directory {
  771. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  772. metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND directory == false", metadata.account, serverUrl))
  773. }
  774. for metadata in metadatas {
  775. NCManageDatabase.shared.deleteVideo(metadata: metadata)
  776. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  777. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  778. if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  779. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadataLivePhoto.ocId))
  780. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadataLivePhoto.ocId))
  781. }
  782. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "classFile": metadata.classFile, "onlyLocalCache": true])
  783. }
  784. return completion(0, "")
  785. }
  786. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
  787. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  788. if isDirectoryEncrypted {
  789. #if !EXTENSION
  790. if metadataLive == nil {
  791. NCNetworkingE2EE.shared.deleteMetadata(metadata, completion: completion)
  792. } else {
  793. NCNetworkingE2EE.shared.deleteMetadata(metadataLive!) { (errorCode, errorDescription) in
  794. if errorCode == 0 {
  795. NCNetworkingE2EE.shared.deleteMetadata(metadata, completion: completion)
  796. } else {
  797. completion(errorCode, errorDescription)
  798. }
  799. }
  800. }
  801. #endif
  802. } else {
  803. if metadataLive == nil {
  804. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  805. } else {
  806. self.deleteMetadataPlain(metadataLive!, addCustomHeaders: nil) { (errorCode, errorDescription) in
  807. if errorCode == 0 {
  808. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  809. } else {
  810. completion(errorCode, errorDescription)
  811. }
  812. }
  813. }
  814. }
  815. }
  816. func deleteMetadataPlain(_ metadata: tableMetadata, addCustomHeaders: [String: String]?, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  817. // verify permission
  818. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanDelete)
  819. if metadata.permissions != "" && permission == false {
  820. return completion(NCGlobal.shared.errorInternalError, "_no_permission_delete_file_")
  821. }
  822. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  823. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName, customUserAgent: nil, addCustomHeaders: addCustomHeaders) { (account, errorCode, errorDescription) in
  824. if errorCode == 0 || errorCode == NCGlobal.shared.errorResourceNotFound {
  825. do {
  826. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  827. } catch { }
  828. NCManageDatabase.shared.deleteVideo(metadata: metadata)
  829. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  830. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  831. if metadata.directory {
  832. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account)
  833. }
  834. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "classFile": metadata.classFile, "onlyLocalCache": true])
  835. }
  836. completion(errorCode, errorDescription)
  837. }
  838. }
  839. //MARK: - WebDav Favorite
  840. @objc func favoriteMetadata(_ metadata: tableMetadata, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  841. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  842. favoriteMetadataPlain(metadataLive) { (errorCode, errorDescription) in
  843. if errorCode == 0 {
  844. self.favoriteMetadataPlain(metadata, completion: completion)
  845. } else {
  846. completion(errorCode, errorDescription)
  847. }
  848. }
  849. } else {
  850. favoriteMetadataPlain(metadata, completion: completion)
  851. }
  852. }
  853. private func favoriteMetadataPlain(_ metadata: tableMetadata, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  854. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, account: metadata.account)!
  855. let favorite = !metadata.favorite
  856. let ocId = metadata.ocId
  857. NCCommunication.shared.setFavorite(fileName: fileName, favorite: favorite) { (account, errorCode, errorDescription) in
  858. if errorCode == 0 && metadata.account == account {
  859. NCManageDatabase.shared.setMetadataFavorite(ocId: metadata.ocId, favorite: favorite)
  860. #if !EXTENSION
  861. if favorite {
  862. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorReadFile)
  863. }
  864. #endif
  865. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  866. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterFavoriteFile, userInfo: ["ocId": metadata.ocId])
  867. }
  868. }
  869. completion(errorCode, errorDescription)
  870. }
  871. }
  872. @objc func listingFavoritescompletion(selector: String, completion: @escaping (_ account: String, _ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  873. NCCommunication.shared.listingFavorites(showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, errorCode, errorDescription) in
  874. if errorCode == 0 {
  875. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (_, _, metadatas) in
  876. NCManageDatabase.shared.updateMetadatasFavorite(account: account, metadatas: metadatas)
  877. if selector != NCGlobal.shared.selectorListingFavorite {
  878. #if !EXTENSION
  879. for metadata in metadatas {
  880. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: selector)
  881. }
  882. #endif
  883. }
  884. completion(account, metadatas, errorCode, errorDescription)
  885. }
  886. } else {
  887. completion(account, nil, errorCode, errorDescription)
  888. }
  889. }
  890. }
  891. //MARK: - WebDav Rename
  892. @objc func renameMetadata(_ metadata: tableMetadata, fileNameNew: String, viewController: UIViewController?, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  893. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
  894. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  895. let fileNameNewLive = (fileNameNew as NSString).deletingPathExtension + ".mov"
  896. if isDirectoryEncrypted {
  897. #if !EXTENSION
  898. if metadataLive == nil {
  899. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, completion: completion)
  900. } else {
  901. NCNetworkingE2EE.shared.renameMetadata(metadataLive!, fileNameNew: fileNameNewLive) { (errorCode, errorDescription) in
  902. if errorCode == 0 {
  903. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, completion: completion)
  904. } else {
  905. completion(errorCode, errorDescription)
  906. }
  907. }
  908. }
  909. #endif
  910. } else {
  911. if metadataLive == nil {
  912. renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  913. } else {
  914. renameMetadataPlain(metadataLive!, fileNameNew: fileNameNewLive) { (errorCode, errorDescription) in
  915. if errorCode == 0 {
  916. self.renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  917. } else {
  918. completion(errorCode, errorDescription)
  919. }
  920. }
  921. }
  922. }
  923. }
  924. private func renameMetadataPlain(_ metadata: tableMetadata, fileNameNew: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  925. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  926. if !(metadata.permissions == "") && !permission {
  927. return completion(NCGlobal.shared.errorInternalError, "_no_permission_modify_file_")
  928. }
  929. guard let fileNameNew = CCUtility.removeForbiddenCharactersServer(fileNameNew) else {
  930. return completion(0, "")
  931. }
  932. if fileNameNew.count == 0 || fileNameNew == metadata.fileNameView {
  933. return completion(0, "")
  934. }
  935. let fileNamePath = metadata.serverUrl + "/" + metadata.fileName
  936. let fileNameToPath = metadata.serverUrl + "/" + fileNameNew
  937. let ocId = metadata.ocId
  938. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNamePath, serverUrlFileNameDestination: fileNameToPath, overwrite: false) { (account, errorCode, errorDescription) in
  939. if errorCode == 0 {
  940. NCManageDatabase.shared.renameMetadata(fileNameTo: fileNameNew, ocId: ocId)
  941. if metadata.directory {
  942. let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  943. let serverUrlTo = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: fileNameNew)!
  944. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  945. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, serverUrlTo: serverUrlTo, etag: "", ocId: nil, fileId: nil, encrypted: directory.e2eEncrypted, richWorkspace: nil, account: metadata.account)
  946. }
  947. } else {
  948. let ext = (metadata.fileName as NSString).pathExtension
  949. let extNew = (fileNameNew as NSString).pathExtension
  950. if ext != extNew {
  951. if let path = CCUtility.getDirectoryProviderStorageOcId(ocId) {
  952. NCUtilityFileSystem.shared.deleteFile(filePath: path)
  953. }
  954. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": metadata.serverUrl])
  955. } else {
  956. NCManageDatabase.shared.setLocalFile(ocId: ocId, fileName: fileNameNew, etag: nil)
  957. // Move file system
  958. let atPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + metadata.fileName
  959. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + fileNameNew
  960. do {
  961. try FileManager.default.moveItem(atPath: atPath, toPath: toPath)
  962. } catch { }
  963. }
  964. }
  965. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  966. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRenameFile, userInfo: ["ocId": metadata.ocId])
  967. }
  968. }
  969. completion(errorCode, errorDescription)
  970. }
  971. }
  972. //MARK: - WebDav Move
  973. @objc func moveMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  974. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  975. moveMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  976. if errorCode == 0 {
  977. self.moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  978. } else {
  979. completion(errorCode, errorDescription)
  980. }
  981. }
  982. } else {
  983. moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  984. }
  985. }
  986. private func moveMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  987. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  988. if !(metadata.permissions == "") && !permission {
  989. return completion(NCGlobal.shared.errorInternalError, "_no_permission_modify_file_")
  990. }
  991. let serverUrlFrom = metadata.serverUrl
  992. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  993. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  994. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  995. if errorCode == 0 {
  996. if metadata.directory {
  997. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: account)
  998. }
  999. NCManageDatabase.shared.moveMetadata(ocId: metadata.ocId, serverUrlTo: serverUrlTo)
  1000. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMoveFile, userInfo: ["ocId": metadata.ocId, "serverUrlFrom": serverUrlFrom])
  1001. }
  1002. completion(errorCode, errorDescription)
  1003. }
  1004. }
  1005. //MARK: - WebDav Copy
  1006. @objc func copyMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  1007. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  1008. copyMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  1009. if errorCode == 0 {
  1010. self.copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1011. } else {
  1012. completion(errorCode, errorDescription)
  1013. }
  1014. }
  1015. } else {
  1016. copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1017. }
  1018. }
  1019. private func copyMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  1020. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  1021. if !(metadata.permissions == "") && !permission {
  1022. return completion(NCGlobal.shared.errorInternalError, "_no_permission_modify_file_")
  1023. }
  1024. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  1025. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  1026. NCCommunication.shared.copyFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  1027. if errorCode == 0 {
  1028. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCopyFile, userInfo: ["ocId": metadata.ocId, "serverUrlTo": serverUrlTo])
  1029. }
  1030. completion(errorCode, errorDescription)
  1031. }
  1032. }
  1033. //MARK: - Direct Download
  1034. func getVideoUrl(metadata: tableMetadata, completition: @escaping (_ url: URL?)->()) {
  1035. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1036. completition(URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)))
  1037. } else {
  1038. NCCommunication.shared.getDirectDownload(fileId: metadata.fileId) { account, url, errorCode, errorDescription in
  1039. if errorCode == 0 && url != nil {
  1040. if let url = URL(string: url!) {
  1041. completition(url)
  1042. } else {
  1043. completition(nil)
  1044. }
  1045. } else {
  1046. completition(nil)
  1047. }
  1048. }
  1049. }
  1050. }
  1051. //MARK: - TEST API
  1052. /*
  1053. @objc public func getDirectDownload(urlBase: String, username: String, password: String, fileId: String, customUserAgent: String? = nil, completionHandler: @escaping (_ token: String?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  1054. let endpoint = "/ocs/v2.php/apps/dav/api/v1/direct"
  1055. let url:URLConvertible = try! (urlBase + endpoint).asURL() as URLConvertible
  1056. var headers: HTTPHeaders = [.authorization(username: username, password: password)]
  1057. if customUserAgent != nil {
  1058. headers.update(.userAgent(customUserAgent!))
  1059. }
  1060. //headers.update(.contentType("application/json"))
  1061. headers.update(name: "OCS-APIRequest", value: "true")
  1062. let method = HTTPMethod(rawValue: "POST")
  1063. let parameters = [
  1064. "fileId": fileId,
  1065. ]
  1066. AF.request(url, method: method, parameters: parameters, headers: headers).validate(statusCode: 200..<300).response { (response) in
  1067. debugPrint(response)
  1068. switch response.result {
  1069. case .failure(let error):
  1070. completionHandler(nil, 0, "")
  1071. case .success(let data):
  1072. if let data = data {
  1073. completionHandler("", 0, "")
  1074. } else {
  1075. completionHandler(nil, NSURLErrorBadServerResponse, NSLocalizedString("_error_decode_xml_", value: "Invalid response, error decode XML", comment: ""))
  1076. }
  1077. }
  1078. }
  1079. }
  1080. */
  1081. }