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