NCNetworking.swift 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  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. let folder = NSUUID().uuidString
  350. let uploadFolder = metadata.urlBase + "/" + NCUtilityFileSystem.shared.getDAV() + "/uploads/" + account.userId + "/" + folder
  351. var uploadErrorCode: Int = 0
  352. var uploadErrorDescription = ""
  353. NCCommunication.shared.createFolder(uploadFolder) { (account, ocId, date, errorCode, errorDescription) in
  354. if errorCode == 0 {
  355. let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)!
  356. if let filesNames = self.fileChunks(path: path, fileName: metadata.fileName, pathChunks: path, size: 10) {
  357. DispatchQueue.global(qos: .background).async {
  358. for fileName in filesNames {
  359. let serverUrlFileName = uploadFolder + "/" + fileName
  360. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: fileName)!
  361. let semaphore = Semaphore()
  362. NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.creationDate as Date, dateModificationFile: metadata.date as Date, customUserAgent: nil, addCustomHeaders: nil, requestHandler: { (request) in
  363. //
  364. }, taskHandler: { (task) in
  365. //
  366. }, progressHandler: { (progress) in
  367. //
  368. }) { (account, ocId, etag, date, size, allHeaderFields, error, errorCode, errorDescription) in
  369. uploadErrorCode = errorCode
  370. uploadErrorDescription = errorDescription
  371. semaphore.continue()
  372. }
  373. semaphore.wait()
  374. if uploadErrorCode != 0 {
  375. print("error upload")
  376. break
  377. }
  378. }
  379. if uploadErrorCode == 0 {
  380. // Assembling the chunks
  381. //curl -X MOVE -u roeland:pass --header 'Destination:https://server/remote.php/dav/files/roeland/dest/file.zip' https://server/remote.php/dav/uploads/roeland/myapp-e1663913-4423-4efe-a9cd-26e7beeca3c0/.file
  382. } else {
  383. // delete
  384. //curl -X DELETE -u roeland:pass https://server/remote.php/dav/uploads/roeland/myapp-e1663913-4423-4efe-a9cd-26e7beeca3c0/
  385. }
  386. }
  387. } else {
  388. print("error chunk filename")
  389. }
  390. } else {
  391. print("error create directory")
  392. }
  393. }
  394. }
  395. private func uploadFileInBackground(metadata: tableMetadata, account: tableAccount, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  396. var session: URLSession?
  397. let metadata = tableMetadata.init(value: metadata)
  398. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  399. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  400. if metadata.session == sessionIdentifierBackground || metadata.session == sessionIdentifierBackgroundExtension {
  401. session = sessionManagerBackground
  402. } else if metadata.session == sessionIdentifierBackgroundWWan {
  403. session = sessionManagerBackgroundWWan
  404. }
  405. // Check file dim > 0
  406. if NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath) == 0 {
  407. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  408. completion(404, NSLocalizedString("_error_not_found_", value: "The requested resource could not be found", comment: ""))
  409. } else {
  410. 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!) {
  411. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  412. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId":metadata.ocId])
  413. completion(0, "")
  414. } else {
  415. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  416. completion(NCGlobal.shared.ErrorInternalError, "task null")
  417. }
  418. }
  419. }
  420. func uploadProgress(_ progress: Double, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  421. delegate?.uploadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  422. var metadata: tableMetadata?
  423. let description: String = task.taskDescription ?? ""
  424. if let metadataTmp = self.uploadMetadataInBackground[fileName+serverUrl] {
  425. metadata = metadataTmp
  426. } else if let metadataTmp = NCManageDatabase.shared.getMetadataFromOcId(description){
  427. self.uploadMetadataInBackground[fileName+serverUrl] = metadataTmp
  428. metadata = metadataTmp
  429. }
  430. if metadata != nil {
  431. 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)])
  432. }
  433. }
  434. func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  435. if delegate != nil {
  436. delegate?.uploadComplete?(fileName: fileName, serverUrl: serverUrl, ocId: ocId, etag: etag, date: date, size:size, description: description, task: task, errorCode: errorCode, errorDescription: errorDescription)
  437. } else {
  438. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(description) else { return }
  439. guard let tableAccount = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account)) else { return }
  440. let ocIdTemp = metadata.ocId
  441. var errorDescription = errorDescription
  442. if errorCode == 0 && ocId != nil && size > 0 {
  443. let metadata = tableMetadata.init(value: metadata)
  444. NCUtilityFileSystem.shared.moveFileInBackground(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
  445. metadata.uploadDate = date ?? NSDate()
  446. metadata.etag = etag ?? ""
  447. metadata.ocId = ocId!
  448. if let fileId = NCUtility.shared.ocIdToFileId(ocId: ocId) {
  449. metadata.fileId = fileId
  450. }
  451. metadata.session = ""
  452. metadata.sessionError = ""
  453. metadata.sessionTaskIdentifier = 0
  454. metadata.status = NCGlobal.shared.metadataStatusNormal
  455. // Delete Asset on Photos album
  456. if tableAccount.autoUploadDeleteAssetLocalIdentifier && metadata.assetLocalIdentifier != "" && metadata.sessionSelector == NCGlobal.shared.selectorUploadAutoUpload {
  457. metadata.deleteAssetLocalIdentifier = true;
  458. }
  459. if CCUtility.getDisableLocalCacheAfterUpload() {
  460. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  461. } else {
  462. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  463. }
  464. NCManageDatabase.shared.addMetadata(metadata)
  465. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  466. #if !EXTENSION
  467. self.getOcIdInBackgroundSession { (listOcId) in
  468. if listOcId.count == 0 && self.uploadRequest.count == 0 {
  469. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  470. appDelegate.networkingProcessUpload?.startProcess()
  471. }
  472. }
  473. CCUtility.setExif(metadata) { (latitude, longitude, location, date, lensMode) in };
  474. #endif
  475. NCCommunicationCommon.shared.writeLog("Upload complete " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)")
  476. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":ocIdTemp, "errorCode":errorCode, "errorDescription":""])
  477. } else {
  478. if errorCode == NSURLErrorCancelled || errorCode == NCGlobal.shared.ErrorRequestExplicityCancelled {
  479. if metadata.status == NCGlobal.shared.metadataStatusUploadForcedStart {
  480. NCManageDatabase.shared.setMetadataSession(ocId: ocId!, session: sessionIdentifierBackground, sessionError: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusInUpload)
  481. NCNetworking.shared.upload(metadata: metadata) { (_, _) in }
  482. } else {
  483. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  484. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  485. }
  486. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
  487. } else if errorCode == 401 || errorCode == 403 {
  488. #if !EXTENSION
  489. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account)
  490. #endif
  491. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  492. } else if errorCode == Int(CFNetworkErrors.cfurlErrorServerCertificateUntrusted.rawValue) {
  493. CCUtility.setCertificateError(metadata.account, error: true)
  494. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  495. } else {
  496. if size == 0 {
  497. errorDescription = "File length 0"
  498. NCCommunicationCommon.shared.writeLog("Upload error 0 length " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)")
  499. }
  500. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  501. }
  502. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId":metadata.ocId, "ocIdTemp":ocIdTemp, "errorCode":errorCode, "errorDescription":""])
  503. }
  504. // Delete
  505. self.uploadMetadataInBackground[fileName+serverUrl] = nil
  506. }
  507. }
  508. @objc func verifyUploadZombie() {
  509. var session: URLSession?
  510. // verify metadataStatusInUpload (BACKGROUND)
  511. 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))
  512. for metadata in metadatasInUploadBackground {
  513. DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
  514. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d AND sessionTaskIdentifier == 0", metadata.ocId, NCGlobal.shared.metadataStatusInUpload)) {
  515. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: self.sessionIdentifierBackground, sessionError: "", sessionSelector: nil, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusWaitUpload)
  516. }
  517. }
  518. }
  519. // metadataStatusUploading (BACKGROUND)
  520. let metadatasUploadingBackground = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "(session == %@ OR session == %@ OR session == %@) AND status == %d", sessionIdentifierBackground, sessionIdentifierBackgroundWWan, sessionIdentifierBackgroundExtension, NCGlobal.shared.metadataStatusUploading))
  521. for metadata in metadatasUploadingBackground {
  522. if metadata.session == sessionIdentifierBackground {
  523. session = self.sessionManagerBackground
  524. } else if metadata.session == sessionIdentifierBackgroundWWan {
  525. session = self.sessionManagerBackgroundWWan
  526. }
  527. var taskUpload: URLSessionTask?
  528. session?.getAllTasks(completionHandler: { (tasks) in
  529. for task in tasks {
  530. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  531. taskUpload = task
  532. }
  533. }
  534. if taskUpload == nil {
  535. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d", metadata.ocId, NCGlobal.shared.metadataStatusUploading)) {
  536. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: self.sessionIdentifierBackground, sessionError: "", sessionSelector: nil, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusWaitUpload)
  537. }
  538. }
  539. })
  540. }
  541. // metadataStatusUploading
  542. let metadatasUploading = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d", NCCommunicationCommon.shared.sessionIdentifierUpload, NCGlobal.shared.metadataStatusUploading))
  543. for metadata in metadatasUploading {
  544. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  545. if uploadRequest[fileNameLocalPath] == nil {
  546. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: "", sessionSelector: nil, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusWaitUpload)
  547. }
  548. }
  549. }
  550. func getOcIdInBackgroundSession(completion: @escaping (_ listOcId: [String])->()) {
  551. var listOcId: [String] = []
  552. sessionManagerBackground.getAllTasks(completionHandler: { (tasks) in
  553. for task in tasks {
  554. listOcId.append(task.description)
  555. }
  556. self.sessionManagerBackgroundWWan.getAllTasks(completionHandler: { (tasks) in
  557. for task in tasks {
  558. listOcId.append(task.description)
  559. }
  560. completion(listOcId)
  561. })
  562. })
  563. }
  564. //MARK: - Transfer (Download Upload)
  565. @objc func cancelTransferMetadata(_ metadata: tableMetadata, completion: @escaping ()->()) {
  566. let metadata = tableMetadata.init(value: metadata)
  567. if metadata.session.count == 0 {
  568. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  569. completion()
  570. return
  571. }
  572. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierDownload {
  573. NCNetworking.shared.cancelDownload(ocId: metadata.ocId, serverUrl: metadata.serverUrl, fileNameView: metadata.fileNameView)
  574. completion()
  575. return
  576. }
  577. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  578. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else { return }
  579. if let request = uploadRequest[fileNameLocalPath] {
  580. request.cancel()
  581. } else {
  582. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  583. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  584. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
  585. }
  586. completion()
  587. return
  588. }
  589. var session: URLSession?
  590. if metadata.session == NCNetworking.shared.sessionIdentifierBackground {
  591. session = NCNetworking.shared.sessionManagerBackground
  592. } else if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundWWan {
  593. session = NCNetworking.shared.sessionManagerBackgroundWWan
  594. }
  595. if session == nil {
  596. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  597. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
  598. completion()
  599. return
  600. }
  601. session?.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  602. var cancel = false
  603. if metadata.session.count > 0 && metadata.session.contains("upload") {
  604. for task in uploadTasks {
  605. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  606. task.cancel()
  607. cancel = true
  608. }
  609. }
  610. if cancel == false {
  611. do {
  612. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  613. }
  614. catch { }
  615. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  616. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId":metadata.ocId, "serverUrl":metadata.serverUrl, "account":metadata.account])
  617. }
  618. }
  619. completion()
  620. }
  621. }
  622. @objc func cancelAllTransfer(account: String, completion: @escaping ()->()) {
  623. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", account, NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusUploadError))
  624. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status != %d", NCGlobal.shared.metadataStatusNormal))
  625. var counter = 0
  626. for metadata in metadatas {
  627. counter += 1
  628. if (metadata.status == NCGlobal.shared.metadataStatusWaitDownload || metadata.status == NCGlobal.shared.metadataStatusDownloadError) {
  629. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  630. }
  631. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  632. self.cancelTransferMetadata(metadata) {
  633. if counter == metadatas.count {
  634. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  635. completion()
  636. }
  637. }
  638. }
  639. }
  640. }
  641. #if !EXTENSION
  642. NCOperationQueue.shared.downloadCancelAll()
  643. #endif
  644. }
  645. //MARK: - WebDav Read file, folder
  646. @objc func readFolder(serverUrl: String, account: String, completion: @escaping (_ account: String, _ metadataFolder: tableMetadata?, _ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ metadatasLocalUpdate: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  647. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
  648. if errorCode == 0 {
  649. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: true, account: account) { (metadataFolder, metadatasFolder, metadatas) in
  650. // Add metadata folder
  651. NCManageDatabase.shared.addMetadata(tableMetadata.init(value: metadataFolder))
  652. // Update directory
  653. 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)
  654. // Update sub directories
  655. for metadata in metadatasFolder {
  656. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  657. 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)
  658. }
  659. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, NCGlobal.shared.metadataStatusNormal))
  660. let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareEtagLocal: true)
  661. completion(account, metadataFolder, metadatas, metadatasChanged.metadatasUpdate, metadatasChanged.metadatasLocalUpdate, errorCode, "")
  662. }
  663. } else {
  664. completion(account, nil, nil, nil, nil, errorCode, errorDescription)
  665. }
  666. }
  667. }
  668. @objc func readFile(serverUrlFileName: String, account: String, completion: @escaping (_ account: String, _ metadata: tableMetadata?, _ errorCode: Int, _ errorDescription: String)->()) {
  669. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, responseData, errorCode, errorDescription) in
  670. if errorCode == 0 && files.count == 1 {
  671. let file = files[0]
  672. let isEncrypted = CCUtility.isFolderEncrypted(file.serverUrl, e2eEncrypted:file.e2eEncrypted, account: account, urlBase: file.urlBase)
  673. let metadata = NCManageDatabase.shared.convertNCFileToMetadata(file, isEncrypted: isEncrypted, account: account)
  674. completion(account, metadata, errorCode, errorDescription)
  675. } else {
  676. completion(account, nil, errorCode, errorDescription)
  677. }
  678. }
  679. }
  680. //MARK: - WebDav Search
  681. @objc func searchFiles(urlBase: String, user: String, literal: String, completion: @escaping (_ account: String, _ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  682. NCCommunication.shared.searchLiteral(serverUrl: urlBase, depth: "infinity", literal: literal, showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, errorCode, errorDescription) in
  683. if errorCode == 0 {
  684. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (metadataFolder, metadatasFolder, metadatas) in
  685. // Update sub directories
  686. for metadata in metadatasFolder {
  687. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  688. 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)
  689. }
  690. NCManageDatabase.shared.addMetadatas(metadatas)
  691. let metadatas = Array(metadatas.map { tableMetadata.init(value:$0) })
  692. completion(account, metadatas, errorCode, errorDescription)
  693. }
  694. } else {
  695. completion(account, nil, errorCode, errorDescription)
  696. }
  697. }
  698. }
  699. //MARK: - WebDav Create Folder
  700. @objc func createFolder(fileName: String, serverUrl: String, account: String, urlBase: String, overwrite: Bool = false, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  701. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: false, account: account, urlBase: urlBase)
  702. if isDirectoryEncrypted {
  703. #if !EXTENSION
  704. NCNetworkingE2EE.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, completion: completion)
  705. #endif
  706. } else {
  707. createFolderPlain(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: overwrite, completion: completion)
  708. }
  709. }
  710. private func createFolderPlain(fileName: String, serverUrl: String, account: String, urlBase: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  711. var fileNameFolder = CCUtility.removeForbiddenCharactersServer(fileName)!
  712. if (!overwrite) {
  713. fileNameFolder = NCUtilityFileSystem.shared.createFileName(fileNameFolder, serverUrl: serverUrl, account: account)
  714. }
  715. if fileNameFolder.count == 0 {
  716. completion(0, "")
  717. return
  718. }
  719. let fileNameFolderUrl = serverUrl + "/" + fileNameFolder
  720. NCCommunication.shared.createFolder(fileNameFolderUrl) { (account, ocId, date, errorCode, errorDescription) in
  721. if errorCode == 0 {
  722. self.readFile(serverUrlFileName: fileNameFolderUrl, account: account) { (account, metadataFolder, errorCode, errorDescription) in
  723. if errorCode == 0 {
  724. if let metadata = metadataFolder {
  725. NCManageDatabase.shared.addMetadata(metadata)
  726. 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)
  727. }
  728. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(metadataFolder?.ocId) {
  729. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCreateFolder, userInfo: ["ocId": metadata.ocId])
  730. }
  731. }
  732. completion(errorCode, errorDescription)
  733. }
  734. } else if errorCode == 405 && overwrite {
  735. completion(0, "")
  736. } else {
  737. completion(errorCode, errorDescription)
  738. }
  739. }
  740. }
  741. func createFolder(assets: [PHAsset], selector: String, useSubFolder: Bool, account: String, urlBase: String) -> Bool {
  742. let serverUrl = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: urlBase, account: account)
  743. let fileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  744. let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: urlBase, account: account)
  745. var result = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase)
  746. if useSubFolder && result {
  747. for dateSubFolder in CCUtility.createNameSubFolder(assets) {
  748. let fileName = (dateSubFolder as! NSString).lastPathComponent
  749. let serverUrl = ((autoUploadPath + "/" + (dateSubFolder as! String)) as NSString).deletingLastPathComponent
  750. result = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase)
  751. if !result { break }
  752. }
  753. }
  754. return result
  755. }
  756. private func createFolderWithSemaphore(fileName: String, serverUrl: String, account: String, urlBase: String) -> Bool {
  757. var result: Bool = false
  758. let semaphore = Semaphore()
  759. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: true) { (errorCode, errorDescription) in
  760. if errorCode == 0 { result = true }
  761. semaphore.continue()
  762. }
  763. if semaphore.wait() == .success { result = true }
  764. return result
  765. }
  766. //MARK: - WebDav Delete
  767. @objc func deleteMetadata(_ metadata: tableMetadata, account: String, urlBase: String, onlyLocal: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  768. if (onlyLocal) {
  769. var metadatas = [metadata]
  770. if metadata.directory {
  771. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  772. metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND directory == false", account, serverUrl))
  773. }
  774. for metadata in metadatas {
  775. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  776. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  777. if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  778. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadataLivePhoto.ocId))
  779. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadataLivePhoto.ocId))
  780. }
  781. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "typeFile": metadata.typeFile, "onlyLocal": true])
  782. }
  783. completion(0, "")
  784. return
  785. }
  786. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: urlBase)
  787. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  788. if isDirectoryEncrypted {
  789. #if !EXTENSION
  790. if metadataLive == nil {
  791. NCNetworkingE2EE.shared.deleteMetadata(metadata, urlBase: urlBase, completion: completion)
  792. } else {
  793. NCNetworkingE2EE.shared.deleteMetadata(metadataLive!, urlBase: urlBase) { (errorCode, errorDescription) in
  794. if errorCode == 0 {
  795. NCNetworkingE2EE.shared.deleteMetadata(metadata, urlBase: urlBase, completion: completion)
  796. } else {
  797. completion(errorCode, errorDescription)
  798. }
  799. }
  800. }
  801. #endif
  802. } else {
  803. if metadataLive == nil {
  804. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  805. } else {
  806. self.deleteMetadataPlain(metadataLive!, addCustomHeaders: nil) { (errorCode, errorDescription) in
  807. if errorCode == 0 {
  808. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  809. } else {
  810. completion(errorCode, errorDescription)
  811. }
  812. }
  813. }
  814. }
  815. }
  816. func deleteMetadataPlain(_ metadata: tableMetadata, addCustomHeaders: [String: String]?, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  817. // verify permission
  818. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanDelete)
  819. if metadata.permissions != "" && permission == false {
  820. completion(NCGlobal.shared.ErrorInternalError, "_no_permission_delete_file_")
  821. return
  822. }
  823. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  824. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName, customUserAgent: nil, addCustomHeaders: addCustomHeaders) { (account, errorCode, errorDescription) in
  825. if errorCode == 0 || errorCode == NCGlobal.shared.ErrorResourceNotFound {
  826. do {
  827. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  828. } catch { }
  829. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  830. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  831. if metadata.directory {
  832. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account)
  833. }
  834. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "typeFile": metadata.typeFile, "onlyLocal": true])
  835. }
  836. completion(errorCode, errorDescription)
  837. }
  838. }
  839. //MARK: - WebDav Favorite
  840. @objc func favoriteMetadata(_ metadata: tableMetadata, urlBase: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  841. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  842. favoriteMetadataPlain(metadataLive, urlBase: urlBase) { (errorCode, errorDescription) in
  843. if errorCode == 0 {
  844. self.favoriteMetadataPlain(metadata, urlBase: urlBase, completion: completion)
  845. } else {
  846. completion(errorCode, errorDescription)
  847. }
  848. }
  849. } else {
  850. favoriteMetadataPlain(metadata, urlBase: urlBase, completion: completion)
  851. }
  852. }
  853. private func favoriteMetadataPlain(_ metadata: tableMetadata, urlBase: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String)->()) {
  854. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: urlBase, account: metadata.account)!
  855. let favorite = !metadata.favorite
  856. let ocId = metadata.ocId
  857. NCCommunication.shared.setFavorite(fileName: fileName, favorite: favorite) { (account, errorCode, errorDescription) in
  858. if errorCode == 0 && metadata.account == account {
  859. NCManageDatabase.shared.setMetadataFavorite(ocId: metadata.ocId, favorite: favorite)
  860. #if !EXTENSION
  861. if favorite {
  862. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorReadFile)
  863. }
  864. #endif
  865. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  866. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterFavoriteFile, userInfo: ["ocId": metadata.ocId])
  867. }
  868. }
  869. completion(errorCode, errorDescription)
  870. }
  871. }
  872. @objc func listingFavoritescompletion(selector: String, completion: @escaping (_ account: String, _ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  873. NCCommunication.shared.listingFavorites(showHiddenFiles: CCUtility.getShowHiddenFiles()) { (account, files, errorCode, errorDescription) in
  874. if errorCode == 0 {
  875. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (_, _, metadatas) in
  876. NCManageDatabase.shared.updateMetadatasFavorite(account: account, metadatas: metadatas)
  877. if selector != NCGlobal.shared.selectorListingFavorite {
  878. #if !EXTENSION
  879. for metadata in metadatas {
  880. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: selector)
  881. }
  882. #endif
  883. }
  884. completion(account, metadatas, errorCode, errorDescription)
  885. }
  886. } else {
  887. completion(account, nil, errorCode, errorDescription)
  888. }
  889. }
  890. }
  891. //MARK: - WebDav Rename
  892. @objc func renameMetadata(_ metadata: tableMetadata, fileNameNew: String, urlBase: String, viewController: UIViewController?, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  893. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: urlBase)
  894. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  895. let fileNameNewLive = (fileNameNew as NSString).deletingPathExtension + ".mov"
  896. if isDirectoryEncrypted {
  897. #if !EXTENSION
  898. if metadataLive == nil {
  899. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, urlBase: urlBase, completion: completion)
  900. } else {
  901. NCNetworkingE2EE.shared.renameMetadata(metadataLive!, fileNameNew: fileNameNewLive, urlBase: urlBase) { (errorCode, errorDescription) in
  902. if errorCode == 0 {
  903. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, urlBase: urlBase, completion: completion)
  904. } else {
  905. completion(errorCode, errorDescription)
  906. }
  907. }
  908. }
  909. #endif
  910. } else {
  911. if metadataLive == nil {
  912. renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  913. } else {
  914. renameMetadataPlain(metadataLive!, fileNameNew: fileNameNewLive) { (errorCode, errorDescription) in
  915. if errorCode == 0 {
  916. self.renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  917. } else {
  918. completion(errorCode, errorDescription)
  919. }
  920. }
  921. }
  922. }
  923. }
  924. private func renameMetadataPlain(_ metadata: tableMetadata, fileNameNew: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  925. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  926. if !(metadata.permissions == "") && !permission {
  927. completion(NCGlobal.shared.ErrorInternalError, "_no_permission_modify_file_")
  928. return
  929. }
  930. guard let fileNameNew = CCUtility.removeForbiddenCharactersServer(fileNameNew) else {
  931. completion(0, "")
  932. return
  933. }
  934. if fileNameNew.count == 0 || fileNameNew == metadata.fileNameView {
  935. completion(0, "")
  936. return
  937. }
  938. let fileNamePath = metadata.serverUrl + "/" + metadata.fileName
  939. let fileNameToPath = metadata.serverUrl + "/" + fileNameNew
  940. let ocId = metadata.ocId
  941. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNamePath, serverUrlFileNameDestination: fileNameToPath, overwrite: false) { (account, errorCode, errorDescription) in
  942. if errorCode == 0 {
  943. NCManageDatabase.shared.renameMetadata(fileNameTo: fileNameNew, ocId: ocId)
  944. if metadata.directory {
  945. let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  946. let serverUrlTo = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: fileNameNew)!
  947. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  948. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, serverUrlTo: serverUrlTo, etag: "", ocId: nil, fileId: nil, encrypted: directory.e2eEncrypted, richWorkspace: nil, account: metadata.account)
  949. }
  950. } else {
  951. let ext = (metadata.fileName as NSString).pathExtension
  952. let extNew = (fileNameNew as NSString).pathExtension
  953. if ext != extNew {
  954. if let path = CCUtility.getDirectoryProviderStorageOcId(ocId) {
  955. NCUtilityFileSystem.shared.deleteFile(filePath: path)
  956. }
  957. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": metadata.serverUrl])
  958. } else {
  959. NCManageDatabase.shared.setLocalFile(ocId: ocId, fileName: fileNameNew, etag: nil)
  960. // Move file system
  961. let atPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + metadata.fileName
  962. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + fileNameNew
  963. do {
  964. try FileManager.default.moveItem(atPath: atPath, toPath: toPath)
  965. } catch { }
  966. }
  967. }
  968. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  969. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRenameFile, userInfo: ["ocId": metadata.ocId])
  970. }
  971. }
  972. completion(errorCode, errorDescription)
  973. }
  974. }
  975. //MARK: - WebDav Move
  976. @objc func moveMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  977. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  978. moveMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  979. if errorCode == 0 {
  980. self.moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  981. } else {
  982. completion(errorCode, errorDescription)
  983. }
  984. }
  985. } else {
  986. moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  987. }
  988. }
  989. private func moveMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  990. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  991. if !(metadata.permissions == "") && !permission {
  992. completion(NCGlobal.shared.ErrorInternalError, "_no_permission_modify_file_")
  993. return
  994. }
  995. let serverUrlFrom = metadata.serverUrl
  996. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  997. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  998. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  999. if errorCode == 0 {
  1000. if metadata.directory {
  1001. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: account)
  1002. }
  1003. NCManageDatabase.shared.moveMetadata(ocId: metadata.ocId, serverUrlTo: serverUrlTo)
  1004. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMoveFile, userInfo: ["ocId": metadata.ocId, "serverUrlFrom": serverUrlFrom])
  1005. }
  1006. completion(errorCode, errorDescription)
  1007. }
  1008. }
  1009. //MARK: - WebDav Copy
  1010. @objc func copyMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  1011. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  1012. copyMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { (errorCode, errorDescription) in
  1013. if errorCode == 0 {
  1014. self.copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1015. } else {
  1016. completion(errorCode, errorDescription)
  1017. }
  1018. }
  1019. } else {
  1020. copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1021. }
  1022. }
  1023. private func copyMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?)->()) {
  1024. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  1025. if !(metadata.permissions == "") && !permission {
  1026. completion(NCGlobal.shared.ErrorInternalError, "_no_permission_modify_file_")
  1027. return
  1028. }
  1029. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  1030. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  1031. NCCommunication.shared.copyFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { (account, errorCode, errorDescription) in
  1032. if errorCode == 0 {
  1033. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCopyFile, userInfo: ["ocId": metadata.ocId, "serverUrlTo": serverUrlTo])
  1034. }
  1035. completion(errorCode, errorDescription)
  1036. }
  1037. }
  1038. //MARK: - TEST API
  1039. /*
  1040. XXXXXXXXXXXXXXX-YYYYYYYYYYYYYYY
  1041. Where XXXXXXXXXXXXXXX is the start byte of the chunk (with leading zeros) and YYYYYYYYYYYYYYY is the end byte of the chunk with leading zeros.
  1042. 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
  1043. This will upload 2 chunks of a file. The first chunk is 10MB in size and the second chunk is 5MB in size.
  1044. */
  1045. func fileChunks(path: String, fileName: String, pathChunks: String, size: Int) -> [String]? {
  1046. var filesNameOut: [String] = []
  1047. do {
  1048. let data = try Data(contentsOf: URL(fileURLWithPath: path + "/" + fileName))
  1049. let dataLen = data.count
  1050. let chunkSize = ((1024 * 1000) * size) // MB
  1051. let fullChunks = Int(dataLen / chunkSize)
  1052. let totalChunks = fullChunks + (dataLen % 1024 != 0 ? 1 : 0)
  1053. for chunkCounter in 0..<totalChunks {
  1054. let chunkBase = chunkCounter * chunkSize
  1055. var diff = chunkSize
  1056. if chunkCounter == totalChunks - 1 {
  1057. diff = dataLen - chunkBase
  1058. }
  1059. let range:Range<Data.Index> = chunkBase..<(chunkBase + diff)
  1060. let chunk = data.subdata(in: range)
  1061. let fileNameOut = fileName + "." + String(format: "%010d", chunkCounter)
  1062. try chunk.write(to: URL(fileURLWithPath: pathChunks + "/" + fileNameOut))
  1063. filesNameOut.append(fileNameOut)
  1064. }
  1065. } catch {
  1066. return nil
  1067. }
  1068. return filesNameOut
  1069. }
  1070. /*
  1071. @objc public func getAppPassword(serverUrl: String, username: String, password: String, customUserAgent: String? = nil, completionHandler: @escaping (_ token: String?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  1072. let endpoint = "/ocs/v2.php/core/getapppassword"
  1073. let url:URLConvertible = try! (serverUrl + endpoint).asURL() as URLConvertible
  1074. var headers: HTTPHeaders = [.authorization(username: username, password: password)]
  1075. if customUserAgent != nil {
  1076. headers.update(.userAgent(customUserAgent!))
  1077. }
  1078. //headers.update(.contentType("application/json"))
  1079. headers.update(name: "OCS-APIRequest", value: "true")
  1080. var urlRequest: URLRequest
  1081. do {
  1082. try urlRequest = URLRequest(url: url, method: HTTPMethod(rawValue: "GET"), headers: headers)
  1083. } catch {
  1084. completionHandler(nil, error._code, error.localizedDescription)
  1085. return
  1086. }
  1087. AF.request(urlRequest).validate(statusCode: 200..<300).response { (response) in
  1088. debugPrint(response)
  1089. switch response.result {
  1090. case .failure(let error):
  1091. completionHandler(nil, 0, "")
  1092. case .success(let data):
  1093. if let data = data {
  1094. completionHandler("", 0, "")
  1095. } else {
  1096. completionHandler(nil, NSURLErrorBadServerResponse, NSLocalizedString("_error_decode_xml_", value: "Invalid response, error decode XML", comment: ""))
  1097. }
  1098. }
  1099. }
  1100. }
  1101. */
  1102. }