summaryrefslogtreecommitdiff
path: root/src/response.zig
blob: a37013386a3f7fda1b90ca0359730ebb18097cb1 (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
const std = @import("std");
const Request = @import("request.zig");
const Types = @import("types.zig");

pub const Response = @This();

pub const default_parse_options = std.json.ParseOptions{
    .ignore_unknown_fields = true,
    .duplicate_field_behavior = .@"error",
};

allocator: std.mem.Allocator,
data: Data,

pub const Data = union(enum) {
    TorrentGet: TorrentGet,
    TorrentAdd: TorrentAdd,
};

pub fn parseBody(
    allocator: std.mem.Allocator,
    method: Request.Method,
    body: []const u8,
    parseOptions: ?std.json.ParseOptions,
) !Response {
    @setEvalBranchQuota(10000);
    switch (method) {
        .@"torrent-get" => {
            const decoded = try std.json.parseFromSlice(
                TorrentGet,
                allocator,
                body,
                parseOptions orelse default_parse_options,
            );
            return Response{
                .data = Data{ .TorrentGet = decoded },
                .allocator = allocator,
            };
        },
        .@"torrent-add" => {
            const decoded = try std.json.parseFromSlice(
                TorrentAdd,
                allocator,
                body,
                parseOptions orelse default_parse_options,
            );
            return Response{
                .data = Data{ .TorrentAdd = decoded },
                .allocator = allocator,
            };
        },
        else => unreachable,
    }
}

pub fn deinit(self: *Response) void {
    std.json.parseFree(@TypeOf(self.data), self.allocator, self.*.data);
}

pub const TorrentGet = struct {
    pub const Arguments = struct {
        torrents: ?[]Types.Torrent = null,
    };
    result: []const u8,
    arguments: @This().Arguments,
};

pub const TorrentAdd = struct {
    pub const Arguments = struct {
        @"torrent-added": ?struct {
            hashString: []const u8,
            id: u64,
            name: []const u8,
        } = null,
    };
    result: []const u8,
    arguments: @This().Arguments,
};