ucmd_chat.c 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855
  1. /* chat: native client for Cloudron Chat on the ngui canvas toolkit.
  2. *
  3. * Login is the native Cloudron OIDC driver in chat_login.c (username,
  4. * password, optional TOTP) or a pasted session cookie. The session cookie is
  5. * kept in a uhttp cookie jar and saved with the server address in a small
  6. * config file: /data/CHAT.CFG on an installed disk, /share/chat.cfg when
  7. * there is no persistent /data mount, or the path given as argument.
  8. * The password is never stored.
  9. *
  10. * Everything else is the Chat REST API over uhttp: the channel and DM
  11. * directory, message pages (newest first, older paging with ?before=, live
  12. * updates with ?after=), sending, read markers, joining public channels and
  13. * opening DMs. There is no WebSocket: the open conversation is polled every
  14. * ~2 s and the directory every ~12 s, and polling waits while the user types.
  15. *
  16. * Network calls block the UI; the frame showing the "Loading" status is
  17. * presented first. TLS certificates are NOT verified (tls.c phase A), which
  18. * the login screen says. */
  19. #include "ucmd_lib.h"
  20. #include "ngui.h"
  21. #include "uhttp.h"
  22. #include "ujson.h"
  23. #include "chat_login.h"
  24. #include "img.h"
  25. #include <stdlib.h>
  26. #include <stdio.h>
  27. #include <string.h>
  28. #define DEFAULT_CFG_DATA "/data/CHAT.CFG"
  29. #define DEFAULT_CFG_SHARE "/share/chat.cfg"
  30. #define RESP_CAP (512u * 1024u)
  31. #define JSON_NODES 16384u
  32. #define JSON_SCAP (RESP_CAP + 2u * JSON_NODES)
  33. #define MAX_CONV 128
  34. #define MAX_MSG 240
  35. #define MAX_PICK 256
  36. #define BODY_MAX 4096
  37. #define PAGE_SIZE 50
  38. #define LIVE_PAGE 50
  39. #define MSG_IMG_MAX 3
  40. #define CHAT_IMG_W 480
  41. #define CHAT_IMG_H 320
  42. #define PREVIEW_MAX_W 420
  43. #define PREVIEW_PAD 8
  44. #define PREVIEW_THUMB_W 120
  45. #define PREVIEW_THUMB_H 72
  46. #define PREVIEW_GAP 10
  47. #define PREVIEW_TITLE_MAX 200
  48. #define PREVIEW_DESC_MAX 360
  49. #define PREVIEW_SITE_MAX 96
  50. #define CHAT_IMG_MAX 16
  51. #define CHAT_AVATAR_MAX 64
  52. #define CHAT_AVATAR 32
  53. #define CHAT_IMG_BUDGET (6u * 1024u * 1024u)
  54. #define CHAT_IMG_ARENA_MAX (12u * 1024u * 1024u)
  55. #define CHAT_IMG_FETCH_MAX (4u * 1024u * 1024u)
  56. #define CHAT_IMG_URL_MAX (UHTTP_HOST_MAX + UHTTP_PATH_MAX + 16)
  57. #define CHAT_PIC_QUEUED 0
  58. #define CHAT_PIC_READY 1
  59. #define CHAT_PIC_FETCHING 2
  60. #define CHAT_PIC_FAILED (-1)
  61. #define POLL_CONV_MS 2000
  62. #define POLL_CONV_IDLE_MS 5000
  63. #define POLL_DIR_MS 12000
  64. #define POLL_DIR_IDLE_MS 20000
  65. #define TYPING_HOLD_MS 1000
  66. #define KEEPALIVE_IDLE_MS 30000
  67. /* widget IDs */
  68. enum {
  69. ID_SERVER = 1, ID_CFG, ID_SIGNIN, ID_COOKIE_MODE, ID_USER, ID_PASS,
  70. ID_TOTP, ID_BACK, ID_COOKIE, ID_USE_COOKIE, ID_COMPOSE, ID_SEND,
  71. ID_REFRESH, ID_SIGNOUT, ID_BROWSE, ID_NEWDM, ID_OLDER, ID_NEWMSG,
  72. ID_RETRY, ID_MODAL_CLOSE, ID_FILTER, ID_MODAL_ROW = 1000
  73. };
  74. enum screen { SCR_SERVER, SCR_CRED, SCR_TOTP, SCR_COOKIE, SCR_MAIN };
  75. enum modal { MODAL_NONE, MODAL_BROWSE, MODAL_NEWDM };
  76. /* pending actions, collected while drawing and run after the frame */
  77. enum {
  78. ACT_NONE, ACT_START_LOGIN, ACT_SUBMIT, ACT_SUBMIT_TOTP, ACT_USE_COOKIE,
  79. ACT_SEND, ACT_REFRESH, ACT_SIGNOUT, ACT_OPEN_CONV, ACT_OLDER,
  80. ACT_BROWSE, ACT_NEWDM, ACT_JOIN, ACT_OPEN_DM, ACT_RETRY,
  81. ACT_COOKIE_SCREEN, ACT_BACK, ACT_OPEN_URL
  82. };
  83. struct conv {
  84. char id[48];
  85. char name[64];
  86. char preview[96];
  87. char kind; /* 'c' public, 'p' private, 'd' DM */
  88. char presence; /* DM: 'o' online, 'a' away, 'f' offline */
  89. int unread;
  90. };
  91. struct msg {
  92. char id[48];
  93. char user_id[48];
  94. char author[48];
  95. char *author_pic; /* profile picture URL, or NULL */
  96. char created[32]; /* ISO 8601 UTC, sorts as text */
  97. char reply[96]; /* "Name: snippet" */
  98. char extra[112]; /* attachments / thread / reactions line */
  99. char *body; /* Latin-1, malloc'd */
  100. char *img_url[MSG_IMG_MAX]; /* image attachments, malloc'd URLs */
  101. char *preview_image; /* link-preview thumbnail URL, or NULL */
  102. char *preview_url; /* link target, or NULL */
  103. char preview_title[PREVIEW_TITLE_MAX];
  104. char preview_desc[PREVIEW_DESC_MAX];
  105. char preview_site[PREVIEW_SITE_MAX];
  106. unsigned char nimg;
  107. unsigned char action; /* type "me" */
  108. int height;
  109. int layout_w;
  110. int compact;
  111. int day_header;
  112. };
  113. struct pick {
  114. char id[48];
  115. char name[64];
  116. char sub[64];
  117. char pic[256];
  118. };
  119. static struct ngui ui;
  120. static struct uhttp http;
  121. static struct uhttp_jar jar;
  122. static struct chat_login login;
  123. static struct ujson json;
  124. static struct ujson_node *jnodes;
  125. static char *jsbuf;
  126. static char *resp;
  127. static unsigned int resp_len;
  128. static enum screen screen = SCR_SERVER;
  129. static enum modal modal = MODAL_NONE;
  130. static int action, action_arg;
  131. static char preview_press_id[48]; /* card held down, by message id */
  132. static char cfg_path[CHAT_PATH_MAX];
  133. static int cfg_is_default;
  134. static char server[CHAT_SERVER_MAX];
  135. static char server_host[UHTTP_HOST_MAX];
  136. static int server_secure;
  137. static char saved_cookie[CHAT_COOKIE_MAX];
  138. static unsigned int saved_jar_changes;
  139. static char me_id[48];
  140. static char me_name[64];
  141. static struct ngui_input server_in, cfg_in, user_in, pass_in, totp_in;
  142. static struct ngui_input cookie_in, compose_in, filter_in;
  143. static struct conv convs[MAX_CONV];
  144. static int nconv;
  145. static int cur = -1; /* index into convs */
  146. static char cur_id[48];
  147. static struct msg msgs[MAX_MSG];
  148. static int nmsg;
  149. static int has_older;
  150. static unsigned int msgs_gen; /* bumped whenever msgs[] changes */
  151. static int history_full;
  152. static struct ngui_scroll tl_scroll, side_scroll, modal_scroll;
  153. static int at_bottom = 1;
  154. static int new_below;
  155. static struct pick picks[MAX_PICK];
  156. static int npick;
  157. static int modal_sel; /* keyboard selection among visible rows */
  158. static unsigned int last_older_ms;
  159. static char status[160];
  160. static int status_err;
  161. static char busy[96];
  162. static int offline;
  163. static unsigned int backoff_ms;
  164. static unsigned int next_conv_poll, next_dir_poll, retry_at;
  165. static unsigned int last_input_ms;
  166. static unsigned int last_net_ms;
  167. static unsigned int client_seq;
  168. /* ---- small string helpers ---- */
  169. static void s_copy(char *d, const char *s, unsigned int cap)
  170. {
  171. unsigned int i = 0;
  172. if (!cap)
  173. return;
  174. while (s && s[i] && i + 1 < cap) {
  175. d[i] = s[i];
  176. i++;
  177. }
  178. d[i] = '\0';
  179. }
  180. static void s_cat(char *d, const char *s, unsigned int cap)
  181. {
  182. unsigned int n = (unsigned int)strlen(d);
  183. if (n < cap)
  184. s_copy(d + n, s, cap - n);
  185. }
  186. static void s_cat_uint(char *d, unsigned int v, unsigned int cap)
  187. {
  188. char tmp[12];
  189. int i = 11;
  190. tmp[i] = '\0';
  191. do {
  192. tmp[--i] = (char)('0' + v % 10);
  193. v /= 10;
  194. } while (v && i > 0);
  195. s_cat(d, tmp + i, cap);
  196. }
  197. static void set_status(const char *a, const char *b, int err)
  198. {
  199. status[0] = '\0';
  200. s_cat(status, a, sizeof(status));
  201. if (b)
  202. s_cat(status, b, sizeof(status));
  203. status_err = err;
  204. ngui_invalidate(&ui);
  205. }
  206. /* ---- UTF-8 -> Latin-1 display text ---- */
  207. static unsigned int put_ascii(char *d, unsigned int n, unsigned int cap,
  208. const char *s)
  209. {
  210. while (*s && n + 1 < cap)
  211. d[n++] = *s++;
  212. return n;
  213. }
  214. /* Map a code point outside Latin-1 to a short ASCII stand-in; NULL to skip
  215. * it entirely (joiners, variation selectors, skin tones). */
  216. static const char *cp_fallback(unsigned int cp)
  217. {
  218. switch (cp) {
  219. case 0x2018: case 0x2019: case 0x201A: case 0x2032: return "'";
  220. case 0x201C: case 0x201D: case 0x201E: case 0x2033: return "\"";
  221. case 0x2010: case 0x2011: case 0x2012: case 0x2013: return "-";
  222. case 0x2014: case 0x2015: return "--";
  223. case 0x2026: return "...";
  224. case 0x2022: case 0x2023: case 0x25CF: return "\xb7";
  225. case 0x20AC: return "EUR";
  226. case 0x2122: return "TM";
  227. case 0x2192: return "->";
  228. case 0x2190: return "<-";
  229. case 0x2264: return "<=";
  230. case 0x2265: return ">=";
  231. case 0x2260: return "!=";
  232. case 0x2764: case 0x2665: return "<3";
  233. case 0x2705: case 0x2714: case 0x2713: return "[v]";
  234. case 0x274C: case 0x2716: return "[x]";
  235. case 0x26A0: return "/!\\";
  236. case 0x1F44D: return "(y)";
  237. case 0x1F44E: return "(n)";
  238. case 0x1F44B: return "o/";
  239. case 0x1F64F: return "_/\\_";
  240. case 0x1F389: case 0x1F38A: return "*\\o/*";
  241. case 0x1F600: case 0x1F603: case 0x1F604: case 0x1F60A:
  242. case 0x1F642: case 0x263A: return ":)";
  243. case 0x1F601: case 0x1F606: case 0x1F602: case 0x1F923: return ":D";
  244. case 0x1F609: return ";)";
  245. case 0x1F61B: case 0x1F61C: case 0x1F61D: return ":P";
  246. case 0x1F622: case 0x1F62D: case 0x1F641: case 0x2639: return ":(";
  247. case 0x1F62E: case 0x1F632: return ":O";
  248. case 0x1F914: return ":-/";
  249. case 0x1F525: return "(fire)";
  250. case 0x1F680: return "(rocket)";
  251. case 0x1F440: return "(eyes)";
  252. case 0x200B: case 0x200C: case 0x200D: case 0xFEFF:
  253. return 0;
  254. }
  255. if (cp >= 0xFE00 && cp <= 0xFE0F)
  256. return 0; /* variation selectors */
  257. if (cp >= 0x1F3FB && cp <= 0x1F3FF)
  258. return 0; /* skin tones */
  259. if (cp >= 0x2000 && cp <= 0x200A)
  260. return " ";
  261. return "?";
  262. }
  263. /* Convert UTF-8 to Latin-1 display text. Tabs become spaces, other control
  264. * characters (except newline) are dropped. */
  265. static unsigned int to_latin1(char *d, unsigned int cap, const char *s)
  266. {
  267. const unsigned char *p = (const unsigned char *)s;
  268. unsigned int n = 0;
  269. if (!cap)
  270. return 0;
  271. while (*p && n + 1 < cap) {
  272. unsigned int cp, extra, i;
  273. if (*p < 0x80) {
  274. cp = *p++;
  275. } else {
  276. if ((*p & 0xE0) == 0xC0) {
  277. cp = *p & 0x1F;
  278. extra = 1;
  279. } else if ((*p & 0xF0) == 0xE0) {
  280. cp = *p & 0x0F;
  281. extra = 2;
  282. } else if ((*p & 0xF8) == 0xF0) {
  283. cp = *p & 0x07;
  284. extra = 3;
  285. } else {
  286. p++;
  287. d[n++] = '?';
  288. continue;
  289. }
  290. p++;
  291. for (i = 0; i < extra; i++) {
  292. if ((*p & 0xC0) != 0x80)
  293. break;
  294. cp = (cp << 6) | (*p++ & 0x3F);
  295. }
  296. if (i < extra) {
  297. d[n++] = '?';
  298. continue;
  299. }
  300. }
  301. if (cp == '\t' || cp == 0xA0) {
  302. d[n++] = ' ';
  303. } else if (cp == '\n') {
  304. d[n++] = '\n';
  305. } else if (cp < 0x20 || cp == 0x7F || (cp >= 0x80 && cp < 0xA0)) {
  306. continue;
  307. } else if (cp < 0x100) {
  308. d[n++] = (char)cp;
  309. } else {
  310. const char *f = cp_fallback(cp);
  311. if (f)
  312. n = put_ascii(d, n, cap, f);
  313. }
  314. }
  315. d[n] = '\0';
  316. return n;
  317. }
  318. /* One-line version (newlines become spaces), for previews/snippets. */
  319. static void to_latin1_line(char *d, unsigned int cap, const char *s)
  320. {
  321. unsigned int i;
  322. to_latin1(d, cap, s);
  323. for (i = 0; d[i]; i++)
  324. if (d[i] == '\n')
  325. d[i] = ' ';
  326. }
  327. /* ---- config file ---- */
  328. static int read_file(const char *path, char *buf, unsigned int cap)
  329. {
  330. int n = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)(cap - 1));
  331. if (n < 0)
  332. return n;
  333. buf[n] = '\0';
  334. return n;
  335. }
  336. static int write_file(const char *path, const char *buf, unsigned int len)
  337. {
  338. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, (int)len);
  339. }
  340. /* The persistent data volume wins when it is mounted and writable; the
  341. * volatile /share is the fallback (live USB, or a board without /data). */
  342. static const char *default_cfg_path(void)
  343. {
  344. struct sys_mount m;
  345. unsigned int i;
  346. for (i = 0; u_syscall2(SYS_LIST_MOUNTS, (int)i, (int)&m) == 1; i++)
  347. if (strcmp(m.name, "data") == 0 && !m.ro)
  348. return DEFAULT_CFG_DATA;
  349. return DEFAULT_CFG_SHARE;
  350. }
  351. static int set_server(const char *s)
  352. {
  353. char norm[CHAT_SERVER_MAX];
  354. if (chat_server_normalize(s, norm, sizeof(norm)) != 0)
  355. return -1;
  356. if (chat_server_host(norm, server_host, sizeof(server_host),
  357. &server_secure) != 0)
  358. return -1;
  359. s_copy(server, norm, sizeof(server));
  360. return 0;
  361. }
  362. /* Export the Chat host's cookies and write the config file. */
  363. static void save_config(void)
  364. {
  365. static char out[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 128];
  366. int n;
  367. uhttp_jar_header(&jar, server_host, "/api/me", server_secure,
  368. saved_cookie, sizeof(saved_cookie));
  369. saved_jar_changes = jar.changes;
  370. n = chat_config_format(out, sizeof(out), server, saved_cookie);
  371. if (n < 0 || write_file(cfg_path, out, (unsigned int)n) < 0)
  372. set_status("Could not save the session to ", cfg_path, 1);
  373. memset(out, 0, sizeof(out));
  374. }
  375. /* A server may roll its session cookie: save when the jar changed. */
  376. static void maybe_save_cookie(void)
  377. {
  378. char now[CHAT_COOKIE_MAX];
  379. if (jar.changes == saved_jar_changes || screen != SCR_MAIN)
  380. return;
  381. uhttp_jar_header(&jar, server_host, "/api/me", server_secure, now,
  382. sizeof(now));
  383. saved_jar_changes = jar.changes;
  384. if (strcmp(now, saved_cookie) != 0)
  385. save_config();
  386. }
  387. /* ---- HTTP / JSON plumbing ---- */
  388. static void paint_now(void);
  389. static int line_h(void);
  390. static void net_drop(void)
  391. {
  392. http.keepalive = 0;
  393. uhttp_close(&http);
  394. }
  395. /* Request server + path; JSON body or NULL. Returns the HTTP status or a
  396. * UHTTP_ERR_*; the body is in resp/resp_len. */
  397. static int api(const char *method, const char *path, const char *body)
  398. {
  399. char url[CHAT_SERVER_MAX + 256];
  400. unsigned int len = 0;
  401. int st;
  402. s_copy(url, server, sizeof(url));
  403. s_cat(url, path, sizeof(url));
  404. http.jar = &jar;
  405. http.accept = "application/json";
  406. st = chat_http(&http, method, url, body, resp, RESP_CAP, &len);
  407. resp_len = st > 0 ? len : 0;
  408. last_net_ms = u_ticks_ms();
  409. maybe_save_cookie();
  410. return st;
  411. }
  412. static int parse_resp(void)
  413. {
  414. int root = ujson_parse(&json, resp, resp_len);
  415. return root;
  416. }
  417. /* ---- message images and avatars ---- */
  418. struct chat_pic {
  419. char *url;
  420. struct img_image img;
  421. unsigned int bytes; /* RGB565 bytes in the message-image budget */
  422. unsigned int last_used;
  423. int state; /* CHAT_PIC_* */
  424. };
  425. static struct chat_pic chat_images[CHAT_IMG_MAX];
  426. static int nchat_images;
  427. static unsigned int chat_image_bytes;
  428. static struct chat_pic chat_avatars[CHAT_AVATAR_MAX];
  429. static int nchat_avatars;
  430. static unsigned int chat_pic_clock;
  431. static unsigned char *chat_fetch_buf;
  432. static unsigned char *chat_arena;
  433. static unsigned int chat_arena_size;
  434. static void chat_pic_free(struct chat_pic *p)
  435. {
  436. free(p->url);
  437. free(p->img.px);
  438. free(p->img.alpha);
  439. memset(p, 0, sizeof(*p));
  440. }
  441. static struct chat_pic *chat_pic_find(struct chat_pic *arr, int n,
  442. const char *url)
  443. {
  444. int i;
  445. for (i = 0; i < n; i++)
  446. if (arr[i].url && strcmp(arr[i].url, url) == 0)
  447. return &arr[i];
  448. return 0;
  449. }
  450. /* Pick a cache slot, evicting the least recently used entry when full.
  451. * avatars: their images never change the timeline layout. */
  452. static struct chat_pic *chat_pic_slot(struct chat_pic *arr, int *count, int max,
  453. const char *url, int avatars)
  454. {
  455. struct chat_pic *p = chat_pic_find(arr, *count, url);
  456. unsigned int best = ~0u;
  457. int i, victim = -1;
  458. if (p)
  459. return p;
  460. if (*count < max) {
  461. p = &arr[*count];
  462. memset(p, 0, sizeof(*p));
  463. p->url = strdup(url);
  464. if (!p->url)
  465. return 0;
  466. (*count)++;
  467. } else {
  468. for (i = 0; i < *count; i++) {
  469. if (arr[i].state == CHAT_PIC_QUEUED ||
  470. arr[i].state == CHAT_PIC_FETCHING)
  471. continue;
  472. if (arr[i].last_used < best) {
  473. best = arr[i].last_used;
  474. victim = i;
  475. }
  476. }
  477. if (victim < 0)
  478. return 0;
  479. p = &arr[victim];
  480. if (!avatars) {
  481. chat_image_bytes -= p->bytes;
  482. msgs_gen++;
  483. }
  484. chat_pic_free(p);
  485. p->url = strdup(url);
  486. if (!p->url)
  487. return 0;
  488. }
  489. p->state = CHAT_PIC_QUEUED;
  490. p->last_used = ++chat_pic_clock;
  491. return p;
  492. }
  493. static struct chat_pic *chat_image_slot(const char *url)
  494. {
  495. return chat_pic_slot(chat_images, &nchat_images, CHAT_IMG_MAX, url, 0);
  496. }
  497. static struct chat_pic *chat_avatar_slot(const char *url)
  498. {
  499. return chat_pic_slot(chat_avatars, &nchat_avatars, CHAT_AVATAR_MAX,
  500. url, 1);
  501. }
  502. static int chat_image_room(unsigned int need)
  503. {
  504. while (chat_image_bytes + need > CHAT_IMG_BUDGET) {
  505. unsigned int best = ~0u;
  506. int i, victim = -1;
  507. for (i = 0; i < nchat_images; i++) {
  508. if (chat_images[i].state != CHAT_PIC_READY)
  509. continue;
  510. if (chat_images[i].last_used < best) {
  511. best = chat_images[i].last_used;
  512. victim = i;
  513. }
  514. }
  515. if (victim < 0)
  516. return -1;
  517. chat_image_bytes -= chat_images[victim].bytes;
  518. chat_pic_free(&chat_images[victim]);
  519. msgs_gen++;
  520. }
  521. return 0;
  522. }
  523. static unsigned char *chat_pic_arena_get(unsigned int need)
  524. {
  525. if (need <= chat_arena_size)
  526. return chat_arena;
  527. free(chat_arena);
  528. chat_arena = (unsigned char *)malloc(need);
  529. chat_arena_size = chat_arena ? need : 0;
  530. return chat_arena;
  531. }
  532. /* Clip the scaled avatar to a circle with a 4x4 supersampled edge. The RGB
  533. * pixels stay untouched; only the alpha plane changes. */
  534. static void chat_avatar_mask(unsigned char *alpha, unsigned int w,
  535. unsigned int h)
  536. {
  537. unsigned int x, y;
  538. for (y = 0; y < h; y++) {
  539. for (x = 0; x < w; x++) {
  540. unsigned int hits = 0;
  541. int sx, sy;
  542. for (sy = 0; sy < 4; sy++) {
  543. int py = (int)y * 8 + sy * 2 + 1;
  544. int dy = py - (int)h * 4;
  545. for (sx = 0; sx < 4; sx++) {
  546. int px = (int)x * 8 + sx * 2 + 1;
  547. int dx = px - (int)w * 4;
  548. if (dx * dx + dy * dy <=
  549. (int)w * 4 * (int)w * 4)
  550. hits++;
  551. }
  552. }
  553. alpha[y * w + x] =
  554. (unsigned char)((unsigned int)alpha[y * w + x] *
  555. hits / 16u);
  556. }
  557. }
  558. }
  559. static int chat_pic_store(struct chat_pic *p, unsigned int len, int avatar)
  560. {
  561. struct img_info info;
  562. struct img_options opt = {0};
  563. struct img_mem mem;
  564. struct img_image decoded;
  565. struct img_blit blit;
  566. unsigned char *arena, *alpha = 0;
  567. unsigned short *px;
  568. unsigned int est, scale, dw, dh, sw, sh, i, need;
  569. int r;
  570. if (img_sniff(chat_fetch_buf, len, &info) != 0)
  571. return -1;
  572. est = img_estimate(&info);
  573. if (est == 0xFFFFFFFFu || est > CHAT_IMG_ARENA_MAX)
  574. return -1;
  575. arena = chat_pic_arena_get(est);
  576. if (!arena)
  577. return -1;
  578. img_mem_init(&mem, arena, est);
  579. opt.max_pixels = 4u * 1024u * 1024u;
  580. opt.max_w = avatar ? CHAT_AVATAR : CHAT_IMG_W;
  581. opt.max_h = avatar ? CHAT_AVATAR : CHAT_IMG_H;
  582. r = img_decode(chat_fetch_buf, len, &opt, &mem, &decoded);
  583. if (r != 0 || !decoded.w || !decoded.h)
  584. return -1;
  585. if (avatar) {
  586. sw = (CHAT_AVATAR << 16) / decoded.w;
  587. sh = (CHAT_AVATAR << 16) / decoded.h;
  588. scale = sw < sh ? sw : sh;
  589. dw = dh = CHAT_AVATAR;
  590. } else {
  591. scale = 65536;
  592. if (decoded.w > CHAT_IMG_W)
  593. scale = (CHAT_IMG_W << 16) / decoded.w;
  594. if (((decoded.h * scale) >> 16) > CHAT_IMG_H)
  595. scale = (CHAT_IMG_H << 16) / decoded.h;
  596. dw = (decoded.w * scale) >> 16;
  597. dh = (decoded.h * scale) >> 16;
  598. if (!dw)
  599. dw = 1;
  600. if (!dh)
  601. dh = 1;
  602. need = dw * dh * 2u;
  603. if (chat_image_room(need) != 0)
  604. return -1;
  605. }
  606. px = (unsigned short *)malloc(dw * dh * 2u);
  607. if (!px)
  608. return -1;
  609. for (i = 0; i < dw * dh; i++)
  610. px[i] = avatar ? 0xFFFF : ui.theme.bg;
  611. if (avatar) {
  612. /* Keep an alpha plane even for an opaque picture: the circular
  613. * mask below clips it to the avatar circle. */
  614. alpha = (unsigned char *)malloc(dw * dh);
  615. if (alpha)
  616. memset(alpha, 255, dw * dh);
  617. }
  618. memset(&blit, 0, sizeof(blit));
  619. blit.dst = px;
  620. blit.dst_w = (int)dw;
  621. blit.dst_h = (int)dh;
  622. blit.clip_x = 0;
  623. blit.clip_y = 0;
  624. blit.clip_w = (int)dw;
  625. blit.clip_h = (int)dh;
  626. blit.x = avatar ? (int)(dw - ((decoded.w * scale) >> 16)) / 2 : 0;
  627. blit.y = avatar ? (int)(dh - ((decoded.h * scale) >> 16)) / 2 : 0;
  628. blit.scale = scale;
  629. blit.bg = avatar ? 0xFFFF : ui.theme.bg;
  630. blit.bg2 = blit.bg;
  631. blit.dst_a = alpha;
  632. blit.flags = alpha ? IMG_BLIT_SAVE_ALPHA :
  633. (decoded.alpha ? IMG_BLIT_OVER_DST : 0);
  634. img_draw(&decoded, &blit);
  635. if (avatar && alpha)
  636. chat_avatar_mask(alpha, dw, dh);
  637. p->img.format = decoded.format;
  638. p->img.w = dw;
  639. p->img.h = dh;
  640. p->img.px = px;
  641. p->img.alpha = alpha;
  642. p->img.flags = 0;
  643. p->bytes = avatar ? 0 : dw * dh * 2u;
  644. if (!avatar)
  645. chat_image_bytes += p->bytes;
  646. return 0;
  647. }
  648. /* Install a message-image bitmap decoded by the fetch helper (the helper
  649. * already applied the 480x320 bounds). Avatars are still decoded here at
  650. * 32x32 so the circular mask sees the same square source as before. */
  651. static int chat_pic_store_px(struct chat_pic *p, unsigned char *buf,
  652. unsigned int len, unsigned int dw,
  653. unsigned int dh, int has_alpha)
  654. {
  655. unsigned int npx = dw * dh, need;
  656. unsigned short *px;
  657. unsigned char *alpha = 0;
  658. if (!buf || !dw || !dh || len < npx * 2u)
  659. return -1;
  660. need = npx * 2u;
  661. if (chat_image_room(need) != 0)
  662. return -1;
  663. px = (unsigned short *)malloc(need);
  664. if (!px)
  665. return -1;
  666. memcpy(px, buf, need);
  667. if (has_alpha && len >= need + npx) {
  668. alpha = (unsigned char *)malloc(npx);
  669. if (alpha)
  670. memcpy(alpha, buf + need, npx);
  671. }
  672. p->img.format = 0;
  673. p->img.w = dw;
  674. p->img.h = dh;
  675. p->img.px = px;
  676. p->img.alpha = alpha;
  677. p->img.flags = 0;
  678. p->bytes = need;
  679. chat_image_bytes += need;
  680. return 0;
  681. }
  682. /* ---- asynchronous media fetch ----
  683. *
  684. * chat_http() blocks the UI for the whole body, so every image and avatar
  685. * used to freeze the window for the download plus the decode. Media now
  686. * goes through the same curl __serve helper as the browser: the chat loop
  687. * submits a request file and polls a small done marker, while a private tty
  688. * absorbs the helper's DNS/TLS log lines. Only the (short) decode runs on
  689. * the chat thread. */
  690. static int chat_media_pid = -1;
  691. static int chat_media_tty = -1;
  692. static unsigned int chat_media_session;
  693. static unsigned int chat_media_seq;
  694. static unsigned int chat_media_deadline;
  695. static int chat_media_busy;
  696. static int chat_media_retried;
  697. static struct chat_pic *chat_media_pic;
  698. static int chat_media_avatar;
  699. static char chat_media_req[40], chat_media_body[40];
  700. static char chat_media_meta[40], chat_media_done[40];
  701. static char chat_media_px[40];
  702. static void chat_media_paths(void)
  703. {
  704. if (chat_media_session)
  705. return;
  706. chat_media_session = ((unsigned int)u_getpid() << 16) ^
  707. (u_ticks_ms() & 0xFFFFu);
  708. if (!chat_media_session)
  709. chat_media_session = 1;
  710. snprintf(chat_media_req, sizeof(chat_media_req), "/share/bf%u_0req",
  711. chat_media_session);
  712. snprintf(chat_media_body, sizeof(chat_media_body), "/share/bf%u_0body",
  713. chat_media_session);
  714. snprintf(chat_media_meta, sizeof(chat_media_meta), "/share/bf%u_0meta",
  715. chat_media_session);
  716. snprintf(chat_media_done, sizeof(chat_media_done), "/share/bf%u_0done",
  717. chat_media_session);
  718. snprintf(chat_media_px, sizeof(chat_media_px), "/share/bf%u_0px",
  719. chat_media_session);
  720. }
  721. static void chat_media_tty_drain(void)
  722. {
  723. char sink[256];
  724. int i;
  725. if (chat_media_tty <= 0)
  726. return;
  727. for (i = 0; i < 8; i++)
  728. if (u_tty_read(chat_media_tty, sink, sizeof(sink)) <= 0)
  729. break;
  730. }
  731. static void chat_media_jar_sync(void)
  732. {
  733. u_syscall3(SYS_WRITE_FILE, (int)"/share/bchat.jar", (int)&jar,
  734. (int)sizeof(jar));
  735. }
  736. static int chat_media_start(void)
  737. {
  738. char arg[64];
  739. int t;
  740. chat_media_paths();
  741. if (chat_media_pid > 0 && u_alive((unsigned int)chat_media_pid))
  742. return 0;
  743. chat_media_pid = -1;
  744. if (chat_media_tty == -1) {
  745. t = u_tty_create();
  746. chat_media_tty = t > 0 ? t : 0;
  747. }
  748. chat_media_jar_sync();
  749. snprintf(arg, sizeof(arg), "__serve %u 0 /share/bchat.jar",
  750. chat_media_session);
  751. chat_media_pid = u_spawn("/ramfs/bin/curl", arg, chat_media_tty, "/");
  752. if (chat_media_pid <= 0) {
  753. chat_media_pid = -1;
  754. return -1;
  755. }
  756. return 0;
  757. }
  758. static void chat_media_stop(void)
  759. {
  760. chat_media_tty_drain();
  761. if (chat_media_pid > 0)
  762. u_kill((unsigned int)chat_media_pid);
  763. chat_media_pid = -1;
  764. }
  765. static void chat_media_fail(void)
  766. {
  767. if (chat_media_pic)
  768. chat_media_pic->state = CHAT_PIC_FAILED;
  769. chat_media_pic = 0;
  770. chat_media_busy = 0;
  771. chat_media_retried = 0;
  772. u_syscall1(SYS_UNLINK, (int)chat_media_done);
  773. u_syscall1(SYS_UNLINK, (int)chat_media_meta);
  774. u_syscall1(SYS_UNLINK, (int)chat_media_body);
  775. u_syscall1(SYS_UNLINK, (int)chat_media_px);
  776. ngui_invalidate(&ui);
  777. }
  778. static int chat_media_submit(struct chat_pic *p, int avatar)
  779. {
  780. /* The helper's request file accepts a full URL; image CDN links with
  781. * query strings are routinely longer than 512 bytes. */
  782. char req[CHAT_IMG_URL_MAX + 64];
  783. int n;
  784. if (!chat_fetch_buf) {
  785. chat_fetch_buf = (unsigned char *)malloc(CHAT_IMG_FETCH_MAX);
  786. if (!chat_fetch_buf)
  787. return -1;
  788. }
  789. chat_media_paths();
  790. if (chat_media_start() != 0)
  791. return -1;
  792. chat_media_jar_sync();
  793. chat_media_seq++;
  794. if (!chat_media_seq)
  795. chat_media_seq = 1;
  796. chat_media_retried = 0;
  797. if (!avatar)
  798. n = snprintf(req, sizeof(req), "%u %u D %u %u %s\n",
  799. chat_media_seq, CHAT_IMG_FETCH_MAX,
  800. CHAT_IMG_W, CHAT_IMG_H, p->url);
  801. else
  802. n = snprintf(req, sizeof(req), "%u %u %s\n",
  803. chat_media_seq, CHAT_IMG_FETCH_MAX, p->url);
  804. if (n <= 0 || n >= (int)sizeof(req))
  805. return -1;
  806. u_syscall1(SYS_UNLINK, (int)chat_media_done);
  807. u_syscall1(SYS_UNLINK, (int)chat_media_meta);
  808. u_syscall1(SYS_UNLINK, (int)chat_media_body);
  809. u_syscall1(SYS_UNLINK, (int)chat_media_px);
  810. if (u_syscall3(SYS_WRITE_FILE, (int)chat_media_req, (int)req, n) < 0)
  811. return -1;
  812. p->state = CHAT_PIC_FETCHING;
  813. chat_media_pic = p;
  814. chat_media_avatar = avatar;
  815. chat_media_busy = 1;
  816. chat_media_deadline = u_ticks_ms() + 30000;
  817. return 0;
  818. }
  819. /* 1 when the outstanding job finished (success or failure). */
  820. static unsigned int chat_meta_uint(char **pp)
  821. {
  822. char *p = *pp;
  823. unsigned int v = 0;
  824. while (*p >= '0' && *p <= '9') {
  825. v = v * 10 + (unsigned int)(*p - '0');
  826. p++;
  827. }
  828. while (*p && *p != '\n')
  829. p++;
  830. if (*p)
  831. p++;
  832. *pp = p;
  833. return v;
  834. }
  835. static int chat_media_poll(void)
  836. {
  837. char done[24], meta[1200];
  838. int rn, st = 0, err = 0;
  839. unsigned int seq;
  840. unsigned int dw = 0, dh = 0, nw = 0, nh = 0, alpha = 0;
  841. unsigned int px_len = 0, dec_err = 0;
  842. if (!chat_media_busy)
  843. return 0;
  844. chat_media_tty_drain();
  845. rn = u_syscall3(SYS_READ_FILE, (int)chat_media_done, (int)done,
  846. (int)(sizeof(done) - 1));
  847. if (rn > 0) {
  848. char *q;
  849. done[rn] = '\0';
  850. seq = (unsigned int)atoi(done);
  851. if (seq != chat_media_seq)
  852. return 0;
  853. rn = u_syscall3(SYS_READ_FILE, (int)chat_media_meta, (int)meta,
  854. (int)(sizeof(meta) - 1));
  855. if (rn > 0) {
  856. meta[rn] = '\0';
  857. q = meta;
  858. (void)chat_meta_uint(&q); /* seq */
  859. st = (int)chat_meta_uint(&q);
  860. err = (int)chat_meta_uint(&q);
  861. (void)chat_meta_uint(&q); /* trunc */
  862. while (*q && *q != '\n') /* encoding */
  863. q++;
  864. if (*q)
  865. q++;
  866. while (*q && *q != '\n') /* content type */
  867. q++;
  868. if (*q)
  869. q++;
  870. while (*q && *q != '\n') /* final URL */
  871. q++;
  872. if (*q)
  873. q++;
  874. (void)chat_meta_uint(&q); /* body bytes */
  875. (void)chat_meta_uint(&q); /* open */
  876. (void)chat_meta_uint(&q); /* first */
  877. (void)chat_meta_uint(&q); /* total */
  878. dw = chat_meta_uint(&q);
  879. dh = chat_meta_uint(&q);
  880. nw = chat_meta_uint(&q);
  881. nh = chat_meta_uint(&q);
  882. alpha = chat_meta_uint(&q);
  883. px_len = chat_meta_uint(&q);
  884. dec_err = chat_meta_uint(&q);
  885. (void)chat_meta_uint(&q); /* dec ms */
  886. }
  887. if (st == 200 && !err && chat_media_pic) {
  888. int stored = 0;
  889. (void)nw;
  890. (void)nh;
  891. if (!chat_media_avatar && px_len && !dec_err &&
  892. dw && dh && px_len <= CHAT_IMG_FETCH_MAX) {
  893. rn = u_syscall3(SYS_READ_FILE, (int)chat_media_px,
  894. (int)chat_fetch_buf,
  895. (int)CHAT_IMG_FETCH_MAX);
  896. if (rn == (int)px_len &&
  897. chat_pic_store_px(chat_media_pic,
  898. chat_fetch_buf, px_len,
  899. dw, dh, (int)alpha) == 0)
  900. stored = 1;
  901. }
  902. if (!stored) {
  903. rn = u_syscall3(SYS_READ_FILE,
  904. (int)chat_media_body,
  905. (int)chat_fetch_buf,
  906. (int)CHAT_IMG_FETCH_MAX);
  907. if (rn > 0 &&
  908. chat_pic_store(chat_media_pic,
  909. (unsigned int)rn,
  910. chat_media_avatar) == 0)
  911. stored = 1;
  912. }
  913. if (stored) {
  914. chat_media_pic->state = CHAT_PIC_READY;
  915. chat_media_pic->last_used = ++chat_pic_clock;
  916. if (!chat_media_avatar) {
  917. msgs_gen++;
  918. if (at_bottom)
  919. tl_scroll.offset = 1 << 28;
  920. }
  921. } else {
  922. chat_media_pic->state = CHAT_PIC_FAILED;
  923. }
  924. } else if (chat_media_pic) {
  925. chat_media_pic->state = CHAT_PIC_FAILED;
  926. }
  927. chat_media_pic = 0;
  928. chat_media_busy = 0;
  929. u_syscall1(SYS_UNLINK, (int)chat_media_done);
  930. u_syscall1(SYS_UNLINK, (int)chat_media_meta);
  931. u_syscall1(SYS_UNLINK, (int)chat_media_body);
  932. u_syscall1(SYS_UNLINK, (int)chat_media_px);
  933. ngui_invalidate(&ui);
  934. return 1;
  935. }
  936. if (chat_media_pid > 0 && !u_alive((unsigned int)chat_media_pid)) {
  937. chat_media_pid = -1;
  938. if (!chat_media_retried && chat_media_start() == 0) {
  939. chat_media_retried = 1;
  940. return 0;
  941. }
  942. chat_media_fail();
  943. return 1;
  944. }
  945. if ((int)(u_ticks_ms() - chat_media_deadline) >= 0) {
  946. chat_media_stop();
  947. chat_media_fail();
  948. return 1;
  949. }
  950. return 0;
  951. }
  952. static void chat_media_tick(void)
  953. {
  954. int i;
  955. if (screen != SCR_MAIN || offline)
  956. return;
  957. if (chat_media_busy) {
  958. chat_media_poll();
  959. return;
  960. }
  961. /* Holding a helper keeps a TCP socket open, which pauses the board's
  962. * net-dev watcher; release it when the window is not being used. */
  963. if (!ui.focused) {
  964. if (chat_media_pid > 0)
  965. chat_media_stop();
  966. return;
  967. }
  968. for (i = 0; i < nchat_images; i++) {
  969. if (chat_images[i].state == CHAT_PIC_QUEUED) {
  970. if (chat_media_submit(&chat_images[i], 0) != 0)
  971. chat_images[i].state = CHAT_PIC_FAILED;
  972. ngui_invalidate(&ui);
  973. return;
  974. }
  975. }
  976. for (i = 0; i < nchat_avatars; i++) {
  977. if (chat_avatars[i].state == CHAT_PIC_QUEUED) {
  978. if (chat_media_submit(&chat_avatars[i], 1) != 0)
  979. chat_avatars[i].state = CHAT_PIC_FAILED;
  980. ngui_invalidate(&ui);
  981. return;
  982. }
  983. }
  984. }
  985. static void chat_media_clear(void)
  986. {
  987. int i;
  988. chat_media_stop();
  989. chat_media_pic = 0;
  990. chat_media_busy = 0;
  991. chat_media_retried = 0;
  992. for (i = 0; i < nchat_images; i++)
  993. chat_pic_free(&chat_images[i]);
  994. for (i = 0; i < nchat_avatars; i++)
  995. chat_pic_free(&chat_avatars[i]);
  996. nchat_images = 0;
  997. nchat_avatars = 0;
  998. chat_image_bytes = 0;
  999. free(chat_fetch_buf);
  1000. chat_fetch_buf = 0;
  1001. free(chat_arena);
  1002. chat_arena = 0;
  1003. chat_arena_size = 0;
  1004. }
  1005. /* Refresh/Retry gives failed pictures another chance. */
  1006. static void chat_media_retry(void)
  1007. {
  1008. int i;
  1009. for (i = 0; i < nchat_images; i++)
  1010. if (chat_images[i].state == CHAT_PIC_FAILED)
  1011. chat_images[i].state = CHAT_PIC_QUEUED;
  1012. for (i = 0; i < nchat_avatars; i++)
  1013. if (chat_avatars[i].state == CHAT_PIC_FAILED)
  1014. chat_avatars[i].state = CHAT_PIC_QUEUED;
  1015. ngui_invalidate(&ui);
  1016. }
  1017. /* Resolve a picture URL; Cloudron's older profile-avatar path is rewritten
  1018. * to the /api/avatars/ route the current server serves. */
  1019. static int chat_pic_url(const char *raw, char *out, unsigned int cap)
  1020. {
  1021. static const char old_prefix[] = "/api/v1/profile/avatar/";
  1022. const char *p;
  1023. char tmp[CHAT_IMG_URL_MAX];
  1024. char *q;
  1025. if (!raw || !raw[0])
  1026. return -1;
  1027. p = strstr(raw, old_prefix);
  1028. if (p) {
  1029. s_copy(tmp, "/api/avatars/", sizeof(tmp));
  1030. s_cat(tmp, p + sizeof(old_prefix) - 1, sizeof(tmp));
  1031. q = strchr(tmp, '?');
  1032. if (q)
  1033. *q = '\0';
  1034. raw = tmp;
  1035. }
  1036. return uhttp_resolve(server, raw, out, cap);
  1037. }
  1038. static int chat_image_name(const char *mime, const char *filename)
  1039. {
  1040. static const char *const ext[] = {
  1041. ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tga",
  1042. ".ppm", ".pgm", ".pbm", ".ico", ".cur", ".pam"
  1043. };
  1044. unsigned int i;
  1045. if (mime && strncmp(mime, "image/", 6) == 0)
  1046. return 1;
  1047. if (!filename)
  1048. return 0;
  1049. for (i = 0; i < sizeof(ext) / sizeof(ext[0]); i++) {
  1050. unsigned int n = (unsigned int)strlen(ext[i]);
  1051. unsigned int j;
  1052. const char *s = filename + strlen(filename);
  1053. if ((unsigned int)strlen(filename) < n)
  1054. continue;
  1055. s -= n;
  1056. for (j = 0; j < n; j++) {
  1057. char a = s[j], b = ext[i][j];
  1058. if (a >= 'A' && a <= 'Z')
  1059. a = (char)(a - 'A' + 'a');
  1060. if (a != b)
  1061. break;
  1062. }
  1063. if (j == n)
  1064. return 1;
  1065. }
  1066. return 0;
  1067. }
  1068. /* Layout/draw dimensions for one message image. *state is the cache state
  1069. * (a missing entry is treated as queued; draw queues it). */
  1070. static void chat_image_measure(const char *url, int tw, int *dw, int *dh,
  1071. unsigned int *scale, int *state)
  1072. {
  1073. struct chat_pic *p = chat_pic_find(chat_images, nchat_images, url);
  1074. unsigned int sc = 65536;
  1075. if (p && p->state == CHAT_PIC_READY) {
  1076. if ((int)p->img.w > tw)
  1077. sc = ((unsigned int)tw << 16) / p->img.w;
  1078. if (((p->img.h * sc) >> 16) > CHAT_IMG_H)
  1079. sc = (CHAT_IMG_H << 16) / p->img.h;
  1080. *dw = (int)((p->img.w * sc) >> 16);
  1081. *dh = (int)((p->img.h * sc) >> 16);
  1082. if (*dw < 1)
  1083. *dw = 1;
  1084. if (*dh < 1)
  1085. *dh = 1;
  1086. *scale = sc;
  1087. *state = CHAT_PIC_READY;
  1088. return;
  1089. }
  1090. *dw = tw < 320 ? tw : 320;
  1091. if (*dw < 40)
  1092. *dw = 40;
  1093. *dh = 120;
  1094. *scale = 65536;
  1095. *state = p ? p->state : CHAT_PIC_QUEUED;
  1096. }
  1097. static struct ngui_rect chat_clip_rect(void)
  1098. {
  1099. if (ui.nclip > 0)
  1100. return ui.clip[ui.nclip - 1];
  1101. return (struct ngui_rect){ 0, 0, ui.w, ui.h };
  1102. }
  1103. static void chat_image_draw(const char *url, int x, int y, int tw)
  1104. {
  1105. struct chat_pic *p = chat_pic_find(chat_images, nchat_images, url);
  1106. struct ngui_rect clip = chat_clip_rect();
  1107. int dw, dh, state;
  1108. unsigned int scale;
  1109. if (!p)
  1110. p = chat_image_slot(url);
  1111. chat_image_measure(url, tw, &dw, &dh, &scale, &state);
  1112. if (p && p->state == CHAT_PIC_READY) {
  1113. struct img_blit blit;
  1114. memset(&blit, 0, sizeof(blit));
  1115. blit.dst = ui.px;
  1116. blit.dst_w = ui.w;
  1117. blit.dst_h = ui.h;
  1118. blit.clip_x = clip.x;
  1119. blit.clip_y = clip.y;
  1120. blit.clip_w = clip.w;
  1121. blit.clip_h = clip.h;
  1122. blit.x = x;
  1123. blit.y = y;
  1124. blit.scale = scale;
  1125. blit.bg = ui.theme.bg;
  1126. blit.bg2 = ui.theme.bg;
  1127. blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0;
  1128. img_draw(&p->img, &blit);
  1129. ngui_frame(&ui, (struct ngui_rect){ x, y, dw, dh },
  1130. ui.theme.border);
  1131. } else {
  1132. struct ngui_rect box = { x, y, dw, dh };
  1133. ngui_fill_rect(&ui, box, ui.theme.panel_alt);
  1134. ngui_frame(&ui, box, ui.theme.border);
  1135. ngui_text_ellipsis(&ui, box, x + 8, y + (dh - line_h()) / 2,
  1136. state == CHAT_PIC_FAILED ?
  1137. "Image could not be loaded" :
  1138. "Loading image...", ui.theme.text_dim);
  1139. }
  1140. }
  1141. /* ---- link preview cards ---- */
  1142. static int preview_text_w(const char *s, unsigned int n, int px, int bold)
  1143. {
  1144. return (int)ngui_text_width_px(&ui, s, n, px, bold, 0, 0);
  1145. }
  1146. static int preview_line_h(int px)
  1147. {
  1148. int h = ngui_text_line_height(&ui, px, 0);
  1149. return h > 0 ? h : (px * 5) / 4;
  1150. }
  1151. /* Length of the next wrapped line, measured at a specific size/weight. */
  1152. static unsigned int preview_wrap(const char *s, unsigned int n, int maxw,
  1153. int px, int bold, unsigned int *adv)
  1154. {
  1155. unsigned int i = 0, end = 0, j;
  1156. if (n && s[0] == '\n') {
  1157. *adv = 1;
  1158. return 0;
  1159. }
  1160. for (;;) {
  1161. j = i;
  1162. while (j < n && s[j] == ' ')
  1163. j++;
  1164. while (j < n && s[j] != ' ' && s[j] != '\n')
  1165. j++;
  1166. if (j == i)
  1167. break;
  1168. if (preview_text_w(s, j, px, bold) > maxw) {
  1169. if (end == 0) {
  1170. unsigned int k = 1;
  1171. while (k < j &&
  1172. preview_text_w(s, k + 1, px, bold) <= maxw)
  1173. k++;
  1174. *adv = k;
  1175. return k;
  1176. }
  1177. break;
  1178. }
  1179. end = j;
  1180. i = j;
  1181. if (j >= n || s[j] == '\n')
  1182. break;
  1183. }
  1184. *adv = end;
  1185. while (*adv < n && s[*adv] == ' ')
  1186. (*adv)++;
  1187. if (*adv < n && s[*adv] == '\n')
  1188. (*adv)++;
  1189. return end;
  1190. }
  1191. static int preview_line_count(const char *s, int maxw, int px, int bold,
  1192. int max_lines)
  1193. {
  1194. unsigned int n = (unsigned int)strlen(s), pos = 0, adv;
  1195. int lines = 0;
  1196. while (pos < n && lines < max_lines) {
  1197. preview_wrap(s + pos, n - pos, maxw, px, bold, &adv);
  1198. if (!adv)
  1199. adv = 1;
  1200. pos += adv;
  1201. lines++;
  1202. }
  1203. return lines;
  1204. }
  1205. static void preview_text_ellipsis(const char *s, int x, int y, int maxw,
  1206. int px, int bold, unsigned short color)
  1207. {
  1208. unsigned int n = (unsigned int)strlen(s), i, best = 0;
  1209. int dots = preview_text_w("...", 3, px, bold);
  1210. for (i = 0; i <= n; i++) {
  1211. if (preview_text_w(s, i, px, bold) > maxw)
  1212. break;
  1213. best = i;
  1214. }
  1215. if (best == n) {
  1216. ngui_text_px(&ui, x, y, s, n, color, px, bold, 0, 0);
  1217. return;
  1218. }
  1219. while (best > 0 &&
  1220. preview_text_w(s, best, px, bold) + dots > maxw)
  1221. best--;
  1222. ngui_text_px(&ui, x, y, s, best, color, px, bold, 0, 0);
  1223. ngui_text_px(&ui, x + preview_text_w(s, best, px, bold), y, "...", 3,
  1224. color, px, bold, 0, 0);
  1225. }
  1226. static void preview_text_draw(const char *s, int x, int y, int maxw,
  1227. int max_lines, int px, int bold,
  1228. unsigned short color)
  1229. {
  1230. unsigned int n = (unsigned int)strlen(s), pos = 0, adv;
  1231. int lines = 0, lh = preview_line_h(px);
  1232. while (pos < n && lines < max_lines) {
  1233. unsigned int len = preview_wrap(s + pos, n - pos, maxw, px,
  1234. bold, &adv);
  1235. if (!adv)
  1236. adv = 1;
  1237. if (lines == max_lines - 1 && pos + adv < n)
  1238. preview_text_ellipsis(s + pos, x, y, maxw, px, bold,
  1239. color);
  1240. else
  1241. ngui_text_px(&ui, x, y, s + pos, len, color, px, bold,
  1242. 0, 0);
  1243. pos += adv;
  1244. y += lh;
  1245. lines++;
  1246. }
  1247. }
  1248. static int preview_content_height(const struct msg *m, int content_w)
  1249. {
  1250. int h = 0, n;
  1251. if (content_w < 20)
  1252. content_w = 20;
  1253. if (m->preview_site[0])
  1254. h += preview_line_h(12);
  1255. if (m->preview_title[0]) {
  1256. n = preview_line_count(m->preview_title, content_w, 13, 1, 2);
  1257. if (h)
  1258. h += 3;
  1259. h += n * preview_line_h(13);
  1260. }
  1261. if (m->preview_desc[0]) {
  1262. n = preview_line_count(m->preview_desc, content_w, 12, 0, 3);
  1263. if (h)
  1264. h += 3;
  1265. h += n * preview_line_h(12);
  1266. }
  1267. return h;
  1268. }
  1269. static int msg_has_preview(const struct msg *m)
  1270. {
  1271. return m->preview_site[0] || m->preview_title[0] ||
  1272. m->preview_desc[0] || (m->preview_image && m->preview_image[0]);
  1273. }
  1274. static int preview_thumb_visible(const struct msg *m, int card_w)
  1275. {
  1276. return m->preview_image && m->preview_image[0] &&
  1277. card_w >= 2 * PREVIEW_PAD + PREVIEW_THUMB_W + PREVIEW_GAP + 20;
  1278. }
  1279. /* Fixed card height: it depends on the text, never on whether the thumbnail
  1280. * has finished loading, so the timeline does not jump when it arrives. */
  1281. static int chat_preview_card_height(const struct msg *m, int tw)
  1282. {
  1283. int cw = tw < PREVIEW_MAX_W ? tw : PREVIEW_MAX_W;
  1284. int content_w = cw - 2 * PREVIEW_PAD;
  1285. int h;
  1286. if (content_w < 20)
  1287. content_w = 20;
  1288. if (preview_thumb_visible(m, cw))
  1289. content_w -= PREVIEW_THUMB_W + PREVIEW_GAP;
  1290. if (content_w < 20)
  1291. content_w = 20;
  1292. h = preview_content_height(m, content_w);
  1293. if (h < PREVIEW_THUMB_H)
  1294. h = PREVIEW_THUMB_H;
  1295. return h + 2 * PREVIEW_PAD;
  1296. }
  1297. static struct ngui_rect chat_preview_rect(const struct msg *m, int x, int y,
  1298. int tw)
  1299. {
  1300. int cw = tw < PREVIEW_MAX_W ? tw : PREVIEW_MAX_W;
  1301. return (struct ngui_rect){ x, y, cw, chat_preview_card_height(m, tw) };
  1302. }
  1303. static void chat_preview_draw(struct msg *m, int x, int y, int tw)
  1304. {
  1305. int cw = tw < PREVIEW_MAX_W ? tw : PREVIEW_MAX_W;
  1306. int ch = chat_preview_card_height(m, tw);
  1307. int content_x = x + PREVIEW_PAD;
  1308. int content_w = cw - 2 * PREVIEW_PAD;
  1309. int ty = y + PREVIEW_PAD;
  1310. int thumb;
  1311. struct ngui_rect card = { x, y, cw, ch };
  1312. struct chat_pic *p = 0;
  1313. if (cw < 1)
  1314. return;
  1315. ngui_fill_round_rect(&ui, card, 8, 8, 8, 8, ui.theme.panel);
  1316. ngui_frame_round(&ui, card, 8, 8, 8, 8, 1, ui.theme.border);
  1317. ngui_push_clip(&ui, card);
  1318. thumb = preview_thumb_visible(m, cw);
  1319. if (thumb) {
  1320. p = chat_image_slot(m->preview_image);
  1321. if (!p || p->state == CHAT_PIC_FAILED)
  1322. thumb = 0;
  1323. }
  1324. if (thumb) {
  1325. struct ngui_rect tr = { x + PREVIEW_PAD, y + PREVIEW_PAD,
  1326. PREVIEW_THUMB_W, PREVIEW_THUMB_H };
  1327. ngui_fill_rect(&ui, tr, ui.theme.panel_alt);
  1328. if (p && p->state == CHAT_PIC_READY) {
  1329. struct img_blit blit;
  1330. unsigned int scale, dw, dh;
  1331. scale = ((unsigned int)PREVIEW_THUMB_W << 16) /
  1332. (unsigned int)p->img.w;
  1333. if ((((unsigned int)PREVIEW_THUMB_H << 16) /
  1334. (unsigned int)p->img.h) < scale)
  1335. scale = ((unsigned int)PREVIEW_THUMB_H << 16) /
  1336. (unsigned int)p->img.h;
  1337. dw = ((unsigned int)p->img.w * scale) >> 16;
  1338. dh = ((unsigned int)p->img.h * scale) >> 16;
  1339. memset(&blit, 0, sizeof(blit));
  1340. blit.dst = ui.px;
  1341. blit.dst_w = ui.w;
  1342. blit.dst_h = ui.h;
  1343. blit.clip_x = tr.x;
  1344. blit.clip_y = tr.y;
  1345. blit.clip_w = tr.w;
  1346. blit.clip_h = tr.h;
  1347. blit.x = tr.x + (tr.w - (int)dw) / 2;
  1348. blit.y = tr.y + (tr.h - (int)dh) / 2;
  1349. blit.scale = scale;
  1350. blit.bg = ui.theme.panel_alt;
  1351. blit.bg2 = ui.theme.panel_alt;
  1352. blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0;
  1353. img_draw(&p->img, &blit);
  1354. }
  1355. content_x += PREVIEW_THUMB_W + PREVIEW_GAP;
  1356. content_w -= PREVIEW_THUMB_W + PREVIEW_GAP;
  1357. }
  1358. if (content_w < 20)
  1359. content_w = 20;
  1360. if (m->preview_site[0]) {
  1361. preview_text_draw(m->preview_site, content_x, ty, content_w, 1,
  1362. 12, 0, ui.theme.text_dim);
  1363. ty += preview_line_h(12);
  1364. }
  1365. if (m->preview_title[0]) {
  1366. if (m->preview_site[0])
  1367. ty += 3;
  1368. preview_text_draw(m->preview_title, content_x, ty, content_w, 2,
  1369. 13, 1, ui.theme.text);
  1370. ty += preview_line_count(m->preview_title, content_w, 13, 1, 2) *
  1371. preview_line_h(13);
  1372. }
  1373. if (m->preview_desc[0]) {
  1374. if (m->preview_site[0] || m->preview_title[0])
  1375. ty += 3;
  1376. preview_text_draw(m->preview_desc, content_x, ty, content_w, 3,
  1377. 12, 0, ui.theme.text_dim);
  1378. }
  1379. ngui_pop_clip(&ui);
  1380. }
  1381. static int chat_avatar_draw(const char *url, int x, int y, int size,
  1382. unsigned short fallback)
  1383. {
  1384. struct chat_pic *p;
  1385. if (!url || !url[0])
  1386. return 0;
  1387. p = chat_pic_find(chat_avatars, nchat_avatars, url);
  1388. if (!p)
  1389. p = chat_avatar_slot(url);
  1390. if (p && p->state == CHAT_PIC_READY) {
  1391. struct ngui_rect clip = chat_clip_rect();
  1392. struct img_blit blit;
  1393. memset(&blit, 0, sizeof(blit));
  1394. blit.dst = ui.px;
  1395. blit.dst_w = ui.w;
  1396. blit.dst_h = ui.h;
  1397. blit.clip_x = clip.x;
  1398. blit.clip_y = clip.y;
  1399. blit.clip_w = clip.w;
  1400. blit.clip_h = clip.h;
  1401. blit.x = x;
  1402. blit.y = y;
  1403. blit.scale = ((unsigned int)size << 16) / CHAT_AVATAR;
  1404. blit.bg = fallback;
  1405. blit.bg2 = fallback;
  1406. blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0;
  1407. img_draw(&p->img, &blit);
  1408. return 1;
  1409. }
  1410. return 0;
  1411. }
  1412. static void go_login(const char *why);
  1413. /* Common error handling for API calls in the main screen. Returns 1 when
  1414. * the status is a success. */
  1415. static int api_ok(int st, const char *what)
  1416. {
  1417. if (st >= 200 && st < 300) {
  1418. if (offline) {
  1419. offline = 0;
  1420. set_status("Connected", 0, 0);
  1421. }
  1422. backoff_ms = 0;
  1423. return 1;
  1424. }
  1425. if (st == 401) {
  1426. go_login("Session expired - please sign in again");
  1427. return 0;
  1428. }
  1429. if (st > 0) {
  1430. char code[64];
  1431. s_copy(code, what, sizeof(code));
  1432. s_cat(code, ": HTTP ", sizeof(code));
  1433. s_cat_uint(code, (unsigned int)st, sizeof(code));
  1434. set_status(code, 0, 1);
  1435. return 0;
  1436. }
  1437. offline = 1;
  1438. backoff_ms = backoff_ms == 0 ? 2000 : backoff_ms < 5000 ? 5000 :
  1439. backoff_ms < 10000 ? 10000 : 30000;
  1440. retry_at = u_ticks_ms() + backoff_ms;
  1441. set_status("Offline: ", uhttp_error_string(st), 1);
  1442. net_drop();
  1443. return 0;
  1444. }
  1445. /* ---- conversations ---- */
  1446. static int conv_find(const char *id)
  1447. {
  1448. int i;
  1449. for (i = 0; i < nconv; i++)
  1450. if (strcmp(convs[i].id, id) == 0)
  1451. return i;
  1452. return -1;
  1453. }
  1454. static void conv_from_json(struct conv *c, int o, int dm)
  1455. {
  1456. int last;
  1457. s_copy(c->id, ujson_get_str(&json, o, "id"), sizeof(c->id));
  1458. c->unread = (int)ujson_int(&json, ujson_get(&json, o, "unreadCount"), 0);
  1459. c->preview[0] = '\0';
  1460. last = ujson_get(&json, o, "lastMessage");
  1461. if (ujson_type(&json, last) == UJSON_OBJECT) {
  1462. char tmp[96];
  1463. to_latin1_line(tmp, sizeof(tmp),
  1464. ujson_get_str(&json, last, "authorName"));
  1465. s_copy(c->preview, tmp, sizeof(c->preview));
  1466. s_cat(c->preview, ": ", sizeof(c->preview));
  1467. to_latin1_line(tmp, sizeof(tmp),
  1468. ujson_get_str(&json, last, "body"));
  1469. s_cat(c->preview, tmp, sizeof(c->preview));
  1470. }
  1471. if (dm) {
  1472. int other = ujson_get(&json, o, "otherUser");
  1473. const char *pres = ujson_get_str(&json, o, "presence");
  1474. const char *nm = ujson_get_str(&json, other, "name");
  1475. if (!nm[0])
  1476. nm = ujson_get_str(&json, other, "username");
  1477. to_latin1_line(c->name, sizeof(c->name), nm[0] ? nm : "(unknown)");
  1478. c->kind = 'd';
  1479. c->presence = strcmp(pres, "online") == 0 ? 'o' :
  1480. strcmp(pres, "away") == 0 ? 'a' : 'f';
  1481. } else {
  1482. to_latin1_line(c->name, sizeof(c->name),
  1483. ujson_get_str(&json, o, "name"));
  1484. c->kind = strcmp(ujson_get_str(&json, o, "type"), "private") == 0 ?
  1485. 'p' : 'c';
  1486. c->presence = 0;
  1487. }
  1488. }
  1489. static int load_directory(void)
  1490. {
  1491. static struct conv next[MAX_CONV];
  1492. int n = 0, st, root, it, pass;
  1493. for (pass = 0; pass < 2; pass++) {
  1494. st = api(0, pass ? "/api/dms" : "/api/channels", 0);
  1495. if (!api_ok(st, pass ? "Direct messages" : "Channels"))
  1496. return -1;
  1497. root = parse_resp();
  1498. if (root < 0) {
  1499. set_status("Bad directory reply: ", json.error, 1);
  1500. return -1;
  1501. }
  1502. for (it = ujson_first(&json, root); it >= 0 && n < MAX_CONV;
  1503. it = ujson_next(&json, it)) {
  1504. if (ujson_truthy(&json, ujson_get(&json, it, "archived")))
  1505. continue;
  1506. if (pass && ujson_truthy(&json, ujson_get(&json, it,
  1507. "isSelf")))
  1508. continue;
  1509. conv_from_json(&next[n], it, pass);
  1510. if (next[n].id[0])
  1511. n++;
  1512. }
  1513. }
  1514. memcpy(convs, next, sizeof(struct conv) * (unsigned int)n);
  1515. nconv = n;
  1516. cur = cur_id[0] ? conv_find(cur_id) : -1;
  1517. if (cur >= 0 && at_bottom)
  1518. convs[cur].unread = 0; /* we are reading it */
  1519. ngui_invalidate(&ui);
  1520. return 0;
  1521. }
  1522. /* ---- messages ---- */
  1523. static void msg_free(struct msg *m)
  1524. {
  1525. int i;
  1526. free(m->body);
  1527. m->body = 0;
  1528. free(m->author_pic);
  1529. m->author_pic = 0;
  1530. free(m->preview_image);
  1531. m->preview_image = 0;
  1532. free(m->preview_url);
  1533. m->preview_url = 0;
  1534. for (i = 0; i < m->nimg; i++) {
  1535. free(m->img_url[i]);
  1536. m->img_url[i] = 0;
  1537. }
  1538. m->nimg = 0;
  1539. }
  1540. /* Resolve and remember one image URL; duplicates and overflowing messages
  1541. * are ignored. */
  1542. static int msg_add_image(struct msg *m, const char *raw)
  1543. {
  1544. char url[CHAT_IMG_URL_MAX];
  1545. int i;
  1546. if (!raw || !raw[0] || m->nimg >= MSG_IMG_MAX)
  1547. return 0;
  1548. if (uhttp_resolve(server, raw, url, sizeof(url)) != 0)
  1549. return 0;
  1550. for (i = 0; i < m->nimg; i++)
  1551. if (strcmp(m->img_url[i], url) == 0)
  1552. return 0;
  1553. m->img_url[m->nimg] = strdup(url);
  1554. if (!m->img_url[m->nimg])
  1555. return -1;
  1556. m->nimg++;
  1557. return 0;
  1558. }
  1559. /* Flatten one preview field to Latin-1 and trim its edges. */
  1560. static void preview_text(char *dst, unsigned int cap, const char *raw)
  1561. {
  1562. unsigned int i, n;
  1563. to_latin1_line(dst, cap, raw ? raw : "");
  1564. for (i = 0; dst[i] == ' '; i++)
  1565. ;
  1566. if (i) {
  1567. n = (unsigned int)strlen(dst + i);
  1568. memmove(dst, dst + i, n + 1);
  1569. }
  1570. n = (unsigned int)strlen(dst);
  1571. while (n && (dst[n - 1] == ' ' || dst[n - 1] == '\t'))
  1572. dst[--n] = '\0';
  1573. }
  1574. /* Read the message's link-preview object. The server resolves the link and
  1575. * sends the Open Graph title/description/site name plus absolute image URLs;
  1576. * the card draws them, and only the thumbnail goes through the image cache. */
  1577. static void msg_set_preview(struct msg *m, int o)
  1578. {
  1579. int p = ujson_get(&json, o, "preview");
  1580. const char *url, *image;
  1581. if (ujson_type(&json, p) != UJSON_OBJECT)
  1582. return;
  1583. url = ujson_get_str(&json, p, "url");
  1584. image = ujson_get_str(&json, p, "image");
  1585. preview_text(m->preview_title, sizeof(m->preview_title),
  1586. ujson_get_str(&json, p, "title"));
  1587. preview_text(m->preview_desc, sizeof(m->preview_desc),
  1588. ujson_get_str(&json, p, "description"));
  1589. preview_text(m->preview_site, sizeof(m->preview_site),
  1590. ujson_get_str(&json, p, "siteName"));
  1591. if (!m->preview_site[0] && url[0]) {
  1592. struct uhttp_url u;
  1593. if (uhttp_parse_url(url, &u) == 0)
  1594. s_copy(m->preview_site, u.host,
  1595. sizeof(m->preview_site));
  1596. }
  1597. if (url[0]) {
  1598. char resolved[CHAT_IMG_URL_MAX];
  1599. if (uhttp_resolve(server, url, resolved, sizeof(resolved)) ==
  1600. 0)
  1601. m->preview_url = strdup(resolved);
  1602. }
  1603. if (image[0]) {
  1604. char resolved[CHAT_IMG_URL_MAX];
  1605. if (uhttp_resolve(server, image, resolved, sizeof(resolved)) ==
  1606. 0)
  1607. m->preview_image = strdup(resolved);
  1608. }
  1609. }
  1610. static void msg_set_author_pic(struct msg *m, const char *raw)
  1611. {
  1612. char url[CHAT_IMG_URL_MAX];
  1613. if (!raw[0] || chat_pic_url(raw, url, sizeof(url)) != 0)
  1614. return;
  1615. m->author_pic = strdup(url);
  1616. }
  1617. static void clear_messages(void)
  1618. {
  1619. int i;
  1620. for (i = 0; i < nmsg; i++)
  1621. msg_free(&msgs[i]);
  1622. nmsg = 0;
  1623. msgs_gen++;
  1624. has_older = 0;
  1625. history_full = 0;
  1626. new_below = 0;
  1627. }
  1628. static int msg_find(const char *id)
  1629. {
  1630. int i;
  1631. for (i = nmsg - 1; i >= 0; i--)
  1632. if (strcmp(msgs[i].id, id) == 0)
  1633. return i;
  1634. return -1;
  1635. }
  1636. static void build_extra(struct msg *m, int o)
  1637. {
  1638. int it, n;
  1639. m->extra[0] = '\0';
  1640. for (it = ujson_first(&json, ujson_get(&json, o, "attachments"));
  1641. it >= 0; it = ujson_next(&json, it)) {
  1642. char name[64];
  1643. const char *mime = ujson_get_str(&json, it, "mime");
  1644. const char *fn = ujson_get_str(&json, it, "filename");
  1645. const char *url = ujson_get_str(&json, it, "url");
  1646. if (chat_image_name(mime, fn) && url[0])
  1647. continue; /* drawn inline by the timeline */
  1648. to_latin1_line(name, sizeof(name), fn);
  1649. if (m->extra[0])
  1650. s_cat(m->extra, ", ", sizeof(m->extra));
  1651. else
  1652. s_cat(m->extra, "[file] ", sizeof(m->extra));
  1653. s_cat(m->extra, name, sizeof(m->extra));
  1654. }
  1655. if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT &&
  1656. !ujson_get_str(&json, ujson_get(&json, o, "gif"), "url")[0]) {
  1657. if (m->extra[0])
  1658. s_cat(m->extra, " ", sizeof(m->extra));
  1659. s_cat(m->extra, "[GIF]", sizeof(m->extra));
  1660. }
  1661. if (strcmp(ujson_get_str(&json, o, "type"), "poll") == 0) {
  1662. if (m->extra[0])
  1663. s_cat(m->extra, " ", sizeof(m->extra));
  1664. s_cat(m->extra, "[poll - open in the web app]", sizeof(m->extra));
  1665. }
  1666. if (ujson_get_str(&json, o, "callUrl")[0]) {
  1667. if (m->extra[0])
  1668. s_cat(m->extra, " ", sizeof(m->extra));
  1669. s_cat(m->extra, "[call]", sizeof(m->extra));
  1670. }
  1671. n = (int)ujson_int(&json, ujson_get(&json, o, "threadCount"), 0);
  1672. if (n > 0) {
  1673. if (m->extra[0])
  1674. s_cat(m->extra, " \xb7 ", sizeof(m->extra));
  1675. s_cat_uint(m->extra, (unsigned int)n, sizeof(m->extra));
  1676. s_cat(m->extra, n == 1 ? " reply" : " replies", sizeof(m->extra));
  1677. }
  1678. n = 0;
  1679. for (it = ujson_first(&json, ujson_get(&json, o, "reactions"));
  1680. it >= 0; it = ujson_next(&json, it)) {
  1681. int c = (int)ujson_int(&json, ujson_get(&json, it, "count"), 1);
  1682. n += c > 0 ? c : 1;
  1683. }
  1684. if (n > 0) {
  1685. if (m->extra[0])
  1686. s_cat(m->extra, " \xb7 ", sizeof(m->extra));
  1687. s_cat_uint(m->extra, (unsigned int)n, sizeof(m->extra));
  1688. s_cat(m->extra, n == 1 ? " reaction" : " reactions",
  1689. sizeof(m->extra));
  1690. }
  1691. if (ujson_truthy(&json, ujson_get(&json, o, "pinned"))) {
  1692. if (m->extra[0])
  1693. s_cat(m->extra, " \xb7 ", sizeof(m->extra));
  1694. s_cat(m->extra, "pinned", sizeof(m->extra));
  1695. }
  1696. }
  1697. /* Fill m from a message object; 0 ok, -1 skip (deleted/thread reply). */
  1698. static int msg_from_json(struct msg *m, int o)
  1699. {
  1700. static char body[BODY_MAX + 8];
  1701. const char *nm;
  1702. int rt;
  1703. unsigned int len;
  1704. if (ujson_truthy(&json, ujson_get(&json, o, "deleted")))
  1705. return -1;
  1706. /* Thread replies live in the thread panel, not the timeline. */
  1707. if (ujson_get_str(&json, o, "parentId")[0])
  1708. return -1;
  1709. memset(m, 0, sizeof(*m));
  1710. s_copy(m->id, ujson_get_str(&json, o, "id"), sizeof(m->id));
  1711. if (!m->id[0])
  1712. return -1;
  1713. s_copy(m->user_id, ujson_get_str(&json, o, "userId"), sizeof(m->user_id));
  1714. nm = ujson_get_str(&json, o, "authorName");
  1715. if (!nm[0])
  1716. nm = ujson_get_str(&json, o, "authorUsername");
  1717. to_latin1_line(m->author, sizeof(m->author), nm[0] ? nm : "?");
  1718. msg_set_author_pic(m, ujson_get_str(&json, o, "authorPicture"));
  1719. s_copy(m->created, ujson_get_str(&json, o, "createdAt"),
  1720. sizeof(m->created));
  1721. m->action = strcmp(ujson_get_str(&json, o, "type"), "me") == 0;
  1722. len = to_latin1(body, BODY_MAX, ujson_get_str(&json, o, "body"));
  1723. if (len + 1 >= BODY_MAX) {
  1724. /* truncated: mark it */
  1725. body[BODY_MAX - 4] = '.';
  1726. body[BODY_MAX - 3] = '.';
  1727. body[BODY_MAX - 2] = '.';
  1728. body[BODY_MAX - 1] = '\0';
  1729. }
  1730. /* Trim trailing newlines/spaces. */
  1731. len = (unsigned int)strlen(body);
  1732. while (len && (body[len - 1] == '\n' || body[len - 1] == ' '))
  1733. body[--len] = '\0';
  1734. m->body = strdup(body);
  1735. if (!m->body) {
  1736. msg_free(m);
  1737. return -1;
  1738. }
  1739. {
  1740. int it;
  1741. const char *mime, *fn;
  1742. for (it = ujson_first(&json,
  1743. ujson_get(&json, o, "attachments"));
  1744. it >= 0; it = ujson_next(&json, it)) {
  1745. mime = ujson_get_str(&json, it, "mime");
  1746. fn = ujson_get_str(&json, it, "filename");
  1747. if (chat_image_name(mime, fn) &&
  1748. msg_add_image(m, ujson_get_str(&json, it, "url")) != 0) {
  1749. msg_free(m);
  1750. return -1;
  1751. }
  1752. }
  1753. }
  1754. if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT &&
  1755. msg_add_image(m, ujson_get_str(&json, ujson_get(&json, o, "gif"),
  1756. "url")) != 0) {
  1757. msg_free(m);
  1758. return -1;
  1759. }
  1760. msg_set_preview(m, o);
  1761. rt = ujson_get(&json, o, "replyTo");
  1762. if (ujson_type(&json, rt) == UJSON_OBJECT) {
  1763. char tmp[96];
  1764. to_latin1_line(m->reply, sizeof(m->reply),
  1765. ujson_get_str(&json, rt, "authorName"));
  1766. s_cat(m->reply, ": ", sizeof(m->reply));
  1767. if (ujson_truthy(&json, ujson_get(&json, rt, "deleted")))
  1768. s_copy(tmp, "(deleted)", sizeof(tmp));
  1769. else
  1770. to_latin1_line(tmp, sizeof(tmp),
  1771. ujson_get_str(&json, rt, "body"));
  1772. if (!tmp[0])
  1773. s_copy(tmp, "(attachment)", sizeof(tmp));
  1774. s_cat(m->reply, tmp, sizeof(m->reply));
  1775. }
  1776. build_extra(m, o);
  1777. return 0;
  1778. }
  1779. static int msg_before(const struct msg *a, const struct msg *b)
  1780. {
  1781. int c = strcmp(a->created, b->created);
  1782. return c < 0 || (c == 0 && strcmp(a->id, b->id) < 0);
  1783. }
  1784. /* Insert or update a message, keeping msgs sorted. older: we are paging
  1785. * back in history (never evict old messages for it). Returns 1 when a new
  1786. * message was added, 0 when updated/skipped. */
  1787. static int msg_merge(struct msg *m, int older)
  1788. {
  1789. int i = msg_find(m->id), pos;
  1790. msgs_gen++;
  1791. if (i >= 0) {
  1792. /* Edited body or new reactions: replace in place. */
  1793. msg_free(&msgs[i]);
  1794. msgs[i] = *m;
  1795. return 0;
  1796. }
  1797. if (nmsg >= MAX_MSG) {
  1798. if (older) {
  1799. history_full = 1;
  1800. msg_free(m);
  1801. return 0;
  1802. }
  1803. msg_free(&msgs[0]);
  1804. memmove(&msgs[0], &msgs[1], sizeof(struct msg) * (MAX_MSG - 1));
  1805. nmsg--;
  1806. has_older = 1;
  1807. history_full = 1;
  1808. }
  1809. pos = nmsg;
  1810. while (pos > 0 && msg_before(m, &msgs[pos - 1]))
  1811. pos--;
  1812. memmove(&msgs[pos + 1], &msgs[pos],
  1813. sizeof(struct msg) * (unsigned int)(nmsg - pos));
  1814. msgs[pos] = *m;
  1815. nmsg++;
  1816. return 1;
  1817. }
  1818. /* Merge every message of the parsed reply. Returns the number added. */
  1819. static int merge_reply(int root, int older, int *count)
  1820. {
  1821. int it, added = 0, n = 0;
  1822. for (it = ujson_first(&json, root); it >= 0; it = ujson_next(&json, it)) {
  1823. struct msg m;
  1824. const char *id = ujson_get_str(&json, it, "id");
  1825. n++;
  1826. if (ujson_truthy(&json, ujson_get(&json, it, "deleted"))) {
  1827. /* A deletion we already show: drop it. */
  1828. int k = msg_find(id);
  1829. if (k >= 0) {
  1830. msg_free(&msgs[k]);
  1831. memmove(&msgs[k], &msgs[k + 1],
  1832. sizeof(struct msg) *
  1833. (unsigned int)(nmsg - k - 1));
  1834. nmsg--;
  1835. msgs_gen++;
  1836. }
  1837. continue;
  1838. }
  1839. if (msg_from_json(&m, it) == 0)
  1840. added += msg_merge(&m, older);
  1841. }
  1842. if (count)
  1843. *count = n;
  1844. return added;
  1845. }
  1846. static void mark_read(void)
  1847. {
  1848. char path[96];
  1849. int st;
  1850. if (cur < 0)
  1851. return;
  1852. s_copy(path, "/api/channels/", sizeof(path));
  1853. s_cat(path, convs[cur].id, sizeof(path));
  1854. s_cat(path, "/read", sizeof(path));
  1855. st = api("POST", path, 0);
  1856. if (api_ok(st, "Mark read"))
  1857. convs[cur].unread = 0;
  1858. }
  1859. static void msgs_path(char *path, unsigned int cap, const char *query)
  1860. {
  1861. s_copy(path, "/api/channels/", cap);
  1862. s_cat(path, cur_id, cap);
  1863. s_cat(path, "/messages?", cap);
  1864. s_cat(path, query, cap);
  1865. }
  1866. static void scroll_to_end(void)
  1867. {
  1868. tl_scroll.offset = 1 << 28; /* clamped when laid out */
  1869. at_bottom = 1;
  1870. new_below = 0;
  1871. }
  1872. static void open_conv(int idx)
  1873. {
  1874. char path[160];
  1875. int st, root, n = 0;
  1876. if (idx < 0 || idx >= nconv)
  1877. return;
  1878. cur = idx;
  1879. s_copy(cur_id, convs[idx].id, sizeof(cur_id));
  1880. clear_messages();
  1881. scroll_to_end();
  1882. s_copy(busy, "Loading messages...", sizeof(busy));
  1883. paint_now();
  1884. msgs_path(path, sizeof(path), "limit=50");
  1885. st = api(0, path, 0);
  1886. busy[0] = '\0';
  1887. if (!api_ok(st, "Messages"))
  1888. return;
  1889. root = parse_resp();
  1890. if (root < 0) {
  1891. set_status("Bad message reply: ", json.error, 1);
  1892. return;
  1893. }
  1894. merge_reply(root, 1, &n);
  1895. has_older = n >= PAGE_SIZE;
  1896. scroll_to_end();
  1897. mark_read();
  1898. next_conv_poll = u_ticks_ms() + POLL_CONV_MS;
  1899. ngui_invalidate(&ui);
  1900. }
  1901. static int content_height(void);
  1902. static void load_older(void)
  1903. {
  1904. char path[200], q[96];
  1905. int st, root, n = 0, before_h, added;
  1906. if (cur < 0 || !nmsg || history_full)
  1907. return;
  1908. last_older_ms = u_ticks_ms();
  1909. s_copy(q, "limit=50&before=", sizeof(q));
  1910. s_cat(q, msgs[0].id, sizeof(q));
  1911. msgs_path(path, sizeof(path), q);
  1912. s_copy(busy, "Loading older messages...", sizeof(busy));
  1913. paint_now();
  1914. st = api(0, path, 0);
  1915. busy[0] = '\0';
  1916. if (!api_ok(st, "Older messages"))
  1917. return;
  1918. root = parse_resp();
  1919. if (root < 0)
  1920. return;
  1921. before_h = content_height();
  1922. added = merge_reply(root, 1, &n);
  1923. has_older = n >= PAGE_SIZE && !history_full;
  1924. /* Keep the view on the same message. */
  1925. if (added)
  1926. tl_scroll.offset += content_height() - before_h;
  1927. ngui_invalidate(&ui);
  1928. }
  1929. static void poll_conv(void)
  1930. {
  1931. char path[200], q[96];
  1932. int st, root, added, n = 0;
  1933. if (cur < 0)
  1934. return;
  1935. if (!nmsg) {
  1936. msgs_path(path, sizeof(path), "limit=50");
  1937. } else {
  1938. s_copy(q, "limit=50&after=", sizeof(q));
  1939. s_cat(q, msgs[nmsg - 1].id, sizeof(q));
  1940. msgs_path(path, sizeof(path), q);
  1941. }
  1942. st = api(0, path, 0);
  1943. if (st == 404 && nmsg) {
  1944. /* The anchor message was deleted: reload the page. */
  1945. open_conv(cur);
  1946. return;
  1947. }
  1948. if (!api_ok(st, "Messages"))
  1949. return;
  1950. root = parse_resp();
  1951. if (root < 0) {
  1952. set_status("Bad message reply: ", json.error, 1);
  1953. return;
  1954. }
  1955. added = merge_reply(root, 0, &n);
  1956. if (n >= LIVE_PAGE) {
  1957. /* More than a page arrived: jump to the newest page. */
  1958. open_conv(cur);
  1959. return;
  1960. }
  1961. if (added) {
  1962. if (at_bottom) {
  1963. scroll_to_end();
  1964. mark_read();
  1965. } else {
  1966. new_below += added;
  1967. }
  1968. ngui_invalidate(&ui);
  1969. }
  1970. }
  1971. static void make_client_id(char *out, unsigned int cap)
  1972. {
  1973. static const char hex[] = "0123456789abcdef";
  1974. unsigned int v = u_ticks_ms() ^ ((unsigned int)u_getpid() << 20);
  1975. unsigned int c = ++client_seq, i;
  1976. s_copy(out, "nebos-", cap);
  1977. for (i = 0; i < 8; i++) {
  1978. char ch[2] = { hex[(v >> (28 - 4 * i)) & 15], 0 };
  1979. s_cat(out, ch, cap);
  1980. }
  1981. s_cat(out, "-", cap);
  1982. s_cat_uint(out, c, cap);
  1983. }
  1984. static void send_message(void)
  1985. {
  1986. static char body[NGUI_INPUT_MAX * 6 + 160];
  1987. char path[96], cid[40];
  1988. int st, root, r;
  1989. unsigned int n = 0;
  1990. const char *t = compose_in.text;
  1991. while (*t == ' ')
  1992. t++;
  1993. if (cur < 0 || !*t)
  1994. return;
  1995. make_client_id(cid, sizeof(cid));
  1996. s_copy(body, "{\"body\":", sizeof(body));
  1997. n = (unsigned int)strlen(body);
  1998. {
  1999. /* The field holds Latin-1/ASCII: encode as UTF-8 for JSON. */
  2000. static char utf8[NGUI_INPUT_MAX * 2 + 4];
  2001. unsigned int k = 0;
  2002. const unsigned char *p = (const unsigned char *)t;
  2003. while (*p && k + 3 < sizeof(utf8)) {
  2004. if (*p < 0x80) {
  2005. utf8[k++] = (char)*p;
  2006. } else {
  2007. utf8[k++] = (char)(0xC0 | (*p >> 6));
  2008. utf8[k++] = (char)(0x80 | (*p & 0x3F));
  2009. }
  2010. p++;
  2011. }
  2012. utf8[k] = '\0';
  2013. r = ujson_escape(body + n, sizeof(body) - n, utf8);
  2014. }
  2015. if (r < 0)
  2016. return;
  2017. n += (unsigned int)r;
  2018. s_cat(body, ",\"clientId\":\"", sizeof(body));
  2019. s_cat(body, cid, sizeof(body));
  2020. s_cat(body, "\"}", sizeof(body));
  2021. s_copy(path, "/api/channels/", sizeof(path));
  2022. s_cat(path, cur_id, sizeof(path));
  2023. s_cat(path, "/messages", sizeof(path));
  2024. s_copy(busy, "Sending...", sizeof(busy));
  2025. paint_now();
  2026. st = api("POST", path, body);
  2027. busy[0] = '\0';
  2028. if (!api_ok(st, "Send")) {
  2029. if (st > 0) {
  2030. char msg[96];
  2031. root = parse_resp();
  2032. s_copy(msg, root >= 0 ?
  2033. ujson_get_str(&json, root, "error") : "", sizeof(msg));
  2034. if (msg[0])
  2035. set_status("Send failed: ", msg, 1);
  2036. }
  2037. return; /* the text stays in the composer */
  2038. }
  2039. ngui_input_set(&compose_in, "");
  2040. root = parse_resp();
  2041. if (root >= 0 && ujson_type(&json, root) == UJSON_OBJECT) {
  2042. struct msg m;
  2043. if (msg_from_json(&m, root) == 0)
  2044. msg_merge(&m, 0);
  2045. }
  2046. scroll_to_end();
  2047. mark_read();
  2048. next_conv_poll = u_ticks_ms() + POLL_CONV_MS;
  2049. ngui_set_focus(&ui, ID_COMPOSE);
  2050. }
  2051. /* ---- browse / new DM ---- */
  2052. static void load_picks(int dms)
  2053. {
  2054. int st, root, it;
  2055. npick = 0;
  2056. ngui_input_set(&filter_in, "");
  2057. s_copy(busy, dms ? "Loading people..." : "Loading channels...",
  2058. sizeof(busy));
  2059. paint_now();
  2060. st = api(0, dms ? "/api/users" : "/api/channels/public", 0);
  2061. busy[0] = '\0';
  2062. if (!api_ok(st, dms ? "Users" : "Public channels"))
  2063. return;
  2064. root = parse_resp();
  2065. if (root < 0)
  2066. return;
  2067. for (it = ujson_first(&json, root); it >= 0 && npick < MAX_PICK;
  2068. it = ujson_next(&json, it)) {
  2069. struct pick *p = &picks[npick];
  2070. const char *nm;
  2071. s_copy(p->id, ujson_get_str(&json, it, "id"), sizeof(p->id));
  2072. if (!p->id[0])
  2073. continue;
  2074. p->pic[0] = '\0';
  2075. {
  2076. char url[CHAT_IMG_URL_MAX];
  2077. if (chat_pic_url(ujson_get_str(&json, it, "picture"),
  2078. url, sizeof(url)) == 0)
  2079. s_copy(p->pic, url, sizeof(p->pic));
  2080. }
  2081. if (dms) {
  2082. if (strcmp(p->id, me_id) == 0)
  2083. continue;
  2084. nm = ujson_get_str(&json, it, "name");
  2085. if (!nm[0])
  2086. nm = ujson_get_str(&json, it, "username");
  2087. to_latin1_line(p->name, sizeof(p->name), nm);
  2088. to_latin1_line(p->sub, sizeof(p->sub),
  2089. ujson_get_str(&json, it, "username"));
  2090. } else {
  2091. to_latin1_line(p->name, sizeof(p->name),
  2092. ujson_get_str(&json, it, "name"));
  2093. to_latin1_line(p->sub, sizeof(p->sub),
  2094. ujson_get_str(&json, it, "description"));
  2095. }
  2096. npick++;
  2097. }
  2098. modal = dms ? MODAL_NEWDM : MODAL_BROWSE;
  2099. modal_scroll.offset = 0;
  2100. modal_sel = 0;
  2101. ngui_set_focus(&ui, ID_FILTER);
  2102. }
  2103. static void pick_action(int idx)
  2104. {
  2105. char path[128], body[96], id[48];
  2106. int st, root;
  2107. if (idx < 0 || idx >= npick)
  2108. return;
  2109. if (modal == MODAL_BROWSE) {
  2110. s_copy(path, "/api/channels/", sizeof(path));
  2111. s_cat(path, picks[idx].id, sizeof(path));
  2112. s_cat(path, "/join", sizeof(path));
  2113. s_copy(busy, "Joining...", sizeof(busy));
  2114. paint_now();
  2115. st = api("POST", path, 0);
  2116. busy[0] = '\0';
  2117. if (!api_ok(st, "Join"))
  2118. return;
  2119. s_copy(id, picks[idx].id, sizeof(id));
  2120. } else {
  2121. s_copy(body, "{\"userId\":", sizeof(body));
  2122. if (ujson_escape(body + strlen(body), sizeof(body) - strlen(body),
  2123. picks[idx].id) < 0)
  2124. return;
  2125. s_cat(body, "}", sizeof(body));
  2126. s_copy(busy, "Opening conversation...", sizeof(busy));
  2127. paint_now();
  2128. st = api("POST", "/api/dms", body);
  2129. busy[0] = '\0';
  2130. if (!api_ok(st, "New DM"))
  2131. return;
  2132. root = parse_resp();
  2133. s_copy(id, root >= 0 ? ujson_get_str(&json, root, "id") : "",
  2134. sizeof(id));
  2135. }
  2136. modal = MODAL_NONE;
  2137. if (load_directory() == 0 && id[0]) {
  2138. int k = conv_find(id);
  2139. if (k >= 0)
  2140. open_conv(k);
  2141. }
  2142. }
  2143. /* ---- session ---- */
  2144. static void enter_main(void)
  2145. {
  2146. int root;
  2147. screen = SCR_MAIN;
  2148. offline = 0;
  2149. backoff_ms = 0;
  2150. root = parse_resp(); /* the /api/me reply */
  2151. if (root >= 0) {
  2152. const char *nm = ujson_get_str(&json, root, "name");
  2153. s_copy(me_id, ujson_get_str(&json, root, "id"), sizeof(me_id));
  2154. to_latin1_line(me_name, sizeof(me_name),
  2155. nm[0] ? nm : ujson_get_str(&json, root, "username"));
  2156. }
  2157. set_status("Connected", 0, 0);
  2158. if (load_directory() == 0 && nconv > 0 && cur < 0) {
  2159. int i, pick = 0;
  2160. for (i = 0; i < nconv; i++) {
  2161. if (convs[i].kind != 'd' &&
  2162. strcmp(convs[i].name, "general") == 0) {
  2163. pick = i;
  2164. break;
  2165. }
  2166. }
  2167. open_conv(pick);
  2168. }
  2169. next_dir_poll = u_ticks_ms() + POLL_DIR_MS;
  2170. ngui_set_focus(&ui, ID_COMPOSE);
  2171. }
  2172. static void go_login(const char *why)
  2173. {
  2174. net_drop();
  2175. uhttp_jar_clear(&jar);
  2176. saved_jar_changes = jar.changes;
  2177. saved_cookie[0] = '\0';
  2178. chat_media_clear();
  2179. screen = SCR_SERVER;
  2180. modal = MODAL_NONE;
  2181. clear_messages();
  2182. nconv = 0;
  2183. cur = -1;
  2184. cur_id[0] = '\0';
  2185. set_status(why, 0, why != 0);
  2186. ngui_set_focus(&ui, ID_SERVER);
  2187. }
  2188. /* After the jar holds a session: validate it with /api/me. */
  2189. static int check_session(int keep_offline)
  2190. {
  2191. unsigned int len = 0;
  2192. int r;
  2193. s_copy(busy, "Checking session...", sizeof(busy));
  2194. paint_now();
  2195. r = chat_session_check(&http, &jar, server, resp, RESP_CAP, &len);
  2196. busy[0] = '\0';
  2197. resp_len = len;
  2198. if (r == 0) {
  2199. save_config();
  2200. enter_main();
  2201. return 0;
  2202. }
  2203. if (r == 1) {
  2204. go_login("The saved session is no longer valid - sign in again");
  2205. return -1;
  2206. }
  2207. if (keep_offline) {
  2208. /* Network trouble: keep the cached session and retry. */
  2209. screen = SCR_MAIN;
  2210. offline = 1;
  2211. backoff_ms = 5000;
  2212. retry_at = u_ticks_ms() + backoff_ms;
  2213. set_status("Offline: ", r < 0 && r > -100 ?
  2214. uhttp_error_string(r) : "server error", 1);
  2215. return -1;
  2216. }
  2217. set_status("Session check failed: ", r < 0 && r > -100 ?
  2218. uhttp_error_string(r) : "server error", 1);
  2219. return -1;
  2220. }
  2221. static void start_login(void)
  2222. {
  2223. int r;
  2224. if (set_server(server_in.text) != 0) {
  2225. set_status("Enter a server such as chat.example.com", 0, 1);
  2226. return;
  2227. }
  2228. if (cfg_in.text[0])
  2229. s_copy(cfg_path, cfg_in.text, sizeof(cfg_path));
  2230. uhttp_jar_clear(&jar);
  2231. s_copy(busy, "Contacting the server...", sizeof(busy));
  2232. paint_now();
  2233. r = chat_login_start(&login, &http, &jar, server, resp, RESP_CAP);
  2234. busy[0] = '\0';
  2235. net_drop();
  2236. if (r == CHAT_LOGIN_OK) {
  2237. resp_len = (unsigned int)strlen(resp);
  2238. save_config();
  2239. enter_main();
  2240. return;
  2241. }
  2242. if (r == CHAT_LOGIN_FORM) {
  2243. screen = SCR_CRED;
  2244. set_status("", 0, 0);
  2245. ngui_set_focus(&ui, user_in.len ? ID_PASS : ID_USER);
  2246. return;
  2247. }
  2248. if (r == CHAT_LOGIN_NOFORM) {
  2249. screen = SCR_COOKIE;
  2250. set_status(login.error, 0, 1);
  2251. ngui_set_focus(&ui, ID_COOKIE);
  2252. return;
  2253. }
  2254. set_status(login.error, 0, 1);
  2255. }
  2256. static void wipe_secrets(void)
  2257. {
  2258. memset(pass_in.text, 0, sizeof(pass_in.text));
  2259. pass_in.len = pass_in.cursor = pass_in.anchor = pass_in.scroll = 0;
  2260. memset(totp_in.text, 0, sizeof(totp_in.text));
  2261. totp_in.len = totp_in.cursor = totp_in.anchor = totp_in.scroll = 0;
  2262. }
  2263. static void submit_login(int with_totp)
  2264. {
  2265. int r;
  2266. if (!user_in.text[0] || !pass_in.text[0]) {
  2267. set_status("Enter the username and password", 0, 1);
  2268. return;
  2269. }
  2270. s_copy(busy, "Signing in...", sizeof(busy));
  2271. paint_now();
  2272. r = chat_login_submit(&login, &http, &jar, user_in.text, pass_in.text,
  2273. with_totp ? totp_in.text : "", resp, RESP_CAP);
  2274. busy[0] = '\0';
  2275. net_drop();
  2276. if (r == CHAT_LOGIN_TOTP) {
  2277. if (with_totp) {
  2278. set_status("The code was not accepted", 0, 1);
  2279. } else {
  2280. screen = SCR_TOTP;
  2281. set_status("", 0, 0);
  2282. }
  2283. ngui_set_focus(&ui, ID_TOTP);
  2284. return;
  2285. }
  2286. if (r == CHAT_LOGIN_OK) {
  2287. wipe_secrets();
  2288. resp_len = (unsigned int)strlen(resp);
  2289. save_config();
  2290. enter_main();
  2291. return;
  2292. }
  2293. if (r == CHAT_LOGIN_DENIED && screen == SCR_TOTP) {
  2294. /* A wrong TOTP code is also a 401. */
  2295. set_status(login.error, 0, 1);
  2296. ngui_input_set(&totp_in, "");
  2297. return;
  2298. }
  2299. if (r == CHAT_LOGIN_DENIED) {
  2300. memset(pass_in.text, 0, sizeof(pass_in.text));
  2301. ngui_input_set(&pass_in, "");
  2302. ngui_set_focus(&ui, ID_PASS);
  2303. }
  2304. if (r == CHAT_LOGIN_PASSKEY || r == CHAT_LOGIN_ERROR)
  2305. wipe_secrets();
  2306. if (r == CHAT_LOGIN_PASSKEY)
  2307. screen = SCR_COOKIE;
  2308. set_status(login.error, 0, 1);
  2309. }
  2310. static void use_cookie(void)
  2311. {
  2312. if (set_server(server_in.text) != 0) {
  2313. set_status("Enter a server such as chat.example.com", 0, 1);
  2314. return;
  2315. }
  2316. if (cfg_in.text[0])
  2317. s_copy(cfg_path, cfg_in.text, sizeof(cfg_path));
  2318. uhttp_jar_clear(&jar);
  2319. {
  2320. const char *c = cookie_in.text;
  2321. /* Accept a pasted "Cookie: ..." header too. */
  2322. if (strncmp(c, "Cookie:", 7) == 0 || strncmp(c, "cookie:", 7) == 0)
  2323. c += 7;
  2324. if (uhttp_jar_import(&jar, server_host, server_secure, c) <= 0) {
  2325. set_status("Paste the cookie as name=value", 0, 1);
  2326. return;
  2327. }
  2328. }
  2329. check_session(0);
  2330. if (screen == SCR_MAIN)
  2331. ngui_input_set(&cookie_in, "");
  2332. }
  2333. static void sign_out(void)
  2334. {
  2335. /* Best effort: end the server session too. */
  2336. if (server[0]) {
  2337. s_copy(busy, "Signing out...", sizeof(busy));
  2338. paint_now();
  2339. api(0, "/auth/logout", 0);
  2340. busy[0] = '\0';
  2341. }
  2342. go_login("Signed out");
  2343. {
  2344. static char out[CHAT_SERVER_MAX + 80];
  2345. int n = chat_config_format(out, sizeof(out), server, "");
  2346. if (n > 0)
  2347. write_file(cfg_path, out, (unsigned int)n);
  2348. }
  2349. }
  2350. static void load_config(void)
  2351. {
  2352. static char buf[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 256];
  2353. char srv[CHAT_SERVER_MAX];
  2354. int n, migrated = 0;
  2355. n = read_file(cfg_path, buf, sizeof(buf));
  2356. /* First start on a persistent volume: carry a session that an older
  2357. * build saved in /share into /data once. */
  2358. if (n <= 0 && cfg_is_default &&
  2359. strcmp(cfg_path, DEFAULT_CFG_DATA) == 0) {
  2360. n = read_file(DEFAULT_CFG_SHARE, buf, sizeof(buf));
  2361. migrated = n > 0;
  2362. }
  2363. ngui_input_set(&cfg_in, cfg_path);
  2364. if (n <= 0 || chat_config_parse(buf, (unsigned int)n, srv, sizeof(srv),
  2365. saved_cookie,
  2366. sizeof(saved_cookie)) != 0) {
  2367. ngui_input_set(&server_in, "chat.cloudron.io");
  2368. saved_cookie[0] = '\0';
  2369. memset(buf, 0, sizeof(buf));
  2370. return;
  2371. }
  2372. memset(buf, 0, sizeof(buf));
  2373. ngui_input_set(&server_in, srv);
  2374. if (set_server(srv) != 0 || !saved_cookie[0])
  2375. return;
  2376. uhttp_jar_import(&jar, server_host, server_secure, saved_cookie);
  2377. saved_jar_changes = jar.changes;
  2378. if (migrated)
  2379. save_config();
  2380. check_session(1);
  2381. }
  2382. /* ---- text layout ---- */
  2383. static int line_h(void)
  2384. {
  2385. int h = ngui_text_line_height(&ui, ui.font_px, 0);
  2386. return h > 0 ? h : 16;
  2387. }
  2388. static int text_w(const char *s, unsigned int n, int bold)
  2389. {
  2390. return (int)ngui_text_width_px(&ui, s, n, ui.font_px, bold, 0, 0);
  2391. }
  2392. /* Length of the next wrapped line of s (n bytes) for width maxw; *adv gets
  2393. * the bytes to skip to the next line. */
  2394. static unsigned int wrap_line(const char *s, unsigned int n, int maxw,
  2395. unsigned int *adv)
  2396. {
  2397. unsigned int i = 0, end = 0, j;
  2398. if (n && s[0] == '\n') {
  2399. *adv = 1;
  2400. return 0;
  2401. }
  2402. for (;;) {
  2403. j = i;
  2404. while (j < n && s[j] == ' ')
  2405. j++;
  2406. while (j < n && s[j] != ' ' && s[j] != '\n')
  2407. j++;
  2408. if (j == i)
  2409. break;
  2410. if (text_w(s, j, 0) > maxw) {
  2411. if (end == 0) {
  2412. /* One word wider than the line: split it. */
  2413. unsigned int k = 1;
  2414. while (k < j && text_w(s, k + 1, 0) <= maxw)
  2415. k++;
  2416. *adv = k;
  2417. return k;
  2418. }
  2419. break;
  2420. }
  2421. end = j;
  2422. i = j;
  2423. if (j >= n || s[j] == '\n')
  2424. break;
  2425. }
  2426. *adv = end;
  2427. while (*adv < n && s[*adv] == ' ')
  2428. (*adv)++;
  2429. if (*adv < n && s[*adv] == '\n')
  2430. (*adv)++;
  2431. return end;
  2432. }
  2433. static int count_lines(const char *s, int maxw)
  2434. {
  2435. unsigned int n = (unsigned int)strlen(s), pos = 0, adv;
  2436. int lines = 0;
  2437. if (!n)
  2438. return 0;
  2439. while (pos < n) {
  2440. wrap_line(s + pos, n - pos, maxw, &adv);
  2441. if (!adv)
  2442. adv = 1;
  2443. pos += adv;
  2444. lines++;
  2445. }
  2446. return lines;
  2447. }
  2448. #define AVATAR 32
  2449. #define TEXT_X 52
  2450. #define PAD_TOP 8
  2451. #define PAD_GROUP 2
  2452. static int same_day(const struct msg *a, const struct msg *b)
  2453. {
  2454. return strncmp(a->created, b->created, 10) == 0;
  2455. }
  2456. static int same_group(const struct msg *a, const struct msg *b)
  2457. {
  2458. unsigned int ta, tb;
  2459. if (strcmp(a->user_id, b->user_id) != 0 || !same_day(a, b) ||
  2460. b->reply[0] || b->action)
  2461. return 0;
  2462. /* HH:MM at offsets 11..15: within five minutes */
  2463. ta = (unsigned int)atoi(a->created + 11) * 60 +
  2464. (unsigned int)atoi(a->created + 14);
  2465. tb = (unsigned int)atoi(b->created + 11) * 60 +
  2466. (unsigned int)atoi(b->created + 14);
  2467. return tb >= ta && tb - ta <= 5;
  2468. }
  2469. static void layout_msg(int i, int width)
  2470. {
  2471. struct msg *m = &msgs[i];
  2472. int lh = line_h(), h, tw = width - TEXT_X - 12;
  2473. int k;
  2474. if (tw < 40)
  2475. tw = 40;
  2476. m->day_header = i == 0 || !same_day(&msgs[i - 1], m);
  2477. m->compact = i > 0 && !m->day_header && same_group(&msgs[i - 1], m);
  2478. h = m->compact ? PAD_GROUP : PAD_TOP + lh + 2;
  2479. if (m->day_header)
  2480. h += lh + 12;
  2481. if (m->reply[0])
  2482. h += lh + 2;
  2483. h += count_lines(m->body, tw) * lh;
  2484. for (k = 0; k < m->nimg; k++) {
  2485. int dw, dh, state;
  2486. unsigned int scale;
  2487. chat_image_measure(m->img_url[k], tw, &dw, &dh, &scale,
  2488. &state);
  2489. h += dh + 6;
  2490. }
  2491. if (msg_has_preview(m))
  2492. h += chat_preview_card_height(m, tw) + 6;
  2493. if (m->extra[0])
  2494. h += lh + 2;
  2495. h += 2;
  2496. if (!m->compact && h < PAD_TOP + AVATAR + 4)
  2497. h = PAD_TOP + AVATAR + 4;
  2498. m->height = h;
  2499. m->layout_w = width;
  2500. }
  2501. static int tl_width;
  2502. static unsigned int laid_gen;
  2503. static int laid_font = -1;
  2504. /* Heights depend on the width, the font and the neighbours (grouping and
  2505. * day headers), so any change re-lays out every message. */
  2506. static int content_height(void)
  2507. {
  2508. int i, h = has_older || history_full ? 36 : 8;
  2509. int all = laid_gen != msgs_gen || laid_font != line_h();
  2510. for (i = 0; i < nmsg; i++) {
  2511. if (all || msgs[i].layout_w != tl_width)
  2512. layout_msg(i, tl_width);
  2513. h += msgs[i].height;
  2514. }
  2515. laid_gen = msgs_gen;
  2516. laid_font = line_h();
  2517. return h + 8;
  2518. }
  2519. /* ---- drawing helpers ---- */
  2520. static unsigned short avatar_color(const char *id)
  2521. {
  2522. static const unsigned short pal[] = {
  2523. NGUI_RGB(0xd0, 0x5a, 0x5a), NGUI_RGB(0x5a, 0x9a, 0xd0),
  2524. NGUI_RGB(0x5a, 0xb0, 0x70), NGUI_RGB(0xc0, 0x8a, 0x3a),
  2525. NGUI_RGB(0x9a, 0x6a, 0xc8), NGUI_RGB(0x3a, 0xa8, 0xa8),
  2526. NGUI_RGB(0xc8, 0x6a, 0xa0), NGUI_RGB(0x80, 0x90, 0x40),
  2527. };
  2528. unsigned int h = 0;
  2529. while (*id)
  2530. h = h * 31 + (unsigned char)*id++;
  2531. return pal[h % (sizeof(pal) / sizeof(pal[0]))];
  2532. }
  2533. static void draw_avatar(int x, int y, int size, const char *name,
  2534. const char *id, const char *pic)
  2535. {
  2536. struct ngui_rect r = { x, y, size, size };
  2537. char ini[2];
  2538. int tw;
  2539. ngui_fill_round_rect(&ui, r, size / 2, size / 2, size / 2, size / 2,
  2540. avatar_color(id));
  2541. if (chat_avatar_draw(pic, x, y, size, avatar_color(id)))
  2542. return;
  2543. ini[0] = name[0] ? name[0] : '?';
  2544. if (ini[0] >= 'a' && ini[0] <= 'z')
  2545. ini[0] = (char)(ini[0] - 'a' + 'A');
  2546. ini[1] = '\0';
  2547. tw = text_w(ini, 1, 1);
  2548. ngui_text_px(&ui, x + (size - tw) / 2, y + (size - line_h()) / 2, ini, 1,
  2549. NGUI_RGB(0xff, 0xff, 0xff), ui.font_px, 1, 0, 0);
  2550. }
  2551. static void draw_dot(int x, int y, int d, unsigned short color, int filled)
  2552. {
  2553. struct ngui_rect r = { x, y, d, d };
  2554. if (filled)
  2555. ngui_fill_round_rect(&ui, r, d / 2, d / 2, d / 2, d / 2, color);
  2556. else
  2557. ngui_frame_round(&ui, r, d / 2, d / 2, d / 2, d / 2, 1, color);
  2558. }
  2559. static void draw_badge(int right, int y, int count)
  2560. {
  2561. char num[12] = "";
  2562. int tw, w;
  2563. struct ngui_rect r;
  2564. if (count > 99)
  2565. s_copy(num, "99+", sizeof(num));
  2566. else
  2567. s_cat_uint(num, (unsigned int)count, sizeof(num));
  2568. tw = text_w(num, (unsigned int)strlen(num), 1);
  2569. w = tw + 12;
  2570. r.x = right - w;
  2571. r.y = y;
  2572. r.w = w;
  2573. r.h = line_h() + 2;
  2574. ngui_fill_round_rect(&ui, r, r.h / 2, r.h / 2, r.h / 2, r.h / 2,
  2575. ui.theme.accent);
  2576. ngui_text_px(&ui, r.x + 6, y + 1, num, (unsigned int)strlen(num),
  2577. NGUI_RGB(0xff, 0xff, 0xff), ui.font_px, 1, 0, 0);
  2578. }
  2579. static void draw_lock(int x, int y, unsigned short c)
  2580. {
  2581. struct ngui_rect body = { x, y + 5, 9, 7 };
  2582. struct ngui_rect shackle = { x + 2, y + 1, 5, 6 };
  2583. ngui_frame_round(&ui, shackle, 2, 2, 0, 0, 1, c);
  2584. ngui_fill_rect(&ui, body, c);
  2585. }
  2586. static void label(struct ngui_rect *body, const char *text)
  2587. {
  2588. struct ngui_rect r = ngui_cut_top(body, 20);
  2589. ngui_text(&ui, r.x, r.y + 2, text, ui.theme.text_dim);
  2590. }
  2591. /* ---- login screens ---- */
  2592. static struct ngui_rect card_rect(int h)
  2593. {
  2594. struct ngui_rect r;
  2595. int w = ui.w - 40 < 460 ? ui.w - 40 : 460;
  2596. if (w < 200)
  2597. w = ui.w;
  2598. r.w = w;
  2599. r.h = h;
  2600. r.x = (ui.w - w) / 2;
  2601. r.y = (ui.h - h) / 2 > 10 ? (ui.h - h) / 2 : 10;
  2602. return r;
  2603. }
  2604. static void field(struct ngui_rect *body, const char *text, unsigned int id,
  2605. struct ngui_input *in, unsigned int next_id, int submit_act)
  2606. {
  2607. int r;
  2608. label(body, text);
  2609. r = ngui_text_input(&ui, id, ngui_cut_top(body, 30), in);
  2610. ngui_cut_top(body, 8);
  2611. if (r & NGUI_INPUT_NEXT)
  2612. ngui_set_focus(&ui, next_id);
  2613. if ((r & NGUI_INPUT_SUBMIT) && submit_act)
  2614. action = submit_act;
  2615. }
  2616. static void draw_status_line(struct ngui_rect *body)
  2617. {
  2618. struct ngui_rect r = ngui_cut_top(body, 22);
  2619. if (busy[0])
  2620. ngui_text_ellipsis(&ui, r, r.x, r.y + 2, busy, ui.theme.accent);
  2621. else if (status[0])
  2622. ngui_text_ellipsis(&ui, r, r.x, r.y + 2, status,
  2623. status_err ? ui.theme.error : ui.theme.text_dim);
  2624. }
  2625. static void notice(struct ngui_rect *body, const char *text)
  2626. {
  2627. struct ngui_rect r = ngui_cut_top(body, 18);
  2628. ngui_text_ellipsis(&ui, r, r.x, r.y, text, ui.theme.text_dim);
  2629. }
  2630. static void draw_login(void)
  2631. {
  2632. struct ngui_rect all = { 0, 0, ui.w, ui.h };
  2633. struct ngui_rect card, body, r, b;
  2634. int h = screen == SCR_SERVER ? 380 : screen == SCR_COOKIE ? 400 :
  2635. screen == SCR_TOTP ? 250 : 300;
  2636. ngui_fill_rect(&ui, all, ui.theme.bg);
  2637. card = card_rect(h);
  2638. ngui_fill_rect(&ui, card, ui.theme.panel);
  2639. ngui_frame(&ui, card, ui.theme.border);
  2640. body = card;
  2641. ngui_inset(&body, 18);
  2642. r = ngui_cut_top(&body, 30);
  2643. ngui_text_px(&ui, r.x, r.y, "NebOS Chat", 10, ui.theme.text, 22, 1, 0, 0);
  2644. if (screen == SCR_SERVER) {
  2645. field(&body, "Server", ID_SERVER, &server_in, ID_CFG,
  2646. ACT_START_LOGIN);
  2647. field(&body, "Config file (session cookie, RAM-only on /share)",
  2648. ID_CFG, &cfg_in, ID_SERVER, ACT_START_LOGIN);
  2649. r = ngui_cut_top(&body, 32);
  2650. b = ngui_cut_left(&r, 110);
  2651. if (ngui_button(&ui, ID_SIGNIN, b, "Sign in"))
  2652. action = ACT_START_LOGIN;
  2653. ngui_cut_left(&r, 10);
  2654. b = ngui_cut_left(&r, 170);
  2655. if (ngui_button(&ui, ID_COOKIE_MODE, b, "Paste a cookie..."))
  2656. action = ACT_COOKIE_SCREEN;
  2657. ngui_cut_top(&body, 8);
  2658. draw_status_line(&body);
  2659. notice(&body, "TLS certificates are not verified: only sign in");
  2660. notice(&body, "on a trusted network. Passkeys and external SSO");
  2661. notice(&body, "are not supported (use the cookie option).");
  2662. } else if (screen == SCR_CRED || screen == SCR_TOTP) {
  2663. r = ngui_cut_top(&body, 22);
  2664. {
  2665. char t[160];
  2666. s_copy(t, "Sign in to ", sizeof(t));
  2667. s_cat(t, login.app_name[0] ? login.app_name : "Chat",
  2668. sizeof(t));
  2669. s_cat(t, " at ", sizeof(t));
  2670. s_cat(t, server_host, sizeof(t));
  2671. ngui_text_ellipsis(&ui, r, r.x, r.y, t, ui.theme.text_dim);
  2672. }
  2673. if (screen == SCR_CRED) {
  2674. field(&body, "Username or email", ID_USER, &user_in,
  2675. ID_PASS, ACT_SUBMIT);
  2676. field(&body, "Password", ID_PASS, &pass_in, ID_USER,
  2677. ACT_SUBMIT);
  2678. } else {
  2679. field(&body, "Two-factor code (authenticator app)",
  2680. ID_TOTP, &totp_in, ID_TOTP, ACT_SUBMIT_TOTP);
  2681. }
  2682. r = ngui_cut_top(&body, 32);
  2683. b = ngui_cut_left(&r, 110);
  2684. if (ngui_button(&ui, ID_SIGNIN, b, "Sign in"))
  2685. action = screen == SCR_TOTP ? ACT_SUBMIT_TOTP : ACT_SUBMIT;
  2686. ngui_cut_left(&r, 10);
  2687. b = ngui_cut_left(&r, 90);
  2688. if (ngui_button(&ui, ID_BACK, b, "Back"))
  2689. action = ACT_BACK;
  2690. ngui_cut_top(&body, 8);
  2691. draw_status_line(&body);
  2692. notice(&body, "The password is sent over unverified TLS and");
  2693. notice(&body, "is never stored.");
  2694. } else {
  2695. field(&body, "Server", ID_SERVER, &server_in, ID_COOKIE,
  2696. ACT_USE_COOKIE);
  2697. field(&body, "Session cookie (e.g. connect.sid=s%3A...)",
  2698. ID_COOKIE, &cookie_in, ID_CFG, ACT_USE_COOKIE);
  2699. field(&body, "Config file", ID_CFG, &cfg_in, ID_SERVER,
  2700. ACT_USE_COOKIE);
  2701. r = ngui_cut_top(&body, 32);
  2702. b = ngui_cut_left(&r, 130);
  2703. if (ngui_button(&ui, ID_USE_COOKIE, b, "Use cookie"))
  2704. action = ACT_USE_COOKIE;
  2705. ngui_cut_left(&r, 10);
  2706. b = ngui_cut_left(&r, 90);
  2707. if (ngui_button(&ui, ID_BACK, b, "Back"))
  2708. action = ACT_BACK;
  2709. ngui_cut_top(&body, 8);
  2710. draw_status_line(&body);
  2711. notice(&body, "Copy the connect.sid cookie from a signed-in web");
  2712. notice(&body, "browser. It is a bearer credential: it is saved");
  2713. notice(&body, "in the config file until you sign out.");
  2714. }
  2715. }
  2716. /* ---- main screen ---- */
  2717. #define SIDE_ROW 38
  2718. #define SIDE_HEAD 26
  2719. static void draw_sidebar(struct ngui_rect r)
  2720. {
  2721. struct ngui_rect list, btns, b;
  2722. int y, i, section, row_w;
  2723. int lh = line_h();
  2724. ngui_fill_rect(&ui, r, ui.theme.panel);
  2725. btns = ngui_cut_bottom(&r, 40);
  2726. ngui_inset(&btns, 6);
  2727. b = ngui_cut_left(&btns, (btns.w - 6) / 2);
  2728. if (ngui_button(&ui, ID_BROWSE, b, "Browse"))
  2729. action = ACT_BROWSE;
  2730. ngui_cut_left(&btns, 6);
  2731. if (ngui_button(&ui, ID_NEWDM, btns, "New DM"))
  2732. action = ACT_NEWDM;
  2733. list = r;
  2734. side_scroll.content_h = 2 * SIDE_HEAD + nconv * SIDE_ROW + 8;
  2735. ngui_scroll_begin(&ui, list, &side_scroll);
  2736. ngui_scroll_wheel(&ui, list, &side_scroll);
  2737. row_w = list.w;
  2738. y = list.y - side_scroll.offset;
  2739. for (section = 0; section < 2; section++) {
  2740. ngui_text_px(&ui, list.x + 10, y + 6,
  2741. section ? "DIRECT MESSAGES" : "CHANNELS",
  2742. section ? 15 : 8, ui.theme.text_dim, 12, 1, 0, 0);
  2743. y += SIDE_HEAD;
  2744. for (i = 0; i < nconv; i++) {
  2745. struct conv *c = &convs[i];
  2746. struct ngui_rect row = { list.x, y, row_w, SIDE_ROW - 2 };
  2747. int hot, nx, right;
  2748. if ((c->kind == 'd') != section)
  2749. continue;
  2750. hot = ui.inside && ngui_rect_contains(&row, ui.mouse_x,
  2751. ui.mouse_y) &&
  2752. ngui_rect_contains(&list, ui.mouse_x, ui.mouse_y);
  2753. if (i == cur)
  2754. ngui_fill_rect(&ui, row, ui.theme.selection);
  2755. else if (hot)
  2756. ngui_fill_rect(&ui, row, ui.theme.panel_alt);
  2757. if (ui.pressed && modal == MODAL_NONE &&
  2758. ngui_rect_contains(&row, ui.press_x, ui.press_y) &&
  2759. ngui_rect_contains(&list, ui.press_x, ui.press_y)) {
  2760. action = ACT_OPEN_CONV;
  2761. action_arg = i;
  2762. }
  2763. nx = list.x + 26;
  2764. if (c->kind == 'd') {
  2765. unsigned short pc = c->presence == 'o' ?
  2766. NGUI_RGB(0x40, 0xc0, 0x60) :
  2767. c->presence == 'a' ?
  2768. NGUI_RGB(0xe0, 0xb0, 0x30) :
  2769. ui.theme.text_dim;
  2770. draw_dot(list.x + 10, y + 6 + (lh - 9) / 2, 9, pc,
  2771. c->presence != 'f');
  2772. } else if (c->kind == 'p') {
  2773. draw_lock(list.x + 9, y + 4, ui.theme.text_dim);
  2774. } else {
  2775. ngui_text(&ui, list.x + 10, y + 4, "#",
  2776. ui.theme.text_dim);
  2777. }
  2778. right = list.x + row_w - 8;
  2779. if (c->unread > 0) {
  2780. draw_badge(right, y + 3, c->unread);
  2781. right -= 40;
  2782. }
  2783. {
  2784. struct ngui_rect nr = { nx, y, right - nx, lh + 6 };
  2785. ngui_push_clip(&ui, nr);
  2786. ngui_text_px(&ui, nx, y + 4, c->name,
  2787. (unsigned int)strlen(c->name),
  2788. ui.theme.text, ui.font_px,
  2789. c->unread > 0, 0, 0);
  2790. ngui_pop_clip(&ui);
  2791. }
  2792. if (c->preview[0]) {
  2793. struct ngui_rect pr = { nx, y + 4 + lh,
  2794. list.x + row_w - 8 - nx,
  2795. lh };
  2796. ngui_push_clip(&ui, pr);
  2797. ngui_text_px(&ui, nx, y + 4 + lh, c->preview,
  2798. (unsigned int)strlen(c->preview),
  2799. ui.theme.text_dim, 12, 0, 0, 0);
  2800. ngui_pop_clip(&ui);
  2801. }
  2802. y += SIDE_ROW;
  2803. }
  2804. }
  2805. if (!nconv)
  2806. ngui_text(&ui, list.x + 10, list.y + SIDE_HEAD + 6,
  2807. "(none yet)", ui.theme.text_dim);
  2808. ngui_scroll_end(&ui, list, &side_scroll);
  2809. }
  2810. static void draw_message(struct msg *m, int x, int y, int width)
  2811. {
  2812. int lh = line_h(), tx = x + TEXT_X, tw = width - TEXT_X - 12;
  2813. unsigned int n, pos = 0, adv;
  2814. if (tw < 40)
  2815. tw = 40;
  2816. if (m->day_header) {
  2817. char d[16];
  2818. int dw;
  2819. struct ngui_rect line = { x + 12, y + 6 + lh / 2, width - 24, 1 };
  2820. s_copy(d, m->created, 11);
  2821. dw = text_w(d, (unsigned int)strlen(d), 0);
  2822. ngui_fill_rect(&ui, line, ui.theme.border);
  2823. ngui_fill_rect(&ui, (struct ngui_rect){ x + (width - dw) / 2 - 8,
  2824. y + 4, dw + 16, lh + 4 }, ui.theme.bg);
  2825. ngui_text(&ui, x + (width - dw) / 2, y + 6, d, ui.theme.text_dim);
  2826. y += lh + 12;
  2827. }
  2828. if (!m->compact) {
  2829. char tm[8];
  2830. int aw;
  2831. y += PAD_TOP;
  2832. draw_avatar(x + 10, y, AVATAR, m->author, m->user_id,
  2833. m->author_pic);
  2834. ngui_text_px(&ui, tx, y, m->author, (unsigned int)strlen(m->author),
  2835. ui.theme.text, ui.font_px, 1, 0, 0);
  2836. aw = text_w(m->author, (unsigned int)strlen(m->author), 1);
  2837. s_copy(tm, m->created + 11, 6);
  2838. ngui_text_px(&ui, tx + aw + 10, y, tm, (unsigned int)strlen(tm),
  2839. ui.theme.text_dim, 12, 0, 0, 0);
  2840. y += lh + 2;
  2841. } else {
  2842. y += PAD_GROUP;
  2843. }
  2844. if (m->reply[0]) {
  2845. struct ngui_rect rr = { tx, y, tw, lh };
  2846. ngui_fill_rect(&ui, (struct ngui_rect){ tx, y + 1, 3, lh - 2 },
  2847. ui.theme.accent);
  2848. ngui_text_ellipsis(&ui, rr, tx + 8, y, m->reply,
  2849. ui.theme.text_dim);
  2850. y += lh + 2;
  2851. }
  2852. n = (unsigned int)strlen(m->body);
  2853. while (pos < n) {
  2854. unsigned int len = wrap_line(m->body + pos, n - pos, tw, &adv);
  2855. if (!adv)
  2856. adv = 1;
  2857. ngui_text_px(&ui, tx, y, m->body + pos, len,
  2858. m->action ? ui.theme.accent : ui.theme.text,
  2859. ui.font_px, 0, m->action, 0);
  2860. pos += adv;
  2861. y += lh;
  2862. }
  2863. {
  2864. int k;
  2865. for (k = 0; k < m->nimg; k++) {
  2866. int dw, dh, state;
  2867. unsigned int scale;
  2868. chat_image_measure(m->img_url[k], tw, &dw, &dh,
  2869. &scale, &state);
  2870. chat_image_draw(m->img_url[k], tx, y, tw);
  2871. y += dh + 6;
  2872. }
  2873. }
  2874. if (msg_has_preview(m)) {
  2875. struct ngui_rect pr = chat_preview_rect(m, tx, y, tw);
  2876. struct ngui_rect clip = chat_clip_rect();
  2877. int press_over = ngui_rect_contains(&clip, ui.press_x,
  2878. ui.press_y) &&
  2879. ngui_rect_contains(&pr, ui.press_x,
  2880. ui.press_y);
  2881. int release_over = ngui_rect_contains(&clip, ui.release_x,
  2882. ui.release_y) &&
  2883. ngui_rect_contains(&pr, ui.release_x,
  2884. ui.release_y);
  2885. int mi = (int)(m - msgs);
  2886. chat_preview_draw(m, tx, y, tw);
  2887. if (m->preview_url &&
  2888. ngui_rect_contains(&clip, ui.mouse_x, ui.mouse_y) &&
  2889. ngui_rect_contains(&pr, ui.mouse_x, ui.mouse_y))
  2890. ngui_set_cursor(&ui, CURSOR_POINTER);
  2891. if (m->preview_url && (ui.pressed & 1) && press_over)
  2892. s_copy(preview_press_id, m->id,
  2893. sizeof(preview_press_id));
  2894. if (m->preview_url && (ui.released & 1) && release_over &&
  2895. strcmp(preview_press_id, m->id) == 0) {
  2896. action = ACT_OPEN_URL;
  2897. action_arg = mi;
  2898. preview_press_id[0] = '\0';
  2899. }
  2900. y += pr.h + 6;
  2901. }
  2902. if (m->extra[0]) {
  2903. struct ngui_rect er = { tx, y + 2, tw, lh };
  2904. ngui_text_ellipsis(&ui, er, tx, y + 2, m->extra,
  2905. ui.theme.text_dim);
  2906. }
  2907. }
  2908. static void draw_timeline(struct ngui_rect r)
  2909. {
  2910. int i, y, total, scrolls, width;
  2911. int was_bottom;
  2912. ngui_fill_rect(&ui, r, ui.theme.bg);
  2913. if (cur < 0) {
  2914. ngui_text(&ui, r.x + 20, r.y + 20,
  2915. nconv ? "Select a conversation" :
  2916. "No conversations yet: browse the public channels",
  2917. ui.theme.text_dim);
  2918. return;
  2919. }
  2920. tl_width = r.w;
  2921. total = content_height();
  2922. tl_scroll.content_h = total;
  2923. ngui_scroll_begin(&ui, r, &tl_scroll);
  2924. if (ngui_scroll_wheel(&ui, r, &tl_scroll))
  2925. last_input_ms = u_ticks_ms();
  2926. scrolls = total > r.h;
  2927. width = r.w;
  2928. /* Scrolling to the very top pages in older history by itself (the
  2929. * button stays for the pointer). Rate-limited so a failing request
  2930. * cannot spin. */
  2931. if (has_older && !history_full && scrolls && tl_scroll.offset <= 0 &&
  2932. !offline && (unsigned int)(u_ticks_ms() - last_older_ms) > 1500)
  2933. action = ACT_OLDER;
  2934. was_bottom = tl_scroll.offset >= total - r.h - 4;
  2935. at_bottom = was_bottom || !scrolls;
  2936. if (at_bottom)
  2937. new_below = 0;
  2938. y = r.y - tl_scroll.offset;
  2939. if (has_older || history_full) {
  2940. struct ngui_rect b = { r.x + (width - 200) / 2, y + 4, 200, 28 };
  2941. if (history_full) {
  2942. ngui_text(&ui, b.x + 4, b.y + 6,
  2943. "History limit reached", ui.theme.text_dim);
  2944. } else if (b.y + b.h > r.y &&
  2945. (!ui.pressed ||
  2946. ngui_rect_contains(&r, ui.press_x, ui.press_y))) {
  2947. if (ngui_button(&ui, ID_OLDER, b, "Load older messages"))
  2948. action = ACT_OLDER;
  2949. }
  2950. y += 36;
  2951. } else {
  2952. y += 8;
  2953. }
  2954. for (i = 0; i < nmsg; i++) {
  2955. struct msg *m = &msgs[i];
  2956. if (y + m->height > r.y && y < r.y + r.h)
  2957. draw_message(m, r.x, y, width);
  2958. y += m->height;
  2959. }
  2960. if (ui.released)
  2961. preview_press_id[0] = '\0';
  2962. if (!nmsg)
  2963. ngui_text(&ui, r.x + 20, r.y + 50,
  2964. "No messages yet - say hello!", ui.theme.text_dim);
  2965. ngui_scroll_end(&ui, r, &tl_scroll);
  2966. if (new_below > 0 && !at_bottom) {
  2967. char t[40] = "";
  2968. struct ngui_rect b;
  2969. s_cat_uint(t, (unsigned int)new_below, sizeof(t));
  2970. s_cat(t, new_below == 1 ? " new message" : " new messages",
  2971. sizeof(t));
  2972. b.w = text_w(t, (unsigned int)strlen(t), 0) + 30;
  2973. b.h = 26;
  2974. b.x = r.x + (width - b.w) / 2;
  2975. b.y = r.y + r.h - b.h - 8;
  2976. if (ngui_button(&ui, ID_NEWMSG, b, t))
  2977. scroll_to_end();
  2978. }
  2979. }
  2980. static int total_unread(void)
  2981. {
  2982. int i, n = 0;
  2983. for (i = 0; i < nconv; i++)
  2984. n += convs[i].unread > 0 ? convs[i].unread : 0;
  2985. return n;
  2986. }
  2987. static void draw_modal(void)
  2988. {
  2989. struct ngui_rect all = { 0, 0, ui.w, ui.h };
  2990. struct ngui_rect card, body, r, list;
  2991. int w = ui.w * 7 / 10, h = ui.h * 8 / 10, i, y, shown = 0, vis;
  2992. int lh = line_h();
  2993. (void)all;
  2994. if (w < 320)
  2995. w = ui.w - 20;
  2996. if (h < 240)
  2997. h = ui.h - 20;
  2998. card.w = w;
  2999. card.h = h;
  3000. card.x = (ui.w - w) / 2;
  3001. card.y = (ui.h - h) / 2;
  3002. ngui_fill_rect(&ui, card, ui.theme.panel);
  3003. ngui_frame(&ui, card, ui.theme.accent);
  3004. body = card;
  3005. ngui_inset(&body, 14);
  3006. r = ngui_cut_top(&body, 28);
  3007. ngui_text_px(&ui, r.x, r.y, modal == MODAL_BROWSE ?
  3008. "Browse public channels" : "New direct message",
  3009. modal == MODAL_BROWSE ? 22 : 18, ui.theme.text, 18, 1, 0, 0);
  3010. if (ngui_button(&ui, ID_MODAL_CLOSE,
  3011. (struct ngui_rect){ r.x + r.w - 80, r.y, 80, 26 },
  3012. "Close"))
  3013. modal = MODAL_NONE;
  3014. ngui_cut_top(&body, 6);
  3015. filter_in.placeholder = "Filter... (Up/Down, Enter)";
  3016. for (i = 0; i < npick; i++)
  3017. if (!filter_in.text[0] || strstr(picks[i].name, filter_in.text) ||
  3018. strstr(picks[i].sub, filter_in.text))
  3019. shown++;
  3020. {
  3021. int k = ngui_key_peek(&ui), fr;
  3022. if (k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) {
  3023. ngui_key(&ui);
  3024. modal_sel += k == NGUI_KEY_UP ? -1 : 1;
  3025. }
  3026. fr = ngui_text_input(&ui, ID_FILTER, ngui_cut_top(&body, 30),
  3027. &filter_in);
  3028. if (fr & NGUI_INPUT_CHANGED) {
  3029. modal_scroll.offset = 0;
  3030. modal_sel = 0;
  3031. }
  3032. if (modal_sel >= shown)
  3033. modal_sel = shown - 1;
  3034. if (modal_sel < 0)
  3035. modal_sel = 0;
  3036. if ((fr & NGUI_INPUT_SUBMIT) && shown) {
  3037. int vis = 0;
  3038. for (i = 0; i < npick; i++) {
  3039. if (filter_in.text[0] &&
  3040. !strstr(picks[i].name, filter_in.text) &&
  3041. !strstr(picks[i].sub, filter_in.text))
  3042. continue;
  3043. if (vis++ == modal_sel) {
  3044. action = modal == MODAL_BROWSE ?
  3045. ACT_JOIN : ACT_OPEN_DM;
  3046. action_arg = i;
  3047. break;
  3048. }
  3049. }
  3050. ngui_set_focus(&ui, ID_FILTER);
  3051. }
  3052. if ((fr & NGUI_INPUT_CANCEL) && !(fr & NGUI_INPUT_NEXT))
  3053. modal = MODAL_NONE;
  3054. }
  3055. ngui_cut_top(&body, 8);
  3056. list = body;
  3057. ngui_fill_rect(&ui, list, ui.theme.bg);
  3058. modal_scroll.content_h = shown * 44;
  3059. ngui_scroll_begin(&ui, list, &modal_scroll);
  3060. ngui_scroll_wheel(&ui, list, &modal_scroll);
  3061. y = list.y - modal_scroll.offset;
  3062. vis = 0;
  3063. for (i = 0; i < npick; i++) {
  3064. struct pick *p = &picks[i];
  3065. struct ngui_rect row, b;
  3066. if (filter_in.text[0] && !strstr(p->name, filter_in.text) &&
  3067. !strstr(p->sub, filter_in.text))
  3068. continue;
  3069. if (vis++ == modal_sel) {
  3070. if (y < list.y)
  3071. modal_scroll.offset -= list.y - y;
  3072. else if (y + 44 > list.y + list.h)
  3073. modal_scroll.offset += y + 44 - list.y - list.h;
  3074. y = list.y + (vis - 1) * 44 - modal_scroll.offset;
  3075. ngui_fill_rect(&ui, (struct ngui_rect){ list.x, y,
  3076. list.w - 16, 43 },
  3077. ui.theme.selection);
  3078. }
  3079. row.x = list.x;
  3080. row.y = y;
  3081. row.w = list.w - 16;
  3082. row.h = 42;
  3083. if (y + 44 > list.y && y < list.y + list.h) {
  3084. ngui_fill_rect(&ui, (struct ngui_rect){ row.x, y + 43,
  3085. row.w, 1 }, ui.theme.border);
  3086. if (modal == MODAL_NEWDM)
  3087. draw_avatar(row.x + 8, y + 6, 30, p->name, p->id,
  3088. p->pic);
  3089. ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48, y,
  3090. row.w - 160, lh + 4 },
  3091. row.x + 48, y + 4,
  3092. p->name,
  3093. ui.theme.text);
  3094. ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48,
  3095. y + 4 + lh, row.w - 160, lh },
  3096. row.x + 48, y + 4 + lh, p->sub,
  3097. ui.theme.text_dim);
  3098. if (modal == MODAL_BROWSE)
  3099. ngui_text(&ui, row.x + 14, y + 12, "#",
  3100. ui.theme.text_dim);
  3101. b.x = row.x + row.w - 100;
  3102. b.y = y + 8;
  3103. b.w = 92;
  3104. b.h = 26;
  3105. if ((!ui.pressed ||
  3106. ngui_rect_contains(&list, ui.press_x, ui.press_y)) &&
  3107. ngui_button(&ui, ID_MODAL_ROW + (unsigned int)i, b,
  3108. modal == MODAL_BROWSE ? "Join" : "Message")) {
  3109. action = modal == MODAL_BROWSE ? ACT_JOIN :
  3110. ACT_OPEN_DM;
  3111. action_arg = i;
  3112. }
  3113. }
  3114. y += 44;
  3115. }
  3116. if (!shown)
  3117. ngui_text(&ui, list.x + 12, list.y + 12,
  3118. npick ? "Nothing matches the filter" :
  3119. modal == MODAL_BROWSE ?
  3120. "You are in every public channel" : "Nobody else here",
  3121. ui.theme.text_dim);
  3122. ngui_scroll_end(&ui, list, &modal_scroll);
  3123. }
  3124. /* Keyboard shortcuts, handled before the composer swallows the keys:
  3125. * PgUp/PgDn scroll the timeline; Ctrl+B browse, Ctrl+N new DM, Ctrl+R
  3126. * refresh. With the composer unfocused (Esc): Up/Down switch conversations,
  3127. * Home/End jump in the timeline, and typing refocuses the composer. */
  3128. static void main_keys(void)
  3129. {
  3130. for (;;) {
  3131. int k = ngui_key_peek(&ui);
  3132. if (!k)
  3133. return;
  3134. if (k == NGUI_KEY_PAGE_UP || k == NGUI_KEY_PAGE_DOWN) {
  3135. ngui_scroll_keys(&ui, &tl_scroll);
  3136. continue;
  3137. }
  3138. if (k == 0x02 || k == 0x0E || k == 0x12) {
  3139. ngui_key(&ui);
  3140. action = k == 0x02 ? ACT_BROWSE : k == 0x0E ? ACT_NEWDM :
  3141. ACT_REFRESH;
  3142. return;
  3143. }
  3144. if (ui.focus)
  3145. return;
  3146. if (k == NGUI_KEY_HOME) {
  3147. ngui_key(&ui);
  3148. tl_scroll.offset = 0;
  3149. } else if (k == NGUI_KEY_END) {
  3150. ngui_key(&ui);
  3151. scroll_to_end();
  3152. } else if (k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) {
  3153. int order[MAX_CONV], n = 0, i, pos = -1, sec;
  3154. ngui_key(&ui);
  3155. /* Sidebar order: channels first, then DMs. */
  3156. for (sec = 0; sec < 2; sec++)
  3157. for (i = 0; i < nconv; i++)
  3158. if ((convs[i].kind == 'd') == sec) {
  3159. if (i == cur)
  3160. pos = n;
  3161. order[n++] = i;
  3162. }
  3163. if (!n)
  3164. continue;
  3165. pos = pos < 0 ? 0 : k == NGUI_KEY_UP ?
  3166. (pos > 0 ? pos - 1 : 0) :
  3167. (pos + 1 < n ? pos + 1 : n - 1);
  3168. if (order[pos] != cur) {
  3169. action = ACT_OPEN_CONV;
  3170. action_arg = order[pos];
  3171. return;
  3172. }
  3173. } else if (k >= 0x20 && k <= 0x7E && cur >= 0) {
  3174. ngui_set_focus(&ui, ID_COMPOSE);
  3175. return;
  3176. } else {
  3177. return;
  3178. }
  3179. }
  3180. }
  3181. static void draw_main(void)
  3182. {
  3183. struct ngui_rect all = { 0, 0, ui.w, ui.h };
  3184. struct ngui_rect top, side, bottom, comp, stat, b, tl;
  3185. int side_w = ui.w / 4;
  3186. char t[200];
  3187. unsigned int saved_pressed = ui.pressed;
  3188. /* Nothing under an open modal reacts to the pointer. */
  3189. if (modal != MODAL_NONE)
  3190. ui.pressed = 0;
  3191. if (side_w < 150)
  3192. side_w = 150;
  3193. if (side_w > 260)
  3194. side_w = 260;
  3195. ngui_fill_rect(&ui, all, ui.theme.bg);
  3196. /* top bar */
  3197. top = ngui_cut_top(&all, 38);
  3198. ngui_fill_rect(&ui, top, ui.theme.panel_alt);
  3199. ngui_fill_rect(&ui, (struct ngui_rect){ top.x, top.y + top.h - 1, top.w,
  3200. 1 }, ui.theme.border);
  3201. {
  3202. struct ngui_rect tb = top;
  3203. ngui_inset(&tb, 6);
  3204. b = ngui_cut_right(&tb, 86);
  3205. if (ngui_button(&ui, ID_SIGNOUT, b, "Sign out"))
  3206. action = ACT_SIGNOUT;
  3207. ngui_cut_right(&tb, 6);
  3208. b = ngui_cut_right(&tb, 80);
  3209. if (ngui_button(&ui, ID_REFRESH, b, "Refresh"))
  3210. action = ACT_REFRESH;
  3211. t[0] = '\0';
  3212. if (cur >= 0) {
  3213. s_cat(t, convs[cur].kind == 'd' ? "@ " : "# ", sizeof(t));
  3214. s_cat(t, convs[cur].name, sizeof(t));
  3215. } else {
  3216. s_cat(t, "Chat", sizeof(t));
  3217. }
  3218. ngui_cut_right(&tb, 10);
  3219. ngui_push_clip(&ui, tb);
  3220. ngui_text_px(&ui, tb.x + 4, tb.y + (tb.h - 20) / 2, t,
  3221. (unsigned int)strlen(t), ui.theme.text, 18, 1, 0, 0);
  3222. ngui_pop_clip(&ui);
  3223. }
  3224. if (modal == MODAL_NONE) {
  3225. /* A closed modal leaves its filter focused: hand the keyboard
  3226. * back to the composer. */
  3227. if (ui.focus == ID_FILTER)
  3228. ngui_set_focus(&ui, cur >= 0 ? ID_COMPOSE : 0);
  3229. main_keys();
  3230. }
  3231. /* bottom: composer + status bar */
  3232. bottom = ngui_cut_bottom(&all, 70);
  3233. ngui_fill_rect(&ui, bottom, ui.theme.panel);
  3234. ngui_fill_rect(&ui, (struct ngui_rect){ bottom.x, bottom.y, bottom.w, 1 },
  3235. ui.theme.border);
  3236. stat = ngui_cut_bottom(&bottom, 24);
  3237. comp = bottom;
  3238. ngui_inset(&comp, 7);
  3239. b = ngui_cut_right(&comp, 80);
  3240. compose_in.disabled = cur < 0;
  3241. compose_in.placeholder = cur < 0 ? "" : "Type a message...";
  3242. if (ngui_text_input(&ui, ID_COMPOSE,
  3243. (struct ngui_rect){ comp.x, comp.y, comp.w - 8,
  3244. comp.h }, &compose_in) &
  3245. NGUI_INPUT_SUBMIT)
  3246. action = ACT_SEND;
  3247. if (ngui_button(&ui, ID_SEND, b, "Send") && cur >= 0)
  3248. action = ACT_SEND;
  3249. ngui_fill_rect(&ui, stat, ui.theme.panel_alt);
  3250. {
  3251. struct ngui_rect sr = stat;
  3252. int un = total_unread();
  3253. ngui_inset(&sr, 3);
  3254. if (offline) {
  3255. b = ngui_cut_right(&sr, 70);
  3256. if (ngui_button(&ui, ID_RETRY, b, "Retry"))
  3257. action = ACT_RETRY;
  3258. }
  3259. t[0] = '\0';
  3260. if (busy[0]) {
  3261. s_cat(t, busy, sizeof(t));
  3262. } else {
  3263. s_cat(t, status[0] ? status : "Connected", sizeof(t));
  3264. if (offline && retry_at) {
  3265. int left = (int)(retry_at - u_ticks_ms());
  3266. if (left > 0) {
  3267. s_cat(t, " (retry in ", sizeof(t));
  3268. s_cat_uint(t, (unsigned int)(left + 999) / 1000,
  3269. sizeof(t));
  3270. s_cat(t, " s)", sizeof(t));
  3271. }
  3272. }
  3273. }
  3274. s_cat(t, " \xb7 ", sizeof(t));
  3275. s_cat(t, server_secure ? "TLS unverified" : "no TLS", sizeof(t));
  3276. if (me_name[0]) {
  3277. s_cat(t, " \xb7 ", sizeof(t));
  3278. s_cat(t, me_name, sizeof(t));
  3279. }
  3280. if (un) {
  3281. s_cat(t, " \xb7 ", sizeof(t));
  3282. s_cat_uint(t, (unsigned int)un, sizeof(t));
  3283. s_cat(t, " unread", sizeof(t));
  3284. }
  3285. ngui_text_ellipsis(&ui, sr, sr.x + 4, sr.y + 1, t,
  3286. busy[0] ? ui.theme.accent :
  3287. (offline || status_err) ? ui.theme.error :
  3288. ui.theme.text_dim);
  3289. }
  3290. side = ngui_cut_left(&all, side_w);
  3291. ngui_fill_rect(&ui, (struct ngui_rect){ side.x + side.w - 1, side.y, 1,
  3292. side.h }, ui.theme.border);
  3293. side.w -= 1;
  3294. tl = all;
  3295. if (modal == MODAL_NONE) {
  3296. draw_sidebar(side);
  3297. draw_timeline(tl);
  3298. } else {
  3299. draw_sidebar(side);
  3300. draw_timeline(tl);
  3301. action = ACT_NONE;
  3302. ui.pressed = saved_pressed;
  3303. draw_modal();
  3304. }
  3305. }
  3306. /* ---- frame / main loop ---- */
  3307. static void draw(void)
  3308. {
  3309. if (screen == SCR_MAIN)
  3310. draw_main();
  3311. else
  3312. draw_login();
  3313. }
  3314. /* Present a frame now (status text before a blocking network call). */
  3315. static void paint_now(void)
  3316. {
  3317. int saved_action = action, saved_arg = action_arg;
  3318. ngui_invalidate(&ui);
  3319. if (ngui_begin(&ui)) {
  3320. draw();
  3321. ngui_end(&ui);
  3322. }
  3323. action = saved_action;
  3324. action_arg = saved_arg;
  3325. }
  3326. static void run_action(void)
  3327. {
  3328. int a = action, arg = action_arg;
  3329. action = ACT_NONE;
  3330. switch (a) {
  3331. case ACT_START_LOGIN:
  3332. start_login();
  3333. break;
  3334. case ACT_SUBMIT:
  3335. submit_login(0);
  3336. break;
  3337. case ACT_SUBMIT_TOTP:
  3338. submit_login(1);
  3339. break;
  3340. case ACT_USE_COOKIE:
  3341. use_cookie();
  3342. break;
  3343. case ACT_COOKIE_SCREEN:
  3344. screen = SCR_COOKIE;
  3345. set_status("", 0, 0);
  3346. ngui_set_focus(&ui, ID_COOKIE);
  3347. break;
  3348. case ACT_BACK:
  3349. wipe_secrets();
  3350. screen = SCR_SERVER;
  3351. set_status("", 0, 0);
  3352. ngui_set_focus(&ui, ID_SERVER);
  3353. break;
  3354. case ACT_SEND:
  3355. send_message();
  3356. break;
  3357. case ACT_REFRESH:
  3358. case ACT_RETRY:
  3359. backoff_ms = 0;
  3360. retry_at = 0;
  3361. chat_media_retry();
  3362. s_copy(busy, "Refreshing...", sizeof(busy));
  3363. paint_now();
  3364. busy[0] = '\0';
  3365. if (offline && !me_id[0]) {
  3366. check_session(1);
  3367. break;
  3368. }
  3369. if (load_directory() == 0) {
  3370. if (cur >= 0)
  3371. open_conv(cur);
  3372. else if (nconv)
  3373. open_conv(0);
  3374. }
  3375. next_dir_poll = u_ticks_ms() + POLL_DIR_MS;
  3376. break;
  3377. case ACT_SIGNOUT:
  3378. sign_out();
  3379. break;
  3380. case ACT_OPEN_CONV:
  3381. if (arg != cur)
  3382. open_conv(arg);
  3383. break;
  3384. case ACT_OPEN_URL:
  3385. if (arg >= 0 && arg < nmsg && msgs[arg].preview_url)
  3386. u_spawn("/ramfs/bin/browser", msgs[arg].preview_url,
  3387. 0, "/");
  3388. break;
  3389. case ACT_OLDER:
  3390. load_older();
  3391. break;
  3392. case ACT_BROWSE:
  3393. load_picks(0);
  3394. break;
  3395. case ACT_NEWDM:
  3396. load_picks(1);
  3397. break;
  3398. case ACT_JOIN:
  3399. case ACT_OPEN_DM:
  3400. pick_action(arg);
  3401. break;
  3402. }
  3403. ngui_invalidate(&ui);
  3404. }
  3405. static void poll_tick(void)
  3406. {
  3407. unsigned int now = u_ticks_ms();
  3408. int focused = ui.focused;
  3409. if (screen != SCR_MAIN || modal != MODAL_NONE)
  3410. return;
  3411. if (offline) {
  3412. if (retry_at && (int)(now - retry_at) >= 0) {
  3413. retry_at = 0;
  3414. action = ACT_RETRY;
  3415. run_action();
  3416. }
  3417. return;
  3418. }
  3419. /* Do not interrupt typing or scrolling. */
  3420. if ((unsigned int)(now - last_input_ms) < TYPING_HOLD_MS)
  3421. return;
  3422. if ((int)(now - next_dir_poll) >= 0) {
  3423. load_directory();
  3424. next_dir_poll = now + (focused ? POLL_DIR_MS : POLL_DIR_IDLE_MS);
  3425. next_conv_poll = now; /* follow with the conversation */
  3426. }
  3427. if (cur >= 0 && !offline && (int)(now - next_conv_poll) >= 0) {
  3428. poll_conv();
  3429. next_conv_poll = u_ticks_ms() +
  3430. (focused ? POLL_CONV_MS : POLL_CONV_IDLE_MS);
  3431. }
  3432. /* An open TCP socket pauses the board's net-dev watcher: only keep
  3433. * the connection while the user is actively chatting. */
  3434. if (http.connected &&
  3435. (!focused || (unsigned int)(u_ticks_ms() - last_input_ms) >
  3436. KEEPALIVE_IDLE_MS) &&
  3437. (unsigned int)(u_ticks_ms() - last_net_ms) > 200)
  3438. net_drop();
  3439. }
  3440. void _start(const char *arg)
  3441. {
  3442. struct win_info wi;
  3443. unsigned int w = 980, h = 660;
  3444. resp = (char *)malloc(RESP_CAP);
  3445. jnodes = (struct ujson_node *)malloc(sizeof(struct ujson_node) *
  3446. JSON_NODES);
  3447. jsbuf = (char *)malloc(JSON_SCAP);
  3448. if (!resp || !jnodes || !jsbuf) {
  3449. u_puts("chat: out of memory\n");
  3450. u_exit(1);
  3451. }
  3452. ujson_init(&json, jnodes, JSON_NODES, jsbuf, JSON_SCAP);
  3453. uhttp_init(&http);
  3454. http.user_agent = "NebOS-Chat/1.0 (uhttp)";
  3455. uhttp_jar_init(&jar);
  3456. if (u_win_create(w, h, "Chat", &wi) != 0 &&
  3457. u_win_create(w = 780, h = 540, "Chat", &wi) != 0 &&
  3458. u_win_create(w = 600, h = 420, "Chat", &wi) != 0) {
  3459. u_puts("chat: no graphics window\n");
  3460. u_exit(1);
  3461. }
  3462. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  3463. ngui_font_attach(&ui);
  3464. server_in.placeholder = "chat.example.com";
  3465. user_in.placeholder = "username";
  3466. pass_in.secret = 1;
  3467. totp_in.placeholder = "123456";
  3468. cookie_in.placeholder = "connect.sid=...";
  3469. if (arg && arg[0]) {
  3470. s_copy(cfg_path, arg, sizeof(cfg_path));
  3471. } else {
  3472. s_copy(cfg_path, default_cfg_path(), sizeof(cfg_path));
  3473. cfg_is_default = 1;
  3474. }
  3475. ngui_set_focus(&ui, ID_SERVER);
  3476. last_input_ms = 0;
  3477. /* First frame, then the (possibly slow) session check. */
  3478. paint_now();
  3479. load_config();
  3480. for (;;) {
  3481. int redraw;
  3482. redraw = ngui_begin(&ui);
  3483. if (ui.key_head != ui.key_tail || ui.pressed || ui.scroll_y) {
  3484. last_input_ms = u_ticks_ms();
  3485. if (screen == SCR_MAIN && !offline)
  3486. maybe_save_cookie();
  3487. }
  3488. if (redraw) {
  3489. draw();
  3490. ngui_end(&ui);
  3491. } else {
  3492. ngui_end_ex(&ui, 0);
  3493. }
  3494. if (action != ACT_NONE)
  3495. run_action();
  3496. else
  3497. poll_tick();
  3498. chat_media_tick();
  3499. /* The offline retry countdown needs a once-a-second repaint. */
  3500. if (offline && screen == SCR_MAIN) {
  3501. static unsigned int last_tick;
  3502. if (u_ticks_ms() - last_tick >= 1000) {
  3503. last_tick = u_ticks_ms();
  3504. ngui_invalidate(&ui);
  3505. }
  3506. }
  3507. u_sleep_ms(10);
  3508. }
  3509. }