Storage.swift 16 KB

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