NCNetworking.swift 80 KB

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