NCUtilityFileSystem.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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(metadata: tableMetadata, withFileName: Bool) -> String {
  137. var path = metadata.path.replacingOccurrences(of: "/remote.php/dav/files/"+metadata.user, with: "")
  138. if withFileName { path += metadata.fileName }
  139. return path
  140. }
  141. @objc func deletingLastPathComponent(account: String, serverUrl: String) -> String {
  142. if getHomeServer(account: account) == serverUrl { return serverUrl }
  143. let fileName = (serverUrl as NSString).lastPathComponent
  144. let serverUrl = serverUrl.replacingOccurrences(of: "/"+fileName, with: "", options: String.CompareOptions.backwards, range: nil)
  145. return serverUrl
  146. }
  147. @objc func createFileName(_ fileName: String, serverUrl: String, account: String) -> String {
  148. var resultFileName = fileName
  149. var exitLoop = false
  150. while exitLoop == false {
  151. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "fileNameView == %@ AND serverUrl == %@ AND account == %@", resultFileName, serverUrl, account)) != nil {
  152. var name = NSString(string: resultFileName).deletingPathExtension
  153. let ext = NSString(string: resultFileName).pathExtension
  154. let characters = Array(name)
  155. if characters.count < 2 {
  156. if ext == "" {
  157. resultFileName = name + " " + "1"
  158. } else {
  159. resultFileName = name + " " + "1" + "." + ext
  160. }
  161. } else {
  162. let space = characters[characters.count-2]
  163. let numChar = characters[characters.count-1]
  164. var num = Int(String(numChar))
  165. if space == " " && num != nil {
  166. name = String(name.dropLast())
  167. num = num! + 1
  168. if ext == "" {
  169. resultFileName = name + "\(num!)"
  170. } else {
  171. resultFileName = name + "\(num!)" + "." + ext
  172. }
  173. } else {
  174. if ext == "" {
  175. resultFileName = name + " " + "1"
  176. } else {
  177. resultFileName = name + " " + "1" + "." + ext
  178. }
  179. }
  180. }
  181. } else {
  182. exitLoop = true
  183. }
  184. }
  185. return resultFileName
  186. }
  187. @objc func getDirectorySize(directory: String) -> Int64 {
  188. let url = URL(fileURLWithPath: directory)
  189. let manager = FileManager.default
  190. var totalSize: Int64 = 0
  191. if let enumerator = manager.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey], options: []) {
  192. for case let fileURL as URL in enumerator {
  193. if let attributes = try? manager.attributesOfItem(atPath: fileURL.path) {
  194. if let size = attributes[.size] as? Int64 {
  195. totalSize += size
  196. }
  197. }
  198. }
  199. }
  200. return totalSize
  201. }
  202. func cleanUp(directory: String, days: TimeInterval) {
  203. if days == 0 { return}
  204. let minimumDate = Date().addingTimeInterval(-days*24*60*60)
  205. let url = URL(fileURLWithPath: directory)
  206. var offlineDir: [String] = []
  207. var offlineFiles: [String] = []
  208. if let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "offline == true"), sorted: "serverUrl", ascending: true) {
  209. for directory: tableDirectory in directories {
  210. offlineDir.append(CCUtility.getDirectoryProviderStorageOcId(directory.ocId))
  211. }
  212. }
  213. let files = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "offline == true"), sorted: "fileName", ascending: true)
  214. for file: tableLocalFile in files {
  215. offlineFiles.append(CCUtility.getDirectoryProviderStorageOcId(file.ocId, fileNameView: file.fileName))
  216. }
  217. func meetsRequirement(date: Date) -> Bool {
  218. return date < minimumDate
  219. }
  220. let manager = FileManager.default
  221. if let enumerator = manager.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey], options: []) {
  222. for case let fileURL as URL in enumerator {
  223. if let attributes = try? manager.attributesOfItem(atPath: fileURL.path) {
  224. if let date = CCUtility.getATime(fileURL.path) {
  225. if attributes[.size] as? Double == 0 { continue }
  226. if attributes[.type] as? FileAttributeType == FileAttributeType.typeDirectory { continue }
  227. if fileURL.pathExtension == NCGlobal.shared.extensionPreview { continue }
  228. // check offline
  229. if offlineFiles.contains(fileURL.path) { continue }
  230. let filter = offlineDir.filter({ fileURL.path.hasPrefix($0)})
  231. if filter.count > 0 { continue }
  232. // check date
  233. if meetsRequirement(date: date) {
  234. let folderURL = fileURL.deletingLastPathComponent()
  235. let ocId = folderURL.lastPathComponent
  236. do {
  237. try manager.removeItem(atPath: fileURL.path)
  238. } catch { }
  239. manager.createFile(atPath: fileURL.path, contents: nil, attributes: nil)
  240. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", ocId))
  241. }
  242. }
  243. }
  244. }
  245. }
  246. }
  247. }