NCUtilityFileSystem.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. //
  2. // NCUtilityFileSystem.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 28/05/2020.
  6. // Copyright © 2020 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 PhotosUI
  26. class NCUtilityFileSystem: NSObject {
  27. let fileManager = FileManager.default
  28. // MARK: -
  29. var directoryGroup: String {
  30. return fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups)?.path ?? ""
  31. }
  32. var directoryDocuments: String {
  33. return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? ""
  34. }
  35. var directoryCertificates: String {
  36. guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups) else { return "" }
  37. let path = directoryGroup.appendingPathComponent(NCGlobal.shared.appCertificates).path
  38. if !fileManager.fileExists(atPath: path) {
  39. do {
  40. try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true)
  41. } catch { print("Error: \(error)") }
  42. }
  43. return path
  44. }
  45. var directoryUserData: String {
  46. guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups) else { return "" }
  47. let path = directoryGroup.appendingPathComponent(NCGlobal.shared.appUserData).path
  48. if !fileManager.fileExists(atPath: path) {
  49. do {
  50. try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true)
  51. } catch { print("Error: \(error)") }
  52. }
  53. return path
  54. }
  55. var directoryScan: String {
  56. guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups) else { return "" }
  57. let path = directoryGroup.appendingPathComponent(NCGlobal.shared.appScan).path
  58. if !fileManager.fileExists(atPath: path) {
  59. do {
  60. try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true)
  61. } catch { print("Error: \(error)") }
  62. }
  63. return path
  64. }
  65. @objc var directoryProviderStorage: String {
  66. guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups) else { return "" }
  67. let path = directoryGroup.appendingPathComponent(NCGlobal.shared.directoryProviderStorage).path
  68. if !fileManager.fileExists(atPath: path) {
  69. do {
  70. try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true)
  71. } catch { print("Error: \(error)") }
  72. }
  73. return path
  74. }
  75. @objc func getDirectoryProviderStorageOcId(_ ocId: String) -> String {
  76. let path = directoryProviderStorage + "/" + ocId
  77. if !fileManager.fileExists(atPath: path) {
  78. do {
  79. try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true)
  80. } catch { print("Error: \(error)") }
  81. }
  82. return path
  83. }
  84. @objc func getDirectoryProviderStorageOcId(_ ocId: String, fileNameView: String) -> String {
  85. let path = getDirectoryProviderStorageOcId(ocId) + "/" + fileNameView
  86. if !fileManager.fileExists(atPath: path) {
  87. fileManager.createFile(atPath: path, contents: nil)
  88. }
  89. return path
  90. }
  91. func getDirectoryProviderStorageIconOcId(_ ocId: String, etag: String) -> String {
  92. return getDirectoryProviderStorageOcId(ocId) + "/" + etag + ".small.ico"
  93. }
  94. func getDirectoryProviderStoragePreviewOcId(_ ocId: String, etag: String) -> String {
  95. return getDirectoryProviderStorageOcId(ocId) + "/" + etag + ".preview.ico"
  96. }
  97. func fileProviderStorageExists(_ metadata: tableMetadata) -> Bool {
  98. let fileNamePath = getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)
  99. let fileNameViewPath = getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  100. do {
  101. let fileNameAttribute = try fileManager.attributesOfItem(atPath: fileNamePath)
  102. let fileNameSize: UInt64 = fileNameAttribute[FileAttributeKey.size] as? UInt64 ?? 0
  103. let fileNameViewAttribute = try fileManager.attributesOfItem(atPath: fileNameViewPath)
  104. let fileNameViewSize: UInt64 = fileNameViewAttribute[FileAttributeKey.size] as? UInt64 ?? 0
  105. if metadata.isDirectoryE2EE == true {
  106. if (fileNameSize == metadata.size || fileNameViewSize == metadata.size) && fileNameViewSize > 0 {
  107. return true
  108. } else {
  109. return false
  110. }
  111. } else {
  112. return (fileNameViewSize == metadata.size) && metadata.size > 0
  113. }
  114. } catch { print("Error: \(error)") }
  115. return false
  116. }
  117. func fileProviderStorageSize(_ ocId: String, fileNameView: String) -> UInt64 {
  118. let fileNamePath = getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)
  119. do {
  120. let fileNameAttribute = try fileManager.attributesOfItem(atPath: fileNamePath)
  121. let fileNameSize: UInt64 = fileNameAttribute[FileAttributeKey.size] as? UInt64 ?? 0
  122. return fileNameSize
  123. } catch { print("Error: \(error)") }
  124. return 0
  125. }
  126. func fileProviderStoragePreviewIconExists(_ ocId: String, etag: String) -> Bool {
  127. let fileNamePathPreview = getDirectoryProviderStoragePreviewOcId(ocId, etag: etag)
  128. let fileNamePathIcon = getDirectoryProviderStorageIconOcId(ocId, etag: etag)
  129. do {
  130. let fileNamePathPreviewAttribute = try fileManager.attributesOfItem(atPath: fileNamePathPreview)
  131. let fileSizePreview: UInt64 = fileNamePathPreviewAttribute[FileAttributeKey.size] as? UInt64 ?? 0
  132. let fileNamePathIconAttribute = try fileManager.attributesOfItem(atPath: fileNamePathIcon)
  133. let fileSizeIcon: UInt64 = fileNamePathIconAttribute[FileAttributeKey.size] as? UInt64 ?? 0
  134. if fileSizePreview > 0 && fileSizeIcon > 0 {
  135. return true
  136. } else {
  137. return false
  138. }
  139. } catch { print("Error: \(error)") }
  140. return false
  141. }
  142. @objc func createDirectoryStandard() {
  143. guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups)?.path else { return }
  144. if !fileManager.fileExists(atPath: directoryDocuments) { try? fileManager.createDirectory(atPath: directoryDocuments, withIntermediateDirectories: true) }
  145. let appDatabaseNextcloud = directoryGroup + "/" + NCGlobal.shared.appDatabaseNextcloud
  146. if !fileManager.fileExists(atPath: appDatabaseNextcloud) { try? fileManager.createDirectory(atPath: appDatabaseNextcloud, withIntermediateDirectories: true) }
  147. if !fileManager.fileExists(atPath: directoryUserData) { try? fileManager.createDirectory(atPath: directoryUserData, withIntermediateDirectories: true) }
  148. if !fileManager.fileExists(atPath: directoryProviderStorage) { try? fileManager.createDirectory(atPath: directoryProviderStorage, withIntermediateDirectories: true) }
  149. let appScan = directoryGroup + "/" + NCGlobal.shared.appScan
  150. if !fileManager.fileExists(atPath: appScan) { try? fileManager.createDirectory(atPath: appScan, withIntermediateDirectories: true) }
  151. if !fileManager.fileExists(atPath: NSTemporaryDirectory()) { try? fileManager.createDirectory(atPath: NSTemporaryDirectory(), withIntermediateDirectories: true) }
  152. // Directory Excluded From Backup
  153. if let url = NSURL(string: directoryDocuments) {
  154. try? url.setResourceValue(true, forKey: URLResourceKey.isExcludedFromBackupKey)
  155. }
  156. if let url = NSURL(string: directoryGroup) {
  157. try? url.setResourceValue(true, forKey: URLResourceKey.isExcludedFromBackupKey)
  158. }
  159. }
  160. @objc func removeGroupApplicationSupport() {
  161. let path = directoryGroup + "/" + NCGlobal.shared.appApplicationSupport
  162. try? fileManager.removeItem(atPath: path)
  163. }
  164. @objc func removeGroupLibraryDirectory() {
  165. try? fileManager.removeItem(atPath: directoryScan)
  166. try? fileManager.removeItem(atPath: directoryUserData)
  167. }
  168. @objc func removeGroupDirectoryProviderStorage() {
  169. try? fileManager.removeItem(atPath: directoryProviderStorage)
  170. }
  171. @objc func removeDocumentsDirectory() {
  172. try? fileManager.removeItem(atPath: directoryDocuments)
  173. }
  174. @objc func removeTemporaryDirectory() {
  175. try? fileManager.removeItem(atPath: NSTemporaryDirectory())
  176. }
  177. @objc func emptyTemporaryDirectory() {
  178. do {
  179. let files = try fileManager.contentsOfDirectory(atPath: NSTemporaryDirectory())
  180. for file in files {
  181. do {
  182. try fileManager.removeItem(atPath: NSTemporaryDirectory() + "/" + file)
  183. } catch { print("Error: \(error)") }
  184. }
  185. } catch { print("Error: \(error)") }
  186. }
  187. func isDirectoryE2EE(serverUrl: String, userBase: NCUserBaseUrl) -> Bool {
  188. return isDirectoryE2EE(account: userBase.account, urlBase: userBase.urlBase, userId: userBase.userId, serverUrl: serverUrl)
  189. }
  190. func isDirectoryE2EE(file: NKFile) -> Bool {
  191. return isDirectoryE2EE(account: file.account, urlBase: file.urlBase, userId: file.userId, serverUrl: file.serverUrl)
  192. }
  193. func isDirectoryE2EE(account: String, urlBase: String, userId: String, serverUrl: String) -> Bool {
  194. if serverUrl == getHomeServer(urlBase: urlBase, userId: userId) || serverUrl == ".." { return false }
  195. if let directory = NCManageDatabase.shared.getTableDirectory(account: account, serverUrl: serverUrl) {
  196. return directory.e2eEncrypted
  197. }
  198. return false
  199. }
  200. func isDirectoryE2EETop(account: String, serverUrl: String) -> Bool {
  201. guard let serverUrl = serverUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return false }
  202. if let url = URL(string: serverUrl)?.deletingLastPathComponent(),
  203. let serverUrl = String(url.absoluteString.dropLast()).removingPercentEncoding {
  204. if let directory = NCManageDatabase.shared.getTableDirectory(account: account, serverUrl: serverUrl) {
  205. return !directory.e2eEncrypted
  206. }
  207. }
  208. return true
  209. }
  210. func getDirectoryE2EETop(serverUrl: String, account: String) -> tableDirectory? {
  211. guard var serverUrl = serverUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return nil }
  212. var top: tableDirectory?
  213. while let url = URL(string: serverUrl)?.deletingLastPathComponent(),
  214. let serverUrlencoding = serverUrl.removingPercentEncoding,
  215. let directory = NCManageDatabase.shared.getTableDirectory(account: account, serverUrl: serverUrlencoding) {
  216. if directory.e2eEncrypted {
  217. top = directory
  218. } else {
  219. return top
  220. }
  221. serverUrl = String(url.absoluteString.dropLast())
  222. }
  223. return top
  224. }
  225. // MARK: -
  226. @objc func getFileSize(filePath: String) -> Int64 {
  227. do {
  228. let attributes = try fileManager.attributesOfItem(atPath: filePath)
  229. return attributes[FileAttributeKey.size] as? Int64 ?? 0
  230. } catch {
  231. print(error)
  232. }
  233. return 0
  234. }
  235. @objc func getFileModificationDate(filePath: String) -> NSDate? {
  236. do {
  237. let attributes = try fileManager.attributesOfItem(atPath: filePath)
  238. return attributes[FileAttributeKey.modificationDate] as? NSDate
  239. } catch {
  240. print(error)
  241. }
  242. return nil
  243. }
  244. @objc func getFileCreationDate(filePath: String) -> NSDate? {
  245. do {
  246. let attributes = try fileManager.attributesOfItem(atPath: filePath)
  247. return attributes[FileAttributeKey.creationDate] as? NSDate
  248. } catch {
  249. print(error)
  250. }
  251. return nil
  252. }
  253. @objc func writeFile(fileURL: URL, text: String) -> Bool {
  254. do {
  255. try FileManager.default.removeItem(at: fileURL)
  256. } catch {
  257. print(error)
  258. }
  259. do {
  260. try text.write(to: fileURL, atomically: true, encoding: .utf8)
  261. return true
  262. } catch {
  263. print(error)
  264. return false
  265. }
  266. }
  267. @objc func removeFile(atPath: String) {
  268. do {
  269. try FileManager.default.removeItem(atPath: atPath)
  270. } catch {
  271. print(error)
  272. }
  273. }
  274. @discardableResult
  275. @objc func moveFile(atPath: String, toPath: String) -> Bool {
  276. if atPath == toPath { return true }
  277. do {
  278. try FileManager.default.removeItem(atPath: toPath)
  279. } catch {
  280. print(error)
  281. }
  282. do {
  283. try FileManager.default.copyItem(atPath: atPath, toPath: toPath)
  284. try FileManager.default.removeItem(atPath: atPath)
  285. return true
  286. } catch {
  287. print(error)
  288. return false
  289. }
  290. }
  291. @discardableResult
  292. @objc func copyFile(atPath: String, toPath: String) -> Bool {
  293. if atPath == toPath { return true }
  294. do {
  295. try FileManager.default.removeItem(atPath: toPath)
  296. } catch {
  297. print(error)
  298. }
  299. do {
  300. try FileManager.default.copyItem(atPath: atPath, toPath: toPath)
  301. return true
  302. } catch {
  303. print(error)
  304. return false
  305. }
  306. }
  307. @discardableResult
  308. func copyFile(at: URL, to: URL) -> Bool {
  309. if at == to { return true }
  310. do {
  311. try FileManager.default.removeItem(at: to)
  312. } catch {
  313. print(error)
  314. }
  315. do {
  316. try FileManager.default.copyItem(at: at, to: to)
  317. return true
  318. } catch {
  319. print(error)
  320. return false
  321. }
  322. }
  323. @objc func moveFileInBackground(atPath: String, toPath: String) {
  324. if atPath == toPath { return }
  325. DispatchQueue.global().async {
  326. try? FileManager.default.removeItem(atPath: toPath)
  327. try? FileManager.default.copyItem(atPath: atPath, toPath: toPath)
  328. try? FileManager.default.removeItem(atPath: atPath)
  329. }
  330. }
  331. @objc func linkItem(atPath: String, toPath: String) {
  332. try? FileManager.default.removeItem(atPath: toPath)
  333. try? FileManager.default.linkItem(atPath: atPath, toPath: toPath)
  334. }
  335. // MARK: -
  336. @objc func getHomeServer(urlBase: String, userId: String) -> String {
  337. return urlBase + "/remote.php/dav/files/" + userId
  338. }
  339. @objc func getPath(path: String, user: String, fileName: String? = nil) -> String {
  340. var path = path.replacingOccurrences(of: "/remote.php/dav/files/" + user, with: "")
  341. if let fileName = fileName {
  342. path += fileName
  343. }
  344. return path
  345. }
  346. @objc func deleteLastPath(serverUrlPath: String, home: String? = nil) -> String? {
  347. var returnString: String?
  348. if home == serverUrlPath {
  349. return serverUrlPath
  350. }
  351. if let serverUrlPath = serverUrlPath.urlEncoded, let url = URL(string: serverUrlPath) {
  352. if let path = url.deletingLastPathComponent().absoluteString.removingPercentEncoding {
  353. if path.last == "/" {
  354. returnString = String(path.dropLast())
  355. } else {
  356. returnString = path
  357. }
  358. }
  359. }
  360. return returnString
  361. }
  362. func stringAppendServerUrl(_ serverUrl: String, addFileName: String) -> String {
  363. if addFileName.isEmpty {
  364. return serverUrl
  365. } else if serverUrl.last == "/" {
  366. return serverUrl + addFileName
  367. } else {
  368. return serverUrl + "/" + addFileName
  369. }
  370. }
  371. @objc func getFileNamePath(_ fileName: String, serverUrl: String, urlBase: String, userId: String) -> String {
  372. let home = getHomeServer(urlBase: urlBase, userId: userId)
  373. var fileNamePath = serverUrl.replacingOccurrences(of: home, with: "") + "/" + fileName
  374. if fileNamePath.first == "/" {
  375. fileNamePath.removeFirst()
  376. }
  377. return fileNamePath
  378. }
  379. @objc func createFileName(_ fileName: String, serverUrl: String, account: String) -> String {
  380. var resultFileName = fileName
  381. var exitLoop = false
  382. while exitLoop == false {
  383. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "fileNameView == %@ AND serverUrl == %@ AND account == %@", resultFileName, serverUrl, account)) != nil {
  384. var name = NSString(string: resultFileName).deletingPathExtension
  385. let ext = NSString(string: resultFileName).pathExtension
  386. let characters = Array(name)
  387. if characters.count < 2 {
  388. if ext.isEmpty {
  389. resultFileName = name + " " + "1"
  390. } else {
  391. resultFileName = name + " " + "1" + "." + ext
  392. }
  393. } else {
  394. let space = characters[characters.count - 2]
  395. let numChar = characters[characters.count - 1]
  396. var num = Int(String(numChar))
  397. if space == " " && num != nil {
  398. name = String(name.dropLast())
  399. num = num! + 1
  400. if ext.isEmpty {
  401. resultFileName = name + "\(num!)"
  402. } else {
  403. resultFileName = name + "\(num!)" + "." + ext
  404. }
  405. } else {
  406. if ext.isEmpty {
  407. resultFileName = name + " " + "1"
  408. } else {
  409. resultFileName = name + " " + "1" + "." + ext
  410. }
  411. }
  412. }
  413. } else {
  414. exitLoop = true
  415. }
  416. }
  417. return resultFileName
  418. }
  419. func createFileNameDate(_ fileName: String, ext: String) -> String {
  420. let formatter = DateFormatter()
  421. formatter.dateFormat = "yy-MM-dd HH-mm-ss"
  422. let fileNameDate = formatter.string(from: Date())
  423. if fileName.isEmpty, !ext.isEmpty {
  424. return fileNameDate + "." + ext
  425. } else if !fileName.isEmpty, ext.isEmpty {
  426. return fileName + " " + fileNameDate
  427. } else if fileName.isEmpty, ext.isEmpty {
  428. return fileNameDate
  429. } else {
  430. return fileName + " " + fileNameDate + "." + ext
  431. }
  432. }
  433. @objc func getDirectorySize(directory: String) -> Int64 {
  434. let url = URL(fileURLWithPath: directory)
  435. let manager = FileManager.default
  436. var totalSize: Int64 = 0
  437. if let enumerator = manager.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey], options: []) {
  438. for case let fileURL as URL in enumerator {
  439. if let attributes = try? manager.attributesOfItem(atPath: fileURL.path) {
  440. if let size = attributes[.size] as? Int64 {
  441. totalSize += size
  442. }
  443. }
  444. }
  445. }
  446. return totalSize
  447. }
  448. @objc func transformedSize(_ bytes: Int64) -> String {
  449. let formatter: ByteCountFormatter = ByteCountFormatter()
  450. formatter.countStyle = .binary
  451. return formatter.string(fromByteCount: bytes)
  452. }
  453. func cleanUp(directory: String, days: TimeInterval) {
  454. if days == 0 { return}
  455. let minimumDate = Date().addingTimeInterval(-days * 24 * 60 * 60)
  456. let url = URL(fileURLWithPath: directory)
  457. var offlineDir: [String] = []
  458. if let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "offline == true"), sorted: "serverUrl", ascending: true) {
  459. for directory: tableDirectory in directories {
  460. offlineDir.append(getDirectoryProviderStorageOcId(directory.ocId))
  461. }
  462. }
  463. let resultsLocalFile = NCManageDatabase.shared.getResultsTableLocalFile(predicate: NSPredicate(format: "offline == false"), sorted: "lastOpeningDate", ascending: true)
  464. let manager = FileManager.default
  465. if let enumerator = manager.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey], options: []) {
  466. for case let fileURL as URL in enumerator {
  467. if let attributes = try? manager.attributesOfItem(atPath: fileURL.path) {
  468. if attributes[.size] as? Double == 0 { continue }
  469. if attributes[.type] as? FileAttributeType == FileAttributeType.typeDirectory { continue }
  470. if fileURL.pathExtension == "ico" { continue }
  471. // check directory offline
  472. let filter = offlineDir.filter({ fileURL.path.hasPrefix($0)})
  473. if !filter.isEmpty { continue }
  474. // -----------------------
  475. let folderURL = fileURL.deletingLastPathComponent()
  476. let ocId = folderURL.lastPathComponent
  477. if let result = resultsLocalFile?.filter({ $0.ocId == ocId }).first, (result.lastOpeningDate as Date) < minimumDate {
  478. do {
  479. try manager.removeItem(atPath: fileURL.path)
  480. } catch { }
  481. manager.createFile(atPath: fileURL.path, contents: nil, attributes: nil)
  482. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", ocId))
  483. }
  484. }
  485. }
  486. }
  487. }
  488. func clearCacheDirectory(_ directory: String) {
  489. if let cacheURL = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first {
  490. do {
  491. let directoryURL = cacheURL.appendingPathComponent(directory, isDirectory: true)
  492. let directoryContents = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: nil, options: [])
  493. for file in directoryContents {
  494. do {
  495. try fileManager.removeItem(at: file)
  496. } catch let error as NSError {
  497. debugPrint("Ooops! Something went wrong: \(error)")
  498. }
  499. }
  500. } catch let error as NSError {
  501. print(error.localizedDescription)
  502. }
  503. }
  504. }
  505. func createGranularityPath(asset: PHAsset? = nil, serverUrl: String? = nil) -> String {
  506. let autoUploadSubfolderGranularity = NCManageDatabase.shared.getAccountAutoUploadSubfolderGranularity()
  507. let dateFormatter = DateFormatter()
  508. let date = asset?.creationDate ?? Date()
  509. var path = ""
  510. dateFormatter.dateFormat = "yyyy"
  511. let year = dateFormatter.string(from: date)
  512. dateFormatter.dateFormat = "MM"
  513. let month = dateFormatter.string(from: date)
  514. dateFormatter.dateFormat = "dd"
  515. let day = dateFormatter.string(from: date)
  516. if autoUploadSubfolderGranularity == NCGlobal.shared.subfolderGranularityYearly {
  517. path = "\(year)"
  518. } else if autoUploadSubfolderGranularity == NCGlobal.shared.subfolderGranularityDaily {
  519. path = "\(year)/\(month)/\(day)"
  520. } else { // Month Granularity is default
  521. path = "\(year)/\(month)"
  522. }
  523. if let serverUrl {
  524. return serverUrl + "/" + path
  525. } else {
  526. return path
  527. }
  528. }
  529. }