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