NCUtilityFileSystem.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. @objc func getFileSize(filePath: String) -> Int64 {
  32. do {
  33. let attributes = try fileManager.attributesOfItem(atPath: filePath)
  34. return attributes[FileAttributeKey.size] as? Int64 ?? 0
  35. } catch {
  36. print(error)
  37. }
  38. return 0
  39. }
  40. @objc func getFileModificationDate(filePath: String) -> NSDate? {
  41. do {
  42. let attributes = try fileManager.attributesOfItem(atPath: filePath)
  43. return attributes[FileAttributeKey.modificationDate] as? NSDate
  44. } catch {
  45. print(error)
  46. }
  47. return nil
  48. }
  49. @objc func getFileCreationDate(filePath: String) -> NSDate? {
  50. do {
  51. let attributes = try fileManager.attributesOfItem(atPath: filePath)
  52. return attributes[FileAttributeKey.creationDate] as? NSDate
  53. } catch {
  54. print(error)
  55. }
  56. return nil
  57. }
  58. @objc func writeFile(fileURL: URL, text: String) -> Bool {
  59. do {
  60. try FileManager.default.removeItem(at: fileURL)
  61. } catch {
  62. print(error)
  63. }
  64. do {
  65. try text.write(to: fileURL, atomically: true, encoding: .utf8)
  66. return true
  67. } catch {
  68. print(error)
  69. return false
  70. }
  71. }
  72. @objc func deleteFile(filePath: String) {
  73. do {
  74. try FileManager.default.removeItem(atPath: filePath)
  75. } catch {
  76. print(error)
  77. }
  78. }
  79. @discardableResult
  80. @objc func moveFile(atPath: String, toPath: String) -> Bool {
  81. if atPath == toPath { return true }
  82. do {
  83. try FileManager.default.removeItem(atPath: toPath)
  84. } catch {
  85. print(error)
  86. }
  87. do {
  88. try FileManager.default.copyItem(atPath: atPath, toPath: toPath)
  89. try FileManager.default.removeItem(atPath: atPath)
  90. return true
  91. } catch {
  92. print(error)
  93. return false
  94. }
  95. }
  96. @discardableResult
  97. @objc func copyFile(atPath: String, toPath: String) -> Bool {
  98. if atPath == toPath { return true }
  99. do {
  100. try FileManager.default.removeItem(atPath: toPath)
  101. } catch {
  102. print(error)
  103. }
  104. do {
  105. try FileManager.default.copyItem(atPath: atPath, toPath: toPath)
  106. return true
  107. } catch {
  108. print(error)
  109. return false
  110. }
  111. }
  112. @objc func moveFileInBackground(atPath: String, toPath: String) {
  113. if atPath == toPath { return }
  114. DispatchQueue.global().async {
  115. try? FileManager.default.removeItem(atPath: toPath)
  116. try? FileManager.default.copyItem(atPath: atPath, toPath: toPath)
  117. try? FileManager.default.removeItem(atPath: atPath)
  118. }
  119. }
  120. @objc func linkItem(atPath: String, toPath: String) {
  121. try? FileManager.default.removeItem(atPath: toPath)
  122. try? FileManager.default.linkItem(atPath: atPath, toPath: toPath)
  123. }
  124. // MARK: -
  125. @objc func getWebDAV(account: String) -> String {
  126. // return NCManageDatabase.shared.getCapabilitiesServerString(account: account, elements: NCElementsJSON.shared.capabilitiesWebDavRoot) ?? "remote.php/webdav"
  127. return "remote.php/dav"
  128. }
  129. @objc func getHomeServer(account: String) -> String {
  130. var home = self.getWebDAV(account: account)
  131. if let tableAccount = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) {
  132. home = tableAccount.urlBase + "/" + self.getWebDAV(account: account) + "/files/" + tableAccount.userId
  133. }
  134. return home
  135. }
  136. @objc func getPath(path: String, user: String, fileName: String? = nil) -> String {
  137. var path = path.replacingOccurrences(of: "/remote.php/dav/files/" + user, with: "")
  138. if let fileName = fileName {
  139. path += fileName
  140. }
  141. return path
  142. }
  143. @objc func deletingLastPathComponent(account: String, serverUrl: String) -> String {
  144. if getHomeServer(account: account) == serverUrl { return serverUrl }
  145. let fileName = (serverUrl as NSString).lastPathComponent
  146. let serverUrl = serverUrl.replacingOccurrences(of: "/" + fileName, with: "", options: String.CompareOptions.backwards, range: nil)
  147. return serverUrl
  148. }
  149. @objc func createFileName(_ fileName: String, serverUrl: String, account: String) -> String {
  150. var resultFileName = fileName
  151. var exitLoop = false
  152. while exitLoop == false {
  153. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "fileNameView == %@ AND serverUrl == %@ AND account == %@", resultFileName, serverUrl, account)) != nil {
  154. var name = NSString(string: resultFileName).deletingPathExtension
  155. let ext = NSString(string: resultFileName).pathExtension
  156. let characters = Array(name)
  157. if characters.count < 2 {
  158. if ext == "" {
  159. resultFileName = name + " " + "1"
  160. } else {
  161. resultFileName = name + " " + "1" + "." + ext
  162. }
  163. } else {
  164. let space = characters[characters.count-2]
  165. let numChar = characters[characters.count-1]
  166. var num = Int(String(numChar))
  167. if space == " " && num != nil {
  168. name = String(name.dropLast())
  169. num = num! + 1
  170. if ext == "" {
  171. resultFileName = name + "\(num!)"
  172. } else {
  173. resultFileName = name + "\(num!)" + "." + ext
  174. }
  175. } else {
  176. if ext == "" {
  177. resultFileName = name + " " + "1"
  178. } else {
  179. resultFileName = name + " " + "1" + "." + ext
  180. }
  181. }
  182. }
  183. } else {
  184. exitLoop = true
  185. }
  186. }
  187. return resultFileName
  188. }
  189. @objc func getDirectorySize(directory: String) -> Int64 {
  190. let url = URL(fileURLWithPath: directory)
  191. let manager = FileManager.default
  192. var totalSize: Int64 = 0
  193. if let enumerator = manager.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey], options: []) {
  194. for case let fileURL as URL in enumerator {
  195. if let attributes = try? manager.attributesOfItem(atPath: fileURL.path) {
  196. if let size = attributes[.size] as? Int64 {
  197. totalSize += size
  198. }
  199. }
  200. }
  201. }
  202. return totalSize
  203. }
  204. func cleanUp(directory: String, days: TimeInterval) {
  205. if days == 0 { return}
  206. let minimumDate = Date().addingTimeInterval(-days*24*60*60)
  207. let url = URL(fileURLWithPath: directory)
  208. var offlineDir: [String] = []
  209. var offlineFiles: [String] = []
  210. if let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "offline == true"), sorted: "serverUrl", ascending: true) {
  211. for directory: tableDirectory in directories {
  212. offlineDir.append(CCUtility.getDirectoryProviderStorageOcId(directory.ocId))
  213. }
  214. }
  215. let files = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "offline == true"), sorted: "fileName", ascending: true)
  216. for file: tableLocalFile in files {
  217. offlineFiles.append(CCUtility.getDirectoryProviderStorageOcId(file.ocId, fileNameView: file.fileName))
  218. }
  219. func meetsRequirement(date: Date) -> Bool {
  220. return date < minimumDate
  221. }
  222. let manager = FileManager.default
  223. if let enumerator = manager.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey], options: []) {
  224. for case let fileURL as URL in enumerator {
  225. if let attributes = try? manager.attributesOfItem(atPath: fileURL.path) {
  226. if let date = CCUtility.getATime(fileURL.path) {
  227. if attributes[.size] as? Double == 0 { continue }
  228. if attributes[.type] as? FileAttributeType == FileAttributeType.typeDirectory { continue }
  229. if fileURL.pathExtension == NCGlobal.shared.extensionPreview { continue }
  230. // check offline
  231. if offlineFiles.contains(fileURL.path) { continue }
  232. let filter = offlineDir.filter({ fileURL.path.hasPrefix($0)})
  233. if filter.count > 0 { continue }
  234. // check date
  235. if meetsRequirement(date: date) {
  236. let folderURL = fileURL.deletingLastPathComponent()
  237. let ocId = folderURL.lastPathComponent
  238. do {
  239. try manager.removeItem(atPath: fileURL.path)
  240. } catch { }
  241. manager.createFile(atPath: fileURL.path, contents: nil, attributes: nil)
  242. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", ocId))
  243. }
  244. }
  245. }
  246. }
  247. }
  248. }
  249. }