NCNetworking.swift 81 KB

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