ModelFileManager.swift 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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. // TODO: Consider mocking this for tests?
  17. enum ModelFileManager {
  18. private static let nameSeparator = "__"
  19. private static let modelNamePrefix = "fbml_model"
  20. private static let fileManager = FileManager.default
  21. /// Root directory of model file storage on device.
  22. static var modelsDirectory: URL {
  23. // TODO: Reconsider force unwrapping.
  24. #if os(tvOS)
  25. return fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
  26. #else
  27. return fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
  28. #endif
  29. }
  30. /// Name for model file stored on device.
  31. private static func getDownloadedModelFileName(appName: String, modelName: String) -> String {
  32. return [modelNamePrefix, appName, modelName].joined(separator: nameSeparator)
  33. }
  34. /// Model name from file path.
  35. static func getModelNameFromFilePath(_ path: URL) -> String? {
  36. return path.lastPathComponent.components(separatedBy: nameSeparator).last
  37. }
  38. /// Full path of model file stored on device.
  39. static func getDownloadedModelFilePath(appName: String, modelName: String) -> URL {
  40. let modelFileName = ModelFileManager.getDownloadedModelFileName(
  41. appName: appName,
  42. modelName: modelName
  43. )
  44. return ModelFileManager.modelsDirectory
  45. .appendingPathComponent(modelFileName)
  46. }
  47. /// Check if file is available at URL.
  48. static func isFileReachable(at fileURL: URL) -> Bool {
  49. do {
  50. return try fileURL.checkResourceIsReachable()
  51. } catch {
  52. /// File unreachable.
  53. return false
  54. }
  55. }
  56. /// Move file at a location to another location.
  57. static func moveFile(at sourceURL: URL, to destinationURL: URL, size: Int64) throws {
  58. if isFileReachable(at: destinationURL) {
  59. do {
  60. try fileManager.removeItem(at: destinationURL)
  61. } catch {
  62. // TODO: Handle this - new model file downloaded but not saved due to FileManager error.
  63. throw DownloadError
  64. .internalError(
  65. description: ModelFileManager.ErrorDescription
  66. .replaceFile(error.localizedDescription)
  67. )
  68. }
  69. }
  70. do {
  71. try fileManager.moveItem(at: sourceURL, to: destinationURL)
  72. } catch CocoaError.fileWriteOutOfSpace {
  73. throw DownloadError.notEnoughSpace
  74. } catch {
  75. throw DownloadError
  76. .internalError(description: ModelFileManager
  77. .ErrorDescription.saveFile(error.localizedDescription))
  78. }
  79. }
  80. /// Remove model file at a specific location.
  81. static func removeFile(at url: URL) throws {
  82. do {
  83. try fileManager.removeItem(at: url)
  84. } catch {
  85. throw DownloadedModelError
  86. .internalError(
  87. description: ModelFileManager.ErrorDescription.deleteFile(error.localizedDescription)
  88. )
  89. }
  90. }
  91. static func contentsOfModelsDirectory() throws -> [URL] {
  92. do {
  93. let directoryContents = try ModelFileManager.fileManager.contentsOfDirectory(
  94. at: modelsDirectory,
  95. includingPropertiesForKeys: nil,
  96. options: .skipsHiddenFiles
  97. )
  98. return directoryContents.filter { directoryItem in
  99. !directoryItem.hasDirectoryPath
  100. }
  101. } catch {
  102. throw DownloadedModelError
  103. .internalError(
  104. description: ModelFileManager.ErrorDescription
  105. .retrieveFile(error.localizedDescription)
  106. )
  107. }
  108. }
  109. }
  110. /// Possible error messages during file management.
  111. extension ModelFileManager {
  112. /// Error descriptions.
  113. private enum ErrorDescription {
  114. static let retrieveFile = { (error: String) in
  115. "Could not retrieve model files in directory: \(error)"
  116. }
  117. static let deleteFile = { (error: String) in
  118. "Could not delete old model file: \(error)"
  119. }
  120. static let saveFile = { (error: String) in
  121. "Unable to save model file: \(error)"
  122. }
  123. static let replaceFile = { (error: String) in
  124. "Could not replace existing model file: \(error)"
  125. }
  126. static let availableStorage = { (error: String?) -> String in
  127. if let error = error {
  128. return "Failed to check storage capacity on device: \(error)"
  129. } else {
  130. return "Failed to check storage capacity on device."
  131. }
  132. }
  133. }
  134. }