ucmd_chat.c 80 KB

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