NCNetworking.swift 68 KB

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