summaryrefslogtreecommitdiff
path: root/Hutch/Networking/PasteService.swift
blob: 92a618e36de4814fe0c684d59b9b738b6ef89c74 (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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import Foundation

struct PasteListPage: Decodable, Sendable {
    let results: [Paste]
    let cursor: String?
}

final class PasteService: Sendable {
    private let client: SRHTClient

    init(client: SRHTClient) {
        self.client = client
    }

    private static let listQuery = """
    query pastes($cursor: Cursor) {
        pastes(cursor: $cursor) {
            results {
                id
                created
                visibility
                files {
                    filename
                    hash
                }
                user {
                    canonicalName
                }
            }
            cursor
        }
    }
    """

    private static let detailQuery = """
    query paste($id: String!) {
        paste(id: $id) {
            id
            created
            visibility
            files {
                filename
                hash
                contents
            }
            user {
                canonicalName
            }
        }
    }
    """

    private static let createMutation = """
    mutation createPaste($files: [Upload!]!, $visibility: Visibility!) {
        create(files: $files, visibility: $visibility) {
            id
            created
            visibility
            files {
                filename
                hash
                contents
            }
            user {
                canonicalName
            }
        }
    }
    """

    private static let updateMutation = """
    mutation updatePaste($id: String!, $visibility: Visibility!) {
        update(id: $id, visibility: $visibility) {
            id
            created
            visibility
            files {
                filename
                hash
                contents
            }
            user {
                canonicalName
            }
        }
    }
    """

    private static let deleteMutation = """
    mutation deletePaste($id: String!) {
        delete(id: $id) {
            id
            created
            visibility
            files {
                filename
                hash
            }
            user {
                canonicalName
            }
        }
    }
    """

    private static let cacheKey = "paste.pastes"

    func listPastes(cursor: String?, useCache: Bool) async throws -> PasteListPage {
        let variables = cursor.map { ["cursor": $0 as any Sendable] }
        let result: PasteListResponse
        if useCache, cursor == nil {
            let cached = try await client.executeCached(
                service: .paste,
                query: Self.listQuery,
                variables: variables,
                responseType: PasteListResponse.self,
                cacheKey: APICacheKeys.pasteList(cursor: cursor),
                resourceType: .pasteList,
                ttl: APICacheTTLs.ticketList,
                policy: .cacheFirstThenRefresh
            )
            result = cached.value
        } else {
            result = try await client.execute(
                service: .paste,
                query: Self.listQuery,
                variables: variables,
                responseType: PasteListResponse.self
            )
        }
        return result.pastes ?? PasteListPage(results: [], cursor: nil)
    }

    func loadCachedPastes() async -> PasteListPage? {
        guard let data = await client.cachedPayload(forKey: APICacheKeys.pasteList()) ?? client.responseCache.get(forKey: Self.cacheKey) else {
            return nil
        }

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .srhtFlexible
        guard let response = try? decoder.decode(GraphQLResponse<PasteListResponse>.self, from: data) else {
            return nil
        }
        return response.data?.pastes
    }

    func loadPaste(id: String) async throws -> Paste? {
        let result = try await client.execute(
            service: .paste,
            query: Self.detailQuery,
            variables: ["id": id],
            responseType: PasteDetailResponse.self
        )
        return result.paste
    }

    func createPaste(files: [PasteUploadDraft], visibility: Visibility) async throws -> Paste {
        let uploadFiles = normalizedUploadFiles(from: files)
        let variables: [String: any Sendable] = [
            "files": [String?](repeating: nil, count: uploadFiles.count),
            "visibility": visibility.rawValue
        ]

        let result = try await client.executeMultipartFiles(
            service: .paste,
            query: Self.createMutation,
            variables: variables,
            files: uploadFiles.enumerated().map { index, file in
                MultipartUploadFile(
                    variablePath: "files.\(index)",
                    fileData: file.data,
                    fileName: file.fileName,
                    mimeType: "text/plain"
                )
            },
            responseType: CreatePasteResponse.self
        )
        await invalidatePasteCaches()
        return result.create
    }

    func updateVisibility(id: String, visibility: Visibility) async throws -> Paste? {
        let result = try await client.execute(
            service: .paste,
            query: Self.updateMutation,
            variables: ["id": id, "visibility": visibility.rawValue],
            responseType: UpdatePasteResponse.self
        )
        await invalidatePasteCaches()
        return result.update
    }

    func deletePaste(id: String) async throws -> Paste? {
        let result = try await client.execute(
            service: .paste,
            query: Self.deleteMutation,
            variables: ["id": id],
            responseType: DeletePasteResponse.self
        )
        await invalidatePasteCaches()
        return result.delete
    }

    func loadContents(from url: URL) async throws -> String {
        try await client.fetchText(url: url)
    }

    private func normalizedUploadFiles(from files: [PasteUploadDraft]) -> [(fileName: String, data: Data)] {
        files.compactMap { draft in
            let text = draft.contents
            guard let data = text.data(using: .utf8) else {
                return nil
            }

            return (draft.filename, data)
        }
    }

    private func invalidatePasteCaches() async {
        await client.invalidateCache(prefix: APICacheKeys.prefix(SRHTService.paste.rawValue, "pastes"))
    }
}

private struct PasteListResponse: Decodable, Sendable {
    let pastes: PasteListPage?
}

private struct PasteDetailResponse: Decodable, Sendable {
    let paste: Paste?
}

private struct CreatePasteResponse: Decodable, Sendable {
    let create: Paste
}

private struct UpdatePasteResponse: Decodable, Sendable {
    let update: Paste?
}

private struct DeletePasteResponse: Decodable, Sendable {
    let delete: Paste?
}