NCNetworking.swift 59 KB

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