Storage.swift 16 KB

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