NCUtilityFileSystem.swift 22 KB

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