mastoapi.c 159 KB

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