ModelFileManager.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. /// Separator in model file name components.
  18. private static let nameSeparator = "@@"
  19. private static let modelNamePrefix = "fbml_model"
  20. private static let fileExtension = "tflite"
  21. private static let fileManager = FileManager.default
  22. /// Root directory of model file storage on device.
  23. static var modelsDirectory: URL? {
  24. let rootDirOptional: URL? = {
  25. #if os(tvOS)
  26. return fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first
  27. #else
  28. return fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first ?? nil
  29. #endif
  30. }()
  31. guard let rootDirURL = rootDirOptional else {
  32. return nil
  33. }
  34. let modelDirURL = rootDirURL.appendingPathComponent(
  35. "com.firebase.FirebaseMLModelDownloader",
  36. isDirectory: true
  37. )
  38. do {
  39. if !fileManager.fileExists(atPath: modelDirURL.absoluteString) {
  40. try fileManager.createDirectory(at: modelDirURL, withIntermediateDirectories: true)
  41. }
  42. } catch {
  43. return nil
  44. }
  45. return modelDirURL
  46. }
  47. /// Name for model file stored on device.
  48. static func getDownloadedModelFileName(appName: String, modelName: String) -> String {
  49. return [modelNamePrefix, appName, modelName].joined(separator: nameSeparator)
  50. }
  51. /// Model name from file path.
  52. static func getModelNameFromFilePath(_ path: URL) -> String? {
  53. let components = path.deletingPathExtension().lastPathComponent
  54. .components(separatedBy: nameSeparator)
  55. // The file name should have prefix, app name, and model name.
  56. if components.count == 3 {
  57. return components.last
  58. }
  59. return nil
  60. }
  61. /// Full path of model file stored on device.
  62. static func getDownloadedModelFileURL(appName: String, modelName: String) -> URL? {
  63. let modelFileName = ModelFileManager.getDownloadedModelFileName(
  64. appName: appName,
  65. modelName: modelName
  66. )
  67. guard let modelsDir = ModelFileManager.modelsDirectory else { return nil }
  68. return modelsDir.appendingPathComponent(modelFileName).appendingPathExtension(fileExtension)
  69. }
  70. /// Check if file is available at URL.
  71. static func isFileReachable(at fileURL: URL) -> Bool {
  72. do {
  73. return try fileURL.checkResourceIsReachable()
  74. } catch {
  75. // File unreachable.
  76. return false
  77. }
  78. }
  79. /// Move file at a location to another location.
  80. static func moveFile(at sourceURL: URL, to destinationURL: URL, size: Int64) throws {
  81. if isFileReachable(at: destinationURL) {
  82. do {
  83. try fileManager.removeItem(at: destinationURL)
  84. } catch {
  85. // TODO: Handle this - new model file downloaded but not saved due to FileManager error.
  86. throw DownloadError
  87. .internalError(
  88. description: ModelFileManager.ErrorDescription
  89. .replaceFile(error.localizedDescription)
  90. )
  91. }
  92. }
  93. do {
  94. try fileManager.moveItem(at: sourceURL, to: destinationURL)
  95. } catch CocoaError.fileWriteOutOfSpace {
  96. throw DownloadError.notEnoughSpace
  97. } catch {
  98. throw DownloadError
  99. .internalError(description: ModelFileManager
  100. .ErrorDescription.saveFile(error.localizedDescription))
  101. }
  102. }
  103. /// Remove model file at a specific location.
  104. static func removeFile(at url: URL) throws {
  105. do {
  106. try fileManager.removeItem(at: url)
  107. } catch {
  108. throw DownloadedModelError
  109. .internalError(
  110. description: ModelFileManager.ErrorDescription.deleteFile(error.localizedDescription)
  111. )
  112. }
  113. }
  114. /// Get all model files in models directory.
  115. static func contentsOfModelsDirectory() throws -> [URL] {
  116. guard let modelsDir = modelsDirectory else {
  117. throw DownloadedModelError
  118. .internalError(
  119. description: ModelFileManager.ErrorDescription.noApplicationSupportDirectory
  120. )
  121. }
  122. do {
  123. let directoryContents = try ModelFileManager.fileManager.contentsOfDirectory(
  124. at: modelsDir,
  125. includingPropertiesForKeys: nil,
  126. options: .skipsHiddenFiles
  127. )
  128. return directoryContents.filter { directoryItem in
  129. directoryItem.path.contains(ModelFileManager.modelNamePrefix) && !directoryItem
  130. .hasDirectoryPath
  131. }
  132. } catch {
  133. throw DownloadedModelError
  134. .internalError(
  135. description: ModelFileManager.ErrorDescription
  136. .retrieveFile(error.localizedDescription)
  137. )
  138. }
  139. }
  140. }
  141. /// NOTE: Use for testing only.
  142. extension ModelFileManager {
  143. static func emptyModelsDirectory() throws {
  144. do {
  145. let directoryContents = try ModelFileManager.contentsOfModelsDirectory()
  146. for path in directoryContents {
  147. try ModelFileManager.removeFile(at: path)
  148. }
  149. } catch {
  150. throw DownloadedModelError
  151. .internalError(
  152. description: ModelFileManager.ErrorDescription
  153. .emptyDirectory(error.localizedDescription)
  154. )
  155. }
  156. }
  157. }
  158. /// Possible error messages during file management.
  159. extension ModelFileManager {
  160. /// Error descriptions.
  161. private enum ErrorDescription {
  162. static let retrieveFile = { (error: String) in
  163. "Could not retrieve model files in directory: \(error)"
  164. }
  165. static let deleteFile = { (error: String) in
  166. "Could not delete old model file: \(error)"
  167. }
  168. static let saveFile = { (error: String) in
  169. "Unable to save model file: \(error)"
  170. }
  171. static let replaceFile = { (error: String) in
  172. "Could not replace existing model file: \(error)"
  173. }
  174. static let availableStorage = { (error: String?) -> String in
  175. if let error = error {
  176. return "Failed to check storage capacity on device: \(error)"
  177. } else {
  178. return "Failed to check storage capacity on device."
  179. }
  180. }
  181. static let noApplicationSupportDirectory =
  182. "Could not locate Application Support directory for model storage."
  183. static let emptyDirectory = { (error: String) in
  184. "Could not empty models directory: \(error)"
  185. }
  186. }
  187. }