StorageMetadata.swift 8.7 KB

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