1
0

mastoapi.c 154 KB

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