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

struct account *account_from_json(const char *json_data)
{
    struct account *a;
    json_t *root;
    json_error_t error;

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

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

struct account *account_from_json_t(const json_t *root)
{
    struct account *a;
    if (!root) {
        log_msg(LOG_WARNING, "account_from_json_t", "json data is null");
        return NULL;
    }

    if (!json_is_object(root)) {
        log_msg(LOG_WARNING, "account_from_json_t", "json root is not object");
        return NULL;
    }

    a = calloc(1, sizeof(struct account));
    if (!a) {
        err(1, "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 account_free(struct 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);
}