mastoapi.c 154 KB

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