NCUtilityFileSystem.swift 12 KB

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