NCNetworking.swift 76 KB

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