Storage.swift 16 KB

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