StorageMetadata.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. /**
  16. * Class which represents the metadata on an object in Firebase Storage.
  17. *
  18. * This metadata is
  19. * returned on successful operations, and can be used to retrieve download URLs, content types,
  20. * and a Storage reference to the object in question. Full documentation can be found in the
  21. * [GCS documentation](https://cloud.google.com/storage/docs/json_api/v1/objects#resource)
  22. */
  23. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  24. @objc(FIRStorageMetadata) open class StorageMetadata: NSObject,
  25. @unchecked Sendable /* TODO: sendable */ {
  26. // MARK: - Public APIs
  27. /**
  28. * The name of the bucket containing this object.
  29. */
  30. @objc public let bucket: String
  31. /**
  32. * Cache-Control directive for the object data.
  33. */
  34. @objc public var cacheControl: String?
  35. /**
  36. * Content-Disposition of the object data.
  37. */
  38. @objc public var contentDisposition: String?
  39. /**
  40. * Content-Encoding of the object data.
  41. */
  42. @objc public var contentEncoding: String?
  43. /**
  44. * Content-Language of the object data.
  45. */
  46. @objc public var contentLanguage: String?
  47. /**
  48. * Content-Type of the object data.
  49. */
  50. @objc public var contentType: String?
  51. /**
  52. * MD5 hash of the data; encoded using base64.
  53. */
  54. @objc public let md5Hash: String?
  55. /**
  56. * The content generation of this object. Used for object versioning.
  57. */
  58. @objc public let generation: Int64
  59. /**
  60. * User-provided metadata, in key/value pairs.
  61. */
  62. @objc public var customMetadata: [String: String]?
  63. /**
  64. * The version of the metadata for this object at this generation. Used
  65. * for preconditions and for detecting changes in metadata. A metageneration number is only
  66. * meaningful in the context of a particular generation of a particular object.
  67. */
  68. @objc public let metageneration: Int64
  69. /**
  70. * The name of this object, in gs://bucket/path/to/object.txt, this is object.txt.
  71. */
  72. @objc public internal(set) var name: String?
  73. /**
  74. * The full path of this object, in gs://bucket/path/to/object.txt, this is path/to/object.txt.
  75. */
  76. @objc public internal(set) var path: String?
  77. /**
  78. * Content-Length of the data in bytes.
  79. */
  80. @objc public let size: Int64
  81. /**
  82. * The creation time of the object in RFC 3339 format.
  83. */
  84. @objc public let timeCreated: Date?
  85. /**
  86. * The modification time of the object metadata in RFC 3339 format.
  87. */
  88. @objc public let updated: Date?
  89. /**
  90. * Never used API
  91. */
  92. @available(*, deprecated) @objc public let storageReference: StorageReference? = nil
  93. /**
  94. * Creates a Dictionary from the contents of the metadata.
  95. * @return A Dictionary that represents the contents of the metadata.
  96. */
  97. @objc open func dictionaryRepresentation() -> [String: AnyHashable] {
  98. let stringFromDate = StorageMetadata.RFC3339StringFromDate
  99. return [
  100. "bucket": bucket,
  101. "cacheControl": cacheControl,
  102. "contentDisposition": contentDisposition,
  103. "contentEncoding": contentEncoding,
  104. "contentLanguage": contentLanguage,
  105. "contentType": contentType,
  106. "md5Hash": md5Hash,
  107. "size": size != 0 ? size : nil,
  108. "generation": generation != 0 ? "\(generation)" : nil,
  109. "metageneration": metageneration != 0 ? "\(metageneration)" : nil,
  110. "timeCreated": timeCreated.map(stringFromDate),
  111. "updated": updated.map(stringFromDate),
  112. "name": path,
  113. ].compactMapValues { $0 }.merging(["metadata": customMetadata]) { current, _ in current }
  114. }
  115. /**
  116. * Determines if the current metadata represents a "file".
  117. */
  118. @objc public var isFile: Bool {
  119. return fileType == .file
  120. }
  121. // TODO: Nothing in the implementation ever sets `.folder`.
  122. /**
  123. * Determines if the current metadata represents a "folder".
  124. */
  125. @objc public var isFolder: Bool {
  126. return fileType == .folder
  127. }
  128. // MARK: - Public Initializers
  129. /**
  130. * Creates an empty instance of StorageMetadata.
  131. * @return An empty instance of StorageMetadata.
  132. */
  133. @objc override public convenience init() {
  134. self.init(dictionary: [:])
  135. }
  136. /**
  137. * Creates an instance of StorageMetadata from the contents of a dictionary.
  138. * @return An instance of StorageMetadata that represents the contents of a dictionary.
  139. */
  140. @objc public init(dictionary: [String: AnyHashable]) {
  141. initialMetadata = dictionary
  142. bucket = dictionary["bucket"] as? String ?? ""
  143. cacheControl = dictionary["cacheControl"] as? String ?? nil
  144. contentDisposition = dictionary["contentDisposition"] as? String ?? nil
  145. contentEncoding = dictionary["contentEncoding"] as? String ?? nil
  146. contentLanguage = dictionary["contentLanguage"] as? String ?? nil
  147. contentType = dictionary["contentType"] as? String ?? nil
  148. customMetadata = dictionary["metadata"] as? [String: String] ?? nil
  149. size = StorageMetadata.intFromDictionaryValue(dictionary["size"])
  150. generation = StorageMetadata.intFromDictionaryValue(dictionary["generation"])
  151. metageneration = StorageMetadata.intFromDictionaryValue(dictionary["metageneration"])
  152. timeCreated = StorageMetadata.dateFromRFC3339String(dictionary["timeCreated"])
  153. updated = StorageMetadata.dateFromRFC3339String(dictionary["updated"])
  154. md5Hash = dictionary["md5Hash"] as? String ?? nil
  155. // GCS "name" is our path, our "name" is just the last path component of the path
  156. if let name = dictionary["name"] as? String {
  157. path = name
  158. self.name = (name as NSString).lastPathComponent
  159. }
  160. fileType = .unknown
  161. }
  162. // MARK: - NSObject overrides
  163. @objc override open func copy() -> Any {
  164. let clone = StorageMetadata(dictionary: dictionaryRepresentation())
  165. clone.initialMetadata = initialMetadata
  166. return clone
  167. }
  168. @objc override open func isEqual(_ object: Any?) -> Bool {
  169. guard let ref = object as? StorageMetadata else {
  170. return false
  171. }
  172. return ref.dictionaryRepresentation() == dictionaryRepresentation()
  173. }
  174. @objc override public var hash: Int {
  175. return (dictionaryRepresentation() as NSDictionary).hash
  176. }
  177. @objc override public var description: String {
  178. return "\(type(of: self)) \(dictionaryRepresentation())"
  179. }
  180. // MARK: - Internal APIs
  181. func updatedMetadata() -> [String: AnyHashable] {
  182. return remove(matchingMetadata: dictionaryRepresentation(), oldMetadata: initialMetadata)
  183. }
  184. enum StorageMetadataType {
  185. case unknown
  186. case file
  187. case folder
  188. }
  189. var fileType: StorageMetadataType
  190. // MARK: - Private APIs and data
  191. private var initialMetadata: [String: AnyHashable]
  192. private static func intFromDictionaryValue(_ value: Any?) -> Int64 {
  193. if let value = value as? Int { return Int64(value) }
  194. if let value = value as? Int64 { return value }
  195. if let value = value as? String { return Int64(value) ?? 0 }
  196. return 0
  197. }
  198. private static let dateFormatter: DateFormatter = {
  199. let dateFormatter = DateFormatter()
  200. dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
  201. dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZZZZZ"
  202. dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
  203. return dateFormatter
  204. }()
  205. private static func dateFromRFC3339String(_ value: Any?) -> Date? {
  206. if let stringValue = value as? String {
  207. return dateFormatter.date(from: stringValue) ?? nil
  208. }
  209. return nil
  210. }
  211. static func RFC3339StringFromDate(_ date: Date) -> String {
  212. return dateFormatter.string(from: date)
  213. }
  214. private func remove(matchingMetadata: [String: AnyHashable],
  215. oldMetadata: [String: AnyHashable]) -> [String: AnyHashable] {
  216. var newMetadata = matchingMetadata
  217. for (key, oldValue) in oldMetadata {
  218. guard let newValue = newMetadata[key] else {
  219. // Adds 'NSNull' for entries that only exist in oldMetadata.
  220. newMetadata[key] = NSNull()
  221. continue
  222. }
  223. if let oldString = oldValue as? String,
  224. let newString = newValue as? String {
  225. if oldString == newString {
  226. newMetadata[key] = nil
  227. }
  228. } else if let oldDictionary = oldValue as? [String: AnyHashable],
  229. let newDictionary = newValue as? [String: AnyHashable] {
  230. let outDictionary = remove(matchingMetadata: newDictionary, oldMetadata: oldDictionary)
  231. if outDictionary.count == 0 {
  232. newMetadata[key] = nil
  233. } else {
  234. newMetadata[key] = outDictionary
  235. }
  236. }
  237. }
  238. return newMetadata
  239. }
  240. }