ModelDownloader.swift 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. // Copyright 2020 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. import FirebaseCore
  16. /// Possible errors with model downloading.
  17. public enum DownloadError: Error, Equatable {
  18. /// No model with this name found on server.
  19. case notFound
  20. /// Caller does not have necessary permissions for this operation.
  21. case permissionDenied
  22. /// Conditions not met to perform download.
  23. case failedPrecondition
  24. /// Not enough space for model on device.
  25. case notEnoughSpace
  26. /// Malformed model name.
  27. case invalidArgument
  28. /// Other errors with description.
  29. case internalError(description: String)
  30. }
  31. /// Possible errors with locating model on device.
  32. public enum DownloadedModelError: Error, Equatable {
  33. /// File system error.
  34. case fileIOError(description: String)
  35. /// Model not found on device.
  36. case notFound
  37. }
  38. /// Possible ways to get a custom model.
  39. public enum ModelDownloadType {
  40. /// Get local model stored on device.
  41. case localModel
  42. /// Get local model on device and update to latest model from server in the background.
  43. case localModelUpdateInBackground
  44. /// Get latest model from server.
  45. case latestModel
  46. }
  47. /// Downloader to manage custom model downloads.
  48. public class ModelDownloader {
  49. /// Name of the app associated with this instance of ModelDownloader.
  50. private let appName: String
  51. /// Shared dictionary mapping app name to a specific instance of model downloader.
  52. // TODO: Switch to using Firebase components.
  53. private static var modelDownloaderDictionary: [String: ModelDownloader] = [:]
  54. /// Private init for downloader.
  55. private init(app: FirebaseApp) {
  56. appName = app.name
  57. NotificationCenter.default.addObserver(
  58. self,
  59. selector: #selector(deleteModelDownloader),
  60. name: Notification.Name("FIRAppDeleteNotification"),
  61. object: nil
  62. )
  63. }
  64. /// Handles app deletion notification.
  65. @objc private func deleteModelDownloader(notification: Notification) {
  66. if let userInfo = notification.userInfo,
  67. let appName = userInfo["FIRAppNameKey"] as? String {
  68. ModelDownloader.modelDownloaderDictionary.removeValue(forKey: appName)
  69. // TODO: Clean up user defaults
  70. // TODO: Clean up local instances of app
  71. }
  72. }
  73. /// Model downloader with default app.
  74. public static func modelDownloader() -> ModelDownloader {
  75. guard let defaultApp = FirebaseApp.app() else {
  76. fatalError("Default Firebase app not configured.")
  77. }
  78. return modelDownloader(app: defaultApp)
  79. }
  80. /// Model Downloader with custom app.
  81. public static func modelDownloader(app: FirebaseApp) -> ModelDownloader {
  82. if let downloader = modelDownloaderDictionary[app.name] {
  83. return downloader
  84. } else {
  85. let downloader = ModelDownloader(app: app)
  86. modelDownloaderDictionary[app.name] = downloader
  87. return downloader
  88. }
  89. }
  90. /// Downloads a custom model to device or gets a custom model already on device, w/ optional handler for progress.
  91. public func getModel(name modelName: String, downloadType: ModelDownloadType,
  92. conditions: ModelDownloadConditions,
  93. progressHandler: ((Float) -> Void)? = nil,
  94. completion: @escaping (Result<CustomModel, DownloadError>) -> Void) {
  95. // TODO: Model download
  96. let modelSize = Int()
  97. let modelPath = String()
  98. let modelHash = String()
  99. let customModel = CustomModel(
  100. name: modelName,
  101. size: modelSize,
  102. path: modelPath,
  103. hash: modelHash
  104. )
  105. completion(.success(customModel))
  106. completion(.failure(.notFound))
  107. }
  108. /// Gets all downloaded models.
  109. public func listDownloadedModels(completion: @escaping (Result<Set<CustomModel>,
  110. DownloadedModelError>) -> Void) {
  111. let customModels = Set<CustomModel>()
  112. // TODO: List downloaded models
  113. completion(.success(customModels))
  114. completion(.failure(.notFound))
  115. }
  116. /// Deletes a custom model from device.
  117. public func deleteDownloadedModel(name modelName: String,
  118. completion: @escaping (Result<Void, DownloadedModelError>)
  119. -> Void) {
  120. // TODO: Delete previously downloaded model
  121. completion(.success(()))
  122. completion(.failure(.notFound))
  123. }
  124. }