NCUtilityFileSystem.swift 14 KB

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