| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132 |
- /* chat: native client for Cloudron Chat on the ngui canvas toolkit.
- *
- * Login is the native Cloudron OIDC driver in chat_login.c (username,
- * password, optional TOTP) or a pasted session cookie. The session cookie is
- * kept in a uhttp cookie jar and saved with the server address in a small
- * config file: /data/CHAT.CFG on an installed disk, /share/chat.cfg when
- * there is no persistent /data mount, or the path given as argument.
- * The password is never stored.
- *
- * Everything else is the Chat REST API over uhttp: the channel and DM
- * directory, message pages (newest first, older paging with ?before=, live
- * updates with ?after=), sending, read markers, joining public channels and
- * opening DMs. There is no WebSocket: the open conversation is polled every
- * ~2 s and the directory every ~12 s, and polling waits while the user types.
- *
- * Network calls block the UI; the frame showing the "Loading" status is
- * presented first. TLS certificates are NOT verified (tls.c phase A), which
- * the login screen says. */
- #include "ucmd_lib.h"
- #include "ngui.h"
- #include "uhttp.h"
- #include "ujson.h"
- #include "chat_login.h"
- #include "img.h"
- #include <stdlib.h>
- #include <string.h>
- #define DEFAULT_CFG_DATA "/data/CHAT.CFG"
- #define DEFAULT_CFG_SHARE "/share/chat.cfg"
- #define RESP_CAP (512u * 1024u)
- #define JSON_NODES 16384u
- #define JSON_SCAP (RESP_CAP + 2u * JSON_NODES)
- #define MAX_CONV 128
- #define MAX_MSG 240
- #define MAX_PICK 256
- #define BODY_MAX 4096
- #define PAGE_SIZE 50
- #define LIVE_PAGE 50
- #define MSG_IMG_MAX 3
- #define CHAT_IMG_W 480
- #define CHAT_IMG_H 320
- #define CHAT_IMG_MAX 16
- #define CHAT_AVATAR_MAX 64
- #define CHAT_AVATAR 32
- #define CHAT_IMG_BUDGET (6u * 1024u * 1024u)
- #define CHAT_IMG_ARENA_MAX (12u * 1024u * 1024u)
- #define CHAT_IMG_FETCH_MAX (4u * 1024u * 1024u)
- #define CHAT_IMG_URL_MAX (UHTTP_HOST_MAX + UHTTP_PATH_MAX + 16)
- #define CHAT_PIC_QUEUED 0
- #define CHAT_PIC_READY 1
- #define CHAT_PIC_FAILED (-1)
- #define POLL_CONV_MS 2000
- #define POLL_CONV_IDLE_MS 5000
- #define POLL_DIR_MS 12000
- #define POLL_DIR_IDLE_MS 20000
- #define TYPING_HOLD_MS 1000
- #define KEEPALIVE_IDLE_MS 30000
- /* widget IDs */
- enum {
- ID_SERVER = 1, ID_CFG, ID_SIGNIN, ID_COOKIE_MODE, ID_USER, ID_PASS,
- ID_TOTP, ID_BACK, ID_COOKIE, ID_USE_COOKIE, ID_COMPOSE, ID_SEND,
- ID_REFRESH, ID_SIGNOUT, ID_BROWSE, ID_NEWDM, ID_OLDER, ID_NEWMSG,
- ID_RETRY, ID_MODAL_CLOSE, ID_FILTER, ID_MODAL_ROW = 1000
- };
- enum screen { SCR_SERVER, SCR_CRED, SCR_TOTP, SCR_COOKIE, SCR_MAIN };
- enum modal { MODAL_NONE, MODAL_BROWSE, MODAL_NEWDM };
- /* pending actions, collected while drawing and run after the frame */
- enum {
- ACT_NONE, ACT_START_LOGIN, ACT_SUBMIT, ACT_SUBMIT_TOTP, ACT_USE_COOKIE,
- ACT_SEND, ACT_REFRESH, ACT_SIGNOUT, ACT_OPEN_CONV, ACT_OLDER,
- ACT_BROWSE, ACT_NEWDM, ACT_JOIN, ACT_OPEN_DM, ACT_RETRY,
- ACT_COOKIE_SCREEN, ACT_BACK
- };
- struct conv {
- char id[48];
- char name[64];
- char preview[96];
- char kind; /* 'c' public, 'p' private, 'd' DM */
- char presence; /* DM: 'o' online, 'a' away, 'f' offline */
- int unread;
- };
- struct msg {
- char id[48];
- char user_id[48];
- char author[48];
- char *author_pic; /* profile picture URL, or NULL */
- char created[32]; /* ISO 8601 UTC, sorts as text */
- char reply[96]; /* "Name: snippet" */
- char extra[112]; /* attachments / thread / reactions line */
- char *body; /* Latin-1, malloc'd */
- char *img_url[MSG_IMG_MAX]; /* image attachments, malloc'd URLs */
- unsigned char nimg;
- unsigned char action; /* type "me" */
- int height;
- int layout_w;
- int compact;
- int day_header;
- };
- struct pick {
- char id[48];
- char name[64];
- char sub[64];
- char pic[256];
- };
- static struct ngui ui;
- static struct uhttp http;
- static struct uhttp_jar jar;
- static struct chat_login login;
- static struct ujson json;
- static struct ujson_node *jnodes;
- static char *jsbuf;
- static char *resp;
- static unsigned int resp_len;
- static enum screen screen = SCR_SERVER;
- static enum modal modal = MODAL_NONE;
- static int action, action_arg;
- static char cfg_path[CHAT_PATH_MAX];
- static int cfg_is_default;
- static char server[CHAT_SERVER_MAX];
- static char server_host[UHTTP_HOST_MAX];
- static int server_secure;
- static char saved_cookie[CHAT_COOKIE_MAX];
- static unsigned int saved_jar_changes;
- static char me_id[48];
- static char me_name[64];
- static struct ngui_input server_in, cfg_in, user_in, pass_in, totp_in;
- static struct ngui_input cookie_in, compose_in, filter_in;
- static struct conv convs[MAX_CONV];
- static int nconv;
- static int cur = -1; /* index into convs */
- static char cur_id[48];
- static struct msg msgs[MAX_MSG];
- static int nmsg;
- static int has_older;
- static unsigned int msgs_gen; /* bumped whenever msgs[] changes */
- static int history_full;
- static struct ngui_scroll tl_scroll, side_scroll, modal_scroll;
- static int at_bottom = 1;
- static int new_below;
- static struct pick picks[MAX_PICK];
- static int npick;
- static int modal_sel; /* keyboard selection among visible rows */
- static unsigned int last_older_ms;
- static char status[160];
- static int status_err;
- static char busy[96];
- static int offline;
- static unsigned int backoff_ms;
- static unsigned int next_conv_poll, next_dir_poll, retry_at;
- static unsigned int last_input_ms;
- static unsigned int last_net_ms;
- static unsigned int client_seq;
- /* ---- small string helpers ---- */
- static void s_copy(char *d, const char *s, unsigned int cap)
- {
- unsigned int i = 0;
- if (!cap)
- return;
- while (s && s[i] && i + 1 < cap) {
- d[i] = s[i];
- i++;
- }
- d[i] = '\0';
- }
- static void s_cat(char *d, const char *s, unsigned int cap)
- {
- unsigned int n = (unsigned int)strlen(d);
- if (n < cap)
- s_copy(d + n, s, cap - n);
- }
- static void s_cat_uint(char *d, unsigned int v, unsigned int cap)
- {
- char tmp[12];
- int i = 11;
- tmp[i] = '\0';
- do {
- tmp[--i] = (char)('0' + v % 10);
- v /= 10;
- } while (v && i > 0);
- s_cat(d, tmp + i, cap);
- }
- static void set_status(const char *a, const char *b, int err)
- {
- status[0] = '\0';
- s_cat(status, a, sizeof(status));
- if (b)
- s_cat(status, b, sizeof(status));
- status_err = err;
- ngui_invalidate(&ui);
- }
- /* ---- UTF-8 -> Latin-1 display text ---- */
- static unsigned int put_ascii(char *d, unsigned int n, unsigned int cap,
- const char *s)
- {
- while (*s && n + 1 < cap)
- d[n++] = *s++;
- return n;
- }
- /* Map a code point outside Latin-1 to a short ASCII stand-in; NULL to skip
- * it entirely (joiners, variation selectors, skin tones). */
- static const char *cp_fallback(unsigned int cp)
- {
- switch (cp) {
- case 0x2018: case 0x2019: case 0x201A: case 0x2032: return "'";
- case 0x201C: case 0x201D: case 0x201E: case 0x2033: return "\"";
- case 0x2010: case 0x2011: case 0x2012: case 0x2013: return "-";
- case 0x2014: case 0x2015: return "--";
- case 0x2026: return "...";
- case 0x2022: case 0x2023: case 0x25CF: return "\xb7";
- case 0x20AC: return "EUR";
- case 0x2122: return "TM";
- case 0x2192: return "->";
- case 0x2190: return "<-";
- case 0x2264: return "<=";
- case 0x2265: return ">=";
- case 0x2260: return "!=";
- case 0x2764: case 0x2665: return "<3";
- case 0x2705: case 0x2714: case 0x2713: return "[v]";
- case 0x274C: case 0x2716: return "[x]";
- case 0x26A0: return "/!\\";
- case 0x1F44D: return "(y)";
- case 0x1F44E: return "(n)";
- case 0x1F44B: return "o/";
- case 0x1F64F: return "_/\\_";
- case 0x1F389: case 0x1F38A: return "*\\o/*";
- case 0x1F600: case 0x1F603: case 0x1F604: case 0x1F60A:
- case 0x1F642: case 0x263A: return ":)";
- case 0x1F601: case 0x1F606: case 0x1F602: case 0x1F923: return ":D";
- case 0x1F609: return ";)";
- case 0x1F61B: case 0x1F61C: case 0x1F61D: return ":P";
- case 0x1F622: case 0x1F62D: case 0x1F641: case 0x2639: return ":(";
- case 0x1F62E: case 0x1F632: return ":O";
- case 0x1F914: return ":-/";
- case 0x1F525: return "(fire)";
- case 0x1F680: return "(rocket)";
- case 0x1F440: return "(eyes)";
- case 0x200B: case 0x200C: case 0x200D: case 0xFEFF:
- return 0;
- }
- if (cp >= 0xFE00 && cp <= 0xFE0F)
- return 0; /* variation selectors */
- if (cp >= 0x1F3FB && cp <= 0x1F3FF)
- return 0; /* skin tones */
- if (cp >= 0x2000 && cp <= 0x200A)
- return " ";
- return "?";
- }
- /* Convert UTF-8 to Latin-1 display text. Tabs become spaces, other control
- * characters (except newline) are dropped. */
- static unsigned int to_latin1(char *d, unsigned int cap, const char *s)
- {
- const unsigned char *p = (const unsigned char *)s;
- unsigned int n = 0;
- if (!cap)
- return 0;
- while (*p && n + 1 < cap) {
- unsigned int cp, extra, i;
- if (*p < 0x80) {
- cp = *p++;
- } else {
- if ((*p & 0xE0) == 0xC0) {
- cp = *p & 0x1F;
- extra = 1;
- } else if ((*p & 0xF0) == 0xE0) {
- cp = *p & 0x0F;
- extra = 2;
- } else if ((*p & 0xF8) == 0xF0) {
- cp = *p & 0x07;
- extra = 3;
- } else {
- p++;
- d[n++] = '?';
- continue;
- }
- p++;
- for (i = 0; i < extra; i++) {
- if ((*p & 0xC0) != 0x80)
- break;
- cp = (cp << 6) | (*p++ & 0x3F);
- }
- if (i < extra) {
- d[n++] = '?';
- continue;
- }
- }
- if (cp == '\t' || cp == 0xA0) {
- d[n++] = ' ';
- } else if (cp == '\n') {
- d[n++] = '\n';
- } else if (cp < 0x20 || cp == 0x7F || (cp >= 0x80 && cp < 0xA0)) {
- continue;
- } else if (cp < 0x100) {
- d[n++] = (char)cp;
- } else {
- const char *f = cp_fallback(cp);
- if (f)
- n = put_ascii(d, n, cap, f);
- }
- }
- d[n] = '\0';
- return n;
- }
- /* One-line version (newlines become spaces), for previews/snippets. */
- static void to_latin1_line(char *d, unsigned int cap, const char *s)
- {
- unsigned int i;
- to_latin1(d, cap, s);
- for (i = 0; d[i]; i++)
- if (d[i] == '\n')
- d[i] = ' ';
- }
- /* ---- config file ---- */
- static int read_file(const char *path, char *buf, unsigned int cap)
- {
- int n = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)(cap - 1));
- if (n < 0)
- return n;
- buf[n] = '\0';
- return n;
- }
- static int write_file(const char *path, const char *buf, unsigned int len)
- {
- return u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, (int)len);
- }
- /* The persistent data volume wins when it is mounted and writable; the
- * volatile /share is the fallback (live USB, or a board without /data). */
- static const char *default_cfg_path(void)
- {
- struct sys_mount m;
- unsigned int i;
- for (i = 0; u_syscall2(SYS_LIST_MOUNTS, (int)i, (int)&m) == 1; i++)
- if (strcmp(m.name, "data") == 0 && !m.ro)
- return DEFAULT_CFG_DATA;
- return DEFAULT_CFG_SHARE;
- }
- static int set_server(const char *s)
- {
- char norm[CHAT_SERVER_MAX];
- if (chat_server_normalize(s, norm, sizeof(norm)) != 0)
- return -1;
- if (chat_server_host(norm, server_host, sizeof(server_host),
- &server_secure) != 0)
- return -1;
- s_copy(server, norm, sizeof(server));
- return 0;
- }
- /* Export the Chat host's cookies and write the config file. */
- static void save_config(void)
- {
- static char out[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 128];
- int n;
- uhttp_jar_header(&jar, server_host, "/api/me", server_secure,
- saved_cookie, sizeof(saved_cookie));
- saved_jar_changes = jar.changes;
- n = chat_config_format(out, sizeof(out), server, saved_cookie);
- if (n < 0 || write_file(cfg_path, out, (unsigned int)n) < 0)
- set_status("Could not save the session to ", cfg_path, 1);
- memset(out, 0, sizeof(out));
- }
- /* A server may roll its session cookie: save when the jar changed. */
- static void maybe_save_cookie(void)
- {
- char now[CHAT_COOKIE_MAX];
- if (jar.changes == saved_jar_changes || screen != SCR_MAIN)
- return;
- uhttp_jar_header(&jar, server_host, "/api/me", server_secure, now,
- sizeof(now));
- saved_jar_changes = jar.changes;
- if (strcmp(now, saved_cookie) != 0)
- save_config();
- }
- /* ---- HTTP / JSON plumbing ---- */
- static void paint_now(void);
- static int line_h(void);
- static void net_drop(void)
- {
- http.keepalive = 0;
- uhttp_close(&http);
- }
- /* Request server + path; JSON body or NULL. Returns the HTTP status or a
- * UHTTP_ERR_*; the body is in resp/resp_len. */
- static int api(const char *method, const char *path, const char *body)
- {
- char url[CHAT_SERVER_MAX + 256];
- unsigned int len = 0;
- int st;
- s_copy(url, server, sizeof(url));
- s_cat(url, path, sizeof(url));
- http.jar = &jar;
- http.accept = "application/json";
- st = chat_http(&http, method, url, body, resp, RESP_CAP, &len);
- resp_len = st > 0 ? len : 0;
- last_net_ms = u_ticks_ms();
- maybe_save_cookie();
- return st;
- }
- static int parse_resp(void)
- {
- int root = ujson_parse(&json, resp, resp_len);
- return root;
- }
- /* ---- message images and avatars ---- */
- struct chat_pic {
- char *url;
- struct img_image img;
- unsigned int bytes; /* RGB565 bytes in the message-image budget */
- unsigned int last_used;
- int state; /* CHAT_PIC_* */
- };
- static struct chat_pic chat_images[CHAT_IMG_MAX];
- static int nchat_images;
- static unsigned int chat_image_bytes;
- static struct chat_pic chat_avatars[CHAT_AVATAR_MAX];
- static int nchat_avatars;
- static unsigned int chat_pic_clock;
- static unsigned char *chat_fetch_buf;
- static unsigned char *chat_arena;
- static unsigned int chat_arena_size;
- static void chat_pic_free(struct chat_pic *p)
- {
- free(p->url);
- free(p->img.px);
- free(p->img.alpha);
- memset(p, 0, sizeof(*p));
- }
- static struct chat_pic *chat_pic_find(struct chat_pic *arr, int n,
- const char *url)
- {
- int i;
- for (i = 0; i < n; i++)
- if (arr[i].url && strcmp(arr[i].url, url) == 0)
- return &arr[i];
- return 0;
- }
- /* Pick a cache slot, evicting the least recently used entry when full.
- * avatars: their images never change the timeline layout. */
- static struct chat_pic *chat_pic_slot(struct chat_pic *arr, int *count, int max,
- const char *url, int avatars)
- {
- struct chat_pic *p = chat_pic_find(arr, *count, url);
- unsigned int best = ~0u;
- int i, victim = -1;
- if (p)
- return p;
- if (*count < max) {
- p = &arr[*count];
- memset(p, 0, sizeof(*p));
- p->url = strdup(url);
- if (!p->url)
- return 0;
- (*count)++;
- } else {
- for (i = 0; i < *count; i++) {
- if (arr[i].state == CHAT_PIC_QUEUED)
- continue;
- if (arr[i].last_used < best) {
- best = arr[i].last_used;
- victim = i;
- }
- }
- if (victim < 0)
- return 0;
- p = &arr[victim];
- if (!avatars) {
- chat_image_bytes -= p->bytes;
- msgs_gen++;
- }
- chat_pic_free(p);
- p->url = strdup(url);
- if (!p->url)
- return 0;
- }
- p->state = CHAT_PIC_QUEUED;
- p->last_used = ++chat_pic_clock;
- return p;
- }
- static struct chat_pic *chat_image_slot(const char *url)
- {
- return chat_pic_slot(chat_images, &nchat_images, CHAT_IMG_MAX, url, 0);
- }
- static struct chat_pic *chat_avatar_slot(const char *url)
- {
- return chat_pic_slot(chat_avatars, &nchat_avatars, CHAT_AVATAR_MAX,
- url, 1);
- }
- static int chat_image_room(unsigned int need)
- {
- while (chat_image_bytes + need > CHAT_IMG_BUDGET) {
- unsigned int best = ~0u;
- int i, victim = -1;
- for (i = 0; i < nchat_images; i++) {
- if (chat_images[i].state != CHAT_PIC_READY)
- continue;
- if (chat_images[i].last_used < best) {
- best = chat_images[i].last_used;
- victim = i;
- }
- }
- if (victim < 0)
- return -1;
- chat_image_bytes -= chat_images[victim].bytes;
- chat_pic_free(&chat_images[victim]);
- msgs_gen++;
- }
- return 0;
- }
- static unsigned char *chat_pic_arena_get(unsigned int need)
- {
- if (need <= chat_arena_size)
- return chat_arena;
- free(chat_arena);
- chat_arena = (unsigned char *)malloc(need);
- chat_arena_size = chat_arena ? need : 0;
- return chat_arena;
- }
- static int chat_pic_store(struct chat_pic *p, unsigned int len, int avatar)
- {
- struct img_info info;
- struct img_options opt;
- struct img_mem mem;
- struct img_image decoded;
- struct img_blit blit;
- unsigned char *arena, *alpha = 0;
- unsigned short *px;
- unsigned int est, scale, dw, dh, sw, sh, i, need;
- int r;
- if (img_sniff(chat_fetch_buf, len, &info) != 0)
- return -1;
- est = img_estimate(&info);
- if (est == 0xFFFFFFFFu || est > CHAT_IMG_ARENA_MAX)
- return -1;
- arena = chat_pic_arena_get(est);
- if (!arena)
- return -1;
- img_mem_init(&mem, arena, est);
- opt.max_pixels = 4u * 1024u * 1024u;
- r = img_decode(chat_fetch_buf, len, &opt, &mem, &decoded);
- if (r != 0 || !decoded.w || !decoded.h)
- return -1;
- if (avatar) {
- sw = (CHAT_AVATAR << 16) / decoded.w;
- sh = (CHAT_AVATAR << 16) / decoded.h;
- scale = sw < sh ? sw : sh;
- dw = dh = CHAT_AVATAR;
- } else {
- scale = 65536;
- if (decoded.w > CHAT_IMG_W)
- scale = (CHAT_IMG_W << 16) / decoded.w;
- if (((decoded.h * scale) >> 16) > CHAT_IMG_H)
- scale = (CHAT_IMG_H << 16) / decoded.h;
- dw = (decoded.w * scale) >> 16;
- dh = (decoded.h * scale) >> 16;
- if (!dw)
- dw = 1;
- if (!dh)
- dh = 1;
- need = dw * dh * 2u;
- if (chat_image_room(need) != 0)
- return -1;
- }
- px = (unsigned short *)malloc(dw * dh * 2u);
- if (!px)
- return -1;
- for (i = 0; i < dw * dh; i++)
- px[i] = avatar ? 0xFFFF : ui.theme.bg;
- if (avatar && decoded.alpha) {
- alpha = (unsigned char *)malloc(dw * dh);
- if (alpha)
- memset(alpha, 255, dw * dh);
- }
- memset(&blit, 0, sizeof(blit));
- blit.dst = px;
- blit.dst_w = (int)dw;
- blit.dst_h = (int)dh;
- blit.clip_x = 0;
- blit.clip_y = 0;
- blit.clip_w = (int)dw;
- blit.clip_h = (int)dh;
- blit.x = avatar ? (int)(dw - ((decoded.w * scale) >> 16)) / 2 : 0;
- blit.y = avatar ? (int)(dh - ((decoded.h * scale) >> 16)) / 2 : 0;
- blit.scale = scale;
- blit.bg = avatar ? 0xFFFF : ui.theme.bg;
- blit.bg2 = blit.bg;
- blit.dst_a = alpha;
- blit.flags = alpha ? IMG_BLIT_SAVE_ALPHA :
- (decoded.alpha ? IMG_BLIT_OVER_DST : 0);
- img_draw(&decoded, &blit);
- p->img.format = decoded.format;
- p->img.w = dw;
- p->img.h = dh;
- p->img.px = px;
- p->img.alpha = alpha;
- p->img.flags = 0;
- p->bytes = avatar ? 0 : dw * dh * 2u;
- if (!avatar)
- chat_image_bytes += p->bytes;
- return 0;
- }
- static void chat_pic_load(struct chat_pic *p, int avatar)
- {
- unsigned int len = 0;
- int st;
- if (!chat_fetch_buf)
- chat_fetch_buf = (unsigned char *)malloc(CHAT_IMG_FETCH_MAX);
- if (!chat_fetch_buf) {
- p->state = CHAT_PIC_FAILED;
- return;
- }
- http.jar = &jar;
- http.accept = "image/*,*/*";
- st = chat_http(&http, 0, p->url, 0, (char *)chat_fetch_buf,
- CHAT_IMG_FETCH_MAX, &len);
- if (st != 200 || len == 0 || chat_pic_store(p, len, avatar) != 0) {
- p->state = CHAT_PIC_FAILED;
- } else {
- p->state = CHAT_PIC_READY;
- p->last_used = ++chat_pic_clock;
- if (!avatar) {
- msgs_gen++;
- if (at_bottom)
- tl_scroll.offset = 1 << 28;
- }
- }
- ngui_invalidate(&ui);
- }
- static void chat_media_tick(void)
- {
- int i;
- if (screen != SCR_MAIN || offline)
- return;
- for (i = 0; i < nchat_images; i++) {
- if (chat_images[i].state == CHAT_PIC_QUEUED) {
- chat_pic_load(&chat_images[i], 0);
- return;
- }
- }
- for (i = 0; i < nchat_avatars; i++) {
- if (chat_avatars[i].state == CHAT_PIC_QUEUED) {
- chat_pic_load(&chat_avatars[i], 1);
- return;
- }
- }
- }
- static void chat_media_clear(void)
- {
- int i;
- for (i = 0; i < nchat_images; i++)
- chat_pic_free(&chat_images[i]);
- for (i = 0; i < nchat_avatars; i++)
- chat_pic_free(&chat_avatars[i]);
- nchat_images = 0;
- nchat_avatars = 0;
- chat_image_bytes = 0;
- free(chat_fetch_buf);
- chat_fetch_buf = 0;
- free(chat_arena);
- chat_arena = 0;
- chat_arena_size = 0;
- }
- /* Refresh/Retry gives failed pictures another chance. */
- static void chat_media_retry(void)
- {
- int i;
- for (i = 0; i < nchat_images; i++)
- if (chat_images[i].state == CHAT_PIC_FAILED)
- chat_images[i].state = CHAT_PIC_QUEUED;
- for (i = 0; i < nchat_avatars; i++)
- if (chat_avatars[i].state == CHAT_PIC_FAILED)
- chat_avatars[i].state = CHAT_PIC_QUEUED;
- ngui_invalidate(&ui);
- }
- /* Resolve a picture URL; Cloudron's older profile-avatar path is rewritten
- * to the /api/avatars/ route the current server serves. */
- static int chat_pic_url(const char *raw, char *out, unsigned int cap)
- {
- static const char old_prefix[] = "/api/v1/profile/avatar/";
- const char *p;
- char tmp[CHAT_IMG_URL_MAX];
- char *q;
- if (!raw || !raw[0])
- return -1;
- p = strstr(raw, old_prefix);
- if (p) {
- s_copy(tmp, "/api/avatars/", sizeof(tmp));
- s_cat(tmp, p + sizeof(old_prefix) - 1, sizeof(tmp));
- q = strchr(tmp, '?');
- if (q)
- *q = '\0';
- raw = tmp;
- }
- return uhttp_resolve(server, raw, out, cap);
- }
- static int chat_image_name(const char *mime, const char *filename)
- {
- static const char *const ext[] = {
- ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tga",
- ".ppm", ".pgm", ".pbm", ".ico", ".cur", ".pam"
- };
- unsigned int i;
- if (mime && strncmp(mime, "image/", 6) == 0)
- return 1;
- if (!filename)
- return 0;
- for (i = 0; i < sizeof(ext) / sizeof(ext[0]); i++) {
- unsigned int n = (unsigned int)strlen(ext[i]);
- unsigned int j;
- const char *s = filename + strlen(filename);
- if ((unsigned int)strlen(filename) < n)
- continue;
- s -= n;
- for (j = 0; j < n; j++) {
- char a = s[j], b = ext[i][j];
- if (a >= 'A' && a <= 'Z')
- a = (char)(a - 'A' + 'a');
- if (a != b)
- break;
- }
- if (j == n)
- return 1;
- }
- return 0;
- }
- /* Layout/draw dimensions for one message image. *state is the cache state
- * (a missing entry is treated as queued; draw queues it). */
- static void chat_image_measure(const char *url, int tw, int *dw, int *dh,
- unsigned int *scale, int *state)
- {
- struct chat_pic *p = chat_pic_find(chat_images, nchat_images, url);
- unsigned int sc = 65536;
- if (p && p->state == CHAT_PIC_READY) {
- if ((int)p->img.w > tw)
- sc = ((unsigned int)tw << 16) / p->img.w;
- if (((p->img.h * sc) >> 16) > CHAT_IMG_H)
- sc = (CHAT_IMG_H << 16) / p->img.h;
- *dw = (int)((p->img.w * sc) >> 16);
- *dh = (int)((p->img.h * sc) >> 16);
- if (*dw < 1)
- *dw = 1;
- if (*dh < 1)
- *dh = 1;
- *scale = sc;
- *state = CHAT_PIC_READY;
- return;
- }
- *dw = tw < 320 ? tw : 320;
- if (*dw < 40)
- *dw = 40;
- *dh = 120;
- *scale = 65536;
- *state = p ? p->state : CHAT_PIC_QUEUED;
- }
- static struct ngui_rect chat_clip_rect(void)
- {
- if (ui.nclip > 0)
- return ui.clip[ui.nclip - 1];
- return (struct ngui_rect){ 0, 0, ui.w, ui.h };
- }
- static void chat_image_draw(const char *url, int x, int y, int tw)
- {
- struct chat_pic *p = chat_pic_find(chat_images, nchat_images, url);
- struct ngui_rect clip = chat_clip_rect();
- int dw, dh, state;
- unsigned int scale;
- if (!p)
- p = chat_image_slot(url);
- chat_image_measure(url, tw, &dw, &dh, &scale, &state);
- if (p && p->state == CHAT_PIC_READY) {
- struct img_blit blit;
- memset(&blit, 0, sizeof(blit));
- blit.dst = ui.px;
- blit.dst_w = ui.w;
- blit.dst_h = ui.h;
- blit.clip_x = clip.x;
- blit.clip_y = clip.y;
- blit.clip_w = clip.w;
- blit.clip_h = clip.h;
- blit.x = x;
- blit.y = y;
- blit.scale = scale;
- blit.bg = ui.theme.bg;
- blit.bg2 = ui.theme.bg;
- blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0;
- img_draw(&p->img, &blit);
- ngui_frame(&ui, (struct ngui_rect){ x, y, dw, dh },
- ui.theme.border);
- } else {
- struct ngui_rect box = { x, y, dw, dh };
- ngui_fill_rect(&ui, box, ui.theme.panel_alt);
- ngui_frame(&ui, box, ui.theme.border);
- ngui_text_ellipsis(&ui, box, x + 8, y + (dh - line_h()) / 2,
- state == CHAT_PIC_FAILED ?
- "Image could not be loaded" :
- "Loading image...", ui.theme.text_dim);
- }
- }
- static int chat_avatar_draw(const char *url, int x, int y, int size,
- unsigned short fallback)
- {
- struct chat_pic *p;
- if (!url || !url[0])
- return 0;
- p = chat_pic_find(chat_avatars, nchat_avatars, url);
- if (!p)
- p = chat_avatar_slot(url);
- if (p && p->state == CHAT_PIC_READY) {
- struct ngui_rect clip = chat_clip_rect();
- struct img_blit blit;
- memset(&blit, 0, sizeof(blit));
- blit.dst = ui.px;
- blit.dst_w = ui.w;
- blit.dst_h = ui.h;
- blit.clip_x = clip.x;
- blit.clip_y = clip.y;
- blit.clip_w = clip.w;
- blit.clip_h = clip.h;
- blit.x = x;
- blit.y = y;
- blit.scale = ((unsigned int)size << 16) / CHAT_AVATAR;
- blit.bg = fallback;
- blit.bg2 = fallback;
- blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0;
- img_draw(&p->img, &blit);
- return 1;
- }
- return 0;
- }
- static void go_login(const char *why);
- /* Common error handling for API calls in the main screen. Returns 1 when
- * the status is a success. */
- static int api_ok(int st, const char *what)
- {
- if (st >= 200 && st < 300) {
- if (offline) {
- offline = 0;
- set_status("Connected", 0, 0);
- }
- backoff_ms = 0;
- return 1;
- }
- if (st == 401) {
- go_login("Session expired - please sign in again");
- return 0;
- }
- if (st > 0) {
- char code[64];
- s_copy(code, what, sizeof(code));
- s_cat(code, ": HTTP ", sizeof(code));
- s_cat_uint(code, (unsigned int)st, sizeof(code));
- set_status(code, 0, 1);
- return 0;
- }
- offline = 1;
- backoff_ms = backoff_ms == 0 ? 2000 : backoff_ms < 5000 ? 5000 :
- backoff_ms < 10000 ? 10000 : 30000;
- retry_at = u_ticks_ms() + backoff_ms;
- set_status("Offline: ", uhttp_error_string(st), 1);
- net_drop();
- return 0;
- }
- /* ---- conversations ---- */
- static int conv_find(const char *id)
- {
- int i;
- for (i = 0; i < nconv; i++)
- if (strcmp(convs[i].id, id) == 0)
- return i;
- return -1;
- }
- static void conv_from_json(struct conv *c, int o, int dm)
- {
- int last;
- s_copy(c->id, ujson_get_str(&json, o, "id"), sizeof(c->id));
- c->unread = (int)ujson_int(&json, ujson_get(&json, o, "unreadCount"), 0);
- c->preview[0] = '\0';
- last = ujson_get(&json, o, "lastMessage");
- if (ujson_type(&json, last) == UJSON_OBJECT) {
- char tmp[96];
- to_latin1_line(tmp, sizeof(tmp),
- ujson_get_str(&json, last, "authorName"));
- s_copy(c->preview, tmp, sizeof(c->preview));
- s_cat(c->preview, ": ", sizeof(c->preview));
- to_latin1_line(tmp, sizeof(tmp),
- ujson_get_str(&json, last, "body"));
- s_cat(c->preview, tmp, sizeof(c->preview));
- }
- if (dm) {
- int other = ujson_get(&json, o, "otherUser");
- const char *pres = ujson_get_str(&json, o, "presence");
- const char *nm = ujson_get_str(&json, other, "name");
- if (!nm[0])
- nm = ujson_get_str(&json, other, "username");
- to_latin1_line(c->name, sizeof(c->name), nm[0] ? nm : "(unknown)");
- c->kind = 'd';
- c->presence = strcmp(pres, "online") == 0 ? 'o' :
- strcmp(pres, "away") == 0 ? 'a' : 'f';
- } else {
- to_latin1_line(c->name, sizeof(c->name),
- ujson_get_str(&json, o, "name"));
- c->kind = strcmp(ujson_get_str(&json, o, "type"), "private") == 0 ?
- 'p' : 'c';
- c->presence = 0;
- }
- }
- static int load_directory(void)
- {
- static struct conv next[MAX_CONV];
- int n = 0, st, root, it, pass;
- for (pass = 0; pass < 2; pass++) {
- st = api(0, pass ? "/api/dms" : "/api/channels", 0);
- if (!api_ok(st, pass ? "Direct messages" : "Channels"))
- return -1;
- root = parse_resp();
- if (root < 0) {
- set_status("Bad directory reply: ", json.error, 1);
- return -1;
- }
- for (it = ujson_first(&json, root); it >= 0 && n < MAX_CONV;
- it = ujson_next(&json, it)) {
- if (ujson_truthy(&json, ujson_get(&json, it, "archived")))
- continue;
- if (pass && ujson_truthy(&json, ujson_get(&json, it,
- "isSelf")))
- continue;
- conv_from_json(&next[n], it, pass);
- if (next[n].id[0])
- n++;
- }
- }
- memcpy(convs, next, sizeof(struct conv) * (unsigned int)n);
- nconv = n;
- cur = cur_id[0] ? conv_find(cur_id) : -1;
- if (cur >= 0 && at_bottom)
- convs[cur].unread = 0; /* we are reading it */
- ngui_invalidate(&ui);
- return 0;
- }
- /* ---- messages ---- */
- static void msg_free(struct msg *m)
- {
- int i;
- free(m->body);
- m->body = 0;
- free(m->author_pic);
- m->author_pic = 0;
- for (i = 0; i < m->nimg; i++) {
- free(m->img_url[i]);
- m->img_url[i] = 0;
- }
- m->nimg = 0;
- }
- /* Resolve and remember one image URL; duplicates and overflowing messages
- * are ignored. */
- static int msg_add_image(struct msg *m, const char *raw)
- {
- char url[CHAT_IMG_URL_MAX];
- int i;
- if (!raw || !raw[0] || m->nimg >= MSG_IMG_MAX)
- return 0;
- if (uhttp_resolve(server, raw, url, sizeof(url)) != 0)
- return 0;
- for (i = 0; i < m->nimg; i++)
- if (strcmp(m->img_url[i], url) == 0)
- return 0;
- m->img_url[m->nimg] = strdup(url);
- if (!m->img_url[m->nimg])
- return -1;
- m->nimg++;
- return 0;
- }
- static void msg_set_author_pic(struct msg *m, const char *raw)
- {
- char url[CHAT_IMG_URL_MAX];
- if (!raw[0] || chat_pic_url(raw, url, sizeof(url)) != 0)
- return;
- m->author_pic = strdup(url);
- }
- static void clear_messages(void)
- {
- int i;
- for (i = 0; i < nmsg; i++)
- msg_free(&msgs[i]);
- nmsg = 0;
- msgs_gen++;
- has_older = 0;
- history_full = 0;
- new_below = 0;
- }
- static int msg_find(const char *id)
- {
- int i;
- for (i = nmsg - 1; i >= 0; i--)
- if (strcmp(msgs[i].id, id) == 0)
- return i;
- return -1;
- }
- static void build_extra(struct msg *m, int o)
- {
- int it, n;
- m->extra[0] = '\0';
- for (it = ujson_first(&json, ujson_get(&json, o, "attachments"));
- it >= 0; it = ujson_next(&json, it)) {
- char name[64];
- const char *mime = ujson_get_str(&json, it, "mime");
- const char *fn = ujson_get_str(&json, it, "filename");
- const char *url = ujson_get_str(&json, it, "url");
- if (chat_image_name(mime, fn) && url[0])
- continue; /* drawn inline by the timeline */
- to_latin1_line(name, sizeof(name), fn);
- if (m->extra[0])
- s_cat(m->extra, ", ", sizeof(m->extra));
- else
- s_cat(m->extra, "[file] ", sizeof(m->extra));
- s_cat(m->extra, name, sizeof(m->extra));
- }
- if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT &&
- !ujson_get_str(&json, ujson_get(&json, o, "gif"), "url")[0]) {
- if (m->extra[0])
- s_cat(m->extra, " ", sizeof(m->extra));
- s_cat(m->extra, "[GIF]", sizeof(m->extra));
- }
- if (strcmp(ujson_get_str(&json, o, "type"), "poll") == 0) {
- if (m->extra[0])
- s_cat(m->extra, " ", sizeof(m->extra));
- s_cat(m->extra, "[poll - open in the web app]", sizeof(m->extra));
- }
- if (ujson_get_str(&json, o, "callUrl")[0]) {
- if (m->extra[0])
- s_cat(m->extra, " ", sizeof(m->extra));
- s_cat(m->extra, "[call]", sizeof(m->extra));
- }
- n = (int)ujson_int(&json, ujson_get(&json, o, "threadCount"), 0);
- if (n > 0) {
- if (m->extra[0])
- s_cat(m->extra, " \xb7 ", sizeof(m->extra));
- s_cat_uint(m->extra, (unsigned int)n, sizeof(m->extra));
- s_cat(m->extra, n == 1 ? " reply" : " replies", sizeof(m->extra));
- }
- n = 0;
- for (it = ujson_first(&json, ujson_get(&json, o, "reactions"));
- it >= 0; it = ujson_next(&json, it)) {
- int c = (int)ujson_int(&json, ujson_get(&json, it, "count"), 1);
- n += c > 0 ? c : 1;
- }
- if (n > 0) {
- if (m->extra[0])
- s_cat(m->extra, " \xb7 ", sizeof(m->extra));
- s_cat_uint(m->extra, (unsigned int)n, sizeof(m->extra));
- s_cat(m->extra, n == 1 ? " reaction" : " reactions",
- sizeof(m->extra));
- }
- if (ujson_truthy(&json, ujson_get(&json, o, "pinned"))) {
- if (m->extra[0])
- s_cat(m->extra, " \xb7 ", sizeof(m->extra));
- s_cat(m->extra, "pinned", sizeof(m->extra));
- }
- }
- /* Fill m from a message object; 0 ok, -1 skip (deleted/thread reply). */
- static int msg_from_json(struct msg *m, int o)
- {
- static char body[BODY_MAX + 8];
- const char *nm;
- int rt;
- unsigned int len;
- if (ujson_truthy(&json, ujson_get(&json, o, "deleted")))
- return -1;
- /* Thread replies live in the thread panel, not the timeline. */
- if (ujson_get_str(&json, o, "parentId")[0])
- return -1;
- memset(m, 0, sizeof(*m));
- s_copy(m->id, ujson_get_str(&json, o, "id"), sizeof(m->id));
- if (!m->id[0])
- return -1;
- s_copy(m->user_id, ujson_get_str(&json, o, "userId"), sizeof(m->user_id));
- nm = ujson_get_str(&json, o, "authorName");
- if (!nm[0])
- nm = ujson_get_str(&json, o, "authorUsername");
- to_latin1_line(m->author, sizeof(m->author), nm[0] ? nm : "?");
- msg_set_author_pic(m, ujson_get_str(&json, o, "authorPicture"));
- s_copy(m->created, ujson_get_str(&json, o, "createdAt"),
- sizeof(m->created));
- m->action = strcmp(ujson_get_str(&json, o, "type"), "me") == 0;
- len = to_latin1(body, BODY_MAX, ujson_get_str(&json, o, "body"));
- if (len + 1 >= BODY_MAX) {
- /* truncated: mark it */
- body[BODY_MAX - 4] = '.';
- body[BODY_MAX - 3] = '.';
- body[BODY_MAX - 2] = '.';
- body[BODY_MAX - 1] = '\0';
- }
- /* Trim trailing newlines/spaces. */
- len = (unsigned int)strlen(body);
- while (len && (body[len - 1] == '\n' || body[len - 1] == ' '))
- body[--len] = '\0';
- m->body = strdup(body);
- if (!m->body) {
- msg_free(m);
- return -1;
- }
- {
- int it;
- const char *mime, *fn;
- for (it = ujson_first(&json,
- ujson_get(&json, o, "attachments"));
- it >= 0; it = ujson_next(&json, it)) {
- mime = ujson_get_str(&json, it, "mime");
- fn = ujson_get_str(&json, it, "filename");
- if (chat_image_name(mime, fn) &&
- msg_add_image(m, ujson_get_str(&json, it, "url")) != 0) {
- msg_free(m);
- return -1;
- }
- }
- }
- if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT &&
- msg_add_image(m, ujson_get_str(&json, ujson_get(&json, o, "gif"),
- "url")) != 0) {
- msg_free(m);
- return -1;
- }
- if (ujson_type(&json, ujson_get(&json, o, "preview")) == UJSON_OBJECT &&
- msg_add_image(m, ujson_get_str(&json,
- ujson_get(&json, o, "preview"),
- "image")) != 0) {
- msg_free(m);
- return -1;
- }
- rt = ujson_get(&json, o, "replyTo");
- if (ujson_type(&json, rt) == UJSON_OBJECT) {
- char tmp[96];
- to_latin1_line(m->reply, sizeof(m->reply),
- ujson_get_str(&json, rt, "authorName"));
- s_cat(m->reply, ": ", sizeof(m->reply));
- if (ujson_truthy(&json, ujson_get(&json, rt, "deleted")))
- s_copy(tmp, "(deleted)", sizeof(tmp));
- else
- to_latin1_line(tmp, sizeof(tmp),
- ujson_get_str(&json, rt, "body"));
- if (!tmp[0])
- s_copy(tmp, "(attachment)", sizeof(tmp));
- s_cat(m->reply, tmp, sizeof(m->reply));
- }
- build_extra(m, o);
- return 0;
- }
- static int msg_before(const struct msg *a, const struct msg *b)
- {
- int c = strcmp(a->created, b->created);
- return c < 0 || (c == 0 && strcmp(a->id, b->id) < 0);
- }
- /* Insert or update a message, keeping msgs sorted. older: we are paging
- * back in history (never evict old messages for it). Returns 1 when a new
- * message was added, 0 when updated/skipped. */
- static int msg_merge(struct msg *m, int older)
- {
- int i = msg_find(m->id), pos;
- msgs_gen++;
- if (i >= 0) {
- /* Edited body or new reactions: replace in place. */
- msg_free(&msgs[i]);
- msgs[i] = *m;
- return 0;
- }
- if (nmsg >= MAX_MSG) {
- if (older) {
- history_full = 1;
- msg_free(m);
- return 0;
- }
- msg_free(&msgs[0]);
- memmove(&msgs[0], &msgs[1], sizeof(struct msg) * (MAX_MSG - 1));
- nmsg--;
- has_older = 1;
- history_full = 1;
- }
- pos = nmsg;
- while (pos > 0 && msg_before(m, &msgs[pos - 1]))
- pos--;
- memmove(&msgs[pos + 1], &msgs[pos],
- sizeof(struct msg) * (unsigned int)(nmsg - pos));
- msgs[pos] = *m;
- nmsg++;
- return 1;
- }
- /* Merge every message of the parsed reply. Returns the number added. */
- static int merge_reply(int root, int older, int *count)
- {
- int it, added = 0, n = 0;
- for (it = ujson_first(&json, root); it >= 0; it = ujson_next(&json, it)) {
- struct msg m;
- const char *id = ujson_get_str(&json, it, "id");
- n++;
- if (ujson_truthy(&json, ujson_get(&json, it, "deleted"))) {
- /* A deletion we already show: drop it. */
- int k = msg_find(id);
- if (k >= 0) {
- msg_free(&msgs[k]);
- memmove(&msgs[k], &msgs[k + 1],
- sizeof(struct msg) *
- (unsigned int)(nmsg - k - 1));
- nmsg--;
- msgs_gen++;
- }
- continue;
- }
- if (msg_from_json(&m, it) == 0)
- added += msg_merge(&m, older);
- }
- if (count)
- *count = n;
- return added;
- }
- static void mark_read(void)
- {
- char path[96];
- int st;
- if (cur < 0)
- return;
- s_copy(path, "/api/channels/", sizeof(path));
- s_cat(path, convs[cur].id, sizeof(path));
- s_cat(path, "/read", sizeof(path));
- st = api("POST", path, 0);
- if (api_ok(st, "Mark read"))
- convs[cur].unread = 0;
- }
- static void msgs_path(char *path, unsigned int cap, const char *query)
- {
- s_copy(path, "/api/channels/", cap);
- s_cat(path, cur_id, cap);
- s_cat(path, "/messages?", cap);
- s_cat(path, query, cap);
- }
- static void scroll_to_end(void)
- {
- tl_scroll.offset = 1 << 28; /* clamped when laid out */
- at_bottom = 1;
- new_below = 0;
- }
- static void open_conv(int idx)
- {
- char path[160];
- int st, root, n = 0;
- if (idx < 0 || idx >= nconv)
- return;
- cur = idx;
- s_copy(cur_id, convs[idx].id, sizeof(cur_id));
- clear_messages();
- scroll_to_end();
- s_copy(busy, "Loading messages...", sizeof(busy));
- paint_now();
- msgs_path(path, sizeof(path), "limit=50");
- st = api(0, path, 0);
- busy[0] = '\0';
- if (!api_ok(st, "Messages"))
- return;
- root = parse_resp();
- if (root < 0) {
- set_status("Bad message reply: ", json.error, 1);
- return;
- }
- merge_reply(root, 1, &n);
- has_older = n >= PAGE_SIZE;
- scroll_to_end();
- mark_read();
- next_conv_poll = u_ticks_ms() + POLL_CONV_MS;
- ngui_invalidate(&ui);
- }
- static int content_height(void);
- static void load_older(void)
- {
- char path[200], q[96];
- int st, root, n = 0, before_h, added;
- if (cur < 0 || !nmsg || history_full)
- return;
- last_older_ms = u_ticks_ms();
- s_copy(q, "limit=50&before=", sizeof(q));
- s_cat(q, msgs[0].id, sizeof(q));
- msgs_path(path, sizeof(path), q);
- s_copy(busy, "Loading older messages...", sizeof(busy));
- paint_now();
- st = api(0, path, 0);
- busy[0] = '\0';
- if (!api_ok(st, "Older messages"))
- return;
- root = parse_resp();
- if (root < 0)
- return;
- before_h = content_height();
- added = merge_reply(root, 1, &n);
- has_older = n >= PAGE_SIZE && !history_full;
- /* Keep the view on the same message. */
- if (added)
- tl_scroll.offset += content_height() - before_h;
- ngui_invalidate(&ui);
- }
- static void poll_conv(void)
- {
- char path[200], q[96];
- int st, root, added, n = 0;
- if (cur < 0)
- return;
- if (!nmsg) {
- msgs_path(path, sizeof(path), "limit=50");
- } else {
- s_copy(q, "limit=50&after=", sizeof(q));
- s_cat(q, msgs[nmsg - 1].id, sizeof(q));
- msgs_path(path, sizeof(path), q);
- }
- st = api(0, path, 0);
- if (st == 404 && nmsg) {
- /* The anchor message was deleted: reload the page. */
- open_conv(cur);
- return;
- }
- if (!api_ok(st, "Messages"))
- return;
- root = parse_resp();
- if (root < 0) {
- set_status("Bad message reply: ", json.error, 1);
- return;
- }
- added = merge_reply(root, 0, &n);
- if (n >= LIVE_PAGE) {
- /* More than a page arrived: jump to the newest page. */
- open_conv(cur);
- return;
- }
- if (added) {
- if (at_bottom) {
- scroll_to_end();
- mark_read();
- } else {
- new_below += added;
- }
- ngui_invalidate(&ui);
- }
- }
- static void make_client_id(char *out, unsigned int cap)
- {
- static const char hex[] = "0123456789abcdef";
- unsigned int v = u_ticks_ms() ^ ((unsigned int)u_getpid() << 20);
- unsigned int c = ++client_seq, i;
- s_copy(out, "nebos-", cap);
- for (i = 0; i < 8; i++) {
- char ch[2] = { hex[(v >> (28 - 4 * i)) & 15], 0 };
- s_cat(out, ch, cap);
- }
- s_cat(out, "-", cap);
- s_cat_uint(out, c, cap);
- }
- static void send_message(void)
- {
- static char body[NGUI_INPUT_MAX * 6 + 160];
- char path[96], cid[40];
- int st, root, r;
- unsigned int n = 0;
- const char *t = compose_in.text;
- while (*t == ' ')
- t++;
- if (cur < 0 || !*t)
- return;
- make_client_id(cid, sizeof(cid));
- s_copy(body, "{\"body\":", sizeof(body));
- n = (unsigned int)strlen(body);
- {
- /* The field holds Latin-1/ASCII: encode as UTF-8 for JSON. */
- static char utf8[NGUI_INPUT_MAX * 2 + 4];
- unsigned int k = 0;
- const unsigned char *p = (const unsigned char *)t;
- while (*p && k + 3 < sizeof(utf8)) {
- if (*p < 0x80) {
- utf8[k++] = (char)*p;
- } else {
- utf8[k++] = (char)(0xC0 | (*p >> 6));
- utf8[k++] = (char)(0x80 | (*p & 0x3F));
- }
- p++;
- }
- utf8[k] = '\0';
- r = ujson_escape(body + n, sizeof(body) - n, utf8);
- }
- if (r < 0)
- return;
- n += (unsigned int)r;
- s_cat(body, ",\"clientId\":\"", sizeof(body));
- s_cat(body, cid, sizeof(body));
- s_cat(body, "\"}", sizeof(body));
- s_copy(path, "/api/channels/", sizeof(path));
- s_cat(path, cur_id, sizeof(path));
- s_cat(path, "/messages", sizeof(path));
- s_copy(busy, "Sending...", sizeof(busy));
- paint_now();
- st = api("POST", path, body);
- busy[0] = '\0';
- if (!api_ok(st, "Send")) {
- if (st > 0) {
- char msg[96];
- root = parse_resp();
- s_copy(msg, root >= 0 ?
- ujson_get_str(&json, root, "error") : "", sizeof(msg));
- if (msg[0])
- set_status("Send failed: ", msg, 1);
- }
- return; /* the text stays in the composer */
- }
- ngui_input_set(&compose_in, "");
- root = parse_resp();
- if (root >= 0 && ujson_type(&json, root) == UJSON_OBJECT) {
- struct msg m;
- if (msg_from_json(&m, root) == 0)
- msg_merge(&m, 0);
- }
- scroll_to_end();
- mark_read();
- next_conv_poll = u_ticks_ms() + POLL_CONV_MS;
- ngui_set_focus(&ui, ID_COMPOSE);
- }
- /* ---- browse / new DM ---- */
- static void load_picks(int dms)
- {
- int st, root, it;
- npick = 0;
- ngui_input_set(&filter_in, "");
- s_copy(busy, dms ? "Loading people..." : "Loading channels...",
- sizeof(busy));
- paint_now();
- st = api(0, dms ? "/api/users" : "/api/channels/public", 0);
- busy[0] = '\0';
- if (!api_ok(st, dms ? "Users" : "Public channels"))
- return;
- root = parse_resp();
- if (root < 0)
- return;
- for (it = ujson_first(&json, root); it >= 0 && npick < MAX_PICK;
- it = ujson_next(&json, it)) {
- struct pick *p = &picks[npick];
- const char *nm;
- s_copy(p->id, ujson_get_str(&json, it, "id"), sizeof(p->id));
- if (!p->id[0])
- continue;
- p->pic[0] = '\0';
- {
- char url[CHAT_IMG_URL_MAX];
- if (chat_pic_url(ujson_get_str(&json, it, "picture"),
- url, sizeof(url)) == 0)
- s_copy(p->pic, url, sizeof(p->pic));
- }
- if (dms) {
- if (strcmp(p->id, me_id) == 0)
- continue;
- nm = ujson_get_str(&json, it, "name");
- if (!nm[0])
- nm = ujson_get_str(&json, it, "username");
- to_latin1_line(p->name, sizeof(p->name), nm);
- to_latin1_line(p->sub, sizeof(p->sub),
- ujson_get_str(&json, it, "username"));
- } else {
- to_latin1_line(p->name, sizeof(p->name),
- ujson_get_str(&json, it, "name"));
- to_latin1_line(p->sub, sizeof(p->sub),
- ujson_get_str(&json, it, "description"));
- }
- npick++;
- }
- modal = dms ? MODAL_NEWDM : MODAL_BROWSE;
- modal_scroll.offset = 0;
- modal_sel = 0;
- ngui_set_focus(&ui, ID_FILTER);
- }
- static void pick_action(int idx)
- {
- char path[128], body[96], id[48];
- int st, root;
- if (idx < 0 || idx >= npick)
- return;
- if (modal == MODAL_BROWSE) {
- s_copy(path, "/api/channels/", sizeof(path));
- s_cat(path, picks[idx].id, sizeof(path));
- s_cat(path, "/join", sizeof(path));
- s_copy(busy, "Joining...", sizeof(busy));
- paint_now();
- st = api("POST", path, 0);
- busy[0] = '\0';
- if (!api_ok(st, "Join"))
- return;
- s_copy(id, picks[idx].id, sizeof(id));
- } else {
- s_copy(body, "{\"userId\":", sizeof(body));
- if (ujson_escape(body + strlen(body), sizeof(body) - strlen(body),
- picks[idx].id) < 0)
- return;
- s_cat(body, "}", sizeof(body));
- s_copy(busy, "Opening conversation...", sizeof(busy));
- paint_now();
- st = api("POST", "/api/dms", body);
- busy[0] = '\0';
- if (!api_ok(st, "New DM"))
- return;
- root = parse_resp();
- s_copy(id, root >= 0 ? ujson_get_str(&json, root, "id") : "",
- sizeof(id));
- }
- modal = MODAL_NONE;
- if (load_directory() == 0 && id[0]) {
- int k = conv_find(id);
- if (k >= 0)
- open_conv(k);
- }
- }
- /* ---- session ---- */
- static void enter_main(void)
- {
- int root;
- screen = SCR_MAIN;
- offline = 0;
- backoff_ms = 0;
- root = parse_resp(); /* the /api/me reply */
- if (root >= 0) {
- const char *nm = ujson_get_str(&json, root, "name");
- s_copy(me_id, ujson_get_str(&json, root, "id"), sizeof(me_id));
- to_latin1_line(me_name, sizeof(me_name),
- nm[0] ? nm : ujson_get_str(&json, root, "username"));
- }
- set_status("Connected", 0, 0);
- if (load_directory() == 0 && nconv > 0 && cur < 0) {
- int i, pick = 0;
- for (i = 0; i < nconv; i++) {
- if (convs[i].kind != 'd' &&
- strcmp(convs[i].name, "general") == 0) {
- pick = i;
- break;
- }
- }
- open_conv(pick);
- }
- next_dir_poll = u_ticks_ms() + POLL_DIR_MS;
- ngui_set_focus(&ui, ID_COMPOSE);
- }
- static void go_login(const char *why)
- {
- net_drop();
- uhttp_jar_clear(&jar);
- saved_jar_changes = jar.changes;
- saved_cookie[0] = '\0';
- chat_media_clear();
- screen = SCR_SERVER;
- modal = MODAL_NONE;
- clear_messages();
- nconv = 0;
- cur = -1;
- cur_id[0] = '\0';
- set_status(why, 0, why != 0);
- ngui_set_focus(&ui, ID_SERVER);
- }
- /* After the jar holds a session: validate it with /api/me. */
- static int check_session(int keep_offline)
- {
- unsigned int len = 0;
- int r;
- s_copy(busy, "Checking session...", sizeof(busy));
- paint_now();
- r = chat_session_check(&http, &jar, server, resp, RESP_CAP, &len);
- busy[0] = '\0';
- resp_len = len;
- if (r == 0) {
- save_config();
- enter_main();
- return 0;
- }
- if (r == 1) {
- go_login("The saved session is no longer valid - sign in again");
- return -1;
- }
- if (keep_offline) {
- /* Network trouble: keep the cached session and retry. */
- screen = SCR_MAIN;
- offline = 1;
- backoff_ms = 5000;
- retry_at = u_ticks_ms() + backoff_ms;
- set_status("Offline: ", r < 0 && r > -100 ?
- uhttp_error_string(r) : "server error", 1);
- return -1;
- }
- set_status("Session check failed: ", r < 0 && r > -100 ?
- uhttp_error_string(r) : "server error", 1);
- return -1;
- }
- static void start_login(void)
- {
- int r;
- if (set_server(server_in.text) != 0) {
- set_status("Enter a server such as chat.example.com", 0, 1);
- return;
- }
- if (cfg_in.text[0])
- s_copy(cfg_path, cfg_in.text, sizeof(cfg_path));
- uhttp_jar_clear(&jar);
- s_copy(busy, "Contacting the server...", sizeof(busy));
- paint_now();
- r = chat_login_start(&login, &http, &jar, server, resp, RESP_CAP);
- busy[0] = '\0';
- net_drop();
- if (r == CHAT_LOGIN_OK) {
- resp_len = (unsigned int)strlen(resp);
- save_config();
- enter_main();
- return;
- }
- if (r == CHAT_LOGIN_FORM) {
- screen = SCR_CRED;
- set_status("", 0, 0);
- ngui_set_focus(&ui, user_in.len ? ID_PASS : ID_USER);
- return;
- }
- if (r == CHAT_LOGIN_NOFORM) {
- screen = SCR_COOKIE;
- set_status(login.error, 0, 1);
- ngui_set_focus(&ui, ID_COOKIE);
- return;
- }
- set_status(login.error, 0, 1);
- }
- static void wipe_secrets(void)
- {
- memset(pass_in.text, 0, sizeof(pass_in.text));
- pass_in.len = pass_in.cursor = pass_in.anchor = pass_in.scroll = 0;
- memset(totp_in.text, 0, sizeof(totp_in.text));
- totp_in.len = totp_in.cursor = totp_in.anchor = totp_in.scroll = 0;
- }
- static void submit_login(int with_totp)
- {
- int r;
- if (!user_in.text[0] || !pass_in.text[0]) {
- set_status("Enter the username and password", 0, 1);
- return;
- }
- s_copy(busy, "Signing in...", sizeof(busy));
- paint_now();
- r = chat_login_submit(&login, &http, &jar, user_in.text, pass_in.text,
- with_totp ? totp_in.text : "", resp, RESP_CAP);
- busy[0] = '\0';
- net_drop();
- if (r == CHAT_LOGIN_TOTP) {
- if (with_totp) {
- set_status("The code was not accepted", 0, 1);
- } else {
- screen = SCR_TOTP;
- set_status("", 0, 0);
- }
- ngui_set_focus(&ui, ID_TOTP);
- return;
- }
- if (r == CHAT_LOGIN_OK) {
- wipe_secrets();
- resp_len = (unsigned int)strlen(resp);
- save_config();
- enter_main();
- return;
- }
- if (r == CHAT_LOGIN_DENIED && screen == SCR_TOTP) {
- /* A wrong TOTP code is also a 401. */
- set_status(login.error, 0, 1);
- ngui_input_set(&totp_in, "");
- return;
- }
- if (r == CHAT_LOGIN_DENIED) {
- memset(pass_in.text, 0, sizeof(pass_in.text));
- ngui_input_set(&pass_in, "");
- ngui_set_focus(&ui, ID_PASS);
- }
- if (r == CHAT_LOGIN_PASSKEY || r == CHAT_LOGIN_ERROR)
- wipe_secrets();
- if (r == CHAT_LOGIN_PASSKEY)
- screen = SCR_COOKIE;
- set_status(login.error, 0, 1);
- }
- static void use_cookie(void)
- {
- if (set_server(server_in.text) != 0) {
- set_status("Enter a server such as chat.example.com", 0, 1);
- return;
- }
- if (cfg_in.text[0])
- s_copy(cfg_path, cfg_in.text, sizeof(cfg_path));
- uhttp_jar_clear(&jar);
- {
- const char *c = cookie_in.text;
- /* Accept a pasted "Cookie: ..." header too. */
- if (strncmp(c, "Cookie:", 7) == 0 || strncmp(c, "cookie:", 7) == 0)
- c += 7;
- if (uhttp_jar_import(&jar, server_host, server_secure, c) <= 0) {
- set_status("Paste the cookie as name=value", 0, 1);
- return;
- }
- }
- check_session(0);
- if (screen == SCR_MAIN)
- ngui_input_set(&cookie_in, "");
- }
- static void sign_out(void)
- {
- /* Best effort: end the server session too. */
- if (server[0]) {
- s_copy(busy, "Signing out...", sizeof(busy));
- paint_now();
- api(0, "/auth/logout", 0);
- busy[0] = '\0';
- }
- go_login("Signed out");
- {
- static char out[CHAT_SERVER_MAX + 80];
- int n = chat_config_format(out, sizeof(out), server, "");
- if (n > 0)
- write_file(cfg_path, out, (unsigned int)n);
- }
- }
- static void load_config(void)
- {
- static char buf[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 256];
- char srv[CHAT_SERVER_MAX];
- int n, migrated = 0;
- n = read_file(cfg_path, buf, sizeof(buf));
- /* First start on a persistent volume: carry a session that an older
- * build saved in /share into /data once. */
- if (n <= 0 && cfg_is_default &&
- strcmp(cfg_path, DEFAULT_CFG_DATA) == 0) {
- n = read_file(DEFAULT_CFG_SHARE, buf, sizeof(buf));
- migrated = n > 0;
- }
- ngui_input_set(&cfg_in, cfg_path);
- if (n <= 0 || chat_config_parse(buf, (unsigned int)n, srv, sizeof(srv),
- saved_cookie,
- sizeof(saved_cookie)) != 0) {
- ngui_input_set(&server_in, "chat.cloudron.io");
- saved_cookie[0] = '\0';
- memset(buf, 0, sizeof(buf));
- return;
- }
- memset(buf, 0, sizeof(buf));
- ngui_input_set(&server_in, srv);
- if (set_server(srv) != 0 || !saved_cookie[0])
- return;
- uhttp_jar_import(&jar, server_host, server_secure, saved_cookie);
- saved_jar_changes = jar.changes;
- if (migrated)
- save_config();
- check_session(1);
- }
- /* ---- text layout ---- */
- static int line_h(void)
- {
- int h = ngui_text_line_height(&ui, ui.font_px, 0);
- return h > 0 ? h : 16;
- }
- static int text_w(const char *s, unsigned int n, int bold)
- {
- return (int)ngui_text_width_px(&ui, s, n, ui.font_px, bold, 0, 0);
- }
- /* Length of the next wrapped line of s (n bytes) for width maxw; *adv gets
- * the bytes to skip to the next line. */
- static unsigned int wrap_line(const char *s, unsigned int n, int maxw,
- unsigned int *adv)
- {
- unsigned int i = 0, end = 0, j;
- if (n && s[0] == '\n') {
- *adv = 1;
- return 0;
- }
- for (;;) {
- j = i;
- while (j < n && s[j] == ' ')
- j++;
- while (j < n && s[j] != ' ' && s[j] != '\n')
- j++;
- if (j == i)
- break;
- if (text_w(s, j, 0) > maxw) {
- if (end == 0) {
- /* One word wider than the line: split it. */
- unsigned int k = 1;
- while (k < j && text_w(s, k + 1, 0) <= maxw)
- k++;
- *adv = k;
- return k;
- }
- break;
- }
- end = j;
- i = j;
- if (j >= n || s[j] == '\n')
- break;
- }
- *adv = end;
- while (*adv < n && s[*adv] == ' ')
- (*adv)++;
- if (*adv < n && s[*adv] == '\n')
- (*adv)++;
- return end;
- }
- static int count_lines(const char *s, int maxw)
- {
- unsigned int n = (unsigned int)strlen(s), pos = 0, adv;
- int lines = 0;
- if (!n)
- return 0;
- while (pos < n) {
- wrap_line(s + pos, n - pos, maxw, &adv);
- if (!adv)
- adv = 1;
- pos += adv;
- lines++;
- }
- return lines;
- }
- #define AVATAR 32
- #define TEXT_X 52
- #define PAD_TOP 8
- #define PAD_GROUP 2
- static int same_day(const struct msg *a, const struct msg *b)
- {
- return strncmp(a->created, b->created, 10) == 0;
- }
- static int same_group(const struct msg *a, const struct msg *b)
- {
- unsigned int ta, tb;
- if (strcmp(a->user_id, b->user_id) != 0 || !same_day(a, b) ||
- b->reply[0] || b->action)
- return 0;
- /* HH:MM at offsets 11..15: within five minutes */
- ta = (unsigned int)atoi(a->created + 11) * 60 +
- (unsigned int)atoi(a->created + 14);
- tb = (unsigned int)atoi(b->created + 11) * 60 +
- (unsigned int)atoi(b->created + 14);
- return tb >= ta && tb - ta <= 5;
- }
- static void layout_msg(int i, int width)
- {
- struct msg *m = &msgs[i];
- int lh = line_h(), h, tw = width - TEXT_X - 12;
- int k;
- if (tw < 40)
- tw = 40;
- m->day_header = i == 0 || !same_day(&msgs[i - 1], m);
- m->compact = i > 0 && !m->day_header && same_group(&msgs[i - 1], m);
- h = m->compact ? PAD_GROUP : PAD_TOP + lh + 2;
- if (m->day_header)
- h += lh + 12;
- if (m->reply[0])
- h += lh + 2;
- h += count_lines(m->body, tw) * lh;
- for (k = 0; k < m->nimg; k++) {
- int dw, dh, state;
- unsigned int scale;
- chat_image_measure(m->img_url[k], tw, &dw, &dh, &scale,
- &state);
- h += dh + 6;
- }
- if (m->extra[0])
- h += lh + 2;
- h += 2;
- if (!m->compact && h < PAD_TOP + AVATAR + 4)
- h = PAD_TOP + AVATAR + 4;
- m->height = h;
- m->layout_w = width;
- }
- static int tl_width;
- static unsigned int laid_gen;
- static int laid_font = -1;
- /* Heights depend on the width, the font and the neighbours (grouping and
- * day headers), so any change re-lays out every message. */
- static int content_height(void)
- {
- int i, h = has_older || history_full ? 36 : 8;
- int all = laid_gen != msgs_gen || laid_font != line_h();
- for (i = 0; i < nmsg; i++) {
- if (all || msgs[i].layout_w != tl_width)
- layout_msg(i, tl_width);
- h += msgs[i].height;
- }
- laid_gen = msgs_gen;
- laid_font = line_h();
- return h + 8;
- }
- /* ---- drawing helpers ---- */
- static unsigned short avatar_color(const char *id)
- {
- static const unsigned short pal[] = {
- NGUI_RGB(0xd0, 0x5a, 0x5a), NGUI_RGB(0x5a, 0x9a, 0xd0),
- NGUI_RGB(0x5a, 0xb0, 0x70), NGUI_RGB(0xc0, 0x8a, 0x3a),
- NGUI_RGB(0x9a, 0x6a, 0xc8), NGUI_RGB(0x3a, 0xa8, 0xa8),
- NGUI_RGB(0xc8, 0x6a, 0xa0), NGUI_RGB(0x80, 0x90, 0x40),
- };
- unsigned int h = 0;
- while (*id)
- h = h * 31 + (unsigned char)*id++;
- return pal[h % (sizeof(pal) / sizeof(pal[0]))];
- }
- static void draw_avatar(int x, int y, int size, const char *name,
- const char *id, const char *pic)
- {
- struct ngui_rect r = { x, y, size, size };
- char ini[2];
- int tw;
- ngui_fill_round_rect(&ui, r, size / 2, size / 2, size / 2, size / 2,
- avatar_color(id));
- if (chat_avatar_draw(pic, x, y, size, avatar_color(id)))
- return;
- ini[0] = name[0] ? name[0] : '?';
- if (ini[0] >= 'a' && ini[0] <= 'z')
- ini[0] = (char)(ini[0] - 'a' + 'A');
- ini[1] = '\0';
- tw = text_w(ini, 1, 1);
- ngui_text_px(&ui, x + (size - tw) / 2, y + (size - line_h()) / 2, ini, 1,
- NGUI_RGB(0xff, 0xff, 0xff), ui.font_px, 1, 0, 0);
- }
- static void draw_dot(int x, int y, int d, unsigned short color, int filled)
- {
- struct ngui_rect r = { x, y, d, d };
- if (filled)
- ngui_fill_round_rect(&ui, r, d / 2, d / 2, d / 2, d / 2, color);
- else
- ngui_frame_round(&ui, r, d / 2, d / 2, d / 2, d / 2, 1, color);
- }
- static void draw_badge(int right, int y, int count)
- {
- char num[12] = "";
- int tw, w;
- struct ngui_rect r;
- if (count > 99)
- s_copy(num, "99+", sizeof(num));
- else
- s_cat_uint(num, (unsigned int)count, sizeof(num));
- tw = text_w(num, (unsigned int)strlen(num), 1);
- w = tw + 12;
- r.x = right - w;
- r.y = y;
- r.w = w;
- r.h = line_h() + 2;
- ngui_fill_round_rect(&ui, r, r.h / 2, r.h / 2, r.h / 2, r.h / 2,
- ui.theme.accent);
- ngui_text_px(&ui, r.x + 6, y + 1, num, (unsigned int)strlen(num),
- NGUI_RGB(0xff, 0xff, 0xff), ui.font_px, 1, 0, 0);
- }
- static void draw_lock(int x, int y, unsigned short c)
- {
- struct ngui_rect body = { x, y + 5, 9, 7 };
- struct ngui_rect shackle = { x + 2, y + 1, 5, 6 };
- ngui_frame_round(&ui, shackle, 2, 2, 0, 0, 1, c);
- ngui_fill_rect(&ui, body, c);
- }
- static void label(struct ngui_rect *body, const char *text)
- {
- struct ngui_rect r = ngui_cut_top(body, 20);
- ngui_text(&ui, r.x, r.y + 2, text, ui.theme.text_dim);
- }
- /* ---- login screens ---- */
- static struct ngui_rect card_rect(int h)
- {
- struct ngui_rect r;
- int w = ui.w - 40 < 460 ? ui.w - 40 : 460;
- if (w < 200)
- w = ui.w;
- r.w = w;
- r.h = h;
- r.x = (ui.w - w) / 2;
- r.y = (ui.h - h) / 2 > 10 ? (ui.h - h) / 2 : 10;
- return r;
- }
- static void field(struct ngui_rect *body, const char *text, unsigned int id,
- struct ngui_input *in, unsigned int next_id, int submit_act)
- {
- int r;
- label(body, text);
- r = ngui_text_input(&ui, id, ngui_cut_top(body, 30), in);
- ngui_cut_top(body, 8);
- if (r & NGUI_INPUT_NEXT)
- ngui_set_focus(&ui, next_id);
- if ((r & NGUI_INPUT_SUBMIT) && submit_act)
- action = submit_act;
- }
- static void draw_status_line(struct ngui_rect *body)
- {
- struct ngui_rect r = ngui_cut_top(body, 22);
- if (busy[0])
- ngui_text_ellipsis(&ui, r, r.x, r.y + 2, busy, ui.theme.accent);
- else if (status[0])
- ngui_text_ellipsis(&ui, r, r.x, r.y + 2, status,
- status_err ? ui.theme.error : ui.theme.text_dim);
- }
- static void notice(struct ngui_rect *body, const char *text)
- {
- struct ngui_rect r = ngui_cut_top(body, 18);
- ngui_text_ellipsis(&ui, r, r.x, r.y, text, ui.theme.text_dim);
- }
- static void draw_login(void)
- {
- struct ngui_rect all = { 0, 0, ui.w, ui.h };
- struct ngui_rect card, body, r, b;
- int h = screen == SCR_SERVER ? 380 : screen == SCR_COOKIE ? 400 :
- screen == SCR_TOTP ? 250 : 300;
- ngui_fill_rect(&ui, all, ui.theme.bg);
- card = card_rect(h);
- ngui_fill_rect(&ui, card, ui.theme.panel);
- ngui_frame(&ui, card, ui.theme.border);
- body = card;
- ngui_inset(&body, 18);
- r = ngui_cut_top(&body, 30);
- ngui_text_px(&ui, r.x, r.y, "NebOS Chat", 10, ui.theme.text, 22, 1, 0, 0);
- if (screen == SCR_SERVER) {
- field(&body, "Server", ID_SERVER, &server_in, ID_CFG,
- ACT_START_LOGIN);
- field(&body, "Config file (session cookie, RAM-only on /share)",
- ID_CFG, &cfg_in, ID_SERVER, ACT_START_LOGIN);
- r = ngui_cut_top(&body, 32);
- b = ngui_cut_left(&r, 110);
- if (ngui_button(&ui, ID_SIGNIN, b, "Sign in"))
- action = ACT_START_LOGIN;
- ngui_cut_left(&r, 10);
- b = ngui_cut_left(&r, 170);
- if (ngui_button(&ui, ID_COOKIE_MODE, b, "Paste a cookie..."))
- action = ACT_COOKIE_SCREEN;
- ngui_cut_top(&body, 8);
- draw_status_line(&body);
- notice(&body, "TLS certificates are not verified: only sign in");
- notice(&body, "on a trusted network. Passkeys and external SSO");
- notice(&body, "are not supported (use the cookie option).");
- } else if (screen == SCR_CRED || screen == SCR_TOTP) {
- r = ngui_cut_top(&body, 22);
- {
- char t[160];
- s_copy(t, "Sign in to ", sizeof(t));
- s_cat(t, login.app_name[0] ? login.app_name : "Chat",
- sizeof(t));
- s_cat(t, " at ", sizeof(t));
- s_cat(t, server_host, sizeof(t));
- ngui_text_ellipsis(&ui, r, r.x, r.y, t, ui.theme.text_dim);
- }
- if (screen == SCR_CRED) {
- field(&body, "Username or email", ID_USER, &user_in,
- ID_PASS, ACT_SUBMIT);
- field(&body, "Password", ID_PASS, &pass_in, ID_USER,
- ACT_SUBMIT);
- } else {
- field(&body, "Two-factor code (authenticator app)",
- ID_TOTP, &totp_in, ID_TOTP, ACT_SUBMIT_TOTP);
- }
- r = ngui_cut_top(&body, 32);
- b = ngui_cut_left(&r, 110);
- if (ngui_button(&ui, ID_SIGNIN, b, "Sign in"))
- action = screen == SCR_TOTP ? ACT_SUBMIT_TOTP : ACT_SUBMIT;
- ngui_cut_left(&r, 10);
- b = ngui_cut_left(&r, 90);
- if (ngui_button(&ui, ID_BACK, b, "Back"))
- action = ACT_BACK;
- ngui_cut_top(&body, 8);
- draw_status_line(&body);
- notice(&body, "The password is sent over unverified TLS and");
- notice(&body, "is never stored.");
- } else {
- field(&body, "Server", ID_SERVER, &server_in, ID_COOKIE,
- ACT_USE_COOKIE);
- field(&body, "Session cookie (e.g. connect.sid=s%3A...)",
- ID_COOKIE, &cookie_in, ID_CFG, ACT_USE_COOKIE);
- field(&body, "Config file", ID_CFG, &cfg_in, ID_SERVER,
- ACT_USE_COOKIE);
- r = ngui_cut_top(&body, 32);
- b = ngui_cut_left(&r, 130);
- if (ngui_button(&ui, ID_USE_COOKIE, b, "Use cookie"))
- action = ACT_USE_COOKIE;
- ngui_cut_left(&r, 10);
- b = ngui_cut_left(&r, 90);
- if (ngui_button(&ui, ID_BACK, b, "Back"))
- action = ACT_BACK;
- ngui_cut_top(&body, 8);
- draw_status_line(&body);
- notice(&body, "Copy the connect.sid cookie from a signed-in web");
- notice(&body, "browser. It is a bearer credential: it is saved");
- notice(&body, "in the config file until you sign out.");
- }
- }
- /* ---- main screen ---- */
- #define SIDE_ROW 38
- #define SIDE_HEAD 26
- static void draw_sidebar(struct ngui_rect r)
- {
- struct ngui_rect list, btns, b;
- int y, i, section, row_w, scrolls;
- int lh = line_h();
- ngui_fill_rect(&ui, r, ui.theme.panel);
- btns = ngui_cut_bottom(&r, 40);
- ngui_inset(&btns, 6);
- b = ngui_cut_left(&btns, (btns.w - 6) / 2);
- if (ngui_button(&ui, ID_BROWSE, b, "Browse"))
- action = ACT_BROWSE;
- ngui_cut_left(&btns, 6);
- if (ngui_button(&ui, ID_NEWDM, btns, "New DM"))
- action = ACT_NEWDM;
- list = r;
- side_scroll.content_h = 2 * SIDE_HEAD + nconv * SIDE_ROW + 8;
- ngui_scroll_begin(&ui, list, &side_scroll);
- ngui_scroll_wheel(&ui, list, &side_scroll);
- scrolls = side_scroll.content_h > side_scroll.view_h;
- row_w = list.w - (scrolls ? 16 : 0);
- y = list.y - side_scroll.offset;
- for (section = 0; section < 2; section++) {
- ngui_text_px(&ui, list.x + 10, y + 6,
- section ? "DIRECT MESSAGES" : "CHANNELS",
- section ? 15 : 8, ui.theme.text_dim, 12, 1, 0, 0);
- y += SIDE_HEAD;
- for (i = 0; i < nconv; i++) {
- struct conv *c = &convs[i];
- struct ngui_rect row = { list.x, y, row_w, SIDE_ROW - 2 };
- int hot, nx, right;
- if ((c->kind == 'd') != section)
- continue;
- hot = ui.inside && ngui_rect_contains(&row, ui.mouse_x,
- ui.mouse_y) &&
- ngui_rect_contains(&list, ui.mouse_x, ui.mouse_y);
- if (i == cur)
- ngui_fill_rect(&ui, row, ui.theme.selection);
- else if (hot)
- ngui_fill_rect(&ui, row, ui.theme.panel_alt);
- if (ui.pressed && modal == MODAL_NONE &&
- ngui_rect_contains(&row, ui.press_x, ui.press_y) &&
- ngui_rect_contains(&list, ui.press_x, ui.press_y)) {
- action = ACT_OPEN_CONV;
- action_arg = i;
- }
- nx = list.x + 26;
- if (c->kind == 'd') {
- unsigned short pc = c->presence == 'o' ?
- NGUI_RGB(0x40, 0xc0, 0x60) :
- c->presence == 'a' ?
- NGUI_RGB(0xe0, 0xb0, 0x30) :
- ui.theme.text_dim;
- draw_dot(list.x + 10, y + 6 + (lh - 9) / 2, 9, pc,
- c->presence != 'f');
- } else if (c->kind == 'p') {
- draw_lock(list.x + 9, y + 4, ui.theme.text_dim);
- } else {
- ngui_text(&ui, list.x + 10, y + 4, "#",
- ui.theme.text_dim);
- }
- right = list.x + row_w - 8;
- if (c->unread > 0) {
- draw_badge(right, y + 3, c->unread);
- right -= 40;
- }
- {
- struct ngui_rect nr = { nx, y, right - nx, lh + 6 };
- ngui_push_clip(&ui, nr);
- ngui_text_px(&ui, nx, y + 4, c->name,
- (unsigned int)strlen(c->name),
- ui.theme.text, ui.font_px,
- c->unread > 0, 0, 0);
- ngui_pop_clip(&ui);
- }
- if (c->preview[0]) {
- struct ngui_rect pr = { nx, y + 4 + lh,
- list.x + row_w - 8 - nx,
- lh };
- ngui_push_clip(&ui, pr);
- ngui_text_px(&ui, nx, y + 4 + lh, c->preview,
- (unsigned int)strlen(c->preview),
- ui.theme.text_dim, 12, 0, 0, 0);
- ngui_pop_clip(&ui);
- }
- y += SIDE_ROW;
- }
- }
- if (!nconv)
- ngui_text(&ui, list.x + 10, list.y + SIDE_HEAD + 6,
- "(none yet)", ui.theme.text_dim);
- ngui_scroll_end(&ui, list, &side_scroll);
- }
- static void draw_message(struct msg *m, int x, int y, int width)
- {
- int lh = line_h(), tx = x + TEXT_X, tw = width - TEXT_X - 12;
- unsigned int n, pos = 0, adv;
- if (tw < 40)
- tw = 40;
- if (m->day_header) {
- char d[16];
- int dw;
- struct ngui_rect line = { x + 12, y + 6 + lh / 2, width - 24, 1 };
- s_copy(d, m->created, 11);
- dw = text_w(d, (unsigned int)strlen(d), 0);
- ngui_fill_rect(&ui, line, ui.theme.border);
- ngui_fill_rect(&ui, (struct ngui_rect){ x + (width - dw) / 2 - 8,
- y + 4, dw + 16, lh + 4 }, ui.theme.bg);
- ngui_text(&ui, x + (width - dw) / 2, y + 6, d, ui.theme.text_dim);
- y += lh + 12;
- }
- if (!m->compact) {
- char tm[8];
- int aw;
- y += PAD_TOP;
- draw_avatar(x + 10, y, AVATAR, m->author, m->user_id,
- m->author_pic);
- ngui_text_px(&ui, tx, y, m->author, (unsigned int)strlen(m->author),
- ui.theme.text, ui.font_px, 1, 0, 0);
- aw = text_w(m->author, (unsigned int)strlen(m->author), 1);
- s_copy(tm, m->created + 11, 6);
- ngui_text_px(&ui, tx + aw + 10, y, tm, (unsigned int)strlen(tm),
- ui.theme.text_dim, 12, 0, 0, 0);
- y += lh + 2;
- } else {
- y += PAD_GROUP;
- }
- if (m->reply[0]) {
- struct ngui_rect rr = { tx, y, tw, lh };
- ngui_fill_rect(&ui, (struct ngui_rect){ tx, y + 1, 3, lh - 2 },
- ui.theme.accent);
- ngui_text_ellipsis(&ui, rr, tx + 8, y, m->reply,
- ui.theme.text_dim);
- y += lh + 2;
- }
- n = (unsigned int)strlen(m->body);
- while (pos < n) {
- unsigned int len = wrap_line(m->body + pos, n - pos, tw, &adv);
- if (!adv)
- adv = 1;
- ngui_text_px(&ui, tx, y, m->body + pos, len,
- m->action ? ui.theme.accent : ui.theme.text,
- ui.font_px, 0, m->action, 0);
- pos += adv;
- y += lh;
- }
- {
- int k;
- for (k = 0; k < m->nimg; k++) {
- int dw, dh, state;
- unsigned int scale;
- chat_image_measure(m->img_url[k], tw, &dw, &dh,
- &scale, &state);
- chat_image_draw(m->img_url[k], tx, y, tw);
- y += dh + 6;
- }
- }
- if (m->extra[0]) {
- struct ngui_rect er = { tx, y + 2, tw, lh };
- ngui_text_ellipsis(&ui, er, tx, y + 2, m->extra,
- ui.theme.text_dim);
- }
- }
- static void draw_timeline(struct ngui_rect r)
- {
- int i, y, total, scrolls, width;
- int was_bottom;
- ngui_fill_rect(&ui, r, ui.theme.bg);
- if (cur < 0) {
- ngui_text(&ui, r.x + 20, r.y + 20,
- nconv ? "Select a conversation" :
- "No conversations yet: browse the public channels",
- ui.theme.text_dim);
- return;
- }
- tl_width = r.w - 16;
- total = content_height();
- tl_scroll.content_h = total;
- ngui_scroll_begin(&ui, r, &tl_scroll);
- if (ngui_scroll_wheel(&ui, r, &tl_scroll))
- last_input_ms = u_ticks_ms();
- scrolls = total > r.h;
- width = r.w - (scrolls ? 16 : 0);
- if (width != tl_width) {
- tl_width = width;
- total = content_height();
- tl_scroll.content_h = total;
- }
- /* Scrolling to the very top pages in older history by itself (the
- * button stays for the pointer). Rate-limited so a failing request
- * cannot spin. */
- if (has_older && !history_full && scrolls && tl_scroll.offset <= 0 &&
- !offline && (unsigned int)(u_ticks_ms() - last_older_ms) > 1500)
- action = ACT_OLDER;
- was_bottom = tl_scroll.offset >= total - r.h - 4;
- at_bottom = was_bottom || !scrolls;
- if (at_bottom)
- new_below = 0;
- y = r.y - tl_scroll.offset;
- if (has_older || history_full) {
- struct ngui_rect b = { r.x + (width - 200) / 2, y + 4, 200, 28 };
- if (history_full) {
- ngui_text(&ui, b.x + 4, b.y + 6,
- "History limit reached", ui.theme.text_dim);
- } else if (b.y + b.h > r.y &&
- (!ui.pressed ||
- ngui_rect_contains(&r, ui.press_x, ui.press_y))) {
- if (ngui_button(&ui, ID_OLDER, b, "Load older messages"))
- action = ACT_OLDER;
- }
- y += 36;
- } else {
- y += 8;
- }
- for (i = 0; i < nmsg; i++) {
- struct msg *m = &msgs[i];
- if (y + m->height > r.y && y < r.y + r.h)
- draw_message(m, r.x, y, width);
- y += m->height;
- }
- if (!nmsg)
- ngui_text(&ui, r.x + 20, r.y + 50,
- "No messages yet - say hello!", ui.theme.text_dim);
- ngui_scroll_end(&ui, r, &tl_scroll);
- if (new_below > 0 && !at_bottom) {
- char t[40] = "";
- struct ngui_rect b;
- s_cat_uint(t, (unsigned int)new_below, sizeof(t));
- s_cat(t, new_below == 1 ? " new message" : " new messages",
- sizeof(t));
- b.w = text_w(t, (unsigned int)strlen(t), 0) + 30;
- b.h = 26;
- b.x = r.x + (width - b.w) / 2;
- b.y = r.y + r.h - b.h - 8;
- if (ngui_button(&ui, ID_NEWMSG, b, t))
- scroll_to_end();
- }
- }
- static int total_unread(void)
- {
- int i, n = 0;
- for (i = 0; i < nconv; i++)
- n += convs[i].unread > 0 ? convs[i].unread : 0;
- return n;
- }
- static void draw_modal(void)
- {
- struct ngui_rect all = { 0, 0, ui.w, ui.h };
- struct ngui_rect card, body, r, list;
- int w = ui.w * 7 / 10, h = ui.h * 8 / 10, i, y, shown = 0, vis;
- int lh = line_h();
- (void)all;
- if (w < 320)
- w = ui.w - 20;
- if (h < 240)
- h = ui.h - 20;
- card.w = w;
- card.h = h;
- card.x = (ui.w - w) / 2;
- card.y = (ui.h - h) / 2;
- ngui_fill_rect(&ui, card, ui.theme.panel);
- ngui_frame(&ui, card, ui.theme.accent);
- body = card;
- ngui_inset(&body, 14);
- r = ngui_cut_top(&body, 28);
- ngui_text_px(&ui, r.x, r.y, modal == MODAL_BROWSE ?
- "Browse public channels" : "New direct message",
- modal == MODAL_BROWSE ? 22 : 18, ui.theme.text, 18, 1, 0, 0);
- if (ngui_button(&ui, ID_MODAL_CLOSE,
- (struct ngui_rect){ r.x + r.w - 80, r.y, 80, 26 },
- "Close"))
- modal = MODAL_NONE;
- ngui_cut_top(&body, 6);
- filter_in.placeholder = "Filter... (Up/Down, Enter)";
- for (i = 0; i < npick; i++)
- if (!filter_in.text[0] || strstr(picks[i].name, filter_in.text) ||
- strstr(picks[i].sub, filter_in.text))
- shown++;
- {
- int k = ngui_key_peek(&ui), fr;
- if (k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) {
- ngui_key(&ui);
- modal_sel += k == NGUI_KEY_UP ? -1 : 1;
- }
- fr = ngui_text_input(&ui, ID_FILTER, ngui_cut_top(&body, 30),
- &filter_in);
- if (fr & NGUI_INPUT_CHANGED) {
- modal_scroll.offset = 0;
- modal_sel = 0;
- }
- if (modal_sel >= shown)
- modal_sel = shown - 1;
- if (modal_sel < 0)
- modal_sel = 0;
- if ((fr & NGUI_INPUT_SUBMIT) && shown) {
- int vis = 0;
- for (i = 0; i < npick; i++) {
- if (filter_in.text[0] &&
- !strstr(picks[i].name, filter_in.text) &&
- !strstr(picks[i].sub, filter_in.text))
- continue;
- if (vis++ == modal_sel) {
- action = modal == MODAL_BROWSE ?
- ACT_JOIN : ACT_OPEN_DM;
- action_arg = i;
- break;
- }
- }
- ngui_set_focus(&ui, ID_FILTER);
- }
- if ((fr & NGUI_INPUT_CANCEL) && !(fr & NGUI_INPUT_NEXT))
- modal = MODAL_NONE;
- }
- ngui_cut_top(&body, 8);
- list = body;
- ngui_fill_rect(&ui, list, ui.theme.bg);
- modal_scroll.content_h = shown * 44;
- ngui_scroll_begin(&ui, list, &modal_scroll);
- ngui_scroll_wheel(&ui, list, &modal_scroll);
- y = list.y - modal_scroll.offset;
- vis = 0;
- for (i = 0; i < npick; i++) {
- struct pick *p = &picks[i];
- struct ngui_rect row, b;
- if (filter_in.text[0] && !strstr(p->name, filter_in.text) &&
- !strstr(p->sub, filter_in.text))
- continue;
- if (vis++ == modal_sel) {
- if (y < list.y)
- modal_scroll.offset -= list.y - y;
- else if (y + 44 > list.y + list.h)
- modal_scroll.offset += y + 44 - list.y - list.h;
- y = list.y + (vis - 1) * 44 - modal_scroll.offset;
- ngui_fill_rect(&ui, (struct ngui_rect){ list.x, y,
- list.w - 16, 43 },
- ui.theme.selection);
- }
- row.x = list.x;
- row.y = y;
- row.w = list.w - 16;
- row.h = 42;
- if (y + 44 > list.y && y < list.y + list.h) {
- ngui_fill_rect(&ui, (struct ngui_rect){ row.x, y + 43,
- row.w, 1 }, ui.theme.border);
- if (modal == MODAL_NEWDM)
- draw_avatar(row.x + 8, y + 6, 30, p->name, p->id,
- p->pic);
- ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48, y,
- row.w - 160, lh + 4 },
- row.x + 48, y + 4,
- p->name,
- ui.theme.text);
- ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48,
- y + 4 + lh, row.w - 160, lh },
- row.x + 48, y + 4 + lh, p->sub,
- ui.theme.text_dim);
- if (modal == MODAL_BROWSE)
- ngui_text(&ui, row.x + 14, y + 12, "#",
- ui.theme.text_dim);
- b.x = row.x + row.w - 100;
- b.y = y + 8;
- b.w = 92;
- b.h = 26;
- if ((!ui.pressed ||
- ngui_rect_contains(&list, ui.press_x, ui.press_y)) &&
- ngui_button(&ui, ID_MODAL_ROW + (unsigned int)i, b,
- modal == MODAL_BROWSE ? "Join" : "Message")) {
- action = modal == MODAL_BROWSE ? ACT_JOIN :
- ACT_OPEN_DM;
- action_arg = i;
- }
- }
- y += 44;
- }
- if (!shown)
- ngui_text(&ui, list.x + 12, list.y + 12,
- npick ? "Nothing matches the filter" :
- modal == MODAL_BROWSE ?
- "You are in every public channel" : "Nobody else here",
- ui.theme.text_dim);
- ngui_scroll_end(&ui, list, &modal_scroll);
- }
- /* Keyboard shortcuts, handled before the composer swallows the keys:
- * PgUp/PgDn scroll the timeline; Ctrl+B browse, Ctrl+N new DM, Ctrl+R
- * refresh. With the composer unfocused (Esc): Up/Down switch conversations,
- * Home/End jump in the timeline, and typing refocuses the composer. */
- static void main_keys(void)
- {
- for (;;) {
- int k = ngui_key_peek(&ui);
- if (!k)
- return;
- if (k == NGUI_KEY_PAGE_UP || k == NGUI_KEY_PAGE_DOWN) {
- ngui_scroll_keys(&ui, &tl_scroll);
- continue;
- }
- if (k == 0x02 || k == 0x0E || k == 0x12) {
- ngui_key(&ui);
- action = k == 0x02 ? ACT_BROWSE : k == 0x0E ? ACT_NEWDM :
- ACT_REFRESH;
- return;
- }
- if (ui.focus)
- return;
- if (k == NGUI_KEY_HOME) {
- ngui_key(&ui);
- tl_scroll.offset = 0;
- } else if (k == NGUI_KEY_END) {
- ngui_key(&ui);
- scroll_to_end();
- } else if (k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) {
- int order[MAX_CONV], n = 0, i, pos = -1, sec;
- ngui_key(&ui);
- /* Sidebar order: channels first, then DMs. */
- for (sec = 0; sec < 2; sec++)
- for (i = 0; i < nconv; i++)
- if ((convs[i].kind == 'd') == sec) {
- if (i == cur)
- pos = n;
- order[n++] = i;
- }
- if (!n)
- continue;
- pos = pos < 0 ? 0 : k == NGUI_KEY_UP ?
- (pos > 0 ? pos - 1 : 0) :
- (pos + 1 < n ? pos + 1 : n - 1);
- if (order[pos] != cur) {
- action = ACT_OPEN_CONV;
- action_arg = order[pos];
- return;
- }
- } else if (k >= 0x20 && k <= 0x7E && cur >= 0) {
- ngui_set_focus(&ui, ID_COMPOSE);
- return;
- } else {
- return;
- }
- }
- }
- static void draw_main(void)
- {
- struct ngui_rect all = { 0, 0, ui.w, ui.h };
- struct ngui_rect top, side, bottom, comp, stat, b, tl;
- int side_w = ui.w / 4;
- char t[200];
- unsigned int saved_pressed = ui.pressed;
- /* Nothing under an open modal reacts to the pointer. */
- if (modal != MODAL_NONE)
- ui.pressed = 0;
- if (side_w < 150)
- side_w = 150;
- if (side_w > 260)
- side_w = 260;
- ngui_fill_rect(&ui, all, ui.theme.bg);
- /* top bar */
- top = ngui_cut_top(&all, 38);
- ngui_fill_rect(&ui, top, ui.theme.panel_alt);
- ngui_fill_rect(&ui, (struct ngui_rect){ top.x, top.y + top.h - 1, top.w,
- 1 }, ui.theme.border);
- {
- struct ngui_rect tb = top;
- ngui_inset(&tb, 6);
- b = ngui_cut_right(&tb, 86);
- if (ngui_button(&ui, ID_SIGNOUT, b, "Sign out"))
- action = ACT_SIGNOUT;
- ngui_cut_right(&tb, 6);
- b = ngui_cut_right(&tb, 80);
- if (ngui_button(&ui, ID_REFRESH, b, "Refresh"))
- action = ACT_REFRESH;
- t[0] = '\0';
- if (cur >= 0) {
- s_cat(t, convs[cur].kind == 'd' ? "@ " : "# ", sizeof(t));
- s_cat(t, convs[cur].name, sizeof(t));
- } else {
- s_cat(t, "Chat", sizeof(t));
- }
- ngui_cut_right(&tb, 10);
- ngui_push_clip(&ui, tb);
- ngui_text_px(&ui, tb.x + 4, tb.y + (tb.h - 20) / 2, t,
- (unsigned int)strlen(t), ui.theme.text, 18, 1, 0, 0);
- ngui_pop_clip(&ui);
- }
- if (modal == MODAL_NONE) {
- /* A closed modal leaves its filter focused: hand the keyboard
- * back to the composer. */
- if (ui.focus == ID_FILTER)
- ngui_set_focus(&ui, cur >= 0 ? ID_COMPOSE : 0);
- main_keys();
- }
- /* bottom: composer + status bar */
- bottom = ngui_cut_bottom(&all, 70);
- ngui_fill_rect(&ui, bottom, ui.theme.panel);
- ngui_fill_rect(&ui, (struct ngui_rect){ bottom.x, bottom.y, bottom.w, 1 },
- ui.theme.border);
- stat = ngui_cut_bottom(&bottom, 24);
- comp = bottom;
- ngui_inset(&comp, 7);
- b = ngui_cut_right(&comp, 80);
- compose_in.disabled = cur < 0;
- compose_in.placeholder = cur < 0 ? "" : "Type a message...";
- if (ngui_text_input(&ui, ID_COMPOSE,
- (struct ngui_rect){ comp.x, comp.y, comp.w - 8,
- comp.h }, &compose_in) &
- NGUI_INPUT_SUBMIT)
- action = ACT_SEND;
- if (ngui_button(&ui, ID_SEND, b, "Send") && cur >= 0)
- action = ACT_SEND;
- ngui_fill_rect(&ui, stat, ui.theme.panel_alt);
- {
- struct ngui_rect sr = stat;
- int un = total_unread();
- ngui_inset(&sr, 3);
- if (offline) {
- b = ngui_cut_right(&sr, 70);
- if (ngui_button(&ui, ID_RETRY, b, "Retry"))
- action = ACT_RETRY;
- }
- t[0] = '\0';
- if (busy[0]) {
- s_cat(t, busy, sizeof(t));
- } else {
- s_cat(t, status[0] ? status : "Connected", sizeof(t));
- if (offline && retry_at) {
- int left = (int)(retry_at - u_ticks_ms());
- if (left > 0) {
- s_cat(t, " (retry in ", sizeof(t));
- s_cat_uint(t, (unsigned int)(left + 999) / 1000,
- sizeof(t));
- s_cat(t, " s)", sizeof(t));
- }
- }
- }
- s_cat(t, " \xb7 ", sizeof(t));
- s_cat(t, server_secure ? "TLS unverified" : "no TLS", sizeof(t));
- if (me_name[0]) {
- s_cat(t, " \xb7 ", sizeof(t));
- s_cat(t, me_name, sizeof(t));
- }
- if (un) {
- s_cat(t, " \xb7 ", sizeof(t));
- s_cat_uint(t, (unsigned int)un, sizeof(t));
- s_cat(t, " unread", sizeof(t));
- }
- ngui_text_ellipsis(&ui, sr, sr.x + 4, sr.y + 1, t,
- busy[0] ? ui.theme.accent :
- (offline || status_err) ? ui.theme.error :
- ui.theme.text_dim);
- }
- side = ngui_cut_left(&all, side_w);
- ngui_fill_rect(&ui, (struct ngui_rect){ side.x + side.w - 1, side.y, 1,
- side.h }, ui.theme.border);
- side.w -= 1;
- tl = all;
- if (modal == MODAL_NONE) {
- draw_sidebar(side);
- draw_timeline(tl);
- } else {
- draw_sidebar(side);
- draw_timeline(tl);
- action = ACT_NONE;
- ui.pressed = saved_pressed;
- draw_modal();
- }
- }
- /* ---- frame / main loop ---- */
- static void draw(void)
- {
- if (screen == SCR_MAIN)
- draw_main();
- else
- draw_login();
- }
- /* Present a frame now (status text before a blocking network call). */
- static void paint_now(void)
- {
- int saved_action = action, saved_arg = action_arg;
- ngui_invalidate(&ui);
- if (ngui_begin(&ui)) {
- draw();
- ngui_end(&ui);
- }
- action = saved_action;
- action_arg = saved_arg;
- }
- static void run_action(void)
- {
- int a = action, arg = action_arg;
- action = ACT_NONE;
- switch (a) {
- case ACT_START_LOGIN:
- start_login();
- break;
- case ACT_SUBMIT:
- submit_login(0);
- break;
- case ACT_SUBMIT_TOTP:
- submit_login(1);
- break;
- case ACT_USE_COOKIE:
- use_cookie();
- break;
- case ACT_COOKIE_SCREEN:
- screen = SCR_COOKIE;
- set_status("", 0, 0);
- ngui_set_focus(&ui, ID_COOKIE);
- break;
- case ACT_BACK:
- wipe_secrets();
- screen = SCR_SERVER;
- set_status("", 0, 0);
- ngui_set_focus(&ui, ID_SERVER);
- break;
- case ACT_SEND:
- send_message();
- break;
- case ACT_REFRESH:
- case ACT_RETRY:
- backoff_ms = 0;
- retry_at = 0;
- chat_media_retry();
- s_copy(busy, "Refreshing...", sizeof(busy));
- paint_now();
- busy[0] = '\0';
- if (offline && !me_id[0]) {
- check_session(1);
- break;
- }
- if (load_directory() == 0) {
- if (cur >= 0)
- open_conv(cur);
- else if (nconv)
- open_conv(0);
- }
- next_dir_poll = u_ticks_ms() + POLL_DIR_MS;
- break;
- case ACT_SIGNOUT:
- sign_out();
- break;
- case ACT_OPEN_CONV:
- if (arg != cur)
- open_conv(arg);
- break;
- case ACT_OLDER:
- load_older();
- break;
- case ACT_BROWSE:
- load_picks(0);
- break;
- case ACT_NEWDM:
- load_picks(1);
- break;
- case ACT_JOIN:
- case ACT_OPEN_DM:
- pick_action(arg);
- break;
- }
- ngui_invalidate(&ui);
- }
- static void poll_tick(void)
- {
- unsigned int now = u_ticks_ms();
- int focused = ui.focused;
- if (screen != SCR_MAIN || modal != MODAL_NONE)
- return;
- if (offline) {
- if (retry_at && (int)(now - retry_at) >= 0) {
- retry_at = 0;
- action = ACT_RETRY;
- run_action();
- }
- return;
- }
- /* Do not interrupt typing or scrolling. */
- if ((unsigned int)(now - last_input_ms) < TYPING_HOLD_MS)
- return;
- if ((int)(now - next_dir_poll) >= 0) {
- load_directory();
- next_dir_poll = now + (focused ? POLL_DIR_MS : POLL_DIR_IDLE_MS);
- next_conv_poll = now; /* follow with the conversation */
- }
- if (cur >= 0 && !offline && (int)(now - next_conv_poll) >= 0) {
- poll_conv();
- next_conv_poll = u_ticks_ms() +
- (focused ? POLL_CONV_MS : POLL_CONV_IDLE_MS);
- }
- /* An open TCP socket pauses the board's net-dev watcher: only keep
- * the connection while the user is actively chatting. */
- if (http.connected &&
- (!focused || (unsigned int)(u_ticks_ms() - last_input_ms) >
- KEEPALIVE_IDLE_MS) &&
- (unsigned int)(u_ticks_ms() - last_net_ms) > 200)
- net_drop();
- }
- void _start(const char *arg)
- {
- struct win_info wi;
- unsigned int w = 980, h = 660;
- resp = (char *)malloc(RESP_CAP);
- jnodes = (struct ujson_node *)malloc(sizeof(struct ujson_node) *
- JSON_NODES);
- jsbuf = (char *)malloc(JSON_SCAP);
- if (!resp || !jnodes || !jsbuf) {
- u_puts("chat: out of memory\n");
- u_exit(1);
- }
- ujson_init(&json, jnodes, JSON_NODES, jsbuf, JSON_SCAP);
- uhttp_init(&http);
- http.user_agent = "NebOS-Chat/1.0 (uhttp)";
- uhttp_jar_init(&jar);
- if (u_win_create(w, h, "Chat", &wi) != 0 &&
- u_win_create(w = 780, h = 540, "Chat", &wi) != 0 &&
- u_win_create(w = 600, h = 420, "Chat", &wi) != 0) {
- u_puts("chat: no graphics window\n");
- u_exit(1);
- }
- ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
- ngui_font_attach(&ui);
- server_in.placeholder = "chat.example.com";
- user_in.placeholder = "username";
- pass_in.secret = 1;
- totp_in.placeholder = "123456";
- cookie_in.placeholder = "connect.sid=...";
- if (arg && arg[0]) {
- s_copy(cfg_path, arg, sizeof(cfg_path));
- } else {
- s_copy(cfg_path, default_cfg_path(), sizeof(cfg_path));
- cfg_is_default = 1;
- }
- ngui_set_focus(&ui, ID_SERVER);
- last_input_ms = 0;
- /* First frame, then the (possibly slow) session check. */
- paint_now();
- load_config();
- for (;;) {
- int redraw;
- redraw = ngui_begin(&ui);
- if (ui.key_head != ui.key_tail || ui.pressed || ui.scroll_y) {
- last_input_ms = u_ticks_ms();
- if (screen == SCR_MAIN && !offline)
- maybe_save_cookie();
- }
- if (redraw) {
- draw();
- ngui_end(&ui);
- } else {
- ngui_end_ex(&ui, 0);
- }
- if (action != ACT_NONE)
- run_action();
- else
- poll_tick();
- chat_media_tick();
- /* The offline retry countdown needs a once-a-second repaint. */
- if (offline && screen == SCR_MAIN) {
- static unsigned int last_tick;
- if (u_ticks_ms() - last_tick >= 1000) {
- last_tick = u_ticks_ms();
- ngui_invalidate(&ui);
- }
- }
- u_sleep_ms(10);
- }
- }
|