StorageMetadata.swift 8.7 KB

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