NCNetworking.swift 74 KB

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