NCUtilityFileSystem.swift 14 KB

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