Просмотр исходного кода

chat: render link preview cards

Johannes Zellner 2 дней назад
Родитель
Сommit
a09b22571c
7 измененных файлов с 430 добавлено и 17 удалено
  1. 12 5
      AGENTS.md
  2. 1 1
      docs/graphics.html
  3. 0 0
      docs/network.html
  4. 1 1
      docs/userland.html
  5. 28 1
      tools/mock_chat.py
  6. 2 0
      tools/qmp_chat_test.py
  7. 386 9
      user/apps/chat/ucmd_chat.c

+ 12 - 5
AGENTS.md

@@ -1883,7 +1883,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   unread badges, presence dots and previews; a timeline with circular
   unread badges, presence dots and previews; a timeline with circular
   profile-picture avatars (initials until the picture loads, or when there is
   profile-picture avatars (initials until the picture loads, or when there is
   none), author grouping, UTC times, day headers, reply snippets, inline
   none), author grouping, UTC times, day headers, reply snippets, inline
-  image attachments/link-preview images and an attachments/thread/reaction
+  image attachments, link-preview cards (thumbnail, site, title and
+  description, matching the web client; clicking one opens the link in the
+  browser) and an attachments/thread/reaction
   line; a composer; browse/join and new-DM pickers.  It talks to the Chat REST
   line; a composer; browse/join and new-DM pickers.  It talks to the Chat REST
   API (`/api/me`, `/api/channels`, `/api/dms`, `/api/channels/public`,
   API (`/api/me`, `/api/channels`, `/api/dms`, `/api/channels/public`,
   `/api/users`, messages with `?limit=50`, `&before=` and `&after=`, POST
   `/api/users`, messages with `?limit=50`, `&before=` and `&after=`, POST
@@ -1899,7 +1901,11 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   32x32 (`img_options.max_w/h`), which keeps the square source the circular
   32x32 (`img_options.max_w/h`), which keeps the square source the circular
   mask expects while a large JPEG avatar gets a reduced IDCT instead of a
   mask expects while a large JPEG avatar gets a reduced IDCT instead of a
   full 512x512 decode.  The in-tree image library (PNG/JPEG/GIF first
   full 512x512 decode.  The in-tree image library (PNG/JPEG/GIF first
-  frame/BMP/TGA/PNM/ICO/PAM) is the fallback for both.  They live in a
+  frame/BMP/TGA/PNM/ICO/PAM) is the fallback for both.  A link preview is a
+  card under the message (Open Graph site name, bold title and description
+  from the server's `preview` object) with an optional 120x72 thumbnail; a
+  thumbnail that cannot be fetched or decoded (for example WebP/AVIF) is
+  hidden and the text card stays.  They live in a
   16-entry, 6 MB message-image LRU plus a 64-entry avatar cache.  The fetch
   16-entry, 6 MB message-image LRU plus a 64-entry avatar cache.  The fetch
   is capped at 4 MB and the decoder at 4 MP / 12 MB of scratch.  The helper
   is capped at 4 MB and the decoder at 4 MP / 12 MB of scratch.  The helper
   is stopped when the window loses focus, so its TCP socket does not pause
   is stopped when the window loses focus, so its TCP socket does not pause
@@ -2987,9 +2993,10 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     `/share/chat.cfg` without a `/data` mount) is a bearer credential
     `/share/chat.cfg` without a `/data` mount) is a bearer credential
     (persistent on `/data`, RAM-only on `/share`; concurrent chat windows
     (persistent on `/data`, RAM-only on `/share`; concurrent chat windows
     share the file).  No threads, reactions, polls, search, edits or deletes
     share the file).  No threads, reactions, polls, search, edits or deletes
-    beyond what a reload shows; image attachments and link-preview images
-    render inline up to the 4 MB fetch / 4 MP decode caps (first GIF frame;
-    WebP/AVIF/SVG are not decoded), file attachments are still text-only,
+    beyond what a reload shows; image attachments and link-preview
+    thumbnails render up to the 4 MB fetch / 4 MP decode caps, a card whose
+    thumbnail format is unsupported (WebP/AVIF/SVG) keeps its title and
+    description, file attachments are still text-only,
     messages over 4 KB are truncated, history holds 240 messages, times are
     messages over 4 KB are truncated, history holds 240 messages, times are
     UTC and text is Latin-1.  REST calls still block the UI for their
     UTC and text is Latin-1.  REST calls still block the UI for their
     duration; message images decode in the `curl __serve` helper (480x320
     duration; message images decode in the `curl __serve` helper (480x320

+ 1 - 1
docs/graphics.html

@@ -419,7 +419,7 @@
 			</div>
 			</div>
 			<div class="card">
 			<div class="card">
 				<h3>chat</h3>
 				<h3>chat</h3>
-				<p>Cloudron Chat client: native OIDC login, channel/DM sidebar with unread badges and presence dots, a wrapped timeline with avatars, day headers and reply snippets, a composer and browse/new-DM pickers. Media downloads use a warm <code>curl __serve</code> helper; message images are also decoded there (480&times;320 bounds), while avatars decode at 32&times;32 on the chat thread, so the window keeps drawing. Saved sessions resume from <code>/data</code>. The top-bar <em>Chat</em> button launches it.</p>
+				<p>Cloudron Chat client: native OIDC login, channel/DM sidebar with unread badges and presence dots, a wrapped timeline with avatars, day headers, reply snippets and link-preview cards (site, title, description and an optional thumbnail; clicking one opens the link in the browser), a composer and browse/new-DM pickers. Media downloads use a warm <code>curl __serve</code> helper; message images are also decoded there (480&times;320 bounds), while avatars decode at 32&times;32 on the chat thread, so the window keeps drawing. Saved sessions resume from <code>/data</code>. The top-bar <em>Chat</em> button launches it.</p>
 			</div>
 			</div>
 			<div class="card">
 			<div class="card">
 				<h3>disks</h3>
 				<h3>disks</h3>

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
docs/network.html


+ 1 - 1
docs/userland.html

@@ -349,7 +349,7 @@
 			<li><strong>files</strong> — browser for the VFS; opens text in <code>edit</code>, images in <code>view</code>, HTML in <code>browser</code>. First user of ngui.</li>
 			<li><strong>files</strong> — browser for the VFS; opens text in <code>edit</code>, images in <code>view</code>, HTML in <code>browser</code>. First user of ngui.</li>
 			<li><strong>disks</strong> — storage manager (top-bar <em>Disks</em> button, or the <em>Disks</em> button in <code>files</code>): devices, MBR partitions and mounts; per-volume mount name, read-only and automount saved to <code>/data/MOUNTS.CFG</code>; Format and Install NebOS dialogs that run <code>format -y</code>/<code>install -y</code> on a private tty and show the log. See <a href="filesystems.html#disks">Filesystems → Storage manager</a>.</li>
 			<li><strong>disks</strong> — storage manager (top-bar <em>Disks</em> button, or the <em>Disks</em> button in <code>files</code>): devices, MBR partitions and mounts; per-volume mount name, read-only and automount saved to <code>/data/MOUNTS.CFG</code>; Format and Install NebOS dialogs that run <code>format -y</code>/<code>install -y</code> on a private tty and show the log. See <a href="filesystems.html#disks">Filesystems → Storage manager</a>.</li>
 			<li><strong>gallery</strong> — live widget and primitive showcase; the real app ships in the pack.</li>
 			<li><strong>gallery</strong> — live widget and primitive showcase; the real app ships in the pack.</li>
-			<li><strong>chat</strong> — native Cloudron Chat client (top-bar <em>Chat</em> button, or <code>chat [config-path]</code>): username/password/TOTP login through the Cloudron OIDC API or a pasted session cookie, channels and DMs with unread badges and presence, history with older paging, inline image attachments and profile-picture avatars, sending, REST polling, read markers, browse/join and new DM.  The session cookie (never the password) is saved in <code>/data/CHAT.CFG</code> when the persistent volume is mounted, or in the RAM-only <code>/share/chat.cfg</code> otherwise.  Keys: Enter sends, PgUp/PgDn scroll, Home at the top pages in older history, Ctrl+B browse, Ctrl+N new DM, Ctrl+R refresh, and with the composer unfocused (Esc) Up/Down switch conversations.  See <a href="network.html#chat">Network → Chat client</a>.</li>
+			<li><strong>chat</strong> — native Cloudron Chat client (top-bar <em>Chat</em> button, or <code>chat [config-path]</code>): username/password/TOTP login through the Cloudron OIDC API or a pasted session cookie, channels and DMs with unread badges and presence, history with older paging, inline image attachments, link-preview cards (click one to open it in the browser) and profile-picture avatars, sending, REST polling, read markers, browse/join and new DM.  The session cookie (never the password) is saved in <code>/data/CHAT.CFG</code> when the persistent volume is mounted, or in the RAM-only <code>/share/chat.cfg</code> otherwise.  Keys: Enter sends, PgUp/PgDn scroll, Home at the top pages in older history, Ctrl+B browse, Ctrl+N new DM, Ctrl+R refresh, and with the composer unfocused (Esc) Up/Down switch conversations.  See <a href="network.html#chat">Network → Chat client</a>.</li>
 			<li><strong>solitaire</strong> — Klondike with drag-and-drop, scoring and a win animation.</li>
 			<li><strong>solitaire</strong> — Klondike with drag-and-drop, scoring and a win animation.</li>
 			<li><strong>mines</strong> — second ngui canvas app; shares the toolkit and event model.</li>
 			<li><strong>mines</strong> — second ngui canvas app; shares the toolkit and event model.</li>
 			<li><strong>view</strong> — fit/1:1/zoom/pan image viewer, animated GIF playback.</li>
 			<li><strong>view</strong> — fit/1:1/zoom/pan image viewer, animated GIF playback.</li>

+ 28 - 1
tools/mock_chat.py

@@ -6,7 +6,8 @@ Two plain-HTTP origins on the host, reachable from a QEMU slirp guest as
 
 
   chat  (default port 18080): /auth/login, /auth/callback, /auth/return,
   chat  (default port 18080): /auth/login, /auth/callback, /auth/return,
         /auth/logout and the /api/* routes the client uses, including
         /auth/logout and the /api/* routes the client uses, including
-        /api/avatars/<uid> and /api/attachments/<id> for pictures
+        /api/avatars/<uid>, /api/attachments/<id> and /api/previews/p1 for
+        pictures
   login (default port 18081): /openid/auth, /openid/interaction/<uid>
   login (default port 18081): /openid/auth, /openid/interaction/<uid>
         (login page with cloudron-config JSON, consent page as a bare
         (login page with cloudron-config JSON, consent page as a bare
         auto-submit form), POST .../login and .../confirm
         auto-submit form), POST .../login and .../confirm
@@ -116,6 +117,17 @@ def attachment_png():
 ATTACHMENT_PNG = attachment_png()
 ATTACHMENT_PNG = attachment_png()
 
 
 
 
+def preview_png():
+    def pixel(x, y):
+        if (x // 16 + y // 16) % 2:
+            return (68, 132, 220)
+        return (30, 36, 52)
+    return png_rgb(160, 100, pixel)
+
+
+PREVIEW_PNG = preview_png()
+
+
 def note(line):
 def note(line):
     STATE["log"].append(line)
     STATE["log"].append(line)
     if ARGS and ARGS.verbose:
     if ARGS and ARGS.verbose:
@@ -182,6 +194,18 @@ def seed(n_general):
                          "url": "/api/attachments/a2"}],
                          "url": "/api/attachments/a2"}],
                     "threadCount": 2,
                     "threadCount": 2,
                     "reactions": [{"emoji": "\U0001F44D", "count": 3}]})
                     "reactions": [{"emoji": "\U0001F44D", "count": 3}]})
+    add_message("c-general", "u-carol",
+                "Release notes: https://cloudron.io/blog/",
+                extra={
+                    "preview": {
+                        "url": "https://cloudron.io/blog/",
+                        "title": "Cloudron release notes",
+                        "description": "What changed in the latest release, "
+                                       "including new app versions.",
+                        "siteName": "Cloudron",
+                        "image": "/api/previews/p1",
+                        "favicon": "/api/avatars/u-carol",
+                        "type": "website"}})
     add_message("c-secret", "u-alice", "Private channel, only us two.")
     add_message("c-secret", "u-alice", "Private channel, only us two.")
     add_message("d-alice", "u-alice", "Hi Test, this is a direct message!")
     add_message("d-alice", "u-alice", "Hi Test, this is a direct message!")
     # test has read general up to the history; the rest is unread
     # test has read general up to the history; the rest is unread
@@ -470,6 +494,9 @@ class ChatHandler(Base):
             if len(parts) == 3 and parts[:2] == ["api", "attachments"]:
             if len(parts) == 3 and parts[:2] == ["api", "attachments"]:
                 if parts[2] == "a2":
                 if parts[2] == "a2":
                     return self.send(200, ATTACHMENT_PNG, "image/png")
                     return self.send(200, ATTACHMENT_PNG, "image/png")
+            if len(parts) == 3 and parts[:2] == ["api", "previews"]:
+                if parts[2] == "p1":
+                    return self.send(200, PREVIEW_PNG, "image/png")
             if len(parts) == 4 and parts[:2] == ["api", "channels"] and parts[3] == "messages":
             if len(parts) == 4 and parts[:2] == ["api", "channels"] and parts[3] == "messages":
                 c = STATE["channels"].get(parts[2])
                 c = STATE["channels"].get(parts[2])
                 if not c or uid not in c["members"]:
                 if not c or uid not in c["members"]:

+ 2 - 0
tools/qmp_chat_test.py

@@ -289,6 +289,8 @@ def main():
               wait_for(lambda: logged("GET /api/avatars/"), 20, "avatars"))
               wait_for(lambda: logged("GET /api/avatars/"), 20, "avatars"))
         check("message image fetched",
         check("message image fetched",
               wait_for(lambda: logged("GET /api/attachments/a2"), 20, "image"))
               wait_for(lambda: logged("GET /api/attachments/a2"), 20, "image"))
+        check("link-preview image fetched",
+              wait_for(lambda: logged("GET /api/previews/p1"), 20, "preview"))
         time.sleep(4.0)
         time.sleep(4.0)
         shot(s, workdir, out, "3-main")
         shot(s, workdir, out, "3-main")
         if not full:
         if not full:

+ 386 - 9
user/apps/chat/ucmd_chat.c

@@ -44,6 +44,14 @@
 #define MSG_IMG_MAX    3
 #define MSG_IMG_MAX    3
 #define CHAT_IMG_W     480
 #define CHAT_IMG_W     480
 #define CHAT_IMG_H     320
 #define CHAT_IMG_H     320
+#define PREVIEW_MAX_W  420
+#define PREVIEW_PAD    8
+#define PREVIEW_THUMB_W 120
+#define PREVIEW_THUMB_H 72
+#define PREVIEW_GAP    10
+#define PREVIEW_TITLE_MAX 200
+#define PREVIEW_DESC_MAX  360
+#define PREVIEW_SITE_MAX  96
 #define CHAT_IMG_MAX   16
 #define CHAT_IMG_MAX   16
 #define CHAT_AVATAR_MAX 64
 #define CHAT_AVATAR_MAX 64
 #define CHAT_AVATAR    32
 #define CHAT_AVATAR    32
@@ -79,7 +87,7 @@ enum {
 	ACT_NONE, ACT_START_LOGIN, ACT_SUBMIT, ACT_SUBMIT_TOTP, ACT_USE_COOKIE,
 	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_SEND, ACT_REFRESH, ACT_SIGNOUT, ACT_OPEN_CONV, ACT_OLDER,
 	ACT_BROWSE, ACT_NEWDM, ACT_JOIN, ACT_OPEN_DM, ACT_RETRY,
 	ACT_BROWSE, ACT_NEWDM, ACT_JOIN, ACT_OPEN_DM, ACT_RETRY,
-	ACT_COOKIE_SCREEN, ACT_BACK
+	ACT_COOKIE_SCREEN, ACT_BACK, ACT_OPEN_URL
 };
 };
 
 
 struct conv {
 struct conv {
@@ -101,6 +109,11 @@ struct msg {
 	char extra[112];        /* attachments / thread / reactions line */
 	char extra[112];        /* attachments / thread / reactions line */
 	char *body;             /* Latin-1, malloc'd */
 	char *body;             /* Latin-1, malloc'd */
 	char *img_url[MSG_IMG_MAX]; /* image attachments, malloc'd URLs */
 	char *img_url[MSG_IMG_MAX]; /* image attachments, malloc'd URLs */
+	char *preview_image;    /* link-preview thumbnail URL, or NULL */
+	char *preview_url;      /* link target, or NULL */
+	char preview_title[PREVIEW_TITLE_MAX];
+	char preview_desc[PREVIEW_DESC_MAX];
+	char preview_site[PREVIEW_SITE_MAX];
 	unsigned char nimg;
 	unsigned char nimg;
 	unsigned char action;   /* type "me" */
 	unsigned char action;   /* type "me" */
 	int height;
 	int height;
@@ -129,6 +142,7 @@ static unsigned int resp_len;
 static enum screen screen = SCR_SERVER;
 static enum screen screen = SCR_SERVER;
 static enum modal modal = MODAL_NONE;
 static enum modal modal = MODAL_NONE;
 static int action, action_arg;
 static int action, action_arg;
+static char preview_press_id[48];  /* card held down, by message id */
 
 
 static char cfg_path[CHAT_PATH_MAX];
 static char cfg_path[CHAT_PATH_MAX];
 static int cfg_is_default;
 static int cfg_is_default;
@@ -854,7 +868,9 @@ static void chat_media_fail(void)
 
 
 static int chat_media_submit(struct chat_pic *p, int avatar)
 static int chat_media_submit(struct chat_pic *p, int avatar)
 {
 {
-	char req[512];
+	/* The helper's request file accepts a full URL; image CDN links with
+	 * query strings are routinely longer than 512 bytes. */
+	char req[CHAT_IMG_URL_MAX + 64];
 	int n;
 	int n;
 
 
 	if (!chat_fetch_buf) {
 	if (!chat_fetch_buf) {
@@ -1240,6 +1256,273 @@ static void chat_image_draw(const char *url, int x, int y, int tw)
 	}
 	}
 }
 }
 
 
+/* ---- link preview cards ---- */
+
+static int preview_text_w(const char *s, unsigned int n, int px, int bold)
+{
+	return (int)ngui_text_width_px(&ui, s, n, px, bold, 0, 0);
+}
+
+static int preview_line_h(int px)
+{
+	int h = ngui_text_line_height(&ui, px, 0);
+
+	return h > 0 ? h : (px * 5) / 4;
+}
+
+/* Length of the next wrapped line, measured at a specific size/weight. */
+static unsigned int preview_wrap(const char *s, unsigned int n, int maxw,
+				 int px, int bold, 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 (preview_text_w(s, j, px, bold) > maxw) {
+			if (end == 0) {
+				unsigned int k = 1;
+
+				while (k < j &&
+				       preview_text_w(s, k + 1, px, bold) <= 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 preview_line_count(const char *s, int maxw, int px, int bold,
+			      int max_lines)
+{
+	unsigned int n = (unsigned int)strlen(s), pos = 0, adv;
+	int lines = 0;
+
+	while (pos < n && lines < max_lines) {
+		preview_wrap(s + pos, n - pos, maxw, px, bold, &adv);
+		if (!adv)
+			adv = 1;
+		pos += adv;
+		lines++;
+	}
+	return lines;
+}
+
+static void preview_text_ellipsis(const char *s, int x, int y, int maxw,
+				  int px, int bold, unsigned short color)
+{
+	unsigned int n = (unsigned int)strlen(s), i, best = 0;
+	int dots = preview_text_w("...", 3, px, bold);
+
+	for (i = 0; i <= n; i++) {
+		if (preview_text_w(s, i, px, bold) > maxw)
+			break;
+		best = i;
+	}
+	if (best == n) {
+		ngui_text_px(&ui, x, y, s, n, color, px, bold, 0, 0);
+		return;
+	}
+	while (best > 0 &&
+	       preview_text_w(s, best, px, bold) + dots > maxw)
+		best--;
+	ngui_text_px(&ui, x, y, s, best, color, px, bold, 0, 0);
+	ngui_text_px(&ui, x + preview_text_w(s, best, px, bold), y, "...", 3,
+		     color, px, bold, 0, 0);
+}
+
+static void preview_text_draw(const char *s, int x, int y, int maxw,
+			      int max_lines, int px, int bold,
+			      unsigned short color)
+{
+	unsigned int n = (unsigned int)strlen(s), pos = 0, adv;
+	int lines = 0, lh = preview_line_h(px);
+
+	while (pos < n && lines < max_lines) {
+		unsigned int len = preview_wrap(s + pos, n - pos, maxw, px,
+						bold, &adv);
+
+		if (!adv)
+			adv = 1;
+		if (lines == max_lines - 1 && pos + adv < n)
+			preview_text_ellipsis(s + pos, x, y, maxw, px, bold,
+					      color);
+		else
+			ngui_text_px(&ui, x, y, s + pos, len, color, px, bold,
+				     0, 0);
+		pos += adv;
+		y += lh;
+		lines++;
+	}
+}
+
+static int preview_content_height(const struct msg *m, int content_w)
+{
+	int h = 0, n;
+
+	if (content_w < 20)
+		content_w = 20;
+	if (m->preview_site[0])
+		h += preview_line_h(12);
+	if (m->preview_title[0]) {
+		n = preview_line_count(m->preview_title, content_w, 13, 1, 2);
+		if (h)
+			h += 3;
+		h += n * preview_line_h(13);
+	}
+	if (m->preview_desc[0]) {
+		n = preview_line_count(m->preview_desc, content_w, 12, 0, 3);
+		if (h)
+			h += 3;
+		h += n * preview_line_h(12);
+	}
+	return h;
+}
+
+static int msg_has_preview(const struct msg *m)
+{
+	return m->preview_site[0] || m->preview_title[0] ||
+	       m->preview_desc[0] || (m->preview_image && m->preview_image[0]);
+}
+
+static int preview_thumb_visible(const struct msg *m, int card_w)
+{
+	return m->preview_image && m->preview_image[0] &&
+	       card_w >= 2 * PREVIEW_PAD + PREVIEW_THUMB_W + PREVIEW_GAP + 20;
+}
+
+/* Fixed card height: it depends on the text, never on whether the thumbnail
+ * has finished loading, so the timeline does not jump when it arrives. */
+static int chat_preview_card_height(const struct msg *m, int tw)
+{
+	int cw = tw < PREVIEW_MAX_W ? tw : PREVIEW_MAX_W;
+	int content_w = cw - 2 * PREVIEW_PAD;
+	int h;
+
+	if (content_w < 20)
+		content_w = 20;
+	if (preview_thumb_visible(m, cw))
+		content_w -= PREVIEW_THUMB_W + PREVIEW_GAP;
+	if (content_w < 20)
+		content_w = 20;
+	h = preview_content_height(m, content_w);
+	if (h < PREVIEW_THUMB_H)
+		h = PREVIEW_THUMB_H;
+	return h + 2 * PREVIEW_PAD;
+}
+
+static struct ngui_rect chat_preview_rect(const struct msg *m, int x, int y,
+					  int tw)
+{
+	int cw = tw < PREVIEW_MAX_W ? tw : PREVIEW_MAX_W;
+
+	return (struct ngui_rect){ x, y, cw, chat_preview_card_height(m, tw) };
+}
+
+static void chat_preview_draw(struct msg *m, int x, int y, int tw)
+{
+	int cw = tw < PREVIEW_MAX_W ? tw : PREVIEW_MAX_W;
+	int ch = chat_preview_card_height(m, tw);
+	int content_x = x + PREVIEW_PAD;
+	int content_w = cw - 2 * PREVIEW_PAD;
+	int ty = y + PREVIEW_PAD;
+	int thumb;
+	struct ngui_rect card = { x, y, cw, ch };
+	struct chat_pic *p = 0;
+
+	if (cw < 1)
+		return;
+	ngui_fill_round_rect(&ui, card, 8, 8, 8, 8, ui.theme.panel);
+	ngui_frame_round(&ui, card, 8, 8, 8, 8, 1, ui.theme.border);
+	ngui_push_clip(&ui, card);
+
+	thumb = preview_thumb_visible(m, cw);
+	if (thumb) {
+		p = chat_image_slot(m->preview_image);
+		if (!p || p->state == CHAT_PIC_FAILED)
+			thumb = 0;
+	}
+	if (thumb) {
+		struct ngui_rect tr = { x + PREVIEW_PAD, y + PREVIEW_PAD,
+					PREVIEW_THUMB_W, PREVIEW_THUMB_H };
+
+		ngui_fill_rect(&ui, tr, ui.theme.panel_alt);
+		if (p && p->state == CHAT_PIC_READY) {
+			struct img_blit blit;
+			unsigned int scale, dw, dh;
+
+			scale = ((unsigned int)PREVIEW_THUMB_W << 16) /
+				(unsigned int)p->img.w;
+			if ((((unsigned int)PREVIEW_THUMB_H << 16) /
+			     (unsigned int)p->img.h) < scale)
+				scale = ((unsigned int)PREVIEW_THUMB_H << 16) /
+					(unsigned int)p->img.h;
+			dw = ((unsigned int)p->img.w * scale) >> 16;
+			dh = ((unsigned int)p->img.h * scale) >> 16;
+			memset(&blit, 0, sizeof(blit));
+			blit.dst = ui.px;
+			blit.dst_w = ui.w;
+			blit.dst_h = ui.h;
+			blit.clip_x = tr.x;
+			blit.clip_y = tr.y;
+			blit.clip_w = tr.w;
+			blit.clip_h = tr.h;
+			blit.x = tr.x + (tr.w - (int)dw) / 2;
+			blit.y = tr.y + (tr.h - (int)dh) / 2;
+			blit.scale = scale;
+			blit.bg = ui.theme.panel_alt;
+			blit.bg2 = ui.theme.panel_alt;
+			blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0;
+			img_draw(&p->img, &blit);
+		}
+		content_x += PREVIEW_THUMB_W + PREVIEW_GAP;
+		content_w -= PREVIEW_THUMB_W + PREVIEW_GAP;
+	}
+	if (content_w < 20)
+		content_w = 20;
+	if (m->preview_site[0]) {
+		preview_text_draw(m->preview_site, content_x, ty, content_w, 1,
+				  12, 0, ui.theme.text_dim);
+		ty += preview_line_h(12);
+	}
+	if (m->preview_title[0]) {
+		if (m->preview_site[0])
+			ty += 3;
+		preview_text_draw(m->preview_title, content_x, ty, content_w, 2,
+				  13, 1, ui.theme.text);
+		ty += preview_line_count(m->preview_title, content_w, 13, 1, 2) *
+		      preview_line_h(13);
+	}
+	if (m->preview_desc[0]) {
+		if (m->preview_site[0] || m->preview_title[0])
+			ty += 3;
+		preview_text_draw(m->preview_desc, content_x, ty, content_w, 3,
+				  12, 0, ui.theme.text_dim);
+	}
+	ngui_pop_clip(&ui);
+}
+
 static int chat_avatar_draw(const char *url, int x, int y, int size,
 static int chat_avatar_draw(const char *url, int x, int y, int size,
 			    unsigned short fallback)
 			    unsigned short fallback)
 {
 {
@@ -1406,6 +1689,10 @@ static void msg_free(struct msg *m)
 	m->body = 0;
 	m->body = 0;
 	free(m->author_pic);
 	free(m->author_pic);
 	m->author_pic = 0;
 	m->author_pic = 0;
+	free(m->preview_image);
+	m->preview_image = 0;
+	free(m->preview_url);
+	m->preview_url = 0;
 	for (i = 0; i < m->nimg; i++) {
 	for (i = 0; i < m->nimg; i++) {
 		free(m->img_url[i]);
 		free(m->img_url[i]);
 		m->img_url[i] = 0;
 		m->img_url[i] = 0;
@@ -1434,6 +1721,64 @@ static int msg_add_image(struct msg *m, const char *raw)
 	return 0;
 	return 0;
 }
 }
 
 
+/* Flatten one preview field to Latin-1 and trim its edges. */
+static void preview_text(char *dst, unsigned int cap, const char *raw)
+{
+	unsigned int i, n;
+
+	to_latin1_line(dst, cap, raw ? raw : "");
+	for (i = 0; dst[i] == ' '; i++)
+		;
+	if (i) {
+		n = (unsigned int)strlen(dst + i);
+		memmove(dst, dst + i, n + 1);
+	}
+	n = (unsigned int)strlen(dst);
+	while (n && (dst[n - 1] == ' ' || dst[n - 1] == '\t'))
+		dst[--n] = '\0';
+}
+
+/* Read the message's link-preview object.  The server resolves the link and
+ * sends the Open Graph title/description/site name plus absolute image URLs;
+ * the card draws them, and only the thumbnail goes through the image cache. */
+static void msg_set_preview(struct msg *m, int o)
+{
+	int p = ujson_get(&json, o, "preview");
+	const char *url, *image;
+
+	if (ujson_type(&json, p) != UJSON_OBJECT)
+		return;
+	url = ujson_get_str(&json, p, "url");
+	image = ujson_get_str(&json, p, "image");
+	preview_text(m->preview_title, sizeof(m->preview_title),
+		     ujson_get_str(&json, p, "title"));
+	preview_text(m->preview_desc, sizeof(m->preview_desc),
+		     ujson_get_str(&json, p, "description"));
+	preview_text(m->preview_site, sizeof(m->preview_site),
+		     ujson_get_str(&json, p, "siteName"));
+	if (!m->preview_site[0] && url[0]) {
+		struct uhttp_url u;
+
+		if (uhttp_parse_url(url, &u) == 0)
+			s_copy(m->preview_site, u.host,
+			       sizeof(m->preview_site));
+	}
+	if (url[0]) {
+		char resolved[CHAT_IMG_URL_MAX];
+
+		if (uhttp_resolve(server, url, resolved, sizeof(resolved)) ==
+		    0)
+			m->preview_url = strdup(resolved);
+	}
+	if (image[0]) {
+		char resolved[CHAT_IMG_URL_MAX];
+
+		if (uhttp_resolve(server, image, resolved, sizeof(resolved)) ==
+		    0)
+			m->preview_image = strdup(resolved);
+	}
+}
+
 static void msg_set_author_pic(struct msg *m, const char *raw)
 static void msg_set_author_pic(struct msg *m, const char *raw)
 {
 {
 	char url[CHAT_IMG_URL_MAX];
 	char url[CHAT_IMG_URL_MAX];
@@ -1596,13 +1941,7 @@ static int msg_from_json(struct msg *m, int o)
 		msg_free(m);
 		msg_free(m);
 		return -1;
 		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;
-	}
+	msg_set_preview(m, o);
 	rt = ujson_get(&json, o, "replyTo");
 	rt = ujson_get(&json, o, "replyTo");
 	if (ujson_type(&json, rt) == UJSON_OBJECT) {
 	if (ujson_type(&json, rt) == UJSON_OBJECT) {
 		char tmp[96];
 		char tmp[96];
@@ -2404,6 +2743,8 @@ static void layout_msg(int i, int width)
 				   &state);
 				   &state);
 		h += dh + 6;
 		h += dh + 6;
 	}
 	}
+	if (msg_has_preview(m))
+		h += chat_preview_card_height(m, tw) + 6;
 	if (m->extra[0])
 	if (m->extra[0])
 		h += lh + 2;
 		h += lh + 2;
 	h += 2;
 	h += 2;
@@ -2832,6 +3173,35 @@ static void draw_message(struct msg *m, int x, int y, int width)
 			y += dh + 6;
 			y += dh + 6;
 		}
 		}
 	}
 	}
+	if (msg_has_preview(m)) {
+		struct ngui_rect pr = chat_preview_rect(m, tx, y, tw);
+		struct ngui_rect clip = chat_clip_rect();
+		int press_over = ngui_rect_contains(&clip, ui.press_x,
+						    ui.press_y) &&
+				 ngui_rect_contains(&pr, ui.press_x,
+						    ui.press_y);
+		int release_over = ngui_rect_contains(&clip, ui.release_x,
+						      ui.release_y) &&
+				   ngui_rect_contains(&pr, ui.release_x,
+						      ui.release_y);
+		int mi = (int)(m - msgs);
+
+		chat_preview_draw(m, tx, y, tw);
+		if (m->preview_url &&
+		    ngui_rect_contains(&clip, ui.mouse_x, ui.mouse_y) &&
+		    ngui_rect_contains(&pr, ui.mouse_x, ui.mouse_y))
+			ngui_set_cursor(&ui, CURSOR_POINTER);
+		if (m->preview_url && (ui.pressed & 1) && press_over)
+			s_copy(preview_press_id, m->id,
+			       sizeof(preview_press_id));
+		if (m->preview_url && (ui.released & 1) && release_over &&
+		    strcmp(preview_press_id, m->id) == 0) {
+			action = ACT_OPEN_URL;
+			action_arg = mi;
+			preview_press_id[0] = '\0';
+		}
+		y += pr.h + 6;
+	}
 	if (m->extra[0]) {
 	if (m->extra[0]) {
 		struct ngui_rect er = { tx, y + 2, tw, lh };
 		struct ngui_rect er = { tx, y + 2, tw, lh };
 
 
@@ -2896,6 +3266,8 @@ static void draw_timeline(struct ngui_rect r)
 			draw_message(m, r.x, y, width);
 			draw_message(m, r.x, y, width);
 		y += m->height;
 		y += m->height;
 	}
 	}
+	if (ui.released)
+		preview_press_id[0] = '\0';
 	if (!nmsg)
 	if (!nmsg)
 		ngui_text(&ui, r.x + 20, r.y + 50,
 		ngui_text(&ui, r.x + 20, r.y + 50,
 			  "No messages yet - say hello!", ui.theme.text_dim);
 			  "No messages yet - say hello!", ui.theme.text_dim);
@@ -3346,6 +3718,11 @@ static void run_action(void)
 		if (arg != cur)
 		if (arg != cur)
 			open_conv(arg);
 			open_conv(arg);
 		break;
 		break;
+	case ACT_OPEN_URL:
+		if (arg >= 0 && arg < nmsg && msgs[arg].preview_url)
+			u_spawn("/ramfs/bin/browser", msgs[arg].preview_url,
+				0, "/");
+		break;
 	case ACT_OLDER:
 	case ACT_OLDER:
 		load_older();
 		load_older();
 		break;
 		break;

Некоторые файлы не были показаны из-за большого количества измененных файлов