NCNetworking.swift 68 KB

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