StorageGetDownloadURLTask.swift 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. #if COCOAPODS
  16. import GTMSessionFetcher
  17. #else
  18. import GTMSessionFetcherCore
  19. #endif
  20. /**
  21. * Task which provides the ability to get a download URL for an object in Firebase Storage.
  22. */
  23. class StorageGetDownloadURLTask: StorageTask, StorageTaskManagement {
  24. private var fetcher: GTMSessionFetcher?
  25. private var fetcherCompletion: ((Data?, NSError?) -> Void)?
  26. private var taskCompletion: ((_ downloadURL: URL?, _: Error?) -> Void)?
  27. init(reference: StorageReference,
  28. fetcherService: GTMSessionFetcherService,
  29. queue: DispatchQueue,
  30. completion: ((_: URL?, _: Error?) -> Void)?) {
  31. super.init(reference: reference, service: fetcherService, queue: queue)
  32. taskCompletion = completion
  33. }
  34. deinit {
  35. self.fetcher?.stopFetching()
  36. }
  37. /**
  38. * Prepares a task and begins execution.
  39. */
  40. func enqueue() {
  41. if let completion = taskCompletion {
  42. taskCompletion = { (url: URL?, error: Error?) in
  43. completion(url, error)
  44. // Reference self in completion handler in order to retain self until completion is called.
  45. self.taskCompletion = nil
  46. }
  47. }
  48. dispatchQueue.async { [weak self] in
  49. guard let self = self else { return }
  50. var request = self.baseRequest
  51. request.httpMethod = "GET"
  52. request.timeoutInterval = self.reference.storage.maxOperationRetryTime
  53. let fetcher = self.fetcherService.fetcher(with: request)
  54. fetcher.comment = "GetDownloadURLTask"
  55. self.fetcher = fetcher
  56. self.fetcherCompletion = { [weak self] (data: Data?, error: NSError?) in
  57. guard let self = self else { return }
  58. var downloadURL: URL?
  59. if let error = error {
  60. if self.error == nil {
  61. self.error = StorageErrorCode.error(withServerError: error, ref: self.reference)
  62. }
  63. } else {
  64. if let data = data,
  65. let responseDictionary = try? JSONSerialization
  66. .jsonObject(with: data) as? [String: Any] {
  67. downloadURL = self.downloadURLFromMetadataDictionary(responseDictionary)
  68. if downloadURL == nil {
  69. self.error = NSError(domain: StorageErrorDomain,
  70. code: StorageErrorCode.unknown.rawValue,
  71. userInfo: [NSLocalizedDescriptionKey:
  72. "Failed to retrieve a download URL."])
  73. }
  74. } else {
  75. self.error = StorageErrorCode.error(withInvalidRequest: data)
  76. }
  77. }
  78. self.taskCompletion?(downloadURL, self.error)
  79. self.fetcherCompletion = nil
  80. }
  81. self.fetcher?.beginFetch { [weak self] data, error in
  82. self?.fetcherCompletion?(data, error as? NSError)
  83. }
  84. }
  85. }
  86. func downloadURLFromMetadataDictionary(_ dictionary: [String: Any]) -> URL? {
  87. let downloadTokens = dictionary["downloadTokens"]
  88. guard let downloadTokens = downloadTokens as? String,
  89. downloadTokens.count > 0 else {
  90. return nil
  91. }
  92. let downloadTokenArray = downloadTokens.components(separatedBy: ",")
  93. let bucket = dictionary["bucket"] ?? "<error: missing bucket>"
  94. let path = dictionary["name"] as? String ?? "<error: missing path name>"
  95. let fullPath = "/v0/b/\(bucket)/o/\(StorageUtils.GCSEscapedString(path))"
  96. var components = URLComponents()
  97. components.scheme = reference.storage.scheme
  98. components.host = reference.storage.host
  99. components.port = reference.storage.port
  100. components.percentEncodedPath = fullPath
  101. // The backend can return an arbitrary number of download tokens, but we only expose the first
  102. // token via the download URL.
  103. let altItem = URLQueryItem(name: "alt", value: "media")
  104. let tokenItem = URLQueryItem(name: "token", value: downloadTokenArray[0])
  105. components.queryItems = [altItem, tokenItem]
  106. return components.url
  107. }
  108. }