ucmd_chat.c 79 KB

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