NCNetworking.swift 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  1. //
  2. // NCNetworking.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 23/10/19.
  6. // Copyright © 2019 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. import OpenSSL
  25. import NCCommunication
  26. import Alamofire
  27. import Queuer
  28. @objc public protocol NCNetworkingDelegate {
  29. @objc optional func downloadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask)
  30. @objc optional func uploadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask)
  31. @objc optional func downloadComplete(fileName: String, serverUrl: String, etag: String?, date: NSDate?, dateLastModified: NSDate?, length: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String)
  32. @objc optional func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String)
  33. }
  34. @objc class NCNetworking: NSObject, NCCommunicationCommonDelegate {
  35. @objc public static let shared: NCNetworking = {
  36. let instance = NCNetworking()
  37. return instance
  38. }()
  39. weak 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. // REQUESTS
  83. var requestsUnifiedSearch: [DataRequest] = []
  84. // MARK: - init
  85. override init() {
  86. super.init()
  87. #if EXTENSION
  88. _ = sessionIdentifierBackgroundExtension
  89. #else
  90. _ = sessionManagerBackground
  91. _ = sessionManagerBackgroundWWan
  92. #endif
  93. }
  94. // MARK: - Communication Delegate
  95. func networkReachabilityObserver(_ typeReachability: NCCommunicationCommon.typeReachability) {
  96. #if !EXTENSION
  97. if typeReachability == NCCommunicationCommon.typeReachability.reachableCellular || typeReachability == NCCommunicationCommon.typeReachability.reachableEthernetOrWiFi {
  98. if !lastReachability {
  99. NCService.shared.startRequestServicesServer()
  100. }
  101. lastReachability = true
  102. } else {
  103. if lastReachability {
  104. NCContentPresenter.shared.messageNotification("_network_not_available_", description: nil, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: -1009)
  105. }
  106. lastReachability = false
  107. }
  108. networkReachability = typeReachability
  109. #endif
  110. }
  111. func authenticationChallenge(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  112. if checkTrustedChallenge(session, didReceive: challenge) {
  113. completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
  114. } else {
  115. completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
  116. }
  117. }
  118. func downloadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  119. delegate?.downloadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  120. }
  121. func downloadComplete(fileName: String, serverUrl: String, etag: String?, date: NSDate?, dateLastModified: NSDate?, length: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  122. delegate?.downloadComplete?(fileName: fileName, serverUrl: serverUrl, etag: etag, date: date, dateLastModified: dateLastModified, length: length, description: description, task: task, errorCode: errorCode, errorDescription: errorDescription)
  123. }
  124. func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
  125. #if !EXTENSION
  126. if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let completionHandler = appDelegate.backgroundSessionCompletionHandler {
  127. NCCommunicationCommon.shared.writeLog("Called urlSessionDidFinishEvents for Background URLSession")
  128. appDelegate.backgroundSessionCompletionHandler = nil
  129. completionHandler()
  130. }
  131. #endif
  132. }
  133. // MARK: - Pinning check
  134. private func checkTrustedChallenge(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge) -> Bool {
  135. let protectionSpace: URLProtectionSpace = challenge.protectionSpace
  136. let directoryCertificate = CCUtility.getDirectoryCerificates()!
  137. let host = challenge.protectionSpace.host
  138. let certificateSavedPath = directoryCertificate + "/" + host + ".der"
  139. var isTrusted: Bool
  140. #if !EXTENSION
  141. defer {
  142. DispatchQueue.main.async {
  143. if !isTrusted {
  144. (UIApplication.shared.delegate as? AppDelegate)?.trustCertificateError(host: host)
  145. }
  146. }
  147. }
  148. #endif
  149. print("SSL host: \(host)")
  150. if let serverTrust: SecTrust = protectionSpace.serverTrust, let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
  151. // extarct certificate txt
  152. saveX509Certificate(certificate, host: host, directoryCertificate: directoryCertificate)
  153. var secresult = SecTrustResultType.invalid
  154. let status = SecTrustEvaluate(serverTrust, &secresult)
  155. let isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil)
  156. let certificateCopyData = SecCertificateCopyData(certificate)
  157. let data = CFDataGetBytePtr(certificateCopyData);
  158. let size = CFDataGetLength(certificateCopyData);
  159. let certificateData = NSData(bytes: data, length: size)
  160. certificateData.write(toFile: directoryCertificate + "/" + host + ".tmp", atomically: true)
  161. if isServerTrusted {
  162. isTrusted = true
  163. } else if status == errSecSuccess, let certificateDataSaved = NSData(contentsOfFile: certificateSavedPath), certificateData.isEqual(to: certificateDataSaved as Data) {
  164. isTrusted = true
  165. } else {
  166. isTrusted = false
  167. }
  168. } else {
  169. isTrusted = false
  170. }
  171. return isTrusted
  172. }
  173. func writeCertificate(host: String) {
  174. let directoryCertificate = CCUtility.getDirectoryCerificates()!
  175. let certificateAtPath = directoryCertificate + "/" + host + ".tmp"
  176. let certificateToPath = directoryCertificate + "/" + host + ".der"
  177. if !NCUtilityFileSystem.shared.moveFile(atPath: certificateAtPath, toPath: certificateToPath) {
  178. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorCreationFile, priority: .max)
  179. }
  180. }
  181. private func saveX509Certificate(_ certificate: SecCertificate, host: String, directoryCertificate: String) {
  182. let certNamePathTXT = directoryCertificate + "/" + host + ".txt"
  183. let data: CFData = SecCertificateCopyData(certificate)
  184. let mem = BIO_new_mem_buf(CFDataGetBytePtr(data), Int32(CFDataGetLength(data)))
  185. let x509cert = d2i_X509_bio(mem, nil)
  186. if x509cert == nil {
  187. print("[LOG] OpenSSL couldn't parse X509 Certificate")
  188. } else {
  189. // save details
  190. if FileManager.default.fileExists(atPath: certNamePathTXT) {
  191. do {
  192. try FileManager.default.removeItem(atPath: certNamePathTXT)
  193. } catch { }
  194. }
  195. let fileCertInfo = fopen(certNamePathTXT, "w")
  196. if fileCertInfo != nil {
  197. let output = BIO_new_fp(fileCertInfo, BIO_NOCLOSE)
  198. X509_print_ex(output, x509cert, UInt(XN_FLAG_COMPAT), UInt(X509_FLAG_COMPAT))
  199. BIO_free(output)
  200. }
  201. fclose(fileCertInfo)
  202. X509_free(x509cert)
  203. }
  204. BIO_free(mem)
  205. }
  206. func checkPushNotificationServerProxyCertificateUntrusted(viewController: UIViewController?, completion: @escaping (_ errorCode: Int) -> Void) {
  207. guard let host = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host else { return }
  208. NCCommunication.shared.checkServer(serverUrl: NCBrandOptions.shared.pushNotificationServerProxy) { errorCode, _ in
  209. if errorCode == 0 {
  210. NCNetworking.shared.writeCertificate(host: host)
  211. completion(errorCode)
  212. } else if errorCode == NSURLErrorServerCertificateUntrusted {
  213. let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
  214. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
  215. NCNetworking.shared.writeCertificate(host: host)
  216. completion(0)
  217. }))
  218. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in
  219. completion(errorCode)
  220. }))
  221. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
  222. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  223. let vcCertificateDetails = navigationController.topViewController as! NCViewCertificateDetails
  224. vcCertificateDetails.host = host
  225. viewController?.present(navigationController, animated: true)
  226. }
  227. }))
  228. viewController?.present(alertController, animated: true)
  229. } else {
  230. completion(0)
  231. }
  232. }
  233. }
  234. // MARK: - Utility
  235. func cancelTaskWithUrl(_ url: URL) {
  236. NCCommunication.shared.getSessionManager().getAllTasks { tasks in
  237. tasks.filter { $0.state == .running }.filter { $0.originalRequest?.url == url }.first?.cancel()
  238. }
  239. }
  240. @objc func cancelAllTask() {
  241. NCCommunication.shared.getSessionManager().getAllTasks { tasks in
  242. for task in tasks {
  243. task.cancel()
  244. }
  245. }
  246. }
  247. // MARK: - Download
  248. @objc func cancelDownload(ocId: String, serverUrl: String, fileNameView: String) {
  249. #if !EXTENSION
  250. // removed progress ocid
  251. DispatchQueue.main.async { (UIApplication.shared.delegate as! AppDelegate).listProgress[ocId] = nil }
  252. #endif
  253. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView) else { return }
  254. if let request = downloadRequest[fileNameLocalPath] {
  255. request.cancel()
  256. } else {
  257. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  258. NCManageDatabase.shared.setMetadataSession(ocId: ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  259. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadCancelFile, userInfo: ["ocId": metadata.ocId])
  260. }
  261. }
  262. }
  263. @objc func download(metadata: tableMetadata, selector: String, notificationCenterProgressTask: Bool = true, progressHandler: @escaping (_ progress: Progress) -> Void = { _ in }, completion: @escaping (_ errorCode: Int) -> Void) {
  264. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  265. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
  266. if NCManageDatabase.shared.getMetadataFromOcId(metadata.ocId) == nil {
  267. NCManageDatabase.shared.addMetadata(tableMetadata.init(value: metadata))
  268. }
  269. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading { return }
  270. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: NCCommunicationCommon.shared.sessionIdentifierDownload, sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusInDownload)
  271. NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, queue: NCCommunicationCommon.shared.backgroundQueue, requestHandler: { request in
  272. self.downloadRequest[fileNameLocalPath] = request
  273. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusDownloading)
  274. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadStartFile, userInfo: ["ocId":metadata.ocId])
  275. }, taskHandler: { (_) in
  276. }, progressHandler: { (progress) in
  277. if notificationCenterProgressTask {
  278. #if !EXTENSION
  279. // add progress ocid
  280. let progressType = NCGlobal.progressType(progress: Float(progress.fractionCompleted), totalBytes: progress.totalUnitCount, totalBytesExpected: progress.completedUnitCount)
  281. DispatchQueue.main.async { (UIApplication.shared.delegate as! AppDelegate).listProgress[metadata.ocId] = progressType }
  282. #endif
  283. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterProgressTask, object: nil, userInfo: ["account":metadata.account, "ocId":metadata.ocId, "fileName":metadata.fileName, "serverUrl":metadata.serverUrl, "status":NSNumber(value: NCGlobal.shared.metadataStatusInDownload), "progress":NSNumber(value: progress.fractionCompleted), "totalBytes":NSNumber(value: progress.totalUnitCount), "totalBytesExpected":NSNumber(value: progress.completedUnitCount)])
  284. }
  285. progressHandler(progress)
  286. }) { (account, etag, date, _, allHeaderFields, error, errorCode, errorDescription) in
  287. if error?.isExplicitlyCancelledError ?? false {
  288. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  289. } else if errorCode == 0 {
  290. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal, etag: etag)
  291. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  292. #if !EXTENSION
  293. if let result = NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "fileNameIdentifier == %@ AND serverUrl == %@", metadata.fileName, metadata.serverUrl)) {
  294. NCEndToEndEncryption.sharedManager()?.decryptFileName(metadata.fileName, fileNameView: metadata.fileNameView, ocId: metadata.ocId, key: result.key, initializationVector: result.initializationVector, authenticationTag: result.authenticationTag)
  295. }
  296. CCUtility.setExif(metadata) { _, _, _, _, _ in }
  297. #endif
  298. } else {
  299. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: errorDescription, sessionSelector: selector, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusDownloadError)
  300. #if !EXTENSION
  301. if errorCode == 401 || errorCode == 403 {
  302. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account, errorCode: errorCode, errorDescription: errorDescription)
  303. }
  304. #endif
  305. }
  306. self.downloadRequest[fileNameLocalPath] = nil
  307. #if !EXTENSION
  308. DispatchQueue.main.async { (UIApplication.shared.delegate as! AppDelegate).listProgress[metadata.ocId] = nil }
  309. #endif
  310. if error?.isExplicitlyCancelledError ?? false {
  311. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadCancelFile, userInfo: ["ocId": metadata.ocId])
  312. } else {
  313. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": selector, "errorCode": errorCode, "errorDescription": errorDescription])
  314. }
  315. completion(errorCode)
  316. }
  317. }
  318. // MARK: - Upload
  319. @objc func upload(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  320. func uploadMetadata(_ metadata: tableMetadata) {
  321. // DETECT IF CHUNCK
  322. let chunckSize = CCUtility.getChunkSize() * 1000000
  323. if chunckSize > 0 && metadata.size > chunckSize {
  324. metadata.chunk = true
  325. metadata.session = NCCommunicationCommon.shared.sessionIdentifierUpload
  326. }
  327. // DETECT IF E2EE
  328. if CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase) {
  329. metadata.e2eEncrypted = true
  330. }
  331. NCManageDatabase.shared.addMetadata(metadata)
  332. let metadata = tableMetadata.init(value: metadata)
  333. NCCommunicationCommon.shared.writeLog("Upload file \(metadata.fileNameView) with Identifier \(metadata.assetLocalIdentifier) with size \(metadata.size) [CHUNCK \(metadata.chunk), E2EE \(metadata.e2eEncrypted)]")
  334. if metadata.e2eEncrypted {
  335. #if !EXTENSION_FILE_PROVIDER_EXTENSION
  336. NCNetworkingE2EE.shared.upload(metadata: metadata, start: start) { errorCode, errorDescription in
  337. DispatchQueue.main.async {
  338. completion(errorCode, errorDescription)
  339. }
  340. }
  341. #endif
  342. } else if metadata.chunk {
  343. uploadChunkedFile(metadata: metadata, start: start) { errorCode, errorDescription in
  344. DispatchQueue.main.async {
  345. completion(errorCode, errorDescription)
  346. }
  347. }
  348. } else if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  349. uploadFile(metadata: metadata, start: start) { errorCode, errorDescription in
  350. DispatchQueue.main.async {
  351. completion(errorCode, errorDescription)
  352. }
  353. }
  354. } else {
  355. uploadFileInBackground(metadata: metadata, start: start) { errorCode, errorDescription in
  356. DispatchQueue.main.async {
  357. completion(errorCode, errorDescription)
  358. }
  359. }
  360. }
  361. }
  362. let metadata = tableMetadata.init(value: metadata)
  363. if metadata.assetLocalIdentifier.isEmpty {
  364. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  365. let results = NCCommunicationCommon.shared.getInternalType(fileName: metadata.fileNameView, mimeType: metadata.contentType, directory: false)
  366. metadata.contentType = results.mimeType
  367. metadata.iconName = results.iconName
  368. metadata.classFile = results.classFile
  369. if let date = NCUtilityFileSystem.shared.getFileCreationDate(filePath: fileNameLocalPath) {
  370. metadata.creationDate = date
  371. }
  372. if let date = NCUtilityFileSystem.shared.getFileModificationDate(filePath: fileNameLocalPath) {
  373. metadata.date = date
  374. }
  375. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath)
  376. uploadMetadata(metadata)
  377. } else {
  378. CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadata) { extractMetadata, fileNamePath in
  379. guard let metadata = extractMetadata else {
  380. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  381. return completion(NCGlobal.shared.errorInternalError, "Internal error")
  382. }
  383. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  384. NCUtilityFileSystem.shared.moveFileInBackground(atPath: fileNamePath!, toPath: fileNameLocalPath)
  385. uploadMetadata(metadata)
  386. }
  387. }
  388. }
  389. private func uploadFile(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  390. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  391. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  392. var uploadTask: URLSessionTask?
  393. let description = metadata.ocId
  394. NCCommunication.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, dateCreationFile: metadata.creationDate as Date, dateModificationFile: metadata.date as Date, customUserAgent: nil, addCustomHeaders: nil, requestHandler: { request in
  395. self.uploadRequest[fileNameLocalPath] = request
  396. }, taskHandler: { task in
  397. uploadTask = task
  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. start()
  401. }, progressHandler: { progress in
  402. #if !EXTENSION
  403. // add progress ocid
  404. let progressType = NCGlobal.progressType(progress: Float(progress.fractionCompleted), totalBytes: progress.totalUnitCount, totalBytesExpected: progress.completedUnitCount)
  405. DispatchQueue.main.async { (UIApplication.shared.delegate as! AppDelegate).listProgress[metadata.ocId] = progressType }
  406. #endif
  407. NotificationCenter.default.postOnMainThread(
  408. name: NCGlobal.shared.notificationCenterProgressTask,
  409. userInfo: [
  410. "account": metadata.account,
  411. "ocId": metadata.ocId,
  412. "fileName": metadata.fileName,
  413. "serverUrl": metadata.serverUrl,
  414. "status": NSNumber(value: NCGlobal.shared.metadataStatusInUpload),
  415. "progress": NSNumber(value: progress.fractionCompleted),
  416. "totalBytes": NSNumber(value: progress.totalUnitCount),
  417. "totalBytesExpected": NSNumber(value: progress.completedUnitCount)])
  418. }) { _, ocId, etag, date, size, _, _, errorCode, errorDescription in
  419. self.uploadRequest[fileNameLocalPath] = nil
  420. if let uploadTask = uploadTask {
  421. self.uploadComplete(fileName: metadata.fileName, serverUrl: metadata.serverUrl, ocId: ocId, etag: etag, date: date, size: size, description: description, task: uploadTask, errorCode: errorCode, errorDescription: errorDescription)
  422. }
  423. completion(errorCode, errorDescription)
  424. }
  425. }
  426. private func uploadFileInBackground(metadata: tableMetadata, start: @escaping () -> Void, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  427. var session: URLSession?
  428. let metadata = tableMetadata.init(value: metadata)
  429. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  430. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  431. if metadata.session == sessionIdentifierBackground || metadata.session == sessionIdentifierBackgroundExtension {
  432. session = sessionManagerBackground
  433. } else if metadata.session == sessionIdentifierBackgroundWWan {
  434. session = sessionManagerBackgroundWWan
  435. }
  436. start()
  437. // Check file dim > 0
  438. if NCUtilityFileSystem.shared.getFileSize(filePath: fileNameLocalPath) == 0 && metadata.size != 0 {
  439. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  440. completion(NCGlobal.shared.errorResourceNotFound, NSLocalizedString("_error_not_found_", value: "The requested resource could not be found", comment: ""))
  441. } else {
  442. 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!) {
  443. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, sessionError: "", sessionTaskIdentifier: task.taskIdentifier, status: NCGlobal.shared.metadataStatusUploading)
  444. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadStartFile, userInfo: ["ocId": metadata.ocId])
  445. completion(0, "")
  446. } else {
  447. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  448. completion(NCGlobal.shared.errorInternalError, "task null")
  449. }
  450. }
  451. }
  452. func uploadComplete(fileName: String, serverUrl: String, ocId: String?, etag: String?, date: NSDate?, size: Int64, description: String?, task: URLSessionTask, errorCode: Int, errorDescription: String) {
  453. guard delegate == nil else {
  454. delegate?.uploadComplete?(fileName: fileName, serverUrl: serverUrl, ocId: ocId, etag: etag, date: date, size: size, description: description, task: task, errorCode: errorCode, errorDescription: errorDescription)
  455. return
  456. }
  457. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(description) else { return }
  458. let ocIdTemp = metadata.ocId
  459. var errorDescription = errorDescription
  460. if errorCode == 0, let ocId = ocId, size == metadata.size {
  461. let metadata = tableMetadata.init(value: metadata)
  462. NCUtilityFileSystem.shared.moveFileInBackground(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
  463. metadata.uploadDate = date ?? NSDate()
  464. metadata.etag = etag ?? ""
  465. metadata.ocId = ocId
  466. if let fileId = NCUtility.shared.ocIdToFileId(ocId: ocId) {
  467. metadata.fileId = fileId
  468. }
  469. metadata.session = ""
  470. metadata.sessionError = ""
  471. metadata.sessionTaskIdentifier = 0
  472. metadata.status = NCGlobal.shared.metadataStatusNormal
  473. // Delete Asset on Photos album
  474. if CCUtility.getRemovePhotoCameraRoll() && !metadata.assetLocalIdentifier.isEmpty {
  475. metadata.deleteAssetLocalIdentifier = true
  476. }
  477. if CCUtility.getDisableLocalCacheAfterUpload() {
  478. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  479. } else {
  480. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  481. }
  482. NCManageDatabase.shared.addMetadata(metadata)
  483. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocIdTemp))
  484. #if !EXTENSION
  485. self.getOcIdInBackgroundSession { listOcId in
  486. if listOcId.count == 0 && self.uploadRequest.count == 0 {
  487. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  488. appDelegate.networkingProcessUpload?.startProcess()
  489. }
  490. }
  491. CCUtility.setExif(metadata) { _, _, _, _, _ in }
  492. #endif
  493. NCCommunicationCommon.shared.writeLog("Upload complete " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)")
  494. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "ocIdTemp": ocIdTemp, "errorCode": errorCode, "errorDescription": ""])
  495. } else {
  496. if errorCode == NSURLErrorCancelled || errorCode == NCGlobal.shared.errorRequestExplicityCancelled {
  497. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  498. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  499. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  500. } else if errorCode == 401 || errorCode == 403 {
  501. #if !EXTENSION
  502. NCNetworkingCheckRemoteUser.shared.checkRemoteUser(account: metadata.account, errorCode: errorCode, errorDescription: errorDescription)
  503. #endif
  504. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  505. } else {
  506. if size == 0 {
  507. errorDescription = "File length 0"
  508. NCCommunicationCommon.shared.writeLog("Upload error 0 length " + serverUrl + "/" + fileName + ", result: success(\(size) bytes)")
  509. }
  510. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: errorDescription, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusUploadError)
  511. }
  512. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadedFile, userInfo: ["ocId": metadata.ocId, "ocIdTemp": ocIdTemp, "errorCode": errorCode, "errorDescription": ""])
  513. }
  514. #if !EXTENSION
  515. DispatchQueue.main.async { (UIApplication.shared.delegate as! AppDelegate).listProgress[metadata.ocId] = nil }
  516. #endif
  517. // Delete
  518. self.uploadMetadataInBackground[fileName + serverUrl] = nil
  519. }
  520. func uploadProgress(_ progress: Float, totalBytes: Int64, totalBytesExpected: Int64, fileName: String, serverUrl: String, session: URLSession, task: URLSessionTask) {
  521. delegate?.uploadProgress?(progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected, fileName: fileName, serverUrl: serverUrl, session: session, task: task)
  522. var metadata: tableMetadata?
  523. let description: String = task.taskDescription ?? ""
  524. if let metadataTmp = self.uploadMetadataInBackground[fileName+serverUrl] {
  525. metadata = metadataTmp
  526. } else if let metadataTmp = NCManageDatabase.shared.getMetadataFromOcId(description) {
  527. self.uploadMetadataInBackground[fileName+serverUrl] = metadataTmp
  528. metadata = metadataTmp
  529. }
  530. if let metadata = metadata {
  531. #if !EXTENSION
  532. // add progress ocid
  533. let progressType = NCGlobal.progressType(progress: progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected)
  534. DispatchQueue.main.async { (UIApplication.shared.delegate as! AppDelegate).listProgress[metadata.ocId] = progressType }
  535. #endif
  536. NotificationCenter.default.postOnMainThread(
  537. name: NCGlobal.shared.notificationCenterProgressTask,
  538. userInfo: [
  539. "account": metadata.account,
  540. "ocId": metadata.ocId,
  541. "fileName": metadata.fileName,
  542. "serverUrl": serverUrl,
  543. "status": NSNumber(value: NCGlobal.shared.metadataStatusInUpload),
  544. "progress": NSNumber(value: progress),
  545. "totalBytes": NSNumber(value: totalBytes),
  546. "totalBytesExpected": NSNumber(value: totalBytesExpected)])
  547. }
  548. }
  549. func getOcIdInBackgroundSession(completion: @escaping (_ listOcId: [String]) -> Void) {
  550. var listOcId: [String] = []
  551. sessionManagerBackground.getAllTasks(completionHandler: { tasks in
  552. for task in tasks {
  553. listOcId.append(task.description)
  554. }
  555. self.sessionManagerBackgroundWWan.getAllTasks(completionHandler: { tasks in
  556. for task in tasks {
  557. listOcId.append(task.description)
  558. }
  559. completion(listOcId)
  560. })
  561. })
  562. }
  563. // MARK: - Transfer (Download Upload)
  564. @objc func cancelTransferMetadata(_ metadata: tableMetadata, completion: @escaping () -> Void) {
  565. let metadata = tableMetadata.init(value: metadata)
  566. #if !EXTENSION
  567. // removed progress ocid
  568. DispatchQueue.main.async { (UIApplication.shared.delegate as! AppDelegate).listProgress[metadata.ocId] = nil }
  569. #endif
  570. if metadata.session.count == 0 {
  571. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  572. return completion()
  573. }
  574. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierDownload {
  575. NCNetworking.shared.cancelDownload(ocId: metadata.ocId, serverUrl: metadata.serverUrl, fileNameView: metadata.fileNameView)
  576. return completion()
  577. }
  578. if metadata.session == NCCommunicationCommon.shared.sessionIdentifierUpload {
  579. guard let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else { return }
  580. if let request = uploadRequest[fileNameLocalPath] {
  581. request.cancel()
  582. } else {
  583. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  584. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  585. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  586. }
  587. return completion()
  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. return completion()
  599. }
  600. session?.getTasksWithCompletionHandler { _, uploadTasks, _ in
  601. var cancel = false
  602. if metadata.session.count > 0 && metadata.session.contains("upload") {
  603. for task in uploadTasks {
  604. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  605. task.cancel()
  606. cancel = true
  607. }
  608. }
  609. if cancel == false {
  610. do {
  611. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  612. } catch { }
  613. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  614. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUploadCancelFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account])
  615. }
  616. }
  617. completion()
  618. }
  619. }
  620. @objc func cancelAllTransfer(account: String, completion: @escaping () -> Void) {
  621. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", account, NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusUploadError))
  622. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status != %d", NCGlobal.shared.metadataStatusNormal))
  623. var counter = 0
  624. for metadata in metadatas {
  625. counter += 1
  626. if metadata.status == NCGlobal.shared.metadataStatusWaitDownload || metadata.status == NCGlobal.shared.metadataStatusDownloadError {
  627. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  628. }
  629. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  630. self.cancelTransferMetadata(metadata) {
  631. if counter == metadatas.count {
  632. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  633. completion()
  634. }
  635. }
  636. }
  637. }
  638. }
  639. #if !EXTENSION
  640. NCOperationQueue.shared.downloadCancelAll()
  641. #endif
  642. }
  643. func cancelAllDownloadTransfer() {
  644. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status != %d", NCGlobal.shared.metadataStatusNormal))
  645. for metadata in metadatas {
  646. if metadata.status == NCGlobal.shared.metadataStatusWaitDownload || metadata.status == NCGlobal.shared.metadataStatusDownloadError {
  647. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  648. }
  649. if metadata.status == NCGlobal.shared.metadataStatusDownloading && metadata.session == NCCommunicationCommon.shared.sessionIdentifierDownload {
  650. cancelDownload(ocId: metadata.ocId, serverUrl: metadata.serverUrl, fileNameView: metadata.fileNameView)
  651. }
  652. }
  653. #if !EXTENSION
  654. NCOperationQueue.shared.downloadCancelAll()
  655. #endif
  656. }
  657. // MARK: - WebDav Read file, folder
  658. @objc func readFolder(serverUrl: String, account: String, completion: @escaping (_ account: String, _ metadataFolder: tableMetadata?, _ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ metadatasLocalUpdate: [tableMetadata]?, _ metadatasDelete: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  659. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { account, files, _, errorCode, errorDescription in
  660. if errorCode == 0 {
  661. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: true, account: account) { metadataFolder, metadatasFolder, metadatas in
  662. // Add metadata folder
  663. NCManageDatabase.shared.addMetadata(tableMetadata.init(value: metadataFolder))
  664. // Update directory
  665. NCManageDatabase.shared.addDirectory(encrypted: metadataFolder.e2eEncrypted, favorite: metadataFolder.favorite, ocId: metadataFolder.ocId, fileId: metadataFolder.fileId, etag: metadataFolder.etag, permissions: metadataFolder.permissions, serverUrl: serverUrl, account: metadataFolder.account)
  666. NCManageDatabase.shared.setDirectory(richWorkspace: metadataFolder.richWorkspace, serverUrl: serverUrl, account: metadataFolder.account)
  667. // Update sub directories NO Update richWorkspace
  668. for metadata in metadatasFolder {
  669. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  670. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: serverUrl, account: account)
  671. }
  672. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, NCGlobal.shared.metadataStatusNormal))
  673. let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareEtagLocal: true)
  674. completion(account, metadataFolder, metadatas, metadatasChanged.metadatasUpdate, metadatasChanged.metadatasLocalUpdate, metadatasChanged.metadatasDelete, errorCode, "")
  675. }
  676. } else {
  677. completion(account, nil, nil, nil, nil, nil, errorCode, errorDescription)
  678. }
  679. }
  680. }
  681. @objc func readFile(serverUrlFileName: String, queue: DispatchQueue = NCCommunicationCommon.shared.backgroundQueue, completion: @escaping (_ account: String, _ metadata: tableMetadata?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  682. NCCommunication.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: queue) { account, files, _, errorCode, errorDescription in
  683. if errorCode == 0 && files.count == 1 {
  684. let file = files[0]
  685. let isEncrypted = CCUtility.isFolderEncrypted(file.serverUrl, e2eEncrypted: file.e2eEncrypted, account: account, urlBase: file.urlBase)
  686. let metadata = NCManageDatabase.shared.convertNCFileToMetadata(file, isEncrypted: isEncrypted, account: account)
  687. completion(account, metadata, errorCode, errorDescription)
  688. } else {
  689. completion(account, nil, errorCode, errorDescription)
  690. }
  691. }
  692. }
  693. //MARK: - Search
  694. /// WebDAV search
  695. @objc func searchFiles(urlBase: NCUserBaseUrl, literal: String, completion: @escaping (_ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String) -> ()) {
  696. NCCommunication.shared.searchLiteral(serverUrl: urlBase.urlBase, depth: "infinity", literal: literal, showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { (account, files, errorCode, errorDescription) in
  697. guard errorCode != 0 else {
  698. return completion(nil, errorCode, errorDescription)
  699. }
  700. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { _, metadatasFolder, metadatas in
  701. // Update sub directories
  702. for folder in metadatasFolder {
  703. let serverUrl = folder.serverUrl + "/" + folder.fileName
  704. NCManageDatabase.shared.addDirectory(encrypted: folder.e2eEncrypted, favorite: folder.favorite, ocId: folder.ocId, fileId: folder.fileId, etag: nil, permissions: folder.permissions, serverUrl: serverUrl, account: account)
  705. }
  706. NCManageDatabase.shared.addMetadatas(metadatas)
  707. let metadatas = Array(metadatas.map(tableMetadata.init))
  708. completion(metadatas, errorCode, errorDescription)
  709. }
  710. }
  711. }
  712. /// Unified Search (NC>=20)
  713. ///
  714. func unifiedSearchFiles(urlBase: NCUserBaseUrl, literal: String, providers: @escaping ([NCCSearchProvider]?) -> Void, update: @escaping ([NCCSearchResult]?, [tableMetadata]?) -> Void, completion: @escaping ([NCCSearchResult]?, _ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String) -> ()) {
  715. var searchResults: [NCCSearchResult] = []
  716. var searchFiles: [tableMetadata] = []
  717. var errorCode = 0
  718. var errorDescription = ""
  719. let concurrentQueue = DispatchQueue(label: "com.nextcloud.requestUnifiedSearch.concurrentQueue", attributes: .concurrent)
  720. let dispatchGroup = DispatchGroup()
  721. dispatchGroup.enter()
  722. dispatchGroup.notify(queue: .main) {
  723. completion(searchResults, Array(searchFiles), errorCode, errorDescription)
  724. }
  725. NCCommunication.shared.unifiedSearch(term: literal, timeout: 30, timeoutProvider: 90) { provider in
  726. // example filter
  727. // ["calendar", "files", "fulltextsearch"].contains(provider.id)
  728. return true
  729. } request: { request in
  730. if let request = request {
  731. self.requestsUnifiedSearch.append(request)
  732. }
  733. } providers: { allProviders in
  734. providers(allProviders)
  735. } update: { partialResult, provider, errorCode, errorDescription in
  736. guard let partialResult = partialResult else { return }
  737. searchResults.append(partialResult)
  738. switch provider.id {
  739. case "files":
  740. partialResult.entries.forEach({ entry in
  741. if let fileId = entry.fileId,
  742. let newMetadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ && fileId == %@", urlBase.userAccount, String(fileId))) {
  743. concurrentQueue.async(flags: .barrier) {
  744. searchFiles.append(newMetadata)
  745. }
  746. } else if let filePath = entry.filePath {
  747. self.loadMetadata(urlBase: urlBase, filePath: filePath, dispatchGroup: dispatchGroup) { newMetadata in
  748. concurrentQueue.async(flags: .barrier) {
  749. searchFiles.append(newMetadata)
  750. }
  751. }
  752. } else { print(#function, "[ERROR]: File search entry has no path: \(entry)") }
  753. })
  754. break
  755. case "fulltextsearch":
  756. // NOTE: FTS could also return attributes like files
  757. // https://github.com/nextcloud/files_fulltextsearch/issues/143
  758. partialResult.entries.forEach({ entry in
  759. let url = URLComponents(string: entry.resourceURL)
  760. guard let dir = url?.queryItems?["dir"]?.value, let filename = url?.queryItems?["scrollto"]?.value else { return }
  761. if let newMetadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(
  762. format: "account == %@ && path == %@ && fileName == %@",
  763. urlBase.userAccount,
  764. "/remote.php/dav/files/" + urlBase.user + dir,
  765. filename)) {
  766. concurrentQueue.async(flags: .barrier) {
  767. searchFiles.append(newMetadata)
  768. }
  769. } else {
  770. self.loadMetadata(urlBase: urlBase, filePath: dir + filename, dispatchGroup: dispatchGroup) { newMetadata in
  771. concurrentQueue.async(flags: .barrier) {
  772. searchFiles.append(newMetadata)
  773. }
  774. }
  775. }
  776. })
  777. default:
  778. partialResult.entries.forEach({ entry in
  779. concurrentQueue.async(flags: .barrier) {
  780. let newMetadata = NCManageDatabase.shared.createMetadata(account: urlBase.account, user: urlBase.user, userId: urlBase.userId, fileName: entry.title, fileNameView: entry.title, ocId: NSUUID().uuidString, serverUrl: urlBase.urlBase, urlBase: urlBase.urlBase, url: entry.resourceURL, contentType: "", isUrl: true, name: partialResult.name.lowercased(), subline: entry.subline, iconName: entry.icon, iconUrl: entry.thumbnailURL)
  781. searchFiles.append(newMetadata)
  782. }
  783. })
  784. }
  785. update(searchResults, searchFiles)
  786. } completion: { results, code, description in
  787. self.requestsUnifiedSearch.removeAll()
  788. dispatchGroup.leave()
  789. if let results = results {
  790. searchResults = results
  791. }
  792. errorCode = code
  793. errorDescription = description
  794. }
  795. }
  796. func cancelUnifiedSearchFiles() {
  797. for request in requestsUnifiedSearch {
  798. request.cancel()
  799. }
  800. requestsUnifiedSearch.removeAll()
  801. }
  802. func loadMetadata(urlBase: NCUserBaseUrl, filePath: String, dispatchGroup: DispatchGroup, completion: @escaping (tableMetadata) -> Void) {
  803. let urlPath = urlBase.urlBase + "/remote.php/dav/files/" + urlBase.user + filePath
  804. dispatchGroup.enter()
  805. self.readFile(serverUrlFileName: urlPath) { account, metadata, errorCode, errorDescription in
  806. defer { dispatchGroup.leave() }
  807. guard let metadata = metadata else { return }
  808. DispatchQueue.main.async {
  809. NCManageDatabase.shared.addMetadata(metadata)
  810. completion(metadata)
  811. }
  812. }
  813. }
  814. // MARK: - WebDav Create Folder
  815. @objc func createFolder(fileName: String, serverUrl: String, account: String, urlBase: String, overwrite: Bool = false, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  816. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: false, account: account, urlBase: urlBase)
  817. let fileName = fileName.trimmingCharacters(in: .whitespacesAndNewlines)
  818. if isDirectoryEncrypted {
  819. #if !EXTENSION
  820. NCNetworkingE2EE.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, completion: completion)
  821. #endif
  822. } else {
  823. createFolderPlain(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: overwrite, completion: completion)
  824. }
  825. }
  826. private func createFolderPlain(fileName: String, serverUrl: String, account: String, urlBase: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  827. var fileNameFolder = CCUtility.removeForbiddenCharactersServer(fileName)!
  828. if !overwrite {
  829. fileNameFolder = NCUtilityFileSystem.shared.createFileName(fileNameFolder, serverUrl: serverUrl, account: account)
  830. }
  831. if fileNameFolder.count == 0 {
  832. return completion(0, "")
  833. }
  834. let fileNameFolderUrl = serverUrl + "/" + fileNameFolder
  835. NCCommunication.shared.createFolder(fileNameFolderUrl) { account, ocId, _, errorCode, errorDescription in
  836. if errorCode == 0 {
  837. self.readFile(serverUrlFileName: fileNameFolderUrl) { (account, metadataFolder, errorCode, errorDescription) in
  838. if errorCode == 0 {
  839. if let metadata = metadataFolder {
  840. NCManageDatabase.shared.addMetadata(metadata)
  841. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: fileNameFolderUrl, account: account)
  842. }
  843. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(metadataFolder?.ocId) {
  844. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCreateFolder, userInfo: ["ocId": metadata.ocId])
  845. }
  846. }
  847. completion(errorCode, errorDescription)
  848. }
  849. } else if errorCode == 405 && overwrite {
  850. completion(0, "")
  851. } else {
  852. completion(errorCode, errorDescription)
  853. }
  854. }
  855. }
  856. func createFolder(assets: [PHAsset], selector: String, useSubFolder: Bool, account: String, urlBase: String) -> Bool {
  857. let serverUrl = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: urlBase, account: account)
  858. let fileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  859. let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: urlBase, account: account)
  860. var result = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase)
  861. if useSubFolder && result {
  862. for dateSubFolder in CCUtility.createNameSubFolder(assets) {
  863. let fileName = (dateSubFolder as! NSString).lastPathComponent
  864. let serverUrl = ((autoUploadPath + "/" + (dateSubFolder as! String)) as NSString).deletingLastPathComponent
  865. result = createFolderWithSemaphore(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase)
  866. if !result { break }
  867. }
  868. }
  869. return result
  870. }
  871. private func createFolderWithSemaphore(fileName: String, serverUrl: String, account: String, urlBase: String) -> Bool {
  872. var result: Bool = false
  873. let semaphore = Semaphore()
  874. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: true) { errorCode, _ in
  875. if errorCode == 0 { result = true }
  876. semaphore.continue()
  877. }
  878. if semaphore.wait() == .success { result = true }
  879. return result
  880. }
  881. // MARK: - WebDav Delete
  882. @objc func deleteMetadata(_ metadata: tableMetadata, onlyLocalCache: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  883. if onlyLocalCache {
  884. var metadatas = [metadata]
  885. if metadata.directory {
  886. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  887. metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND directory == false", metadata.account, serverUrl))
  888. }
  889. for metadata in metadatas {
  890. NCManageDatabase.shared.deleteVideo(metadata: metadata)
  891. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  892. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  893. if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  894. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadataLivePhoto.ocId))
  895. NCUtilityFileSystem.shared.deleteFile(filePath: CCUtility.getDirectoryProviderStorageOcId(metadataLivePhoto.ocId))
  896. }
  897. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "serverUrl": metadata.serverUrl, "account": metadata.account, "classFile": metadata.classFile, "onlyLocalCache": true])
  898. }
  899. return completion(0, "")
  900. }
  901. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
  902. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  903. if isDirectoryEncrypted {
  904. #if !EXTENSION
  905. if metadataLive == nil {
  906. NCNetworkingE2EE.shared.deleteMetadata(metadata, completion: completion)
  907. } else {
  908. NCNetworkingE2EE.shared.deleteMetadata(metadataLive!) { errorCode, errorDescription in
  909. if errorCode == 0 {
  910. NCNetworkingE2EE.shared.deleteMetadata(metadata, completion: completion)
  911. } else {
  912. completion(errorCode, errorDescription)
  913. }
  914. }
  915. }
  916. #endif
  917. } else {
  918. if metadataLive == nil {
  919. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  920. } else {
  921. self.deleteMetadataPlain(metadataLive!, addCustomHeaders: nil) { errorCode, errorDescription in
  922. if errorCode == 0 {
  923. self.deleteMetadataPlain(metadata, addCustomHeaders: nil, completion: completion)
  924. } else {
  925. completion(errorCode, errorDescription)
  926. }
  927. }
  928. }
  929. }
  930. }
  931. func deleteMetadataPlain(_ metadata: tableMetadata, addCustomHeaders: [String: String]?, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  932. // verify permission
  933. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanDelete)
  934. if metadata.permissions != "" && permission == false {
  935. return completion(NCGlobal.shared.errorInternalError, "_no_permission_delete_file_")
  936. }
  937. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  938. NCCommunication.shared.deleteFileOrFolder(serverUrlFileName, customUserAgent: nil, addCustomHeaders: addCustomHeaders) { account, errorCode, errorDescription in
  939. if errorCode == 0 || errorCode == NCGlobal.shared.errorResourceNotFound {
  940. do {
  941. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  942. } catch { }
  943. NCManageDatabase.shared.deleteVideo(metadata: metadata)
  944. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  945. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  946. if metadata.directory {
  947. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account)
  948. }
  949. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": metadata.ocId, "fileNameView": metadata.fileNameView, "serverUrl": metadata.serverUrl, "account": metadata.account, "classFile": metadata.classFile, "onlyLocalCache": false])
  950. }
  951. completion(errorCode, errorDescription)
  952. }
  953. }
  954. // MARK: - WebDav Favorite
  955. @objc func favoriteMetadata(_ metadata: tableMetadata, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  956. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  957. favoriteMetadataPlain(metadataLive) { errorCode, errorDescription in
  958. if errorCode == 0 {
  959. self.favoriteMetadataPlain(metadata, completion: completion)
  960. } else {
  961. completion(errorCode, errorDescription)
  962. }
  963. }
  964. } else {
  965. favoriteMetadataPlain(metadata, completion: completion)
  966. }
  967. }
  968. private func favoriteMetadataPlain(_ metadata: tableMetadata, completion: @escaping (_ errorCode: Int, _ errorDescription: String) -> Void) {
  969. let fileName = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, account: metadata.account)!
  970. let favorite = !metadata.favorite
  971. let ocId = metadata.ocId
  972. NCCommunication.shared.setFavorite(fileName: fileName, favorite: favorite) { account, errorCode, errorDescription in
  973. if errorCode == 0 && metadata.account == account {
  974. NCManageDatabase.shared.setMetadataFavorite(ocId: metadata.ocId, favorite: favorite)
  975. #if !EXTENSION
  976. if favorite {
  977. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorReadFile)
  978. }
  979. #endif
  980. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  981. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterFavoriteFile, userInfo: ["ocId": metadata.ocId])
  982. }
  983. }
  984. completion(errorCode, errorDescription)
  985. }
  986. }
  987. @objc func listingFavoritescompletion(selector: String, completion: @escaping (_ account: String, _ metadatas: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  988. NCCommunication.shared.listingFavorites(showHiddenFiles: CCUtility.getShowHiddenFiles(), queue: NCCommunicationCommon.shared.backgroundQueue) { account, files, errorCode, errorDescription in
  989. if errorCode == 0 {
  990. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { _, _, metadatas in
  991. NCManageDatabase.shared.updateMetadatasFavorite(account: account, metadatas: metadatas)
  992. if selector != NCGlobal.shared.selectorListingFavorite {
  993. #if !EXTENSION
  994. for metadata in metadatas {
  995. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: selector)
  996. }
  997. #endif
  998. }
  999. completion(account, metadatas, errorCode, errorDescription)
  1000. }
  1001. } else {
  1002. completion(account, nil, errorCode, errorDescription)
  1003. }
  1004. }
  1005. }
  1006. // MARK: - Lock Files
  1007. @objc func lockUnlockFile(_ metadata: tableMetadata, shoulLock: Bool) {
  1008. NCCommunication.shared.lockUnlockFile(serverUrlFileName: metadata.serverUrl + "/" + metadata.fileName, shouldLock: shoulLock) { errorCode, errorDescription in
  1009. // 0: lock was successful; 412: lock did not change, no error, refresh
  1010. guard errorCode == 0 || errorCode == 412 else {
  1011. NCContentPresenter.shared.messageNotification(metadata.fileName, description: "_files_lock_error_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode, priority: .max)
  1012. return
  1013. }
  1014. NCNetworking.shared.readFile(serverUrlFileName: metadata.serverUrl + "/" + metadata.fileName) { account, metadata, errorCode, errorDescription in
  1015. guard errorCode == 0, let metadata = metadata else { return }
  1016. NCManageDatabase.shared.addMetadata(metadata)
  1017. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource)
  1018. }
  1019. }
  1020. }
  1021. // MARK: - WebDav Rename
  1022. @objc func renameMetadata(_ metadata: tableMetadata, fileNameNew: String, viewController: UIViewController?, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
  1023. let isDirectoryEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
  1024. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  1025. let fileNameNew = fileNameNew.trimmingCharacters(in: .whitespacesAndNewlines)
  1026. let fileNameNewLive = (fileNameNew as NSString).deletingPathExtension + ".mov"
  1027. if isDirectoryEncrypted {
  1028. #if !EXTENSION
  1029. if metadataLive == nil {
  1030. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, completion: completion)
  1031. } else {
  1032. NCNetworkingE2EE.shared.renameMetadata(metadataLive!, fileNameNew: fileNameNewLive) { errorCode, errorDescription in
  1033. if errorCode == 0 {
  1034. NCNetworkingE2EE.shared.renameMetadata(metadata, fileNameNew: fileNameNew, completion: completion)
  1035. } else {
  1036. completion(errorCode, errorDescription)
  1037. }
  1038. }
  1039. }
  1040. #endif
  1041. } else {
  1042. if metadataLive == nil {
  1043. renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  1044. } else {
  1045. renameMetadataPlain(metadataLive!, fileNameNew: fileNameNewLive) { errorCode, errorDescription in
  1046. if errorCode == 0 {
  1047. self.renameMetadataPlain(metadata, fileNameNew: fileNameNew, completion: completion)
  1048. } else {
  1049. completion(errorCode, errorDescription)
  1050. }
  1051. }
  1052. }
  1053. }
  1054. }
  1055. private func renameMetadataPlain(_ metadata: tableMetadata, fileNameNew: String, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
  1056. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  1057. if !(metadata.permissions == "") && !permission {
  1058. return completion(NCGlobal.shared.errorInternalError, "_no_permission_modify_file_")
  1059. }
  1060. guard let fileNameNew = CCUtility.removeForbiddenCharactersServer(fileNameNew) else {
  1061. return completion(0, "")
  1062. }
  1063. if fileNameNew.count == 0 || fileNameNew == metadata.fileNameView {
  1064. return completion(0, "")
  1065. }
  1066. let fileNamePath = metadata.serverUrl + "/" + metadata.fileName
  1067. let fileNameToPath = metadata.serverUrl + "/" + fileNameNew
  1068. let ocId = metadata.ocId
  1069. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: fileNamePath, serverUrlFileNameDestination: fileNameToPath, overwrite: false) { account, errorCode, errorDescription in
  1070. if errorCode == 0 {
  1071. NCManageDatabase.shared.renameMetadata(fileNameTo: fileNameNew, ocId: ocId)
  1072. if metadata.directory {
  1073. let serverUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1074. let serverUrlTo = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: fileNameNew)!
  1075. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  1076. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, serverUrlTo: serverUrlTo, etag: "", ocId: nil, fileId: nil, encrypted: directory.e2eEncrypted, richWorkspace: nil, account: metadata.account)
  1077. }
  1078. } else {
  1079. let ext = (metadata.fileName as NSString).pathExtension
  1080. let extNew = (fileNameNew as NSString).pathExtension
  1081. if ext != extNew {
  1082. if let path = CCUtility.getDirectoryProviderStorageOcId(ocId) {
  1083. NCUtilityFileSystem.shared.deleteFile(filePath: path)
  1084. }
  1085. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": metadata.serverUrl])
  1086. } else {
  1087. NCManageDatabase.shared.setLocalFile(ocId: ocId, fileName: fileNameNew, etag: nil)
  1088. // Move file system
  1089. let atPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + metadata.fileName
  1090. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId) + "/" + fileNameNew
  1091. do {
  1092. try FileManager.default.moveItem(atPath: atPath, toPath: toPath)
  1093. } catch { }
  1094. }
  1095. }
  1096. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  1097. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRenameFile, userInfo: ["ocId": metadata.ocId])
  1098. }
  1099. }
  1100. completion(errorCode, errorDescription)
  1101. }
  1102. }
  1103. // MARK: - WebDav Move
  1104. @objc func moveMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
  1105. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  1106. moveMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { errorCode, errorDescription in
  1107. if errorCode == 0 {
  1108. self.moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1109. } else {
  1110. completion(errorCode, errorDescription)
  1111. }
  1112. }
  1113. } else {
  1114. moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1115. }
  1116. }
  1117. private func moveMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
  1118. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  1119. if !(metadata.permissions == "") && !permission {
  1120. return completion(NCGlobal.shared.errorInternalError, "_no_permission_modify_file_")
  1121. }
  1122. let serverUrlFrom = metadata.serverUrl
  1123. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  1124. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  1125. NCCommunication.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { account, errorCode, errorDescription in
  1126. if errorCode == 0 {
  1127. if metadata.directory {
  1128. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: account)
  1129. }
  1130. NCManageDatabase.shared.moveMetadata(ocId: metadata.ocId, serverUrlTo: serverUrlTo)
  1131. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMoveFile, userInfo: ["ocId": metadata.ocId, "serverUrlFrom": serverUrlFrom])
  1132. }
  1133. completion(errorCode, errorDescription)
  1134. }
  1135. }
  1136. // MARK: - WebDav Copy
  1137. @objc func copyMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
  1138. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  1139. copyMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite) { errorCode, errorDescription in
  1140. if errorCode == 0 {
  1141. self.copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1142. } else {
  1143. completion(errorCode, errorDescription)
  1144. }
  1145. }
  1146. } else {
  1147. copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite, completion: completion)
  1148. }
  1149. }
  1150. private func copyMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool, completion: @escaping (_ errorCode: Int, _ errorDescription: String?) -> Void) {
  1151. let permission = NCUtility.shared.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  1152. if !(metadata.permissions == "") && !permission {
  1153. return completion(NCGlobal.shared.errorInternalError, "_no_permission_modify_file_")
  1154. }
  1155. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  1156. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  1157. NCCommunication.shared.copyFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite) { _, errorCode, errorDescription in
  1158. if errorCode == 0 {
  1159. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCopyFile, userInfo: ["ocId": metadata.ocId, "serverUrlTo": serverUrlTo])
  1160. }
  1161. completion(errorCode, errorDescription)
  1162. }
  1163. }
  1164. // MARK: - Direct Download
  1165. func getVideoUrl(metadata: tableMetadata, completition: @escaping (_ url: URL?) -> Void) {
  1166. if CCUtility.fileProviderStorageExists(metadata) {
  1167. completition(URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)))
  1168. } else {
  1169. NCCommunication.shared.getDirectDownload(fileId: metadata.fileId) { _, url, errorCode, _ in
  1170. if errorCode == 0 && url != nil {
  1171. if let url = URL(string: url!) {
  1172. completition(url)
  1173. } else {
  1174. completition(nil)
  1175. }
  1176. } else {
  1177. completition(nil)
  1178. }
  1179. }
  1180. }
  1181. }
  1182. // MARK: - TEST API
  1183. /*
  1184. @objc public func getDirectDownload(urlBase: String, username: String, password: String, fileId: String, customUserAgent: String? = nil, completionHandler: @escaping (_ token: String?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  1185. let endpoint = "/ocs/v2.php/apps/dav/api/v1/direct"
  1186. let url:URLConvertible = try! (urlBase + endpoint).asURL() as URLConvertible
  1187. var headers: HTTPHeaders = [.authorization(username: username, password: password)]
  1188. if customUserAgent != nil {
  1189. headers.update(.userAgent(customUserAgent!))
  1190. }
  1191. //headers.update(.contentType("application/json"))
  1192. headers.update(name: "OCS-APIRequest", value: "true")
  1193. let method = HTTPMethod(rawValue: "POST")
  1194. let parameters = [
  1195. "fileId": fileId,
  1196. ]
  1197. AF.request(url, method: method, parameters: parameters, headers: headers).validate(statusCode: 200..<300).response { (response) in
  1198. debugPrint(response)
  1199. switch response.result {
  1200. case .failure(let error):
  1201. completionHandler(nil, 0, "")
  1202. case .success(let data):
  1203. if let data = data {
  1204. completionHandler("", 0, "")
  1205. } else {
  1206. completionHandler(nil, NSURLErrorBadServerResponse, NSLocalizedString("_error_decode_xml_", value: "Invalid response, error decode XML", comment: ""))
  1207. }
  1208. }
  1209. }
  1210. }
  1211. */
  1212. }
  1213. extension Array where Element == URLQueryItem {
  1214. subscript(name: String) -> URLQueryItem? {
  1215. first(where: { $0.name == name })
  1216. }
  1217. }