NCUtilityFileSystem.swift 11 KB

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