NCUtilityFileSystem.swift 13 KB

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