StorageGetDownloadURLTask.swift 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. internal 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. internal 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. internal func enqueue() {
  41. weak var weakSelf = self
  42. dispatchQueue.async {
  43. guard let strongSelf = weakSelf else { return }
  44. var request = strongSelf.baseRequest
  45. request.httpMethod = "GET"
  46. request.timeoutInterval = strongSelf.reference.storage.maxOperationRetryTime
  47. let callback = strongSelf.taskCompletion
  48. strongSelf.taskCompletion = nil
  49. let fetcher = strongSelf.fetcherService.fetcher(with: request)
  50. fetcher.comment = "GetDownloadURLTask"
  51. strongSelf.fetcher = fetcher
  52. strongSelf.fetcherCompletion = { (data: Data?, error: NSError?) in
  53. var downloadURL: URL?
  54. if let error = error {
  55. if self.error == nil {
  56. self.error = StorageErrorCode.error(withServerError: error, ref: self.reference)
  57. }
  58. } else {
  59. if let data = data,
  60. let responseDictionary = try? JSONSerialization
  61. .jsonObject(with: data) as? [String: Any] {
  62. downloadURL = strongSelf.downloadURLFromMetadataDictionary(responseDictionary)
  63. if downloadURL == nil {
  64. self.error = NSError(domain: StorageErrorDomain,
  65. code: StorageErrorCode.unknown.rawValue,
  66. userInfo: [NSLocalizedDescriptionKey:
  67. "Failed to retrieve a download URL."])
  68. }
  69. } else {
  70. self.error = StorageErrorCode.error(withInvalidRequest: data)
  71. }
  72. }
  73. callback?(downloadURL, self.error)
  74. self.fetcherCompletion = nil
  75. }
  76. strongSelf.fetcher?.beginFetch { data, error in
  77. let strongSelf = weakSelf
  78. if let fetcherCompletion = strongSelf?.fetcherCompletion {
  79. fetcherCompletion(data, error as? NSError)
  80. }
  81. }
  82. }
  83. }
  84. internal func downloadURLFromMetadataDictionary(_ dictionary: [String: Any]) -> URL? {
  85. let downloadTokens = dictionary["downloadTokens"]
  86. guard let downloadTokens = downloadTokens as? String,
  87. downloadTokens.count > 0 else {
  88. return nil
  89. }
  90. let downloadTokenArray = downloadTokens.components(separatedBy: ",")
  91. let bucket = dictionary["bucket"] ?? "<error: missing bucket>"
  92. let path = dictionary["name"] as? String ?? "<error: missing path name>"
  93. let fullPath = "/v0/b/\(bucket)/o/\(StorageUtils.GCSEscapedString(path))"
  94. var components = URLComponents()
  95. components.scheme = reference.storage.scheme
  96. components.host = reference.storage.host
  97. components.port = reference.storage.port
  98. components.percentEncodedPath = fullPath
  99. // The backend can return an arbitrary number of download tokens, but we only expose the first
  100. // token via the download URL.
  101. let altItem = URLQueryItem(name: "alt", value: "media")
  102. let tokenItem = URLQueryItem(name: "token", value: downloadTokenArray[0])
  103. components.queryItems = [altItem, tokenItem]
  104. return components.url
  105. }
  106. }