blob: f990ed5eaa6ef6e280f1f20956e4ddf9ebb63a1e (
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
53
54
55
56
57
58
59
60
|
import Foundation
nonisolated 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 []
}
}
nonisolated(unsafe) private static let isoFormatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return formatter
}()
private static let alternativeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
private static func parseDate(_ input: String) -> Date? {
if let date = isoFormatter.date(from: input) {
return date
}
if let date = alternativeFormatter.date(from: input) {
return date
}
if let timestamp = Double(input) {
return Date(timeIntervalSince1970: timestamp)
}
return nil
}
}
|