-
Notifications
You must be signed in to change notification settings - Fork 2
/
api.c
440 lines (382 loc) · 9.72 KB
/
api.c
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/* api.c - Copyright (c) 2018, Sijmen J. Mulder (see LICENSE.md) */
#define USERAGENT "nostt (+https://github.com/sjmulder/nostt)"
#define ENDPOINT "https://teletekst-data.nos.nl/json/"
#define SUBST_CHAR '%'
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <wchar.h>
#include <curl/curl.h>
#include <json-c/json.h>
#include "api.h"
#define LEN(a) (sizeof(a)/sizeof(*(a)))
enum parsest {
PS_IN_TEXT,
PS_IN_TAG,
PS_IN_ATTRQUOTES
};
/* see jsonwrite() below */
struct jsonctx {
enum tterr err;
struct json_tokener *tokener;
struct json_object *object;
};
struct entity {
char seq[10];
wchar_t wc;
};
static char curlerrbuf[CURL_ERROR_SIZE];
/* indexed by ttcolor */
static const char *colornames[] = {
"black",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white"
};
static const struct entity entities[] = {
/* HTMLspecial */
{ "&qout;", 0x22 }, { "&", 0x26 },
{ "'", 0x27 }, { "<", 0x3C },
{ ">", 0x3E },
/* HTMLlat1 */
{ "Æ", 0xC6 }, { "Á", 0xC1 },
{ "Â", 0xC2 }, { "À", 0xC0 },
{ "Å", 0xC5 }, { "Ã", 0xC3 },
{ "Ä", 0xC4 }, { "Ç", 0xC7 },
{ "Ð", 0xD0 }, { "É", 0xC9 },
{ "Ê", 0xCA }, { "È", 0xC8 },
{ "Ë", 0xCB }, { "Í", 0xCD },
{ "Î", 0xCE }, { "Ì", 0xCC },
{ "Ï", 0xCF }, { "Ñ", 0xD1 },
{ "Ó", 0xD3 }, { "Ô", 0xD4 },
{ "Ò", 0xD2 }, { "Ø", 0xD8 },
{ "Õ", 0xD5 }, { "Ö", 0xD6 },
{ "Þ", 0xDE }, { "Ú", 0xDA },
{ "Û", 0xDB }, { "Ù", 0xD9 },
{ "Ü", 0xDC }, { "Ý", 0xDD },
{ "á", 0xE1 }, { "â", 0xE2 },
{ "æ", 0xE6 }, { "à", 0xE0 },
{ "å", 0xE5 }, { "ã", 0xE3 },
{ "ä", 0xE4 }, { "ç", 0xE7 },
{ "é", 0xE9 }, { "ê", 0xEA },
{ "è", 0xE8 }, { "ð", 0xF0 },
{ "ë", 0xEB }, { "í", 0xED },
{ "î", 0xEE }, { "ì", 0xEC },
{ "ï", 0xEF }, { "ñ", 0xF1 },
{ "ó", 0xF3 }, { "ô", 0xF4 },
{ "ò", 0xF2 }, { "ø", 0xF8 },
{ "õ", 0xF5 }, { "ö", 0xF6 },
{ "ß", 0xDF }, { "þ", 0xFE },
{ "ú", 0xFA }, { "û", 0xFB },
{ "ù", 0xF9 }, { "ü", 0xFC },
{ "ý", 0xFD }, { "ÿ", 0xFF }
};
static const struct ttattrs defattrs = {
/* fg */ TT_WHITE,
/* bg */ TT_BLACK
};
/* Callback for curl; directly forwards data to the JSON parser. */
static size_t
jsonwrite(char *ptr, size_t sz, size_t nmemb, void *userdata)
{
struct jsonctx *ctx = (struct jsonctx *)userdata;
enum json_tokener_error jsonerr;
if (ctx->err != TT_OK)
return 0;
if (ctx->object) {
ctx->err = TT_EDATA;
return 0;
}
ctx->object = json_tokener_parse_ex(ctx->tokener, ptr,
(int)(sz * nmemb));
if (!ctx->object) {
jsonerr = json_tokener_get_error(ctx->tokener);
if (jsonerr != json_tokener_continue)
ctx->err = TT_EDATA;
}
return sz * nmemb;
}
/* does nothing if no match */
static void
parsecolor(const char *str, const char *end, enum ttcolor *color)
{
size_t i, len;
for (i = 0; i < LEN(colornames); i++) {
len = strlen(colornames[i]);
if ((ptrdiff_t)len >= end - str &&
!strncmp(str, colornames[i], len)) {
*color = (enum ttcolor)i;
return;
}
}
}
/*
* Unescapes HTML entities. *endp will point to the first character
* past the escape sequence.
*/
static wchar_t
unescape(const char *sequence, const char **endp)
{
wchar_t wc;
size_t len, i;
if (*sequence != '&') {
/* assign wc first in case sequence=*endp */
wc = *sequence;
*endp = sequence + 1;
return wc;
}
if (!strncmp("&#x", sequence, 3)) {
wc = (wchar_t)strtol(sequence+3, (char **)endp, 16);
if (**endp == ';')
(*endp)++;
return wc;
}
for (i = 0; i < LEN(entities); i++) {
len = strlen(entities[i].seq);
if (!strncmp(entities[i].seq, sequence, len)) {
*endp = sequence + len;
return entities[i].wc;
}
}
*endp = sequence + 1;
return '&';
}
/*
* Parses class name lists like "red bg-white" into attrs->fg and
* attrs->bg, or leaves them untouched if not specified.
*/
static void
parsecolors(const char *str, const char *end, struct ttattrs *attrs)
{
enum ttcolor *color;
const char *wordend;
while (end - str > 3) {
if (memcmp("bg-", str, 3) == 0) {
color = &attrs->bg;
str += 3;
} else
color = &attrs->fg;
wordend = str+1;
while (wordend < end && !isspace(*wordend))
wordend++;
parsecolor(str, wordend, color);
str = wordend;
while (str < end && isspace(*str))
str++;
}
}
/*
* Very simple HTML parser. Only accepts the following sort of input:
*
* <span class="red bg-white">NOS</span> TELETEKST
* Nieuws <span class="cyan"><a href="#101">101</a></span>
* Sport <span class="cyan"><a href="#102">102</a></span>
*
* Every cell in the page is assigned, either with content, or with a
* space character.
*
* HTML element and attribute names themselves are ignored; if a tag
* contains quotes it is assumed to be a class list. Any tag with a '/'
* in it is considered a closing tag. Nesting is supported, but no
* self-closing tags and such.
*
* This may all seem horribly limited but it's only meant to parse the
* HTML output from the API, which it does.
*/
static enum tterr
parse(const char *html, struct ttpage *page)
{
const char *p;
wchar_t wc;
int line = 0;
int col = 0;
const char *openquote = NULL;
const char *closequote = NULL;
enum parsest state = PS_IN_TEXT;
struct ttattrs curattrs = defattrs;
struct ttattrs atstack[8];
int atdepth = 0;
atstack[0] = defattrs;
p = html;
while (line < TT_NLINES) {
/* clear rest of line if EOL or EOF */
if (*p == '\0' || *p == '\n') {
if (*p == '\n')
p++;
while (col < TT_NCOLS) {
page->attrs[line][col] = defattrs;
page->chars[line][col] = L' ';
col++;
}
line++;
col = 0;
continue;
}
if (*p == '&') {
wc = unescape(p, &p);
p--; /* offset the p++ later on */
} else
wc = *p;
switch (state) {
case PS_IN_TEXT:
switch (wc) {
case '<':
state = PS_IN_TAG;
if (++atdepth < (int)LEN(atstack))
atstack[atdepth] = curattrs;
break;
default:
/* ignore input beyond line length */
if (col < TT_NCOLS) {
page->chars[line][col] = wc;
page->attrs[line][col] =
curattrs;
col++;
}
break;
}
break;
case PS_IN_TAG:
switch (wc) {
case '/':
/*
* End tag, pop attrs. Twice, because we
* just pushed on the start of this
* closing tag too.
*/
if ((atdepth -= 2) < 0)
atdepth = 0;
else if (atdepth < (int)LEN(atstack))
curattrs = atstack[atdepth+1];
break;
case '"':
state = PS_IN_ATTRQUOTES;
openquote = p;
break;
case '>':
state = PS_IN_TEXT;
break;
}
break;
case PS_IN_ATTRQUOTES:
switch (wc) {
case '"':
state = PS_IN_TAG;
closequote = p;
break;
case '>':
state = PS_IN_TEXT;
closequote = p;
break;
}
if (state != PS_IN_ATTRQUOTES) {
/*
* We assume the attribute is 'class',
* so parse the colors.
*/
parsecolors(openquote+1, closequote,
&curattrs);
}
break;
}
p++;
}
return TT_OK;
}
enum tterr
tt_get(const char *id, struct ttpage *page)
{
enum tterr err = TT_OK;
char url[128];
CURL *curl = NULL;
long status;
struct jsonctx json;
struct json_object *jobj, *jval;
const char *html;
wchar_t *wcp;
int line, col;
struct curl_slist *list = NULL;
if (!id || !*id || !page)
return TT_EARG;
memset(&json, 0, sizeof(json));
snprintf(url, LEN(url), ENDPOINT "%s", id);
url[LEN(url)-1] = '\0';
json.tokener = json_tokener_new();
if (!(curl = curl_easy_init())) {
err = TT_ECURL;
goto cleanup;
}
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curlerrbuf);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USERAGENT);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, jsonwrite);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &json);
list = curl_slist_append(list, "Accept-Encoding: "
"application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
if (curl_easy_perform(curl) != CURLE_OK) {
err = TT_ECURL;
goto cleanup;
}
curl_slist_free_all(list);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status);
if (status < 200 || status >= 300) {
err = TT_EAPI;
goto cleanup;
}
jobj = json.object;
if (!jobj || !json_object_is_type(jobj, json_type_object)) {
err = TT_EDATA;
goto cleanup;
}
strncpy(page->id, id, LEN(page->id)-1);
page->id[LEN(page->id)-1] = '\0';
page->nextpage[0] = '\0';
page->nextsub[0] = '\0';
if (json_object_object_get_ex(jobj, "nextPage", &jval)) {
strncpy(page->nextpage, json_object_get_string(jval),
LEN(page->nextpage)-1);
page->nextpage[LEN(page->nextpage)-1] = '\0';
}
if (json_object_object_get_ex(jobj, "nextSubPage", &jval)) {
strncpy(page->nextsub, json_object_get_string(jval),
LEN(page->nextsub)-1);
page->nextsub[LEN(page->nextsub)-1] = '\0';
}
if (!json_object_object_get_ex(jobj, "content", &jval) ||
!(html = json_object_get_string(jval))) {
err = TT_EDATA;
goto cleanup;
}
parse(html, page);
/* Map block drawing characters */
for (line = 0; line < TT_NLINES; line++) {
for (col = 0; col < TT_NCOLS; col++) {
wcp = &page->chars[line][col];
if (*wcp >= 0xF000)
*wcp = SUBST_CHAR;
}
}
cleanup:
if (curl)
curl_easy_cleanup(curl);
if (json.tokener)
json_tokener_free(json.tokener);
return err;
}
const char *
tt_errstr(enum tterr err)
{
switch (err) {
case TT_OK: return "no error";
case TT_EARG: return "invalid argument";
case TT_ECURL: return curlerrbuf;
case TT_EAPI: return "API returned an error code";
case TT_EDATA: return "API returned invalid or unexpected data";
default: return "unknown error";
}
}