NCUtilityFileSystem.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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. var directoryGroup: String {
  29. return fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroup)?.path ?? ""
  30. }
  31. var directoryDocuments: String {
  32. return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? ""
  33. }
  34. var directoryCertificates: String {
  35. guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroup) else { return "" }
  36. let path = directoryGroup.appendingPathComponent(NCGlobal.shared.appCertificates).path
  37. if !fileManager.fileExists(atPath: path) {
  38. do {
  39. try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true)
  40. } catch { print("Error: \(error)") }
  41. }
  42. return path
  43. }
  44. var directoryUserData: String {
  45. guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroup) else { return "" }
  46. let path = directoryGroup.appendingPathComponent(NCGlobal.shared.appUserData).path
  47. if !fileManager.fileExists(atPath: path) {
  48. do {
  49. try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true)
  50. } catch { print("Error: \(error)") }
  51. }
  52. return path
  53. }
  54. var directoryScan: String {
  55. guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroup) else { return "" }
  56. let path = directoryGroup.appendingPathComponent(NCGlobal.shared.appScan).path
  57. if !fileManager.fileExists(atPath: path) {
  58. do {
  59. try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true)
  60. } catch { print("Error: \(error)") }
  61. }
  62. return path
  63. }
  64. var directoryProviderStorage: String {
  65. guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroup) else { return "" }
  66. let path = directoryGroup.appendingPathComponent(NCGlobal.shared.directoryProviderStorage).path
  67. if !fileManager.fileExists(atPath: path) {
  68. do {
  69. try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true)
  70. } catch { print("Error: \(error)") }
  71. }
  72. return path
  73. }
  74. // MARK: -
  75. 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 + NCGlobal.shared.storageExtIcon
  93. }
  94. func getDirectoryProviderStoragePreviewOcId(_ ocId: String, etag: String) -> String {
  95. return getDirectoryProviderStorageOcId(ocId) + "/" + etag + NCGlobal.shared.storageExtPreview
  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 { }
  140. return false
  141. }
  142. func createDirectoryStandard() {
  143. guard let directoryGroup = fileManager.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroup)?.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. func removeGroupApplicationSupport() {
  161. let path = directoryGroup + "/" + NCGlobal.shared.appApplicationSupport
  162. try? fileManager.removeItem(atPath: path)
  163. }
  164. func removeGroupLibraryDirectory() {
  165. try? fileManager.removeItem(atPath: directoryScan)
  166. try? fileManager.removeItem(atPath: directoryUserData)
  167. }
  168. func removeGroupDirectoryProviderStorage() {
  169. try? fileManager.removeItem(atPath: directoryProviderStorage)
  170. }
  171. func removeDocumentsDirectory() {
  172. try? fileManager.removeItem(atPath: directoryDocuments)
  173. }
  174. func removeTemporaryDirectory() {
  175. try? fileManager.removeItem(atPath: NSTemporaryDirectory())
  176. }
  177. 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. 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. 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. 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. 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. func removeFile(atPath: String) {
  268. do {
  269. try FileManager.default.removeItem(atPath: atPath)
  270. } catch {
  271. print(error)
  272. }
  273. }
  274. @discardableResult
  275. 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. 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. 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. 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. func getHomeServer(urlBase: String, userId: String) -> String {
  337. return urlBase + "/remote.php/dav/files/" + userId
  338. }
  339. 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. func deleteLastPath(serverUrlPath: String, home: String? = nil) -> String? {
  347. var returnString: String?
  348. if home == serverUrlPath { return serverUrlPath }
  349. if let serverUrlPath = serverUrlPath.urlEncoded, let url = URL(string: serverUrlPath) {
  350. if let path = url.deletingLastPathComponent().absoluteString.removingPercentEncoding {
  351. if path.last == "/" {
  352. returnString = String(path.dropLast())
  353. } else {
  354. returnString = path
  355. }
  356. }
  357. }
  358. return returnString
  359. }
  360. func stringAppendServerUrl(_ serverUrl: String, addFileName: String) -> String {
  361. if addFileName.isEmpty {
  362. return serverUrl
  363. } else if serverUrl.last == "/" {
  364. return serverUrl + addFileName
  365. } else {
  366. return serverUrl + "/" + addFileName
  367. }
  368. }
  369. func getFileNamePath(_ fileName: String, serverUrl: String, urlBase: String, userId: String) -> String {
  370. let home = getHomeServer(urlBase: urlBase, userId: userId)
  371. var fileNamePath = serverUrl.replacingOccurrences(of: home, with: "") + "/" + fileName
  372. if fileNamePath.first == "/" {
  373. fileNamePath.removeFirst()
  374. }
  375. return fileNamePath
  376. }
  377. func createFileName(_ fileName: String, fileDate: Date, fileType: PHAssetMediaType, notUseMask: Bool = false) -> String {
  378. var fileName = fileName
  379. let keychain = NCKeychain()
  380. var addFileNameType: Bool = keychain.fileNameType
  381. let useFileNameOriginal: Bool = keychain.fileNameOriginal
  382. var numberFileName: String = ""
  383. var fileNameType = ""
  384. let fileNameExt = (fileName as NSString).pathExtension.lowercased()
  385. /// Original FileName
  386. if useFileNameOriginal {
  387. addFileNameType = false
  388. if !notUseMask {
  389. return fileName
  390. }
  391. }
  392. /// Get counter
  393. if fileName.count > 8 {
  394. let index = fileName.index(fileName.startIndex, offsetBy: 4)
  395. numberFileName = String(fileName[index..<fileName.index(index, offsetBy: 4)])
  396. } else {
  397. numberFileName = keychain.incrementalNumber
  398. }
  399. let formatter = DateFormatter()
  400. formatter.locale = Locale(identifier: "en_US_POSIX")
  401. formatter.dateFormat = "yy-MM-dd HH-mm-ss"
  402. let fileNameDate = formatter.string(from: fileDate)
  403. switch fileType {
  404. case .image:
  405. fileNameType = NSLocalizedString("_photo_", comment: "")
  406. case .video:
  407. fileNameType = NSLocalizedString("_video_", comment: "")
  408. case .audio:
  409. fileNameType = NSLocalizedString("_audio_", comment: "")
  410. case .unknown:
  411. fileNameType = NSLocalizedString("_unknown_", comment: "")
  412. default:
  413. fileNameType = NSLocalizedString("_unknown_", comment: "")
  414. }
  415. if !keychain.fileNameMask.isEmpty, !notUseMask {
  416. fileName = keychain.fileNameMask
  417. if !fileName.isEmpty {
  418. formatter.dateFormat = "dd"
  419. let dayNumber = formatter.string(from: fileDate)
  420. formatter.dateFormat = "MMM"
  421. let month = formatter.string(from: fileDate)
  422. formatter.dateFormat = "MM"
  423. let monthNumber = formatter.string(from: fileDate)
  424. formatter.dateFormat = "yyyy"
  425. let year = formatter.string(from: fileDate)
  426. formatter.dateFormat = "yy"
  427. let yearNumber = formatter.string(from: fileDate)
  428. formatter.dateFormat = "HH"
  429. let hour24 = formatter.string(from: fileDate)
  430. formatter.dateFormat = "hh"
  431. let hour12 = formatter.string(from: fileDate)
  432. formatter.dateFormat = "mm"
  433. let minute = formatter.string(from: fileDate)
  434. formatter.dateFormat = "ss"
  435. let second = formatter.string(from: fileDate)
  436. formatter.dateFormat = "a"
  437. let ampm = formatter.string(from: fileDate)
  438. // Replace string with date
  439. fileName = fileName.replacingOccurrences(of: "DD", with: dayNumber)
  440. fileName = fileName.replacingOccurrences(of: "MMM", with: month)
  441. fileName = fileName.replacingOccurrences(of: "MM", with: monthNumber)
  442. fileName = fileName.replacingOccurrences(of: "YYYY", with: year)
  443. fileName = fileName.replacingOccurrences(of: "YY", with: yearNumber)
  444. fileName = fileName.replacingOccurrences(of: "HH", with: hour24)
  445. fileName = fileName.replacingOccurrences(of: "hh", with: hour12)
  446. fileName = fileName.replacingOccurrences(of: "mm", with: minute)
  447. fileName = fileName.replacingOccurrences(of: "ss", with: second)
  448. fileName = fileName.replacingOccurrences(of: "ampm", with: ampm)
  449. if addFileNameType {
  450. fileName = "\(fileNameType)\(fileName)\(numberFileName).\(fileNameExt)"
  451. } else {
  452. fileName = "\(fileName)\(numberFileName).\(fileNameExt)"
  453. }
  454. fileName = fileName.trimmingCharacters(in: .whitespacesAndNewlines)
  455. return fileName
  456. }
  457. }
  458. if addFileNameType {
  459. fileName = "\(fileNameType) \(fileNameDate) \(numberFileName).\(fileNameExt)"
  460. } else {
  461. fileName = "\(fileNameDate) \(numberFileName).\(fileNameExt)"
  462. }
  463. return fileName
  464. }
  465. func createFileName(_ fileName: String, serverUrl: String, account: String) -> String {
  466. var resultFileName = fileName
  467. var exitLoop = false
  468. while exitLoop == false {
  469. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "fileNameView == %@ AND serverUrl == %@ AND account == %@", resultFileName, serverUrl, account)) != nil {
  470. var name = NSString(string: resultFileName).deletingPathExtension
  471. let ext = NSString(string: resultFileName).pathExtension
  472. let characters = Array(name)
  473. if characters.count < 2 {
  474. if ext.isEmpty {
  475. resultFileName = name + " " + "1"
  476. } else {
  477. resultFileName = name + " " + "1" + "." + ext
  478. }
  479. } else {
  480. let space = characters[characters.count - 2]
  481. let numChar = characters[characters.count - 1]
  482. var num = Int(String(numChar))
  483. if space == " " && num != nil {
  484. name = String(name.dropLast())
  485. num = num! + 1
  486. if ext.isEmpty {
  487. resultFileName = name + "\(num!)"
  488. } else {
  489. resultFileName = name + "\(num!)" + "." + ext
  490. }
  491. } else {
  492. if ext.isEmpty {
  493. resultFileName = name + " " + "1"
  494. } else {
  495. resultFileName = name + " " + "1" + "." + ext
  496. }
  497. }
  498. }
  499. } else {
  500. exitLoop = true
  501. }
  502. }
  503. return resultFileName
  504. }
  505. func createFileNameDate(_ fileName: String, ext: String) -> String {
  506. let formatter = DateFormatter()
  507. formatter.dateFormat = "yy-MM-dd HH-mm-ss"
  508. let fileNameDate = formatter.string(from: Date())
  509. if fileName.isEmpty, !ext.isEmpty {
  510. return fileNameDate + "." + ext
  511. } else if !fileName.isEmpty, ext.isEmpty {
  512. return fileName + " " + fileNameDate
  513. } else if fileName.isEmpty, ext.isEmpty {
  514. return fileNameDate
  515. } else {
  516. return fileName + " " + fileNameDate + "." + ext
  517. }
  518. }
  519. func getDirectorySize(directory: String) -> Int64 {
  520. let url = URL(fileURLWithPath: directory)
  521. let manager = FileManager.default
  522. var totalSize: Int64 = 0
  523. if let enumerator = manager.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey], options: []) {
  524. for case let fileURL as URL in enumerator {
  525. if let attributes = try? manager.attributesOfItem(atPath: fileURL.path) {
  526. if let size = attributes[.size] as? Int64 {
  527. totalSize += size
  528. }
  529. }
  530. }
  531. }
  532. return totalSize
  533. }
  534. func transformedSize(_ bytes: Int64) -> String {
  535. let formatter: ByteCountFormatter = ByteCountFormatter()
  536. formatter.countStyle = .binary
  537. return formatter.string(fromByteCount: bytes)
  538. }
  539. func cleanUp(directory: String, days: TimeInterval) {
  540. if days == 0 { return}
  541. let minimumDate = Date().addingTimeInterval(-days * 24 * 60 * 60)
  542. let url = URL(fileURLWithPath: directory)
  543. var offlineDir: [String] = []
  544. if let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "offline == true"), sorted: "serverUrl", ascending: true) {
  545. for directory: tableDirectory in directories {
  546. offlineDir.append(getDirectoryProviderStorageOcId(directory.ocId))
  547. }
  548. }
  549. let resultsLocalFile = NCManageDatabase.shared.getResultsTableLocalFile(predicate: NSPredicate(format: "offline == false"), sorted: "lastOpeningDate", ascending: true)
  550. let manager = FileManager.default
  551. if let enumerator = manager.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey], options: []) {
  552. for case let fileURL as URL in enumerator {
  553. if let attributes = try? manager.attributesOfItem(atPath: fileURL.path) {
  554. if attributes[.size] as? Double == 0 { continue }
  555. if attributes[.type] as? FileAttributeType == FileAttributeType.typeDirectory { continue }
  556. if fileURL.pathExtension == "ico" { continue }
  557. // check directory offline
  558. let filter = offlineDir.filter({ fileURL.path.hasPrefix($0)})
  559. if !filter.isEmpty { continue }
  560. // -----------------------
  561. let folderURL = fileURL.deletingLastPathComponent()
  562. let ocId = folderURL.lastPathComponent
  563. if let result = resultsLocalFile?.filter({ $0.ocId == ocId }).first, (result.lastOpeningDate as Date) < minimumDate {
  564. do {
  565. try manager.removeItem(atPath: fileURL.path)
  566. } catch { }
  567. manager.createFile(atPath: fileURL.path, contents: nil, attributes: nil)
  568. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", ocId))
  569. }
  570. }
  571. }
  572. }
  573. }
  574. func clearCacheDirectory(_ directory: String) {
  575. if let cacheURL = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first {
  576. do {
  577. let directoryURL = cacheURL.appendingPathComponent(directory, isDirectory: true)
  578. let directoryContents = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: nil, options: [])
  579. for file in directoryContents {
  580. do {
  581. try fileManager.removeItem(at: file)
  582. } catch let error as NSError {
  583. debugPrint("Ooops! Something went wrong: \(error)")
  584. }
  585. }
  586. } catch let error as NSError {
  587. print(error.localizedDescription)
  588. }
  589. }
  590. }
  591. func createGranularityPath(asset: PHAsset? = nil, serverUrl: String? = nil) -> String {
  592. let autoUploadSubfolderGranularity = NCManageDatabase.shared.getAccountAutoUploadSubfolderGranularity()
  593. let dateFormatter = DateFormatter()
  594. let date = asset?.creationDate ?? Date()
  595. var path = ""
  596. dateFormatter.dateFormat = "yyyy"
  597. let year = dateFormatter.string(from: date)
  598. dateFormatter.dateFormat = "MM"
  599. let month = dateFormatter.string(from: date)
  600. dateFormatter.dateFormat = "dd"
  601. let day = dateFormatter.string(from: date)
  602. if autoUploadSubfolderGranularity == NCGlobal.shared.subfolderGranularityYearly {
  603. path = "\(year)"
  604. } else if autoUploadSubfolderGranularity == NCGlobal.shared.subfolderGranularityDaily {
  605. path = "\(year)/\(month)/\(day)"
  606. } else { // Month Granularity is default
  607. path = "\(year)/\(month)"
  608. }
  609. if let serverUrl {
  610. return serverUrl + "/" + path
  611. } else {
  612. return path
  613. }
  614. }
  615. }