mastoapi.c 160 KB

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