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