NCNetworking.swift 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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 Foundation
  24. import OpenSSL
  25. import NCCommunication
  26. import Alamofire
  27. import Queuer
  28. @objc public protocol NCNetworkingDelegate {
  29. @objc optional func downloadProgress(_ progress: Double, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask)
  30. @objc optional func uploadProgress(_ progress: Double, 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: Double, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String)
  32. @objc optional func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String)
  33. }
  34. @objc class NCNetworking: NSObject, NCCommunicationCommonDelegate {
  35. @objc public static let shared: NCNetworking = {
  36. let instance = NCNetworking()
  37. return instance
  38. }()
  39. var delegate: NCNetworkingDelegate?
  40. var lastReachability: Bool = true
  41. var downloadRequest: [String: DownloadRequest] = [:]
  42. var uploadRequest: [String: UploadRequest] = [:]
  43. var uploadMetadata: [String: tableMetadata] = [:]
  44. @objc public let sessionMaximumConnectionsPerHost = 5
  45. @objc public let sessionIdentifierBackground: String = "com.nextcloud.session.upload.background"
  46. @objc public let sessionIdentifierBackgroundWWan: String = "com.nextcloud.session.upload.backgroundWWan"
  47. @objc public let sessionIdentifierBackgroundExtension: String = "com.nextcloud.session.upload.extension"
  48. @objc public lazy var sessionManagerBackground: URLSession = {
  49. let configuration = URLSessionConfiguration.background(withIdentifier: sessionIdentifierBackground)
  50. configuration.allowsCellularAccess = true
  51. configuration.sessionSendsLaunchEvents = true
  52. configuration.isDiscretionary = false
  53. configuration.httpMaximumConnectionsPerHost = sessionMaximumConnectionsPerHost
  54. configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
  55. let session = URLSession(configuration: configuration, delegate: NCCommunicationBackground.shared, delegateQueue: OperationQueue.main)
  56. return session
  57. }()
  58. @objc public lazy var sessionManagerBackgroundWWan: URLSession = {
  59. let configuration = URLSessionConfiguration.background(withIdentifier: sessionIdentifierBackgroundWWan)
  60. configuration.allowsCellularAccess = false
  61. configuration.sessionSendsLaunchEvents = true
  62. configuration.isDiscretionary = false
  63. configuration.httpMaximumConnectionsPerHost = sessionMaximumConnectionsPerHost
  64. configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
  65. let session = URLSession(configuration: configuration, delegate: NCCommunicationBackground.shared, delegateQueue: OperationQueue.main)
  66. return session
  67. }()
  68. @objc public lazy var sessionManagerBackgroundExtension: URLSession = {
  69. let configuration = URLSessionConfiguration.background(withIdentifier: sessionIdentifierBackgroundExtension)
  70. configuration.allowsCellularAccess = true
  71. configuration.sessionSendsLaunchEvents = true
  72. configuration.isDiscretionary = false
  73. configuration.httpMaximumConnectionsPerHost = sessionMaximumConnectionsPerHost
  74. configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
  75. configuration.sharedContainerIdentifier = NCBrandOptions.sharedInstance.capabilitiesGroups
  76. let session = URLSession(configuration: configuration, delegate: NCCommunicationBackground.shared, delegateQueue: OperationQueue.main)
  77. return session
  78. }()
  79. //MARK: - init
  80. override init() {
  81. super.init()
  82. _ = sessionManagerBackground
  83. _ = sessionManagerBackgroundWWan
  84. _ = sessionIdentifierBackgroundExtension
  85. }
  86. //MARK: - Communication Delegate
  87. func networkReachabilityObserver(_ typeReachability: NCCommunicationCommon.typeReachability) {
  88. #if !EXTENSION
  89. if typeReachability == NCCommunicationCommon.typeReachability.reachableCellular || typeReachability == NCCommunicationCommon.typeReachability.reachableEthernetOrWiFi {
  90. if !lastReachability {
  91. NCService.shared.startRequestServicesServer()
  92. }
  93. lastReachability = true
  94. } else {
  95. if lastReachability {
  96. NCContentPresenter.shared.messageNotification("_network_not_available_", description: nil, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: -1009)
  97. }
  98. lastReachability = false
  99. }
  100. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_setTitleMain)
  101. #endif
  102. }
  103. func authenticationChallenge(_ challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  104. if checkTrustedChallenge(challenge: challenge, directoryCertificate: CCUtility.getDirectoryCerificates()) {
  105. completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential.init(trust: challenge.protectionSpace.serverTrust!))
  106. } else {
  107. completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
  108. }
  109. }
  110. func downloadProgress(_ progress: Double, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  111. delegate?.downloadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  112. }
  113. func downloadComplete(fileName: String, serverUrl: String, etag: String?, date: NSDate?, dateLastModified: NSDate?, length: Double, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  114. delegate?.downloadComplete?(fileName: fileName, serverUrl: serverUrl, etag: etag, date: date, dateLastModified: dateLastModified, length: length, description: description, task: task, errorCode: errorCode, errorDescription: errorDescription)
  115. }
  116. //MARK: - Pinning check
  117. @objc func checkTrustedChallenge(challenge: URLAuthenticationChallenge, directoryCertificate: String) -> Bool {
  118. var trusted = false
  119. let protectionSpace: URLProtectionSpace = challenge.protectionSpace
  120. let directoryCertificateUrl = URL.init(fileURLWithPath: directoryCertificate)
  121. if let trust: SecTrust = protectionSpace.serverTrust {
  122. saveX509Certificate(trust, certName: "tmp.der", directoryCertificate: directoryCertificate)
  123. do {
  124. let directoryContents = try FileManager.default.contentsOfDirectory(at: directoryCertificateUrl, includingPropertiesForKeys: nil)
  125. let certTmpPath = directoryCertificate+"/"+"tmp.der"
  126. for file in directoryContents {
  127. let certPath = file.path
  128. if certPath == certTmpPath { continue }
  129. if FileManager.default.contentsEqual(atPath:certTmpPath, andPath: certPath) {
  130. trusted = true
  131. break
  132. }
  133. }
  134. } catch { print(error) }
  135. }
  136. return trusted
  137. }
  138. @objc func wrtiteCertificate(directoryCertificate: String) {
  139. let certificateAtPath = directoryCertificate + "/tmp.der"
  140. let certificateToPath = directoryCertificate + "/" + CCUtility.getTimeIntervalSince197() + ".der"
  141. do {
  142. try FileManager.default.moveItem(atPath: certificateAtPath, toPath: certificateToPath)
  143. } catch { }
  144. }
  145. private func saveX509Certificate(_ trust: SecTrust, certName: String, directoryCertificate: String) {
  146. let currentServerCert = secTrustGetLeafCertificate(trust)
  147. let certNamePath = directoryCertificate + "/" + certName
  148. let data: CFData = SecCertificateCopyData(currentServerCert!)
  149. let mem = BIO_new_mem_buf(CFDataGetBytePtr(data), Int32(CFDataGetLength(data)))
  150. let x509cert = d2i_X509_bio(mem, nil)
  151. BIO_free(mem)
  152. if x509cert == nil {
  153. print("[LOG] OpenSSL couldn't parse X509 Certificate")
  154. } else {
  155. if FileManager.default.fileExists(atPath: certNamePath) {
  156. do {
  157. try FileManager.default.removeItem(atPath: certNamePath)
  158. } catch { }
  159. }
  160. let file = fopen(certNamePath, "w")
  161. if file != nil {
  162. PEM_write_X509(file, x509cert);
  163. }
  164. fclose(file);
  165. X509_free(x509cert);
  166. }
  167. }
  168. private func secTrustGetLeafCertificate(_ trust: SecTrust) -> SecCertificate? {
  169. let result: SecCertificate?
  170. if SecTrustGetCertificateCount(trust) > 0 {
  171. result = SecTrustGetCertificateAtIndex(trust, 0)!
  172. assert(result != nil);
  173. } else {
  174. result = nil
  175. }
  176. return result
  177. }
  178. //MARK: - Download
  179. @objc func cancelDownload(ocId: String, serverUrl:String, fileNameView: String) {
  180. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView) else { return }
  181. if let request = downloadRequest[fileNameLocalPath] {
  182. request.cancel()
  183. } else {
  184. NCManageDatabase.sharedInstance.setMetadataSession(ocId: ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: Int(k_metadataStatusNormal))
  185. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":ocId, "serverUrl":serverUrl])
  186. }
  187. }
  188. @objc func download(metadata: tableMetadata, selector: String, setFavorite: Bool = false, completion: @escaping (_ errorCode: Int)->()) {
  189. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  190. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
  191. if NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) == nil {
  192. NCManageDatabase.sharedInstance.addMetadata(tableMetadata.init(value: metadata))
  193. }
  194. if metadata.status == Int(k_metadataStatusInDownload) || metadata.status == Int(k_metadataStatusDownloading) { return }
  195. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, session: NCCommunicationCommon.shared.sessionIdentifierDownload, sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: Int(k_metadataStatusInDownload))
  196. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, object: nil, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  197. NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { (request) in
  198. self.downloadRequest[fileNameLocalPath] = request
  199. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, status: Int(k_metadataStatusDownloading))
  200. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadFileStart, userInfo: ["metadata":metadata])
  201. }, progressHandler: { (progress) in
  202. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_progressTask, object: nil, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "status":NSNumber(value: k_metadataStatusInDownload), "progress":NSNumber(value: progress.fractionCompleted), "totalBytes":NSNumber(value: progress.totalUnitCount), "totalBytesExpected":NSNumber(value: progress.completedUnitCount)])
  203. }) { (account, etag, date, length, error, errorCode, errorDescription) in
  204. if error?.isExplicitlyCancelledError ?? false {
  205. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: Int(k_metadataStatusNormal))
  206. } else if errorCode == 0 {
  207. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: Int(k_metadataStatusNormal), etag: etag, setFavorite: setFavorite)
  208. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  209. #if !EXTENSION
  210. if let result = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "fileNameIdentifier == %@ AND serverUrl == %@", metadata.fileName, metadata.serverUrl)) {
  211. NCEndToEndEncryption.sharedManager()?.decryptFileName(metadata.fileName, fileNameView: metadata.fileNameView, ocId: metadata.ocId, key: result.key, initializationVector: result.initializationVector, authenticationTag: result.authenticationTag)
  212. }
  213. #endif
  214. } else {
  215. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: errorDescription, sessionSelector: selector, sessionTaskIdentifier: 0, status: Int(k_metadataStatusDownloadError))
  216. #if !EXTENSION
  217. if errorCode == 401 || errorCode == 403 {
  218. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account)
  219. } else if errorCode == Int(CFNetworkErrors.cfurlErrorServerCertificateUntrusted.rawValue) {
  220. CCUtility.setCertificateError(metadata.account, error: true)
  221. }
  222. #endif
  223. }
  224. self.downloadRequest[fileNameLocalPath] = nil
  225. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata":metadata, "selector":selector, "errorCode":errorCode, "errorDescription":errorDescription])
  226. //NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  227. completion(errorCode)
  228. }
  229. }
  230. //MARK: - Upload
  231. @objc func cancelUpload(ocId: String) {
  232. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) else { return }
  233. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else { return }
  234. if let request = uploadRequest[fileNameLocalPath] {
  235. request.cancel()
  236. } else {
  237. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  238. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  239. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  240. }
  241. }
  242. @objc func upload(metadata: tableMetadata, background: Bool = true, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  243. guard let account = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account)) else {
  244. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  245. completion(Int(k_CCErrorInternalError), "Internal error")
  246. return
  247. }
  248. var e2eEncrypted = false
  249. let internalContenType = NCCommunicationCommon.shared.getInternalContenType(fileName: metadata.fileNameView, contentType: metadata.contentType, directory: false)
  250. var fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  251. if CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase) {
  252. e2eEncrypted = true
  253. }
  254. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  255. let metadata = tableMetadata.init(value: metadata)
  256. metadata.contentType = internalContenType.contentType
  257. metadata.iconName = internalContenType.iconName
  258. metadata.typeFile = internalContenType.typeFile
  259. if let date = NCUtilityFileSystem.shared.getFileCreationDate(filePath: fileNameLocalPath) {
  260. metadata.creationDate = date
  261. }
  262. if let date = NCUtilityFileSystem.shared.getFileModificationDate(filePath: fileNameLocalPath) {
  263. metadata.date = date
  264. }
  265. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath)
  266. NCManageDatabase.sharedInstance.addMetadata(metadata)
  267. if e2eEncrypted {
  268. #if !EXTENSION
  269. NCNetworkingE2EE.shared.upload(metadata: metadata, account: account, completion: completion)
  270. #endif
  271. } else if background {
  272. uploadFileInBackground(metadata: metadata, account: account, completion: completion)
  273. } else {
  274. uploadFile(metadata: metadata, account: account, completion: completion)
  275. }
  276. } else {
  277. CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadata, notification: true) { (extractMetadata, fileNamePath) in
  278. guard let extractMetadata = extractMetadata else {
  279. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  280. completion(Int(k_CCErrorInternalError), "Internal error")
  281. return
  282. }
  283. fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(extractMetadata.ocId, fileNameView: extractMetadata.fileNameView)
  284. CCUtility.moveFile(atPath: fileNamePath, toPath: fileNameLocalPath)
  285. NCManageDatabase.sharedInstance.addMetadata(extractMetadata)
  286. if e2eEncrypted {
  287. #if !EXTENSION
  288. NCNetworkingE2EE.shared.upload(metadata: extractMetadata, account: account, completion: completion)
  289. #endif
  290. } else if background {
  291. self.uploadFileInBackground(metadata: extractMetadata, account: account, completion: completion)
  292. } else {
  293. self.uploadFile(metadata: extractMetadata, account: account, completion: completion)
  294. }
  295. }
  296. }
  297. }
  298. //
  299. private func uploadFile(metadata: tableMetadata, account: tableAccount, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  300. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  301. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  302. var requestUpload: UploadRequest?
  303. var task: URLSessionTask?
  304. NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.creationDate as Date, dateModificationFile: metadata.date as Date, customUserAgent: nil, addCustomHeaders: nil, requestHandler: { (request) in
  305. requestUpload = request
  306. }, progressHandler: { (progress) in
  307. if task == nil && requestUpload?.task != nil {
  308. task = requestUpload?.task
  309. }
  310. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_progressTask, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "status":NSNumber(value: k_metadataStatusInUpload), "progress":NSNumber(value: progress.fractionCompleted), "totalBytes":NSNumber(value: progress.totalUnitCount), "totalBytesExpected":NSNumber(value: progress.completedUnitCount)])
  311. }) { (account, ocId, etag, date, size, error, errorCode, errorDescription) in
  312. self.uploadComplete(fileName: metadata.fileName, serverUrl: metadata.serverUrl, ocId: ocId, etag: etag, date: date, size: size, description: "", task: task!, errorCode: errorCode, errorDescription: errorDescription)
  313. completion(errorCode, errorDescription)
  314. }
  315. }
  316. private func uploadFileInBackground(metadata: tableMetadata, account: tableAccount, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  317. var session: URLSession?
  318. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  319. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  320. if metadata.session == sessionIdentifierBackground || metadata.session == sessionIdentifierBackgroundExtension {
  321. session = sessionManagerBackground
  322. } else if metadata.session == sessionIdentifierBackgroundWWan {
  323. session = sessionManagerBackgroundWWan
  324. }
  325. 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!) {
  326. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: Int(k_metadataStatusUploading))
  327. #if !EXTENSION
  328. CCGraphics.createNewImage(from: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, typeFile: metadata.typeFile)
  329. #endif
  330. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadFileStart, userInfo: ["metadata":metadata])
  331. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  332. completion(0, "")
  333. } else {
  334. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  335. completion(Int(k_CCErrorInternalError), "task null")
  336. }
  337. }
  338. func uploadProgress(_ progress: Double, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  339. delegate?.uploadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  340. var metadata: tableMetadata?
  341. if let metadataTmp = self.uploadMetadata[fileName+serverUrl] {
  342. metadata = metadataTmp
  343. } else if let metadataTmp = NCManageDatabase.sharedInstance.getMetadataInSessionFromFileName(fileName, serverUrl: serverUrl) {
  344. self.uploadMetadata[fileName+serverUrl] = metadataTmp
  345. metadata = metadataTmp
  346. }
  347. if metadata != nil {
  348. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_progressTask, userInfo: ["account":metadata!.account, "ocId":metadata!.ocId, "serverUrl":serverUrl, "status":NSNumber(value: k_metadataStatusInUpload), "progress":NSNumber(value: progress), "totalBytes":NSNumber(value: totalBytes), "totalBytesExpected":NSNumber(value: totalBytesExpected)])
  349. }
  350. }
  351. func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  352. if delegate != nil {
  353. delegate?.uploadComplete?(fileName: fileName, serverUrl: serverUrl, ocId: ocId, etag: etag, date: date, size:size, description: description, task: task, errorCode: errorCode, errorDescription: errorDescription)
  354. } else {
  355. guard let metadata = NCManageDatabase.sharedInstance.getMetadataInSessionFromFileName(fileName, serverUrl: serverUrl) else { return }
  356. guard let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account)) else { return }
  357. if errorCode == 0 && ocId != nil {
  358. let metadata = tableMetadata.init(value: metadata)
  359. let ocIdTemp = metadata.ocId
  360. CCUtility.moveFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
  361. metadata.uploadDate = date ?? NSDate()
  362. metadata.etag = etag ?? ""
  363. metadata.ocId = ocId!
  364. if let fileId = NCUtility.shared.ocIdToFileId(ocId: ocId) {
  365. metadata.fileId = fileId
  366. }
  367. metadata.session = ""
  368. metadata.sessionError = ""
  369. metadata.sessionTaskIdentifier = 0
  370. metadata.status = Int(k_metadataStatusNormal)
  371. // Delete Asset on Photos album
  372. if tableAccount.autoUploadDeleteAssetLocalIdentifier && metadata.assetLocalIdentifier != "" && metadata.sessionSelector == selectorUploadAutoUpload {
  373. metadata.deleteAssetLocalIdentifier = true;
  374. }
  375. if CCUtility.getDisableLocalCacheAfterUpload() {
  376. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  377. } else {
  378. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  379. }
  380. NCManageDatabase.sharedInstance.addMetadata(metadata)
  381. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  382. #if !EXTENSION
  383. self.getOcIdInSession { (listOcId) in
  384. if listOcId.count == 0 {
  385. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  386. appDelegate.networkingAutoUpload.startProcess()
  387. }
  388. }
  389. #endif
  390. NCCommunicationCommon.shared.writeLog("Upload complete " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)")
  391. } else if errorCode == NSURLErrorCancelled {
  392. if metadata.status == k_metadataStatusUploadForcedStart {
  393. NCManageDatabase.sharedInstance.setMetadataSession(ocId: ocId!, session: sessionIdentifierBackground, sessionError: "", sessionTaskIdentifier: 0, status: Int(k_metadataStatusInUpload))
  394. NCNetworking.shared.upload(metadata: metadata) { (_, _) in }
  395. } else {
  396. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  397. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  398. }
  399. } else if errorCode == 401 || errorCode == 403 {
  400. #if !EXTENSION
  401. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account)
  402. #endif
  403. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: Int(k_metadataStatusUploadError))
  404. } else if errorCode == Int(CFNetworkErrors.cfurlErrorServerCertificateUntrusted.rawValue) {
  405. CCUtility.setCertificateError(metadata.account, error: true)
  406. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: Int(k_metadataStatusUploadError))
  407. } else {
  408. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: Int(k_metadataStatusUploadError))
  409. }
  410. // Delete
  411. self.uploadMetadata[fileName+serverUrl] = nil
  412. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_uploadedFile, userInfo: ["metadata":metadata, "errorCode":errorCode, "errorDescription":""])
  413. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  414. }
  415. }
  416. @objc func verifyUploadZombie() {
  417. var session: URLSession?
  418. // verify k_metadataStatusInUpload (BACKGROUND)
  419. let metadatasInUpload = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "(session == %@ OR session == %@ OR session == %@) AND status == %d AND sessionTaskIdentifier == 0", sessionIdentifierBackground, sessionIdentifierBackgroundExtension, sessionIdentifierBackgroundWWan, k_metadataStatusInUpload))
  420. for metadata in metadatasInUpload {
  421. DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
  422. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d AND sessionTaskIdentifier == 0", metadata.ocId, k_metadataStatusInUpload)) {
  423. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, session: self.sessionIdentifierBackground, sessionError: "", sessionSelector: nil, sessionTaskIdentifier: 0, status: Int(k_metadataStatusWaitUpload))
  424. }
  425. }
  426. }
  427. // k_metadataStatusUploading (BACKGROUND)
  428. let metadatasUploading = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "(session == %@ OR session == %@ OR session == %@) AND status == %d", sessionIdentifierBackground, sessionIdentifierBackgroundWWan, sessionIdentifierBackgroundExtension, k_metadataStatusUploading))
  429. for metadata in metadatasUploading {
  430. if metadata.session == sessionIdentifierBackground {
  431. session = self.sessionManagerBackground
  432. } else if metadata.session == sessionIdentifierBackgroundWWan {
  433. session = self.sessionManagerBackgroundWWan
  434. } else if metadata.session == sessionIdentifierBackgroundExtension {
  435. session = self.sessionManagerBackgroundExtension
  436. }
  437. var taskUpload: URLSessionTask?
  438. session?.getAllTasks(completionHandler: { (tasks) in
  439. for task in tasks {
  440. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  441. taskUpload = task
  442. }
  443. }
  444. if taskUpload == nil {
  445. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d", metadata.ocId, k_metadataStatusUploading)) {
  446. NCManageDatabase.sharedInstance.setMetadataSession(ocId: metadata.ocId, session: self.sessionIdentifierBackground, sessionError: "", sessionSelector: nil, sessionTaskIdentifier: 0, status: Int(k_metadataStatusWaitUpload))
  447. }
  448. }
  449. })
  450. }
  451. }
  452. func getOcIdInSession(completion: @escaping (_ listOcId: [String])->()) {
  453. var listOcId: [String] = []
  454. sessionManagerBackground.getAllTasks(completionHandler: { (tasks) in
  455. for task in tasks {
  456. listOcId.append(task.description)
  457. }
  458. self.sessionManagerBackgroundWWan.getAllTasks(completionHandler: { (tasks) in
  459. for task in tasks {
  460. listOcId.append(task.description)
  461. }
  462. self.sessionManagerBackgroundExtension.getAllTasks(completionHandler: { (tasks) in
  463. for task in tasks {
  464. listOcId.append(task.description)
  465. }
  466. completion(listOcId)
  467. })
  468. })
  469. })
  470. }
  471. //MARK: - WebDav Read file, folder
  472. @objc func readFolder(serverUrl: String, account: String, completion: @escaping (_ account: String, _ metadataFolder: tableMetadata?, _ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ metadatasLocalUpdate: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  473. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
  474. if errorCode == 0 {
  475. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: true, account: account) { (metadataFolder, metadatasFolder, metadatas) in
  476. // Update directory
  477. NCManageDatabase.sharedInstance.addDirectory(encrypted: metadataFolder.e2eEncrypted, favorite: metadataFolder.favorite, ocId: metadataFolder.ocId, fileId: metadataFolder.fileId, etag: metadataFolder.etag, permissions: metadataFolder.permissions, serverUrl: serverUrl, richWorkspace: metadataFolder.richWorkspace, account: metadataFolder.account)
  478. // Update sub directories
  479. for metadata in metadatasFolder {
  480. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  481. NCManageDatabase.sharedInstance.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: serverUrl, richWorkspace: metadata.richWorkspace, account: account)
  482. }
  483. let metadatasResult = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, k_metadataStatusNormal))
  484. let metadatasChanged = NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult, addExistsInLocal: false, addCompareEtagLocal: true)
  485. if metadatasChanged.metadatasUpdate.count > 0 {
  486. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrl])
  487. }
  488. completion(account, metadataFolder, metadatas, metadatasChanged.metadatasUpdate, metadatasChanged.metadatasLocalUpdate, errorCode, "")
  489. }
  490. } else {
  491. #if !EXTENSION
  492. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  493. #endif
  494. completion(account, nil, nil, nil, nil, errorCode, errorDescription)
  495. }
  496. }
  497. }
  498. @objc func readFile(serverUrlFileName: String, account: String, completion: @escaping (_ account: String, _ metadata: tableMetadata?, _ errorCode: Int, _ errorDescription: String)->()) {
  499. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
  500. if errorCode == 0 {
  501. if files.count == 1 {
  502. let file = files[0]
  503. let isEncrypted = CCUtility.isFolderEncrypted(file.serverUrl, e2eEncrypted:file.e2eEncrypted, account: account, urlBase: file.urlBase)
  504. let metadata = NCManageDatabase.sharedInstance.convertNCFileToMetadata(file, isEncrypted: isEncrypted, account: account)
  505. completion(account, metadata, errorCode, "")
  506. } else {
  507. completion(account, nil, errorCode, "")
  508. }
  509. } else {
  510. completion(account, nil, errorCode, errorDescription)
  511. }
  512. }
  513. }
  514. //MARK: - WebDav Create Folder
  515. @objc func createFolder(fileName: String, serverUrl: String, account: String, urlBase: String, overwrite: Bool = false, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  516. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: false, account: account, urlBase: urlBase)
  517. if isDirectoryEncrypted {
  518. #if !EXTENSION
  519. NCNetworkingE2EE.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, completion: completion)
  520. #endif
  521. } else {
  522. createFolderPlain(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: overwrite, completion: completion)
  523. }
  524. }
  525. @objc func createFolderPlain(fileName: String, serverUrl: String, account: String, urlBase: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  526. var fileNameFolder = CCUtility.removeForbiddenCharactersServer(fileName)!
  527. if (!overwrite) {
  528. fileNameFolder = NCUtility.shared.createFileName(fileNameFolder, serverUrl: serverUrl, account: account)
  529. }
  530. if fileNameFolder.count == 0 {
  531. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": Int(0)], errorDescription: "", completion: completion)
  532. return
  533. }
  534. let fileNameFolderUrl = serverUrl + "/" + fileNameFolder
  535. NCCommunication.shared.createFolder(fileNameFolderUrl) { (account, ocId, date, errorCode, errorDescription) in
  536. if errorCode == 0 {
  537. self.readFile(serverUrlFileName: fileNameFolderUrl, account: account) { (account, metadataFolder, errorCode, errorDescription) in
  538. if errorCode == 0 {
  539. // Add Metadata
  540. NCManageDatabase.sharedInstance.addMetadata(metadataFolder!)
  541. // Add folder
  542. NCManageDatabase.sharedInstance.addDirectory(encrypted: metadataFolder!.e2eEncrypted, favorite: metadataFolder!.favorite, ocId: metadataFolder!.ocId, fileId: metadataFolder!.fileId, etag: nil, permissions: metadataFolder!.permissions, serverUrl: fileNameFolderUrl, richWorkspace: metadataFolder!.richWorkspace, account: account)
  543. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  544. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrl])
  545. } else {
  546. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  547. }
  548. }
  549. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrl])
  550. } else if errorCode == 405 && overwrite {
  551. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": 0], errorDescription: "", completion: completion)
  552. } else {
  553. self.NotificationPost(name: k_notificationCenter_createFolder, userInfo: ["fileName": fileName, "serverUrl": serverUrl, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  554. }
  555. }
  556. }
  557. @objc func createFoloder(assets: PHFetchResult<AnyObject>, selector: String, useSubFolder: Bool, account: String, urlBase: String) -> Bool {
  558. let serverUrl = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: urlBase, account: account)
  559. let fileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  560. let autoUploadPath = NCManageDatabase.sharedInstance.getAccountAutoUploadPath(urlBase: urlBase, account: account)
  561. var error = false
  562. error = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase)
  563. if useSubFolder && !error {
  564. for dateSubFolder in CCUtility.createNameSubFolder(assets) {
  565. let fileName = (dateSubFolder as! NSString).lastPathComponent
  566. let serverUrl = ((autoUploadPath + "/" + (dateSubFolder as! String)) as NSString).deletingLastPathComponent
  567. error = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase)
  568. if error { break }
  569. }
  570. }
  571. return error
  572. }
  573. private func createFolderWithSemaphore(fileName: String, serverUrl: String, account: String, urlBase: String) -> Bool {
  574. var error = false
  575. let semaphore = Semaphore()
  576. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: true) { (errorCode, errorDescription) in
  577. if errorCode != 0 { error = true }
  578. semaphore.continue()
  579. }
  580. if semaphore.wait() != .success { error = true }
  581. return error
  582. }
  583. //MARK: - WebDav Delete
  584. @objc func deleteMetadata(_ metadata: tableMetadata, account: String, urlBase: String, onlyLocal: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  585. if (onlyLocal) {
  586. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  587. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  588. if let metadataLivePhoto = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata) {
  589. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadataLivePhoto.ocId))
  590. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadataLivePhoto.ocId))
  591. }
  592. self.NotificationPost(name: k_notificationCenter_deleteFile, userInfo: ["metadata": metadata, "onlyLocal": true ,"errorCode": 0], errorDescription: "", completion: completion)
  593. return
  594. }
  595. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: urlBase)
  596. let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata)
  597. if isDirectoryEncrypted {
  598. #if !EXTENSION
  599. if metadataLive == nil {
  600. NCNetworkingE2EE.shared.deleteMetadata(metadata, urlBase: urlBase, completion: completion)
  601. } else {
  602. NCNetworkingE2EE.shared.deleteMetadata(metadataLive!, urlBase: urlBase) { (errorCode, errorDescription) in
  603. if errorCode == 0 {
  604. NCNetworkingE2EE.shared.deleteMetadata(metadata, urlBase: urlBase, completion: completion)
  605. } else {
  606. completion(errorCode, errorDescription)
  607. }
  608. }
  609. }
  610. #endif
  611. } else {
  612. if metadataLive == nil {
  613. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  614. } else {
  615. self.deleteMetadataPlain(metadataLive!, addCustomHeaders: nil) { (errorCode, errorDescription) in
  616. if errorCode == 0 {
  617. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  618. } else {
  619. completion(errorCode, errorDescription)
  620. }
  621. }
  622. }
  623. }
  624. }
  625. func deleteMetadataPlain(_ metadata: tableMetadata, addCustomHeaders: [String: String]?, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  626. // verify permission
  627. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: k_permission_can_delete)
  628. if metadata.permissions != "" && permission == false {
  629. self.NotificationPost(name: k_notificationCenter_deleteFile, userInfo: ["metadata": metadata, "onlyLocal": false, "errorCode": Int(k_CCErrorInternalError)], errorDescription: "_no_permission_delete_file_", completion: completion)
  630. return
  631. }
  632. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  633. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName, customUserAgent: nil, addCustomHeaders: addCustomHeaders) { (account, errorCode, errorDescription) in
  634. if errorCode == 0 || errorCode == 404 {
  635. do {
  636. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  637. } catch { }
  638. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  639. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  640. if metadata.directory {
  641. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account)
  642. }
  643. }
  644. self.NotificationPost(name: k_notificationCenter_deleteFile, userInfo: ["metadata": metadata, "onlyLocal": false, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  645. }
  646. }
  647. //MARK: - WebDav Favorite
  648. @objc func favoriteMetadata(_ metadata: tableMetadata, urlBase: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  649. if let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata) {
  650. favoriteMetadataPlain(metadataLive, urlBase: urlBase) { (errorCode, errorDescription) in
  651. if errorCode == 0 {
  652. self.favoriteMetadataPlain(metadata, urlBase: urlBase, completion: completion)
  653. } else {
  654. completion(errorCode, errorDescription)
  655. }
  656. }
  657. } else {
  658. favoriteMetadataPlain(metadata, urlBase: urlBase, completion: completion)
  659. }
  660. }
  661. @objc func favoriteMetadataPlain(_ metadata: tableMetadata, urlBase: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  662. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: urlBase, account: metadata.account)!
  663. let favorite = !metadata.favorite
  664. NCCommunication.shared.setFavorite(fileName: fileName, favorite: favorite) { (account, errorCode, errorDescription) in
  665. if errorCode == 0 && metadata.account == account {
  666. NCManageDatabase.sharedInstance.setMetadataFavorite(ocId: metadata.ocId, favorite: favorite)
  667. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  668. }
  669. self.NotificationPost(name: k_notificationCenter_favoriteFile, userInfo: ["metadata": metadata, "favorite": favorite, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  670. }
  671. }
  672. @objc func listingFavoritescompletion(selector: String, completion: @escaping (_ account: String, _ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  673. NCCommunication.shared.listingFavorites(showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, errorCode, errorDescription) in
  674. if errorCode == 0 {
  675. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (_, _, metadatas) in
  676. if selector != selectorListingFavorite {
  677. #if !EXTENSION
  678. for metadata in metadatas {
  679. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: selector)
  680. }
  681. #endif
  682. }
  683. completion(account, metadatas, errorCode, errorDescription)
  684. }
  685. } else {
  686. completion(account, nil, errorCode, errorDescription)
  687. }
  688. }
  689. }
  690. //MARK: - WebDav Rename
  691. @objc func renameMetadata(_ metadata: tableMetadata, fileNameNew: String, urlBase: String, viewController: UIViewController?, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  692. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: urlBase)
  693. let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata)
  694. let fileNameNewLive = (fileNameNew as NSString).deletingPathExtension + ".mov"
  695. if isDirectoryEncrypted {
  696. #if !EXTENSION
  697. if metadataLive == nil {
  698. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, urlBase: urlBase, completion: completion)
  699. } else {
  700. NCNetworkingE2EE.shared.renameMetadata(metadataLive!, fileNameNew: fileNameNewLive, urlBase: urlBase) { (errorCode, errorDescription) in
  701. if errorCode == 0 {
  702. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, urlBase: urlBase, completion: completion)
  703. } else {
  704. completion(errorCode, errorDescription)
  705. }
  706. }
  707. }
  708. #endif
  709. } else {
  710. if metadataLive == nil {
  711. renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  712. } else {
  713. renameMetadataPlain(metadataLive!, fileNameNew: fileNameNewLive) { (errorCode, errorDescription) in
  714. if errorCode == 0 {
  715. self.renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  716. } else {
  717. completion(errorCode, errorDescription)
  718. }
  719. }
  720. }
  721. }
  722. }
  723. private func renameMetadataPlain(_ metadata: tableMetadata, fileNameNew: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  724. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: k_permission_can_rename)
  725. if !(metadata.permissions == "") && !permission {
  726. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "errorCode": Int(k_CCErrorInternalError)], errorDescription: "_no_permission_modify_file_", completion: completion)
  727. return
  728. }
  729. guard let fileNameNew = CCUtility.removeForbiddenCharactersServer(fileNameNew) else {
  730. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "errorCode": Int(0)], errorDescription: "", completion: completion)
  731. return
  732. }
  733. if fileNameNew.count == 0 || fileNameNew == metadata.fileNameView {
  734. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "errorCode": Int(0)], errorDescription: "", completion: completion)
  735. return
  736. }
  737. let fileNamePath = metadata.serverUrl + "/" + metadata.fileName
  738. let fileNameToPath = metadata.serverUrl + "/" + fileNameNew
  739. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNamePath, serverUrlFileNameDestination: fileNameToPath, overwrite: false) { (account, errorCode, errorDescription) in
  740. if errorCode == 0 {
  741. NCManageDatabase.sharedInstance.renameMetadata(fileNameTo: fileNameNew, ocId: metadata.ocId)
  742. if metadata.directory {
  743. let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  744. let serverUrlTo = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: fileNameNew)!
  745. if let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  746. NCManageDatabase.sharedInstance.setDirectory(serverUrl: serverUrl, serverUrlTo: serverUrlTo, etag: "", ocId: nil, fileId: nil, encrypted: directory.e2eEncrypted, richWorkspace: nil, account: metadata.account)
  747. }
  748. } else {
  749. NCManageDatabase.sharedInstance.setLocalFile(ocId: metadata.ocId, date: nil, exifDate: nil, exifLatitude: nil, exifLongitude: nil, fileName: fileNameNew, etag: nil)
  750. // Move file system
  751. let atPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileName
  752. let toPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + fileNameNew
  753. do {
  754. try FileManager.default.moveItem(atPath: atPath, toPath: toPath)
  755. } catch { }
  756. }
  757. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl])
  758. }
  759. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  760. }
  761. }
  762. //MARK: - WebDav Move
  763. @objc func moveMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  764. if let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata) {
  765. moveMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  766. if errorCode == 0 {
  767. self.moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  768. } else {
  769. completion(errorCode, errorDescription)
  770. }
  771. }
  772. } else {
  773. moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  774. }
  775. }
  776. @objc func moveMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  777. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: k_permission_can_rename)
  778. if !(metadata.permissions == "") && !permission {
  779. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "serverUrlTo": serverUrlTo, "errorCode": Int(k_CCErrorInternalError)], errorDescription: "_no_permission_modify_file_", completion: completion)
  780. return
  781. }
  782. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  783. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  784. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  785. if errorCode == 0 {
  786. if metadata.directory {
  787. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: account)
  788. }
  789. NCManageDatabase.sharedInstance.moveMetadata(ocId: metadata.ocId, serverUrlTo: serverUrlTo)
  790. guard let metadataNew = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) else { return }
  791. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":metadata.serverUrl])
  792. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrlTo])
  793. self.NotificationPost(name: k_notificationCenter_moveFile, userInfo: ["metadata": metadata, "metadataNew": metadataNew, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  794. } else {
  795. self.NotificationPost(name: k_notificationCenter_moveFile, userInfo: ["metadata": metadata, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  796. }
  797. }
  798. }
  799. //MARK: - WebDav Copy
  800. @objc func copyMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  801. if let metadataLive = NCManageDatabase.sharedInstance.isLivePhoto(metadata: metadata) {
  802. copyMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  803. if errorCode == 0 {
  804. self.copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  805. } else {
  806. completion(errorCode, errorDescription)
  807. }
  808. }
  809. } else {
  810. copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  811. }
  812. }
  813. @objc func copyMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  814. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: k_permission_can_rename)
  815. if !(metadata.permissions == "") && !permission {
  816. self.NotificationPost(name: k_notificationCenter_renameFile, userInfo: ["metadata": metadata, "serverUrlTo": serverUrlTo, "errorCode": Int(k_CCErrorInternalError)], errorDescription: "_no_permission_modify_file_", completion: completion)
  817. return
  818. }
  819. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  820. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  821. NCCommunication.shared.copyFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  822. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_reloadDataSource, userInfo: ["serverUrl":serverUrlTo])
  823. self.NotificationPost(name: k_notificationCenter_copyFile, userInfo: ["metadata": metadata, "errorCode": errorCode], errorDescription: errorDescription, completion: completion)
  824. }
  825. }
  826. //MARK: - Notification Post
  827. private func NotificationPost(name: String, userInfo: [AnyHashable : Any], errorDescription: Any?, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  828. var userInfo = userInfo
  829. DispatchQueue.main.async {
  830. if errorDescription == nil { userInfo["errorDescription"] = "" }
  831. else { userInfo["errorDescription"] = NSLocalizedString(errorDescription as! String, comment: "") }
  832. NotificationCenter.default.postOnMainThread(name: name, userInfo: userInfo)
  833. completion(userInfo["errorCode"] as! Int, userInfo["errorDescription"] as! String)
  834. }
  835. }
  836. }