NCNetworking.swift 69 KB

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