NCUtilityFileSystem.swift 12 KB

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