NCNetworking.swift 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  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 UIKit
  24. import OpenSSL
  25. import NCCommunication
  26. import Alamofire
  27. import Queuer
  28. @objc public protocol NCNetworkingDelegate {
  29. @objc optional func downloadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask)
  30. @objc optional func uploadProgress(_ progress: Float, 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: NCGlobal.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: Float, 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. func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
  123. #if !EXTENSION
  124. if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let completionHandler = appDelegate.backgroundSessionCompletionHandler {
  125. NCCommunicationCommon.shared.writeLog("Called urlSessionDidFinishEvents for Background URLSession")
  126. appDelegate.backgroundSessionCompletionHandler = nil
  127. completionHandler()
  128. }
  129. #endif
  130. }
  131. //MARK: - Pinning check
  132. @objc func checkTrustedChallenge(challenge: URLAuthenticationChallenge, directoryCertificate: String) -> Bool {
  133. var trusted = false
  134. let protectionSpace: URLProtectionSpace = challenge.protectionSpace
  135. let directoryCertificateUrl = URL.init(fileURLWithPath: directoryCertificate)
  136. if let trust: SecTrust = protectionSpace.serverTrust {
  137. saveX509Certificate(trust, certName: "tmp.der", directoryCertificate: directoryCertificate)
  138. do {
  139. let directoryContents = try FileManager.default.contentsOfDirectory(at: directoryCertificateUrl, includingPropertiesForKeys: nil)
  140. let certTmpPath = directoryCertificate+"/"+"tmp.der"
  141. for file in directoryContents {
  142. let certPath = file.path
  143. if certPath == certTmpPath { continue }
  144. if FileManager.default.contentsEqual(atPath:certTmpPath, andPath: certPath) {
  145. trusted = true
  146. break
  147. }
  148. }
  149. } catch { print(error) }
  150. }
  151. #if !EXTENSION
  152. DispatchQueue.main.async {
  153. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  154. if !trusted && appDelegate.account != "" && appDelegate.urlBase != "" {
  155. if let url = URL(string: appDelegate.urlBase) {
  156. let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
  157. if let host = urlComponents?.host {
  158. let certificatePath = directoryCertificate + "/" + host + ".der"
  159. if FileManager.default.fileExists(atPath: certificatePath) {
  160. CCUtility.setCertificateError(appDelegate.account, error: true)
  161. }
  162. }
  163. }
  164. }
  165. }
  166. #endif
  167. return trusted
  168. }
  169. @objc func writeCertificate(directoryCertificate: String, url: String) {
  170. if let url = URL(string: url) {
  171. let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
  172. if let host = urlComponents?.host {
  173. let certificateAtPath = directoryCertificate + "/tmp.der"
  174. let certificateToPath = directoryCertificate + "/" + host + ".der"
  175. NCUtilityFileSystem.shared.moveFile(atPath: certificateAtPath, toPath: certificateToPath)
  176. }
  177. }
  178. }
  179. private func saveX509Certificate(_ trust: SecTrust, certName: String, directoryCertificate: String) {
  180. let currentServerCert = secTrustGetLeafCertificate(trust)
  181. let certNamePath = directoryCertificate + "/" + certName
  182. let data: CFData = SecCertificateCopyData(currentServerCert!)
  183. let mem = BIO_new_mem_buf(CFDataGetBytePtr(data), Int32(CFDataGetLength(data)))
  184. let x509cert = d2i_X509_bio(mem, nil)
  185. BIO_free(mem)
  186. if x509cert == nil {
  187. print("[LOG] OpenSSL couldn't parse X509 Certificate")
  188. } else {
  189. if FileManager.default.fileExists(atPath: certNamePath) {
  190. do {
  191. try FileManager.default.removeItem(atPath: certNamePath)
  192. } catch { }
  193. }
  194. let file = fopen(certNamePath, "w")
  195. if file != nil {
  196. PEM_write_X509(file, x509cert);
  197. }
  198. fclose(file);
  199. X509_free(x509cert);
  200. }
  201. }
  202. private func secTrustGetLeafCertificate(_ trust: SecTrust) -> SecCertificate? {
  203. let result: SecCertificate?
  204. if SecTrustGetCertificateCount(trust) > 0 {
  205. result = SecTrustGetCertificateAtIndex(trust, 0)!
  206. assert(result != nil);
  207. } else {
  208. result = nil
  209. }
  210. return result
  211. }
  212. //MARK: - Utility
  213. func cancelTaskWithUrl(_ url: URL) {
  214. NCCommunication.shared.getSessionManager().getAllTasks { tasks in
  215. tasks.filter { $0.state == .running }.filter { $0.originalRequest?.url == url }.first?.cancel()
  216. }
  217. }
  218. @objc func cancelAllTask() {
  219. NCCommunication.shared.getSessionManager().getAllTasks { tasks in
  220. for task in tasks {
  221. task.cancel()
  222. }
  223. }
  224. }
  225. //MARK: - Download
  226. @objc func cancelDownload(ocId: String, serverUrl:String, fileNameView: String) {
  227. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView) else { return }
  228. if let request = downloadRequest[fileNameLocalPath] {
  229. request.cancel()
  230. } else {
  231. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  232. NCManageDatabase.shared.setMetadataSession(ocId: ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  233. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadCancelFile, userInfo: ["ocId":metadata.ocId])
  234. }
  235. }
  236. }
  237. @objc func download(metadata: tableMetadata, selector: String, completion: @escaping (_ errorCode: Int)->()) {
  238. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  239. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
  240. if NCManageDatabase.shared.getMetadataFromOcId(metadata.ocId) == nil {
  241. NCManageDatabase.shared.addMetadata(tableMetadata.init(value: metadata))
  242. }
  243. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading { return }
  244. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: NCCommunicationCommon.shared.sessionIdentifierDownload, sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusInDownload)
  245. NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { (request) in
  246. self.downloadRequest[fileNameLocalPath] = request
  247. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusDownloading)
  248. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadStartFile, userInfo: ["ocId":metadata.ocId])
  249. }, taskHandler: { (_) in
  250. }, progressHandler: { (progress) in
  251. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterProgressTask, object: nil, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "status":NSNumber(value: NCGlobal.shared.metadataStatusInDownload), "progress":NSNumber(value: progress.fractionCompleted), "totalBytes":NSNumber(value: progress.totalUnitCount), "totalBytesExpected":NSNumber(value: progress.completedUnitCount)])
  252. }) { (account, etag, date, length, allHeaderFields, error, errorCode, errorDescription) in
  253. if error?.isExplicitlyCancelledError ?? false {
  254. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  255. } else if errorCode == 0 {
  256. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal, etag: etag)
  257. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  258. #if !EXTENSION
  259. if let result = NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "fileNameIdentifier == %@ AND serverUrl == %@", metadata.fileName, metadata.serverUrl)) {
  260. NCEndToEndEncryption.sharedManager()?.decryptFileName(metadata.fileName, fileNameView: metadata.fileNameView, ocId: metadata.ocId, key: result.key, initializationVector: result.initializationVector, authenticationTag: result.authenticationTag)
  261. }
  262. CCUtility.setExif(metadata) { (latitude, longitude, location, date, lensMode) in };
  263. #endif
  264. } else {
  265. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: errorDescription, sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusDownloadError)
  266. #if !EXTENSION
  267. if errorCode == 401 || errorCode == 403 {
  268. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account)
  269. } else if errorCode == Int(CFNetworkErrors.cfurlErrorServerCertificateUntrusted.rawValue) {
  270. CCUtility.setCertificateError(metadata.account, error: true)
  271. }
  272. #endif
  273. }
  274. self.downloadRequest[fileNameLocalPath] = nil
  275. if error?.isExplicitlyCancelledError ?? false {
  276. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadCancelFile, userInfo: ["ocId":metadata.ocId])
  277. } else {
  278. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId":metadata.ocId, "selector":selector, "errorCode":errorCode, "errorDescription":errorDescription])
  279. }
  280. completion(errorCode)
  281. }
  282. }
  283. //MARK: - Upload
  284. @objc func upload(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  285. let metadata = tableMetadata.init(value: metadata)
  286. guard let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account)) else {
  287. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  288. completion(NCGlobal.shared.errorInternalError, "Internal error")
  289. return
  290. }
  291. var fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  292. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  293. let metadata = tableMetadata.init(value: metadata)
  294. let results = NCCommunicationCommon.shared.getInternalType(fileName: metadata.fileNameView, mimeType: metadata.contentType, directory: false)
  295. metadata.contentType = results.mimeType
  296. metadata.iconName = results.iconName
  297. metadata.typeFile = results.typeFile
  298. if let date = NCUtilityFileSystem.shared.getFileCreationDate(filePath: fileNameLocalPath) {
  299. metadata.creationDate = date
  300. }
  301. if let date = NCUtilityFileSystem.shared.getFileModificationDate(filePath: fileNameLocalPath) {
  302. metadata.date = date
  303. }
  304. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath)
  305. NCManageDatabase.shared.addMetadata(metadata)
  306. if metadata.e2eEncrypted {
  307. #if !EXTENSION_FILE_PROVIDER_EXTENSION
  308. NCNetworkingE2EE.shared.upload(metadata: tableMetadata.init(value: metadata), account: account, start: { start() }, completion: completion)
  309. #endif
  310. } else if metadata.chunk {
  311. uploadChunkedFile(metadata: tableMetadata.init(value: metadata), userId: account.userId, start: { start() }, completion: completion)
  312. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  313. uploadFile(metadata: tableMetadata.init(value: metadata), account: account, start: { start() }, completion: completion)
  314. } else {
  315. uploadFileInBackground(metadata: tableMetadata.init(value: metadata), account: account, start: { start() }, completion: completion)
  316. }
  317. } else {
  318. CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadata, notification: true) { (extractMetadata, fileNamePath) in
  319. guard let extractMetadata = extractMetadata else {
  320. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  321. completion(NCGlobal.shared.errorInternalError, "Internal error")
  322. return
  323. }
  324. fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(extractMetadata.ocId, fileNameView: extractMetadata.fileNameView)
  325. NCUtilityFileSystem.shared.moveFileInBackground(atPath: fileNamePath!, toPath: fileNameLocalPath)
  326. NCManageDatabase.shared.addMetadata(extractMetadata)
  327. if metadata.e2eEncrypted {
  328. #if !EXTENSION_FILE_PROVIDER_EXTENSION
  329. NCNetworkingE2EE.shared.upload(metadata: tableMetadata.init(value: extractMetadata), account: account, start: { start() }, completion: completion)
  330. #endif
  331. } else if metadata.chunk {
  332. self.uploadChunkedFile(metadata: tableMetadata.init(value: metadata), userId: account.userId, start: { start() }, completion: completion)
  333. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  334. self.uploadFile(metadata: tableMetadata.init(value: extractMetadata), account: account, start: { start() }, completion: completion)
  335. } else {
  336. self.uploadFileInBackground(metadata: tableMetadata.init(value: extractMetadata), account: account, start: { start() }, completion: completion)
  337. }
  338. }
  339. }
  340. }
  341. private func uploadFile(metadata: tableMetadata, account: tableAccount, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  342. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  343. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  344. var uploadTask: URLSessionTask?
  345. let description = metadata.ocId
  346. NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.creationDate as Date, dateModificationFile: metadata.date as Date, customUserAgent: nil, addCustomHeaders: nil, requestHandler: { (request) in
  347. self.uploadRequest[fileNameLocalPath] = request
  348. }, taskHandler: { (task) in
  349. uploadTask = task
  350. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  351. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId":metadata.ocId])
  352. start()
  353. }, progressHandler: { (progress) in
  354. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterProgressTask, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "status":NSNumber(value: NCGlobal.shared.metadataStatusInUpload), "progress":NSNumber(value: progress.fractionCompleted), "totalBytes":NSNumber(value: progress.totalUnitCount), "totalBytesExpected":NSNumber(value: progress.completedUnitCount)])
  355. }) { (account, ocId, etag, date, size, allHeaderFields, error, errorCode, errorDescription) in
  356. self.uploadRequest[fileNameLocalPath] = nil
  357. self.uploadComplete(fileName: metadata.fileName, serverUrl: metadata.serverUrl, ocId: ocId, etag: etag, date: date, size: size, description: description, task: uploadTask!, errorCode: errorCode, errorDescription: errorDescription)
  358. completion(errorCode, errorDescription)
  359. }
  360. }
  361. private func uploadFileInBackground(metadata: tableMetadata, account: tableAccount, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  362. var session: URLSession?
  363. let metadata = tableMetadata.init(value: metadata)
  364. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  365. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  366. if metadata.session == sessionIdentifierBackground || metadata.session == sessionIdentifierBackgroundExtension {
  367. session = sessionManagerBackground
  368. } else if metadata.session == sessionIdentifierBackgroundWWan {
  369. session = sessionManagerBackgroundWWan
  370. }
  371. start()
  372. // Check file dim > 0
  373. if NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath) == 0 {
  374. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  375. completion(404, NSLocalizedString("_error_not_found_", value: "The requested resource could not be found", comment: ""))
  376. } else {
  377. 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!) {
  378. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  379. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId":metadata.ocId])
  380. completion(0, "")
  381. } else {
  382. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  383. completion(NCGlobal.shared.errorInternalError, "task null")
  384. }
  385. }
  386. }
  387. func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  388. if delegate != nil {
  389. delegate?.uploadComplete?(fileName: fileName, serverUrl: serverUrl, ocId: ocId, etag: etag, date: date, size:size, description: description, task: task, errorCode: errorCode, errorDescription: errorDescription)
  390. } else {
  391. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(description) else { return }
  392. guard let tableAccount = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account)) else { return }
  393. let ocIdTemp = metadata.ocId
  394. var errorDescription = errorDescription
  395. if errorCode == 0 && ocId != nil && size > 0 {
  396. let metadata = tableMetadata.init(value: metadata)
  397. NCUtilityFileSystem.shared.moveFileInBackground(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
  398. metadata.uploadDate = date ?? NSDate()
  399. metadata.etag = etag ?? ""
  400. metadata.ocId = ocId!
  401. if let fileId = NCUtility.shared.ocIdToFileId(ocId: ocId) {
  402. metadata.fileId = fileId
  403. }
  404. metadata.session = ""
  405. metadata.sessionError = ""
  406. metadata.sessionTaskIdentifier = 0
  407. metadata.status = NCGlobal.shared.metadataStatusNormal
  408. // Delete Asset on Photos album
  409. if tableAccount.autoUploadDeleteAssetLocalIdentifier && metadata.assetLocalIdentifier != "" && metadata.sessionSelector == NCGlobal.shared.selectorUploadAutoUpload {
  410. metadata.deleteAssetLocalIdentifier = true;
  411. }
  412. if CCUtility.getDisableLocalCacheAfterUpload() {
  413. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  414. } else {
  415. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  416. }
  417. NCManageDatabase.shared.addMetadata(metadata)
  418. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  419. #if !EXTENSION
  420. self.getOcIdInBackgroundSession { (listOcId) in
  421. if listOcId.count == 0 && self.uploadRequest.count == 0 {
  422. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  423. appDelegate.networkingProcessUpload?.startProcess()
  424. }
  425. }
  426. CCUtility.setExif(metadata) { (latitude, longitude, location, date, lensMode) in };
  427. #endif
  428. NCCommunicationCommon.shared.writeLog("Upload complete " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)")
  429. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":ocIdTemp, "errorCode":errorCode, "errorDescription":""])
  430. } else {
  431. if errorCode == NSURLErrorCancelled || errorCode == NCGlobal.shared.errorRequestExplicityCancelled {
  432. if metadata.status == NCGlobal.shared.metadataStatusUploadForcedStart {
  433. NCManageDatabase.shared.setMetadataSession(ocId: ocId!, session: sessionIdentifierBackground, sessionError: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusInUpload)
  434. NCNetworking.shared.upload(metadata: metadata) { } completion: { (_, _) in }
  435. } else {
  436. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  437. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  438. }
  439. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
  440. } else if errorCode == 401 || errorCode == 403 {
  441. #if !EXTENSION
  442. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account)
  443. #endif
  444. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  445. } else if errorCode == Int(CFNetworkErrors.cfurlErrorServerCertificateUntrusted.rawValue) {
  446. CCUtility.setCertificateError(metadata.account, error: true)
  447. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  448. } else {
  449. if size == 0 {
  450. errorDescription = "File length 0"
  451. NCCommunicationCommon.shared.writeLog("Upload error 0 length " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)")
  452. }
  453. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  454. }
  455. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":ocIdTemp, "errorCode":errorCode, "errorDescription":""])
  456. }
  457. // Delete
  458. self.uploadMetadataInBackground[fileName+serverUrl] = nil
  459. }
  460. }
  461. func uploadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  462. delegate?.uploadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  463. var metadata: tableMetadata?
  464. let description: String = task.taskDescription ?? ""
  465. if let metadataTmp = self.uploadMetadataInBackground[fileName+serverUrl] {
  466. metadata = metadataTmp
  467. } else if let metadataTmp = NCManageDatabase.shared.getMetadataFromOcId(description){
  468. self.uploadMetadataInBackground[fileName+serverUrl] = metadataTmp
  469. metadata = metadataTmp
  470. }
  471. if metadata != nil {
  472. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterProgressTask, userInfo: ["account":metadata!.account, "ocId":metadata!.ocId, "serverUrl":serverUrl, "status":NSNumber(value: NCGlobal.shared.metadataStatusInUpload), "progress":NSNumber(value: progress), "totalBytes":NSNumber(value: totalBytes), "totalBytesExpected":NSNumber(value: totalBytesExpected)])
  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: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
  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: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
  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: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
  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, NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusUploadError))
  549. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status != %d", NCGlobal.shared.metadataStatusNormal))
  550. var counter = 0
  551. for metadata in metadatas {
  552. counter += 1
  553. if (metadata.status == NCGlobal.shared.metadataStatusWaitDownload || metadata.status == NCGlobal.shared.metadataStatusDownloadError) {
  554. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  555. }
  556. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.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, NCGlobal.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: NCGlobal.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. 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 result = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase)
  671. if useSubFolder && result {
  672. for dateSubFolder in CCUtility.createNameSubFolder(assets) {
  673. let fileName = (dateSubFolder as! NSString).lastPathComponent
  674. let serverUrl = ((autoUploadPath + "/" + (dateSubFolder as! String)) as NSString).deletingLastPathComponent
  675. result = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase)
  676. if !result { break }
  677. }
  678. }
  679. return result
  680. }
  681. private func createFolderWithSemaphore(fileName: String, serverUrl: String, account: String, urlBase: String) -> Bool {
  682. var result: Bool = false
  683. let semaphore = Semaphore()
  684. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: true) { (errorCode, errorDescription) in
  685. if errorCode == 0 { result = true }
  686. semaphore.continue()
  687. }
  688. if semaphore.wait() == .success { result = true }
  689. return result
  690. }
  691. //MARK: - WebDav Delete
  692. @objc func deleteMetadata(_ metadata: tableMetadata, account: String, urlBase: String, onlyLocal: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  693. if (onlyLocal) {
  694. var metadatas = [metadata]
  695. if metadata.directory {
  696. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  697. metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND directory == false", account, serverUrl))
  698. }
  699. for metadata in metadatas {
  700. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  701. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  702. if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  703. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadataLivePhoto.ocId))
  704. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadataLivePhoto.ocId))
  705. }
  706. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "typeFile": metadata.typeFile, "onlyLocal": true])
  707. }
  708. completion(0, "")
  709. return
  710. }
  711. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: urlBase)
  712. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  713. if isDirectoryEncrypted {
  714. #if !EXTENSION
  715. if metadataLive == nil {
  716. NCNetworkingE2EE.shared.deleteMetadata(metadata, urlBase: urlBase, completion: completion)
  717. } else {
  718. NCNetworkingE2EE.shared.deleteMetadata(metadataLive!, urlBase: urlBase) { (errorCode, errorDescription) in
  719. if errorCode == 0 {
  720. NCNetworkingE2EE.shared.deleteMetadata(metadata, urlBase: urlBase, completion: completion)
  721. } else {
  722. completion(errorCode, errorDescription)
  723. }
  724. }
  725. }
  726. #endif
  727. } else {
  728. if metadataLive == nil {
  729. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  730. } else {
  731. self.deleteMetadataPlain(metadataLive!, addCustomHeaders: nil) { (errorCode, errorDescription) in
  732. if errorCode == 0 {
  733. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  734. } else {
  735. completion(errorCode, errorDescription)
  736. }
  737. }
  738. }
  739. }
  740. }
  741. func deleteMetadataPlain(_ metadata: tableMetadata, addCustomHeaders: [String: String]?, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  742. // verify permission
  743. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanDelete)
  744. if metadata.permissions != "" && permission == false {
  745. completion(NCGlobal.shared.errorInternalError, "_no_permission_delete_file_")
  746. return
  747. }
  748. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  749. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName, customUserAgent: nil, addCustomHeaders: addCustomHeaders) { (account, errorCode, errorDescription) in
  750. if errorCode == 0 || errorCode == NCGlobal.shared.errorResourceNotFound {
  751. do {
  752. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  753. } catch { }
  754. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  755. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  756. if metadata.directory {
  757. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account)
  758. }
  759. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "typeFile": metadata.typeFile, "onlyLocal": true])
  760. }
  761. completion(errorCode, errorDescription)
  762. }
  763. }
  764. //MARK: - WebDav Favorite
  765. @objc func favoriteMetadata(_ metadata: tableMetadata, urlBase: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  766. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  767. favoriteMetadataPlain(metadataLive, urlBase: urlBase) { (errorCode, errorDescription) in
  768. if errorCode == 0 {
  769. self.favoriteMetadataPlain(metadata, urlBase: urlBase, completion: completion)
  770. } else {
  771. completion(errorCode, errorDescription)
  772. }
  773. }
  774. } else {
  775. favoriteMetadataPlain(metadata, urlBase: urlBase, completion: completion)
  776. }
  777. }
  778. private func favoriteMetadataPlain(_ metadata: tableMetadata, urlBase: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  779. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: urlBase, account: metadata.account)!
  780. let favorite = !metadata.favorite
  781. let ocId = metadata.ocId
  782. NCCommunication.shared.setFavorite(fileName: fileName, favorite: favorite) { (account, errorCode, errorDescription) in
  783. if errorCode == 0 && metadata.account == account {
  784. NCManageDatabase.shared.setMetadataFavorite(ocId: metadata.ocId, favorite: favorite)
  785. #if !EXTENSION
  786. if favorite {
  787. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorReadFile)
  788. }
  789. #endif
  790. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  791. NotificationCenter.default.postOnMainThread(name: NCGlobal.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 != NCGlobal.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.getMetadataLivePhoto(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: NCGlobal.shared.permissionCanRename)
  851. if !(metadata.permissions == "") && !permission {
  852. completion(NCGlobal.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. let ext = (metadata.fileName as NSString).pathExtension
  877. let extNew = (fileNameNew as NSString).pathExtension
  878. if ext != extNew {
  879. if let path = CCUtility.getDirectoryProviderStorageOcId(ocId) {
  880. NCUtilityFileSystem.shared.deleteFile(filePath: path)
  881. }
  882. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": metadata.serverUrl])
  883. } else {
  884. NCManageDatabase.shared.setLocalFile(ocId: ocId, fileName: fileNameNew, etag: nil)
  885. // Move file system
  886. let atPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + metadata.fileName
  887. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + fileNameNew
  888. do {
  889. try FileManager.default.moveItem(atPath: atPath, toPath: toPath)
  890. } catch { }
  891. }
  892. }
  893. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  894. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRenameFile, userInfo: ["ocId": metadata.ocId])
  895. }
  896. }
  897. completion(errorCode, errorDescription)
  898. }
  899. }
  900. //MARK: - WebDav Move
  901. @objc func moveMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  902. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  903. moveMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  904. if errorCode == 0 {
  905. self.moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  906. } else {
  907. completion(errorCode, errorDescription)
  908. }
  909. }
  910. } else {
  911. moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  912. }
  913. }
  914. private func moveMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  915. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  916. if !(metadata.permissions == "") && !permission {
  917. completion(NCGlobal.shared.errorInternalError, "_no_permission_modify_file_")
  918. return
  919. }
  920. let serverUrlFrom = metadata.serverUrl
  921. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  922. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  923. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  924. if errorCode == 0 {
  925. if metadata.directory {
  926. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: account)
  927. }
  928. NCManageDatabase.shared.moveMetadata(ocId: metadata.ocId, serverUrlTo: serverUrlTo)
  929. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMoveFile, userInfo: ["ocId": metadata.ocId, "serverUrlFrom": serverUrlFrom])
  930. }
  931. completion(errorCode, errorDescription)
  932. }
  933. }
  934. //MARK: - WebDav Copy
  935. @objc func copyMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  936. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  937. copyMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  938. if errorCode == 0 {
  939. self.copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  940. } else {
  941. completion(errorCode, errorDescription)
  942. }
  943. }
  944. } else {
  945. copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  946. }
  947. }
  948. private func copyMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  949. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  950. if !(metadata.permissions == "") && !permission {
  951. completion(NCGlobal.shared.errorInternalError, "_no_permission_modify_file_")
  952. return
  953. }
  954. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  955. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  956. NCCommunication.shared.copyFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  957. if errorCode == 0 {
  958. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCopyFile, userInfo: ["ocId": metadata.ocId, "serverUrlTo": serverUrlTo])
  959. }
  960. completion(errorCode, errorDescription)
  961. }
  962. }
  963. //MARK: - TEST API
  964. /*
  965. @objc public func getAppPassword(serverUrl: String, username: String, password: String, customUserAgent: String? = nil, completionHandler: @escaping (_ token: String?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  966. let endpoint = "/ocs/v2.php/core/getapppassword"
  967. let url:URLConvertible = try! (serverUrl + endpoint).asURL() as URLConvertible
  968. var headers: HTTPHeaders = [.authorization(username: username, password: password)]
  969. if customUserAgent != nil {
  970. headers.update(.userAgent(customUserAgent!))
  971. }
  972. //headers.update(.contentType("application/json"))
  973. headers.update(name: "OCS-APIRequest", value: "true")
  974. var urlRequest: URLRequest
  975. do {
  976. try urlRequest = URLRequest(url: url, method: HTTPMethod(rawValue: "GET"), headers: headers)
  977. } catch {
  978. completionHandler(nil, error._code, error.localizedDescription)
  979. return
  980. }
  981. AF.request(urlRequest).validate(statusCode: 200..<300).response { (response) in
  982. debugPrint(response)
  983. switch response.result {
  984. case .failure(let error):
  985. completionHandler(nil, 0, "")
  986. case .success(let data):
  987. if let data = data {
  988. completionHandler("", 0, "")
  989. } else {
  990. completionHandler(nil, NSURLErrorBadServerResponse, NSLocalizedString("_error_decode_xml_", value: "Invalid response, error decode XML", comment: ""))
  991. }
  992. }
  993. }
  994. }
  995. */
  996. }