diff options
| author | Fuwn <[email protected]> | 2025-02-27 16:46:41 -0800 |
|---|---|---|
| committer | Fuwn <[email protected]> | 2025-02-27 16:46:41 -0800 |
| commit | ec2feb28f80d1e4667fe8b0ea489e4d65339934f (patch) | |
| tree | d1ea7ad4f91ee36cea0f4ff704ec03ca2702f41d /Sora/Data/Danbooru/DanbooruPostParser.swift | |
| parent | feat: Development commit (diff) | |
| download | sora-testing-ec2feb28f80d1e4667fe8b0ea489e4d65339934f.tar.xz sora-testing-ec2feb28f80d1e4667fe8b0ea489e4d65339934f.zip | |
feat: Development commit
Diffstat (limited to 'Sora/Data/Danbooru/DanbooruPostParser.swift')
| -rw-r--r-- | Sora/Data/Danbooru/DanbooruPostParser.swift | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/Sora/Data/Danbooru/DanbooruPostParser.swift b/Sora/Data/Danbooru/DanbooruPostParser.swift new file mode 100644 index 0000000..fa62b5b --- /dev/null +++ b/Sora/Data/Danbooru/DanbooruPostParser.swift @@ -0,0 +1,52 @@ +import Foundation + +class DanbooruPostParser { + private let data: Data + + init(data: Data) { + self.data = data + } + + func parse() -> [BooruPost] { + let decoder = JSONDecoder() + + decoder.dateDecodingStrategy = .custom { decoder in + self.parseDate( + try (try decoder.singleValueContainer()).decode(String.self) + ) ?? Date() + } + + do { + return try decoder.decode([DanbooruPost].self, from: data).compactMap { post in + post.toBooruPost() + } + } catch { + return [] + } + } + + private func parseDate(_ input: String) -> Date? { + let isoFormatter = ISO8601DateFormatter() + + isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + + if let date = isoFormatter.date(from: input) { + return date + } + + let alternativeFormatter = DateFormatter() + + alternativeFormatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy" + alternativeFormatter.locale = Locale(identifier: "en_US_POSIX") + + if let date = alternativeFormatter.date(from: input) { + return date + } + + if let timestamp = Double(input) { + return Date(timeIntervalSince1970: timestamp) + } + + return nil + } +} |