NCUtilityFileSystem.swift 13 KB

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