NCNetworking.swift 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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, 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)
  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. var fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  253. if CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase) {
  254. e2eEncrypted = true
  255. }
  256. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  257. let metadata = tableMetadata.init(value: metadata)
  258. let results = NCCommunicationCommon.shared.getInternalType(fileName: metadata.fileNameView, mimeType: metadata.contentType, directory: false)
  259. metadata.contentType = results.mimeType
  260. metadata.iconName = results.iconName
  261. metadata.typeFile = results.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. var metadatas = [metadata]
  696. if metadata.directory {
  697. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  698. metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND directory == false", account, serverUrl))
  699. }
  700. for metadata in metadatas {
  701. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  702. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  703. if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  704. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadataLivePhoto.ocId))
  705. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadataLivePhoto.ocId))
  706. }
  707. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "typeFile": metadata.typeFile, "onlyLocal": true])
  708. }
  709. completion(0, "")
  710. return
  711. }
  712. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: urlBase)
  713. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  714. if isDirectoryEncrypted {
  715. #if !EXTENSION
  716. if metadataLive == nil {
  717. NCNetworkingE2EE.shared.deleteMetadata(metadata, urlBase: urlBase, completion: completion)
  718. } else {
  719. NCNetworkingE2EE.shared.deleteMetadata(metadataLive!, urlBase: urlBase) { (errorCode, errorDescription) in
  720. if errorCode == 0 {
  721. NCNetworkingE2EE.shared.deleteMetadata(metadata, urlBase: urlBase, completion: completion)
  722. } else {
  723. completion(errorCode, errorDescription)
  724. }
  725. }
  726. }
  727. #endif
  728. } else {
  729. if metadataLive == nil {
  730. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  731. } else {
  732. self.deleteMetadataPlain(metadataLive!, addCustomHeaders: nil) { (errorCode, errorDescription) in
  733. if errorCode == 0 {
  734. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  735. } else {
  736. completion(errorCode, errorDescription)
  737. }
  738. }
  739. }
  740. }
  741. }
  742. func deleteMetadataPlain(_ metadata: tableMetadata, addCustomHeaders: [String: String]?, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  743. // verify permission
  744. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCBrandGlobal.shared.permissionCanDelete)
  745. if metadata.permissions != "" && permission == false {
  746. completion(NCBrandGlobal.shared.ErrorInternalError, "_no_permission_delete_file_")
  747. return
  748. }
  749. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  750. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName, customUserAgent: nil, addCustomHeaders: addCustomHeaders) { (account, errorCode, errorDescription) in
  751. if errorCode == 0 || errorCode == NCBrandGlobal.shared.ErrorResourceNotFound {
  752. do {
  753. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  754. } catch { }
  755. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  756. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  757. if metadata.directory {
  758. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account)
  759. }
  760. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "typeFile": metadata.typeFile, "onlyLocal": true])
  761. }
  762. completion(errorCode, errorDescription)
  763. }
  764. }
  765. //MARK: - WebDav Favorite
  766. @objc func favoriteMetadata(_ metadata: tableMetadata, urlBase: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  767. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  768. favoriteMetadataPlain(metadataLive, urlBase: urlBase) { (errorCode, errorDescription) in
  769. if errorCode == 0 {
  770. self.favoriteMetadataPlain(metadata, urlBase: urlBase, completion: completion)
  771. } else {
  772. completion(errorCode, errorDescription)
  773. }
  774. }
  775. } else {
  776. favoriteMetadataPlain(metadata, urlBase: urlBase, completion: completion)
  777. }
  778. }
  779. private func favoriteMetadataPlain(_ metadata: tableMetadata, urlBase: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  780. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: urlBase, account: metadata.account)!
  781. let favorite = !metadata.favorite
  782. let ocId = metadata.ocId
  783. NCCommunication.shared.setFavorite(fileName: fileName, favorite: favorite) { (account, errorCode, errorDescription) in
  784. if errorCode == 0 && metadata.account == account {
  785. NCManageDatabase.shared.setMetadataFavorite(ocId: metadata.ocId, favorite: favorite)
  786. #if !EXTENSION
  787. if favorite {
  788. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCBrandGlobal.shared.selectorReadFile)
  789. }
  790. #endif
  791. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  792. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterFavoriteFile, userInfo: ["ocId": metadata.ocId])
  793. }
  794. }
  795. completion(errorCode, errorDescription)
  796. }
  797. }
  798. @objc func listingFavoritescompletion(selector: String, completion: @escaping (_ account: String, _ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  799. NCCommunication.shared.listingFavorites(showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, errorCode, errorDescription) in
  800. if errorCode == 0 {
  801. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (_, _, metadatas) in
  802. NCManageDatabase.shared.updateMetadatasFavorite(account: account, metadatas: metadatas)
  803. if selector != NCBrandGlobal.shared.selectorListingFavorite {
  804. #if !EXTENSION
  805. for metadata in metadatas {
  806. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: selector)
  807. }
  808. #endif
  809. }
  810. completion(account, metadatas, errorCode, errorDescription)
  811. }
  812. } else {
  813. completion(account, nil, errorCode, errorDescription)
  814. }
  815. }
  816. }
  817. //MARK: - WebDav Rename
  818. @objc func renameMetadata(_ metadata: tableMetadata, fileNameNew: String, urlBase: String, viewController: UIViewController?, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  819. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: urlBase)
  820. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  821. let fileNameNewLive = (fileNameNew as NSString).deletingPathExtension + ".mov"
  822. if isDirectoryEncrypted {
  823. #if !EXTENSION
  824. if metadataLive == nil {
  825. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, urlBase: urlBase, completion: completion)
  826. } else {
  827. NCNetworkingE2EE.shared.renameMetadata(metadataLive!, fileNameNew: fileNameNewLive, urlBase: urlBase) { (errorCode, errorDescription) in
  828. if errorCode == 0 {
  829. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, urlBase: urlBase, completion: completion)
  830. } else {
  831. completion(errorCode, errorDescription)
  832. }
  833. }
  834. }
  835. #endif
  836. } else {
  837. if metadataLive == nil {
  838. renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  839. } else {
  840. renameMetadataPlain(metadataLive!, fileNameNew: fileNameNewLive) { (errorCode, errorDescription) in
  841. if errorCode == 0 {
  842. self.renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  843. } else {
  844. completion(errorCode, errorDescription)
  845. }
  846. }
  847. }
  848. }
  849. }
  850. private func renameMetadataPlain(_ metadata: tableMetadata, fileNameNew: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  851. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCBrandGlobal.shared.permissionCanRename)
  852. if !(metadata.permissions == "") && !permission {
  853. completion(NCBrandGlobal.shared.ErrorInternalError, "_no_permission_modify_file_")
  854. return
  855. }
  856. guard let fileNameNew = CCUtility.removeForbiddenCharactersServer(fileNameNew) else {
  857. completion(0, "")
  858. return
  859. }
  860. if fileNameNew.count == 0 || fileNameNew == metadata.fileNameView {
  861. completion(0, "")
  862. return
  863. }
  864. let fileNamePath = metadata.serverUrl + "/" + metadata.fileName
  865. let fileNameToPath = metadata.serverUrl + "/" + fileNameNew
  866. let ocId = metadata.ocId
  867. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNamePath, serverUrlFileNameDestination: fileNameToPath, overwrite: false) { (account, errorCode, errorDescription) in
  868. if errorCode == 0 {
  869. NCManageDatabase.shared.renameMetadata(fileNameTo: fileNameNew, ocId: ocId)
  870. if metadata.directory {
  871. let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  872. let serverUrlTo = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: fileNameNew)!
  873. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  874. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, serverUrlTo: serverUrlTo, etag: "", ocId: nil, fileId: nil, encrypted: directory.e2eEncrypted, richWorkspace: nil, account: metadata.account)
  875. }
  876. } else {
  877. NCManageDatabase.shared.setLocalFile(ocId: ocId, fileName: fileNameNew, etag: nil)
  878. // Move file system
  879. let atPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + metadata.fileName
  880. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + fileNameNew
  881. do {
  882. try FileManager.default.moveItem(atPath: atPath, toPath: toPath)
  883. } catch { }
  884. }
  885. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  886. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterRenameFile, userInfo: ["ocId": metadata.ocId])
  887. }
  888. }
  889. completion(errorCode, errorDescription)
  890. }
  891. }
  892. //MARK: - WebDav Move
  893. @objc func moveMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  894. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  895. moveMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  896. if errorCode == 0 {
  897. self.moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  898. } else {
  899. completion(errorCode, errorDescription)
  900. }
  901. }
  902. } else {
  903. moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  904. }
  905. }
  906. private func moveMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  907. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCBrandGlobal.shared.permissionCanRename)
  908. if !(metadata.permissions == "") && !permission {
  909. completion(NCBrandGlobal.shared.ErrorInternalError, "_no_permission_modify_file_")
  910. return
  911. }
  912. let serverUrlFrom = metadata.serverUrl
  913. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  914. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  915. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  916. if errorCode == 0 {
  917. if metadata.directory {
  918. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: account)
  919. }
  920. NCManageDatabase.shared.moveMetadata(ocId: metadata.ocId, serverUrlTo: serverUrlTo)
  921. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterMoveFile, userInfo: ["ocId": metadata.ocId, "serverUrlFrom": serverUrlFrom])
  922. }
  923. completion(errorCode, errorDescription)
  924. }
  925. }
  926. //MARK: - WebDav Copy
  927. @objc func copyMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  928. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  929. copyMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  930. if errorCode == 0 {
  931. self.copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  932. } else {
  933. completion(errorCode, errorDescription)
  934. }
  935. }
  936. } else {
  937. copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  938. }
  939. }
  940. private func copyMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  941. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCBrandGlobal.shared.permissionCanRename)
  942. if !(metadata.permissions == "") && !permission {
  943. completion(NCBrandGlobal.shared.ErrorInternalError, "_no_permission_modify_file_")
  944. return
  945. }
  946. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  947. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  948. NCCommunication.shared.copyFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  949. if errorCode == 0 {
  950. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterCopyFile, userInfo: ["ocId": metadata.ocId, "serverUrlTo": serverUrlTo])
  951. }
  952. completion(errorCode, errorDescription)
  953. }
  954. }
  955. }