NCUtilityFileSystem.swift 16 KB

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