ModelFileManager.swift 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. /// Manager for common file operations.
  16. enum ModelFileManager {
  17. private static let nameSeparator = "__"
  18. private static let modelNamePrefix = "fbml_model"
  19. private static let fileManager = FileManager.default
  20. /// Root directory of model file storage on device.
  21. static var modelsDirectory: URL {
  22. // TODO: Reconsider force unwrapping.
  23. #if os(tvOS)
  24. return fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
  25. #else
  26. return fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
  27. #endif
  28. }
  29. /// Name for model file stored on device.
  30. private static func getDownloadedModelFileName(appName: String, modelName: String) -> String {
  31. return [modelNamePrefix, appName, modelName].joined(separator: nameSeparator)
  32. }
  33. /// Model name from file path.
  34. static func getModelNameFromFilePath(_ path: URL) -> String? {
  35. return path.lastPathComponent.components(separatedBy: nameSeparator).last
  36. }
  37. /// Full path of model file stored on device.
  38. static func getDownloadedModelFilePath(appName: String, modelName: String) -> URL {
  39. let modelFileName = ModelFileManager.getDownloadedModelFileName(
  40. appName: appName,
  41. modelName: modelName
  42. )
  43. return ModelFileManager.modelsDirectory
  44. .appendingPathComponent(modelFileName)
  45. }
  46. /// Check if file is available at URL.
  47. static func isFileReachable(at fileURL: URL) -> Bool {
  48. do {
  49. return try fileURL.checkResourceIsReachable()
  50. } catch {
  51. /// File unreachable.
  52. return false
  53. }
  54. }
  55. /// Move file at a location to another location.
  56. static func moveFile(at sourceURL: URL, to destinationURL: URL) throws {
  57. if isFileReachable(at: destinationURL) {
  58. do {
  59. try fileManager.removeItem(at: destinationURL)
  60. } catch {
  61. throw DownloadError
  62. .internalError(
  63. description: ModelFileManager.ErrorDescription
  64. .replaceFile(error.localizedDescription)
  65. )
  66. }
  67. }
  68. do {
  69. try FileManager.default.moveItem(at: sourceURL, to: destinationURL)
  70. } catch {
  71. throw DownloadError
  72. .internalError(description: ModelFileManager
  73. .ErrorDescription.saveFile(error.localizedDescription))
  74. }
  75. }
  76. /// Remove model file at a specific location.
  77. static func removeFile(at url: URL) throws {
  78. do {
  79. try fileManager.removeItem(at: url)
  80. } catch {
  81. throw DownloadedModelError
  82. .internalError(
  83. description: ModelFileManager.ErrorDescription.deleteFile(error.localizedDescription)
  84. )
  85. }
  86. }
  87. static func contentsOfModelsDirectory() throws -> [URL] {
  88. do {
  89. let directoryContents = try ModelFileManager.fileManager.contentsOfDirectory(
  90. at: modelsDirectory,
  91. includingPropertiesForKeys: nil,
  92. options: .skipsHiddenFiles
  93. )
  94. return directoryContents.filter { directoryItem in
  95. !directoryItem.hasDirectoryPath
  96. }
  97. } catch {
  98. throw DownloadedModelError
  99. .internalError(
  100. description: ModelFileManager.ErrorDescription
  101. .retrieveFile(error.localizedDescription)
  102. )
  103. }
  104. }
  105. }
  106. /// Possible error messages during file management.
  107. extension ModelFileManager {
  108. /// Error descriptions.
  109. private enum ErrorDescription {
  110. static let retrieveFile = { (error: String) in
  111. "Could not retrieve model files in directory: \(error)"
  112. }
  113. static let deleteFile = { (error: String) in
  114. "Could not delete old model file: \(error)"
  115. }
  116. static let saveFile = { (error: String) in
  117. "Unable to save model file: \(error)"
  118. }
  119. static let replaceFile = { (error: String) in
  120. "Could not replace existing model file: \(error)"
  121. }
  122. }
  123. }