mastoapi.c 155 KB

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