summaryrefslogtreecommitdiff
path: root/Rune/API/NjallaClient.swift
blob: 8da52cb8d93551d7cdc99735fd37c1490d730c92 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import Foundation

struct NjallaClient: Sendable, Equatable {
    private let token: String
    private let endpoint = URL(string: "https://njal.la/api/1/")!

    init(token: String) {
        self.token = token
    }

    func call<T: Decodable>(_ method: String, params: [String: Any] = [:]) async throws -> T {
        var request = URLRequest(url: endpoint)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue("Njalla \(token)", forHTTPHeaderField: "Authorization")

        let body: [String: Any] = [
            "jsonrpc": "2.0",
            "method": method,
            "params": params,
            "id": "1"
        ]

        request.httpBody = try JSONSerialization.data(withJSONObject: body)

        let (data, response) = try await URLSession.shared.data(for: request)
        _ = (response as? HTTPURLResponse)?.statusCode ?? -1

        let decoder = JSONDecoder()
        let envelope = try decoder.decode(RPCResponse<T>.self, from: data)

        if let error = envelope.error {
            throw NjallaError.api(message: error.message)
        }

        guard let result = envelope.result else {
            throw NjallaError.missingResult
        }

        return result
    }

    func listDomains() async throws -> [Domain] {
        let response: DomainListResponse = try await call("list-domains")
        return response.domains
    }

    func getDomain(named domain: String) async throws -> Domain {
        try await call("get-domain", params: ["domain": domain])
    }

    func editDomain(named domain: String, request: DomainUpdateRequest) async throws -> Domain {
        var params = request.params
        params["domain"] = domain
        return try await call("edit-domain", params: params)
    }

    func listForwards(for domain: String) async throws -> [EmailForward] {
        let response: ForwardListResponse = try await call("list-forwards", params: ["domain": domain])
        return response.forwards
    }

    func addForward(forward: EmailForward) async throws {
        let _: EmptyResult = try await call(
            "add-forward",
            params: [
                "domain": forward.domain,
                "from": forward.from,
                "to": forward.to
            ]
        )
    }

    func removeForward(_ forward: EmailForward) async throws {
        let _: EmptyResult = try await call(
            "remove-forward",
            params: [
                "domain": forward.domain,
                "from": forward.from,
                "to": forward.to
            ]
        )
    }

    func listRecords(for domain: String) async throws -> [DNSRecord] {
        let response: RecordListResponse = try await call("list-records", params: ["domain": domain])
        return response.records.map { record in
            record.domain.isEmpty ? record.withDomain(domain) : record
        }
    }

    func addRecord(for domain: String, draft: DNSRecordDraft) async throws -> DNSRecord {
        try await call("add-record", params: draft.params(domain: domain))
    }

    func editRecord(for domain: String, id: String, draft: DNSRecordDraft) async throws -> DNSRecord {
        try await call("edit-record", params: draft.params(domain: domain, id: id))
    }

    func removeRecord(_ record: DNSRecord) async throws -> [DNSRecord] {
        let params: [String: Any] = [
            "domain": record.domain,
            "id": record.id,
            "name": record.name,
            "type": record.type
        ]
        let response: RecordListResponse = try await call("remove-record", params: params)
        return response.records.map { item in
            item.domain.isEmpty ? item.withDomain(record.domain) : item
        }
    }

    func listTokens() async throws -> [APIToken] {
        let response: TokenListResponse = try await call("list-tokens")
        return response.tokens
    }

    func addToken(request: TokenCreateRequest) async throws {
        let _: EmptyResult = try await call("add-token", params: request.params)
    }

    func removeToken(key: String) async throws {
        let _: EmptyResult = try await call("remove-token", params: ["key": key])
    }

    func getBalance() async throws -> WalletBalance {
        try await call("get-balance")
    }
}

enum NjallaError: LocalizedError {
    case api(message: String)
    case missingResult
    case networkFailure

    var errorDescription: String? {
        switch self {
        case .api(let message):
            return message
        case .missingResult:
            return "The API response did not include a result."
        case .networkFailure:
            return "Network request failed. Check your connection and try again."
        }
    }
}

extension Error {
    var userFacingMessage: String {
        if let njallaError = self as? NjallaError {
            return njallaError.localizedDescription
        }

        if let urlError = self as? URLError {
            switch urlError.code {
            case .cancelled:
                return urlError.localizedDescription
            default:
                return NjallaError.networkFailure.localizedDescription
            }
        }

        return localizedDescription
    }
}

private struct RPCResponse<Result: Decodable>: Decodable {
    let result: Result?
    let error: RPCError?
}

private struct RPCError: Decodable {
    let code: Int
    let message: String
}