NCUtilityFileSystem.swift 15 KB

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