NCNetworking+WebDAV.swift 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. //
  2. // NCNetworking+WebDAV.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 07/02/24.
  6. // Copyright © 2024 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 NextcloudKit
  25. import Alamofire
  26. import Queuer
  27. import Photos
  28. extension NCNetworking {
  29. // MARK: - Read file, folder
  30. func readFolder(serverUrl: String,
  31. account: String,
  32. checkResponseDataChanged: Bool,
  33. queue: DispatchQueue,
  34. taskHandler: @escaping (_ task: URLSessionTask) -> Void = { _ in },
  35. completion: @escaping (_ account: String, _ metadataFolder: tableMetadata?, _ metadatas: [tableMetadata]?, _ isDataChanged: Bool, _ error: NKError) -> Void) {
  36. func storeFolder(_ metadataFolder: tableMetadata?) {
  37. guard let metadataFolder else { return }
  38. self.database.addMetadata(metadataFolder)
  39. self.database.addDirectory(e2eEncrypted: metadataFolder.e2eEncrypted,
  40. favorite: metadataFolder.favorite,
  41. ocId: metadataFolder.ocId,
  42. fileId: metadataFolder.fileId,
  43. etag: metadataFolder.etag,
  44. permissions: metadataFolder.permissions,
  45. richWorkspace: metadataFolder.richWorkspace,
  46. serverUrl: serverUrl,
  47. account: metadataFolder.account)
  48. }
  49. NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrl,
  50. depth: "1",
  51. showHiddenFiles: NCKeychain().showHiddenFiles,
  52. account: account,
  53. options: NKRequestOptions(queue: queue)) { task in
  54. taskHandler(task)
  55. } completion: { account, files, responseData, error in
  56. guard error == .success, let files else {
  57. return completion(account, nil, nil, false, error)
  58. }
  59. let isResponseDataChanged = self.isResponseDataChanged(account: account, responseData: responseData)
  60. if checkResponseDataChanged, !isResponseDataChanged {
  61. let metadataFolder = self.database.getMetadataDirectoryFrom(files: files)
  62. storeFolder(metadataFolder)
  63. return completion(account, metadataFolder, nil, false, error)
  64. }
  65. self.database.convertFilesToMetadatas(files, useFirstAsMetadataFolder: true) { metadataFolder, metadatas in
  66. storeFolder(metadataFolder)
  67. self.database.updateMetadatasFiles(metadatas, serverUrl: serverUrl, account: account)
  68. completion(account, metadataFolder, metadatas, true, error)
  69. }
  70. }
  71. }
  72. func readFile(serverUrlFileName: String,
  73. showHiddenFiles: Bool = NCKeychain().showHiddenFiles,
  74. account: String,
  75. queue: DispatchQueue = NextcloudKit.shared.nkCommonInstance.backgroundQueue,
  76. taskHandler: @escaping (_ task: URLSessionTask) -> Void = { _ in },
  77. completion: @escaping (_ account: String, _ metadata: tableMetadata?, _ error: NKError) -> Void) {
  78. let options = NKRequestOptions(queue: queue)
  79. NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: showHiddenFiles, account: account, options: options) { task in
  80. taskHandler(task)
  81. } completion: { account, files, _, error in
  82. guard error == .success, files?.count == 1, let file = files?.first else {
  83. return completion(account, nil, error)
  84. }
  85. let isDirectoryE2EE = self.utilityFileSystem.isDirectoryE2EE(file: file)
  86. let metadata = self.database.convertFileToMetadata(file, isDirectoryE2EE: isDirectoryE2EE)
  87. completion(account, metadata, error)
  88. }
  89. }
  90. func fileExists(serverUrlFileName: String,
  91. account: String,
  92. completion: @escaping (_ account: String, _ exists: Bool?, _ file: NKFile?, _ error: NKError) -> Void) {
  93. let options = NKRequestOptions(timeout: 10, createProperties: [], queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  94. NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName,
  95. depth: "0",
  96. account: account,
  97. options: options) { account, files, _, error in
  98. if error == .success, let file = files?.first {
  99. completion(account, true, file, error)
  100. } else if error.errorCode == self.global.errorResourceNotFound {
  101. completion(account, false, nil, error)
  102. } else {
  103. completion(account, nil, nil, error)
  104. }
  105. }
  106. }
  107. func fileExists(serverUrlFileName: String, account: String) async -> (account: String, exists: Bool?, file: NKFile?, error: NKError) {
  108. await withUnsafeContinuation({ continuation in
  109. fileExists(serverUrlFileName: serverUrlFileName, account: account) { account, exists, file, error in
  110. continuation.resume(returning: (account, exists, file, error))
  111. }
  112. })
  113. }
  114. func createFileName(fileNameBase: String, account: String, serverUrl: String) async -> String {
  115. var exitLoop = false
  116. var resultFileName = fileNameBase
  117. func newFileName() {
  118. var name = NSString(string: resultFileName).deletingPathExtension
  119. let ext = NSString(string: resultFileName).pathExtension
  120. let characters = Array(name)
  121. if characters.count < 2 {
  122. if ext.isEmpty {
  123. resultFileName = name + " 1"
  124. } else {
  125. resultFileName = name + " 1" + "." + ext
  126. }
  127. } else {
  128. let space = characters[characters.count - 2]
  129. let numChar = characters[characters.count - 1]
  130. var num = Int(String(numChar))
  131. if space == " " && num != nil {
  132. name = String(name.dropLast())
  133. num = num! + 1
  134. if ext.isEmpty {
  135. resultFileName = name + "\(num!)"
  136. } else {
  137. resultFileName = name + "\(num!)" + "." + ext
  138. }
  139. } else {
  140. if ext.isEmpty {
  141. resultFileName = name + " 1"
  142. } else {
  143. resultFileName = name + " 1" + "." + ext
  144. }
  145. }
  146. }
  147. }
  148. while !exitLoop {
  149. if self.database.getMetadata(predicate: NSPredicate(format: "fileNameView == %@ AND serverUrl == %@ AND account == %@", resultFileName, serverUrl, account)) != nil {
  150. newFileName()
  151. continue
  152. }
  153. let results = await fileExists(serverUrlFileName: serverUrl + "/" + resultFileName, account: account)
  154. if let exists = results.exists, exists {
  155. newFileName()
  156. } else {
  157. exitLoop = true
  158. }
  159. }
  160. return resultFileName
  161. }
  162. // MARK: - Create Folder
  163. func createFolder(fileName: String,
  164. serverUrl: String,
  165. overwrite: Bool,
  166. withPush: Bool,
  167. metadata: tableMetadata? = nil,
  168. sceneIdentifier: String?,
  169. session: NCSession.Session,
  170. completion: @escaping (_ error: NKError) -> Void) {
  171. let isDirectoryEncrypted = utilityFileSystem.isDirectoryE2EE(session: session, serverUrl: serverUrl)
  172. let fileName = fileName.trimmingCharacters(in: .whitespacesAndNewlines)
  173. if isDirectoryEncrypted {
  174. #if !EXTENSION
  175. Task {
  176. let error = await NCNetworkingE2EECreateFolder().createFolder(fileName: fileName, serverUrl: serverUrl, withPush: withPush, sceneIdentifier: sceneIdentifier, session: session)
  177. completion(error)
  178. }
  179. #endif
  180. } else {
  181. var fileNameFolder = utility.removeForbiddenCharacters(fileName)
  182. if fileName != fileNameFolder {
  183. let errorDescription = String(format: NSLocalizedString("_forbidden_characters_", comment: ""), self.global.forbiddenCharacters.joined(separator: " "))
  184. let error = NKError(errorCode: self.global.errorConflict, errorDescription: errorDescription)
  185. return completion(error)
  186. }
  187. if !overwrite {
  188. fileNameFolder = utilityFileSystem.createFileName(fileNameFolder, serverUrl: serverUrl, account: session.account)
  189. }
  190. if fileNameFolder.isEmpty {
  191. return completion(.success)
  192. }
  193. let fileNameFolderUrl = serverUrl + "/" + fileNameFolder
  194. NextcloudKit.shared.createFolder(serverUrlFileName: fileNameFolderUrl, account: session.account) { account, _, _, _, error in
  195. self.readFile(serverUrlFileName: fileNameFolderUrl, account: account) { account, metadataFolder, error in
  196. /// metadataStatusWaitCreateFolder
  197. ///
  198. if let metadata, metadata.status == self.global.metadataStatusWaitCreateFolder {
  199. if error == .success {
  200. self.database.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND fileName == %@ AND serverUrl == %@", metadata.account, metadata.fileName, metadata.serverUrl))
  201. } else {
  202. self.database.setMetadataSession(ocId: metadata.ocId, sessionError: error.errorDescription)
  203. }
  204. }
  205. if error == .success, let metadataFolder {
  206. self.database.addMetadata(metadataFolder)
  207. self.database.addDirectory(e2eEncrypted: metadataFolder.e2eEncrypted,
  208. favorite: metadataFolder.favorite,
  209. ocId: metadataFolder.ocId,
  210. fileId: metadataFolder.fileId,
  211. permissions: metadataFolder.permissions,
  212. serverUrl: fileNameFolderUrl,
  213. account: account)
  214. NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterCreateFolder, userInfo: ["ocId": metadataFolder.ocId, "serverUrl": metadataFolder.serverUrl, "account": metadataFolder.account, "withPush": withPush, "sceneIdentifier": sceneIdentifier as Any])
  215. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl": serverUrl])
  216. }
  217. completion(error)
  218. }
  219. }
  220. }
  221. }
  222. func createFolder(assets: [PHAsset]?,
  223. useSubFolder: Bool,
  224. withPush: Bool,
  225. sceneIdentifier: String? = nil,
  226. hud: NCHud? = nil,
  227. session: NCSession.Session) -> Bool {
  228. let autoUploadPath = self.database.getAccountAutoUploadPath(session: session)
  229. let serverUrlBase = self.database.getAccountAutoUploadDirectory(session: session)
  230. let fileNameBase = self.database.getAccountAutoUploadFileName()
  231. let autoUploadSubfolderGranularity = self.database.getAccountAutoUploadSubfolderGranularity()
  232. func createFolder(fileName: String, serverUrl: String) -> Bool {
  233. var result: Bool = false
  234. let semaphore = DispatchSemaphore(value: 0)
  235. self.createFolder(fileName: fileName, serverUrl: serverUrl, overwrite: true, withPush: withPush, metadata: nil, sceneIdentifier: sceneIdentifier, session: session) { error in
  236. if error == .success { result = true }
  237. semaphore.signal()
  238. }
  239. semaphore.wait()
  240. return result
  241. }
  242. func createNameSubFolder() -> [String] {
  243. var datesSubFolder: [String] = []
  244. if let assets {
  245. for asset in assets {
  246. datesSubFolder.append(utilityFileSystem.createGranularityPath(asset: asset))
  247. }
  248. } else {
  249. datesSubFolder.append(utilityFileSystem.createGranularityPath())
  250. }
  251. return Array(Set(datesSubFolder)).sorted()
  252. }
  253. var result = createFolder(fileName: fileNameBase, serverUrl: serverUrlBase)
  254. if useSubFolder && result {
  255. let folders = createNameSubFolder()
  256. var num: Float = 0
  257. for dateSubFolder in folders {
  258. let subfolderArray = dateSubFolder.split(separator: "/")
  259. let year = subfolderArray[0]
  260. let serverUrlYear = autoUploadPath
  261. result = createFolder(fileName: String(year), serverUrl: serverUrlYear) // Year always present independently of preference value
  262. if result && autoUploadSubfolderGranularity >= self.global.subfolderGranularityMonthly {
  263. let month = subfolderArray[1]
  264. let serverUrlMonth = autoUploadPath + "/" + year
  265. result = createFolder(fileName: String(month), serverUrl: serverUrlMonth)
  266. if result && autoUploadSubfolderGranularity == self.global.subfolderGranularityDaily {
  267. let day = subfolderArray[2]
  268. let serverUrlDay = autoUploadPath + "/" + year + "/" + month
  269. result = createFolder(fileName: String(day), serverUrl: serverUrlDay)
  270. }
  271. }
  272. if !result { break }
  273. num += 1
  274. hud?.progress(num: num, total: Float(folders.count))
  275. }
  276. }
  277. return result
  278. }
  279. // MARK: - Delete
  280. func tapHudDelete() {
  281. tapHudStopDelete = true
  282. }
  283. func deleteCache(_ metadata: tableMetadata, sceneIdentifier: String?) async -> (NKError) {
  284. let ncHud = NCHud()
  285. var num: Float = 0
  286. func numIncrement() -> Float {
  287. num += 1
  288. return num
  289. }
  290. func deleteLocalFile(metadata: tableMetadata) {
  291. if let metadataLive = self.database.getMetadataLivePhoto(metadata: metadata) {
  292. self.database.deleteLocalFileOcId(metadataLive.ocId)
  293. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadataLive.ocId))
  294. }
  295. self.database.deleteVideo(metadata: metadata)
  296. self.database.deleteLocalFileOcId(metadata.ocId)
  297. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  298. #if !EXTENSION
  299. NCImageCache.shared.removeImageCache(ocIdPlusEtag: metadata.ocId + metadata.etag)
  300. #endif
  301. }
  302. self.tapHudStopDelete = false
  303. if metadata.directory {
  304. #if !EXTENSION
  305. if let controller = SceneManager.shared.getController(sceneIdentifier: sceneIdentifier) {
  306. await MainActor.run {
  307. ncHud.initHudRing(view: controller.view, tapToCancelDetailText: true, tapOperation: tapHudDelete)
  308. }
  309. }
  310. #endif
  311. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  312. let metadatas = self.database.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND directory == false", metadata.account, serverUrl))
  313. let total = Float(metadatas.count)
  314. for metadata in metadatas {
  315. deleteLocalFile(metadata: metadata)
  316. let num = numIncrement()
  317. ncHud.progress(num: num, total: total)
  318. if tapHudStopDelete { break }
  319. }
  320. #if !EXTENSION
  321. ncHud.dismiss()
  322. #endif
  323. } else {
  324. deleteLocalFile(metadata: metadata)
  325. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl": metadata.serverUrl, "clearDataSource": true])
  326. }
  327. return .success
  328. }
  329. func deleteMetadatas(_ metadatas: [tableMetadata], sceneIdentifier: String?) {
  330. var metadatasPlain: [tableMetadata] = []
  331. var metadatasE2EE: [tableMetadata] = []
  332. let ncHud = NCHud()
  333. var num: Float = 0
  334. func numIncrement() -> Float {
  335. num += 1
  336. return num
  337. }
  338. for metadata in metadatas {
  339. if metadata.isDirectoryE2EE {
  340. metadatasE2EE.append(metadata)
  341. } else {
  342. metadatasPlain.append(metadata)
  343. }
  344. }
  345. #if !EXTENSION
  346. if !metadatasE2EE.isEmpty {
  347. if isOffline {
  348. return NCContentPresenter().showInfo(error: NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_offline_not_allowed_"))
  349. }
  350. self.tapHudStopDelete = false
  351. let total = Float(metadatasE2EE.count)
  352. Task {
  353. if let controller = SceneManager.shared.getController(sceneIdentifier: sceneIdentifier) {
  354. await MainActor.run {
  355. ncHud.initHudRing(view: controller.view, tapToCancelDetailText: true, tapOperation: tapHudDelete)
  356. }
  357. }
  358. var ocIdDeleted: [String] = []
  359. var error = NKError()
  360. for metadata in metadatasE2EE where error == .success {
  361. error = await NCNetworkingE2EEDelete().delete(metadata: metadata)
  362. if error == .success {
  363. ocIdDeleted.append(metadata.ocId)
  364. }
  365. let num = numIncrement()
  366. ncHud.progress(num: num, total: total)
  367. if tapHudStopDelete { break }
  368. }
  369. ncHud.dismiss()
  370. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": ocIdDeleted, "error": error])
  371. }
  372. }
  373. #endif
  374. for metadata in metadatasPlain {
  375. let permission = NCUtility().permissionsContainsString(metadata.permissions, permissions: NCPermissions().permissionCanDelete)
  376. if (!metadata.permissions.isEmpty && permission == false) || (metadata.status != global.metadataStatusNormal) {
  377. return NCContentPresenter().showInfo(error: NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_delete_file_"))
  378. }
  379. if metadata.status == global.metadataStatusWaitCreateFolder {
  380. let metadatas = database.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@", metadata.account, metadata.serverUrl))
  381. for metadata in metadatas {
  382. database.deleteMetadataOcId(metadata.ocId)
  383. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  384. }
  385. return
  386. }
  387. self.database.setMetadataStatus(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusWaitDelete)
  388. }
  389. }
  390. // MARK: - Rename
  391. func renameMetadata(_ metadata: tableMetadata, fileNameNew: String) {
  392. let permission = utility.permissionsContainsString(metadata.permissions, permissions: NCPermissions().permissionCanRename)
  393. if (!metadata.permissions.isEmpty && permission == false) ||
  394. (metadata.status != global.metadataStatusNormal && metadata.status != global.metadataStatusWaitRename) {
  395. return NCContentPresenter().showInfo(error: NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_modify_file_"))
  396. }
  397. if metadata.isDirectoryE2EE {
  398. #if !EXTENSION
  399. if isOffline {
  400. return NCContentPresenter().showInfo(error: NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_offline_not_allowed_"))
  401. }
  402. Task {
  403. let error = await NCNetworkingE2EERename().rename(metadata: metadata, fileNameNew: fileNameNew)
  404. if error != .success {
  405. NCContentPresenter().showError(error: error)
  406. }
  407. }
  408. #endif
  409. } else {
  410. self.database.renameMetadata(fileNameNew: fileNameNew, ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusWaitRename)
  411. }
  412. }
  413. // MARK: - Move
  414. func moveMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool) {
  415. let permission = utility.permissionsContainsString(metadata.permissions, permissions: NCPermissions().permissionCanRename)
  416. if (!metadata.permissions.isEmpty && !permission) ||
  417. (metadata.status != global.metadataStatusNormal && metadata.status != global.metadataStatusWaitMove) {
  418. return NCContentPresenter().showInfo(error: NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_modify_file_"))
  419. }
  420. self.database.setMetadataCopyMove(ocId: metadata.ocId, serverUrlTo: serverUrlTo, overwrite: overwrite.description, status: NCGlobal.shared.metadataStatusWaitMove)
  421. }
  422. // MARK: - Copy
  423. func copyMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool) {
  424. let permission = utility.permissionsContainsString(metadata.permissions, permissions: NCPermissions().permissionCanRename)
  425. if (!metadata.permissions.isEmpty && !permission) ||
  426. (metadata.status != global.metadataStatusNormal && metadata.status != global.metadataStatusWaitCopy) {
  427. return NCContentPresenter().showInfo(error: NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_modify_file_"))
  428. }
  429. self.database.setMetadataCopyMove(ocId: metadata.ocId, serverUrlTo: serverUrlTo, overwrite: overwrite.description, status: NCGlobal.shared.metadataStatusWaitCopy)
  430. }
  431. // MARK: - Favorite
  432. func favoriteMetadata(_ metadata: tableMetadata,
  433. completion: @escaping (_ error: NKError) -> Void) {
  434. if metadata.status != global.metadataStatusNormal && metadata.status != global.metadataStatusWaitFavorite {
  435. return NCContentPresenter().showInfo(error: NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_favorite_file_"))
  436. }
  437. self.database.setMetadataFavorite(ocId: metadata.ocId, favorite: !metadata.favorite, saveOldFavorite: metadata.favorite.description, status: global.metadataStatusWaitFavorite)
  438. NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterFavoriteFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl])
  439. }
  440. // MARK: - Lock Files
  441. func lockUnlockFile(_ metadata: tableMetadata, shoulLock: Bool) {
  442. NextcloudKit.shared.lockUnlockFile(serverUrlFileName: metadata.serverUrl + "/" + metadata.fileName, shouldLock: shoulLock, account: metadata.account) { _, _, error in
  443. // 0: lock was successful; 412: lock did not change, no error, refresh
  444. guard error == .success || error.errorCode == self.global.errorPreconditionFailed else {
  445. let error = NKError(errorCode: error.errorCode, errorDescription: "_files_lock_error_")
  446. NCContentPresenter().messageNotification(metadata.fileName, error: error, delay: self.global.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  447. return
  448. }
  449. self.readFile(serverUrlFileName: metadata.serverUrl + "/" + metadata.fileName, account: metadata.account) { _, metadata, error in
  450. guard error == .success, let metadata = metadata else { return }
  451. self.database.addMetadata(metadata)
  452. NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterReloadDataSource, userInfo: ["serverUrl": metadata.serverUrl, "clearDataSource": true])
  453. }
  454. }
  455. }
  456. // MARK: - Direct Download
  457. func getVideoUrl(metadata: tableMetadata,
  458. completition: @escaping (_ url: URL?, _ autoplay: Bool, _ error: NKError) -> Void) {
  459. if !metadata.url.isEmpty {
  460. if metadata.url.hasPrefix("/") {
  461. completition(URL(fileURLWithPath: metadata.url), true, .success)
  462. } else {
  463. completition(URL(string: metadata.url), true, .success)
  464. }
  465. } else if utilityFileSystem.fileProviderStorageExists(metadata) {
  466. completition(URL(fileURLWithPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)), false, .success)
  467. } else {
  468. NextcloudKit.shared.getDirectDownload(fileId: metadata.fileId, account: metadata.account) { _, url, _, error in
  469. if error == .success && url != nil {
  470. if let url = URL(string: url!) {
  471. completition(url, false, error)
  472. } else {
  473. completition(nil, false, error)
  474. }
  475. } else {
  476. completition(nil, false, error)
  477. }
  478. }
  479. }
  480. }
  481. // MARK: - Search
  482. /// WebDAV search
  483. func searchFiles(literal: String,
  484. account: String,
  485. taskHandler: @escaping (_ task: URLSessionTask) -> Void = { _ in },
  486. completion: @escaping (_ metadatas: [tableMetadata]?, _ error: NKError) -> Void) {
  487. NextcloudKit.shared.searchLiteral(serverUrl: NCSession.shared.getSession(account: account).urlBase,
  488. depth: "infinity",
  489. literal: literal,
  490. showHiddenFiles: NCKeychain().showHiddenFiles,
  491. account: account,
  492. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { task in
  493. taskHandler(task)
  494. } completion: { _, files, _, error in
  495. guard error == .success, let files else { return completion(nil, error) }
  496. self.database.convertFilesToMetadatas(files, useFirstAsMetadataFolder: false) { _, metadatas in
  497. self.database.addMetadatas(metadatas)
  498. completion(metadatas, error)
  499. }
  500. }
  501. }
  502. /// Unified Search (NC>=20)
  503. ///
  504. func unifiedSearchFiles(literal: String,
  505. account: String,
  506. taskHandler: @escaping (_ task: URLSessionTask) -> Void = { _ in },
  507. providers: @escaping (_ accout: String, _ searchProviders: [NKSearchProvider]?) -> Void,
  508. update: @escaping (_ account: String, _ id: String, NKSearchResult?, [tableMetadata]?) -> Void,
  509. completion: @escaping (_ account: String, _ error: NKError) -> Void) {
  510. let dispatchGroup = DispatchGroup()
  511. let session = NCSession.shared.getSession(account: account)
  512. dispatchGroup.enter()
  513. dispatchGroup.notify(queue: .main) {
  514. completion(session.account, NKError())
  515. }
  516. NextcloudKit.shared.unifiedSearch(term: literal, timeout: 30, timeoutProvider: 90, account: session.account) { _ in
  517. // example filter
  518. // ["calendar", "files", "fulltextsearch"].contains(provider.id)
  519. return true
  520. } request: { request in
  521. if let request = request {
  522. self.requestsUnifiedSearch.append(request)
  523. }
  524. } taskHandler: { task in
  525. taskHandler(task)
  526. } providers: { account, searchProviders in
  527. providers(account, searchProviders)
  528. } update: { account, partialResult, provider, _ in
  529. guard let partialResult = partialResult else { return }
  530. var metadatas: [tableMetadata] = []
  531. switch provider.id {
  532. case "files":
  533. partialResult.entries.forEach({ entry in
  534. if let fileId = entry.fileId,
  535. let metadata = self.database.getMetadata(predicate: NSPredicate(format: "account == %@ && fileId == %@", session.account, String(fileId))) {
  536. metadatas.append(metadata)
  537. } else if let filePath = entry.filePath {
  538. let semaphore = DispatchSemaphore(value: 0)
  539. self.loadMetadata(session: session, filePath: filePath, dispatchGroup: dispatchGroup) { _, metadata, _ in
  540. metadatas.append(metadata)
  541. semaphore.signal()
  542. }
  543. semaphore.wait()
  544. } else { print(#function, "[ERROR]: File search entry has no path: \(entry)") }
  545. })
  546. case "fulltextsearch":
  547. // NOTE: FTS could also return attributes like files
  548. // https://github.com/nextcloud/files_fulltextsearch/issues/143
  549. partialResult.entries.forEach({ entry in
  550. let url = URLComponents(string: entry.resourceURL)
  551. guard let dir = url?.queryItems?["dir"]?.value, let filename = url?.queryItems?["scrollto"]?.value else { return }
  552. if let metadata = self.database.getMetadata(predicate: NSPredicate(
  553. format: "account == %@ && path == %@ && fileName == %@",
  554. session.account,
  555. "/remote.php/dav/files/" + session.user + dir,
  556. filename)) {
  557. metadatas.append(metadata)
  558. } else {
  559. let semaphore = DispatchSemaphore(value: 0)
  560. self.loadMetadata(session: session, filePath: dir + filename, dispatchGroup: dispatchGroup) { _, metadata, _ in
  561. metadatas.append(metadata)
  562. semaphore.signal()
  563. }
  564. semaphore.wait()
  565. }
  566. })
  567. default:
  568. partialResult.entries.forEach({ entry in
  569. let metadata = self.database.createMetadata(fileName: entry.title,
  570. fileNameView: entry.title,
  571. ocId: NSUUID().uuidString,
  572. serverUrl: session.urlBase,
  573. url: entry.resourceURL,
  574. contentType: "",
  575. isUrl: true,
  576. name: partialResult.id,
  577. subline: entry.subline,
  578. iconName: entry.icon,
  579. iconUrl: entry.thumbnailURL,
  580. session: session,
  581. sceneIdentifier: nil)
  582. metadatas.append(metadata)
  583. })
  584. }
  585. update(account, provider.id, partialResult, metadatas)
  586. } completion: { _, _, _ in
  587. self.requestsUnifiedSearch.removeAll()
  588. dispatchGroup.leave()
  589. }
  590. }
  591. func unifiedSearchFilesProvider(id: String, term: String,
  592. limit: Int, cursor: Int,
  593. account: String,
  594. taskHandler: @escaping (_ task: URLSessionTask) -> Void = { _ in },
  595. completion: @escaping (_ account: String, _ searchResult: NKSearchResult?, _ metadatas: [tableMetadata]?, _ error: NKError) -> Void) {
  596. var metadatas: [tableMetadata] = []
  597. let session = NCSession.shared.getSession(account: account)
  598. let request = NextcloudKit.shared.searchProvider(id, term: term, limit: limit, cursor: cursor, timeout: 60, account: session.account) { task in
  599. taskHandler(task)
  600. } completion: { account, searchResult, _, error in
  601. guard let searchResult = searchResult else {
  602. return completion(account, nil, metadatas, error)
  603. }
  604. switch id {
  605. case "files":
  606. searchResult.entries.forEach({ entry in
  607. if let fileId = entry.fileId, let metadata = self.database.getMetadata(predicate: NSPredicate(format: "account == %@ && fileId == %@", session.account, String(fileId))) {
  608. metadatas.append(metadata)
  609. } else if let filePath = entry.filePath {
  610. let semaphore = DispatchSemaphore(value: 0)
  611. self.loadMetadata(session: session, filePath: filePath, dispatchGroup: nil) { _, metadata, _ in
  612. metadatas.append(metadata)
  613. semaphore.signal()
  614. }
  615. semaphore.wait()
  616. } else { print(#function, "[ERROR]: File search entry has no path: \(entry)") }
  617. })
  618. case "fulltextsearch":
  619. // NOTE: FTS could also return attributes like files
  620. // https://github.com/nextcloud/files_fulltextsearch/issues/143
  621. searchResult.entries.forEach({ entry in
  622. let url = URLComponents(string: entry.resourceURL)
  623. guard let dir = url?.queryItems?["dir"]?.value, let filename = url?.queryItems?["scrollto"]?.value else { return }
  624. if let metadata = self.database.getMetadata(predicate: NSPredicate(format: "account == %@ && path == %@ && fileName == %@",
  625. session.account,
  626. "/remote.php/dav/files/" + session.user + dir, filename)) {
  627. metadatas.append(metadata)
  628. } else {
  629. let semaphore = DispatchSemaphore(value: 0)
  630. self.loadMetadata(session: session, filePath: dir + filename, dispatchGroup: nil) { _, metadata, _ in
  631. metadatas.append(metadata)
  632. semaphore.signal()
  633. }
  634. semaphore.wait()
  635. }
  636. })
  637. default:
  638. searchResult.entries.forEach({ entry in
  639. let newMetadata = self.database.createMetadata(fileName: entry.title,
  640. fileNameView: entry.title,
  641. ocId: NSUUID().uuidString,
  642. serverUrl: session.urlBase,
  643. url: entry.resourceURL,
  644. contentType: "",
  645. isUrl: true,
  646. name: searchResult.name.lowercased(),
  647. subline: entry.subline,
  648. iconName: entry.icon,
  649. iconUrl: entry.thumbnailURL,
  650. session: session,
  651. sceneIdentifier: nil)
  652. metadatas.append(newMetadata)
  653. })
  654. }
  655. completion(account, searchResult, metadatas, error)
  656. }
  657. if let request = request {
  658. requestsUnifiedSearch.append(request)
  659. }
  660. }
  661. func cancelUnifiedSearchFiles() {
  662. for request in requestsUnifiedSearch {
  663. request.cancel()
  664. }
  665. requestsUnifiedSearch.removeAll()
  666. }
  667. private func loadMetadata(session: NCSession.Session,
  668. filePath: String,
  669. dispatchGroup: DispatchGroup? = nil,
  670. completion: @escaping (String, tableMetadata, NKError) -> Void) {
  671. let urlPath = session.urlBase + "/remote.php/dav/files/" + session.user + filePath
  672. dispatchGroup?.enter()
  673. self.readFile(serverUrlFileName: urlPath, account: session.account) { account, metadata, error in
  674. defer { dispatchGroup?.leave() }
  675. guard let metadata = metadata else { return }
  676. let returnMetadata = tableMetadata.init(value: metadata)
  677. self.database.addMetadata(metadata)
  678. completion(account, returnMetadata, error)
  679. }
  680. }
  681. }
  682. class NCOperationDownloadAvatar: ConcurrentOperation, @unchecked Sendable {
  683. var user: String
  684. var fileName: String
  685. var etag: String?
  686. var view: UIView?
  687. var account: String
  688. var isPreviewImageView: Bool
  689. init(user: String, fileName: String, account: String, view: UIView?, isPreviewImageView: Bool = false) {
  690. self.user = user
  691. self.fileName = fileName
  692. self.account = account
  693. self.view = view
  694. self.isPreviewImageView = isPreviewImageView
  695. self.etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  696. }
  697. override func start() {
  698. guard !isCancelled else { return self.finish() }
  699. NextcloudKit.shared.downloadAvatar(user: user,
  700. fileNameLocalPath: NCUtilityFileSystem().directoryUserData + "/" + fileName,
  701. sizeImage: NCGlobal.shared.avatarSize,
  702. avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
  703. etag: self.etag,
  704. account: account,
  705. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, image, _, etag, _, error in
  706. if error == .success, let image {
  707. NCManageDatabase.shared.addAvatar(fileName: self.fileName, etag: etag ?? "")
  708. DispatchQueue.main.async {
  709. let visibleCells: [UIView] = (self.view as? UICollectionView)?.visibleCells ?? (self.view as? UITableView)?.visibleCells ?? []
  710. for case let cell as NCCellProtocol in visibleCells {
  711. if self.user == cell.fileUser {
  712. if self.isPreviewImageView, let filePreviewImageView = cell.filePreviewImageView {
  713. UIView.transition(with: filePreviewImageView, duration: 0.75, options: .transitionCrossDissolve, animations: { filePreviewImageView.image = image}, completion: nil)
  714. } else if let fileAvatarImageView = cell.fileAvatarImageView {
  715. UIView.transition(with: fileAvatarImageView, duration: 0.75, options: .transitionCrossDissolve, animations: { fileAvatarImageView.image = image}, completion: nil)
  716. }
  717. break
  718. }
  719. }
  720. }
  721. } else if error.errorCode == NCGlobal.shared.errorNotModified {
  722. NCManageDatabase.shared.setAvatarLoaded(fileName: self.fileName)
  723. }
  724. self.finish()
  725. }
  726. }
  727. }
  728. class NCOperationFileExists: ConcurrentOperation, @unchecked Sendable {
  729. var serverUrlFileName: String
  730. var account: String
  731. var ocId: String
  732. init(metadata: tableMetadata) {
  733. serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  734. account = metadata.account
  735. ocId = metadata.ocId
  736. }
  737. override func start() {
  738. guard !isCancelled else { return self.finish() }
  739. let options = NKRequestOptions(timeout: 10,
  740. createProperties: [],
  741. removeProperties: [],
  742. queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  743. NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName,
  744. depth: "0",
  745. requestBody: nil,
  746. account: account,
  747. options: options) { _, _, _, error in
  748. if error == .success {
  749. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterFileExists, userInfo: ["ocId": self.ocId, "fileExists": true])
  750. } else if error.errorCode == NCGlobal.shared.errorResourceNotFound {
  751. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterFileExists, userInfo: ["ocId": self.ocId, "fileExists": false])
  752. }
  753. self.finish()
  754. }
  755. }
  756. }
  757. class NCOperationDeleteFileOrFolder: ConcurrentOperation, @unchecked Sendable {
  758. let database = NCManageDatabase.shared
  759. let global = NCGlobal.shared
  760. let utility = NCUtility()
  761. let utilityFileSystem = NCUtilityFileSystem()
  762. var metadata: tableMetadata
  763. var ocId: String
  764. init(metadata: tableMetadata) {
  765. self.metadata = metadata
  766. self.ocId = metadata.ocId
  767. }
  768. override func start() {
  769. guard !isCancelled else { return self.finish() }
  770. let options = NKRequestOptions(taskDescription: global.taskDescriptionDeleteFileOrFolder,
  771. queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  772. NextcloudKit.shared.deleteFileOrFolder(serverUrlFileName: self.metadata.serverUrl + "/" + self.metadata.fileName,
  773. account: self.metadata.account,
  774. options: options) { _, _, error in
  775. if error == .success || error.errorCode == NCGlobal.shared.errorResourceNotFound {
  776. do {
  777. try FileManager.default.removeItem(atPath: self.utilityFileSystem.getDirectoryProviderStorageOcId(self.metadata.ocId))
  778. } catch { }
  779. #if !EXTENSION
  780. NCImageCache.shared.removeImageCache(ocIdPlusEtag: self.metadata.ocId + self.metadata.etag)
  781. #endif
  782. self.database.deleteVideo(metadata: self.metadata)
  783. self.database.deleteMetadataOcId(self.metadata.ocId)
  784. self.database.deleteLocalFileOcId(self.metadata.ocId)
  785. if self.metadata.directory {
  786. self.database.deleteDirectoryAndSubDirectory(serverUrl: NCUtilityFileSystem().stringAppendServerUrl(self.metadata.serverUrl, addFileName: self.metadata.fileName), account: self.metadata.account)
  787. }
  788. } else {
  789. self.database.setMetadataStatus(ocId: self.ocId, status: self.global.metadataStatusNormal)
  790. }
  791. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDeleteFile, userInfo: ["ocId": [self.ocId], "error": error])
  792. self.finish()
  793. }
  794. }
  795. }