summaryrefslogtreecommitdiff
path: root/Sora/Data/Danbooru/DanbooruPostParser.swift
blob: fa62b5be29aeaac1537ca05269b760d355ae0983 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
  }
}