NCUtilityFileSystem.swift 15 KB

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