2.81
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 if (initial_status) {
1401 do {
1402 xs *msg = NULL;
1403
1404 /* only return entries older that max_id */
1405 if (max_id) {
1406 if (strcmp(md5, MID_TO_MD5(max_id)) == 0) {
1407 max_id = xs_free(max_id);
1408 if (ascending)
1409 break;
1410 }
1411 if (!ascending)
1412 continue;
1413 }
1414
1415 /* only returns entries newer than since_id */
1416 if (since_id) {
1417 if (strcmp(md5, MID_TO_MD5(since_id)) == 0) {
1418 if (!ascending)
1419 break;
1420 since_id = xs_free(since_id);
1421 }
1422 if (ascending)
1423 continue;
1424 }
1425
1426 /* get the entry */
1427 if (user) {
1428 if (!valid_status(timeline_get_by_md5(user, md5, &msg)))
1429 continue;
1430 }
1431 else {
1432 if (!valid_status(object_get_by_md5(md5, &msg)))
1433 continue;
1434 }
1435
1436 /* discard non-Notes */
1437 const char *id = xs_dict_get(msg, "id");
1438 const char *type = xs_dict_get(msg, "type");
1439 if (!xs_match(type, POSTLIKE_OBJECT_TYPE))
1440 continue;
1441
1442 if (id && is_instance_blocked(id))
1443 continue;
1444
1445 const char *from = NULL;
1446 if (strcmp(type, "Page") == 0)
1447 from = xs_dict_get(msg, "audience");
1448
1449 if (from == NULL)
1450 from = get_atto(msg);
1451
1452 if (from == NULL)
1453 continue;
1454
1455 if (user) {
1456 /* is this message from a person we don't follow? */
1457 if (strcmp(from, user->actor) && !following_check(user, from)) {
1458 /* discard if it was not boosted */
1459 xs *idx = object_announces(id);
1460
1461 if (xs_list_len(idx) == 0)
1462 continue;
1463 }
1464
1465 /* discard notes from muted morons */
1466 if (is_muted(user, from))
1467 continue;
1468
1469 /* discard hidden notes */
1470 if (is_hidden(user, id))
1471 continue;
1472 }
1473 else {
1474 /* skip non-public messages */
1475 if (!is_msg_public(msg))
1476 continue;
1477
1478 /* discard messages from private users */
1479 if (is_msg_from_private_user(msg))
1480 continue;
1481 }
1482
1483 /* if it has a name and it's not an object that may have one,
1484 it's a poll vote, so discard it */
1485 if (!xs_is_null(xs_dict_get(msg, "name")) && !xs_match(type, "Page|Video|Audio|Event"))
1486 continue;
1487
1488 /* convert the Note into a Mastodon status */
1489 xs *st = mastoapi_status(user, msg);
1490
1491 if (st != NULL) {
1492 if (ascending)
1493 out = xs_list_insert(out, 0, st);
1494 else
1495 out = xs_list_append(out, st);
1496 cnt++;
1497 }
1498
1499 } while ((cnt < limit) && (*iterator)(f, md5));
1500 }
1501
1502 int more = index_desc_next(f, md5);
1503
1504 fclose(f);
1505
1506 srv_debug(1, xs_fmt("mastoapi_timeline ret %d%s", cnt, more ? " (+)" : ""));
1507
1508 return out;
1509}
1510
1511
1512xs_str *timeline_link_header(const char *endpoint, xs_list *timeline)
1513/* returns a Link header with paging information */
1514{
1515 xs_str *s = NULL;
1516
1517 if (xs_list_len(timeline) == 0)
1518 return NULL;
1519
1520 const xs_dict *first_st = xs_list_get(timeline, 0);
1521 const xs_dict *last_st = xs_list_get(timeline, -1);
1522 const char *first_id = xs_dict_get(first_st, "id");
1523 const char *last_id = xs_dict_get(last_st, "id");
1524 const char *host = xs_dict_get(srv_config, "host");
1525 const char *protocol = xs_dict_get_def(srv_config, "protocol", "https");
1526
1527 s = xs_fmt(
1528 "<%s:/" "/%s%s?max_id=%s>; rel=\"next\", "
1529 "<%s:/" "/%s%s?since_id=%s>; rel=\"prev\"",
1530 protocol, host, endpoint, last_id,
1531 protocol, host, endpoint, first_id);
1532
1533 srv_debug(1, xs_fmt("timeline_link_header %s", s));
1534
1535 return s;
1536}
1537
1538
1539xs_list *mastoapi_account_lists(snac *user, const char *uid)
1540/* returns the list of list an user is in */
1541{
1542 xs_list *out = xs_list_new();
1543 xs *actor_md5 = NULL;
1544 xs *lol = list_maint(user, NULL, 0);
1545
1546 if (uid) {
1547 if (!xs_is_hex(uid))
1548 actor_md5 = xs_md5_hex(uid, strlen(uid));
1549 else
1550 actor_md5 = xs_dup(uid);
1551 }
1552
1553 const xs_list *li;
1554 xs_list_foreach(lol, li) {
1555 const char *list_id = xs_list_get(li, 0);
1556 const char *list_title = xs_list_get(li, 1);
1557 if (uid) {
1558 xs *users = list_content(user, list_id, NULL, 0);
1559 if (xs_list_in(users, actor_md5) == -1)
1560 continue;
1561 }
1562
1563 xs *d = xs_dict_new();
1564
1565 d = xs_dict_append(d, "id", list_id);
1566 d = xs_dict_append(d, "title", list_title);
1567 d = xs_dict_append(d, "replies_policy", "list");
1568 d = xs_dict_append(d, "exclusive", xs_stock(XSTYPE_FALSE));
1569
1570 out = xs_list_append(out, d);
1571 }
1572
1573 return out;
1574}
1575
1576
1577int mastoapi_get_handler(const xs_dict *req, const char *q_path,
1578 char **body, int *b_size, char **ctype, xs_str **link)
1579{
1580 (void)b_size;
1581
1582 if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
1583 return 0;
1584
1585 int status = HTTP_STATUS_NOT_FOUND;
1586 const xs_dict *args = xs_dict_get(req, "q_vars");
1587 xs *cmd = xs_replace_n(q_path, "/api", "", 1);
1588
1589 snac snac1 = {0};
1590 int logged_in = process_auth_token(&snac1, req);
1591
1592 if (strcmp(cmd, "/v1/accounts/verify_credentials") == 0) { /** **/
1593 if (logged_in) {
1594 credentials_get(body, ctype, &status, snac1);
1595 }
1596 else {
1597 status = HTTP_STATUS_UNPROCESSABLE_CONTENT; // (no login)
1598 }
1599 }
1600 else
1601 if (strcmp(cmd, "/v1/accounts/relationships") == 0) { /** **/
1602 /* find if an account is followed, blocked, etc. */
1603 /* the account to get relationships about is in args "id[]" */
1604
1605 if (logged_in) {
1606 xs *res = xs_list_new();
1607 const char *md5 = xs_dict_get(args, "id[]");
1608
1609 if (xs_is_null(md5))
1610 md5 = xs_dict_get(args, "id");
1611
1612 if (!xs_is_null(md5)) {
1613 if (xs_type(md5) == XSTYPE_LIST)
1614 md5 = xs_list_get(md5, 0);
1615
1616 xs *rel = mastoapi_relationship(&snac1, md5);
1617
1618 if (rel != NULL)
1619 res = xs_list_append(res, rel);
1620 }
1621
1622 *body = xs_json_dumps(res, 4);
1623 *ctype = "application/json";
1624 status = HTTP_STATUS_OK;
1625 }
1626 else
1627 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
1628 }
1629 else
1630 if (strcmp(cmd, "/v1/accounts/lookup") == 0) { /** **/
1631 /* lookup an account */
1632 const char *acct = xs_dict_get(args, "acct");
1633
1634 if (!xs_is_null(acct)) {
1635 xs *s = xs_strip_chars_i(xs_dup(acct), "@");
1636 xs *l = xs_split_n(s, "@", 1);
1637 const char *uid = xs_list_get(l, 0);
1638 const char *host = xs_list_get(l, 1);
1639
1640 if (uid && (!host || strcmp(host, xs_dict_get(srv_config, "host")) == 0)) {
1641 snac user;
1642
1643 if (user_open(&user, uid)) {
1644 xs *actor = msg_actor(&user);
1645 xs *macct = mastoapi_account(NULL, actor);
1646
1647 *body = xs_json_dumps(macct, 4);
1648 *ctype = "application/json";
1649 status = HTTP_STATUS_OK;
1650
1651 user_free(&user);
1652 }
1653 }
1654 }
1655 }
1656 else
1657 if (xs_startswith(cmd, "/v1/accounts/")) { /** **/
1658 /* account-related information */
1659 xs *l = xs_split(cmd, "/");
1660 const char *uid = xs_list_get(l, 3);
1661 const char *opt = xs_list_get(l, 4);
1662
1663 if (uid != NULL) {
1664 snac snac2;
1665 xs *out = NULL;
1666 xs *actor = NULL;
1667
1668 if (logged_in && strcmp(uid, "search") == 0) { /** **/
1669 /* search for accounts starting with q */
1670 const char *aq = xs_dict_get(args, "q");
1671
1672 if (!xs_is_null(aq)) {
1673 xs *q = xs_utf8_to_lower(aq);
1674 out = xs_list_new();
1675 xs *wing = following_list(&snac1);
1676 xs *wers = follower_list(&snac1);
1677 xs *ulst = user_list();
1678 xs_list *p;
1679 const xs_str *v;
1680 xs_set seen;
1681
1682 xs_set_init(&seen);
1683
1684 /* user relations */
1685 xs_list *lsts[] = { wing, wers, NULL };
1686 int n;
1687 for (n = 0; (p = lsts[n]) != NULL; n++) {
1688
1689 while (xs_list_iter(&p, &v)) {
1690 /* already seen? skip */
1691 if (xs_set_add(&seen, v) == 0)
1692 continue;
1693
1694 xs *actor = NULL;
1695
1696 if (valid_status(object_get(v, &actor))) {
1697 const char *uname = xs_dict_get(actor, "preferredUsername");
1698
1699 if (!xs_is_null(uname)) {
1700 xs *luname = xs_tolower_i(xs_dup(uname));
1701
1702 if (xs_startswith(luname, q)) {
1703 xs *acct = mastoapi_account(&snac1, actor);
1704
1705 out = xs_list_append(out, acct);
1706 }
1707 }
1708 }
1709 }
1710 }
1711
1712 /* local users */
1713 p = ulst;
1714 while (xs_list_iter(&p, &v)) {
1715 snac user;
1716
1717 /* skip this same user */
1718 if (strcmp(v, xs_dict_get(snac1.config, "uid")) == 0)
1719 continue;
1720
1721 /* skip if the uid does not start with the query */
1722 xs *v2 = xs_tolower_i(xs_dup(v));
1723 if (!xs_startswith(v2, q))
1724 continue;
1725
1726 if (user_open(&user, v)) {
1727 /* if it's not already seen, add it */
1728 if (xs_set_add(&seen, user.actor) == 1) {
1729 xs *actor = msg_actor(&user);
1730 xs *acct = mastoapi_account(&snac1, actor);
1731
1732 out = xs_list_append(out, acct);
1733 }
1734
1735 user_free(&user);
1736 }
1737 }
1738
1739 xs_set_free(&seen);
1740 }
1741 }
1742 else
1743 /* is it a local user? */
1744 if (user_open(&snac2, uid) || user_open_by_md5(&snac2, uid)) {
1745 if (opt == NULL) {
1746 /* account information */
1747 actor = msg_actor(&snac2);
1748 out = mastoapi_account(NULL, actor);
1749 }
1750 else
1751 if (strcmp(opt, "statuses") == 0) { /** **/
1752 /* the public list of posts of a user */
1753 xs *timeline = timeline_simple_list(&snac2, "public", 0, 256, NULL);
1754 xs_list *p = timeline;
1755 const xs_str *v;
1756
1757 out = xs_list_new();
1758
1759 while (xs_list_iter(&p, &v)) {
1760 xs *msg = NULL;
1761
1762 if (valid_status(timeline_get_by_md5(&snac2, v, &msg))) {
1763 /* add only posts by the author */
1764 if (strcmp(xs_dict_get(msg, "type"), "Note") == 0 &&
1765 xs_startswith(xs_dict_get(msg, "id"), snac2.actor)) {
1766 xs *st = mastoapi_status(&snac2, msg);
1767
1768 if (st)
1769 out = xs_list_append(out, st);
1770 }
1771 }
1772 }
1773 }
1774 else
1775 if (strcmp(opt, "featured_tags") == 0) {
1776 /* snac doesn't have features tags, yet? */
1777 /* implement empty response so apps like Tokodon don't show an error */
1778 out = xs_list_new();
1779 }
1780 else
1781 if (strcmp(opt, "following") == 0) {
1782 xs *wing = following_list(&snac1);
1783 out = xs_list_new();
1784 int c = 0;
1785 const char *v;
1786
1787 while (xs_list_next(wing, &v, &c)) {
1788 xs *actor = NULL;
1789
1790 if (valid_status(object_get(v, &actor))) {
1791 xs *acct = mastoapi_account(NULL, actor);
1792 out = xs_list_append(out, acct);
1793 }
1794 }
1795 }
1796 else
1797 if (strcmp(opt, "followers") == 0) {
1798 out = xs_list_new();
1799 }
1800 else
1801 if (strcmp(opt, "lists") == 0) {
1802 out = mastoapi_account_lists(&snac1, uid);
1803 }
1804
1805 user_free(&snac2);
1806 }
1807 else {
1808 /* try the uid as the md5 of a possibly loaded actor */
1809 if (logged_in && valid_status(object_get_by_md5(uid, &actor))) {
1810 if (opt == NULL) {
1811 /* account information */
1812 out = mastoapi_account(&snac1, actor);
1813 }
1814 else
1815 if (strcmp(opt, "statuses") == 0) {
1816 /* we don't serve statuses of others; return the empty list */
1817 out = xs_list_new();
1818 }
1819 else
1820 if (strcmp(opt, "featured_tags") == 0) {
1821 /* snac doesn't have features tags, yet? */
1822 /* implement empty response so apps like Tokodon don't show an error */
1823 out = xs_list_new();
1824 }
1825 else
1826 if (strcmp(opt, "lists") == 0) {
1827 out = mastoapi_account_lists(&snac1, uid);
1828 }
1829 }
1830 }
1831
1832 if (out != NULL) {
1833 *body = xs_json_dumps(out, 4);
1834 *ctype = "application/json";
1835 status = HTTP_STATUS_OK;
1836 }
1837 }
1838 }
1839 else
1840 if (strcmp(cmd, "/v1/timelines/home") == 0) { /** **/
1841 /* the private timeline */
1842 if (logged_in) {
1843 xs *ifn = user_index_fn(&snac1, "private");
1844 xs *out = mastoapi_timeline(&snac1, args, ifn);
1845
1846 *link = timeline_link_header("/api/v1/timelines/home", out);
1847
1848 *body = xs_json_dumps(out, 4);
1849 *ctype = "application/json";
1850 status = HTTP_STATUS_OK;
1851
1852 srv_debug(2, xs_fmt("mastoapi timeline: returned %d entries", xs_list_len(out)));
1853 }
1854 else {
1855 status = HTTP_STATUS_UNAUTHORIZED;
1856 }
1857 }
1858 else
1859 if (strcmp(cmd, "/v1/timelines/public") == 0) { /** **/
1860 /* the instance public timeline (public timelines for all users) */
1861 xs *ifn = instance_index_fn();
1862 xs *out = mastoapi_timeline(NULL, args, ifn);
1863
1864 *body = xs_json_dumps(out, 4);
1865 *ctype = "application/json";
1866 status = HTTP_STATUS_OK;
1867 }
1868 else
1869 if (xs_startswith(cmd, "/v1/timelines/tag/")) { /** **/
1870 /* get the tag */
1871 xs *l = xs_split(cmd, "/");
1872 const char *tag = xs_list_get(l, -1);
1873
1874 xs *ifn = tag_fn(tag);
1875 xs *out = mastoapi_timeline(NULL, args, ifn);
1876
1877 *body = xs_json_dumps(out, 4);
1878 *ctype = "application/json";
1879 status = HTTP_STATUS_OK;
1880 }
1881 else
1882 if (xs_startswith(cmd, "/v1/timelines/list/")) { /** **/
1883 /* get the list id */
1884 if (logged_in) {
1885 xs *l = xs_split(cmd, "/");
1886 const char *list = xs_list_get(l, -1);
1887
1888 xs *ifn = list_timeline_fn(&snac1, list);
1889 xs *out = mastoapi_timeline(NULL, args, ifn);
1890
1891 *body = xs_json_dumps(out, 4);
1892 *ctype = "application/json";
1893 status = HTTP_STATUS_OK;
1894 }
1895 else
1896 status = HTTP_STATUS_MISDIRECTED_REQUEST;
1897 }
1898 else
1899 if (strcmp(cmd, "/v1/conversations") == 0) { /** **/
1900 /* TBD */
1901 *body = xs_dup("[]");
1902 *ctype = "application/json";
1903 status = HTTP_STATUS_OK;
1904 }
1905 else
1906 if (strcmp(cmd, "/v1/notifications") == 0) { /** **/
1907 if (logged_in) {
1908 xs *l = notify_list(&snac1, 0, 64);
1909 xs *out = xs_list_new();
1910 const char *v;
1911 const xs_list *excl = xs_dict_get(args, "exclude_types[]");
1912 const xs_list *incl = xs_dict_get(args, "types[]");
1913 const char *min_id = xs_dict_get(args, "min_id");
1914 const char *max_id = xs_dict_get(args, "max_id");
1915 const char *limit = xs_dict_get(args, "limit");
1916 int limit_count = 0;
1917 if (xs_is_string(limit)) {
1918 limit_count = atoi(limit);
1919 }
1920
1921 if (dbglevel) {
1922 xs *js = xs_json_dumps(args, 0);
1923 srv_debug(1, xs_fmt("mastoapi_notifications args %s", js));
1924 }
1925
1926 xs_list_foreach(l, v) {
1927 xs *noti = notify_get(&snac1, v);
1928
1929 if (noti == NULL)
1930 continue;
1931
1932 const char *type = xs_dict_get(noti, "type");
1933 const char *utype = xs_dict_get(noti, "utype");
1934 const char *objid = xs_dict_get(noti, "objid");
1935 const char *id = xs_dict_get(noti, "id");
1936 const char *actid = xs_dict_get(noti, "actor");
1937 xs *fid = xs_replace(id, ".", "");
1938 xs *actor = NULL;
1939 xs *entry = NULL;
1940
1941 if (!valid_status(actor_get(actid, &actor)))
1942 continue;
1943
1944 if (objid != NULL && !valid_status(object_get(objid, &entry)))
1945 continue;
1946
1947 if (is_hidden(&snac1, objid))
1948 continue;
1949
1950 if (max_id) {
1951 if (strcmp(fid, max_id) == 0)
1952 max_id = NULL;
1953
1954 continue;
1955 }
1956
1957 if (min_id) {
1958 if (strcmp(fid, min_id) <= 0) {
1959 continue;
1960 }
1961 }
1962
1963 /* convert the type */
1964 if (strcmp(type, "Like") == 0 || strcmp(type, "EmojiReact") == 0)
1965 type = "favourite";
1966 else
1967 if (strcmp(type, "Announce") == 0)
1968 type = "reblog";
1969 else
1970 if (strcmp(type, "Follow") == 0)
1971 type = "follow";
1972 else
1973 if (strcmp(type, "Create") == 0)
1974 type = "mention";
1975 else
1976 if (strcmp(type, "Update") == 0 && strcmp(utype, "Question") == 0)
1977 type = "poll";
1978 else
1979 continue;
1980
1981 /* excluded type? */
1982 if (xs_is_list(excl) && xs_list_in(excl, type) != -1)
1983 continue;
1984
1985 /* included type? */
1986 if (xs_is_list(incl) && xs_list_in(incl, type) == -1)
1987 continue;
1988
1989 xs *mn = xs_dict_new();
1990
1991 mn = xs_dict_append(mn, "type", type);
1992
1993 mn = xs_dict_append(mn, "id", fid);
1994
1995 mn = xs_dict_append(mn, "created_at", xs_dict_get(noti, "date"));
1996
1997 xs *acct = mastoapi_account(&snac1, actor);
1998
1999 if (acct == NULL)
2000 continue;
2001
2002 mn = xs_dict_append(mn, "account", acct);
2003
2004 if (strcmp(type, "follow") != 0 && !xs_is_null(objid)) {
2005 xs *st = mastoapi_status(&snac1, entry);
2006
2007 if (st)
2008 mn = xs_dict_append(mn, "status", st);
2009 }
2010
2011 out = xs_list_append(out, mn);
2012
2013 if (--limit_count <= 0)
2014 break;
2015 }
2016
2017 srv_debug(1, xs_fmt("mastoapi_notifications count %d", xs_list_len(out)));
2018
2019 *body = xs_json_dumps(out, 4);
2020 *ctype = "application/json";
2021 status = HTTP_STATUS_OK;
2022 }
2023 else
2024 status = HTTP_STATUS_UNAUTHORIZED;
2025 }
2026 else
2027 if (strcmp(cmd, "/v1/filters") == 0) { /** **/
2028 /* snac will never have filters */
2029 *body = xs_dup("[]");
2030 *ctype = "application/json";
2031 status = HTTP_STATUS_OK;
2032 }
2033 else
2034 if (strcmp(cmd, "/v2/filters") == 0) { /** **/
2035 /* snac will never have filters
2036 * but still, without a v2 endpoint a short delay is introduced
2037 * in some apps */
2038 *body = xs_dup("[]");
2039 *ctype = "application/json";
2040 status = HTTP_STATUS_OK;
2041 }
2042 else
2043 if (strcmp(cmd, "/v1/favourites") == 0) { /** **/
2044 /* snac will never support a list of favourites */
2045 *body = xs_dup("[]");
2046 *ctype = "application/json";
2047 status = HTTP_STATUS_OK;
2048 }
2049 else
2050 if (strcmp(cmd, "/v1/bookmarks") == 0) { /** **/
2051 if (logged_in) {
2052 xs *ifn = bookmark_index_fn(&snac1);
2053 xs *out = mastoapi_timeline(&snac1, args, ifn);
2054
2055 *body = xs_json_dumps(out, 4);
2056 *ctype = "application/json";
2057 status = HTTP_STATUS_OK;
2058 }
2059 else
2060 status = HTTP_STATUS_UNAUTHORIZED;
2061 }
2062 else
2063 if (strcmp(cmd, "/v1/lists") == 0) { /** list of lists **/
2064 if (logged_in) {
2065 xs *l = mastoapi_account_lists(&snac1, NULL);
2066
2067 *body = xs_json_dumps(l, 4);
2068 *ctype = "application/json";
2069 status = HTTP_STATUS_OK;
2070 }
2071 else
2072 status = HTTP_STATUS_UNAUTHORIZED;
2073 }
2074 else
2075 if (xs_startswith(cmd, "/v1/lists/")) { /** list information **/
2076 if (logged_in) {
2077 xs *l = xs_split(cmd, "/");
2078 const char *p = xs_list_get(l, -1);
2079
2080 if (p) {
2081 if (strcmp(p, "accounts") == 0) {
2082 p = xs_list_get(l, -2);
2083
2084 if (p && xs_is_hex(p)) {
2085 xs *actors = list_content(&snac1, p, NULL, 0);
2086 xs *out = xs_list_new();
2087 int c = 0;
2088 const char *v;
2089
2090 while (xs_list_next(actors, &v, &c)) {
2091 xs *actor = NULL;
2092
2093 if (valid_status(object_get_by_md5(v, &actor))) {
2094 xs *acct = mastoapi_account(&snac1, actor);
2095 out = xs_list_append(out, acct);
2096 }
2097 }
2098
2099 *body = xs_json_dumps(out, 4);
2100 *ctype = "application/json";
2101 status = HTTP_STATUS_OK;
2102 }
2103 }
2104 else
2105 if (xs_is_hex(p)) {
2106 xs *out = xs_list_new();
2107 xs *lol = list_maint(&snac1, NULL, 0);
2108 int c = 0;
2109 const xs_list *v;
2110
2111 while (xs_list_next(lol, &v, &c)) {
2112 const char *id = xs_list_get(v, 0);
2113
2114 if (id && strcmp(id, p) == 0) {
2115 xs *d = xs_dict_new();
2116
2117 d = xs_dict_append(d, "id", p);
2118 d = xs_dict_append(d, "title", xs_list_get(v, 1));
2119 d = xs_dict_append(d, "replies_policy", "list");
2120 d = xs_dict_append(d, "exclusive", xs_stock(XSTYPE_FALSE));
2121
2122 out = xs_dup(d);
2123 break;
2124 }
2125 }
2126
2127 *body = xs_json_dumps(out, 4);
2128 *ctype = "application/json";
2129 status = HTTP_STATUS_OK;
2130 }
2131 }
2132 }
2133 else
2134 status = HTTP_STATUS_UNAUTHORIZED;
2135 }
2136 else
2137 if (strcmp(cmd, "/v1/scheduled_statuses") == 0) { /** **/
2138 /* TBD */
2139 *body = xs_dup("[]");
2140 *ctype = "application/json";
2141 status = HTTP_STATUS_OK;
2142 }
2143 else
2144 if (strcmp(cmd, "/v1/follow_requests") == 0) { /** **/
2145 if (logged_in) {
2146 xs *pend = pending_list(&snac1);
2147 xs *resp = xs_list_new();
2148 const char *id;
2149
2150 xs_list_foreach(pend, id) {
2151 xs *actor = NULL;
2152
2153 if (valid_status(object_get(id, &actor))) {
2154 xs *acct = mastoapi_account(&snac1, actor);
2155
2156 if (acct)
2157 resp = xs_list_append(resp, acct);
2158 }
2159 }
2160
2161 *body = xs_json_dumps(resp, 4);
2162 *ctype = "application/json";
2163 status = HTTP_STATUS_OK;
2164 }
2165 }
2166 else
2167 if (strcmp(cmd, "/v1/announcements") == 0) { /** **/
2168 if (logged_in) {
2169 xs *resp = xs_list_new();
2170 double la = 0.0;
2171 xs *user_la = xs_dup(xs_dict_get(snac1.config, "last_announcement"));
2172 if (user_la != NULL)
2173 la = xs_number_get(user_la);
2174 xs *val_date = xs_str_utctime(la, ISO_DATE_SPEC);
2175
2176 /* contrary to html, we always send the announcement and set the read flag instead */
2177
2178 const t_announcement *annce = announcement(la);
2179 if (annce != NULL && annce->text != NULL) {
2180 xs *an = xs_dict_new();
2181 xs *id = xs_fmt("%d", annce->timestamp);
2182 xs *ct = xs_fmt("<p>%s</p>", annce->text);
2183
2184 an = xs_dict_set(an, "id", id);
2185 an = xs_dict_set(an, "content", ct);
2186 an = xs_dict_set(an, "starts_at", xs_stock(XSTYPE_NULL));
2187 an = xs_dict_set(an, "ends_at", xs_stock(XSTYPE_NULL));
2188 an = xs_dict_set(an, "all_day", xs_stock(XSTYPE_TRUE));
2189 an = xs_dict_set(an, "published_at", val_date);
2190 an = xs_dict_set(an, "updated_at", val_date);
2191 an = xs_dict_set(an, "read", (annce->timestamp >= la)
2192 ? xs_stock(XSTYPE_FALSE) : xs_stock(XSTYPE_TRUE));
2193 an = xs_dict_set(an, "mentions", xs_stock(XSTYPE_LIST));
2194 an = xs_dict_set(an, "statuses", xs_stock(XSTYPE_LIST));
2195 an = xs_dict_set(an, "tags", xs_stock(XSTYPE_LIST));
2196 an = xs_dict_set(an, "emojis", xs_stock(XSTYPE_LIST));
2197 an = xs_dict_set(an, "reactions", xs_stock(XSTYPE_LIST));
2198 resp = xs_list_append(resp, an);
2199 }
2200
2201 *body = xs_json_dumps(resp, 4);
2202 *ctype = "application/json";
2203 status = HTTP_STATUS_OK;
2204 }
2205 }
2206 else
2207 if (strcmp(cmd, "/v1/custom_emojis") == 0) { /** **/
2208 xs *emo = emojis();
2209 xs *list = xs_list_new();
2210 int c = 0;
2211 const xs_str *k;
2212 const xs_val *v;
2213 while(xs_dict_next(emo, &k, &v, &c)) {
2214 xs *current = xs_dict_new();
2215 if (xs_startswith(v, "https://") && xs_startswith((xs_mime_by_ext(v)), "image/")) {
2216 /* remove first and last colon */
2217 xs *shortcode = xs_replace(k, ":", "");
2218 current = xs_dict_append(current, "shortcode", shortcode);
2219 current = xs_dict_append(current, "url", v);
2220 current = xs_dict_append(current, "static_url", v);
2221 current = xs_dict_append(current, "visible_in_picker", xs_stock(XSTYPE_TRUE));
2222 list = xs_list_append(list, current);
2223 }
2224 }
2225 *body = xs_json_dumps(list, 0);
2226 *ctype = "application/json";
2227 status = HTTP_STATUS_OK;
2228 }
2229 else
2230 if (strcmp(cmd, "/v1/instance") == 0) { /** **/
2231 /* returns an instance object */
2232 xs *ins = xs_dict_new();
2233 const char *host = xs_dict_get(srv_config, "host");
2234 const char *title = xs_dict_get(srv_config, "title");
2235 const char *sdesc = xs_dict_get(srv_config, "short_description");
2236
2237 ins = xs_dict_append(ins, "uri", host);
2238 ins = xs_dict_append(ins, "domain", host);
2239 ins = xs_dict_append(ins, "title", title && *title ? title : host);
2240 ins = xs_dict_append(ins, "version", "4.0.0 (not true; really " USER_AGENT ")");
2241 ins = xs_dict_append(ins, "source_url", WHAT_IS_SNAC_URL);
2242 ins = xs_dict_append(ins, "description", host);
2243
2244 ins = xs_dict_append(ins, "short_description", sdesc && *sdesc ? sdesc : host);
2245
2246 xs *susie = xs_fmt("%s/susie.png", srv_baseurl);
2247 ins = xs_dict_append(ins, "thumbnail", susie);
2248
2249 const char *v = xs_dict_get(srv_config, "admin_email");
2250 if (xs_is_null(v) || *v == '\0')
2251 v = "admin@localhost";
2252
2253 ins = xs_dict_append(ins, "email", v);
2254
2255 ins = xs_dict_append(ins, "rules", xs_stock(XSTYPE_LIST));
2256
2257 xs *l1 = xs_list_append(xs_list_new(), "en");
2258 ins = xs_dict_append(ins, "languages", l1);
2259
2260 xs *wss = xs_fmt("wss:/" "/%s", xs_dict_get(srv_config, "host"));
2261 xs *urls = xs_dict_new();
2262 urls = xs_dict_append(urls, "streaming_api", wss);
2263
2264 ins = xs_dict_append(ins, "urls", urls);
2265
2266 xs *d2 = xs_dict_append(xs_dict_new(), "user_count", xs_stock(0));
2267 d2 = xs_dict_append(d2, "status_count", xs_stock(0));
2268 d2 = xs_dict_append(d2, "domain_count", xs_stock(0));
2269 ins = xs_dict_append(ins, "stats", d2);
2270
2271 ins = xs_dict_append(ins, "registrations", xs_stock(XSTYPE_FALSE));
2272 ins = xs_dict_append(ins, "approval_required", xs_stock(XSTYPE_FALSE));
2273 ins = xs_dict_append(ins, "invites_enabled", xs_stock(XSTYPE_FALSE));
2274
2275 xs *cfg = xs_dict_new();
2276
2277 {
2278 xs *d11 = xs_json_loads("{\"characters_reserved_per_url\":32,"
2279 "\"max_characters\":100000,\"max_media_attachments\":4}");
2280
2281 const xs_number *max_attachments = xs_dict_get(srv_config, "max_attachments");
2282 if (xs_type(max_attachments) == XSTYPE_NUMBER)
2283 d11 = xs_dict_set(d11, "max_media_attachments", max_attachments);
2284
2285 cfg = xs_dict_append(cfg, "statuses", d11);
2286
2287 xs *d12 = xs_json_loads("{\"max_featured_tags\":0}");
2288 cfg = xs_dict_append(cfg, "accounts", d12);
2289
2290 xs *d13 = xs_json_loads("{\"image_matrix_limit\":33177600,"
2291 "\"image_size_limit\":16777216,"
2292 "\"video_frame_rate_limit\":120,"
2293 "\"video_matrix_limit\":8294400,"
2294 "\"video_size_limit\":103809024}"
2295 );
2296
2297 {
2298 /* get the supported mime types from the internal list */
2299 const char **p = xs_mime_types;
2300 xs_set mtypes;
2301 xs_set_init(&mtypes);
2302
2303 while (*p) {
2304 const char *type = p[1];
2305
2306 if (xs_startswith(type, "image/") ||
2307 xs_startswith(type, "video/") ||
2308 xs_startswith(type, "audio/"))
2309 xs_set_add(&mtypes, type);
2310
2311 p += 2;
2312 }
2313
2314 xs *l = xs_set_result(&mtypes);
2315 d13 = xs_dict_append(d13, "supported_mime_types", l);
2316 }
2317
2318 cfg = xs_dict_append(cfg, "media_attachments", d13);
2319
2320 xs *d14 = xs_json_loads("{\"max_characters_per_option\":50,"
2321 "\"max_expiration\":2629746,"
2322 "\"max_options\":8,\"min_expiration\":300}");
2323 cfg = xs_dict_append(cfg, "polls", d14);
2324 }
2325
2326 ins = xs_dict_append(ins, "configuration", cfg);
2327
2328 const char *admin_account = xs_dict_get(srv_config, "admin_account");
2329
2330 if (!xs_is_null(admin_account) && *admin_account) {
2331 snac admin;
2332
2333 if (user_open(&admin, admin_account)) {
2334 xs *actor = msg_actor(&admin);
2335 xs *acct = mastoapi_account(NULL, actor);
2336
2337 ins = xs_dict_append(ins, "contact_account", acct);
2338
2339 user_free(&admin);
2340 }
2341 }
2342
2343 *body = xs_json_dumps(ins, 4);
2344 *ctype = "application/json";
2345 status = HTTP_STATUS_OK;
2346 }
2347 else
2348 if (strcmp(cmd, "/v1/instance/peers") == 0) { /** **/
2349 /* get the collected inbox list as the instances "this domain is aware of" */
2350 xs *list = inbox_list();
2351 xs *peers = xs_list_new();
2352 const char *inbox;
2353
2354 xs_list_foreach(list, inbox) {
2355 xs *l = xs_split(inbox, "/");
2356 const char *domain = xs_list_get(l, 2);
2357
2358 if (xs_is_string(domain))
2359 peers = xs_list_append(peers, domain);
2360 }
2361
2362 *body = xs_json_dumps(peers, 4);
2363 *ctype = "application/json";
2364 status = HTTP_STATUS_OK;
2365 }
2366 else
2367 if (strcmp(cmd, "/v1/instance/extended_description") == 0) { /** **/
2368 xs *d = xs_dict_new();
2369 xs *greeting = xs_fmt("%s/greeting.html", srv_basedir);
2370 time_t t = mtime(greeting);
2371 xs *updated_at = xs_str_iso_date(t);
2372 xs *content = xs_replace(snac_blurb, "%host%", xs_dict_get(srv_config, "host"));
2373
2374 d = xs_dict_set(d, "updated_at", updated_at);
2375 d = xs_dict_set(d, "content", content);
2376
2377 *body = xs_json_dumps(d, 4);
2378 *ctype = "application/json";
2379 status = HTTP_STATUS_OK;
2380 }
2381 else
2382 if (xs_startswith(cmd, "/v1/statuses/")) { /** **/
2383 /* information about a status */
2384 if (logged_in) {
2385 xs *l = xs_split(cmd, "/");
2386 const char *oid = xs_list_get(l, 3);
2387 const char *op = xs_list_get(l, 4);
2388
2389 if (!xs_is_null(oid)) {
2390 xs *msg = NULL;
2391 xs *out = NULL;
2392
2393 /* skip the 'fake' part of the id */
2394 oid = MID_TO_MD5(oid);
2395
2396 xs *id = xs_tolower_i(xs_dup(oid));
2397
2398 if (valid_status(object_get_by_md5(id, &msg))) {
2399 if (op == NULL) {
2400 if (!is_muted(&snac1, get_atto(msg))) {
2401 /* return the status itself */
2402 out = mastoapi_status(&snac1, msg);
2403 }
2404 }
2405 else
2406 if (strcmp(op, "context") == 0) { /** **/
2407 /* return ancestors and children */
2408 xs *anc = xs_list_new();
2409 xs *des = xs_list_new();
2410 xs_list *p;
2411 const xs_str *v;
2412 char pid[MD5_HEX_SIZE];
2413
2414 /* build the [grand]parent list, moving up */
2415 strncpy(pid, id, sizeof(pid));
2416
2417 while (object_parent(pid, pid)) {
2418 xs *m2 = NULL;
2419
2420 if (valid_status(timeline_get_by_md5(&snac1, pid, &m2))) {
2421 xs *st = mastoapi_status(&snac1, m2);
2422
2423 if (st)
2424 anc = xs_list_insert(anc, 0, st);
2425 }
2426 else
2427 break;
2428 }
2429
2430 /* build the children list */
2431 xs *children = object_children(xs_dict_get(msg, "id"));
2432 p = children;
2433
2434 while (xs_list_iter(&p, &v)) {
2435 xs *m2 = NULL;
2436
2437 if (valid_status(timeline_get_by_md5(&snac1, v, &m2))) {
2438 if (xs_is_null(xs_dict_get(m2, "name"))) {
2439 xs *st = mastoapi_status(&snac1, m2);
2440
2441 if (st)
2442 des = xs_list_append(des, st);
2443 }
2444 }
2445 }
2446
2447 out = xs_dict_new();
2448 out = xs_dict_append(out, "ancestors", anc);
2449 out = xs_dict_append(out, "descendants", des);
2450 }
2451 else
2452 if (strcmp(op, "reblogged_by") == 0 || /** **/
2453 strcmp(op, "favourited_by") == 0) { /** **/
2454 /* return the list of people who liked or boosted this */
2455 out = xs_list_new();
2456
2457 xs *l = NULL;
2458
2459 if (op[0] == 'r')
2460 l = object_announces(xs_dict_get(msg, "id"));
2461 else
2462 l = object_likes(xs_dict_get(msg, "id"));
2463
2464 xs_list *p = l;
2465 const xs_str *v;
2466
2467 while (xs_list_iter(&p, &v)) {
2468 xs *actor2 = NULL;
2469
2470 if (valid_status(object_get_by_md5(v, &actor2))) {
2471 xs *acct2 = mastoapi_account(&snac1, actor2);
2472
2473 out = xs_list_append(out, acct2);
2474 }
2475 }
2476 }
2477 else
2478 if (strcmp(op, "source") == 0) { /** **/
2479 out = xs_dict_new();
2480
2481 /* get the mastoapi status id */
2482 out = xs_dict_append(out, "id", xs_list_get(l, 3));
2483
2484 out = xs_dict_append(out, "text", xs_dict_get(msg, "sourceContent"));
2485 out = xs_dict_append(out, "spoiler_text", xs_dict_get(msg, "summary"));
2486 }
2487 }
2488 else
2489 srv_debug(1, xs_fmt("mastoapi status: bad id %s", id));
2490
2491 if (out != NULL) {
2492 *body = xs_json_dumps(out, 4);
2493 *ctype = "application/json";
2494 status = HTTP_STATUS_OK;
2495 }
2496 }
2497 }
2498 else
2499 status = HTTP_STATUS_UNAUTHORIZED;
2500 }
2501 else
2502 if (strcmp(cmd, "/v1/preferences") == 0) { /** **/
2503 /* TBD */
2504 *body = xs_dup("{}");
2505 *ctype = "application/json";
2506 status = HTTP_STATUS_OK;
2507 }
2508 else
2509 if (strcmp(cmd, "/v1/markers") == 0) { /** **/
2510 if (logged_in) {
2511 const xs_list *timeline = xs_dict_get(args, "timeline[]");
2512 xs_str *json = NULL;
2513 if (!xs_is_null(timeline))
2514 json = xs_json_dumps(markers_get(&snac1, timeline), 4);
2515
2516 if (!xs_is_null(json))
2517 *body = json;
2518 else
2519 *body = xs_dup("{}");
2520
2521 *ctype = "application/json";
2522 status = HTTP_STATUS_OK;
2523 }
2524 else
2525 status = HTTP_STATUS_UNAUTHORIZED;
2526 }
2527 else
2528 if (strcmp(cmd, "/v1/followed_tags") == 0) { /** **/
2529 if (logged_in) {
2530 xs *r = xs_list_new();
2531 const xs_list *followed_hashtags = xs_dict_get_def(snac1.config,
2532 "followed_hashtags", xs_stock(XSTYPE_LIST));
2533 const char *hashtag;
2534
2535 xs_list_foreach(followed_hashtags, hashtag) {
2536 if (*hashtag == '#') {
2537 xs *d = xs_dict_new();
2538 xs *s = xs_fmt("%s?t=%s", srv_baseurl, hashtag + 1);
2539
2540 d = xs_dict_set(d, "name", hashtag + 1);
2541 d = xs_dict_set(d, "url", s);
2542 d = xs_dict_set(d, "history", xs_stock(XSTYPE_LIST));
2543
2544 r = xs_list_append(r, d);
2545 }
2546 }
2547
2548 *body = xs_json_dumps(r, 4);
2549 *ctype = "application/json";
2550 status = HTTP_STATUS_OK;
2551 }
2552 else
2553 status = HTTP_STATUS_UNAUTHORIZED;
2554 }
2555 else
2556 if (strcmp(cmd, "/v1/blocks") == 0) { /** **/
2557 *body = xs_dup("[]");
2558 *ctype = "application/json";
2559 status = HTTP_STATUS_OK;
2560 }
2561 else
2562 if (strcmp(cmd, "/v1/mutes") == 0) { /** **/
2563 *body = xs_dup("[]");
2564 *ctype = "application/json";
2565 status = HTTP_STATUS_OK;
2566 }
2567 else
2568 if (strcmp(cmd, "/v1/trends/tags") == 0) { /** **/
2569 *body = xs_dup("[]");
2570 *ctype = "application/json";
2571 status = HTTP_STATUS_OK;
2572 }
2573 else
2574 if (strcmp(cmd, "/v1/trends/statuses") == 0) { /** **/
2575 *body = xs_dup("[]");
2576 *ctype = "application/json";
2577 status = HTTP_STATUS_OK;
2578 }
2579 else
2580 if (strcmp(cmd, "/v2/search") == 0) { /** **/
2581 if (logged_in) {
2582 const char *q = xs_dict_get(args, "q");
2583 const char *type = xs_dict_get(args, "type");
2584 const char *offset = xs_dict_get(args, "offset");
2585
2586 xs *acl = xs_list_new();
2587 xs *stl = xs_list_new();
2588 xs *htl = xs_list_new();
2589 xs *res = xs_dict_new();
2590
2591 if (xs_is_null(offset) || strcmp(offset, "0") == 0) {
2592 /* reply something only for offset 0; otherwise,
2593 apps like Tusky keep asking again and again */
2594 if (xs_startswith(q, "https://")) {
2595 if (!timeline_here(&snac1, q)) {
2596 xs *object = NULL;
2597 int status;
2598
2599 status = activitypub_request(&snac1, q, &object);
2600 snac_debug(&snac1, 1, xs_fmt("Request searched URL %s %d", q, status));
2601
2602 if (valid_status(status)) {
2603 /* got it; also request the actor */
2604 const char *attr_to = get_atto(object);
2605 xs *actor_obj = NULL;
2606
2607 if (!xs_is_null(attr_to)) {
2608 status = actor_request(&snac1, attr_to, &actor_obj);
2609
2610 snac_debug(&snac1, 1, xs_fmt("Request author %s of %s %d", attr_to, q, status));
2611
2612 if (valid_status(status)) {
2613 /* add the actor */
2614 actor_add(attr_to, actor_obj);
2615
2616 /* add the post to the timeline */
2617 timeline_add(&snac1, q, object);
2618 }
2619 }
2620 }
2621 }
2622 }
2623
2624 if (!xs_is_null(q)) {
2625 if (xs_is_null(type) || strcmp(type, "accounts") == 0) {
2626 /* do a webfinger query */
2627 char *actor = NULL;
2628 char *user = NULL;
2629
2630 if (valid_status(webfinger_request(q, &actor, &user)) && actor) {
2631 xs *actor_o = NULL;
2632
2633 if (valid_status(actor_request(&snac1, actor, &actor_o))) {
2634 xs *acct = mastoapi_account(NULL, actor_o);
2635
2636 acl = xs_list_append(acl, acct);
2637
2638 if (!object_here(actor))
2639 object_add(actor, actor_o);
2640 }
2641 }
2642 }
2643
2644 if (xs_is_null(type) || strcmp(type, "hashtags") == 0) {
2645 /* search this tag */
2646 xs *tl = tag_search((char *)q, 0, 1);
2647
2648 if (xs_list_len(tl)) {
2649 xs *d = xs_dict_new();
2650
2651 d = xs_dict_append(d, "name", q);
2652 xs *url = xs_fmt("%s?t=%s", srv_baseurl, q);
2653 d = xs_dict_append(d, "url", url);
2654 d = xs_dict_append(d, "history", xs_stock(XSTYPE_LIST));
2655
2656 htl = xs_list_append(htl, d);
2657 }
2658 }
2659
2660 if (xs_is_null(type) || strcmp(type, "statuses") == 0) {
2661 int to = 0;
2662 int cnt = 40;
2663 xs *tl = content_search(&snac1, q, 1, 0, cnt, 0, &to);
2664 int c = 0;
2665 const char *v;
2666
2667 while (xs_list_next(tl, &v, &c) && --cnt) {
2668 xs *post = NULL;
2669
2670 if (!valid_status(timeline_get_by_md5(&snac1, v, &post)))
2671 continue;
2672
2673 xs *s = mastoapi_status(&snac1, post);
2674
2675 if (!xs_is_null(s))
2676 stl = xs_list_append(stl, s);
2677 }
2678 }
2679 }
2680 }
2681
2682 res = xs_dict_append(res, "accounts", acl);
2683 res = xs_dict_append(res, "statuses", stl);
2684 res = xs_dict_append(res, "hashtags", htl);
2685
2686 *body = xs_json_dumps(res, 4);
2687 *ctype = "application/json";
2688 status = HTTP_STATUS_OK;
2689 }
2690 else
2691 status = HTTP_STATUS_UNAUTHORIZED;
2692 }
2693
2694 /* user cleanup */
2695 if (logged_in)
2696 user_free(&snac1);
2697
2698 srv_debug(1, xs_fmt("mastoapi_get_handler %s %d", q_path, status));
2699
2700 return status;
2701}
2702
2703
2704int mastoapi_post_handler(const xs_dict *req, const char *q_path,
2705 const char *payload, int p_size,
2706 char **body, int *b_size, char **ctype)
2707{
2708 (void)p_size;
2709 (void)b_size;
2710
2711 if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
2712 return 0;
2713
2714 int status = HTTP_STATUS_NOT_FOUND;
2715 xs *args = NULL;
2716 const char *i_ctype = xs_dict_get(req, "content-type");
2717
2718 if (i_ctype && xs_startswith(i_ctype, "application/json")) {
2719 if (!xs_is_null(payload))
2720 args = xs_json_loads(payload);
2721 }
2722 else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
2723 {
2724 // Some apps send form data instead of json so we should cater for those
2725 if (!xs_is_null(payload)) {
2726 args = xs_url_vars(payload);
2727 }
2728 }
2729 else
2730 args = xs_dup(xs_dict_get(req, "p_vars"));
2731
2732 if (args == NULL)
2733 return HTTP_STATUS_BAD_REQUEST;
2734
2735 xs *cmd = xs_replace_n(q_path, "/api", "", 1);
2736
2737 snac snac = {0};
2738 int logged_in = process_auth_token(&snac, req);
2739
2740 if (strcmp(cmd, "/v1/apps") == 0) { /** **/
2741 const char *name = xs_dict_get(args, "client_name");
2742 const char *ruri = xs_dict_get(args, "redirect_uris");
2743 const char *scope = xs_dict_get(args, "scope");
2744
2745 /* Ice Cubes sends these values as query parameters, so try these */
2746 if (name == NULL && ruri == NULL && scope == NULL) {
2747 args = xs_dup(xs_dict_get(req, "q_vars"));
2748 name = xs_dict_get(args, "client_name");
2749 ruri = xs_dict_get(args, "redirect_uris");
2750 scope = xs_dict_get(args, "scope");
2751 }
2752
2753 if (xs_type(ruri) == XSTYPE_LIST)
2754 ruri = xs_dict_get(ruri, 0);
2755
2756 if (name && ruri) {
2757 xs *app = xs_dict_new();
2758 xs *id = xs_replace_i(tid(0), ".", "");
2759 xs *csec = random_str();
2760 xs *vkey = random_str();
2761 xs *cid = NULL;
2762
2763 /* pick a non-existent random cid */
2764 for (;;) {
2765 cid = random_str();
2766 xs *p_app = app_get(cid);
2767
2768 if (p_app == NULL)
2769 break;
2770
2771 xs_free(cid);
2772 }
2773
2774 app = xs_dict_append(app, "name", name);
2775 app = xs_dict_append(app, "redirect_uri", ruri);
2776 app = xs_dict_append(app, "client_id", cid);
2777 app = xs_dict_append(app, "client_secret", csec);
2778 app = xs_dict_append(app, "vapid_key", vkey);
2779 app = xs_dict_append(app, "id", id);
2780
2781 *body = xs_json_dumps(app, 4);
2782 *ctype = "application/json";
2783 status = HTTP_STATUS_OK;
2784
2785 app = xs_dict_append(app, "code", "");
2786
2787 if (scope)
2788 app = xs_dict_append(app, "scope", scope);
2789
2790 app_add(cid, app);
2791
2792 srv_debug(1, xs_fmt("mastoapi apps: new app %s", cid));
2793 }
2794 }
2795 else
2796 if (strcmp(cmd, "/v1/statuses") == 0) { /** **/
2797 if (logged_in) {
2798 /* post a new Note */
2799 const char *content = xs_dict_get(args, "status");
2800 const char *mid = xs_dict_get(args, "in_reply_to_id");
2801 const char *visibility = xs_dict_get(args, "visibility");
2802 const char *summary = xs_dict_get(args, "spoiler_text");
2803 const char *media_ids = xs_dict_get(args, "media_ids");
2804 const char *language = xs_dict_get(args, "language");
2805
2806 if (xs_is_null(media_ids))
2807 media_ids = xs_dict_get(args, "media_ids[]");
2808
2809 if (xs_is_null(media_ids))
2810 media_ids = xs_dict_get(args, "media_ids");
2811
2812 if (xs_is_null(visibility))
2813 visibility = "public";
2814
2815 xs *attach_list = xs_list_new();
2816 xs *irt = NULL;
2817
2818 /* is it a reply? */
2819 if (mid != NULL) {
2820 xs *r_msg = NULL;
2821 const char *md5 = MID_TO_MD5(mid);
2822
2823 if (valid_status(object_get_by_md5(md5, &r_msg)))
2824 irt = xs_dup(xs_dict_get(r_msg, "id"));
2825 }
2826
2827 /* does it have attachments? */
2828 if (!xs_is_null(media_ids)) {
2829 xs *mi = NULL;
2830
2831 if (xs_type(media_ids) == XSTYPE_LIST)
2832 mi = xs_dup(media_ids);
2833 else {
2834 mi = xs_list_new();
2835 mi = xs_list_append(mi, media_ids);
2836 }
2837
2838 xs_list *p = mi;
2839 const xs_str *v;
2840
2841 while (xs_list_iter(&p, &v)) {
2842 xs *l = xs_list_new();
2843 xs *url = xs_fmt("%s/s/%s", snac.actor, v);
2844 xs *desc = static_get_meta(&snac, v);
2845
2846 l = xs_list_append(l, url);
2847 l = xs_list_append(l, desc);
2848
2849 attach_list = xs_list_append(attach_list, l);
2850 }
2851 }
2852
2853 /* prepare the message */
2854 int scope = 1;
2855 if (strcmp(visibility, "unlisted") == 0)
2856 scope = 2;
2857 else
2858 if (strcmp(visibility, "public") == 0)
2859 scope = 0;
2860
2861 xs *msg = msg_note(&snac, content, NULL, irt, attach_list, scope, language, NULL);
2862
2863 if (!xs_is_null(summary) && *summary) {
2864 msg = xs_dict_set(msg, "sensitive", xs_stock(XSTYPE_TRUE));
2865 msg = xs_dict_set(msg, "summary", summary);
2866 }
2867
2868 /* scheduled? */
2869 const char *scheduled_at = xs_dict_get(args, "scheduled_at");
2870
2871 if (xs_is_string(scheduled_at) && *scheduled_at) {
2872 msg = xs_dict_set(msg, "published", scheduled_at);
2873
2874 schedule_add(&snac, xs_dict_get(msg, "id"), msg);
2875 }
2876 else {
2877 /* store */
2878 timeline_add(&snac, xs_dict_get(msg, "id"), msg);
2879
2880 /* 'Create' message */
2881 xs *c_msg = msg_create(&snac, msg);
2882 enqueue_message(&snac, c_msg);
2883
2884 timeline_touch(&snac);
2885 }
2886
2887 /* convert to a mastodon status as a response code */
2888 xs *st = mastoapi_status(&snac, msg);
2889
2890 *body = xs_json_dumps(st, 4);
2891 *ctype = "application/json";
2892 status = HTTP_STATUS_OK;
2893 }
2894 else
2895 status = HTTP_STATUS_UNAUTHORIZED;
2896 }
2897 else
2898 if (xs_startswith(cmd, "/v1/statuses")) { /** **/
2899 if (logged_in) {
2900 /* operations on a status */
2901 xs *l = xs_split(cmd, "/");
2902 const char *mid = xs_list_get(l, 3);
2903 const char *op = xs_list_get(l, 4);
2904
2905 if (!xs_is_null(mid)) {
2906 xs *msg = NULL;
2907 xs *out = NULL;
2908
2909 /* skip the 'fake' part of the id */
2910 mid = MID_TO_MD5(mid);
2911
2912 if (valid_status(timeline_get_by_md5(&snac, mid, &msg))) {
2913 const char *id = xs_dict_get(msg, "id");
2914
2915 if (op == NULL) {
2916 /* no operation (?) */
2917 }
2918 else
2919 if (strcmp(op, "favourite") == 0) { /** **/
2920 xs *n_msg = msg_admiration(&snac, id, "Like");
2921
2922 if (n_msg != NULL) {
2923 enqueue_message(&snac, n_msg);
2924 timeline_admire(&snac, xs_dict_get(n_msg, "object"), snac.actor, 1);
2925
2926 out = mastoapi_status(&snac, msg);
2927 }
2928 }
2929 else
2930 if (strcmp(op, "unfavourite") == 0) { /** **/
2931 xs *n_msg = msg_repulsion(&snac, id, "Like");
2932
2933 if (n_msg != NULL) {
2934 enqueue_message(&snac, n_msg);
2935
2936 out = mastoapi_status(&snac, msg);
2937 }
2938 }
2939 else
2940 if (strcmp(op, "reblog") == 0) { /** **/
2941 xs *n_msg = msg_admiration(&snac, id, "Announce");
2942
2943 if (n_msg != NULL) {
2944 enqueue_message(&snac, n_msg);
2945 timeline_admire(&snac, xs_dict_get(n_msg, "object"), snac.actor, 0);
2946
2947 out = mastoapi_status(&snac, msg);
2948 }
2949 }
2950 else
2951 if (strcmp(op, "unreblog") == 0) { /** **/
2952 xs *n_msg = msg_repulsion(&snac, id, "Announce");
2953
2954 if (n_msg != NULL) {
2955 enqueue_message(&snac, n_msg);
2956
2957 out = mastoapi_status(&snac, msg);
2958 }
2959 }
2960 else
2961 if (strcmp(op, "bookmark") == 0) { /** **/
2962 /* bookmark this message */
2963 if (bookmark(&snac, id) == 0)
2964 out = mastoapi_status(&snac, msg);
2965 else
2966 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2967 }
2968 else
2969 if (strcmp(op, "unbookmark") == 0) { /** **/
2970 /* unbookmark this message */
2971 unbookmark(&snac, id);
2972 out = mastoapi_status(&snac, msg);
2973 }
2974 else
2975 if (strcmp(op, "pin") == 0) { /** **/
2976 /* pin this message */
2977 if (pin(&snac, id) == 0)
2978 out = mastoapi_status(&snac, msg);
2979 else
2980 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
2981 }
2982 else
2983 if (strcmp(op, "unpin") == 0) { /** **/
2984 /* unpin this message */
2985 unpin(&snac, id);
2986 out = mastoapi_status(&snac, msg);
2987 }
2988 else
2989 if (strcmp(op, "mute") == 0) { /** **/
2990 /* Mastodon's mute is snac's hide */
2991 }
2992 else
2993 if (strcmp(op, "unmute") == 0) { /** **/
2994 /* Mastodon's unmute is snac's unhide */
2995 }
2996 }
2997
2998 if (out != NULL) {
2999 *body = xs_json_dumps(out, 4);
3000 *ctype = "application/json";
3001 status = HTTP_STATUS_OK;
3002 }
3003 }
3004 }
3005 else
3006 status = HTTP_STATUS_UNAUTHORIZED;
3007 }
3008 else
3009 if (strcmp(cmd, "/v1/notifications/clear") == 0) { /** **/
3010 if (logged_in) {
3011 notify_clear(&snac);
3012 timeline_touch(&snac);
3013
3014 *body = xs_dup("{}");
3015 *ctype = "application/json";
3016 status = HTTP_STATUS_OK;
3017 }
3018 else
3019 status = HTTP_STATUS_UNAUTHORIZED;
3020 }
3021 else
3022 if (strcmp(cmd, "/v1/push/subscription") == 0) { /** **/
3023 /* I don't know what I'm doing */
3024 if (logged_in) {
3025 const char *v;
3026
3027 xs *wpush = xs_dict_new();
3028
3029 wpush = xs_dict_append(wpush, "id", "1");
3030
3031 v = xs_dict_get(args, "data");
3032 v = xs_dict_get(v, "alerts");
3033 wpush = xs_dict_append(wpush, "alerts", v);
3034
3035 v = xs_dict_get(args, "subscription");
3036 v = xs_dict_get(v, "endpoint");
3037 wpush = xs_dict_append(wpush, "endpoint", v);
3038
3039 xs *server_key = random_str();
3040 wpush = xs_dict_append(wpush, "server_key", server_key);
3041
3042 *body = xs_json_dumps(wpush, 4);
3043 *ctype = "application/json";
3044 status = HTTP_STATUS_OK;
3045 }
3046 else
3047 status = HTTP_STATUS_UNAUTHORIZED;
3048 }
3049 else
3050 if (strcmp(cmd, "/v1/media") == 0 || strcmp(cmd, "/v2/media") == 0) { /** **/
3051 if (logged_in) {
3052 const xs_list *file = xs_dict_get(args, "file");
3053 const char *desc = xs_dict_get(args, "description");
3054
3055 if (xs_is_null(desc))
3056 desc = "";
3057
3058 status = HTTP_STATUS_BAD_REQUEST;
3059
3060 if (xs_type(file) == XSTYPE_LIST) {
3061 const char *fn = xs_list_get(file, 0);
3062
3063 if (*fn != '\0') {
3064 char *ext = strrchr(fn, '.');
3065 char rnd[32];
3066 xs_rnd_buf(rnd, sizeof(rnd));
3067 xs *hash = xs_md5_hex(rnd, sizeof(rnd));
3068 xs *id = xs_fmt("post-%s%s", hash, ext ? ext : "");
3069 xs *url = xs_fmt("%s/s/%s", snac.actor, id);
3070 int fo = xs_number_get(xs_list_get(file, 1));
3071 int fs = xs_number_get(xs_list_get(file, 2));
3072
3073 /* store */
3074 static_put(&snac, id, payload + fo, fs);
3075 static_put_meta(&snac, id, desc);
3076
3077 /* prepare a response */
3078 xs *rsp = xs_dict_new();
3079
3080 rsp = xs_dict_append(rsp, "id", id);
3081 rsp = xs_dict_append(rsp, "type", "image");
3082 rsp = xs_dict_append(rsp, "url", url);
3083 rsp = xs_dict_append(rsp, "preview_url", url);
3084 rsp = xs_dict_append(rsp, "remote_url", url);
3085 rsp = xs_dict_append(rsp, "description", desc);
3086
3087 *body = xs_json_dumps(rsp, 4);
3088 *ctype = "application/json";
3089 status = HTTP_STATUS_OK;
3090 }
3091 }
3092 }
3093 else
3094 status = HTTP_STATUS_UNAUTHORIZED;
3095 }
3096 else
3097 if (xs_startswith(cmd, "/v1/accounts")) { /** **/
3098 if (logged_in) {
3099 /* account-related information */
3100 xs *l = xs_split(cmd, "/");
3101 const char *md5 = xs_list_get(l, 3);
3102 const char *opt = xs_list_get(l, 4);
3103 xs *rsp = NULL;
3104
3105 if (!xs_is_null(md5) && *md5) {
3106 xs *actor_o = NULL;
3107
3108 if (xs_is_null(opt)) {
3109 /* ? */
3110 }
3111 else
3112 if (strcmp(opt, "follow") == 0) { /** **/
3113 if (valid_status(object_get_by_md5(md5, &actor_o))) {
3114 const char *actor = xs_dict_get(actor_o, "id");
3115
3116 xs *msg = msg_follow(&snac, actor);
3117
3118 if (msg != NULL) {
3119 /* reload the actor from the message, in may be different */
3120 actor = xs_dict_get(msg, "object");
3121
3122 following_add(&snac, actor, msg);
3123
3124 enqueue_output_by_actor(&snac, msg, actor, 0);
3125
3126 rsp = mastoapi_relationship(&snac, md5);
3127 }
3128 }
3129 }
3130 else
3131 if (strcmp(opt, "unfollow") == 0) { /** **/
3132 if (valid_status(object_get_by_md5(md5, &actor_o))) {
3133 const char *actor = xs_dict_get(actor_o, "id");
3134
3135 /* get the following object */
3136 xs *object = NULL;
3137
3138 if (valid_status(following_get(&snac, actor, &object))) {
3139 xs *msg = msg_undo(&snac, xs_dict_get(object, "object"));
3140
3141 following_del(&snac, actor);
3142
3143 enqueue_output_by_actor(&snac, msg, actor, 0);
3144
3145 rsp = mastoapi_relationship(&snac, md5);
3146 }
3147 }
3148 }
3149 else
3150 if (strcmp(opt, "block") == 0) { /** **/
3151 if (valid_status(object_get_by_md5(md5, &actor_o))) {
3152 const char *actor = xs_dict_get(actor_o, "id");
3153
3154 mute(&snac, actor);
3155
3156 rsp = mastoapi_relationship(&snac, md5);
3157 }
3158 }
3159 else
3160 if (strcmp(opt, "unblock") == 0) { /** **/
3161 if (valid_status(object_get_by_md5(md5, &actor_o))) {
3162 const char *actor = xs_dict_get(actor_o, "id");
3163
3164 unmute(&snac, actor);
3165
3166 rsp = mastoapi_relationship(&snac, md5);
3167 }
3168 }
3169 }
3170
3171 if (rsp != NULL) {
3172 *body = xs_json_dumps(rsp, 4);
3173 *ctype = "application/json";
3174 status = HTTP_STATUS_OK;
3175 }
3176 }
3177 else
3178 status = HTTP_STATUS_UNAUTHORIZED;
3179 }
3180 else
3181 if (xs_startswith(cmd, "/v1/polls")) { /** **/
3182 if (logged_in) {
3183 /* operations on a status */
3184 xs *l = xs_split(cmd, "/");
3185 const char *mid = xs_list_get(l, 3);
3186 const char *op = xs_list_get(l, 4);
3187
3188 if (!xs_is_null(mid)) {
3189 xs *msg = NULL;
3190 xs *out = NULL;
3191
3192 /* skip the 'fake' part of the id */
3193 mid = MID_TO_MD5(mid);
3194
3195 if (valid_status(timeline_get_by_md5(&snac, mid, &msg))) {
3196 const char *id = xs_dict_get(msg, "id");
3197 const char *atto = get_atto(msg);
3198
3199 const xs_list *opts = xs_dict_get(msg, "oneOf");
3200 if (opts == NULL)
3201 opts = xs_dict_get(msg, "anyOf");
3202
3203 if (op == NULL) {
3204 }
3205 else
3206 if (strcmp(op, "votes") == 0) {
3207 const xs_list *choices = xs_dict_get(args, "choices[]");
3208
3209 if (xs_is_null(choices))
3210 choices = xs_dict_get(args, "choices");
3211
3212 if (xs_type(choices) == XSTYPE_LIST) {
3213 const xs_str *v;
3214
3215 int c = 0;
3216 while (xs_list_next(choices, &v, &c)) {
3217 int io = atoi(v);
3218 const xs_dict *o = xs_list_get(opts, io);
3219
3220 if (o) {
3221 const char *name = xs_dict_get(o, "name");
3222
3223 xs *msg = msg_note(&snac, "", atto, (char *)id, NULL, 1, NULL, NULL);
3224 msg = xs_dict_append(msg, "name", name);
3225
3226 xs *c_msg = msg_create(&snac, msg);
3227 enqueue_message(&snac, c_msg);
3228 timeline_add(&snac, xs_dict_get(msg, "id"), msg);
3229 }
3230 }
3231
3232 out = mastoapi_poll(&snac, msg);
3233 }
3234 }
3235 }
3236
3237 if (out != NULL) {
3238 *body = xs_json_dumps(out, 4);
3239 *ctype = "application/json";
3240 status = HTTP_STATUS_OK;
3241 }
3242 }
3243 }
3244 else
3245 status = HTTP_STATUS_UNAUTHORIZED;
3246 }
3247 else
3248 if (strcmp(cmd, "/v1/lists") == 0) {
3249 if (logged_in) {
3250 const char *title = xs_dict_get(args, "title");
3251
3252 if (xs_type(title) == XSTYPE_STRING) {
3253 /* add the list */
3254 xs *out = xs_dict_new();
3255 xs *lid = list_maint(&snac, title, 1);
3256
3257 if (!xs_is_null(lid)) {
3258 out = xs_dict_append(out, "id", lid);
3259 out = xs_dict_append(out, "title", title);
3260 out = xs_dict_append(out, "replies_policy", xs_dict_get_def(args, "replies_policy", "list"));
3261 out = xs_dict_append(out, "exclusive", xs_stock(XSTYPE_FALSE));
3262
3263 status = HTTP_STATUS_OK;
3264 }
3265 else {
3266 out = xs_dict_append(out, "error", "cannot create list");
3267 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
3268 }
3269
3270 *body = xs_json_dumps(out, 4);
3271 *ctype = "application/json";
3272 }
3273 else
3274 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
3275 }
3276 }
3277 else
3278 if (xs_startswith(cmd, "/v1/lists/")) { /** list maintenance **/
3279 if (logged_in) {
3280 xs *l = xs_split(cmd, "/");
3281 const char *op = xs_list_get(l, -1);
3282 const char *id = xs_list_get(l, -2);
3283
3284 if (op && id && xs_is_hex(id)) {
3285 if (strcmp(op, "accounts") == 0) {
3286 const xs_list *accts = xs_dict_get(args, "account_ids[]");
3287
3288 if (xs_is_null(accts))
3289 accts = xs_dict_get(args, "account_ids");
3290
3291 int c = 0;
3292 const char *v;
3293
3294 while (xs_list_next(accts, &v, &c)) {
3295 list_content(&snac, id, v, 1);
3296 }
3297
3298 xs *out = xs_dict_new();
3299 *body = xs_json_dumps(out, 4);
3300 *ctype = "application/json";
3301 status = HTTP_STATUS_OK;
3302 }
3303 }
3304 }
3305 }
3306 else if (strcmp(cmd, "/v1/markers") == 0) { /** **/
3307 xs_str *json = NULL;
3308 if (logged_in) {
3309 const xs_str *home_marker = xs_dict_get(args, "home[last_read_id]");
3310 if (xs_is_null(home_marker)) {
3311 const xs_dict *home = xs_dict_get(args, "home");
3312 if (!xs_is_null(home))
3313 home_marker = xs_dict_get(home, "last_read_id");
3314 }
3315
3316 const xs_str *notify_marker = xs_dict_get(args, "notifications[last_read_id]");
3317 if (xs_is_null(notify_marker)) {
3318 const xs_dict *notify = xs_dict_get(args, "notifications");
3319 if (!xs_is_null(notify))
3320 notify_marker = xs_dict_get(notify, "last_read_id");
3321 }
3322 json = xs_json_dumps(markers_set(&snac, home_marker, notify_marker), 4);
3323 }
3324 if (!xs_is_null(json))
3325 *body = json;
3326 else
3327 *body = xs_dup("{}");
3328
3329 *ctype = "application/json";
3330 status = HTTP_STATUS_OK;
3331 }
3332 else
3333 if (xs_startswith(cmd, "/v1/follow_requests")) { /** **/
3334 if (logged_in) {
3335 /* "authorize" or "reject" */
3336 xs *rel = NULL;
3337 xs *l = xs_split(cmd, "/");
3338 const char *md5 = xs_list_get(l, -2);
3339 const char *s_cmd = xs_list_get(l, -1);
3340
3341 if (xs_is_string(md5) && xs_is_string(s_cmd)) {
3342 xs *actor = NULL;
3343
3344 if (valid_status(object_get_by_md5(md5, &actor))) {
3345 const char *actor_id = xs_dict_get(actor, "id");
3346
3347 if (strcmp(s_cmd, "authorize") == 0) {
3348 xs *fwreq = pending_get(&snac, actor_id);
3349
3350 if (fwreq != NULL) {
3351 xs *reply = msg_accept(&snac, fwreq, actor_id);
3352
3353 enqueue_message(&snac, reply);
3354
3355 if (xs_is_null(xs_dict_get(fwreq, "published"))) {
3356 xs *date = xs_str_utctime(0, ISO_DATE_SPEC);
3357 fwreq = xs_dict_set(fwreq, "published", date);
3358 }
3359
3360 timeline_add(&snac, xs_dict_get(fwreq, "id"), fwreq);
3361
3362 follower_add(&snac, actor_id);
3363
3364 pending_del(&snac, actor_id);
3365 rel = mastoapi_relationship(&snac, md5);
3366 }
3367 }
3368 else
3369 if (strcmp(s_cmd, "reject") == 0) {
3370 pending_del(&snac, actor_id);
3371 rel = mastoapi_relationship(&snac, md5);
3372 }
3373 }
3374 }
3375
3376 if (rel != NULL) {
3377 *body = xs_json_dumps(rel, 4);
3378 *ctype = "application/json";
3379 status = HTTP_STATUS_OK;
3380 }
3381 }
3382 }
3383 else
3384 if (xs_startswith(cmd, "/v1/tags/")) { /** **/
3385 if (logged_in) {
3386 xs *l = xs_split(cmd, "/");
3387 const char *i_tag = xs_list_get(l, 3);
3388 const char *cmd = xs_list_get(l, 4);
3389
3390 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
3391
3392 if (xs_is_string(i_tag) && xs_is_string(cmd)) {
3393 int ok = 0;
3394
3395 xs *tag = xs_fmt("#%s", i_tag);
3396 xs *followed_hashtags = xs_dup(xs_dict_get_def(snac.config,
3397 "followed_hashtags", xs_stock(XSTYPE_LIST)));
3398
3399 if (strcmp(cmd, "follow") == 0) {
3400 followed_hashtags = xs_list_append(followed_hashtags, tag);
3401 ok = 1;
3402 }
3403 else
3404 if (strcmp(cmd, "unfollow") == 0) {
3405 int off = xs_list_in(followed_hashtags, tag);
3406
3407 if (off != -1)
3408 followed_hashtags = xs_list_del(followed_hashtags, off);
3409
3410 ok = 1;
3411 }
3412
3413 if (ok) {
3414 /* update */
3415 xs_dict_set(snac.config, "followed_hashtags", followed_hashtags);
3416 user_persist(&snac, 0);
3417
3418 xs *d = xs_dict_new();
3419 xs *s = xs_fmt("%s?t=%s", srv_baseurl, i_tag);
3420 d = xs_dict_set(d, "name", i_tag);
3421 d = xs_dict_set(d, "url", s);
3422 d = xs_dict_set(d, "history", xs_stock(XSTYPE_LIST));
3423
3424 *body = xs_json_dumps(d, 4);
3425 *ctype = "application/json";
3426 status = HTTP_STATUS_OK;
3427 }
3428 }
3429 }
3430 }
3431 else
3432 status = HTTP_STATUS_UNPROCESSABLE_CONTENT;
3433
3434 /* user cleanup */
3435 if (logged_in)
3436 user_free(&snac);
3437
3438 srv_debug(1, xs_fmt("mastoapi_post_handler %s %d", q_path, status));
3439
3440 return status;
3441}
3442
3443
3444int mastoapi_delete_handler(const xs_dict *req, const char *q_path,
3445 const char *payload, int p_size,
3446 char **body, int *b_size, char **ctype)
3447{
3448 (void)p_size;
3449 (void)body;
3450 (void)b_size;
3451 (void)ctype;
3452
3453 if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
3454 return 0;
3455
3456 int status = HTTP_STATUS_NOT_FOUND;
3457 xs *args = NULL;
3458 const char *i_ctype = xs_dict_get(req, "content-type");
3459
3460 if (i_ctype && xs_startswith(i_ctype, "application/json")) {
3461 if (!xs_is_null(payload))
3462 args = xs_json_loads(payload);
3463 }
3464 else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
3465 {
3466 // Some apps send form data instead of json so we should cater for those
3467 if (!xs_is_null(payload)) {
3468 args = xs_url_vars(payload);
3469 }
3470 }
3471 else
3472 args = xs_dup(xs_dict_get(req, "p_vars"));
3473
3474 if (args == NULL)
3475 return HTTP_STATUS_BAD_REQUEST;
3476
3477 snac snac = {0};
3478 int logged_in = process_auth_token(&snac, req);
3479
3480 xs *cmd = xs_replace_n(q_path, "/api", "", 1);
3481
3482 if (xs_startswith(cmd, "/v1/push/subscription") || xs_startswith(cmd, "/v2/push/subscription")) { /** **/
3483 // pretend we deleted it, since it doesn't exist anyway
3484 status = HTTP_STATUS_OK;
3485 }
3486 else
3487 if (xs_startswith(cmd, "/v1/lists/")) {
3488 if (logged_in) {
3489 xs *l = xs_split(cmd, "/");
3490 const char *p = xs_list_get(l, -1);
3491
3492 if (p) {
3493 if (strcmp(p, "accounts") == 0) {
3494 /* delete account from list */
3495 p = xs_list_get(l, -2);
3496 const xs_list *accts = xs_dict_get(args, "account_ids[]");
3497
3498 if (xs_is_null(accts))
3499 accts = xs_dict_get(args, "account_ids");
3500
3501 int c = 0;
3502 const char *v;
3503
3504 while (xs_list_next(accts, &v, &c)) {
3505 list_content(&snac, p, v, 2);
3506 }
3507 }
3508 else {
3509 /* delete list */
3510 if (xs_is_hex(p)) {
3511 list_maint(&snac, p, 2);
3512 }
3513 }
3514 }
3515
3516 *ctype = "application/json";
3517 status = HTTP_STATUS_OK;
3518 }
3519 else
3520 status = HTTP_STATUS_UNAUTHORIZED;
3521 }
3522
3523 /* user cleanup */
3524 if (logged_in)
3525 user_free(&snac);
3526
3527 srv_debug(1, xs_fmt("mastoapi_delete_handler %s %d", q_path, status));
3528
3529 return status;
3530}
3531
3532
3533int mastoapi_put_handler(const xs_dict *req, const char *q_path,
3534 const char *payload, int p_size,
3535 char **body, int *b_size, char **ctype)
3536{
3537 (void)p_size;
3538 (void)b_size;
3539
3540 if (!xs_startswith(q_path, "/api/v1/") && !xs_startswith(q_path, "/api/v2/"))
3541 return 0;
3542
3543 int status = HTTP_STATUS_NOT_FOUND;
3544 xs *args = NULL;
3545 const char *i_ctype = xs_dict_get(req, "content-type");
3546
3547 if (i_ctype && xs_startswith(i_ctype, "application/json")) {
3548 if (!xs_is_null(payload))
3549 args = xs_json_loads(payload);
3550 }
3551 else
3552 args = xs_dup(xs_dict_get(req, "p_vars"));
3553
3554 if (args == NULL)
3555 return HTTP_STATUS_BAD_REQUEST;
3556
3557 xs *cmd = xs_replace_n(q_path, "/api", "", 1);
3558
3559 snac snac = {0};
3560 int logged_in = process_auth_token(&snac, req);
3561
3562 if (xs_startswith(cmd, "/v1/media") || xs_startswith(cmd, "/v2/media")) { /** **/
3563 if (logged_in) {
3564 xs *l = xs_split(cmd, "/");
3565 const char *stid = xs_list_get(l, 3);
3566
3567 if (!xs_is_null(stid)) {
3568 const char *desc = xs_dict_get(args, "description");
3569
3570 /* set the image metadata */
3571 static_put_meta(&snac, stid, desc);
3572
3573 /* prepare a response */
3574 xs *rsp = xs_dict_new();
3575 xs *url = xs_fmt("%s/s/%s", snac.actor, stid);
3576
3577 rsp = xs_dict_append(rsp, "id", stid);
3578 rsp = xs_dict_append(rsp, "type", "image");
3579 rsp = xs_dict_append(rsp, "url", url);
3580 rsp = xs_dict_append(rsp, "preview_url", url);
3581 rsp = xs_dict_append(rsp, "remote_url", url);
3582 rsp = xs_dict_append(rsp, "description", desc);
3583
3584 *body = xs_json_dumps(rsp, 4);
3585 *ctype = "application/json";
3586 status = HTTP_STATUS_OK;
3587 }
3588 }
3589 else
3590 status = HTTP_STATUS_UNAUTHORIZED;
3591 }
3592 else
3593 if (xs_startswith(cmd, "/v1/statuses")) {
3594 if (logged_in) {
3595 xs *l = xs_split(cmd, "/");
3596 const char *mid = xs_list_get(l, 3);
3597
3598 if (!xs_is_null(mid)) {
3599 const char *md5 = MID_TO_MD5(mid);
3600 xs *rsp = NULL;
3601 xs *msg = NULL;
3602
3603 if (valid_status(timeline_get_by_md5(&snac, md5, &msg))) {
3604 const char *content = xs_dict_get(args, "status");
3605 xs *atls = xs_list_new();
3606 xs *f_content = not_really_markdown(content, &atls, NULL);
3607
3608 /* replace fields with new content */
3609 msg = xs_dict_set(msg, "sourceContent", content);
3610 msg = xs_dict_set(msg, "content", f_content);
3611
3612 xs *updated = xs_str_utctime(0, ISO_DATE_SPEC);
3613 msg = xs_dict_set(msg, "updated", updated);
3614
3615 /* overwrite object, not updating the indexes */
3616 object_add_ow(xs_dict_get(msg, "id"), msg);
3617
3618 /* update message */
3619 xs *c_msg = msg_update(&snac, msg);
3620
3621 enqueue_message(&snac, c_msg);
3622
3623 rsp = mastoapi_status(&snac, msg);
3624 }
3625
3626 if (rsp != NULL) {
3627 *body = xs_json_dumps(rsp, 4);
3628 *ctype = "application/json";
3629 status = HTTP_STATUS_OK;
3630 }
3631 }
3632 }
3633 else
3634 status = HTTP_STATUS_UNAUTHORIZED;
3635 }
3636
3637 /* user cleanup */
3638 if (logged_in)
3639 user_free(&snac);
3640
3641 srv_debug(1, xs_fmt("mastoapi_put_handler %s %d", q_path, status));
3642
3643 return status;
3644}
3645
3646void persist_image(const char *key, const xs_val *data, const char *payload, snac *snac)
3647/* Store header or avatar */
3648{
3649 if (data != NULL) {
3650 if (xs_type(data) == XSTYPE_LIST) {
3651 const char *fn = xs_list_get(data, 0);
3652
3653 if (fn && *fn) {
3654 const char *ext = strrchr(fn, '.');
3655
3656 /* Mona iOS sends always jpg as application/octet-stream with no filename */
3657 if (ext == NULL || strcmp(fn, key) == 0) {
3658 ext = ".jpg";
3659 }
3660
3661 /* Make sure we have a unique file name, otherwise updated images will not be
3662 * re-loaded by clients. */
3663 xs *rnd = random_str();
3664 xs *hash = xs_md5_hex(rnd, strlen(rnd));
3665 xs *id = xs_fmt("%s%s", hash, ext);
3666 xs *url = xs_fmt("%s/s/%s", snac->actor, id);
3667 int fo = xs_number_get(xs_list_get(data, 1));
3668 int fs = xs_number_get(xs_list_get(data, 2));
3669
3670 /* store */
3671 static_put(snac, id, payload + fo, fs);
3672
3673 snac->config = xs_dict_set(snac->config, key, url);
3674 }
3675 }
3676 }
3677}
3678
3679int mastoapi_patch_handler(const xs_dict *req, const char *q_path,
3680 const char *payload, int p_size,
3681 char **body, int *b_size, char **ctype)
3682/* Handle profile updates */
3683{
3684 (void)p_size;
3685 (void)b_size;
3686
3687 if (!xs_startswith(q_path, "/api/v1/"))
3688 return 0;
3689
3690 int status = HTTP_STATUS_NOT_FOUND;
3691 xs *args = NULL;
3692 const char *i_ctype = xs_dict_get(req, "content-type");
3693
3694 if (i_ctype && xs_startswith(i_ctype, "application/json")) {
3695 if (!xs_is_null(payload))
3696 args = xs_json_loads(payload);
3697 }
3698 else if (i_ctype && xs_startswith(i_ctype, "application/x-www-form-urlencoded"))
3699 {
3700 // Some apps send form data instead of json so we should cater for those
3701 if (!xs_is_null(payload)) {
3702 args = xs_url_vars(payload);
3703 }
3704 }
3705 else
3706 args = xs_dup(xs_dict_get(req, "p_vars"));
3707
3708 if (args == NULL)
3709 return HTTP_STATUS_BAD_REQUEST;
3710
3711 xs *cmd = xs_replace_n(q_path, "/api", "", 1);
3712
3713 snac snac = {0};
3714 int logged_in = process_auth_token(&snac, req);
3715
3716 if (xs_startswith(cmd, "/v1/accounts/update_credentials")) { /** **/
3717 /* Update user profile fields */
3718 if (logged_in) {
3719 int c = 0;
3720 const xs_str *k;
3721 const xs_val *v;
3722 const xs_str *field_name = NULL;
3723 xs *new_fields = xs_dict_new();
3724 while (xs_dict_next(args, &k, &v, &c)) {
3725 if (strcmp(k, "display_name") == 0) {
3726 if (v != NULL)
3727 snac.config = xs_dict_set(snac.config, "name", v);
3728 }
3729 else
3730 if (strcmp(k, "note") == 0) {
3731 if (v != NULL)
3732 snac.config = xs_dict_set(snac.config, "bio", v);
3733 }
3734 else
3735 if (strcmp(k, "bot") == 0) {
3736 if (v != NULL)
3737 snac.config = xs_dict_set(snac.config, "bot",
3738 (strcmp(v, "true") == 0 ||
3739 strcmp(v, "1") == 0) ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
3740 }
3741 else
3742 if (strcmp(k, "source[sensitive]") == 0) {
3743 if (v != NULL)
3744 snac.config = xs_dict_set(snac.config, "cw",
3745 strcmp(v, "true") == 0 ? "open" : "");
3746 }
3747 else
3748 if (strcmp(k, "source[privacy]") == 0) {
3749 if (v != NULL)
3750 snac.config = xs_dict_set(snac.config, "private",
3751 strcmp(v, "private") == 0 ? xs_stock(XSTYPE_TRUE) : xs_stock(XSTYPE_FALSE));
3752 }
3753 else
3754 if (strcmp(k, "header") == 0) {
3755 persist_image("header", v, payload, &snac);
3756 }
3757 else
3758 if (strcmp(k, "avatar") == 0) {
3759 persist_image("avatar", v, payload, &snac);
3760 }
3761 else
3762 if (xs_between("fields_attributes", k, "[name]")) {
3763 field_name = strcmp(v, "") != 0 ? v : NULL;
3764 }
3765 else
3766 if (xs_between("fields_attributes", k, "[value]")) {
3767 if (field_name != NULL) {
3768 new_fields = xs_dict_set(new_fields, field_name, v);
3769 snac.config = xs_dict_set(snac.config, "metadata", new_fields);
3770 }
3771 }
3772 else
3773 if (strcmp(k, "locked") == 0) {
3774 snac.config = xs_dict_set(snac.config, "approve_followers",
3775 xs_stock(strcmp(v, "true") == 0 ? XSTYPE_TRUE : XSTYPE_FALSE));
3776 }
3777 /* we don't have support for the following options, yet
3778 - discoverable (0/1)
3779 */
3780 }
3781
3782 /* Persist profile */
3783 if (user_persist(&snac, 1) == 0)
3784 credentials_get(body, ctype, &status, snac);
3785 else
3786 status = HTTP_STATUS_INTERNAL_SERVER_ERROR;
3787 }
3788 else
3789 status = HTTP_STATUS_UNAUTHORIZED;
3790 }
3791
3792 /* user cleanup */
3793 if (logged_in)
3794 user_free(&snac);
3795
3796 srv_debug(1, xs_fmt("mastoapi_patch_handler %s %d", q_path, status));
3797
3798 return status;
3799}
3800
3801
3802void mastoapi_purge(void)
3803{
3804 xs *spec = xs_fmt("%s/app/" "*.json", srv_basedir);
3805 xs *files = xs_glob(spec, 1, 0);
3806 xs_list *p = files;
3807 const xs_str *v;
3808
3809 time_t mt = time(NULL) - 3600;
3810
3811 while (xs_list_iter(&p, &v)) {
3812 xs *cid = xs_replace(v, ".json", "");
3813 xs *fn = _app_fn(cid);
3814
3815 if (mtime(fn) < mt) {
3816 /* get the app */
3817 xs *app = app_get(cid);
3818
3819 if (app) {
3820 /* old apps with no uid are incomplete cruft */
3821 const char *uid = xs_dict_get(app, "uid");
3822
3823 if (xs_is_null(uid) || *uid == '\0') {
3824 unlink(fn);
3825 srv_debug(2, xs_fmt("purged %s", fn));
3826 }
3827 }
3828 }
3829 }
3830}
3831
3832
3833#endif /* #ifndef NO_MASTODON_API */