NCNetworking.swift 74 KB

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