NCUtilityFileSystem.swift 16 KB

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