Refactor a bunch of stuff for cgi fork
[blerg.git] / common / app.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <yajl/yajl_gen.h>
5 #include "app.h"
6
7 int parse_url_info(const char *url, struct url_info *info) {
8         const char *c;
9         int len;
10         info->contents = 0;
11
12         c = strchr(url, '/');
13         if (c == NULL) {
14                 len = strlen(url);
15         } else {
16                 len = c - url;
17         }
18         if (len == 0)
19                 return 0;
20         memcpy(info->author, url, len);
21         info->author[len] = 0;
22         info->contents |= URL_INFO_AUTHOR;
23
24         if (c == NULL || c[1] == 0)
25                 return info->contents;
26
27         info->record = strtoull(c + 1, NULL, 10);
28         info->contents |= URL_INFO_RECORD;
29
30         c = strchr(c, '-');
31         if (c == NULL || c[1] == 0)
32                 return info->contents;
33
34         info->record_to = strtoull(c + 1, NULL, 10);
35         info->contents |= URL_INFO_RECORD_TO;
36
37         return info->contents;
38 }
39
40 uint64_t *make_sequential_list(uint64_t from, uint64_t to) {
41         uint64_t len = to - from + 1;
42         uint64_t *list = malloc(len * sizeof(uint64_t));
43         uint64_t i;
44
45         for (i = 0; i < len; i++) {
46                 list[i] = from + i;
47         }
48
49         return list;
50 }
51
52 void json_generate_one_record(yajl_gen g, const char *author, struct blerg *b, uint64_t record) {
53         char *data;
54         char number[21];
55         int len;
56
57         if (!blerg_fetch(b, record, &data, &len)) {
58                 fprintf(stderr, "Could not fetch record\n");
59                 return;
60         }
61
62         yajl_gen_map_open(g);
63         if (author != NULL) {
64                 yajl_gen_string(g, "author", 6);
65                 yajl_gen_string(g, author, strlen(author));
66         }
67         yajl_gen_string(g, "record", 6);
68         snprintf(number, 21, "%llu", record);
69         yajl_gen_string(g, number, strlen(number));
70         yajl_gen_string(g, "timestamp", 9);
71         yajl_gen_integer(g, blerg_get_timestamp(b, record));
72         yajl_gen_string(g, "data", 4);
73         yajl_gen_string(g, data, len);
74         yajl_gen_map_close(g);
75
76         free(data);
77 }
78