NCNetworking+WebDAV.swift 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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 JGProgressHUD
  25. import NextcloudKit
  26. import Alamofire
  27. import Queuer
  28. import Photos
  29. extension NCNetworking {
  30. // MARK: - Read file, folder
  31. func readFolder(serverUrl: String,
  32. account: String,
  33. forceReplaceMetadatas: Bool = false,
  34. completion: @escaping (_ account: String, _ metadataFolder: tableMetadata?, _ metadatas: [tableMetadata]?, _ metadatasChangedCount: Int, _ metadatasChanged: Bool, _ error: NKError) -> Void) {
  35. NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrl,
  36. depth: "1",
  37. showHiddenFiles: NCKeychain().showHiddenFiles,
  38. includeHiddenFiles: NCGlobal.shared.includeHiddenFiles,
  39. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, files, _, error in
  40. guard error == .success else {
  41. return completion(account, nil, nil, 0, false, error)
  42. }
  43. NCManageDatabase.shared.convertFilesToMetadatas(files, useMetadataFolder: true) { metadataFolder, metadatasFolder, metadatas in
  44. // Add metadata folder
  45. NCManageDatabase.shared.addMetadata(tableMetadata.init(value: metadataFolder))
  46. // Update directory
  47. 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)
  48. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, richWorkspace: metadataFolder.richWorkspace, account: metadataFolder.account)
  49. // Update sub directories NO Update richWorkspace
  50. for metadata in metadatasFolder {
  51. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  52. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: serverUrl, account: account)
  53. }
  54. #if !EXTENSION
  55. // Convert Live Photo
  56. for metadata in metadatas {
  57. if NCGlobal.shared.isLivePhotoServerAvailable, metadata.isLivePhoto {
  58. NCNetworking.shared.convertLivePhoto(metadata: metadata)
  59. }
  60. }
  61. #endif
  62. let predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, NCGlobal.shared.metadataStatusNormal)
  63. if forceReplaceMetadatas {
  64. NCManageDatabase.shared.replaceMetadata(metadatas, predicate: predicate)
  65. completion(account, metadataFolder, metadatas, 0, true, error)
  66. } else {
  67. let results = NCManageDatabase.shared.updateMetadatas(metadatas, predicate: predicate)
  68. completion(account, metadataFolder, metadatas, results.metadatasChangedCount, results.metadatasChanged, error)
  69. }
  70. }
  71. }
  72. }
  73. func readFile(serverUrlFileName: String,
  74. showHiddenFiles: Bool = NCKeychain().showHiddenFiles,
  75. queue: DispatchQueue = NextcloudKit.shared.nkCommonInstance.backgroundQueue,
  76. completion: @escaping (_ account: String, _ metadata: tableMetadata?, _ error: NKError) -> Void) {
  77. let options = NKRequestOptions(queue: queue)
  78. NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName, depth: "0", showHiddenFiles: showHiddenFiles, options: options) { account, files, _, error in
  79. guard error == .success, files.count == 1, let file = files.first else {
  80. completion(account, nil, error)
  81. return
  82. }
  83. let isDirectoryE2EE = self.utilityFileSystem.isDirectoryE2EE(file: file)
  84. let metadata = NCManageDatabase.shared.convertFileToMetadata(file, isDirectoryE2EE: isDirectoryE2EE)
  85. completion(account, metadata, error)
  86. }
  87. }
  88. func fileExists(serverUrlFileName: String,
  89. completion: @escaping (_ account: String, _ exists: Bool?, _ file: NKFile?, _ error: NKError) -> Void) {
  90. let requestBody =
  91. """
  92. <?xml version=\"1.0\" encoding=\"UTF-8\"?>
  93. <d:propfind xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\" xmlns:nc=\"http://nextcloud.org/ns\">
  94. <d:prop></d:prop>
  95. </d:propfind>
  96. """
  97. NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrlFileName,
  98. depth: "0",
  99. requestBody: requestBody.data(using: .utf8),
  100. options: NKRequestOptions(timeout: 10, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, files, _, error in
  101. if error == .success, let file = files.first {
  102. completion(account, true, file, error)
  103. } else if error.errorCode == NCGlobal.shared.errorResourceNotFound {
  104. completion(account, false, nil, error)
  105. } else {
  106. completion(account, nil, nil, error)
  107. }
  108. }
  109. }
  110. func fileExists(serverUrlFileName: String) async -> (account: String, exists: Bool?, file: NKFile?, error: NKError) {
  111. await withUnsafeContinuation({ continuation in
  112. fileExists(serverUrlFileName: serverUrlFileName) { account, exists, file, error in
  113. continuation.resume(returning: (account, exists, file, error))
  114. }
  115. })
  116. }
  117. func createFileName(fileNameBase: String, account: String, serverUrl: String) async -> String {
  118. var exitLoop = false
  119. var resultFileName = fileNameBase
  120. func newFileName() {
  121. var name = NSString(string: resultFileName).deletingPathExtension
  122. let ext = NSString(string: resultFileName).pathExtension
  123. let characters = Array(name)
  124. if characters.count < 2 {
  125. if ext.isEmpty {
  126. resultFileName = name + " 1"
  127. } else {
  128. resultFileName = name + " 1" + "." + ext
  129. }
  130. } else {
  131. let space = characters[characters.count - 2]
  132. let numChar = characters[characters.count - 1]
  133. var num = Int(String(numChar))
  134. if space == " " && num != nil {
  135. name = String(name.dropLast())
  136. num = num! + 1
  137. if ext.isEmpty {
  138. resultFileName = name + "\(num!)"
  139. } else {
  140. resultFileName = name + "\(num!)" + "." + ext
  141. }
  142. } else {
  143. if ext.isEmpty {
  144. resultFileName = name + " 1"
  145. } else {
  146. resultFileName = name + " 1" + "." + ext
  147. }
  148. }
  149. }
  150. }
  151. while !exitLoop {
  152. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "fileNameView == %@ AND serverUrl == %@ AND account == %@", resultFileName, serverUrl, account)) != nil {
  153. newFileName()
  154. continue
  155. }
  156. let results = await fileExists(serverUrlFileName: serverUrl + "/" + resultFileName)
  157. if let exists = results.exists, exists {
  158. newFileName()
  159. } else {
  160. exitLoop = true
  161. }
  162. }
  163. return resultFileName
  164. }
  165. // MARK: - Create Folder
  166. func createFolder(fileName: String,
  167. serverUrl: String,
  168. account: String,
  169. urlBase: String,
  170. userId: String,
  171. overwrite: Bool = false,
  172. withPush: Bool,
  173. completion: @escaping (_ error: NKError) -> Void) {
  174. let isDirectoryEncrypted = utilityFileSystem.isDirectoryE2EE(account: account, urlBase: urlBase, userId: userId, serverUrl: serverUrl)
  175. let fileName = fileName.trimmingCharacters(in: .whitespacesAndNewlines)
  176. if isDirectoryEncrypted {
  177. #if !EXTENSION
  178. Task {
  179. let error = await NCNetworkingE2EECreateFolder().createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, userId: userId, withPush: withPush)
  180. completion(error)
  181. }
  182. #endif
  183. } else {
  184. createFolderPlain(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, overwrite: overwrite, withPush: withPush, completion: completion)
  185. }
  186. }
  187. private func createFolderPlain(fileName: String,
  188. serverUrl: String,
  189. account: String,
  190. urlBase: String,
  191. overwrite: Bool,
  192. withPush: Bool,
  193. completion: @escaping (_ error: NKError) -> Void) {
  194. var fileNameFolder = utility.removeForbiddenCharacters(fileName)
  195. if fileName != fileNameFolder {
  196. let errorDescription = String(format: NSLocalizedString("_forbidden_characters_", comment: ""), NCGlobal.shared.forbiddenCharacters.joined(separator: " "))
  197. let error = NKError(errorCode: NCGlobal.shared.errorConflict, errorDescription: errorDescription)
  198. return completion(error)
  199. }
  200. if !overwrite {
  201. fileNameFolder = utilityFileSystem.createFileName(fileNameFolder, serverUrl: serverUrl, account: account)
  202. }
  203. if fileNameFolder.isEmpty {
  204. return completion(NKError())
  205. }
  206. let fileNameFolderUrl = serverUrl + "/" + fileNameFolder
  207. NextcloudKit.shared.createFolder(serverUrlFileName: fileNameFolderUrl) { account, _, _, error in
  208. guard error == .success else {
  209. if error.errorCode == NCGlobal.shared.errorMethodNotSupported && overwrite {
  210. completion(NKError())
  211. } else {
  212. completion(error)
  213. }
  214. return
  215. }
  216. self.readFile(serverUrlFileName: fileNameFolderUrl) { account, metadataFolder, error in
  217. if error == .success {
  218. if let metadata = metadataFolder {
  219. NCManageDatabase.shared.addMetadata(metadata)
  220. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: fileNameFolderUrl, account: account)
  221. }
  222. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(metadataFolder?.ocId) {
  223. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCreateFolder, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl, "account": metadata.account, "withPush": withPush])
  224. }
  225. }
  226. completion(error)
  227. }
  228. }
  229. }
  230. func createFolder(assets: [PHAsset],
  231. selector: String,
  232. useSubFolder: Bool,
  233. account: String,
  234. urlBase: String,
  235. userId: String,
  236. withPush: Bool) -> Bool {
  237. let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: urlBase, userId: userId, account: account)
  238. let serverUrlBase = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: urlBase, userId: userId, account: account)
  239. let fileNameBase = NCManageDatabase.shared.getAccountAutoUploadFileName()
  240. let autoUploadSubfolderGranularity = NCManageDatabase.shared.getAccountAutoUploadSubfolderGranularity()
  241. func createFolder(fileName: String, serverUrl: String) -> Bool {
  242. var result: Bool = false
  243. let semaphore = DispatchSemaphore(value: 0)
  244. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: account, urlBase: urlBase, userId: userId, overwrite: true, withPush: withPush) { error in
  245. if error == .success { result = true }
  246. semaphore.signal()
  247. }
  248. semaphore.wait()
  249. return result
  250. }
  251. func createNameSubFolder() -> [String] {
  252. var datesSubFolder: [String] = []
  253. let dateFormatter = DateFormatter()
  254. for asset in assets {
  255. let date = asset.creationDate ?? Date()
  256. dateFormatter.dateFormat = "yyyy"
  257. let year = dateFormatter.string(from: date)
  258. dateFormatter.dateFormat = "MM"
  259. let month = dateFormatter.string(from: date)
  260. dateFormatter.dateFormat = "dd"
  261. let day = dateFormatter.string(from: date)
  262. if autoUploadSubfolderGranularity == NCGlobal.shared.subfolderGranularityYearly {
  263. datesSubFolder.append("\(year)")
  264. } else if autoUploadSubfolderGranularity == NCGlobal.shared.subfolderGranularityDaily {
  265. datesSubFolder.append("\(year)/\(month)/\(day)")
  266. } else { // Month Granularity is default
  267. datesSubFolder.append("\(year)/\(month)")
  268. }
  269. }
  270. return Array(Set(datesSubFolder))
  271. }
  272. var result = createFolder(fileName: fileNameBase, serverUrl: serverUrlBase)
  273. if useSubFolder && result {
  274. for dateSubFolder in createNameSubFolder() {
  275. let subfolderArray = dateSubFolder.split(separator: "/")
  276. let year = subfolderArray[0]
  277. let serverUrlYear = autoUploadPath
  278. result = createFolder(fileName: String(year), serverUrl: serverUrlYear) // Year always present independently of preference value
  279. if result && autoUploadSubfolderGranularity >= NCGlobal.shared.subfolderGranularityMonthly {
  280. let month = subfolderArray[1]
  281. let serverUrlMonth = autoUploadPath + "/" + year
  282. result = createFolder(fileName: String(month), serverUrl: serverUrlMonth)
  283. if result && autoUploadSubfolderGranularity == NCGlobal.shared.subfolderGranularityDaily {
  284. let day = subfolderArray[2]
  285. let serverUrlDay = autoUploadPath + "/" + year + "/" + month
  286. result = createFolder(fileName: String(day), serverUrl: serverUrlDay)
  287. }
  288. }
  289. if !result { break }
  290. }
  291. }
  292. return result
  293. }
  294. // MARK: - Delete
  295. func deleteMetadata(_ metadata: tableMetadata, onlyLocalCache: Bool) async -> (NKError) {
  296. if onlyLocalCache {
  297. #if !EXTENSION
  298. NCActivityIndicator.shared.start()
  299. #endif
  300. func delete(metadata: tableMetadata) {
  301. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  302. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "account == %@ AND ocId == %@", metadataLive.account, metadataLive.ocId))
  303. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadataLive.ocId))
  304. }
  305. NCManageDatabase.shared.deleteVideo(metadata: metadata)
  306. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "account == %@ AND ocId == %@", metadata.account, metadata.ocId))
  307. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  308. }
  309. if metadata.directory {
  310. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  311. if let metadatas = NCManageDatabase.shared.getResultsMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND directory == false", metadata.account, serverUrl)) {
  312. for metadata in metadatas {
  313. delete(metadata: metadata)
  314. }
  315. }
  316. } else {
  317. delete(metadata: metadata)
  318. }
  319. #if !EXTENSION
  320. NCActivityIndicator.shared.stop()
  321. #endif
  322. return NKError()
  323. }
  324. if metadata.isDirectoryE2EE {
  325. #if !EXTENSION
  326. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  327. let error = await NCNetworkingE2EEDelete().delete(metadata: metadataLive)
  328. if error == .success {
  329. return await NCNetworkingE2EEDelete().delete(metadata: metadata)
  330. } else {
  331. return error
  332. }
  333. } else {
  334. return await NCNetworkingE2EEDelete().delete(metadata: metadata)
  335. }
  336. #else
  337. return NKError()
  338. #endif
  339. } else {
  340. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata), metadata.isNotFlaggedAsLivePhotoByServer {
  341. let error = await deleteMetadataPlain(metadataLive)
  342. if error == .success {
  343. return await deleteMetadataPlain(metadata)
  344. } else {
  345. return error
  346. }
  347. } else {
  348. return await deleteMetadataPlain(metadata)
  349. }
  350. }
  351. }
  352. func deleteMetadataPlain(_ metadata: tableMetadata, customHeader: [String: String]? = nil) async -> NKError {
  353. // verify permission
  354. let permission = utility.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanDelete)
  355. if !metadata.permissions.isEmpty && permission == false {
  356. return NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_delete_file_")
  357. }
  358. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  359. let options = NKRequestOptions(customHeader: customHeader)
  360. let result = await NextcloudKit.shared.deleteFileOrFolder(serverUrlFileName: serverUrlFileName, options: options)
  361. if result.error == .success || result.error.errorCode == NCGlobal.shared.errorResourceNotFound {
  362. do {
  363. try FileManager.default.removeItem(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  364. } catch { }
  365. NCManageDatabase.shared.deleteVideo(metadata: metadata)
  366. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  367. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  368. // LIVE PHOTO SERVER
  369. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata), metadataLive.isFlaggedAsLivePhotoByServer {
  370. do {
  371. try FileManager.default.removeItem(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadataLive.ocId))
  372. } catch { }
  373. NCManageDatabase.shared.deleteVideo(metadata: metadataLive)
  374. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadataLive.ocId))
  375. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadataLive.ocId))
  376. }
  377. if metadata.directory {
  378. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: utilityFileSystem.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: metadata.account)
  379. }
  380. }
  381. return result.error
  382. }
  383. // MARK: - Rename
  384. func renameMetadata(_ metadata: tableMetadata,
  385. fileNameNew: String,
  386. indexPath: IndexPath,
  387. viewController: UIViewController?,
  388. completion: @escaping (_ error: NKError) -> Void) {
  389. let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  390. let fileNameNew = fileNameNew.trimmingCharacters(in: .whitespacesAndNewlines)
  391. let fileNameNewLive = (fileNameNew as NSString).deletingPathExtension + ".mov"
  392. if metadata.isDirectoryE2EE {
  393. #if !EXTENSION
  394. Task {
  395. if let metadataLive = metadataLive {
  396. let error = await NCNetworkingE2EERename().rename(metadata: metadataLive, fileNameNew: fileNameNew, indexPath: indexPath)
  397. if error == .success {
  398. let error = await NCNetworkingE2EERename().rename(metadata: metadata, fileNameNew: fileNameNew, indexPath: indexPath)
  399. DispatchQueue.main.async { completion(error) }
  400. } else {
  401. DispatchQueue.main.async { completion(error) }
  402. }
  403. } else {
  404. let error = await NCNetworkingE2EERename().rename(metadata: metadata, fileNameNew: fileNameNew, indexPath: indexPath)
  405. DispatchQueue.main.async { completion(error) }
  406. }
  407. }
  408. #endif
  409. } else {
  410. if let metadataLive, metadata.isNotFlaggedAsLivePhotoByServer {
  411. renameMetadataPlain(metadataLive, fileNameNew: fileNameNewLive, indexPath: indexPath) { error in
  412. if error == .success {
  413. self.renameMetadataPlain(metadata, fileNameNew: fileNameNew, indexPath: indexPath, completion: completion)
  414. } else {
  415. completion(error)
  416. }
  417. }
  418. } else {
  419. renameMetadataPlain(metadata, fileNameNew: fileNameNew, indexPath: indexPath, completion: completion)
  420. }
  421. }
  422. }
  423. private func renameMetadataPlain(_ metadata: tableMetadata,
  424. fileNameNew: String,
  425. indexPath: IndexPath,
  426. completion: @escaping (_ error: NKError) -> Void) {
  427. let permission = utility.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  428. if !metadata.permissions.isEmpty && !permission {
  429. return completion(NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_modify_file_"))
  430. }
  431. let fileName = utility.removeForbiddenCharacters(fileNameNew)
  432. if fileName != fileNameNew {
  433. let errorDescription = String(format: NSLocalizedString("_forbidden_characters_", comment: ""), NCGlobal.shared.forbiddenCharacters.joined(separator: " "))
  434. let error = NKError(errorCode: NCGlobal.shared.errorConflict, errorDescription: errorDescription)
  435. return completion(error)
  436. }
  437. let fileNameNew = fileName
  438. if fileNameNew.isEmpty || fileNameNew == metadata.fileNameView {
  439. return completion(NKError())
  440. }
  441. let fileNamePath = metadata.serverUrl + "/" + metadata.fileName
  442. let fileNameToPath = metadata.serverUrl + "/" + fileNameNew
  443. NextcloudKit.shared.moveFileOrFolder(serverUrlFileNameSource: fileNamePath, serverUrlFileNameDestination: fileNameToPath, overwrite: false) { _, error in
  444. if error == .success {
  445. NCManageDatabase.shared.renameMetadata(fileNameTo: fileNameNew, ocId: metadata.ocId)
  446. if metadata.directory {
  447. let serverUrl = self.utilityFileSystem.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)
  448. let serverUrlTo = self.utilityFileSystem.stringAppendServerUrl(metadata.serverUrl, addFileName: fileNameNew)
  449. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  450. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, serverUrlTo: serverUrlTo, etag: "", ocId: nil, fileId: nil, encrypted: directory.e2eEncrypted, richWorkspace: nil, account: metadata.account)
  451. }
  452. } else {
  453. if (metadata.fileName as NSString).pathExtension != (fileNameNew as NSString).pathExtension {
  454. let path = self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId)
  455. self.utilityFileSystem.removeFile(atPath: path)
  456. } else {
  457. NCManageDatabase.shared.setLocalFile(ocId: metadata.ocId, fileName: fileNameNew)
  458. let atPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileName
  459. let toPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + fileNameNew
  460. self.utilityFileSystem.moveFile(atPath: atPath, toPath: toPath)
  461. }
  462. }
  463. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRenameFile, userInfo: ["ocId": metadata.ocId, "account": metadata.account, "indexPath": indexPath])
  464. }
  465. completion(error)
  466. }
  467. }
  468. // MARK: - Move
  469. func moveMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool) async -> NKError {
  470. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata), metadata.isNotFlaggedAsLivePhotoByServer {
  471. let error = await moveMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite)
  472. if error == .success {
  473. return await moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite)
  474. } else {
  475. return error
  476. }
  477. }
  478. return await moveMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite)
  479. }
  480. private func moveMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool) async -> NKError {
  481. let permission = utility.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  482. if !metadata.permissions.isEmpty && !permission {
  483. return NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_modify_file_")
  484. }
  485. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  486. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  487. let result = await NextcloudKit.shared.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite)
  488. if result.error == .success {
  489. if metadata.directory {
  490. NCManageDatabase.shared.deleteDirectoryAndSubDirectory(serverUrl: utilityFileSystem.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: result.account)
  491. } else {
  492. do {
  493. try FileManager.default.removeItem(atPath: self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  494. } catch { }
  495. NCManageDatabase.shared.deleteVideo(metadata: metadata)
  496. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  497. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  498. // LIVE PHOTO SERVER
  499. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata), metadataLive.isFlaggedAsLivePhotoByServer {
  500. do {
  501. try FileManager.default.removeItem(atPath: self.utilityFileSystem.getDirectoryProviderStorageOcId(metadataLive.ocId))
  502. } catch { }
  503. NCManageDatabase.shared.deleteVideo(metadata: metadataLive)
  504. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadataLive.ocId))
  505. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadataLive.ocId))
  506. }
  507. }
  508. }
  509. return result.error
  510. }
  511. // MARK: - Copy
  512. func copyMetadata(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool) async -> NKError {
  513. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata), metadata.isNotFlaggedAsLivePhotoByServer {
  514. let error = await copyMetadataPlain(metadataLive, serverUrlTo: serverUrlTo, overwrite: overwrite)
  515. if error == .success {
  516. return await copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite)
  517. } else {
  518. return error
  519. }
  520. }
  521. return await copyMetadataPlain(metadata, serverUrlTo: serverUrlTo, overwrite: overwrite)
  522. }
  523. private func copyMetadataPlain(_ metadata: tableMetadata, serverUrlTo: String, overwrite: Bool) async -> NKError {
  524. let permission = utility.permissionsContainsString(metadata.permissions, permissions: NCGlobal.shared.permissionCanRename)
  525. if !metadata.permissions.isEmpty && !permission {
  526. return NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_permission_modify_file_")
  527. }
  528. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  529. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  530. let result = await NextcloudKit.shared.copyFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite)
  531. return result.error
  532. }
  533. // MARK: - Favorite
  534. func favoriteMetadata(_ metadata: tableMetadata,
  535. completion: @escaping (_ error: NKError) -> Void) {
  536. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  537. favoriteMetadataPlain(metadataLive) { error in
  538. if error == .success {
  539. self.favoriteMetadataPlain(metadata, completion: completion)
  540. } else {
  541. completion(error)
  542. }
  543. }
  544. } else {
  545. favoriteMetadataPlain(metadata, completion: completion)
  546. }
  547. }
  548. private func favoriteMetadataPlain(_ metadata: tableMetadata,
  549. completion: @escaping (_ error: NKError) -> Void) {
  550. let fileName = utilityFileSystem.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId)
  551. let favorite = !metadata.favorite
  552. let ocId = metadata.ocId
  553. NextcloudKit.shared.setFavorite(fileName: fileName, favorite: favorite) { account, error in
  554. if error == .success && metadata.account == account {
  555. metadata.favorite = favorite
  556. NCManageDatabase.shared.addMetadata(metadata)
  557. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterFavoriteFile, userInfo: ["ocId": ocId, "serverUrl": metadata.serverUrl])
  558. }
  559. completion(error)
  560. }
  561. }
  562. // MARK: - Lock Files
  563. func lockUnlockFile(_ metadata: tableMetadata, shoulLock: Bool) {
  564. NextcloudKit.shared.lockUnlockFile(serverUrlFileName: metadata.serverUrl + "/" + metadata.fileName, shouldLock: shoulLock) { _, error in
  565. // 0: lock was successful; 412: lock did not change, no error, refresh
  566. guard error == .success || error.errorCode == NCGlobal.shared.errorPreconditionFailed else {
  567. let error = NKError(errorCode: error.errorCode, errorDescription: "_files_lock_error_")
  568. NCContentPresenter().messageNotification(metadata.fileName, error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  569. return
  570. }
  571. NCNetworking.shared.readFile(serverUrlFileName: metadata.serverUrl + "/" + metadata.fileName) { _, metadata, error in
  572. guard error == .success, let metadata = metadata else { return }
  573. NCManageDatabase.shared.addMetadata(metadata)
  574. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource)
  575. }
  576. }
  577. }
  578. // MARK: - Direct Download
  579. func getVideoUrl(metadata: tableMetadata,
  580. completition: @escaping (_ url: URL?, _ autoplay: Bool, _ error: NKError) -> Void) {
  581. if !metadata.url.isEmpty {
  582. if metadata.url.hasPrefix("/") {
  583. completition(URL(fileURLWithPath: metadata.url), true, .success)
  584. } else {
  585. completition(URL(string: metadata.url), true, .success)
  586. }
  587. } else if utilityFileSystem.fileProviderStorageExists(metadata) {
  588. completition(URL(fileURLWithPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)), false, .success)
  589. } else {
  590. NextcloudKit.shared.getDirectDownload(fileId: metadata.fileId) { _, url, _, error in
  591. if error == .success && url != nil {
  592. if let url = URL(string: url!) {
  593. completition(url, false, error)
  594. } else {
  595. completition(nil, false, error)
  596. }
  597. } else {
  598. completition(nil, false, error)
  599. }
  600. }
  601. }
  602. }
  603. // MARK: - Get Preview
  604. func getPreview(url: URL,
  605. options: NKRequestOptions = NKRequestOptions()) async -> (account: String, data: Data?, error: NKError) {
  606. await withUnsafeContinuation({ continuation in
  607. NextcloudKit.shared.getPreview(url: url, options: options) { account, data, error in
  608. continuation.resume(returning: (account: account, data: data, error: error))
  609. }
  610. })
  611. }
  612. // MARK: - Download Preview
  613. func downloadPreview(fileNamePathOrFileId: String,
  614. fileNamePreviewLocalPath: String,
  615. widthPreview: Int,
  616. heightPreview: Int,
  617. fileNameIconLocalPath: String? = nil,
  618. sizeIcon: Int = 0,
  619. etag: String? = nil,
  620. endpointTrashbin: Bool = false,
  621. useInternalEndpoint: Bool = true,
  622. options: NKRequestOptions = NKRequestOptions()) async -> (account: String, imagePreview: UIImage?, imageIcon: UIImage?, imageOriginal: UIImage?, etag: String?, error: NKError) {
  623. await withUnsafeContinuation({ continuation in
  624. NextcloudKit.shared.downloadPreview(fileNamePathOrFileId: fileNamePathOrFileId, fileNamePreviewLocalPath: fileNamePreviewLocalPath, widthPreview: widthPreview, heightPreview: heightPreview, fileNameIconLocalPath: fileNameIconLocalPath, sizeIcon: sizeIcon, etag: etag, options: options) { account, imagePreview, imageIcon, imageOriginal, etag, error in
  625. continuation.resume(returning: (account: account, imagePreview: imagePreview, imageIcon: imageIcon, imageOriginal: imageOriginal, etag: etag, error: error))
  626. }
  627. })
  628. }
  629. // MARK: - Search
  630. /// WebDAV search
  631. func searchFiles(urlBase: NCUserBaseUrl,
  632. literal: String,
  633. completion: @escaping (_ metadatas: [tableMetadata]?, _ error: NKError) -> Void) {
  634. NextcloudKit.shared.searchLiteral(serverUrl: urlBase.urlBase,
  635. depth: "infinity",
  636. literal: literal,
  637. showHiddenFiles: NCKeychain().showHiddenFiles,
  638. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, files, _, error in
  639. guard error == .success else {
  640. return completion(nil, error)
  641. }
  642. NCManageDatabase.shared.convertFilesToMetadatas(files, useMetadataFolder: false) { _, metadatasFolder, metadatas in
  643. // Update sub directories
  644. for folder in metadatasFolder {
  645. let serverUrl = folder.serverUrl + "/" + folder.fileName
  646. NCManageDatabase.shared.addDirectory(encrypted: folder.e2eEncrypted, favorite: folder.favorite, ocId: folder.ocId, fileId: folder.fileId, etag: nil, permissions: folder.permissions, serverUrl: serverUrl, account: account)
  647. }
  648. NCManageDatabase.shared.addMetadatas(metadatas)
  649. let metadatas = Array(metadatas.map(tableMetadata.init))
  650. completion(metadatas, error)
  651. }
  652. }
  653. }
  654. /// Unified Search (NC>=20)
  655. ///
  656. func unifiedSearchFiles(userBaseUrl: NCUserBaseUrl,
  657. literal: String,
  658. providers: @escaping (_ accout: String, _ searchProviders: [NKSearchProvider]?) -> Void,
  659. update: @escaping (_ account: String, _ id: String, NKSearchResult?, [tableMetadata]?) -> Void,
  660. completion: @escaping (_ account: String, _ error: NKError) -> Void) {
  661. let dispatchGroup = DispatchGroup()
  662. dispatchGroup.enter()
  663. dispatchGroup.notify(queue: .main) {
  664. completion(userBaseUrl.account, NKError())
  665. }
  666. NextcloudKit.shared.unifiedSearch(term: literal, timeout: 30, timeoutProvider: 90) { _ in
  667. // example filter
  668. // ["calendar", "files", "fulltextsearch"].contains(provider.id)
  669. return true
  670. } request: { request in
  671. if let request = request {
  672. self.requestsUnifiedSearch.append(request)
  673. }
  674. } providers: { account, searchProviders in
  675. providers(account, searchProviders)
  676. } update: { account, partialResult, provider, _ in
  677. guard let partialResult = partialResult else { return }
  678. var metadatas: [tableMetadata] = []
  679. switch provider.id {
  680. case "files":
  681. partialResult.entries.forEach({ entry in
  682. if let fileId = entry.fileId,
  683. let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ && fileId == %@", userBaseUrl.userAccount, String(fileId))) {
  684. metadatas.append(metadata)
  685. } else if let filePath = entry.filePath {
  686. let semaphore = DispatchSemaphore(value: 0)
  687. self.loadMetadata(userBaseUrl: userBaseUrl, filePath: filePath, dispatchGroup: dispatchGroup) { _, metadata, _ in
  688. metadatas.append(metadata)
  689. semaphore.signal()
  690. }
  691. semaphore.wait()
  692. } else { print(#function, "[ERROR]: File search entry has no path: \(entry)") }
  693. })
  694. case "fulltextsearch":
  695. // NOTE: FTS could also return attributes like files
  696. // https://github.com/nextcloud/files_fulltextsearch/issues/143
  697. partialResult.entries.forEach({ entry in
  698. let url = URLComponents(string: entry.resourceURL)
  699. guard let dir = url?.queryItems?["dir"]?.value, let filename = url?.queryItems?["scrollto"]?.value else { return }
  700. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(
  701. format: "account == %@ && path == %@ && fileName == %@",
  702. userBaseUrl.userAccount,
  703. "/remote.php/dav/files/" + userBaseUrl.user + dir,
  704. filename)) {
  705. metadatas.append(metadata)
  706. } else {
  707. let semaphore = DispatchSemaphore(value: 0)
  708. self.loadMetadata(userBaseUrl: userBaseUrl, filePath: dir + filename, dispatchGroup: dispatchGroup) { _, metadata, _ in
  709. metadatas.append(metadata)
  710. semaphore.signal()
  711. }
  712. semaphore.wait()
  713. }
  714. })
  715. default:
  716. partialResult.entries.forEach({ entry in
  717. 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)
  718. metadatas.append(metadata)
  719. })
  720. }
  721. update(account, provider.id, partialResult, metadatas)
  722. } completion: { _, _, _ in
  723. self.requestsUnifiedSearch.removeAll()
  724. dispatchGroup.leave()
  725. }
  726. }
  727. func unifiedSearchFilesProvider(userBaseUrl: NCUserBaseUrl,
  728. id: String, term: String,
  729. limit: Int, cursor: Int,
  730. completion: @escaping (_ account: String, _ searchResult: NKSearchResult?, _ metadatas: [tableMetadata]?, _ error: NKError) -> Void) {
  731. var metadatas: [tableMetadata] = []
  732. let request = NextcloudKit.shared.searchProvider(id, account: userBaseUrl.account, term: term, limit: limit, cursor: cursor, timeout: 60) { account, searchResult, _, error in
  733. guard let searchResult = searchResult else {
  734. completion(account, nil, metadatas, error)
  735. return
  736. }
  737. switch id {
  738. case "files":
  739. searchResult.entries.forEach({ entry in
  740. if let fileId = entry.fileId, let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ && fileId == %@", userBaseUrl.userAccount, String(fileId))) {
  741. metadatas.append(metadata)
  742. } else if let filePath = entry.filePath {
  743. let semaphore = DispatchSemaphore(value: 0)
  744. self.loadMetadata(userBaseUrl: userBaseUrl, filePath: filePath, dispatchGroup: nil) { _, metadata, _ in
  745. metadatas.append(metadata)
  746. semaphore.signal()
  747. }
  748. semaphore.wait()
  749. } else { print(#function, "[ERROR]: File search entry has no path: \(entry)") }
  750. })
  751. case "fulltextsearch":
  752. // NOTE: FTS could also return attributes like files
  753. // https://github.com/nextcloud/files_fulltextsearch/issues/143
  754. searchResult.entries.forEach({ entry in
  755. let url = URLComponents(string: entry.resourceURL)
  756. guard let dir = url?.queryItems?["dir"]?.value, let filename = url?.queryItems?["scrollto"]?.value else { return }
  757. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ && path == %@ && fileName == %@", userBaseUrl.userAccount, "/remote.php/dav/files/" + userBaseUrl.user + dir, filename)) {
  758. metadatas.append(metadata)
  759. } else {
  760. let semaphore = DispatchSemaphore(value: 0)
  761. self.loadMetadata(userBaseUrl: userBaseUrl, filePath: dir + filename, dispatchGroup: nil) { _, metadata, _ in
  762. metadatas.append(metadata)
  763. semaphore.signal()
  764. }
  765. semaphore.wait()
  766. }
  767. })
  768. default:
  769. searchResult.entries.forEach({ entry in
  770. 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)
  771. metadatas.append(newMetadata)
  772. })
  773. }
  774. completion(account, searchResult, metadatas, error)
  775. }
  776. if let request = request {
  777. requestsUnifiedSearch.append(request)
  778. }
  779. }
  780. func cancelUnifiedSearchFiles() {
  781. for request in requestsUnifiedSearch {
  782. request.cancel()
  783. }
  784. requestsUnifiedSearch.removeAll()
  785. }
  786. private func loadMetadata(userBaseUrl: NCUserBaseUrl,
  787. filePath: String,
  788. dispatchGroup: DispatchGroup? = nil,
  789. completion: @escaping (String, tableMetadata, NKError) -> Void) {
  790. let urlPath = userBaseUrl.urlBase + "/remote.php/dav/files/" + userBaseUrl.user + filePath
  791. dispatchGroup?.enter()
  792. self.readFile(serverUrlFileName: urlPath) { account, metadata, error in
  793. defer { dispatchGroup?.leave() }
  794. guard let metadata = metadata else { return }
  795. let returnMetadata = tableMetadata.init(value: metadata)
  796. NCManageDatabase.shared.addMetadata(metadata)
  797. completion(account, returnMetadata, error)
  798. }
  799. }
  800. func cancelDataTask() {
  801. let sessionManager = NextcloudKit.shared.sessionManager
  802. sessionManager.session.getTasksWithCompletionHandler { dataTasks, _, _ in
  803. dataTasks.forEach {
  804. $0.cancel()
  805. }
  806. }
  807. }
  808. }
  809. class NCOperationDownloadAvatar: ConcurrentOperation {
  810. var user: String
  811. var fileName: String
  812. var etag: String?
  813. var fileNameLocalPath: String
  814. var cell: NCCellProtocol!
  815. var view: UIView?
  816. var cellImageView: UIImageView?
  817. init(user: String, fileName: String, fileNameLocalPath: String, cell: NCCellProtocol, view: UIView?, cellImageView: UIImageView?) {
  818. self.user = user
  819. self.fileName = fileName
  820. self.fileNameLocalPath = fileNameLocalPath
  821. self.cell = cell
  822. self.view = view
  823. self.etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  824. self.cellImageView = cellImageView
  825. }
  826. override func start() {
  827. guard !isCancelled else { return self.finish() }
  828. NextcloudKit.shared.downloadAvatar(user: user,
  829. fileNameLocalPath: fileNameLocalPath,
  830. sizeImage: NCGlobal.shared.avatarSize,
  831. avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
  832. etag: self.etag,
  833. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imageAvatar, _, etag, error in
  834. if error == .success, let imageAvatar = imageAvatar, let etag = etag {
  835. NCManageDatabase.shared.addAvatar(fileName: self.fileName, etag: etag)
  836. DispatchQueue.main.async {
  837. if self.user == self.cell.fileUser, let avatarImageView = self.cellImageView {
  838. UIView.transition(with: avatarImageView,
  839. duration: 0.75,
  840. options: .transitionCrossDissolve,
  841. animations: { avatarImageView.image = imageAvatar },
  842. completion: nil)
  843. } else {
  844. if self.view is UICollectionView {
  845. (self.view as? UICollectionView)?.reloadData()
  846. } else if self.view is UITableView {
  847. (self.view as? UITableView)?.reloadData()
  848. }
  849. }
  850. }
  851. } else if error.errorCode == NCGlobal.shared.errorNotModified {
  852. NCManageDatabase.shared.setAvatarLoaded(fileName: self.fileName)
  853. }
  854. self.finish()
  855. }
  856. }
  857. }