summaryrefslogtreecommitdiff
path: root/Sora/Data/MoebooruXMLParser.swift
blob: 105329987f1dd1bdb5f7d36c1b3f9ebb80ed43dd (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
import Foundation

class MoebooruXMLParser: NSObject, XMLParserDelegate {
    private var posts: [MoebooruPost] = []
    private var currentAttributes: [String: String] = [:]
    private var currentPost: MoebooruPost?

    func parse(data: Data) -> [MoebooruPost] {
        let parser = XMLParser(data: data)

        parser.delegate = self
        parser.parse()

        return posts
    }

    func parser(_: XMLParser, didStartElement elementName: String,
                namespaceURI _: String?, qualifiedName _: String?,
                attributes attributeDict: [String: String])
    {
        if elementName == "post" {
            currentAttributes = attributeDict

            if let id = Int(attributeDict["id"] ?? ""),
               let createdAtTimestamp = TimeInterval(attributeDict["created_at"] ?? "")
            {
                if let score = Int(attributeDict["score"] ?? ""),
                   let width = Int(attributeDict["width"] ?? ""),
                   let height = Int(attributeDict["height"] ?? "")
                {
                    posts.append(MoebooruPost(
                        id: id,
                        tags: attributeDict["tags"]?.components(separatedBy: " ") ?? [],
                        createdAt: Date(timeIntervalSince1970: createdAtTimestamp),
                        author: attributeDict["author"] ?? "",
                        source: URL(string: attributeDict["source"] ?? ""),
                        score: score,
                        fileURL: URL(string: attributeDict["file_url"] ?? ""),
                        previewURL: URL(string: attributeDict["preview_url"] ?? ""),
                        sampleURL: URL(string: attributeDict["sample_url"] ?? ""),
                        jpegURL: URL(string: attributeDict["jpeg_url"] ?? ""),
                        width: width,
                        height: height
                    ))
                }
            }
        }
    }
}