NCNetworking.swift 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450
  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) -> Void = { _ in }, completion: @escaping (_ errorCode: Int) -> Void) {
  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, _, 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. func uploadMetadata(_ metadata: tableMetadata) {
  319. // DETECT IF CHUNCK
  320. let chunckSize = CCUtility.getChunkSize() * 1000000
  321. if chunckSize > 0 && metadata.size > chunckSize {
  322. metadata.chunk = true
  323. metadata.session = NCCommunicationCommon.shared.sessionIdentifierUpload
  324. }
  325. // DETECT IF E2EE
  326. if CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase) {
  327. metadata.e2eEncrypted = true
  328. }
  329. NCManageDatabase.shared.addMetadata(metadata)
  330. let metadata = tableMetadata.init(value: metadata)
  331. NCCommunicationCommon.shared.writeLog("Upload file \(metadata.fileNameView) with Identifier \(metadata.assetLocalIdentifier) with size \(metadata.size) [CHUNCK \(metadata.chunk), E2EE \(metadata.e2eEncrypted)]")
  332. if metadata.e2eEncrypted {
  333. #if !EXTENSION_FILE_PROVIDER_EXTENSION
  334. NCNetworkingE2EE.shared.upload(metadata: metadata, start: start) { errorCode, errorDescription in
  335. DispatchQueue.main.async {
  336. completion(errorCode, errorDescription)
  337. }
  338. }
  339. #endif
  340. } else if metadata.chunk {
  341. uploadChunkedFile(metadata: metadata, start: start) { errorCode, errorDescription in
  342. DispatchQueue.main.async {
  343. completion(errorCode, errorDescription)
  344. }
  345. }
  346. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  347. uploadFile(metadata: metadata, start: start) { errorCode, errorDescription in
  348. DispatchQueue.main.async {
  349. completion(errorCode, errorDescription)
  350. }
  351. }
  352. } else {
  353. uploadFileInBackground(metadata: metadata, start: start) { errorCode, errorDescription in
  354. DispatchQueue.main.async {
  355. completion(errorCode, errorDescription)
  356. }
  357. }
  358. }
  359. }
  360. let metadata = tableMetadata.init(value: metadata)
  361. if metadata.assetLocalIdentifier.isEmpty {
  362. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  363. let results = NCCommunicationCommon.shared.getInternalType(fileName: metadata.fileNameView, mimeType: metadata.contentType, directory: false)
  364. metadata.contentType = results.mimeType
  365. metadata.iconName = results.iconName
  366. metadata.classFile = results.classFile
  367. if let date = NCUtilityFileSystem.shared.getFileCreationDate(filePath: fileNameLocalPath) {
  368. metadata.creationDate = date
  369. }
  370. if let date = NCUtilityFileSystem.shared.getFileModificationDate(filePath: fileNameLocalPath) {
  371. metadata.date = date
  372. }
  373. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath)
  374. uploadMetadata(metadata)
  375. } else {
  376. CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadata) { extractMetadata, fileNamePath in
  377. guard let metadata = extractMetadata else {
  378. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  379. return completion(NCGlobal.shared.errorInternalError, "Internal error")
  380. }
  381. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  382. NCUtilityFileSystem.shared.moveFileInBackground(atPath: fileNamePath!, toPath: fileNameLocalPath)
  383. uploadMetadata(metadata)
  384. }
  385. }
  386. }
  387. private func uploadFile(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  388. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  389. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  390. var uploadTask: URLSessionTask?
  391. let description = metadata.ocId
  392. NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.creationDate as Date, dateModificationFile: metadata.date as Date, customUserAgent: nil, addCustomHeaders: nil, requestHandler: { request in
  393. self.uploadRequest[fileNameLocalPath] = request
  394. }, taskHandler: { task in
  395. uploadTask = task
  396. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  397. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId": metadata.ocId])
  398. start()
  399. }, progressHandler: { progress in
  400. #if !EXTENSION
  401. // add progress ocid
  402. let progressType = NCGlobal.progressType(progress: Float(progress.fractionCompleted), totalBytes: progress.totalUnitCount, totalBytesExpected: progress.completedUnitCount)
  403. DispatchQueue.main.async { (UIApplication.shared.delegate as! AppDelegate).listProgress[metadata.ocId] = progressType }
  404. #endif
  405. NotificationCenter.default.postOnMainThread(
  406. name: NCGlobal.shared.notificationCenterProgressTask,
  407. userInfo: [
  408. "account": metadata.account,
  409. "ocId": metadata.ocId,
  410. "fileName": metadata.fileName,
  411. "serverUrl": metadata.serverUrl,
  412. "status": NSNumber(value: NCGlobal.shared.metadataStatusInUpload),
  413. "progress": NSNumber(value: progress.fractionCompleted),
  414. "totalBytes": NSNumber(value: progress.totalUnitCount),
  415. "totalBytesExpected": NSNumber(value: progress.completedUnitCount)])
  416. }) { _, ocId, etag, date, size, _, _, errorCode, errorDescription in
  417. self.uploadRequest[fileNameLocalPath] = nil
  418. if let uploadTask = uploadTask {
  419. self.uploadComplete(fileName: metadata.fileName, serverUrl: metadata.serverUrl, ocId: ocId, etag: etag, date: date, size: size, description: description, task: uploadTask, errorCode: errorCode, errorDescription: errorDescription)
  420. }
  421. completion(errorCode, errorDescription)
  422. }
  423. }
  424. private func uploadFileInBackground(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  425. var session: URLSession?
  426. let metadata = tableMetadata.init(value: metadata)
  427. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  428. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  429. if metadata.session == sessionIdentifierBackground || metadata.session == sessionIdentifierBackgroundExtension {
  430. session = sessionManagerBackground
  431. } else if metadata.session == sessionIdentifierBackgroundWWan {
  432. session = sessionManagerBackgroundWWan
  433. }
  434. start()
  435. // Check file dim > 0
  436. if NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath) == 0 && metadata.size != 0 {
  437. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  438. completion(NCGlobal.shared.errorResourceNotFound, NSLocalizedString("_error_not_found_", value: "The requested resource could not be found", comment: ""))
  439. } else {
  440. 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!) {
  441. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  442. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId": metadata.ocId])
  443. completion(0, "")
  444. } else {
  445. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  446. completion(NCGlobal.shared.errorInternalError, "task null")
  447. }
  448. }
  449. }
  450. func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  451. guard delegate == nil else {
  452. delegate?.uploadComplete?(fileName: fileName, serverUrl: serverUrl, ocId: ocId, etag: etag, date: date, size: size, description: description, task: task, errorCode: errorCode, errorDescription: errorDescription)
  453. return
  454. }
  455. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(description) else { return }
  456. let ocIdTemp = metadata.ocId
  457. var errorDescription = errorDescription
  458. if errorCode == 0, let ocId = ocId, size == metadata.size {
  459. let metadata = tableMetadata.init(value: metadata)
  460. NCUtilityFileSystem.shared.moveFileInBackground(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
  461. metadata.uploadDate = date ?? NSDate()
  462. metadata.etag = etag ?? ""
  463. metadata.ocId = ocId
  464. if let fileId = NCUtility.shared.ocIdToFileId(ocId: ocId) {
  465. metadata.fileId = fileId
  466. }
  467. metadata.session = ""
  468. metadata.sessionError = ""
  469. metadata.sessionTaskIdentifier = 0
  470. metadata.status = NCGlobal.shared.metadataStatusNormal
  471. // Delete Asset on Photos album
  472. if CCUtility.getRemovePhotoCameraRoll() && !metadata.assetLocalIdentifier.isEmpty {
  473. metadata.deleteAssetLocalIdentifier = true
  474. }
  475. if CCUtility.getDisableLocalCacheAfterUpload() {
  476. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  477. } else {
  478. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  479. }
  480. NCManageDatabase.shared.addMetadata(metadata)
  481. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  482. #if !EXTENSION
  483. self.getOcIdInBackgroundSession { listOcId in
  484. if listOcId.count == 0 && self.uploadRequest.count == 0 {
  485. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  486. appDelegate.networkingProcessUpload?.startProcess()
  487. }
  488. }
  489. CCUtility.setExif(metadata) { _, _, _, _, _ in }
  490. #endif
  491. NCCommunicationCommon.shared.writeLog("Upload complete " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)")
  492. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "ocIdTemp": ocIdTemp, "errorCode": errorCode, "errorDescription": ""])
  493. } else {
  494. if errorCode == NSURLErrorCancelled || errorCode == NCGlobal.shared.errorRequestExplicityCancelled {
  495. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  496. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  497. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  498. } else if errorCode == 401 || errorCode == 403 {
  499. #if !EXTENSION
  500. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account, errorCode: errorCode, errorDescription: errorDescription)
  501. #endif
  502. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  503. } else {
  504. if size == 0 {
  505. errorDescription = "File length 0"
  506. NCCommunicationCommon.shared.writeLog("Upload error 0 length " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)")
  507. }
  508. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  509. }
  510. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "ocIdTemp": ocIdTemp, "errorCode": errorCode, "errorDescription": ""])
  511. }
  512. #if !EXTENSION
  513. DispatchQueue.main.async { (UIApplication.shared.delegate as! AppDelegate).listProgress[metadata.ocId] = nil }
  514. #endif
  515. // Delete
  516. self.uploadMetadataInBackground[fileName + serverUrl] = nil
  517. }
  518. func uploadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  519. delegate?.uploadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  520. var metadata: tableMetadata?
  521. let description: String = task.taskDescription ?? ""
  522. if let metadataTmp = self.uploadMetadataInBackground[fileName+serverUrl] {
  523. metadata = metadataTmp
  524. } else if let metadataTmp = NCManageDatabase.shared.getMetadataFromOcId(description) {
  525. self.uploadMetadataInBackground[fileName+serverUrl] = metadataTmp
  526. metadata = metadataTmp
  527. }
  528. if let metadata = metadata {
  529. #if !EXTENSION
  530. // add progress ocid
  531. let progressType = NCGlobal.progressType(progress: progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected)
  532. DispatchQueue.main.async { (UIApplication.shared.delegate as! AppDelegate).listProgress[metadata.ocId] = progressType }
  533. #endif
  534. NotificationCenter.default.postOnMainThread(
  535. name: NCGlobal.shared.notificationCenterProgressTask,
  536. userInfo: [
  537. "account": metadata.account,
  538. "ocId": metadata.ocId,
  539. "fileName": metadata.fileName,
  540. "serverUrl": serverUrl,
  541. "status": NSNumber(value: NCGlobal.shared.metadataStatusInUpload),
  542. "progress": NSNumber(value: progress),
  543. "totalBytes": NSNumber(value: totalBytes),
  544. "totalBytesExpected": NSNumber(value: totalBytesExpected)])
  545. }
  546. }
  547. func getOcIdInBackgroundSession(completion: @escaping (_ listOcId: [String]) -> Void) {
  548. var listOcId: [String] = []
  549. sessionManagerBackground.getAllTasks(completionHandler: { tasks in
  550. for task in tasks {
  551. listOcId.append(task.description)
  552. }
  553. self.sessionManagerBackgroundWWan.getAllTasks(completionHandler: { tasks in
  554. for task in tasks {
  555. listOcId.append(task.description)
  556. }
  557. completion(listOcId)
  558. })
  559. })
  560. }
  561. // MARK: - Transfer (Download Upload)
  562. @objc func cancelTransferMetadata(_ metadata: tableMetadata, completion: @escaping () -> Void) {
  563. let metadata = tableMetadata.init(value: metadata)
  564. #if !EXTENSION
  565. // removed progress ocid
  566. DispatchQueue.main.async { (UIApplication.shared.delegate as! AppDelegate).listProgress[metadata.ocId] = nil }
  567. #endif
  568. if metadata.session.count == 0 {
  569. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  570. return completion()
  571. }
  572. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierDownload {
  573. NCNetworking.shared.cancelDownload(ocId: metadata.ocId, serverUrl: metadata.serverUrl, fileNameView: metadata.fileNameView)
  574. return completion()
  575. }
  576. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  577. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else { return }
  578. if let request = uploadRequest[fileNameLocalPath] {
  579. request.cancel()
  580. } else {
  581. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  582. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  583. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  584. }
  585. return completion()
  586. }
  587. var session: URLSession?
  588. if metadata.session == NCNetworking.shared.sessionIdentifierBackground {
  589. session = NCNetworking.shared.sessionManagerBackground
  590. } else if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundWWan {
  591. session = NCNetworking.shared.sessionManagerBackgroundWWan
  592. }
  593. if session == nil {
  594. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  595. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  596. return completion()
  597. }
  598. session?.getTasksWithCompletionHandler { _, uploadTasks, _ in
  599. var cancel = false
  600. if metadata.session.count > 0 && metadata.session.contains("upload") {
  601. for task in uploadTasks {
  602. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  603. task.cancel()
  604. cancel = true
  605. }
  606. }
  607. if cancel == false {
  608. do {
  609. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  610. } catch { }
  611. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  612. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  613. }
  614. }
  615. completion()
  616. }
  617. }
  618. @objc func cancelAllTransfer(account: String, completion: @escaping () -> Void) {
  619. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", account, NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusUploadError))
  620. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status != %d", NCGlobal.shared.metadataStatusNormal))
  621. var counter = 0
  622. for metadata in metadatas {
  623. counter += 1
  624. if metadata.status == NCGlobal.shared.metadataStatusWaitDownload || metadata.status == NCGlobal.shared.metadataStatusDownloadError {
  625. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  626. }
  627. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  628. self.cancelTransferMetadata(metadata) {
  629. if counter == metadatas.count {
  630. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  631. completion()
  632. }
  633. }
  634. }
  635. }
  636. }
  637. #if !EXTENSION
  638. NCOperationQueue.shared.downloadCancelAll()
  639. #endif
  640. }
  641. func cancelAllDownloadTransfer() {
  642. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status != %d", NCGlobal.shared.metadataStatusNormal))
  643. for metadata in metadatas {
  644. if metadata.status == NCGlobal.shared.metadataStatusWaitDownload || metadata.status == NCGlobal.shared.metadataStatusDownloadError {
  645. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  646. }
  647. if metadata.status == NCGlobal.shared.metadataStatusDownloading && metadata.session == NCCommunicationCommon.shared.sessionIdentifierDownload {
  648. cancelDownload(ocId: metadata.ocId, serverUrl: metadata.serverUrl, fileNameView: metadata.fileNameView)
  649. }
  650. }
  651. #if !EXTENSION
  652. NCOperationQueue.shared.downloadCancelAll()
  653. #endif
  654. }
  655. // MARK: - WebDav Read file, folder
  656. @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) {
  657. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { account, files, _, errorCode, errorDescription in
  658. if errorCode == 0 {
  659. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: true, account: account) { metadataFolder, metadatasFolder, metadatas in
  660. // Add metadata folder
  661. NCManageDatabase.shared.addMetadata(tableMetadata.init(value: metadataFolder))
  662. // Update directory
  663. 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)
  664. NCManageDatabase.shared.setDirectory(richWorkspace: metadataFolder.richWorkspace, serverUrl: serverUrl, account: metadataFolder.account)
  665. // Update sub directories NO Update richWorkspace
  666. for metadata in metadatasFolder {
  667. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  668. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: serverUrl, account: account)
  669. }
  670. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, NCGlobal.shared.metadataStatusNormal))
  671. let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareEtagLocal: true)
  672. completion(account, metadataFolder, metadatas, metadatasChanged.metadatasUpdate, metadatasChanged.metadatasLocalUpdate, metadatasChanged.metadatasDelete, errorCode, "")
  673. }
  674. } else {
  675. completion(account, nil, nil, nil, nil, nil, errorCode, errorDescription)
  676. }
  677. }
  678. }
  679. @objc func readFile(serverUrlFileName: String, account: String, queue: DispatchQueue = NCCommunicationCommon.shared.backgroundQueue, completion: @escaping (_ account: String, _ metadata: tableMetadata?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  680. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: queue) { account, files, _, errorCode, errorDescription in
  681. if errorCode == 0 && files.count == 1 {
  682. let file = files[0]
  683. let isEncrypted = CCUtility.isFolderEncrypted(file.serverUrl, e2eEncrypted: file.e2eEncrypted, account: account, urlBase: file.urlBase)
  684. let metadata = NCManageDatabase.shared.convertNCFileToMetadata(file, isEncrypted: isEncrypted, account: account)
  685. completion(account, metadata, errorCode, errorDescription)
  686. } else {
  687. completion(account, nil, errorCode, errorDescription)
  688. }
  689. }
  690. }
  691. // MARK: - WebDav Search
  692. @objc func searchFiles(urlBase: String, user: String, literal: String, completion: @escaping (_ account: String, _ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  693. NCCommunication.shared.searchLiteral(serverUrl: urlBase, depth: "infinity", literal: literal, showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { account, files, errorCode, errorDescription in
  694. if errorCode == 0 {
  695. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { _, metadatasFolder, metadatas in
  696. // Update sub directories
  697. for metadata in metadatasFolder {
  698. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  699. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: serverUrl, account: account)
  700. }
  701. NCManageDatabase.shared.addMetadatas(metadatas)
  702. let metadatas = Array(metadatas.map { tableMetadata.init(value: $0) })
  703. completion(account, metadatas, errorCode, errorDescription)
  704. }
  705. } else {
  706. completion(account, nil, errorCode, errorDescription)
  707. }
  708. }
  709. }
  710. // MARK: - WebDav Create Folder
  711. @objc func createFolder(fileName: String, serverUrl: String, account: String, urlBase: String, overwrite: Bool = false, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  712. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: false, account: account, urlBase: urlBase)
  713. let fileName = fileName.trimmingCharacters(in: .whitespacesAndNewlines)
  714. if isDirectoryEncrypted {
  715. #if !EXTENSION
  716. NCNetworkingE2EE.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, completion: completion)
  717. #endif
  718. } else {
  719. createFolderPlain(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: overwrite, completion: completion)
  720. }
  721. }
  722. private func createFolderPlain(fileName: String, serverUrl: String, account: String, urlBase: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  723. var fileNameFolder = CCUtility.removeForbiddenCharactersServer(fileName)!
  724. if !overwrite {
  725. fileNameFolder = NCUtilityFileSystem.shared.createFileName(fileNameFolder, serverUrl: serverUrl, account: account)
  726. }
  727. if fileNameFolder.count == 0 {
  728. return completion(0, "")
  729. }
  730. let fileNameFolderUrl = serverUrl + "/" + fileNameFolder
  731. NCCommunication.shared.createFolder(fileNameFolderUrl) { account, ocId, _, errorCode, errorDescription in
  732. if errorCode == 0 {
  733. self.readFile(serverUrlFileName: fileNameFolderUrl, account: account) { account, metadataFolder, errorCode, errorDescription in
  734. if errorCode == 0 {
  735. if let metadata = metadataFolder {
  736. NCManageDatabase.shared.addMetadata(metadata)
  737. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: fileNameFolderUrl, account: account)
  738. }
  739. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(metadataFolder?.ocId) {
  740. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCreateFolder, userInfo: ["ocId": metadata.ocId])
  741. }
  742. }
  743. completion(errorCode, errorDescription)
  744. }
  745. } else if errorCode == 405 && overwrite {
  746. completion(0, "")
  747. } else {
  748. completion(errorCode, errorDescription)
  749. }
  750. }
  751. }
  752. func createFolder(assets: [PHAsset], selector: String, useSubFolder: Bool, account: String, urlBase: String) -> Bool {
  753. let serverUrl = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: urlBase, account: account)
  754. let fileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  755. let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: urlBase, account: account)
  756. var result = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase)
  757. if useSubFolder && result {
  758. for dateSubFolder in CCUtility.createNameSubFolder(assets) {
  759. let fileName = (dateSubFolder as! NSString).lastPathComponent
  760. let serverUrl = ((autoUploadPath + "/" + (dateSubFolder as! String)) as NSString).deletingLastPathComponent
  761. result = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase)
  762. if !result { break }
  763. }
  764. }
  765. return result
  766. }
  767. private func createFolderWithSemaphore(fileName: String, serverUrl: String, account: String, urlBase: String) -> Bool {
  768. var result: Bool = false
  769. let semaphore = Semaphore()
  770. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: true) { errorCode, _ in
  771. if errorCode == 0 { result = true }
  772. semaphore.continue()
  773. }
  774. if semaphore.wait() == .success { result = true }
  775. return result
  776. }
  777. // MARK: - WebDav Delete
  778. @objc func deleteMetadata(_ metadata: tableMetadata, onlyLocalCache: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  779. if onlyLocalCache {
  780. var metadatas = [metadata]
  781. if metadata.directory {
  782. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  783. metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND directory == false", metadata.account, serverUrl))
  784. }
  785. for metadata in metadatas {
  786. NCManageDatabase.shared.deleteVideo(metadata: metadata)
  787. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  788. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  789. if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  790. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadataLivePhoto.ocId))
  791. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadataLivePhoto.ocId))
  792. }
  793. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "classFile": metadata.classFile, "onlyLocalCache": true])
  794. }
  795. return completion(0, "")
  796. }
  797. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
  798. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  799. if isDirectoryEncrypted {
  800. #if !EXTENSION
  801. if metadataLive == nil {
  802. NCNetworkingE2EE.shared.deleteMetadata(metadata, completion: completion)
  803. } else {
  804. NCNetworkingE2EE.shared.deleteMetadata(metadataLive!) { errorCode, errorDescription in
  805. if errorCode == 0 {
  806. NCNetworkingE2EE.shared.deleteMetadata(metadata, completion: completion)
  807. } else {
  808. completion(errorCode, errorDescription)
  809. }
  810. }
  811. }
  812. #endif
  813. } else {
  814. if metadataLive == nil {
  815. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  816. } else {
  817. self.deleteMetadataPlain(metadataLive!, addCustomHeaders: nil) { errorCode, errorDescription in
  818. if errorCode == 0 {
  819. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  820. } else {
  821. completion(errorCode, errorDescription)
  822. }
  823. }
  824. }
  825. }
  826. }
  827. func deleteMetadataPlain(_ metadata: tableMetadata, addCustomHeaders: [String: String]?, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  828. // verify permission
  829. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanDelete)
  830. if metadata.permissions != "" && permission == false {
  831. return completion(NCGlobal.shared.errorInternalError, "_no_permission_delete_file_")
  832. }
  833. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  834. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName, customUserAgent: nil, addCustomHeaders: addCustomHeaders) { account, errorCode, errorDescription in
  835. if errorCode == 0 || errorCode == NCGlobal.shared.errorResourceNotFound {
  836. do {
  837. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  838. } catch { }
  839. NCManageDatabase.shared.deleteVideo(metadata: metadata)
  840. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  841. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  842. if metadata.directory {
  843. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account)
  844. }
  845. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "classFile": metadata.classFile, "onlyLocalCache": true])
  846. }
  847. completion(errorCode, errorDescription)
  848. }
  849. }
  850. // MARK: - WebDav Favorite
  851. @objc func favoriteMetadata(_ metadata: tableMetadata, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  852. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  853. favoriteMetadataPlain(metadataLive) { errorCode, errorDescription in
  854. if errorCode == 0 {
  855. self.favoriteMetadataPlain(metadata, completion: completion)
  856. } else {
  857. completion(errorCode, errorDescription)
  858. }
  859. }
  860. } else {
  861. favoriteMetadataPlain(metadata, completion: completion)
  862. }
  863. }
  864. private func favoriteMetadataPlain(_ metadata: tableMetadata, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  865. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, account: metadata.account)!
  866. let favorite = !metadata.favorite
  867. let ocId = metadata.ocId
  868. NCCommunication.shared.setFavorite(fileName: fileName, favorite: favorite) { account, errorCode, errorDescription in
  869. if errorCode == 0 && metadata.account == account {
  870. NCManageDatabase.shared.setMetadataFavorite(ocId: metadata.ocId, favorite: favorite)
  871. #if !EXTENSION
  872. if favorite {
  873. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorReadFile)
  874. }
  875. #endif
  876. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  877. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterFavoriteFile, userInfo: ["ocId": metadata.ocId])
  878. }
  879. }
  880. completion(errorCode, errorDescription)
  881. }
  882. }
  883. @objc func listingFavoritescompletion(selector: String, completion: @escaping (_ account: String, _ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  884. NCCommunication.shared.listingFavorites(showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { account, files, errorCode, errorDescription in
  885. if errorCode == 0 {
  886. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { _, _, metadatas in
  887. NCManageDatabase.shared.updateMetadatasFavorite(account: account, metadatas: metadatas)
  888. if selector != NCGlobal.shared.selectorListingFavorite {
  889. #if !EXTENSION
  890. for metadata in metadatas {
  891. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: selector)
  892. }
  893. #endif
  894. }
  895. completion(account, metadatas, errorCode, errorDescription)
  896. }
  897. } else {
  898. completion(account, nil, errorCode, errorDescription)
  899. }
  900. }
  901. }
  902. // MARK: - Lock Files
  903. @objc func lockUnlockFile(_ metadata: tableMetadata, shoulLock: Bool) {
  904. NCCommunication.shared.lockUnlockFile(serverUrlFileName: metadata.serverUrl + "/" + metadata.fileName, shouldLock: shoulLock) { errorCode, errorDescription in
  905. // 0: lock was successful; 412: lock did not change, no error, refresh
  906. guard errorCode == 0 || errorCode == 412 else {
  907. NCContentPresenter.shared.messageNotification(metadata.fileName, description: "_files_lock_error_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode, priority: .max)
  908. return
  909. }
  910. NCNetworking.shared.readFile(serverUrlFileName: metadata.serverUrl + "/" + metadata.fileName, account: metadata.account) { account, metadata, errorCode, errorDescription in
  911. guard errorCode == 0, let metadata = metadata else { return }
  912. NCManageDatabase.shared.addMetadata(metadata)
  913. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource)
  914. }
  915. }
  916. }
  917. // MARK: - WebDav Rename
  918. @objc func renameMetadata(_ metadata: tableMetadata, fileNameNew: String, viewController: UIViewController?, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
  919. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
  920. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  921. let fileNameNew = fileNameNew.trimmingCharacters(in: .whitespacesAndNewlines)
  922. let fileNameNewLive = (fileNameNew as NSString).deletingPathExtension + ".mov"
  923. if isDirectoryEncrypted {
  924. #if !EXTENSION
  925. if metadataLive == nil {
  926. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, completion: completion)
  927. } else {
  928. NCNetworkingE2EE.shared.renameMetadata(metadataLive!, fileNameNew: fileNameNewLive) { errorCode, errorDescription in
  929. if errorCode == 0 {
  930. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, completion: completion)
  931. } else {
  932. completion(errorCode, errorDescription)
  933. }
  934. }
  935. }
  936. #endif
  937. } else {
  938. if metadataLive == nil {
  939. renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  940. } else {
  941. renameMetadataPlain(metadataLive!, fileNameNew: fileNameNewLive) { errorCode, errorDescription in
  942. if errorCode == 0 {
  943. self.renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  944. } else {
  945. completion(errorCode, errorDescription)
  946. }
  947. }
  948. }
  949. }
  950. }
  951. private func renameMetadataPlain(_ metadata: tableMetadata, fileNameNew: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
  952. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  953. if !(metadata.permissions == "") && !permission {
  954. return completion(NCGlobal.shared.errorInternalError, "_no_permission_modify_file_")
  955. }
  956. guard let fileNameNew = CCUtility.removeForbiddenCharactersServer(fileNameNew) else {
  957. return completion(0, "")
  958. }
  959. if fileNameNew.count == 0 || fileNameNew == metadata.fileNameView {
  960. return completion(0, "")
  961. }
  962. let fileNamePath = metadata.serverUrl + "/" + metadata.fileName
  963. let fileNameToPath = metadata.serverUrl + "/" + fileNameNew
  964. let ocId = metadata.ocId
  965. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNamePath, serverUrlFileNameDestination: fileNameToPath, overwrite: false) { account, errorCode, errorDescription in
  966. if errorCode == 0 {
  967. NCManageDatabase.shared.renameMetadata(fileNameTo: fileNameNew, ocId: ocId)
  968. if metadata.directory {
  969. let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  970. let serverUrlTo = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: fileNameNew)!
  971. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  972. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, serverUrlTo: serverUrlTo, etag: "", ocId: nil, fileId: nil, encrypted: directory.e2eEncrypted, richWorkspace: nil, account: metadata.account)
  973. }
  974. } else {
  975. let ext = (metadata.fileName as NSString).pathExtension
  976. let extNew = (fileNameNew as NSString).pathExtension
  977. if ext != extNew {
  978. if let path = CCUtility.getDirectoryProviderStorageOcId(ocId) {
  979. NCUtilityFileSystem.shared.deleteFile(filePath: path)
  980. }
  981. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": metadata.serverUrl])
  982. } else {
  983. NCManageDatabase.shared.setLocalFile(ocId: ocId, fileName: fileNameNew, etag: nil)
  984. // Move file system
  985. let atPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + metadata.fileName
  986. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + fileNameNew
  987. do {
  988. try FileManager.default.moveItem(atPath: atPath, toPath: toPath)
  989. } catch { }
  990. }
  991. }
  992. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  993. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRenameFile, userInfo: ["ocId": metadata.ocId])
  994. }
  995. }
  996. completion(errorCode, errorDescription)
  997. }
  998. }
  999. // MARK: - WebDav Move
  1000. @objc func moveMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
  1001. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  1002. moveMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { errorCode, errorDescription in
  1003. if errorCode == 0 {
  1004. self.moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1005. } else {
  1006. completion(errorCode, errorDescription)
  1007. }
  1008. }
  1009. } else {
  1010. moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1011. }
  1012. }
  1013. private func moveMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
  1014. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  1015. if !(metadata.permissions == "") && !permission {
  1016. return completion(NCGlobal.shared.errorInternalError, "_no_permission_modify_file_")
  1017. }
  1018. let serverUrlFrom = metadata.serverUrl
  1019. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  1020. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  1021. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { account, errorCode, errorDescription in
  1022. if errorCode == 0 {
  1023. if metadata.directory {
  1024. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: account)
  1025. }
  1026. NCManageDatabase.shared.moveMetadata(ocId: metadata.ocId, serverUrlTo: serverUrlTo)
  1027. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMoveFile, userInfo: ["ocId": metadata.ocId, "serverUrlFrom": serverUrlFrom])
  1028. }
  1029. completion(errorCode, errorDescription)
  1030. }
  1031. }
  1032. // MARK: - WebDav Copy
  1033. @objc func copyMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
  1034. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  1035. copyMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { errorCode, errorDescription in
  1036. if errorCode == 0 {
  1037. self.copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1038. } else {
  1039. completion(errorCode, errorDescription)
  1040. }
  1041. }
  1042. } else {
  1043. copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1044. }
  1045. }
  1046. private func copyMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
  1047. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  1048. if !(metadata.permissions == "") && !permission {
  1049. return completion(NCGlobal.shared.errorInternalError, "_no_permission_modify_file_")
  1050. }
  1051. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  1052. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  1053. NCCommunication.shared.copyFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { _, errorCode, errorDescription in
  1054. if errorCode == 0 {
  1055. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCopyFile, userInfo: ["ocId": metadata.ocId, "serverUrlTo": serverUrlTo])
  1056. }
  1057. completion(errorCode, errorDescription)
  1058. }
  1059. }
  1060. // MARK: - Direct Download
  1061. func getVideoUrl(metadata: tableMetadata, completition: @escaping (_ url: URL?) -> Void) {
  1062. if CCUtility.fileProviderStorageExists(metadata) {
  1063. completition(URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)))
  1064. } else {
  1065. NCCommunication.shared.getDirectDownload(fileId: metadata.fileId) { _, url, errorCode, _ in
  1066. if errorCode == 0 && url != nil {
  1067. if let url = URL(string: url!) {
  1068. completition(url)
  1069. } else {
  1070. completition(nil)
  1071. }
  1072. } else {
  1073. completition(nil)
  1074. }
  1075. }
  1076. }
  1077. }
  1078. // MARK: - TEST API
  1079. /*
  1080. @objc public func getDirectDownload(urlBase: String, username: String, password: String, fileId: String, customUserAgent: String? = nil, completionHandler: @escaping (_ token: String?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  1081. let endpoint = "/ocs/v2.php/apps/dav/api/v1/direct"
  1082. let url:URLConvertible = try! (urlBase + endpoint).asURL() as URLConvertible
  1083. var headers: HTTPHeaders = [.authorization(username: username, password: password)]
  1084. if customUserAgent != nil {
  1085. headers.update(.userAgent(customUserAgent!))
  1086. }
  1087. //headers.update(.contentType("application/json"))
  1088. headers.update(name: "OCS-APIRequest", value: "true")
  1089. let method = HTTPMethod(rawValue: "POST")
  1090. let parameters = [
  1091. "fileId": fileId,
  1092. ]
  1093. AF.request(url, method: method, parameters: parameters, headers: headers).validate(statusCode: 200..<300).response { (response) in
  1094. debugPrint(response)
  1095. switch response.result {
  1096. case .failure(let error):
  1097. completionHandler(nil, 0, "")
  1098. case .success(let data):
  1099. if let data = data {
  1100. completionHandler("", 0, "")
  1101. } else {
  1102. completionHandler(nil, NSURLErrorBadServerResponse, NSLocalizedString("_error_decode_xml_", value: "Invalid response, error decode XML", comment: ""))
  1103. }
  1104. }
  1105. }
  1106. }
  1107. */
  1108. }