NCUtilityFileSystem.swift 10 KB

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