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