summaryrefslogtreecommitdiff
path: root/libgs/src/account.c
blob: ecf3c28a4cee790c6f47fb3bbc630cee1f764af4 (plain)
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
#define _POSIX_C_SOURCE 200809L
#include <err.h>
#include <string.h>
#include <jansson.h>
#include "account.h"
#include "log.h"

struct gs_account *gs_account_from_json(const char *json_data)
{
    struct gs_account *a;
    json_t *root;
    json_error_t error;

    root = json_loads(json_data, 0, &error);
    if (!root) {
        gs_log(GS_WARNING, "gs_account_from_json", 
                "json parse error: line %d: %s", error.line, error.text);
        return NULL;
    }

    a = gs_account_from_json_t(root);
    json_decref(root);
    return a;
}

struct gs_account *gs_account_from_json_t(const json_t *root)
{
    struct gs_account *a;
    if (!root) {
        gs_log(GS_WARNING, "gs_account_from_json_t", "json data is null");
        return NULL;
    }

    if (!json_is_object(root)) {
        gs_log(GS_WARNING, "gs_account_from_json_t", 
                "json root is not object");
        return NULL;
    }

    a = calloc(1, sizeof(struct gs_account));
    if (!a) {
        err(1, "gs_account_from_json_t");
        return NULL;
    }

    json_t *id = json_object_get(root, "id");
    if (json_is_string(id)) {
        a->id = strdup(json_string_value(id));
    }

    json_t *username = json_object_get(root, "username");
    if (json_is_string(username)) {
        a->username = strdup(json_string_value(username));
    }

    json_t *acct = json_object_get(root, "acct");
    if (json_is_string(acct)) {
        a->acct = strdup(json_string_value(acct));
    }

    json_t *display_name = json_object_get(root, "display_name");
    if (json_is_string(display_name)) {
        a->display_name = strdup(json_string_value(display_name));
    }

    return a;
}

void gs_account_free(struct gs_account *a)
{
    if (a->id)
        free(a->id);
    if (a->username)
        free(a->username);
    if (a->acct)
        free(a->acct);
    if (a->display_name)
        free(a->display_name);
    if (a->note)
        free(a->note);
    if (a->url)
        free(a->url);
    if (a->avatar)
        free(a->avatar);
    if (a->avatar_static)
        free(a->avatar_static);
    if (a->header)
        free(a->header);
    if (a->header_static)
        free(a->header_static);
    free(a);
}