NCNetworking.swift 75 KB

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