NCNetworking.swift 75 KB

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