StorageMetadata.swift 8.8 KB

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