summaryrefslogtreecommitdiff
path: root/libgs/src/timeline.c
blob: fa0a2e81ffecfb1ba797531e7f735e409d233cbb (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 <pthread.h>
#include <jansson.h>
#include "timeline.h"
#include "auth.h"
#include "config.h"
#include "http.h"
#include "string-util.h"
#include "log.h"

struct gs_timeline *gs_timeline_from_json(const char *json_data)
{
    struct gs_timeline *t;
    json_t *root;
    json_error_t error;

    root = json_loads(json_data, 0, &error);
    if (!root) {
        gs_log(GS_WARNING, "timeline_from_json", "json root it null");
        return NULL;
    }

    if (!json_is_array(root)) {
        gs_log(GS_WARNING, "timeline_from_json", "json root is not array");
        json_decref(root);
        return NULL;
    }

    t = calloc(1, sizeof(struct gs_timeline));
    if (!t) {
        err(1, NULL);
        json_decref(root);
        return NULL;
    }

    t->size = json_array_size(root);
    t->statuses = calloc(t->size, sizeof(struct status *));
    if (!(t->statuses)) {
        err(1, NULL);
        gs_timeline_free(t);
        json_decref(root);
        return NULL;
    }

    json_t *data;
    for (size_t i = 0; i < t->size; i++) {
        data = json_array_get(root, i);
        if (!data)
            goto error;
        t->statuses[i] = gs_status_from_json_t(data);
        if (!(t->statuses[i]))
            goto error;
    }
    json_decref(root);
    return t;

error:
    gs_timeline_free(t);
    json_decref(root);
    return NULL;
}

void gs_timeline_free(struct gs_timeline *t)
{
    for (size_t i = 0; i < t->size; i++) {
        if (t->statuses[i])
            gs_status_free(t->statuses[i]);
    }
    free(t->statuses);
    free(t);
}

struct gs_timeline *gs_timeline_get(GSClient *c, const char *max_id, 
        const char *since_id, const char *min_id, int limit)
{
    char *resp;
    struct gs_timeline *t;

    resp = (char *)gs_client_do_api(c, 1, "/api/v1/timelines/home", NULL);
    if (!resp) {
        return NULL;
    }

    t = gs_timeline_from_json(resp);
    free(resp);
    if (!t) {
        return NULL;
    }

    return t;
}