Storage.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. // Copyright 2022 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 FirebaseAppCheckInterop
  16. import FirebaseAuthInterop
  17. import FirebaseCore
  18. #if COCOAPODS
  19. import GTMSessionFetcher
  20. #else
  21. import GTMSessionFetcherCore
  22. #endif
  23. // Avoids exposing internal FirebaseCore APIs to Swift users.
  24. @_implementationOnly import FirebaseCoreExtension
  25. /// Firebase Storage is a service that supports uploading and downloading binary objects,
  26. /// such as images, videos, and other files to Google Cloud Storage. Instances of `Storage`
  27. /// are not thread-safe, but can be accessed from any thread.
  28. ///
  29. /// If you call `Storage.storage()`, the instance will initialize with the default `FirebaseApp`,
  30. /// `FirebaseApp.app()`, and the storage location will come from the provided
  31. /// `GoogleService-Info.plist`.
  32. ///
  33. /// If you provide a custom instance of `FirebaseApp`,
  34. /// the storage location will be specified via the `FirebaseOptions.storageBucket` property.
  35. @objc(FIRStorage) open class Storage: NSObject {
  36. // MARK: - Public APIs
  37. /// The default `Storage` instance.
  38. /// - Returns: An instance of `Storage`, configured with the default `FirebaseApp`.
  39. @objc(storage) open class func storage() -> Storage {
  40. return storage(app: FirebaseApp.app()!)
  41. }
  42. /// A method used to create `Storage` instances initialized with a custom storage bucket URL.
  43. ///
  44. /// Any `StorageReferences` generated from this instance of `Storage` will reference files
  45. /// and directories within the specified bucket.
  46. /// - Parameter url: The `gs://` URL to your Firebase Storage bucket.
  47. /// - Returns: A `Storage` instance, configured with the custom storage bucket.
  48. @objc(storageWithURL:) open class func storage(url: String) -> Storage {
  49. return storage(app: FirebaseApp.app()!, url: url)
  50. }
  51. /// Creates an instance of `Storage`, configured with a custom `FirebaseApp`. `StorageReference`s
  52. /// generated from a resulting instance will reference files in the Firebase project
  53. /// associated with custom `FirebaseApp`.
  54. /// - Parameter app: The custom `FirebaseApp` used for initialization.
  55. /// - Returns: A `Storage` instance, configured with the custom `FirebaseApp`.
  56. @objc(storageForApp:) open class func storage(app: FirebaseApp) -> Storage {
  57. guard let provider = ComponentType<StorageProvider>.instance(for: StorageProvider.self,
  58. in: app.container) else {
  59. fatalError("No \(StorageProvider.self) instance found for Firebase app: \(app.name)")
  60. }
  61. return provider.storage(for: Storage.bucket(for: app))
  62. }
  63. /// Creates an instance of `Storage`, configured with a custom `FirebaseApp` and a custom storage
  64. /// bucket URL.
  65. /// - Parameters:
  66. /// - app: The custom `FirebaseApp` used for initialization.
  67. /// - url: The `gs://` url to your Firebase Storage bucket.
  68. /// - Returns: The `Storage` instance, configured with the custom `FirebaseApp` and storage bucket
  69. /// URL.
  70. @objc(storageForApp:URL:)
  71. open class func storage(app: FirebaseApp, url: String) -> Storage {
  72. guard let provider = ComponentType<StorageProvider>.instance(for: StorageProvider.self,
  73. in: app.container) else {
  74. fatalError("No \(StorageProvider.self) instance found for Firebase app: \(app.name)")
  75. }
  76. return provider.storage(for: Storage.bucket(for: app, urlString: url))
  77. }
  78. /// The `FirebaseApp` associated with this Storage instance.
  79. @objc public let app: FirebaseApp
  80. /// The maximum time in seconds to retry an upload if a failure occurs.
  81. /// Defaults to 10 minutes (600 seconds).
  82. @objc public var maxUploadRetryTime: TimeInterval {
  83. didSet {
  84. maxUploadRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxUploadRetryTime)
  85. }
  86. }
  87. /// The maximum time in seconds to retry a download if a failure occurs.
  88. /// Defaults to 10 minutes (600 seconds).
  89. @objc public var maxDownloadRetryTime: TimeInterval {
  90. didSet {
  91. maxDownloadRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxDownloadRetryTime)
  92. }
  93. }
  94. /// The maximum time in seconds to retry operations other than upload and download if a failure
  95. /// occurs.
  96. /// Defaults to 2 minutes (120 seconds).
  97. @objc public var maxOperationRetryTime: TimeInterval {
  98. didSet {
  99. maxOperationRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxOperationRetryTime)
  100. }
  101. }
  102. /// Specify the maximum upload chunk size. Values less than 256K (262144) will be rounded up to
  103. /// 256K. Values
  104. /// above 256K will be rounded down to the nearest 256K multiple. The default is no maximum.
  105. @objc public var uploadChunkSizeBytes: Int64 = .max
  106. /// A `DispatchQueue` that all developer callbacks are fired on. Defaults to the main queue.
  107. @objc public var callbackQueue: DispatchQueue {
  108. get {
  109. ensureConfigured()
  110. guard let queue = fetcherService?.callbackQueue else {
  111. fatalError("Internal error: Failed to initialize fetcherService callbackQueue")
  112. }
  113. return queue
  114. }
  115. set(newValue) {
  116. ensureConfigured()
  117. fetcherService?.callbackQueue = newValue
  118. }
  119. }
  120. /// Creates a `StorageReference` initialized at the root Firebase Storage location.
  121. /// - Returns: An instance of `StorageReference` referencing the root of the storage bucket.
  122. @objc open func reference() -> StorageReference {
  123. ensureConfigured()
  124. let path = StoragePath(with: storageBucket)
  125. return StorageReference(storage: self, path: path)
  126. }
  127. /// Creates a StorageReference given a `gs://`, `http://`, or `https://` URL pointing to a
  128. /// Firebase Storage location.
  129. ///
  130. /// For example, you can pass in an `https://` download URL retrieved from
  131. /// `StorageReference.downloadURL(completion:)` or the `gs://` URL from
  132. /// `StorageReference.description`.
  133. /// - Parameter url: A gs:// or https:// URL to initialize the reference with.
  134. /// - Returns: An instance of StorageReference at the given child path.
  135. /// - Throws: Throws a fatal error if `url` is not associated with the `FirebaseApp` used to
  136. /// initialize
  137. /// this Storage instance.
  138. @objc open func reference(forURL url: String) -> StorageReference {
  139. ensureConfigured()
  140. do {
  141. let path = try StoragePath.path(string: url)
  142. // If no default bucket exists (empty string), accept anything.
  143. if storageBucket == "" {
  144. return StorageReference(storage: self, path: path)
  145. }
  146. // If there exists a default bucket, throw if provided a different bucket.
  147. if path.bucket != storageBucket {
  148. fatalError("Provided bucket: `\(path.bucket)` does not match the Storage bucket of the current " +
  149. "instance: `\(storageBucket)`")
  150. }
  151. return StorageReference(storage: self, path: path)
  152. } catch let StoragePathError.storagePathError(message) {
  153. fatalError(message)
  154. } catch {
  155. fatalError("Internal error finding StoragePath: \(error)")
  156. }
  157. }
  158. /// Creates a StorageReference given a `gs://`, `http://`, or `https://` URL pointing to a
  159. /// Firebase Storage location.
  160. ///
  161. /// For example, you can pass in an `https://` download URL retrieved from
  162. /// `StorageReference.downloadURL(completion:)` or the `gs://` URL from
  163. /// `StorageReference.description`.
  164. /// - Parameter url: A gs:// or https:// URL to initialize the reference with.
  165. /// - Returns: An instance of StorageReference at the given child path.
  166. /// - Throws: Throws an Error if `url` is not associated with the `FirebaseApp` used to initialize
  167. /// this Storage instance.
  168. open func reference(for url: URL) throws -> StorageReference {
  169. ensureConfigured()
  170. var path: StoragePath
  171. do {
  172. path = try StoragePath.path(string: url.absoluteString)
  173. } catch let StoragePathError.storagePathError(message) {
  174. throw StorageError.pathError(message)
  175. } catch {
  176. throw StorageError.pathError("Internal error finding StoragePath: \(error)")
  177. }
  178. // If no default bucket exists (empty string), accept anything.
  179. if storageBucket == "" {
  180. return StorageReference(storage: self, path: path)
  181. }
  182. // If there exists a default bucket, throw if provided a different bucket.
  183. if path.bucket != storageBucket {
  184. throw StorageError
  185. .bucketMismatch("Provided bucket: `\(path.bucket)` does not match the Storage " +
  186. "bucket of the current instance: `\(storageBucket)`")
  187. }
  188. return StorageReference(storage: self, path: path)
  189. }
  190. /// Creates a `StorageReference` initialized at a location specified by the `path` parameter.
  191. /// - Parameter path: A relative path from the root of the storage bucket,
  192. /// for instance @"path/to/object".
  193. /// - Returns: An instance of `StorageReference` pointing to the given path.
  194. @objc(referenceWithPath:) open func reference(withPath path: String) -> StorageReference {
  195. return reference().child(path)
  196. }
  197. /// Configures the Storage SDK to use an emulated backend instead of the default remote backend.
  198. ///
  199. /// This method should be called before invoking any other methods on a new instance of `Storage`.
  200. /// - Parameter host: A string specifying the host.
  201. /// - Parameter port: The port specified as an `Int`.
  202. @objc open func useEmulator(withHost host: String, port: Int) {
  203. guard host.count > 0 else {
  204. fatalError("Invalid host argument: Cannot connect to empty host.")
  205. }
  206. guard port >= 0 else {
  207. fatalError("Invalid port argument: Port must be greater or equal to zero.")
  208. }
  209. guard fetcherService == nil else {
  210. fatalError("Cannot connect to emulator after Storage SDK initialization. " +
  211. "Call useEmulator(host:port:) before creating a Storage " +
  212. "reference or trying to load data.")
  213. }
  214. usesEmulator = true
  215. scheme = "http"
  216. self.host = host
  217. self.port = port
  218. }
  219. // MARK: - NSObject overrides
  220. @objc override open func copy() -> Any {
  221. let storage = Storage(app: app, bucket: storageBucket)
  222. storage.callbackQueue = callbackQueue
  223. return storage
  224. }
  225. @objc override open func isEqual(_ object: Any?) -> Bool {
  226. guard let ref = object as? Storage else {
  227. return false
  228. }
  229. return app == ref.app && storageBucket == ref.storageBucket
  230. }
  231. @objc override public var hash: Int {
  232. return app.hash ^ callbackQueue.hashValue
  233. }
  234. // MARK: - Internal and Private APIs
  235. private var fetcherService: GTMSessionFetcherService?
  236. var fetcherServiceForApp: GTMSessionFetcherService {
  237. guard let value = fetcherService else {
  238. fatalError("Internal error: fetcherServiceForApp not yet configured.")
  239. }
  240. return value
  241. }
  242. let dispatchQueue: DispatchQueue
  243. init(app: FirebaseApp, bucket: String) {
  244. self.app = app
  245. auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self,
  246. in: app.container)
  247. appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self,
  248. in: app.container)
  249. storageBucket = bucket
  250. host = "firebasestorage.googleapis.com"
  251. scheme = "https"
  252. port = 443
  253. fetcherService = nil // Configured in `ensureConfigured()`
  254. // Must be a serial queue.
  255. dispatchQueue = DispatchQueue(label: "com.google.firebase.storage")
  256. maxDownloadRetryTime = 600.0
  257. maxDownloadRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxDownloadRetryTime)
  258. maxOperationRetryTime = 120.0
  259. maxOperationRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxOperationRetryTime)
  260. maxUploadRetryTime = 600.0
  261. maxUploadRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxUploadRetryTime)
  262. }
  263. /// Map of apps to a dictionary of buckets to GTMSessionFetcherService.
  264. private static let fetcherServiceLock = NSObject()
  265. private static var fetcherServiceMap: [String: [String: GTMSessionFetcherService]] = [:]
  266. private static var retryWhenOffline: GTMSessionFetcherRetryBlock = {
  267. (suggestedWillRetry: Bool,
  268. error: Error?,
  269. response: @escaping GTMSessionFetcherRetryResponse) in
  270. var shouldRetry = suggestedWillRetry
  271. // GTMSessionFetcher does not consider being offline a retryable error, but we do, so we
  272. // special-case it here.
  273. if !shouldRetry, error != nil {
  274. shouldRetry = (error as? NSError)?.code == URLError.notConnectedToInternet.rawValue
  275. }
  276. response(shouldRetry)
  277. }
  278. private static func initFetcherServiceForApp(_ app: FirebaseApp,
  279. _ bucket: String,
  280. _ auth: AuthInterop?,
  281. _ appCheck: AppCheckInterop?)
  282. -> GTMSessionFetcherService {
  283. objc_sync_enter(fetcherServiceLock)
  284. defer { objc_sync_exit(fetcherServiceLock) }
  285. var bucketMap = fetcherServiceMap[app.name]
  286. if bucketMap == nil {
  287. bucketMap = [:]
  288. fetcherServiceMap[app.name] = bucketMap
  289. }
  290. var fetcherService = bucketMap?[bucket]
  291. if fetcherService == nil {
  292. fetcherService = GTMSessionFetcherService()
  293. fetcherService?.isRetryEnabled = true
  294. fetcherService?.retryBlock = retryWhenOffline
  295. fetcherService?.allowLocalhostRequest = true
  296. let authorizer = StorageTokenAuthorizer(
  297. googleAppID: app.options.googleAppID,
  298. fetcherService: fetcherService!,
  299. authProvider: auth,
  300. appCheck: appCheck
  301. )
  302. fetcherService?.authorizer = authorizer
  303. bucketMap?[bucket] = fetcherService
  304. }
  305. return fetcherService!
  306. }
  307. private let auth: AuthInterop?
  308. private let appCheck: AppCheckInterop?
  309. private let storageBucket: String
  310. private var usesEmulator: Bool = false
  311. var host: String
  312. var scheme: String
  313. var port: Int
  314. var maxDownloadRetryInterval: TimeInterval
  315. var maxOperationRetryInterval: TimeInterval
  316. var maxUploadRetryInterval: TimeInterval
  317. /// Performs a crude translation of the user provided timeouts to the retry intervals that
  318. /// GTMSessionFetcher accepts. GTMSessionFetcher times out operations if the time between
  319. /// individual
  320. /// retry attempts exceed a certain threshold, while our API contract looks at the total observed
  321. /// time of the operation (i.e. the sum of all retries).
  322. /// @param retryTime A timeout that caps the sum of all retry attempts
  323. /// @return A timeout that caps the timeout of the last retry attempt
  324. static func computeRetryInterval(fromRetryTime retryTime: TimeInterval) -> TimeInterval {
  325. // GTMSessionFetcher's retry starts at 1 second and then doubles every time. We use this
  326. // information to compute a best-effort estimate of what to translate the user provided retry
  327. // time into.
  328. // Note that this is the same as 2 << (log2(retryTime) - 1), but deemed more readable.
  329. var lastInterval = 1.0
  330. var sumOfAllIntervals = 1.0
  331. while sumOfAllIntervals < retryTime {
  332. lastInterval *= 2
  333. sumOfAllIntervals += lastInterval
  334. }
  335. return lastInterval
  336. }
  337. /// Configures the storage instance. Freezes the host setting.
  338. private func ensureConfigured() {
  339. guard fetcherService == nil else {
  340. return
  341. }
  342. fetcherService = Storage.initFetcherServiceForApp(app, storageBucket, auth, appCheck)
  343. if usesEmulator {
  344. fetcherService?.allowLocalhostRequest = true
  345. fetcherService?.allowedInsecureSchemes = ["http"]
  346. }
  347. }
  348. private static func bucket(for app: FirebaseApp) -> String {
  349. guard let bucket = app.options.storageBucket else {
  350. fatalError("No default Storage bucket found. Did you configure Firebase Storage properly?")
  351. }
  352. if bucket == "" {
  353. return Storage.bucket(for: app, urlString: "")
  354. } else {
  355. return Storage.bucket(for: app, urlString: "gs://\(bucket)/")
  356. }
  357. }
  358. private static func bucket(for app: FirebaseApp, urlString: String) -> String {
  359. if urlString == "" {
  360. return ""
  361. } else {
  362. guard let path = try? StoragePath.path(GSURI: urlString),
  363. path.object == nil || path.object == "" else {
  364. fatalError("Internal Error: Storage bucket cannot be initialized with a path")
  365. }
  366. return path.bucket
  367. }
  368. }
  369. }