From b81e4d0a9ead37be752de9d6e9417959ac1e0d62 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Sun, 22 Sep 2019 18:57:33 -0400 Subject: [PATCH] Tweaks to support decoding Pixelfed instance response --- Pachyderm/Model/Instance.swift | 45 ++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/Pachyderm/Model/Instance.swift b/Pachyderm/Model/Instance.swift index c0b20ae1..77034bab 100644 --- a/Pachyderm/Model/Instance.swift +++ b/Pachyderm/Model/Instance.swift @@ -12,19 +12,49 @@ public class Instance: Decodable { public let uri: String public let title: String public let description: String - public let email: String + public let email: String? public let version: String public let urls: [String: URL] - - // pleroma doesn't currently implement these + public let thumbnail: URL? public let languages: [String]? + public let stats: Stats? + + // pleroma doesn't currently implement these public let contactAccount: Account? // MARK: Unofficial additions to the Mastodon API. - public let stats: Stats? - public let thumbnail: URL? public let maxStatusCharacters: Int? + // we need a custom decoder, because all API-compatible implementations don't return some data in the same format + public required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.uri = try container.decode(String.self, forKey: .uri) + self.title = try container.decode(String.self, forKey: .title) + self.description = try container.decode(String.self, forKey: .description) + self.email = try container.decodeIfPresent(String.self, forKey: .email) + self.version = try container.decode(String.self, forKey: .version) + if let urls = try? container.decodeIfPresent([String: URL].self, forKey: .urls) { + self.urls = urls + } else { + self.urls = [:] + } + + self.languages = try? container.decodeIfPresent([String].self, forKey: .languages) + self.contactAccount = try? container.decodeIfPresent(Account.self, forKey: .contactAccount) + + self.stats = try? container.decodeIfPresent(Stats.self, forKey: .stats) + self.thumbnail = try? container.decodeIfPresent(URL.self, forKey: .thumbnail) + if let maxStatusCharacters = try? container.decodeIfPresent(Int.self, forKey: .maxStatusCharacters) { + self.maxStatusCharacters = maxStatusCharacters + } else if let str = try? container.decodeIfPresent(String.self, forKey: .maxStatusCharacters), + let maxStatusCharacters = Int(str, radix: 10) { + self.maxStatusCharacters = maxStatusCharacters + } else { + self.maxStatusCharacters = nil + } + + } + private enum CodingKeys: String, CodingKey { case uri case title @@ -32,11 +62,12 @@ public class Instance: Decodable { case email case version case urls + case thumbnail case languages + case stats + case contactAccount = "contact_account" - case stats - case thumbnail case maxStatusCharacters = "max_toot_chars" } }