NCNetworking.swift 71 KB

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