NCNetworking.swift 73 KB

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