2.62
mastoapi.c
1/* snac - A simple, minimalistic ActivityPub instance */
2/* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
3
4#ifndef NO_MASTODON_API
5
6#include "xs.h"
7#include "xs_hex.h"
8#include "xs_openssl.h"
9#include "xs_json.h"
10#include "xs_io.h"
11#include "xs_time.h"
12#include "xs_glob.h"
13#include "xs_set.h"
14#include "xs_random.h"
15#include "xs_url.h"
16#include "xs_mime.h"
17#include "xs_match.h"
18
19#include "snac.h"
20
21#include <sys/time.h>
22
23static xs_str *random_str(void)
24/* just what is says in the tin */
25{
26 unsigned int data[4] = {0};
27
28 xs_rnd_buf(data, sizeof(data));
29 return xs_hex_enc((char *)data, sizeof(data));
30}
31
32
33int app_add(const char *id, const xs_dict *app)
34/* stores an app */
35{
36 if (!xs_is_hex(id))
37 return HTTP_STATUS_INTERNAL_SERVER_ERROR;
38
39 int status = HTTP_STATUS_CREATED;
40 xs *fn = xs_fmt("%s/app/", srv_basedir);
41 FILE *f;
42
43 mkdirx(fn);
44 fn = xs_str_cat(fn, id);
45 fn = xs_str_cat(fn, ".json");
46
47 if ((f = fopen(fn, "w")) != NULL) {
48 xs_json_dump(app, 4, f);
49 fclose(f);
50 }
51 else
52 status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
53
54 return status;
55}
56
57
58xs_str *_app_fn(const char *id)
59{
60 return xs_fmt("%s/app/%s.json", srv_basedir, id);
61}
62
63
64xs_dict *app_get(const char *id)
65/* gets an app */
66{
67 if (!xs_is_hex(id))
68 return NULL;
69
70 xs *fn = _app_fn(id);
71 xs_dict *app = NULL;
72 FILE *f;
73
74 if ((f = fopen(fn, "r")) != NULL) {
75 app = xs_json_load(f);
76 fclose(f);
77
78 }
79
80 return app;
81}
82
83
84int app_del(const char *id)
85/* deletes an app */
86{
87 if (!xs_is_hex(id))
88 return -1;
89
90 xs *fn = _app_fn(id);
91
92 return unlink(fn);
93}
94
95
96int token_add(const char *id, const xs_dict *token)
97/* stores a token */
98{
99 if (!xs_is_hex(id))
100 return HTTP_STATUS_INTERNAL_SERVER_ERROR;
101
102 int status = HTTP_STATUS_CREATED;
103 xs *fn = xs_fmt("%s/token/", srv_basedir);
104 FILE *f;
105
106 mkdirx(fn);
107 fn = xs_str_cat(fn, id);
108 fn = xs_str_cat(fn, ".json");
109
110 if ((f = fopen(fn, "w")) != NULL) {
111 xs_json_dump(token, 4, f);
112 fclose(f);
113 }
114 else
115 status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
116
117 return status;
118}
119
120
121xs_dict *token_get(const char *id)
122/* gets a token */
123{
124 if (!xs_is_hex(id))
125 return NULL;
126
127 xs *fn = xs_fmt("%s/token/%s.json", srv_basedir, id);
128 xs_dict *token = NULL;
129 FILE *f;
130
131 if ((f = fopen(fn, "r")) != NULL) {
132 token = xs_json_load(f);
133 fclose(f);
134
135 /* 'touch' the file */
136 utimes(fn, NULL);
137
138 /* also 'touch' the app */
139 const char *app_id = xs_dict_get(token, "client_id");
140
141 if (app_id) {
142 xs *afn = xs_fmt("%s/app/%s.json", srv_basedir, app_id);
143 utimes(afn, NULL);
144 }
145 }
146
147 return token;
148}
149
150
151int token_del(const char *id)
152/* deletes a token */
153{
154 if (!xs_is_hex(id))
155 return -1;
156
157 xs *fn = xs_fmt("%s/token/%s.json", srv_basedir, id);
158
159 return unlink(fn);
160}
161
162
163const char *login_page = ""
164"<!DOCTYPE html>\n"
165"<html>\n"
166"<head>\n"
167"<title>%s OAuth - Snac2</title>\n"
168"<meta content=\"width=device-width, initial-scale=1, minimum-scale=1, user-scalable=no\" name=\"viewport\">"
169"<style>:root {color-scheme: light dark}</style>\n"
170"</head>\n"
171"<body><h1>%s OAuth identify</h1>\n"
172"<div style=\"background-color: red; color: white\">%s</div>\n"
173"<form method=\"post\" action=\"%s:/" "/%s/%s\">\n"
174"<p>Login: <input type=\"text\" name=\"login\"></p>\n"
175"<p>Password: <input type=\"password\" name=\"passwd\"></p>\n"
176"<input type=\"hidden\" name=\"redir\" value=\"%s\">\n"
177"<input type=\"hidden\" name=\"cid\" value=\"%s\">\n"
178"<input type=\"hidden\" name=\"state\" value=\"%s\">\n"
179"<input type=\"submit\" value=\"OK\">\n"
180"</form><p>%s</p></body></html>\n"
181"";
182
183int oauth_get_handler(const xs_dict *req, const char *q_path,
184 char **body, int *b_size, char **ctype)
185{
186 (void)b_size;
187
188 if (!xs_startswith(q_path, "/oauth/"))
189 return 0;
190
191 int status = HTTP_STATUS_NOT_FOUND;
192 const xs_dict *msg = xs_dict_get(req, "q_vars");
193 xs *cmd = xs_replace_n(q_path, "/oauth", "", 1);
194
195 srv_debug(1, xs_fmt("oauth_get_handler %s", q_path));
196
197 if (strcmp(cmd, "/authorize") == 0) { /** **/
198 const char *cid = xs_dict_get(msg, "client_id");
199 const char *ruri = xs_dict_get(msg, "redirect_uri");
200 const char *rtype = xs_dict_get(msg, "response_type");
201 const char *state = xs_dict_get(msg, "state");
202
203 status = HTTP_STATUS_BAD_REQUEST;
204
205 if (cid && ruri && rtype && strcmp(rtype, "code") == 0) {
206 xs *app = app_get(cid);
207
208 if (app != NULL) {
209 const char *host = xs_dict_get(srv_config, "host");
210 const char *proto = xs_dict_get_def(srv_config, "protocol", "https");
211
212 if (xs_is_null(state))
213 state = "";
214
215 *body = xs_fmt(login_page, host, host, "", proto, host, "oauth/x-snac-login",
216 ruri, cid, state, USER_AGENT);
217 *ctype = "text/html";
218 status = HTTP_STATUS_OK;
219
220 srv_debug(1, xs_fmt("oauth authorize: generating login page"));
221 }
222 else
223 srv_debug(1, xs_fmt("oauth authorize: bad client_id %s", cid));
224 }
225 else
226 srv_debug(1, xs_fmt("oauth authorize: invalid or unset arguments"));
227 }
228 else
229 if (strcmp(cmd, "/x-snac-get-token") == 0) { /** **/
230 const char *host = xs_dict_get(srv_config, "host");
231 const char *proto = xs_dict_get_def(srv_config, "protocol", "https");
232
233 *body = xs_fmt(login_page, host, host, "", proto, host, "oauth/x-snac-get-token",
234 "", "", "", USER_AGENT);
235 *ctype = "text/html";
236 status = HTTP_STATUS_OK;
237
238 }
239
240 return status;
241}
242
243
244int oauth_post_handler(const xs_dict *req, const char *q_path,
245 const char *payload, int p_size,
246 char **body, int *b_size, char **ctype)
247{
248 (void)p_size;
249 (void)b_size;
250
251 if (!xs_startswith(q_path, "/oauth/"))
252 return 0;
253
254 int status = HTTP_STATUS_NOT_FOUND;
255
256 const char *i_ctype = xs_dict_get(req, "content-type");
257 xs *args = NULL;
258
259 if (i_ctype && xs_startswith(i_ctype, "application/json")) {
260 if (!xs_is_null(payload))
261 args = xs_json_loads(payload);
262 }
263 else
264 if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded") && payload) {
265 args = xs_url_vars(payload);
266 }
267 else
268 args = xs_dup(xs_dict_get(req, "p_vars"));
269
270 if (args == NULL)
271 return HTTP_STATUS_BAD_REQUEST;
272
273 xs *cmd = xs_replace_n(q_path, "/oauth", "", 1);
274
275 srv_debug(1, xs_fmt("oauth_post_handler %s", q_path));
276
277 if (strcmp(cmd, "/x-snac-login") == 0) { /** **/
278 const char *login = xs_dict_get(args, "login");
279 const char *passwd = xs_dict_get(args, "passwd");
280 const char *redir = xs_dict_get(args, "redir");
281 const char *cid = xs_dict_get(args, "cid");
282 const char *state = xs_dict_get(args, "state");
283 const char *host = xs_dict_get(srv_config, "host");
284 const char *proto = xs_dict_get_def(srv_config, "protocol", "https");
285
286 /* by default, generate another login form with an error */
287 *body = xs_fmt(login_page, host, host, "LOGIN INCORRECT", proto, host, "oauth/x-snac-login",
288 redir, cid, state, USER_AGENT);
289 *ctype = "text/html";
290 status = HTTP_STATUS_OK;
291
292 if (login && passwd && redir && cid) {
293 snac snac;
294
295 if (user_open(&snac, login)) {
296 /* check the login + password */
297 if (check_password(login, passwd, xs_dict_get(snac.config, "passwd"))) {
298 /* success! redirect to the desired uri */
299 xs *code = random_str();
300
301 xs_free(*body);
302
303 if (strcmp(redir, "urn:ietf:wg:oauth:2.0:oob") == 0) {
304 *body = xs_dup(code);
305 }
306 else {
307 if (xs_str_in(redir, "?") != -1)
308 *body = xs_fmt("%s&code=%s", redir, code);
309 else
310 *body = xs_fmt("%s?code=%s", redir, code);
311
312 status = HTTP_STATUS_SEE_OTHER;
313 }
314
315 /* if there is a state, add it */
316 if (!xs_is_null(state) && *state) {
317 *body = xs_str_cat(*body, "&state=");
318 *body = xs_str_cat(*body, state);
319 }
320
321 srv_log(xs_fmt("oauth x-snac-login: '%s' success, redirect to %s",
322 login, *body));
323
324 /* assign the login to the app */
325 xs *app = app_get(cid);
326
327 if (app != NULL) {
328 app = xs_dict_set(app, "uid", login);
329 app = xs_dict_set(app, "code", code);
330 app_add(cid, app);
331 }
332 else
333 srv_log(xs_fmt("oauth x-snac-login: error getting app %s", cid));
334 }
335 else
336 srv_debug(1, xs_fmt("oauth x-snac-login: login '%s' incorrect", login));
337
338 user_free(&snac);
339 }
340 else
341 srv_debug(1, xs_fmt("oauth x-snac-login: bad user '%s'", login));
342 }
343 else
344 srv_debug(1, xs_fmt("oauth x-snac-login: invalid or unset arguments"));
345 }
346 else
347 if (strcmp(cmd, "/token") == 0) { /** **/
348 xs *wrk = NULL;
349 const char *gtype = xs_dict_get(args, "grant_type");
350 const char *code = xs_dict_get(args, "code");
351 const char *cid = xs_dict_get(args, "client_id");
352 const char *csec = xs_dict_get(args, "client_secret");
353 const char *ruri = xs_dict_get(args, "redirect_uri");
354 const char *scope = xs_dict_get(args, "scope");
355
356 /* no client_secret? check if it's inside an authorization header
357 (AndStatus does it this way) */
358 if (xs_is_null(csec)) {
359 const char *auhdr = xs_dict_get(req, "authorization");
360
361 if (!xs_is_null(auhdr) && xs_startswith(auhdr, "Basic ")) {
362 xs *s1 = xs_replace_n(auhdr, "Basic ", "", 1);
363 int size;
364 xs *s2 = xs_base64_dec(s1, &size);
365
366 if (!xs_is_null(s2)) {
367 xs *l1 = xs_split(s2, ":");
368
369 if (xs_list_len(l1) == 2) {
370 wrk = xs_dup(xs_list_get(l1, 1));
371 csec = wrk;
372 }
373 }
374 }
375 }
376
377 /* no code?
378 I'm not sure of the impacts of this right now, but Subway Tooter does not
379 provide a code so one must be generated */
380 if (xs_is_null(code)){
381 code = random_str();
382 }
383 if (gtype && code && cid && csec && ruri) {
384 xs *app = app_get(cid);
385
386 if (app == NULL) {
387 status = HTTP_STATUS_UNAUTHORIZED;
388 srv_log(xs_fmt("oauth token: invalid app %s", cid));
389 }
390 else
391 if (strcmp(csec, xs_dict_get(app, "client_secret")) != 0) {
392 status = HTTP_STATUS_UNAUTHORIZED;
393 srv_log(xs_fmt("oauth token: invalid client_secret for app %s", cid));
394 }
395 else {
396 xs *rsp = xs_dict_new();
397 xs *cat = xs_number_new(time(NULL));
398 xs *tokid = random_str();
399
400 rsp = xs_dict_append(rsp, "access_token", tokid);
401 rsp = xs_dict_append(rsp, "token_type", "Bearer");
402 rsp = xs_dict_append(rsp, "created_at", cat);
403
404 if (!xs_is_null(scope))
405 rsp = xs_dict_append(rsp, "scope", scope);
406
407 *body = xs_json_dumps(rsp, 4);
408 *ctype = "application/json";
409 status = HTTP_STATUS_OK;
410
411 const char *uid = xs_dict_get(app, "uid");
412
413 srv_debug(1, xs_fmt("oauth token: "
414 "successful login for %s, new token %s", uid, tokid));
415
416 xs *token = xs_dict_new();
417 token = xs_dict_append(token, "token", tokid);
418 token = xs_dict_append(token, "client_id", cid);
419 token = xs_dict_append(token, "client_secret", csec);
420 token = xs_dict_append(token, "uid", uid);
421 token = xs_dict_append(token, "code", code);
422
423 token_add(tokid, token);
424 }
425 }
426 else {
427 srv_debug(1, xs_fmt("oauth token: invalid or unset arguments"));
428 status = HTTP_STATUS_BAD_REQUEST;
429 }
430 }
431 else
432 if (strcmp(cmd, "/revoke") == 0) { /** **/
433 const char *cid = xs_dict_get(args, "client_id");
434 const char *csec = xs_dict_get(args, "client_secret");
435 const char *tokid = xs_dict_get(args, "token");
436
437 if (cid && csec && tokid) {
438 xs *token = token_get(tokid);
439
440 *body = xs_str_new("{}");
441 *ctype = "application/json";
442
443 if (token == NULL || strcmp(csec, xs_dict_get(token, "client_secret")) != 0) {
444 srv_debug(1, xs_fmt("oauth revoke: bad secret for token %s", tokid));
445 status = HTTP_STATUS_FORBIDDEN;
446 }
447 else {
448 token_del(tokid);
449 srv_debug(1, xs_fmt("oauth revoke: revoked token %s", tokid));
450 status = HTTP_STATUS_OK;
451
452 /* also delete the app, as it serves no purpose from now on */
453 app_del(cid);
454 }
455 }
456 else {
457 srv_debug(1, xs_fmt("oauth revoke: invalid or unset arguments"));
458 status = HTTP_STATUS_FORBIDDEN;
459 }
460 }
461 if (strcmp(cmd, "/x-snac-get-token") == 0) { /** **/
462 const char *login = xs_dict_get(args, "login");
463 const char *passwd = xs_dict_get(args, "passwd");
464 const char *host = xs_dict_get(srv_config, "host");
465 const char *proto = xs_dict_get_def(srv_config, "protocol", "https");
466
467 /* by default, generate another login form with an error */
468 *body = xs_fmt(login_page, host, host, "LOGIN INCORRECT", proto, host, "oauth/x-snac-get-token",
469 "", "", "", USER_AGENT);
470 *ctype = "text/html";
471 status = HTTP_STATUS_OK;
472
473 if (login && passwd) {
474 snac user;
475
476 if (user_open(&user, login)) {
477 /* check the login + password */
478 if (check_password(login, passwd, xs_dict_get(user.config, "passwd"))) {
479 /* success! create a new token */
480 xs *tokid = random_str();
481
482 srv_debug(1, xs_fmt("x-snac-new-token: "
483 "successful login for %s, new token %s", login, tokid));
484
485 xs *token = xs_dict_new();
486 token = xs_dict_append(token, "token", tokid);
487 token = xs_dict_append(token, "client_id", "snac-client");
488 token = xs_dict_append(token, "client_secret", "");
489 token = xs_dict_append(token, "uid", login);
490 token = xs_dict_append(token, "code", "");
491
492 token_add(tokid, token);
493
494 *ctype = "text/plain";
495 xs_free(*body);
496 *body = xs_dup(tokid);
497 }
498
499 user_free(&user);
500 }
501 }
502 }
503
504 return status;
505}
506
507
508xs_str *mastoapi_id(const xs_dict *msg)
509/* returns a somewhat Mastodon-compatible status id */
510{
511 const char *id = xs_dict_get(msg, "id");
512 xs *md5 = xs_md5_hex(id, strlen(id));
513
514 return xs_fmt("%10.0f%s", object_ctime_by_md5(md5), md5);
515}
516
517#define MID_TO_MD5(id) (id + 10)
518
519
520xs_dict *mastoapi_account(const xs_dict *actor)
521/* converts an ActivityPub actor to a Mastodon account */
522{
523 const char *id = xs_dict_get(actor, "id");
524 const char *pub = xs_dict_get(actor, "published");
525
526 if (xs_type(id) != XSTYPE_STRING)
527 return NULL;
528
529 const char *prefu = xs_dict_get(actor, "preferredUsername");
530
531 const char *display_name = xs_dict_get(actor, "name");
532 if (xs_is_null(display_name) || *display_name == '\0')
533 display_name = prefu;
534
535 xs_dict *acct = xs_dict_new();
536 xs *acct_md5 = xs_md5_hex(id, strlen(id));
537 acct = xs_dict_append(acct, "id", acct_md5);
538 acct = xs_dict_append(acct, "username", prefu);
539 acct = xs_dict_append(acct, "display_name", display_name);
540 acct = xs_dict_append(acct, "discoverable", xs_stock(XSTYPE_TRUE));
541 acct = xs_dict_append(acct, "group", xs_stock(XSTYPE_FALSE));
542 acct = xs_dict_append(acct, "hide_collections", xs_stock(XSTYPE_FALSE));
543 acct = xs_dict_append(acct, "indexable", xs_stock(XSTYPE_TRUE));
544 acct = xs_dict_append(acct, "noindex", xs_stock(XSTYPE_FALSE));
545 acct = xs_dict_append(acct, "roles", xs_stock(XSTYPE_LIST));
546
547 {
548 /* create the acct field as user@host */
549 xs *l = xs_split(id, "/");
550 xs *fquid = xs_fmt("%s@%s", prefu, xs_list_get(l, 2));
551 acct = xs_dict_append(acct, "acct", fquid);
552 }
553
554 if (pub)
555 acct = xs_dict_append(acct, "created_at", pub);
556 else {
557 /* unset created_at crashes Tusky, so lie like a mf */
558 xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
559 acct = xs_dict_append(acct, "created_at", date);
560 }
561
562 xs *last_status_at = xs_str_utctime(0, "%Y-%m-%d");
563 acct = xs_dict_append(acct, "last_status_at", last_status_at);
564
565 const char *note = xs_dict_get(actor, "summary");
566 if (xs_is_null(note))
567 note = "";
568
569 if (strcmp(xs_dict_get(actor, "type"), "Service") == 0)
570 acct = xs_dict_append(acct, "bot", xs_stock(XSTYPE_TRUE));
571 else
572 acct = xs_dict_append(acct, "bot", xs_stock(XSTYPE_FALSE));
573
574 acct = xs_dict_append(acct, "note", note);
575
576 acct = xs_dict_append(acct, "url", id);
577 acct = xs_dict_append(acct, "uri", id);
578
579 xs *avatar = NULL;
580 const xs_dict *av = xs_dict_get(actor, "icon");
581
582 if (xs_type(av) == XSTYPE_DICT) {
583 const char *url = xs_dict_get(av, "url");
584
585 if (url != NULL)
586 avatar = xs_dup(url);
587 }
588
589 if (avatar == NULL)
590 avatar = xs_fmt("%s/susie.png", srv_baseurl);
591
592 acct = xs_dict_append(acct, "avatar", avatar);
593 acct = xs_dict_append(acct, "avatar_static", avatar);
594
595 xs *header = NULL;
596 const xs_dict *hd = xs_dict_get(actor, "image");
597
598 if (xs_type(hd) == XSTYPE_DICT)
599 header = xs_dup(xs_dict_get(hd, "url"));
600
601 if (xs_is_null(header))
602 header = xs_str_new(NULL);
603
604 acct = xs_dict_append(acct, "header", header);
605 acct = xs_dict_append(acct, "header_static", header);
606
607 /* emojis */
608 const xs_list *p;
609 if (!xs_is_null(p = xs_dict_get(actor, "tag"))) {
610 xs *eml = xs_list_new();
611 const xs_dict *v;
612 int c = 0;
613
614 while (xs_list_next(p, &v, &c)) {
615 const char *type = xs_dict_get(v, "type");
616
617 if (!xs_is_null(type) && strcmp(type, "Emoji") == 0) {
618 const char *name = xs_dict_get(v, "name");
619 const xs_dict *icon = xs_dict_get(v, "icon");
620
621 if (!xs_is_null(name) && !xs_is_null(icon)) {
622 const char *url = xs_dict_get(icon, "url");
623
624 if (!xs_is_null(url)) {
625 xs *nm = xs_strip_chars_i(xs_dup(name), ":");
626 xs *d1 = xs_dict_new();
627
628 d1 = xs_dict_append(d1, "shortcode", nm);
629 d1 = xs_dict_append(d1, "url", url);
630 d1 = xs_dict_append(d1, "static_url", url);
631 d1 = xs_dict_append(d1, "visible_in_picker", xs_stock(XSTYPE_TRUE));
632
633 eml = xs_list_append(eml, d1);
634 }
635 }
636 }
637 }
638
639 acct = xs_dict_append(acct, "emojis", eml);
640 }
641
642 acct = xs_dict_append(acct, "locked", xs_stock(XSTYPE_FALSE));
643 acct = xs_dict_append(acct, "followers_count", xs_stock(0));
644 acct = xs_dict_append(acct, "following_count", xs_stock(0));
645 acct = xs_dict_append(acct, "statuses_count", xs_stock(0));
646
647 xs *fields = xs_list_new();
648 p = xs_dict_get(actor, "attachment");
649 const xs_dict *v;
650
651 /* dict of validated links */
652 xs_dict *val_links = NULL;
653 const xs_dict *metadata = xs_stock(XSTYPE_DICT);
654 snac user = {0};
655
656 if (xs_startswith(id, srv_baseurl)) {
657 /* if it's a local user, open it and pick its validated links */
658 if (user_open(&user, prefu)) {
659 val_links = user.links;
660 metadata = xs_dict_get_def(user.config, "metadata", xs_stock(XSTYPE_DICT));
661 }
662 }
663
664 if (xs_is_null(val_links))
665 val_links = xs_stock(XSTYPE_DICT);
666
667 int c = 0;
668 while (xs_list_next(p, &v, &c)) {
669 const char *type = xs_dict_get(v, "type");
670 const char *name = xs_dict_get(v, "name");
671 const char *value = xs_dict_get(v, "value");
672
673 if (!xs_is_null(type) && !xs_is_null(name) &&
674 !xs_is_null(value) && strcmp(type, "PropertyValue") == 0) {
675 xs *val_date = NULL;
676
677 const char *url = xs_dict_get(metadata, name);
678
679 if (!xs_is_null(url) && xs_startswith(url, "https:/" "/")) {
680 const xs_number *verified_time = xs_dict_get(val_links, url);
681 if (xs_type(verified_time) == XSTYPE_NUMBER) {
682 time_t t = xs_number_get(verified_time);
683
684 if (t > 0)
685 val_date = xs_str_utctime(t, ISO_DATE_SPEC);
686 }
687 }
688
689 xs *d = xs_dict_new();
690
691 d = xs_dict_append(d, "name", name);
692 d = xs_dict_append(d, "value", value);
693 d = xs_dict_append(d, "verified_at",
694 xs_type(val_date) == XSTYPE_STRING && *val_date ?
695 val_date : xs_stock(XSTYPE_NULL));
696
697 fields = xs_list_append(fields, d);
698 }
699 }
700
701 user_free(&user);
702
703 acct = xs_dict_append(acct, "fields", fields);
704
705 return acct;
706}
707
708
709xs_str *mastoapi_date(const char *date)
710/* converts an ISO 8601 date to whatever format Mastodon uses */
711{
712 xs_str *s = xs_crop_i(xs_dup(date), 0, 19);
713 s = xs_str_cat(s, ".000Z");
714
715 return s;
716}
717
718
719xs_dict *mastoapi_poll(snac *snac, const xs_dict *msg)
720/* creates a mastoapi Poll object */
721{
722 xs_dict *poll = xs_dict_new();
723 xs *mid = mastoapi_id(msg);
724 const xs_list *opts = NULL;
725 const xs_val *v;
726 int num_votes = 0;
727 xs *options = xs_list_new();
728
729 poll = xs_dict_append(poll, "id", mid);
730 const char *date = xs_dict_get(msg, "endTime");
731 if (date == NULL)
732 date = xs_dict_get(msg, "closed");
733 if (date == NULL)
734 return NULL;
735
736 xs *fd = mastoapi_date(date);
737 poll = xs_dict_append(poll, "expires_at", fd);
738
739 date = xs_dict_get(msg, "closed");
740 time_t t = 0;
741
742 if (date != NULL)
743 t = xs_parse_iso_date(date, 0);
744
745 poll = xs_dict_append(poll, "expired",
746 t < time(NULL) ? xs_stock(XSTYPE_FALSE) : xs_stock(XSTYPE_TRUE));
747
748 if ((opts = xs_dict_get(msg, "oneOf")) != NULL)
749 poll = xs_dict_append(poll, "multiple", xs_stock(XSTYPE_FALSE));
750 else {
751 opts = xs_dict_get(msg, "anyOf");
752 poll = xs_dict_append(poll, "multiple", xs_stock(XSTYPE_TRUE));
753 }
754
755 int c = 0;
756 while (xs_list_next(opts, &v, &c)) {
757 const char *title = xs_dict_get(v, "name");
758 const char *replies = xs_dict_get(v, "replies");
759
760 if (title && replies) {
761 const char *votes_count = xs_dict_get(replies, "totalItems");
762
763 if (xs_type(votes_count) == XSTYPE_NUMBER) {
764 xs *d = xs_dict_new();
765 d = xs_dict_append(d, "title", title);
766 d = xs_dict_append(d, "votes_count", votes_count);
767
768 options = xs_list_append(options, d);
769 num_votes += xs_number_get(votes_count);
770 }
771 }
772 }
773
774 poll = xs_dict_append(poll, "options", options);
775 xs *vc = xs_number_new(num_votes);
776 poll = xs_dict_append(poll, "votes_count", vc);
777
778 poll = xs_dict_append(poll, "emojis", xs_stock(XSTYPE_LIST));
779
780 poll = xs_dict_append(poll, "voted",
781 (snac && was_question_voted(snac, xs_dict_get(msg, "id"))) ?
782 xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
783
784 return poll;
785}
786
787
788xs_dict *mastoapi_status(snac *snac, const xs_dict *msg)
789/* converts an ActivityPub note to a Mastodon status */
790{
791 xs *actor = NULL;
792 actor_get_refresh(snac, get_atto(msg), &actor);
793
794 /* if the author is not here, discard */
795 if (actor == NULL)
796 return NULL;
797
798 const char *type = xs_dict_get(msg, "type");
799 const char *id = xs_dict_get(msg, "id");
800
801 /* fail if it's not a valid actor */
802 if (xs_is_null(type) || xs_is_null(id))
803 return NULL;
804
805 xs *acct = mastoapi_account(actor);
806 if (acct == NULL)
807 return NULL;
808
809 xs *idx = NULL;
810 xs *ixc = NULL;
811 const char *tmp;
812 xs *mid = mastoapi_id(msg);
813
814 xs_dict *st = xs_dict_new();
815
816 st = xs_dict_append(st, "id", mid);
817 st = xs_dict_append(st, "uri", id);
818 st = xs_dict_append(st, "url", id);
819 st = xs_dict_append(st, "account", acct);
820
821 xs *fd = mastoapi_date(xs_dict_get(msg, "published"));
822 st = xs_dict_append(st, "created_at", fd);
823
824 {
825 const char *content = xs_dict_get(msg, "content");
826 const char *name = xs_dict_get(msg, "name");
827 xs *s1 = NULL;
828
829 if (name && content)
830 s1 = xs_fmt("%s<br><br>%s", name, content);
831 else
832 if (name)
833 s1 = xs_dup(name);
834 else
835 if (content)
836 s1 = xs_dup(content);
837 else
838 s1 = xs_str_new(NULL);
839
840 st = xs_dict_append(st, "content", s1);
841 }
842
843 st = xs_dict_append(st, "visibility",
844 is_msg_public(msg) ? "public" : "private");
845
846 tmp = xs_dict_get(msg, "sensitive");
847 if (xs_is_null(tmp))
848 tmp = xs_stock(XSTYPE_FALSE);
849
850 st = xs_dict_append(st, "sensitive", tmp);
851
852 tmp = xs_dict_get(msg, "summary");
853 if (xs_is_null(tmp))
854 tmp = "";
855
856 st = xs_dict_append(st, "spoiler_text", tmp);
857
858 /* create the list of attachments */
859 xs *attach = get_attachments(msg);
860
861 {
862 xs_list *p = attach;
863 const xs_dict *v;
864
865 xs *matt = xs_list_new();
866
867 while (xs_list_iter(&p, &v)) {
868 const char *type = xs_dict_get(v, "type");
869 const char *href = xs_dict_get(v, "href");
870 const char *name = xs_dict_get(v, "name");
871
872 if (xs_match(type, "image/*|video/*|Image|Video")) { /* */
873 xs *matteid = xs_fmt("%s_%d", id, xs_list_len(matt));
874
875 xs *d = xs_dict_new();
876
877 d = xs_dict_append(d, "id", matteid);
878 d = xs_dict_append(d, "url", href);
879 d = xs_dict_append(d, "preview_url", href);
880 d = xs_dict_append(d, "remote_url", href);
881 d = xs_dict_append(d, "description", name);
882
883 d = xs_dict_append(d, "type", (*type == 'v' || *type == 'V') ? "video" : "image");
884
885 matt = xs_list_append(matt, d);
886 }
887 }
888
889 st = xs_dict_append(st, "media_attachments", matt);
890 }
891
892 {
893 xs *ml = xs_list_new();
894 xs *htl = xs_list_new();
895 xs *eml = xs_list_new();
896 const xs_list *tag = xs_dict_get(msg, "tag");
897 int n = 0;
898
899 xs *tag_list = NULL;
900
901 if (xs_type(tag) == XSTYPE_DICT) {
902 tag_list = xs_list_new();
903 tag_list = xs_list_append(tag_list, tag);
904 }
905 else
906 if (xs_type(tag) == XSTYPE_LIST)
907 tag_list = xs_dup(tag);
908 else
909 tag_list = xs_list_new();
910
911 tag = tag_list;
912 const xs_dict *v;
913
914 int c = 0;
915 while (xs_list_next(tag, &v, &c)) {
916 const char *type = xs_dict_get(v, "type");
917
918 if (xs_is_null(type))
919 continue;
920
921 xs *d1 = xs_dict_new();
922
923 if (strcmp(type, "Mention") == 0) {
924 const char *name = xs_dict_get(v, "name");
925 const char *href = xs_dict_get(v, "href");
926
927 if (!xs_is_null(name) && !xs_is_null(href) &&
928 (snac == NULL || strcmp(href, snac->actor) != 0)) {
929 xs *nm = xs_strip_chars_i(xs_dup(name), "@");
930
931 xs *id = xs_fmt("%d", n++);
932 d1 = xs_dict_append(d1, "id", id);
933 d1 = xs_dict_append(d1, "username", nm);
934 d1 = xs_dict_append(d1, "acct", nm);
935 d1 = xs_dict_append(d1, "url", href);
936
937 ml = xs_list_append(ml, d1);
938 }
939 }
940 else
941 if (strcmp(type, "Hashtag") == 0) {
942 const char *name = xs_dict_get(v, "name");
943 const char *href = xs_dict_get(v, "href");
944
945 if (!xs_is_null(name) && !xs_is_null(href)) {
946 xs *nm = xs_strip_chars_i(xs_dup(name), "#");
947
948 d1 = xs_dict_append(d1, "name", nm);
949 d1 = xs_dict_append(d1, "url", href);
950
951 htl = xs_list_append(htl, d1);
952 }
953 }
954 else
955 if (strcmp(type, "Emoji") == 0) {
956 const char *name = xs_dict_get(v, "name");
957 const xs_dict *icon = xs_dict_get(v, "icon");
958
959 if (!xs_is_null(name) && !xs_is_null(icon)) {
960 const char *url = xs_dict_get(icon, "url");
961
962 if (!xs_is_null(url)) {
963 xs *nm = xs_strip_chars_i(xs_dup(name), ":");
964
965 d1 = xs_dict_append(d1, "shortcode", nm);
966 d1 = xs_dict_append(d1, "url", url);
967 d1 = xs_dict_append(d1, "static_url", url);
968 d1 = xs_dict_append(d1, "visible_in_picker", xs_stock(XSTYPE_TRUE));
969 d1 = xs_dict_append(d1, "category", "Emojis");
970
971 eml = xs_list_append(eml, d1);
972 }
973 }
974 }
975 }
976
977 st = xs_dict_append(st, "mentions", ml);
978 st = xs_dict_append(st, "tags", htl);
979 st = xs_dict_append(st, "emojis", eml);
980 }
981
982 xs_free(idx);
983 xs_free(ixc);
984 idx = object_likes(id);
985 ixc = xs_number_new(xs_list_len(idx));
986
987 st = xs_dict_append(st, "favourites_count", ixc);
988 st = xs_dict_append(st, "favourited",
989 (snac && xs_list_in(idx, snac->md5) != -1) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
990
991 xs_free(idx);
992 xs_free(ixc);
993 idx = object_announces(id);
994 ixc = xs_number_new(xs_list_len(idx));
995
996 st = xs_dict_append(st, "reblogs_count", ixc);
997 st = xs_dict_append(st, "reblogged",
998 (snac && xs_list_in(idx, snac->md5) != -1) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
999
1000 /* get the last person who boosted this */
1001 xs *boosted_by_md5 = NULL;
1002 if (xs_list_len(idx))
1003 boosted_by_md5 = xs_dup(xs_list_get(idx, -1));
1004
1005 xs_free(idx);
1006 xs_free(ixc);
1007 idx = object_children(id);
1008 ixc = xs_number_new(xs_list_len(idx));
1009
1010 st = xs_dict_append(st, "replies_count", ixc);
1011
1012 /* default in_reply_to values */
1013 st = xs_dict_append(st, "in_reply_to_id", xs_stock(XSTYPE_NULL));
1014 st = xs_dict_append(st, "in_reply_to_account_id", xs_stock(XSTYPE_NULL));
1015
1016 tmp = xs_dict_get(msg, "inReplyTo");
1017 if (!xs_is_null(tmp)) {
1018 xs *irto = NULL;
1019
1020 if (valid_status(object_get(tmp, &irto))) {
1021 xs *irt_mid = mastoapi_id(irto);
1022 st = xs_dict_set(st, "in_reply_to_id", irt_mid);
1023
1024 const char *at = NULL;
1025 if (!xs_is_null(at = get_atto(irto))) {
1026 xs *at_md5 = xs_md5_hex(at, strlen(at));
1027 st = xs_dict_set(st, "in_reply_to_account_id", at_md5);
1028 }
1029 }
1030 }
1031
1032 st = xs_dict_append(st, "reblog", xs_stock(XSTYPE_NULL));
1033 st = xs_dict_append(st, "card", xs_stock(XSTYPE_NULL));
1034 st = xs_dict_append(st, "language", "en");
1035
1036 st = xs_dict_append(st, "filtered", xs_stock(XSTYPE_LIST));
1037 st = xs_dict_append(st, "muted", xs_stock(XSTYPE_FALSE));
1038
1039 tmp = xs_dict_get(msg, "sourceContent");
1040 if (xs_is_null(tmp))
1041 tmp = "";
1042
1043 st = xs_dict_append(st, "text", tmp);
1044
1045 tmp = xs_dict_get(msg, "updated");
1046 xs *fd2 = NULL;
1047 if (xs_is_null(tmp))
1048 tmp = xs_stock(XSTYPE_NULL);
1049 else {
1050 fd2 = mastoapi_date(tmp);
1051 tmp = fd2;
1052 }
1053
1054 st = xs_dict_append(st, "edited_at", tmp);
1055
1056 if (strcmp(type, "Question") == 0) {
1057 xs *poll = mastoapi_poll(snac, msg);
1058 st = xs_dict_append(st, "poll", poll);
1059 }
1060 else
1061 st = xs_dict_append(st, "poll", xs_stock(XSTYPE_NULL));
1062
1063 st = xs_dict_append(st, "bookmarked",
1064 (snac && is_bookmarked(snac, id)) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1065
1066 st = xs_dict_append(st, "pinned",
1067 (snac && is_pinned(snac, id)) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1068
1069 /* is it a boost? */
1070 if (!xs_is_null(boosted_by_md5)) {
1071 /* create a new dummy status, using st as the 'reblog' field */
1072 xs_dict *bst = xs_dup(st);
1073 xs *b_actor = NULL;
1074
1075 if (valid_status(object_get_by_md5(boosted_by_md5, &b_actor))) {
1076 xs *b_acct = mastoapi_account(b_actor);
1077 xs *fake_uri = NULL;
1078
1079 if (snac)
1080 fake_uri = xs_fmt("%s/d/%s/Announce", snac->actor, mid);
1081 else
1082 fake_uri = xs_fmt("%s#%s", srv_baseurl, mid);
1083
1084 bst = xs_dict_set(bst, "uri", fake_uri);
1085 bst = xs_dict_set(bst, "url", fake_uri);
1086 bst = xs_dict_set(bst, "account", b_acct);
1087 bst = xs_dict_set(bst, "content", "");
1088 bst = xs_dict_set(bst, "reblog", st);
1089
1090 xs_free(st);
1091 st = bst;
1092 }
1093 }
1094
1095 return st;
1096}
1097
1098
1099xs_dict *mastoapi_relationship(snac *snac, const char *md5)
1100{
1101 xs_dict *rel = NULL;
1102 xs *actor_o = NULL;
1103
1104 if (valid_status(object_get_by_md5(md5, &actor_o))) {
1105 rel = xs_dict_new();
1106
1107 const char *actor = xs_dict_get(actor_o, "id");
1108
1109 rel = xs_dict_append(rel, "id", md5);
1110 rel = xs_dict_append(rel, "following",
1111 following_check(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1112
1113 rel = xs_dict_append(rel, "showing_reblogs", xs_stock(XSTYPE_TRUE));
1114 rel = xs_dict_append(rel, "notifying", xs_stock(XSTYPE_FALSE));
1115 rel = xs_dict_append(rel, "followed_by",
1116 follower_check(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1117
1118 rel = xs_dict_append(rel, "blocking",
1119 is_muted(snac, actor) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1120
1121 rel = xs_dict_append(rel, "muting", xs_stock(XSTYPE_FALSE));
1122 rel = xs_dict_append(rel, "muting_notifications", xs_stock(XSTYPE_FALSE));
1123 rel = xs_dict_append(rel, "requested", xs_stock(XSTYPE_FALSE));
1124 rel = xs_dict_append(rel, "domain_blocking", xs_stock(XSTYPE_FALSE));
1125 rel = xs_dict_append(rel, "endorsed", xs_stock(XSTYPE_FALSE));
1126 rel = xs_dict_append(rel, "note", "");
1127 }
1128
1129 return rel;
1130}
1131
1132
1133int process_auth_token(snac *snac, const xs_dict *req)
1134/* processes an authorization token, if there is one */
1135{
1136 int logged_in = 0;
1137 const char *v;
1138
1139 /* if there is an authorization field, try to validate it */
1140 if (!xs_is_null(v = xs_dict_get(req, "authorization")) && xs_startswith(v, "Bearer ")) {
1141 xs *tokid = xs_replace_n(v, "Bearer ", "", 1);
1142 xs *token = token_get(tokid);
1143
1144 if (token != NULL) {
1145 const char *uid = xs_dict_get(token, "uid");
1146
1147 if (!xs_is_null(uid) && user_open(snac, uid)) {
1148 logged_in = 1;
1149
1150 /* this counts as a 'login' */
1151 lastlog_write(snac, "mastoapi");
1152
1153 srv_debug(2, xs_fmt("mastoapi auth: valid token for user '%s'", uid));
1154 }
1155 else
1156 srv_log(xs_fmt("mastoapi auth: corrupted token '%s'", tokid));
1157 }
1158 else
1159 srv_log(xs_fmt("mastoapi auth: invalid token '%s'", tokid));
1160 }
1161
1162 return logged_in;
1163}
1164
1165void credentials_get(char **body, char **ctype, int *status, snac snac)
1166{
1167 xs *acct = xs_dict_new();
1168
1169 acct = xs_dict_append(acct, "id", snac.md5);
1170 acct = xs_dict_append(acct, "username", xs_dict_get(snac.config, "uid"));
1171 acct = xs_dict_append(acct, "acct", xs_dict_get(snac.config, "uid"));
1172 acct = xs_dict_append(acct, "display_name", xs_dict_get(snac.config, "name"));
1173 acct = xs_dict_append(acct, "created_at", xs_dict_get(snac.config, "published"));
1174 acct = xs_dict_append(acct, "last_status_at", xs_dict_get(snac.config, "published"));
1175 acct = xs_dict_append(acct, "note", xs_dict_get(snac.config, "bio"));
1176 acct = xs_dict_append(acct, "url", snac.actor);
1177 acct = xs_dict_append(acct, "locked", xs_stock(XSTYPE_FALSE));
1178 acct = xs_dict_append(acct, "bot", xs_dict_get(snac.config, "bot"));
1179 acct = xs_dict_append(acct, "emojis", xs_stock(XSTYPE_LIST));
1180
1181 xs *src = xs_json_loads("{\"privacy\":\"public\", \"language\":\"en\","
1182 "\"follow_requests_count\": 0,"
1183 "\"sensitive\":false,\"fields\":[],\"note\":\"\"}");
1184 /* some apps take the note from the source object */
1185 src = xs_dict_set(src, "note", xs_dict_get(snac.config, "bio"));
1186 src = xs_dict_set(src, "privacy", xs_type(xs_dict_get(snac.config, "private")) == XSTYPE_TRUE ? "private" : "public");
1187
1188 const xs_str *cw = xs_dict_get(snac.config, "cw");
1189 src = xs_dict_set(src, "sensitive",
1190 strcmp(cw, "open") == 0 ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
1191
1192 src = xs_dict_set(src, "bot", xs_dict_get(snac.config, "bot"));
1193
1194 xs *avatar = NULL;
1195 const char *av = xs_dict_get(snac.config, "avatar");
1196
1197 if (xs_is_null(av) || *av == '\0')
1198 avatar = xs_fmt("%s/susie.png", srv_baseurl);
1199 else
1200 avatar = xs_dup(av);
1201
1202 acct = xs_dict_append(acct, "avatar", avatar);
1203 acct = xs_dict_append(acct, "avatar_static", avatar);
1204
1205 xs *header = NULL;
1206 const char *hd = xs_dict_get(snac.config, "header");
1207
1208 if (!xs_is_null(hd))
1209 header = xs_dup(hd);
1210 else
1211 header = xs_str_new(NULL);
1212
1213 acct = xs_dict_append(acct, "header", header);
1214 acct = xs_dict_append(acct, "header_static", header);
1215
1216 const xs_dict *metadata = xs_dict_get(snac.config, "metadata");
1217 if (xs_type(metadata) == XSTYPE_DICT) {
1218 xs *fields = xs_list_new();
1219 const xs_str *k;
1220 const xs_str *v;
1221
1222 xs_dict *val_links = snac.links;
1223 if (xs_is_null(val_links))
1224 val_links = xs_stock(XSTYPE_DICT);
1225
1226 int c = 0;
1227 while (xs_dict_next(metadata, &k, &v, &c)) {
1228 xs *val_date = NULL;
1229
1230 const xs_number *verified_time = xs_dict_get(val_links, v);
1231 if (xs_type(verified_time) == XSTYPE_NUMBER) {
1232 time_t t = xs_number_get(verified_time);
1233
1234 if (t > 0)
1235 val_date = xs_str_utctime(t, ISO_DATE_SPEC);
1236 }
1237
1238 xs *d = xs_dict_new();
1239
1240 d = xs_dict_append(d, "name", k);
1241 d = xs_dict_append(d, "value", v);
1242 d = xs_dict_append(d, "verified_at",
1243 xs_type(val_date) == XSTYPE_STRING && *val_date ? val_date : xs_stock(XSTYPE_NULL));
1244
1245 fields = xs_list_append(fields, d);
1246 }
1247
1248 acct = xs_dict_set(acct, "fields", fields);
1249 /* some apps take the fields from the source object */
1250 src = xs_dict_set(src, "fields", fields);
1251 }
1252
1253 acct = xs_dict_append(acct, "source", src);
1254 acct = xs_dict_append(acct, "followers_count", xs_stock(0));
1255 acct = xs_dict_append(acct, "following_count", xs_stock(0));
1256 acct = xs_dict_append(acct, "statuses_count", xs_stock(0));
1257
1258 *body = xs_json_dumps(acct, 4);
1259 *ctype = "application/json";
1260 *status = HTTP_STATUS_OK;
1261}
1262
1263
1264xs_list *mastoapi_timeline(snac *user, const xs_dict *args, const char *index_fn)
1265{
1266 xs_list *out = xs_list_new();
1267 FILE *f;
1268 char md5[MD5_HEX_SIZE];
1269
1270 if (dbglevel) {
1271 xs *js = xs_json_dumps(args, 0);
1272 srv_debug(1, xs_fmt("mastoapi_timeline args %s", js));
1273 }
1274
1275 if ((f = fopen(index_fn, "r")) == NULL)
1276 return out;
1277
1278 const char *max_id = xs_dict_get(args, "max_id");
1279 const char *since_id = xs_dict_get(args, "since_id");
1280 const char *min_id = xs_dict_get(args, "min_id");
1281 const char *limit_s = xs_dict_get(args, "limit");
1282 int limit = 0;
1283 int cnt = 0;
1284
1285 if (!xs_is_null(limit_s))
1286 limit = atoi(limit_s);
1287
1288 if (limit == 0)
1289 limit = 20;
1290
1291 if (index_desc_first(f, md5, 0)) {
1292 do {
1293 xs *msg = NULL;
1294
1295 /* only return entries older that max_id */
1296 if (max_id) {
1297 if (strcmp(md5, MID_TO_MD5(max_id)) == 0)
1298 max_id = NULL;
1299
1300 continue;
1301 }
1302
1303 /* only returns entries newer than since_id */
1304 if (since_id) {
1305 if (strcmp(md5, MID_TO_MD5(since_id)) == 0)
1306 break;
1307 }
1308
1309 /* only returns entries newer than min_id */
1310 /* what does really "Return results immediately newer than ID" mean? */
1311 if (min_id) {
1312 if (strcmp(md5, MID_TO_MD5(min_id)) == 0)
1313 break;
1314 }
1315
1316 /* get the entry */
1317 if (user) {
1318 if (!valid_status(timeline_get_by_md5(user, md5, &msg)))
1319 continue;
1320 }
1321 else {
1322 if (!valid_status(object_get_by_md5(md5, &msg)))
1323 continue;
1324 }
1325
1326 /* discard non-Notes */
1327 const char *id = xs_dict_get(msg, "id");
1328 const char *type = xs_dict_get(msg, "type");
1329 if (!xs_match(type, POSTLIKE_OBJECT_TYPE))
1330 continue;
1331
1332 const char *from = NULL;
1333 if (strcmp(type, "Page") == 0)
1334 from = xs_dict_get(msg, "audience");
1335
1336 if (from == NULL)
1337 from = get_atto(msg);
1338
1339 if (from == NULL)
1340 continue;
1341
1342 if (user) {
1343 /* is this message from a person we don't follow? */
1344 if (strcmp(from, user->actor) && !following_check(user, from)) {
1345 /* discard if it was not boosted */
1346 xs *idx = object_announces(id);
1347
1348 if (xs_list_len(idx) == 0)
1349 continue;
1350 }
1351
1352 /* discard notes from muted morons */
1353 if (is_muted(user, from))
1354 continue;
1355
1356 /* discard hidden notes */
1357 if (is_hidden(user, id))
1358 continue;
1359 }
1360 else {
1361 /* skip non-public messages */
1362 if (!is_msg_public(msg))
1363 continue;
1364
1365 /* discard messages from private users */
1366 if (is_msg_from_private_user(msg))
1367 continue;
1368 }
1369
1370 /* if it has a name and it's not a Page or a Video,
1371 it's a poll vote, so discard it */
1372 if (!xs_is_null(xs_dict_get(msg, "name")) && !xs_match(type, "Page|Video"))
1373 continue;
1374
1375 /* convert the Note into a Mastodon status */
1376 xs *st = mastoapi_status(user, msg);
1377
1378 if (st != NULL) {
1379 out = xs_list_append(out, st);
1380 cnt++;
1381 }
1382
1383 } while (cnt < limit && index_desc_next(f, md5));
1384 }
1385
1386 int more = index_desc_next(f, md5);
1387
1388 fclose(f);
1389
1390 srv_debug(1, xs_fmt("mastoapi_timeline ret %d%s", cnt, more ? " (+)" : ""));
1391
1392 return out;
1393}
1394
1395
1396int mastoapi_get_handler(const xs_dict *req, const char *q_path,
1397 char **body, int *b_size, char **ctype)
1398{
1399 (void)b_size;
1400
1401 if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
1402 return 0;
1403
1404 int status = HTTP_STATUS_NOT_FOUND;
1405 const xs_dict *args = xs_dict_get(req, "q_vars");
1406 xs *cmd = xs_replace_n(q_path, "/api", "", 1);
1407
1408 snac snac1 = {0};
1409 int logged_in = process_auth_token(&snac1, req);
1410
1411 if (strcmp(cmd, "/v1/accounts/verify_credentials") == 0) { /** **/
1412 if (logged_in) {
1413 credentials_get(body, ctype, &status, snac1);
1414 }
1415 else {
1416 status = HTTP_STATUS_UNPROCESSABLE_CONTENT; // (no login)
1417 }
1418 }
1419 else
1420 if (strcmp(cmd, "/v1/accounts/relationships") == 0) { /** **/
1421 /* find if an account is followed, blocked, etc. */
1422 /* the account to get relationships about is in args "id[]" */
1423
1424 if (logged_in) {
1425 xs *res = xs_list_new();
1426 const char *md5 = xs_dict_get(args, "id[]");
1427
1428 if (xs_is_null(md5))
1429 md5 = xs_dict_get(args, "id");
1430
1431 if (!xs_is_null(md5)) {
1432 if (xs_type(md5) == XSTYPE_LIST)
1433 md5 = xs_list_get(md5, 0);
1434
1435 xs *rel = mastoapi_relationship(&snac1, md5);
1436
1437 if (rel != NULL)
1438 res = xs_list_append(res, rel);
1439 }
1440
1441 *body = xs_json_dumps(res, 4);
1442 *ctype = "application/json";
1443 status = HTTP_STATUS_OK;
1444 }
1445 else
1446 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
1447 }
1448 else
1449 if (strcmp(cmd, "/v1/accounts/lookup") == 0) { /** **/
1450 /* lookup an account */
1451 const char *acct = xs_dict_get(args, "acct");
1452
1453 if (!xs_is_null(acct)) {
1454 xs *s = xs_strip_chars_i(xs_dup(acct), "@");
1455 xs *l = xs_split_n(s, "@", 1);
1456 const char *uid = xs_list_get(l, 0);
1457 const char *host = xs_list_get(l, 1);
1458
1459 if (uid && (!host || strcmp(host, xs_dict_get(srv_config, "host")) == 0)) {
1460 snac user;
1461
1462 if (user_open(&user, uid)) {
1463 xs *actor = msg_actor(&user);
1464 xs *macct = mastoapi_account(actor);
1465
1466 *body = xs_json_dumps(macct, 4);
1467 *ctype = "application/json";
1468 status = HTTP_STATUS_OK;
1469
1470 user_free(&user);
1471 }
1472 }
1473 }
1474 }
1475 else
1476 if (xs_startswith(cmd, "/v1/accounts/")) { /** **/
1477 /* account-related information */
1478 xs *l = xs_split(cmd, "/");
1479 const char *uid = xs_list_get(l, 3);
1480 const char *opt = xs_list_get(l, 4);
1481
1482 if (uid != NULL) {
1483 snac snac2;
1484 xs *out = NULL;
1485 xs *actor = NULL;
1486
1487 if (logged_in && strcmp(uid, "search") == 0) { /** **/
1488 /* search for accounts starting with q */
1489 const char *aq = xs_dict_get(args, "q");
1490
1491 if (!xs_is_null(aq)) {
1492 xs *q = xs_tolower_i(xs_dup(aq));
1493 out = xs_list_new();
1494 xs *wing = following_list(&snac1);
1495 xs *wers = follower_list(&snac1);
1496 xs *ulst = user_list();
1497 xs_list *p;
1498 const xs_str *v;
1499 xs_set seen;
1500
1501 xs_set_init(&seen);
1502
1503 /* user relations */
1504 xs_list *lsts[] = { wing, wers, NULL };
1505 int n;
1506 for (n = 0; (p = lsts[n]) != NULL; n++) {
1507
1508 while (xs_list_iter(&p, &v)) {
1509 /* already seen? skip */
1510 if (xs_set_add(&seen, v) == 0)
1511 continue;
1512
1513 xs *actor = NULL;
1514
1515 if (valid_status(object_get(v, &actor))) {
1516 const char *uname = xs_dict_get(actor, "preferredUsername");
1517
1518 if (!xs_is_null(uname)) {
1519 xs *luname = xs_tolower_i(xs_dup(uname));
1520
1521 if (xs_startswith(luname, q)) {
1522 xs *acct = mastoapi_account(actor);
1523
1524 out = xs_list_append(out, acct);
1525 }
1526 }
1527 }
1528 }
1529 }
1530
1531 /* local users */
1532 p = ulst;
1533 while (xs_list_iter(&p, &v)) {
1534 snac user;
1535
1536 /* skip this same user */
1537 if (strcmp(v, xs_dict_get(snac1.config, "uid")) == 0)
1538 continue;
1539
1540 /* skip if the uid does not start with the query */
1541 xs *v2 = xs_tolower_i(xs_dup(v));
1542 if (!xs_startswith(v2, q))
1543 continue;
1544
1545 if (user_open(&user, v)) {
1546 /* if it's not already seen, add it */
1547 if (xs_set_add(&seen, user.actor) == 1) {
1548 xs *actor = msg_actor(&user);
1549 xs *acct = mastoapi_account(actor);
1550
1551 out = xs_list_append(out, acct);
1552 }
1553
1554 user_free(&user);
1555 }
1556 }
1557
1558 xs_set_free(&seen);
1559 }
1560 }
1561 else
1562 /* is it a local user? */
1563 if (user_open(&snac2, uid) || user_open_by_md5(&snac2, uid)) {
1564 if (opt == NULL) {
1565 /* account information */
1566 actor = msg_actor(&snac2);
1567 out = mastoapi_account(actor);
1568 }
1569 else
1570 if (strcmp(opt, "statuses") == 0) { /** **/
1571 /* the public list of posts of a user */
1572 xs *timeline = timeline_simple_list(&snac2, "public", 0, 256);
1573 xs_list *p = timeline;
1574 const xs_str *v;
1575
1576 out = xs_list_new();
1577
1578 while (xs_list_iter(&p, &v)) {
1579 xs *msg = NULL;
1580
1581 if (valid_status(timeline_get_by_md5(&snac2, v, &msg))) {
1582 /* add only posts by the author */
1583 if (strcmp(xs_dict_get(msg, "type"), "Note") == 0 &&
1584 xs_startswith(xs_dict_get(msg, "id"), snac2.actor)) {
1585 xs *st = mastoapi_status(&snac2, msg);
1586
1587 if (st)
1588 out = xs_list_append(out, st);
1589 }
1590 }
1591 }
1592 }
1593 else
1594 if (strcmp(opt, "featured_tags") == 0) {
1595 /* snac doesn't have features tags, yet? */
1596 /* implement empty response so apps like Tokodon don't show an error */
1597 out = xs_list_new();
1598 }
1599 else
1600 if (strcmp(opt, "following") == 0) {
1601 xs *wing = following_list(&snac1);
1602 out = xs_list_new();
1603 int c = 0;
1604 const char *v;
1605
1606 while (xs_list_next(wing, &v, &c)) {
1607 xs *actor = NULL;
1608
1609 if (valid_status(object_get(v, &actor))) {
1610 xs *acct = mastoapi_account(actor);
1611 out = xs_list_append(out, acct);
1612 }
1613 }
1614 }
1615 else
1616 if (strcmp(opt, "followers") == 0) {
1617 out = xs_list_new();
1618 }
1619
1620 user_free(&snac2);
1621 }
1622 else {
1623 /* try the uid as the md5 of a possibly loaded actor */
1624 if (logged_in && valid_status(object_get_by_md5(uid, &actor))) {
1625 if (opt == NULL) {
1626 /* account information */
1627 out = mastoapi_account(actor);
1628 }
1629 else
1630 if (strcmp(opt, "statuses") == 0) {
1631 /* we don't serve statuses of others; return the empty list */
1632 out = xs_list_new();
1633 }
1634 else
1635 if (strcmp(opt, "featured_tags") == 0) {
1636 /* snac doesn't have features tags, yet? */
1637 /* implement empty response so apps like Tokodon don't show an error */
1638 out = xs_list_new();
1639 }
1640 }
1641 }
1642
1643 if (out != NULL) {
1644 *body = xs_json_dumps(out, 4);
1645 *ctype = "application/json";
1646 status = HTTP_STATUS_OK;
1647 }
1648 }
1649 }
1650 else
1651 if (strcmp(cmd, "/v1/timelines/home") == 0) { /** **/
1652 /* the private timeline */
1653 if (logged_in) {
1654 xs *ifn = user_index_fn(&snac1, "private");
1655 xs *out = mastoapi_timeline(&snac1, args, ifn);
1656
1657 *body = xs_json_dumps(out, 4);
1658 *ctype = "application/json";
1659 status = HTTP_STATUS_OK;
1660
1661 srv_debug(2, xs_fmt("mastoapi timeline: returned %d entries", xs_list_len(out)));
1662 }
1663 else {
1664 status = HTTP_STATUS_UNAUTHORIZED;
1665 }
1666 }
1667 else
1668 if (strcmp(cmd, "/v1/timelines/public") == 0) { /** **/
1669 /* the instance public timeline (public timelines for all users) */
1670 xs *ifn = instance_index_fn();
1671 xs *out = mastoapi_timeline(NULL, args, ifn);
1672
1673 *body = xs_json_dumps(out, 4);
1674 *ctype = "application/json";
1675 status = HTTP_STATUS_OK;
1676 }
1677 else
1678 if (xs_startswith(cmd, "/v1/timelines/tag/")) { /** **/
1679 /* get the tag */
1680 xs *l = xs_split(cmd, "/");
1681 const char *tag = xs_list_get(l, -1);
1682
1683 xs *ifn = tag_fn(tag);
1684 xs *out = mastoapi_timeline(NULL, args, ifn);
1685
1686 *body = xs_json_dumps(out, 4);
1687 *ctype = "application/json";
1688 status = HTTP_STATUS_OK;
1689 }
1690 else
1691 if (xs_startswith(cmd, "/v1/timelines/list/")) { /** **/
1692 /* get the list id */
1693 if (logged_in) {
1694 xs *l = xs_split(cmd, "/");
1695 const char *list = xs_list_get(l, -1);
1696
1697 xs *ifn = list_timeline_fn(&snac1, list);
1698 xs *out = mastoapi_timeline(NULL, args, ifn);
1699
1700 *body = xs_json_dumps(out, 4);
1701 *ctype = "application/json";
1702 status = HTTP_STATUS_OK;
1703 }
1704 else
1705 status = HTTP_STATUS_MISDIRECTED_REQUEST;
1706 }
1707 else
1708 if (strcmp(cmd, "/v1/conversations") == 0) { /** **/
1709 /* TBD */
1710 *body = xs_dup("[]");
1711 *ctype = "application/json";
1712 status = HTTP_STATUS_OK;
1713 }
1714 else
1715 if (strcmp(cmd, "/v1/notifications") == 0) { /** **/
1716 if (logged_in) {
1717 xs *l = notify_list(&snac1, 0, 64);
1718 xs *out = xs_list_new();
1719 xs_list *p = l;
1720 const xs_dict *v;
1721 const xs_list *excl = xs_dict_get(args, "exclude_types[]");
1722
1723 while (xs_list_iter(&p, &v)) {
1724 xs *noti = notify_get(&snac1, v);
1725
1726 if (noti == NULL)
1727 continue;
1728
1729 const char *type = xs_dict_get(noti, "type");
1730 const char *utype = xs_dict_get(noti, "utype");
1731 const char *objid = xs_dict_get(noti, "objid");
1732 xs *actor = NULL;
1733 xs *entry = NULL;
1734
1735 if (!valid_status(actor_get(xs_dict_get(noti, "actor"), &actor)))
1736 continue;
1737
1738 if (objid != NULL && !valid_status(object_get(objid, &entry)))
1739 continue;
1740
1741 if (is_hidden(&snac1, objid))
1742 continue;
1743
1744 /* convert the type */
1745 if (strcmp(type, "Like") == 0 || strcmp(type, "EmojiReact") == 0)
1746 type = "favourite";
1747 else
1748 if (strcmp(type, "Announce") == 0)
1749 type = "reblog";
1750 else
1751 if (strcmp(type, "Follow") == 0)
1752 type = "follow";
1753 else
1754 if (strcmp(type, "Create") == 0)
1755 type = "mention";
1756 else
1757 if (strcmp(type, "Update") == 0 && strcmp(utype, "Question") == 0)
1758 type = "poll";
1759 else
1760 continue;
1761
1762 /* excluded type? */
1763 if (!xs_is_null(excl) && xs_list_in(excl, type) != -1)
1764 continue;
1765
1766 xs *mn = xs_dict_new();
1767
1768 mn = xs_dict_append(mn, "type", type);
1769
1770 xs *id = xs_replace(xs_dict_get(noti, "id"), ".", "");
1771 mn = xs_dict_append(mn, "id", id);
1772
1773 mn = xs_dict_append(mn, "created_at", xs_dict_get(noti, "date"));
1774
1775 xs *acct = mastoapi_account(actor);
1776 mn = xs_dict_append(mn, "account", acct);
1777
1778 if (strcmp(type, "follow") != 0 && !xs_is_null(objid)) {
1779 xs *st = mastoapi_status(&snac1, entry);
1780
1781 if (st)
1782 mn = xs_dict_append(mn, "status", st);
1783 }
1784
1785 out = xs_list_append(out, mn);
1786 }
1787
1788 *body = xs_json_dumps(out, 4);
1789 *ctype = "application/json";
1790 status = HTTP_STATUS_OK;
1791 }
1792 else
1793 status = HTTP_STATUS_UNAUTHORIZED;
1794 }
1795 else
1796 if (strcmp(cmd, "/v1/filters") == 0) { /** **/
1797 /* snac will never have filters */
1798 *body = xs_dup("[]");
1799 *ctype = "application/json";
1800 status = HTTP_STATUS_OK;
1801 }
1802 else
1803 if (strcmp(cmd, "/v2/filters") == 0) { /** **/
1804 /* snac will never have filters
1805 * but still, without a v2 endpoint a short delay is introduced
1806 * in some apps */
1807 *body = xs_dup("[]");
1808 *ctype = "application/json";
1809 status = HTTP_STATUS_OK;
1810 }
1811 else
1812 if (strcmp(cmd, "/v1/favourites") == 0) { /** **/
1813 /* snac will never support a list of favourites */
1814 *body = xs_dup("[]");
1815 *ctype = "application/json";
1816 status = HTTP_STATUS_OK;
1817 }
1818 else
1819 if (strcmp(cmd, "/v1/bookmarks") == 0) { /** **/
1820 if (logged_in) {
1821 xs *ifn = bookmark_index_fn(&snac1);
1822 xs *out = mastoapi_timeline(&snac1, args, ifn);
1823
1824 *body = xs_json_dumps(out, 4);
1825 *ctype = "application/json";
1826 status = HTTP_STATUS_OK;
1827 }
1828 else
1829 status = HTTP_STATUS_UNAUTHORIZED;
1830 }
1831 else
1832 if (strcmp(cmd, "/v1/lists") == 0) { /** list of lists **/
1833 if (logged_in) {
1834 xs *lol = list_maint(&snac1, NULL, 0);
1835 xs *l = xs_list_new();
1836 int c = 0;
1837 const xs_list *li;
1838
1839 while (xs_list_next(lol, &li, &c)) {
1840 xs *d = xs_dict_new();
1841
1842 d = xs_dict_append(d, "id", xs_list_get(li, 0));
1843 d = xs_dict_append(d, "title", xs_list_get(li, 1));
1844 d = xs_dict_append(d, "replies_policy", "list");
1845 d = xs_dict_append(d, "exclusive", xs_stock(XSTYPE_FALSE));
1846
1847 l = xs_list_append(l, d);
1848 }
1849
1850 *body = xs_json_dumps(l, 4);
1851 *ctype = "application/json";
1852 status = HTTP_STATUS_OK;
1853 }
1854 else
1855 status = HTTP_STATUS_UNAUTHORIZED;
1856 }
1857 else
1858 if (xs_startswith(cmd, "/v1/lists/")) { /** list information **/
1859 if (logged_in) {
1860 xs *l = xs_split(cmd, "/");
1861 const char *p = xs_list_get(l, -1);
1862
1863 if (p) {
1864 if (strcmp(p, "accounts") == 0) {
1865 p = xs_list_get(l, -2);
1866
1867 if (p && xs_is_hex(p)) {
1868 xs *actors = list_content(&snac1, p, NULL, 0);
1869 xs *out = xs_list_new();
1870 int c = 0;
1871 const char *v;
1872
1873 while (xs_list_next(actors, &v, &c)) {
1874 xs *actor = NULL;
1875
1876 if (valid_status(object_get_by_md5(v, &actor))) {
1877 xs *acct = mastoapi_account(actor);
1878 out = xs_list_append(out, acct);
1879 }
1880 }
1881
1882 *body = xs_json_dumps(out, 4);
1883 *ctype = "application/json";
1884 status = HTTP_STATUS_OK;
1885 }
1886 }
1887 else
1888 if (xs_is_hex(p)) {
1889 xs *out = xs_list_new();
1890 xs *lol = list_maint(&snac1, NULL, 0);
1891 int c = 0;
1892 const xs_list *v;
1893
1894 while (xs_list_next(lol, &v, &c)) {
1895 const char *id = xs_list_get(v, 0);
1896
1897 if (id && strcmp(id, p) == 0) {
1898 xs *d = xs_dict_new();
1899
1900 d = xs_dict_append(d, "id", p);
1901 d = xs_dict_append(d, "title", xs_list_get(v, 1));
1902 d = xs_dict_append(d, "replies_policy", "list");
1903 d = xs_dict_append(d, "exclusive", xs_stock(XSTYPE_FALSE));
1904
1905 out = xs_dup(d);
1906 break;
1907 }
1908 }
1909
1910 *body = xs_json_dumps(out, 4);
1911 *ctype = "application/json";
1912 status = HTTP_STATUS_OK;
1913 }
1914 }
1915 }
1916 else
1917 status = HTTP_STATUS_UNAUTHORIZED;
1918 }
1919 else
1920 if (strcmp(cmd, "/v1/scheduled_statuses") == 0) { /** **/
1921 /* snac does not schedule notes */
1922 *body = xs_dup("[]");
1923 *ctype = "application/json";
1924 status = HTTP_STATUS_OK;
1925 }
1926 else
1927 if (strcmp(cmd, "/v1/follow_requests") == 0) { /** **/
1928 /* snac does not support optional follow confirmations */
1929 *body = xs_dup("[]");
1930 *ctype = "application/json";
1931 status = HTTP_STATUS_OK;
1932 }
1933 else
1934 if (strcmp(cmd, "/v1/announcements") == 0) { /** **/
1935 if (logged_in) {
1936 xs *resp = xs_list_new();
1937 double la = 0.0;
1938 xs *user_la = xs_dup(xs_dict_get(snac1.config, "last_announcement"));
1939 if (user_la != NULL)
1940 la = xs_number_get(user_la);
1941 xs *val_date = xs_str_utctime(la, ISO_DATE_SPEC);
1942
1943 /* contrary to html, we always send the announcement and set the read flag instead */
1944
1945 const t_announcement *annce = announcement(la);
1946 if (annce != NULL && annce->text != NULL) {
1947 xs *an = xs_dict_new();
1948 xs *id = xs_fmt("%d", annce->timestamp);
1949 xs *ct = xs_fmt("<p>%s</p>", annce->text);
1950
1951 an = xs_dict_set(an, "id", id);
1952 an = xs_dict_set(an, "content", ct);
1953 an = xs_dict_set(an, "starts_at", xs_stock(XSTYPE_NULL));
1954 an = xs_dict_set(an, "ends_at", xs_stock(XSTYPE_NULL));
1955 an = xs_dict_set(an, "all_day", xs_stock(XSTYPE_TRUE));
1956 an = xs_dict_set(an, "published_at", val_date);
1957 an = xs_dict_set(an, "updated_at", val_date);
1958 an = xs_dict_set(an, "read", (annce->timestamp >= la)
1959 ? xs_stock(XSTYPE_FALSE) : xs_stock(XSTYPE_TRUE));
1960 an = xs_dict_set(an, "mentions", xs_stock(XSTYPE_LIST));
1961 an = xs_dict_set(an, "statuses", xs_stock(XSTYPE_LIST));
1962 an = xs_dict_set(an, "tags", xs_stock(XSTYPE_LIST));
1963 an = xs_dict_set(an, "emojis", xs_stock(XSTYPE_LIST));
1964 an = xs_dict_set(an, "reactions", xs_stock(XSTYPE_LIST));
1965 resp = xs_list_append(resp, an);
1966 }
1967
1968 *body = xs_json_dumps(resp, 4);
1969 *ctype = "application/json";
1970 status = HTTP_STATUS_OK;
1971 }
1972 }
1973 else
1974 if (strcmp(cmd, "/v1/custom_emojis") == 0) { /** **/
1975 /* are you kidding me? */
1976 *body = xs_dup("[]");
1977 *ctype = "application/json";
1978 status = HTTP_STATUS_OK;
1979 }
1980 else
1981 if (strcmp(cmd, "/v1/instance") == 0) { /** **/
1982 /* returns an instance object */
1983 xs *ins = xs_dict_new();
1984 const char *host = xs_dict_get(srv_config, "host");
1985 const char *title = xs_dict_get(srv_config, "title");
1986 const char *sdesc = xs_dict_get(srv_config, "short_description");
1987
1988 ins = xs_dict_append(ins, "uri", host);
1989 ins = xs_dict_append(ins, "domain", host);
1990 ins = xs_dict_append(ins, "title", title && *title ? title : host);
1991 ins = xs_dict_append(ins, "version", "4.0.0 (not true; really " USER_AGENT ")");
1992 ins = xs_dict_append(ins, "source_url", WHAT_IS_SNAC_URL);
1993 ins = xs_dict_append(ins, "description", host);
1994
1995 ins = xs_dict_append(ins, "short_description", sdesc && *sdesc ? sdesc : host);
1996
1997 xs *susie = xs_fmt("%s/susie.png", srv_baseurl);
1998 ins = xs_dict_append(ins, "thumbnail", susie);
1999
2000 const char *v = xs_dict_get(srv_config, "admin_email");
2001 if (xs_is_null(v) || *v == '\0')
2002 v = "admin@localhost";
2003
2004 ins = xs_dict_append(ins, "email", v);
2005
2006 ins = xs_dict_append(ins, "rules", xs_stock(XSTYPE_LIST));
2007
2008 xs *l1 = xs_list_append(xs_list_new(), "en");
2009 ins = xs_dict_append(ins, "languages", l1);
2010
2011 xs *wss = xs_fmt("wss:/" "/%s", xs_dict_get(srv_config, "host"));
2012 xs *urls = xs_dict_new();
2013 urls = xs_dict_append(urls, "streaming_api", wss);
2014
2015 ins = xs_dict_append(ins, "urls", urls);
2016
2017 xs *d2 = xs_dict_append(xs_dict_new(), "user_count", xs_stock(0));
2018 d2 = xs_dict_append(d2, "status_count", xs_stock(0));
2019 d2 = xs_dict_append(d2, "domain_count", xs_stock(0));
2020 ins = xs_dict_append(ins, "stats", d2);
2021
2022 ins = xs_dict_append(ins, "registrations", xs_stock(XSTYPE_FALSE));
2023 ins = xs_dict_append(ins, "approval_required", xs_stock(XSTYPE_FALSE));
2024 ins = xs_dict_append(ins, "invites_enabled", xs_stock(XSTYPE_FALSE));
2025
2026 xs *cfg = xs_dict_new();
2027
2028 {
2029 xs *d11 = xs_json_loads("{\"characters_reserved_per_url\":32,"
2030 "\"max_characters\":100000,\"max_media_attachments\":8}");
2031 cfg = xs_dict_append(cfg, "statuses", d11);
2032
2033 xs *d12 = xs_json_loads("{\"max_featured_tags\":0}");
2034 cfg = xs_dict_append(cfg, "accounts", d12);
2035
2036 xs *d13 = xs_json_loads("{\"image_matrix_limit\":33177600,"
2037 "\"image_size_limit\":16777216,"
2038 "\"video_frame_rate_limit\":120,"
2039 "\"video_matrix_limit\":8294400,"
2040 "\"video_size_limit\":103809024}"
2041 );
2042
2043 {
2044 /* get the supported mime types from the internal list */
2045 const char **p = xs_mime_types;
2046 xs_set mtypes;
2047 xs_set_init(&mtypes);
2048
2049 while (*p) {
2050 const char *type = p[1];
2051
2052 if (xs_startswith(type, "image/") ||
2053 xs_startswith(type, "video/") ||
2054 xs_startswith(type, "audio/"))
2055 xs_set_add(&mtypes, type);
2056
2057 p += 2;
2058 }
2059
2060 xs *l = xs_set_result(&mtypes);
2061 d13 = xs_dict_append(d13, "supported_mime_types", l);
2062 }
2063
2064 cfg = xs_dict_append(cfg, "media_attachments", d13);
2065
2066 xs *d14 = xs_json_loads("{\"max_characters_per_option\":50,"
2067 "\"max_expiration\":2629746,"
2068 "\"max_options\":8,\"min_expiration\":300}");
2069 cfg = xs_dict_append(cfg, "polls", d14);
2070 }
2071
2072 ins = xs_dict_append(ins, "configuration", cfg);
2073
2074 const char *admin_account = xs_dict_get(srv_config, "admin_account");
2075
2076 if (!xs_is_null(admin_account) && *admin_account) {
2077 snac admin;
2078
2079 if (user_open(&admin, admin_account)) {
2080 xs *actor = msg_actor(&admin);
2081 xs *acct = mastoapi_account(actor);
2082
2083 ins = xs_dict_append(ins, "contact_account", acct);
2084
2085 user_free(&admin);
2086 }
2087 }
2088
2089 *body = xs_json_dumps(ins, 4);
2090 *ctype = "application/json";
2091 status = HTTP_STATUS_OK;
2092 }
2093 else
2094 if (xs_startswith(cmd, "/v1/statuses/")) { /** **/
2095 /* information about a status */
2096 if (logged_in) {
2097 xs *l = xs_split(cmd, "/");
2098 const char *id = xs_list_get(l, 3);
2099 const char *op = xs_list_get(l, 4);
2100
2101 if (!xs_is_null(id)) {
2102 xs *msg = NULL;
2103 xs *out = NULL;
2104
2105 /* skip the 'fake' part of the id */
2106 id = MID_TO_MD5(id);
2107
2108 if (valid_status(object_get_by_md5(id, &msg))) {
2109 if (op == NULL) {
2110 if (!is_muted(&snac1, get_atto(msg))) {
2111 /* return the status itself */
2112 out = mastoapi_status(&snac1, msg);
2113 }
2114 }
2115 else
2116 if (strcmp(op, "context") == 0) { /** **/
2117 /* return ancestors and children */
2118 xs *anc = xs_list_new();
2119 xs *des = xs_list_new();
2120 xs_list *p;
2121 const xs_str *v;
2122 char pid[MD5_HEX_SIZE];
2123
2124 /* build the [grand]parent list, moving up */
2125 strncpy(pid, id, sizeof(pid));
2126
2127 while (object_parent(pid, pid)) {
2128 xs *m2 = NULL;
2129
2130 if (valid_status(timeline_get_by_md5(&snac1, pid, &m2))) {
2131 xs *st = mastoapi_status(&snac1, m2);
2132
2133 if (st)
2134 anc = xs_list_insert(anc, 0, st);
2135 }
2136 else
2137 break;
2138 }
2139
2140 /* build the children list */
2141 xs *children = object_children(xs_dict_get(msg, "id"));
2142 p = children;
2143
2144 while (xs_list_iter(&p, &v)) {
2145 xs *m2 = NULL;
2146
2147 if (valid_status(timeline_get_by_md5(&snac1, v, &m2))) {
2148 if (xs_is_null(xs_dict_get(m2, "name"))) {
2149 xs *st = mastoapi_status(&snac1, m2);
2150
2151 if (st)
2152 des = xs_list_append(des, st);
2153 }
2154 }
2155 }
2156
2157 out = xs_dict_new();
2158 out = xs_dict_append(out, "ancestors", anc);
2159 out = xs_dict_append(out, "descendants", des);
2160 }
2161 else
2162 if (strcmp(op, "reblogged_by") == 0 || /** **/
2163 strcmp(op, "favourited_by") == 0) { /** **/
2164 /* return the list of people who liked or boosted this */
2165 out = xs_list_new();
2166
2167 xs *l = NULL;
2168
2169 if (op[0] == 'r')
2170 l = object_announces(xs_dict_get(msg, "id"));
2171 else
2172 l = object_likes(xs_dict_get(msg, "id"));
2173
2174 xs_list *p = l;
2175 const xs_str *v;
2176
2177 while (xs_list_iter(&p, &v)) {
2178 xs *actor2 = NULL;
2179
2180 if (valid_status(object_get_by_md5(v, &actor2))) {
2181 xs *acct2 = mastoapi_account(actor2);
2182
2183 out = xs_list_append(out, acct2);
2184 }
2185 }
2186 }
2187 else
2188 if (strcmp(op, "source") == 0) { /** **/
2189 out = xs_dict_new();
2190
2191 /* get the mastoapi status id */
2192 out = xs_dict_append(out, "id", xs_list_get(l, 3));
2193
2194 out = xs_dict_append(out, "text", xs_dict_get(msg, "sourceContent"));
2195 out = xs_dict_append(out, "spoiler_text", xs_dict_get(msg, "summary"));
2196 }
2197 }
2198 else
2199 srv_debug(1, xs_fmt("mastoapi status: bad id %s", id));
2200
2201 if (out != NULL) {
2202 *body = xs_json_dumps(out, 4);
2203 *ctype = "application/json";
2204 status = HTTP_STATUS_OK;
2205 }
2206 }
2207 }
2208 else
2209 status = HTTP_STATUS_UNAUTHORIZED;
2210 }
2211 else
2212 if (strcmp(cmd, "/v1/preferences") == 0) { /** **/
2213 *body = xs_dup("{}");
2214 *ctype = "application/json";
2215 status = HTTP_STATUS_OK;
2216 }
2217 else
2218 if (strcmp(cmd, "/v1/markers") == 0) { /** **/
2219 *body = xs_dup("{}");
2220 *ctype = "application/json";
2221 status = HTTP_STATUS_OK;
2222 }
2223 else
2224 if (strcmp(cmd, "/v1/followed_tags") == 0) { /** **/
2225 *body = xs_dup("[]");
2226 *ctype = "application/json";
2227 status = HTTP_STATUS_OK;
2228 }
2229 else
2230 if (strcmp(cmd, "/v1/trends/tags") == 0) { /** **/
2231 *body = xs_dup("[]");
2232 *ctype = "application/json";
2233 status = HTTP_STATUS_OK;
2234 }
2235 else
2236 if (strcmp(cmd, "/v1/trends/statuses") == 0) { /** **/
2237 *body = xs_dup("[]");
2238 *ctype = "application/json";
2239 status = HTTP_STATUS_OK;
2240 }
2241 else
2242 if (strcmp(cmd, "/v2/search") == 0) { /** **/
2243 if (logged_in) {
2244 const char *q = xs_dict_get(args, "q");
2245 const char *type = xs_dict_get(args, "type");
2246 const char *offset = xs_dict_get(args, "offset");
2247
2248 xs *acl = xs_list_new();
2249 xs *stl = xs_list_new();
2250 xs *htl = xs_list_new();
2251 xs *res = xs_dict_new();
2252
2253 if (xs_is_null(offset) || strcmp(offset, "0") == 0) {
2254 /* reply something only for offset 0; otherwise,
2255 apps like Tusky keep asking again and again */
2256
2257 if (!xs_is_null(q)) {
2258 if (xs_is_null(type) || strcmp(type, "accounts") == 0) {
2259 /* do a webfinger query */
2260 char *actor = NULL;
2261 char *user = NULL;
2262
2263 if (valid_status(webfinger_request(q, &actor, &user)) && actor) {
2264 xs *actor_o = NULL;
2265
2266 if (valid_status(actor_request(&snac1, actor, &actor_o))) {
2267 xs *acct = mastoapi_account(actor_o);
2268
2269 acl = xs_list_append(acl, acct);
2270
2271 if (!object_here(actor))
2272 object_add(actor, actor_o);
2273 }
2274 }
2275 }
2276
2277 if (xs_is_null(type) || strcmp(type, "hashtags") == 0) {
2278 /* search this tag */
2279 xs *tl = tag_search((char *)q, 0, 1);
2280
2281 if (xs_list_len(tl)) {
2282 xs *d = xs_dict_new();
2283
2284 d = xs_dict_append(d, "name", q);
2285 xs *url = xs_fmt("%s?t=%s", srv_baseurl, q);
2286 d = xs_dict_append(d, "url", url);
2287 d = xs_dict_append(d, "history", xs_stock(XSTYPE_LIST));
2288
2289 htl = xs_list_append(htl, d);
2290 }
2291 }
2292
2293 if (xs_is_null(type) || strcmp(type, "statuses") == 0) {
2294 int to = 0;
2295 int cnt = 40;
2296 xs *tl = content_search(&snac1, q, 1, 0, cnt, 0, &to);
2297 int c = 0;
2298 const char *v;
2299
2300 while (xs_list_next(tl, &v, &c) && --cnt) {
2301 xs *post = NULL;
2302
2303 if (!valid_status(timeline_get_by_md5(&snac1, v, &post)))
2304 continue;
2305
2306 xs *s = mastoapi_status(&snac1, post);
2307
2308 if (!xs_is_null(s))
2309 stl = xs_list_append(stl, s);
2310 }
2311 }
2312 }
2313 }
2314
2315 res = xs_dict_append(res, "accounts", acl);
2316 res = xs_dict_append(res, "statuses", stl);
2317 res = xs_dict_append(res, "hashtags", htl);
2318
2319 *body = xs_json_dumps(res, 4);
2320 *ctype = "application/json";
2321 status = HTTP_STATUS_OK;
2322 }
2323 else
2324 status = HTTP_STATUS_UNAUTHORIZED;
2325 }
2326
2327 /* user cleanup */
2328 if (logged_in)
2329 user_free(&snac1);
2330
2331 srv_debug(1, xs_fmt("mastoapi_get_handler %s %d", q_path, status));
2332
2333 return status;
2334}
2335
2336
2337int mastoapi_post_handler(const xs_dict *req, const char *q_path,
2338 const char *payload, int p_size,
2339 char **body, int *b_size, char **ctype)
2340{
2341 (void)p_size;
2342 (void)b_size;
2343
2344 if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
2345 return 0;
2346
2347 int status = HTTP_STATUS_NOT_FOUND;
2348 xs *args = NULL;
2349 const char *i_ctype = xs_dict_get(req, "content-type");
2350
2351 if (i_ctype && xs_startswith(i_ctype, "application/json")) {
2352 if (!xs_is_null(payload))
2353 args = xs_json_loads(payload);
2354 }
2355 else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
2356 {
2357 // Some apps send form data instead of json so we should cater for those
2358 if (!xs_is_null(payload)) {
2359 args = xs_url_vars(payload);
2360 }
2361 }
2362 else
2363 args = xs_dup(xs_dict_get(req, "p_vars"));
2364
2365 if (args == NULL)
2366 return HTTP_STATUS_BAD_REQUEST;
2367
2368 xs *cmd = xs_replace_n(q_path, "/api", "", 1);
2369
2370 snac snac = {0};
2371 int logged_in = process_auth_token(&snac, req);
2372
2373 if (strcmp(cmd, "/v1/apps") == 0) { /** **/
2374 const char *name = xs_dict_get(args, "client_name");
2375 const char *ruri = xs_dict_get(args, "redirect_uris");
2376 const char *scope = xs_dict_get(args, "scope");
2377
2378 /* Ice Cubes sends these values as query parameters, so try these */
2379 if (name == NULL && ruri == NULL && scope == NULL) {
2380 args = xs_dup(xs_dict_get(req, "q_vars"));
2381 name = xs_dict_get(args, "client_name");
2382 ruri = xs_dict_get(args, "redirect_uris");
2383 scope = xs_dict_get(args, "scope");
2384 }
2385
2386 if (xs_type(ruri) == XSTYPE_LIST)
2387 ruri = xs_dict_get(ruri, 0);
2388
2389 if (name && ruri) {
2390 xs *app = xs_dict_new();
2391 xs *id = xs_replace_i(tid(0), ".", "");
2392 xs *csec = random_str();
2393 xs *vkey = random_str();
2394 xs *cid = NULL;
2395
2396 /* pick a non-existent random cid */
2397 for (;;) {
2398 cid = random_str();
2399 xs *p_app = app_get(cid);
2400
2401 if (p_app == NULL)
2402 break;
2403
2404 xs_free(cid);
2405 }
2406
2407 app = xs_dict_append(app, "name", name);
2408 app = xs_dict_append(app, "redirect_uri", ruri);
2409 app = xs_dict_append(app, "client_id", cid);
2410 app = xs_dict_append(app, "client_secret", csec);
2411 app = xs_dict_append(app, "vapid_key", vkey);
2412 app = xs_dict_append(app, "id", id);
2413
2414 *body = xs_json_dumps(app, 4);
2415 *ctype = "application/json";
2416 status = HTTP_STATUS_OK;
2417
2418 app = xs_dict_append(app, "code", "");
2419
2420 if (scope)
2421 app = xs_dict_append(app, "scope", scope);
2422
2423 app_add(cid, app);
2424
2425 srv_debug(1, xs_fmt("mastoapi apps: new app %s", cid));
2426 }
2427 }
2428 else
2429 if (strcmp(cmd, "/v1/statuses") == 0) { /** **/
2430 if (logged_in) {
2431 /* post a new Note */
2432 const char *content = xs_dict_get(args, "status");
2433 const char *mid = xs_dict_get(args, "in_reply_to_id");
2434 const char *visibility = xs_dict_get(args, "visibility");
2435 const char *summary = xs_dict_get(args, "spoiler_text");
2436 const char *media_ids = xs_dict_get(args, "media_ids");
2437
2438 if (xs_is_null(media_ids))
2439 media_ids = xs_dict_get(args, "media_ids[]");
2440
2441 if (xs_is_null(media_ids))
2442 media_ids = xs_dict_get(args, "media_ids");
2443
2444 if (xs_is_null(visibility))
2445 visibility = "public";
2446
2447 xs *attach_list = xs_list_new();
2448 xs *irt = NULL;
2449
2450 /* is it a reply? */
2451 if (mid != NULL) {
2452 xs *r_msg = NULL;
2453 const char *md5 = MID_TO_MD5(mid);
2454
2455 if (valid_status(object_get_by_md5(md5, &r_msg)))
2456 irt = xs_dup(xs_dict_get(r_msg, "id"));
2457 }
2458
2459 /* does it have attachments? */
2460 if (!xs_is_null(media_ids)) {
2461 xs *mi = NULL;
2462
2463 if (xs_type(media_ids) == XSTYPE_LIST)
2464 mi = xs_dup(media_ids);
2465 else {
2466 mi = xs_list_new();
2467 mi = xs_list_append(mi, media_ids);
2468 }
2469
2470 xs_list *p = mi;
2471 const xs_str *v;
2472
2473 while (xs_list_iter(&p, &v)) {
2474 xs *l = xs_list_new();
2475 xs *url = xs_fmt("%s/s/%s", snac.actor, v);
2476 xs *desc = static_get_meta(&snac, v);
2477
2478 l = xs_list_append(l, url);
2479 l = xs_list_append(l, desc);
2480
2481 attach_list = xs_list_append(attach_list, l);
2482 }
2483 }
2484
2485 /* prepare the message */
2486 xs *msg = msg_note(&snac, content, NULL, irt, attach_list,
2487 strcmp(visibility, "public") == 0 ? 0 : 1);
2488
2489 if (!xs_is_null(summary) && *summary) {
2490 msg = xs_dict_set(msg, "sensitive", xs_stock(XSTYPE_TRUE));
2491 msg = xs_dict_set(msg, "summary", summary);
2492 }
2493
2494 /* store */
2495 timeline_add(&snac, xs_dict_get(msg, "id"), msg);
2496
2497 /* 'Create' message */
2498 xs *c_msg = msg_create(&snac, msg);
2499 enqueue_message(&snac, c_msg);
2500
2501 timeline_touch(&snac);
2502
2503 /* convert to a mastodon status as a response code */
2504 xs *st = mastoapi_status(&snac, msg);
2505
2506 *body = xs_json_dumps(st, 4);
2507 *ctype = "application/json";
2508 status = HTTP_STATUS_OK;
2509 }
2510 else
2511 status = HTTP_STATUS_UNAUTHORIZED;
2512 }
2513 else
2514 if (xs_startswith(cmd, "/v1/statuses")) { /** **/
2515 if (logged_in) {
2516 /* operations on a status */
2517 xs *l = xs_split(cmd, "/");
2518 const char *mid = xs_list_get(l, 3);
2519 const char *op = xs_list_get(l, 4);
2520
2521 if (!xs_is_null(mid)) {
2522 xs *msg = NULL;
2523 xs *out = NULL;
2524
2525 /* skip the 'fake' part of the id */
2526 mid = MID_TO_MD5(mid);
2527
2528 if (valid_status(timeline_get_by_md5(&snac, mid, &msg))) {
2529 const char *id = xs_dict_get(msg, "id");
2530
2531 if (op == NULL) {
2532 /* no operation (?) */
2533 }
2534 else
2535 if (strcmp(op, "favourite") == 0) { /** **/
2536 xs *n_msg = msg_admiration(&snac, id, "Like");
2537
2538 if (n_msg != NULL) {
2539 enqueue_message(&snac, n_msg);
2540 timeline_admire(&snac, xs_dict_get(n_msg, "object"), snac.actor, 1);
2541
2542 out = mastoapi_status(&snac, msg);
2543 }
2544 }
2545 else
2546 if (strcmp(op, "unfavourite") == 0) { /** **/
2547 xs *n_msg = msg_repulsion(&snac, id, "Like");
2548
2549 if (n_msg != NULL) {
2550 enqueue_message(&snac, n_msg);
2551
2552 out = mastoapi_status(&snac, msg);
2553 }
2554 }
2555 else
2556 if (strcmp(op, "reblog") == 0) { /** **/
2557 xs *n_msg = msg_admiration(&snac, id, "Announce");
2558
2559 if (n_msg != NULL) {
2560 enqueue_message(&snac, n_msg);
2561 timeline_admire(&snac, xs_dict_get(n_msg, "object"), snac.actor, 0);
2562
2563 out = mastoapi_status(&snac, msg);
2564 }
2565 }
2566 else
2567 if (strcmp(op, "unreblog") == 0) { /** **/
2568 xs *n_msg = msg_repulsion(&snac, id, "Announce");
2569
2570 if (n_msg != NULL) {
2571 enqueue_message(&snac, n_msg);
2572
2573 out = mastoapi_status(&snac, msg);
2574 }
2575 }
2576 else
2577 if (strcmp(op, "bookmark") == 0) { /** **/
2578 /* bookmark this message */
2579 if (bookmark(&snac, id) == 0)
2580 out = mastoapi_status(&snac, msg);
2581 else
2582 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2583 }
2584 else
2585 if (strcmp(op, "unbookmark") == 0) { /** **/
2586 /* unbookmark this message */
2587 unbookmark(&snac, id);
2588 out = mastoapi_status(&snac, msg);
2589 }
2590 else
2591 if (strcmp(op, "pin") == 0) { /** **/
2592 /* pin this message */
2593 if (pin(&snac, id) == 0)
2594 out = mastoapi_status(&snac, msg);
2595 else
2596 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2597 }
2598 else
2599 if (strcmp(op, "unpin") == 0) { /** **/
2600 /* unpin this message */
2601 unpin(&snac, id);
2602 out = mastoapi_status(&snac, msg);
2603 }
2604 else
2605 if (strcmp(op, "mute") == 0) { /** **/
2606 /* Mastodon's mute is snac's hide */
2607 }
2608 else
2609 if (strcmp(op, "unmute") == 0) { /** **/
2610 /* Mastodon's unmute is snac's unhide */
2611 }
2612 }
2613
2614 if (out != NULL) {
2615 *body = xs_json_dumps(out, 4);
2616 *ctype = "application/json";
2617 status = HTTP_STATUS_OK;
2618 }
2619 }
2620 }
2621 else
2622 status = HTTP_STATUS_UNAUTHORIZED;
2623 }
2624 else
2625 if (strcmp(cmd, "/v1/notifications/clear") == 0) { /** **/
2626 if (logged_in) {
2627 notify_clear(&snac);
2628 timeline_touch(&snac);
2629
2630 *body = xs_dup("{}");
2631 *ctype = "application/json";
2632 status = HTTP_STATUS_OK;
2633 }
2634 else
2635 status = HTTP_STATUS_UNAUTHORIZED;
2636 }
2637 else
2638 if (strcmp(cmd, "/v1/push/subscription") == 0) { /** **/
2639 /* I don't know what I'm doing */
2640 if (logged_in) {
2641 const char *v;
2642
2643 xs *wpush = xs_dict_new();
2644
2645 wpush = xs_dict_append(wpush, "id", "1");
2646
2647 v = xs_dict_get(args, "data");
2648 v = xs_dict_get(v, "alerts");
2649 wpush = xs_dict_append(wpush, "alerts", v);
2650
2651 v = xs_dict_get(args, "subscription");
2652 v = xs_dict_get(v, "endpoint");
2653 wpush = xs_dict_append(wpush, "endpoint", v);
2654
2655 xs *server_key = random_str();
2656 wpush = xs_dict_append(wpush, "server_key", server_key);
2657
2658 *body = xs_json_dumps(wpush, 4);
2659 *ctype = "application/json";
2660 status = HTTP_STATUS_OK;
2661 }
2662 else
2663 status = HTTP_STATUS_UNAUTHORIZED;
2664 }
2665 else
2666 if (strcmp(cmd, "/v1/media") == 0 || strcmp(cmd, "/v2/media") == 0) { /** **/
2667 if (logged_in) {
2668 const xs_list *file = xs_dict_get(args, "file");
2669 const char *desc = xs_dict_get(args, "description");
2670
2671 if (xs_is_null(desc))
2672 desc = "";
2673
2674 status = HTTP_STATUS_BAD_REQUEST;
2675
2676 if (xs_type(file) == XSTYPE_LIST) {
2677 const char *fn = xs_list_get(file, 0);
2678
2679 if (*fn != '\0') {
2680 char *ext = strrchr(fn, '.');
2681 xs *hash = xs_md5_hex(fn, strlen(fn));
2682 xs *id = xs_fmt("%s%s", hash, ext);
2683 xs *url = xs_fmt("%s/s/%s", snac.actor, id);
2684 int fo = xs_number_get(xs_list_get(file, 1));
2685 int fs = xs_number_get(xs_list_get(file, 2));
2686
2687 /* store */
2688 static_put(&snac, id, payload + fo, fs);
2689 static_put_meta(&snac, id, desc);
2690
2691 /* prepare a response */
2692 xs *rsp = xs_dict_new();
2693
2694 rsp = xs_dict_append(rsp, "id", id);
2695 rsp = xs_dict_append(rsp, "type", "image");
2696 rsp = xs_dict_append(rsp, "url", url);
2697 rsp = xs_dict_append(rsp, "preview_url", url);
2698 rsp = xs_dict_append(rsp, "remote_url", url);
2699 rsp = xs_dict_append(rsp, "description", desc);
2700
2701 *body = xs_json_dumps(rsp, 4);
2702 *ctype = "application/json";
2703 status = HTTP_STATUS_OK;
2704 }
2705 }
2706 }
2707 else
2708 status = HTTP_STATUS_UNAUTHORIZED;
2709 }
2710 else
2711 if (xs_startswith(cmd, "/v1/accounts")) { /** **/
2712 if (logged_in) {
2713 /* account-related information */
2714 xs *l = xs_split(cmd, "/");
2715 const char *md5 = xs_list_get(l, 3);
2716 const char *opt = xs_list_get(l, 4);
2717 xs *rsp = NULL;
2718
2719 if (!xs_is_null(md5) && *md5) {
2720 xs *actor_o = NULL;
2721
2722 if (xs_is_null(opt)) {
2723 /* ? */
2724 }
2725 else
2726 if (strcmp(opt, "follow") == 0) { /** **/
2727 if (valid_status(object_get_by_md5(md5, &actor_o))) {
2728 const char *actor = xs_dict_get(actor_o, "id");
2729
2730 xs *msg = msg_follow(&snac, actor);
2731
2732 if (msg != NULL) {
2733 /* reload the actor from the message, in may be different */
2734 actor = xs_dict_get(msg, "object");
2735
2736 following_add(&snac, actor, msg);
2737
2738 enqueue_output_by_actor(&snac, msg, actor, 0);
2739
2740 rsp = mastoapi_relationship(&snac, md5);
2741 }
2742 }
2743 }
2744 else
2745 if (strcmp(opt, "unfollow") == 0) { /** **/
2746 if (valid_status(object_get_by_md5(md5, &actor_o))) {
2747 const char *actor = xs_dict_get(actor_o, "id");
2748
2749 /* get the following object */
2750 xs *object = NULL;
2751
2752 if (valid_status(following_get(&snac, actor, &object))) {
2753 xs *msg = msg_undo(&snac, xs_dict_get(object, "object"));
2754
2755 following_del(&snac, actor);
2756
2757 enqueue_output_by_actor(&snac, msg, actor, 0);
2758
2759 rsp = mastoapi_relationship(&snac, md5);
2760 }
2761 }
2762 }
2763 else
2764 if (strcmp(opt, "block") == 0) { /** **/
2765 if (valid_status(object_get_by_md5(md5, &actor_o))) {
2766 const char *actor = xs_dict_get(actor_o, "id");
2767
2768 mute(&snac, actor);
2769
2770 rsp = mastoapi_relationship(&snac, md5);
2771 }
2772 }
2773 else
2774 if (strcmp(opt, "unblock") == 0) { /** **/
2775 if (valid_status(object_get_by_md5(md5, &actor_o))) {
2776 const char *actor = xs_dict_get(actor_o, "id");
2777
2778 unmute(&snac, actor);
2779
2780 rsp = mastoapi_relationship(&snac, md5);
2781 }
2782 }
2783 }
2784
2785 if (rsp != NULL) {
2786 *body = xs_json_dumps(rsp, 4);
2787 *ctype = "application/json";
2788 status = HTTP_STATUS_OK;
2789 }
2790 }
2791 else
2792 status = HTTP_STATUS_UNAUTHORIZED;
2793 }
2794 else
2795 if (xs_startswith(cmd, "/v1/polls")) { /** **/
2796 if (logged_in) {
2797 /* operations on a status */
2798 xs *l = xs_split(cmd, "/");
2799 const char *mid = xs_list_get(l, 3);
2800 const char *op = xs_list_get(l, 4);
2801
2802 if (!xs_is_null(mid)) {
2803 xs *msg = NULL;
2804 xs *out = NULL;
2805
2806 /* skip the 'fake' part of the id */
2807 mid = MID_TO_MD5(mid);
2808
2809 if (valid_status(timeline_get_by_md5(&snac, mid, &msg))) {
2810 const char *id = xs_dict_get(msg, "id");
2811 const char *atto = get_atto(msg);
2812
2813 const xs_list *opts = xs_dict_get(msg, "oneOf");
2814 if (opts == NULL)
2815 opts = xs_dict_get(msg, "anyOf");
2816
2817 if (op == NULL) {
2818 }
2819 else
2820 if (strcmp(op, "votes") == 0) {
2821 const xs_list *choices = xs_dict_get(args, "choices[]");
2822
2823 if (xs_is_null(choices))
2824 choices = xs_dict_get(args, "choices");
2825
2826 if (xs_type(choices) == XSTYPE_LIST) {
2827 const xs_str *v;
2828
2829 int c = 0;
2830 while (xs_list_next(choices, &v, &c)) {
2831 int io = atoi(v);
2832 const xs_dict *o = xs_list_get(opts, io);
2833
2834 if (o) {
2835 const char *name = xs_dict_get(o, "name");
2836
2837 xs *msg = msg_note(&snac, "", atto, (char *)id, NULL, 1);
2838 msg = xs_dict_append(msg, "name", name);
2839
2840 xs *c_msg = msg_create(&snac, msg);
2841 enqueue_message(&snac, c_msg);
2842 timeline_add(&snac, xs_dict_get(msg, "id"), msg);
2843 }
2844 }
2845
2846 out = mastoapi_poll(&snac, msg);
2847 }
2848 }
2849 }
2850
2851 if (out != NULL) {
2852 *body = xs_json_dumps(out, 4);
2853 *ctype = "application/json";
2854 status = HTTP_STATUS_OK;
2855 }
2856 }
2857 }
2858 else
2859 status = HTTP_STATUS_UNAUTHORIZED;
2860 }
2861 else
2862 if (strcmp(cmd, "/v1/lists") == 0) {
2863 if (logged_in) {
2864 const char *title = xs_dict_get(args, "title");
2865
2866 if (xs_type(title) == XSTYPE_STRING) {
2867 /* add the list */
2868 xs *out = xs_dict_new();
2869 xs *lid = list_maint(&snac, title, 1);
2870
2871 if (!xs_is_null(lid)) {
2872 out = xs_dict_append(out, "id", lid);
2873 out = xs_dict_append(out, "title", title);
2874 out = xs_dict_append(out, "replies_policy", xs_dict_get_def(args, "replies_policy", "list"));
2875 out = xs_dict_append(out, "exclusive", xs_stock(XSTYPE_FALSE));
2876
2877 status = HTTP_STATUS_OK;
2878 }
2879 else {
2880 out = xs_dict_append(out, "error", "cannot create list");
2881 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2882 }
2883
2884 *body = xs_json_dumps(out, 4);
2885 *ctype = "application/json";
2886 }
2887 else
2888 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2889 }
2890 }
2891 if (xs_startswith(cmd, "/v1/lists/")) { /** list maintenance **/
2892 if (logged_in) {
2893 xs *l = xs_split(cmd, "/");
2894 const char *op = xs_list_get(l, -1);
2895 const char *id = xs_list_get(l, -2);
2896
2897 if (op && id && xs_is_hex(id)) {
2898 if (strcmp(op, "accounts") == 0) {
2899 const xs_list *accts = xs_dict_get(args, "account_ids[]");
2900
2901 if (xs_is_null(accts))
2902 accts = xs_dict_get(args, "account_ids");
2903
2904 int c = 0;
2905 const char *v;
2906
2907 while (xs_list_next(accts, &v, &c)) {
2908 list_content(&snac, id, v, 1);
2909 }
2910
2911 xs *out = xs_dict_new();
2912 *body = xs_json_dumps(out, 4);
2913 *ctype = "application/json";
2914 status = HTTP_STATUS_OK;
2915 }
2916 }
2917 }
2918 else
2919 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2920 }
2921
2922 /* user cleanup */
2923 if (logged_in)
2924 user_free(&snac);
2925
2926 srv_debug(1, xs_fmt("mastoapi_post_handler %s %d", q_path, status));
2927
2928 return status;
2929}
2930
2931
2932int mastoapi_delete_handler(const xs_dict *req, const char *q_path,
2933 const char *payload, int p_size,
2934 char **body, int *b_size, char **ctype)
2935{
2936 (void)p_size;
2937 (void)body;
2938 (void)b_size;
2939 (void)ctype;
2940
2941 if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
2942 return 0;
2943
2944 int status = HTTP_STATUS_NOT_FOUND;
2945 xs *args = NULL;
2946 const char *i_ctype = xs_dict_get(req, "content-type");
2947
2948 if (i_ctype && xs_startswith(i_ctype, "application/json")) {
2949 if (!xs_is_null(payload))
2950 args = xs_json_loads(payload);
2951 }
2952 else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
2953 {
2954 // Some apps send form data instead of json so we should cater for those
2955 if (!xs_is_null(payload)) {
2956 args = xs_url_vars(payload);
2957 }
2958 }
2959 else
2960 args = xs_dup(xs_dict_get(req, "p_vars"));
2961
2962 if (args == NULL)
2963 return HTTP_STATUS_BAD_REQUEST;
2964
2965 snac snac = {0};
2966 int logged_in = process_auth_token(&snac, req);
2967
2968 xs *cmd = xs_replace_n(q_path, "/api", "", 1);
2969
2970 if (xs_startswith(cmd, "/v1/push/subscription") || xs_startswith(cmd, "/v2/push/subscription")) { /** **/
2971 // pretend we deleted it, since it doesn't exist anyway
2972 status = HTTP_STATUS_OK;
2973 }
2974 else
2975 if (xs_startswith(cmd, "/v1/lists/")) {
2976 if (logged_in) {
2977 xs *l = xs_split(cmd, "/");
2978 const char *p = xs_list_get(l, -1);
2979
2980 if (p) {
2981 if (strcmp(p, "accounts") == 0) {
2982 /* delete account from list */
2983 p = xs_list_get(l, -2);
2984 const xs_list *accts = xs_dict_get(args, "account_ids[]");
2985
2986 if (xs_is_null(accts))
2987 accts = xs_dict_get(args, "account_ids");
2988
2989 int c = 0;
2990 const char *v;
2991
2992 while (xs_list_next(accts, &v, &c)) {
2993 list_content(&snac, p, v, 2);
2994 }
2995 }
2996 else {
2997 /* delete list */
2998 if (xs_is_hex(p)) {
2999 list_maint(&snac, p, 2);
3000 }
3001 }
3002 }
3003
3004 *ctype = "application/json";
3005 status = HTTP_STATUS_OK;
3006 }
3007 else
3008 status = HTTP_STATUS_UNAUTHORIZED;
3009 }
3010
3011 /* user cleanup */
3012 if (logged_in)
3013 user_free(&snac);
3014
3015 srv_debug(1, xs_fmt("mastoapi_delete_handler %s %d", q_path, status));
3016
3017 return status;
3018}
3019
3020
3021int mastoapi_put_handler(const xs_dict *req, const char *q_path,
3022 const char *payload, int p_size,
3023 char **body, int *b_size, char **ctype)
3024{
3025 (void)p_size;
3026 (void)b_size;
3027
3028 if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
3029 return 0;
3030
3031 int status = HTTP_STATUS_NOT_FOUND;
3032 xs *args = NULL;
3033 const char *i_ctype = xs_dict_get(req, "content-type");
3034
3035 if (i_ctype && xs_startswith(i_ctype, "application/json")) {
3036 if (!xs_is_null(payload))
3037 args = xs_json_loads(payload);
3038 }
3039 else
3040 args = xs_dup(xs_dict_get(req, "p_vars"));
3041
3042 if (args == NULL)
3043 return HTTP_STATUS_BAD_REQUEST;
3044
3045 xs *cmd = xs_replace_n(q_path, "/api", "", 1);
3046
3047 snac snac = {0};
3048 int logged_in = process_auth_token(&snac, req);
3049
3050 if (xs_startswith(cmd, "/v1/media") || xs_startswith(cmd, "/v2/media")) { /** **/
3051 if (logged_in) {
3052 xs *l = xs_split(cmd, "/");
3053 const char *stid = xs_list_get(l, 3);
3054
3055 if (!xs_is_null(stid)) {
3056 const char *desc = xs_dict_get(args, "description");
3057
3058 /* set the image metadata */
3059 static_put_meta(&snac, stid, desc);
3060
3061 /* prepare a response */
3062 xs *rsp = xs_dict_new();
3063 xs *url = xs_fmt("%s/s/%s", snac.actor, stid);
3064
3065 rsp = xs_dict_append(rsp, "id", stid);
3066 rsp = xs_dict_append(rsp, "type", "image");
3067 rsp = xs_dict_append(rsp, "url", url);
3068 rsp = xs_dict_append(rsp, "preview_url", url);
3069 rsp = xs_dict_append(rsp, "remote_url", url);
3070 rsp = xs_dict_append(rsp, "description", desc);
3071
3072 *body = xs_json_dumps(rsp, 4);
3073 *ctype = "application/json";
3074 status = HTTP_STATUS_OK;
3075 }
3076 }
3077 else
3078 status = HTTP_STATUS_UNAUTHORIZED;
3079 }
3080 else
3081 if (xs_startswith(cmd, "/v1/statuses")) {
3082 if (logged_in) {
3083 xs *l = xs_split(cmd, "/");
3084 const char *mid = xs_list_get(l, 3);
3085
3086 if (!xs_is_null(mid)) {
3087 const char *md5 = MID_TO_MD5(mid);
3088 xs *rsp = NULL;
3089 xs *msg = NULL;
3090
3091 if (valid_status(timeline_get_by_md5(&snac, md5, &msg))) {
3092 const char *content = xs_dict_get(args, "status");
3093 xs *atls = xs_list_new();
3094 xs *f_content = not_really_markdown(content, &atls, NULL);
3095
3096 /* replace fields with new content */
3097 msg = xs_dict_set(msg, "sourceContent", content);
3098 msg = xs_dict_set(msg, "content", f_content);
3099
3100 xs *updated = xs_str_utctime(0, ISO_DATE_SPEC);
3101 msg = xs_dict_set(msg, "updated", updated);
3102
3103 /* overwrite object, not updating the indexes */
3104 object_add_ow(xs_dict_get(msg, "id"), msg);
3105
3106 /* update message */
3107 xs *c_msg = msg_update(&snac, msg);
3108
3109 enqueue_message(&snac, c_msg);
3110
3111 rsp = mastoapi_status(&snac, msg);
3112 }
3113
3114 if (rsp != NULL) {
3115 *body = xs_json_dumps(rsp, 4);
3116 *ctype = "application/json";
3117 status = HTTP_STATUS_OK;
3118 }
3119 }
3120 }
3121 else
3122 status = HTTP_STATUS_UNAUTHORIZED;
3123 }
3124
3125 /* user cleanup */
3126 if (logged_in)
3127 user_free(&snac);
3128
3129 srv_debug(1, xs_fmt("mastoapi_put_handler %s %d", q_path, status));
3130
3131 return status;
3132}
3133
3134void persist_image(const char *key, const xs_val *data, const char *payload, snac *snac)
3135/* Store header or avatar */
3136{
3137 if (data != NULL) {
3138 if (xs_type(data) == XSTYPE_LIST) {
3139 const char *fn = xs_list_get(data, 0);
3140
3141 if (fn && *fn) {
3142 const char *ext = strrchr(fn, '.');
3143
3144 /* Mona iOS sends always jpg as application/octet-stream with no filename */
3145 if (ext == NULL || strcmp(fn, key) == 0) {
3146 ext = ".jpg";
3147 }
3148
3149 /* Make sure we have a unique file name, otherwise updated images will not be
3150 * re-loaded by clients. */
3151 xs *rnd = random_str();
3152 xs *hash = xs_md5_hex(rnd, strlen(rnd));
3153 xs *id = xs_fmt("%s%s", hash, ext);
3154 xs *url = xs_fmt("%s/s/%s", snac->actor, id);
3155 int fo = xs_number_get(xs_list_get(data, 1));
3156 int fs = xs_number_get(xs_list_get(data, 2));
3157
3158 /* store */
3159 static_put(snac, id, payload + fo, fs);
3160
3161 snac->config = xs_dict_set(snac->config, key, url);
3162 }
3163 }
3164 }
3165}
3166
3167int mastoapi_patch_handler(const xs_dict *req, const char *q_path,
3168 const char *payload, int p_size,
3169 char **body, int *b_size, char **ctype)
3170/* Handle profile updates */
3171{
3172 (void)p_size;
3173 (void)b_size;
3174
3175 if (!xs_startswith(q_path, "/api/v1/"))
3176 return 0;
3177
3178 int status = HTTP_STATUS_NOT_FOUND;
3179 xs *args = NULL;
3180 const char *i_ctype = xs_dict_get(req, "content-type");
3181
3182 if (i_ctype && xs_startswith(i_ctype, "application/json")) {
3183 if (!xs_is_null(payload))
3184 args = xs_json_loads(payload);
3185 }
3186 else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
3187 {
3188 // Some apps send form data instead of json so we should cater for those
3189 if (!xs_is_null(payload)) {
3190 args = xs_url_vars(payload);
3191 }
3192 }
3193 else
3194 args = xs_dup(xs_dict_get(req, "p_vars"));
3195
3196 if (args == NULL)
3197 return HTTP_STATUS_BAD_REQUEST;
3198
3199 xs *cmd = xs_replace_n(q_path, "/api", "", 1);
3200
3201 snac snac = {0};
3202 int logged_in = process_auth_token(&snac, req);
3203
3204 if (xs_startswith(cmd, "/v1/accounts/update_credentials")) {
3205 /* Update user profile fields */
3206 if (logged_in) {
3207 int c = 0;
3208 const xs_str *k;
3209 const xs_val *v;
3210 const xs_str *field_name = NULL;
3211 xs *new_fields = xs_dict_new();
3212 while (xs_dict_next(args, &k, &v, &c)) {
3213 if (strcmp(k, "display_name") == 0) {
3214 if (v != NULL)
3215 snac.config = xs_dict_set(snac.config, "name", v);
3216 }
3217 else
3218 if (strcmp(k, "note") == 0) {
3219 if (v != NULL)
3220 snac.config = xs_dict_set(snac.config, "bio", v);
3221 }
3222 else
3223 if (strcmp(k, "bot") == 0) {
3224 if (v != NULL)
3225 snac.config = xs_dict_set(snac.config, "bot",
3226 (strcmp(v, "true") == 0 ||
3227 strcmp(v, "1") == 0) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
3228 }
3229 else
3230 if (strcmp(k, "source[sensitive]") == 0) {
3231 if (v != NULL)
3232 snac.config = xs_dict_set(snac.config, "cw",
3233 strcmp(v, "true") == 0 ? "open" : "");
3234 }
3235 else
3236 if (strcmp(k, "source[privacy]") == 0) {
3237 if (v != NULL)
3238 snac.config = xs_dict_set(snac.config, "private",
3239 strcmp(v, "private") == 0 ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
3240 }
3241 else
3242 if (strcmp(k, "header") == 0) {
3243 persist_image("header", v, payload, &snac);
3244 }
3245 else
3246 if (strcmp(k, "avatar") == 0) {
3247 persist_image("avatar", v, payload, &snac);
3248 }
3249 else
3250 if (xs_between("fields_attributes", k, "[name]")) {
3251 field_name = strcmp(v, "") != 0 ? v : NULL;
3252 }
3253 else
3254 if (xs_between("fields_attributes", k, "[value]")) {
3255 if (field_name != NULL) {
3256 new_fields = xs_dict_set(new_fields, field_name, v);
3257 snac.config = xs_dict_set(snac.config, "metadata", new_fields);
3258 }
3259 }
3260 /* we don't have support for the following options, yet
3261 - discoverable (0/1)
3262 - locked (0/1)
3263 */
3264 }
3265
3266 /* Persist profile */
3267 if (user_persist(&snac, 1) == 0)
3268 credentials_get(body, ctype, &status, snac);
3269 else
3270 status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
3271 }
3272 else
3273 status = HTTP_STATUS_UNAUTHORIZED;
3274 }
3275
3276 /* user cleanup */
3277 if (logged_in)
3278 user_free(&snac);
3279
3280 srv_debug(1, xs_fmt("mastoapi_patch_handler %s %d", q_path, status));
3281
3282 return status;
3283}
3284
3285
3286void mastoapi_purge(void)
3287{
3288 xs *spec = xs_fmt("%s/app/" "*.json", srv_basedir);
3289 xs *files = xs_glob(spec, 1, 0);
3290 xs_list *p = files;
3291 const xs_str *v;
3292
3293 time_t mt = time(NULL) - 3600;
3294
3295 while (xs_list_iter(&p, &v)) {
3296 xs *cid = xs_replace(v, ".json", "");
3297 xs *fn = _app_fn(cid);
3298
3299 if (mtime(fn) < mt) {
3300 /* get the app */
3301 xs *app = app_get(cid);
3302
3303 if (app) {
3304 /* old apps with no uid are incomplete cruft */
3305 const char *uid = xs_dict_get(app, "uid");
3306
3307 if (xs_is_null(uid) || *uid == '\0') {
3308 unlink(fn);
3309 srv_debug(2, xs_fmt("purged %s", fn));
3310 }
3311 }
3312 }
3313 }
3314}
3315
3316
3317#endif /* #ifndef NO_MASTODON_API */