NCNetworking.swift 74 KB

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