NCNetworking.swift 76 KB

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