StorageMetadata.swift 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. * Never used API
  90. */
  91. @available(*, deprecated) @objc public let storageReference: StorageReference? = nil
  92. /**
  93. * Creates a Dictionary from the contents of the metadata.
  94. * @return A Dictionary that represents the contents of the metadata.
  95. */
  96. @objc open func dictionaryRepresentation() -> [String: AnyHashable] {
  97. let stringFromDate = StorageMetadata.RFC3339StringFromDate
  98. return [
  99. "bucket": bucket,
  100. "cacheControl": cacheControl,
  101. "contentDisposition": contentDisposition,
  102. "contentEncoding": contentEncoding,
  103. "contentLanguage": contentLanguage,
  104. "contentType": contentType,
  105. "md5Hash": md5Hash,
  106. "size": size != 0 ? size : nil,
  107. "generation": generation != 0 ? "\(generation)" : nil,
  108. "metageneration": metageneration != 0 ? "\(metageneration)" : nil,
  109. "timeCreated": timeCreated.map(stringFromDate),
  110. "updated": updated.map(stringFromDate),
  111. "name": path,
  112. ].compactMapValues { $0 }.merging(["metadata": customMetadata]) { current, _ in current }
  113. }
  114. /**
  115. * Determines if the current metadata represents a "file".
  116. */
  117. @objc public var isFile: Bool {
  118. return fileType == .file
  119. }
  120. // TODO: Nothing in the implementation ever sets `.folder`.
  121. /**
  122. * Determines if the current metadata represents a "folder".
  123. */
  124. @objc public var isFolder: Bool {
  125. return fileType == .folder
  126. }
  127. // MARK: - Public Initializers
  128. /**
  129. * Creates an empty instance of StorageMetadata.
  130. * @return An empty instance of StorageMetadata.
  131. */
  132. @objc override public convenience init() {
  133. self.init(dictionary: [:])
  134. }
  135. /**
  136. * Creates an instance of StorageMetadata from the contents of a dictionary.
  137. * @return An instance of StorageMetadata that represents the contents of a dictionary.
  138. */
  139. @objc public init(dictionary: [String: AnyHashable]) {
  140. initialMetadata = dictionary
  141. bucket = dictionary["bucket"] as? String ?? ""
  142. cacheControl = dictionary["cacheControl"] as? String ?? nil
  143. contentDisposition = dictionary["contentDisposition"] as? String ?? nil
  144. contentEncoding = dictionary["contentEncoding"] as? String ?? nil
  145. contentLanguage = dictionary["contentLanguage"] as? String ?? nil
  146. contentType = dictionary["contentType"] as? String ?? nil
  147. customMetadata = dictionary["metadata"] as? [String: String] ?? nil
  148. size = StorageMetadata.intFromDictionaryValue(dictionary["size"])
  149. generation = StorageMetadata.intFromDictionaryValue(dictionary["generation"])
  150. metageneration = StorageMetadata.intFromDictionaryValue(dictionary["metageneration"])
  151. timeCreated = StorageMetadata.dateFromRFC3339String(dictionary["timeCreated"])
  152. updated = StorageMetadata.dateFromRFC3339String(dictionary["updated"])
  153. md5Hash = dictionary["md5Hash"] as? String ?? nil
  154. // GCS "name" is our path, our "name" is just the last path component of the path
  155. if let name = dictionary["name"] as? String {
  156. path = name
  157. self.name = (name as NSString).lastPathComponent
  158. }
  159. fileType = .unknown
  160. }
  161. // MARK: - NSObject overrides
  162. @objc override open func copy() -> Any {
  163. let clone = StorageMetadata(dictionary: dictionaryRepresentation())
  164. clone.initialMetadata = initialMetadata
  165. return clone
  166. }
  167. @objc override open func isEqual(_ object: Any?) -> Bool {
  168. guard let ref = object as? StorageMetadata else {
  169. return false
  170. }
  171. return ref.dictionaryRepresentation() == dictionaryRepresentation()
  172. }
  173. @objc override public var hash: Int {
  174. return (dictionaryRepresentation() as NSDictionary).hash
  175. }
  176. @objc override public var description: String {
  177. return "\(type(of: self)) \(dictionaryRepresentation())"
  178. }
  179. // MARK: - Internal APIs
  180. func updatedMetadata() -> [String: AnyHashable] {
  181. return remove(matchingMetadata: dictionaryRepresentation(), oldMetadata: initialMetadata)
  182. }
  183. enum StorageMetadataType {
  184. case unknown
  185. case file
  186. case folder
  187. }
  188. var fileType: StorageMetadataType
  189. // MARK: - Private APIs and data
  190. private var initialMetadata: [String: AnyHashable]
  191. private static func intFromDictionaryValue(_ value: Any?) -> Int64 {
  192. if let value = value as? Int { return Int64(value) }
  193. if let value = value as? Int64 { return value }
  194. if let value = value as? String { return Int64(value) ?? 0 }
  195. return 0
  196. }
  197. private static let dateFormatter: DateFormatter = {
  198. let dateFormatter = DateFormatter()
  199. dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
  200. dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZZZZZ"
  201. dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
  202. return dateFormatter
  203. }()
  204. private static func dateFromRFC3339String(_ value: Any?) -> Date? {
  205. if let stringValue = value as? String {
  206. return dateFormatter.date(from: stringValue) ?? nil
  207. }
  208. return nil
  209. }
  210. static func RFC3339StringFromDate(_ date: Date) -> String {
  211. return dateFormatter.string(from: date)
  212. }
  213. private func remove(matchingMetadata: [String: AnyHashable],
  214. oldMetadata: [String: AnyHashable]) -> [String: AnyHashable] {
  215. var newMetadata = matchingMetadata
  216. for (key, oldValue) in oldMetadata {
  217. guard let newValue = newMetadata[key] else {
  218. // Adds 'NSNull' for entries that only exist in oldMetadata.
  219. newMetadata[key] = NSNull()
  220. continue
  221. }
  222. if let oldString = oldValue as? String,
  223. let newString = newValue as? String {
  224. if oldString == newString {
  225. newMetadata[key] = nil
  226. }
  227. } else if let oldDictionary = oldValue as? [String: AnyHashable],
  228. let newDictionary = newValue as? [String: AnyHashable] {
  229. let outDictionary = remove(matchingMetadata: newDictionary, oldMetadata: oldDictionary)
  230. if outDictionary.count == 0 {
  231. newMetadata[key] = nil
  232. } else {
  233. newMetadata[key] = outDictionary
  234. }
  235. }
  236. }
  237. return newMetadata
  238. }
  239. }