xonecas.io
8058
Ir

irvc / commit 09a04ff

feat: image support in conversations

xonecas2026-10-11 09a04fff580cdca42fb27ab95e8fa58d035edf13 parent 45a51e3

8 files changed

.gitignore+1−0
@@ -19,3 +19,4 @@ web/dist/
1919 /irvc.db
2020 /irvc.db-shm
2121 /irvc.db-wal
22+/media/
README.md+2−0
@@ -41,6 +41,8 @@ Secrets come from the shell env:
4141 | `IRVC_LIVEKIT_URL` | — | e.g. `wss://livekit.example.com` (browser-facing) |
4242 | `IRVC_LIVEKIT_API_KEY` | — | must match livekit-server |
4343 | `IRVC_LIVEKIT_SECRET` | — | must match livekit-server |
44+| `IRVC_MEDIA_DIR` | `media` | uploaded image storage, the only other state |
45+| `IRVC_MAX_UPLOAD` | `8388608` | max image upload bytes |
4446
4547 Voice is disabled if the LiveKit vars are unset.
4648
config.go+16−1
@@ -1,6 +1,9 @@
11 package main
22
3-import "os"
3+import (
4+ "os"
5+ "strconv"
6+)
47
58 type Config struct {
69 ListenAddr string
@@ -9,6 +12,8 @@ type Config struct {
912 LiveKitURL string
1013 LiveKitKey string
1114 LiveKitSecret string
15+ MediaDir string
16+ MaxUpload int64
1217 }
1318
1419 func LoadConfig() *Config {
@@ -19,9 +24,19 @@ func LoadConfig() *Config {
1924 LiveKitURL: env("IRVC_LIVEKIT_URL", ""),
2025 LiveKitKey: env("IRVC_LIVEKIT_API_KEY", ""),
2126 LiveKitSecret: env("IRVC_LIVEKIT_SECRET", ""),
27+ MediaDir: env("IRVC_MEDIA_DIR", "media"),
28+ MaxUpload: envInt("IRVC_MAX_UPLOAD", 8<<20),
2229 }
2330 }
2431
32+func envInt(key string, def int64) int64 {
33+ v, err := strconv.ParseInt(os.Getenv(key), 10, 64)
34+ if err != nil || v <= 0 {
35+ return def
36+ }
37+ return v
38+}
39+
2540 func env(key, def string) string {
2641 if v := os.Getenv(key); v != "" {
2742 return v
main.go+5−0
@@ -49,6 +49,9 @@ func runServer(cfg *Config, db *sql.DB) {
4949 if cfg.SessionSecret == "" {
5050 log.Fatal("IRVC_SESSION_SECRET is required")
5151 }
52+ if err := os.MkdirAll(cfg.MediaDir, 0o755); err != nil {
53+ log.Fatalf("media dir: %v", err)
54+ }
5255 s := &Server{cfg: cfg, db: db, hub: newHub(db)}
5356
5457 r := gin.Default()
@@ -69,6 +72,8 @@ func runServer(cfg *Config, db *sql.DB) {
6972 authed.POST("/channels/:id/messages", s.handleSendMessage)
7073 authed.POST("/channels/:id/voice", s.handleVoiceToken)
7174 authed.POST("/invites", s.handleCreateInvite)
75+ authed.POST("/upload", s.handleUpload)
76+ authed.GET("/media/:name", s.handleMedia)
7277 authed.GET("/ws", s.handleWS)
7378
7479 serveFrontend(r)
media.go+69−0
@@ -0,0 +1,69 @@
1+package main
2+
3+import (
4+ "io"
5+ "net/http"
6+ "os"
7+ "path/filepath"
8+ "regexp"
9+
10+ "github.com/gin-gonic/gin"
11+)
12+
13+// Raster only: SVG and HTML can carry script, so they are not accepted.
14+var imageExt = map[string]string{
15+ "image/png": ".png",
16+ "image/jpeg": ".jpg",
17+ "image/gif": ".gif",
18+ "image/webp": ".webp",
19+}
20+
21+var mediaName = regexp.MustCompile(`^[A-Za-z0-9_-]+\.[a-z]+$`)
22+
23+func (s *Server) handleUpload(c *gin.Context) {
24+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, s.cfg.MaxUpload)
25+ file, err := c.FormFile("file")
26+ if err != nil {
27+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid upload"})
28+ return
29+ }
30+ f, err := file.Open()
31+ if err != nil {
32+ c.JSON(http.StatusInternalServerError, gin.H{"error": "open"})
33+ return
34+ }
35+ defer f.Close()
36+ head := make([]byte, 512)
37+ n, _ := io.ReadFull(f, head)
38+ ext, ok := imageExt[http.DetectContentType(head[:n])]
39+ if !ok {
40+ c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image"})
41+ return
42+ }
43+ if _, err := f.Seek(0, io.SeekStart); err != nil {
44+ c.JSON(http.StatusInternalServerError, gin.H{"error": "read"})
45+ return
46+ }
47+ name := randToken() + ext
48+ dst, err := os.Create(filepath.Join(s.cfg.MediaDir, name))
49+ if err != nil {
50+ c.JSON(http.StatusInternalServerError, gin.H{"error": "write"})
51+ return
52+ }
53+ defer dst.Close()
54+ if _, err := io.Copy(dst, f); err != nil {
55+ c.JSON(http.StatusInternalServerError, gin.H{"error": "write"})
56+ return
57+ }
58+ c.JSON(http.StatusOK, gin.H{"url": "/api/media/" + name})
59+}
60+
61+func (s *Server) handleMedia(c *gin.Context) {
62+ name := c.Param("name")
63+ if !mediaName.MatchString(name) {
64+ c.Status(http.StatusNotFound)
65+ return
66+ }
67+ c.Header("X-Content-Type-Options", "nosniff")
68+ c.File(filepath.Join(s.cfg.MediaDir, name))
69+}
web/src/components/ChatPane.tsx+61−3
@@ -1,7 +1,14 @@
1-import { useEffect, useRef, useState, type FormEvent, type KeyboardEvent } from "react";
2-import { SendHorizontal } from "lucide-react";
1+import {
2+ useEffect,
3+ useRef,
4+ useState,
5+ type ClipboardEvent,
6+ type FormEvent,
7+ type KeyboardEvent,
8+} from "react";
9+import { Paperclip, SendHorizontal } from "lucide-react";
310 import { Button } from "@/components/ui/button";
4-import { api } from "../lib/api";
11+import { api, upload } from "../lib/api";
512 import type { Channel, Message } from "../lib/types";
613 import Markdown from "./Markdown";
714
@@ -26,6 +33,7 @@ export default function ChatPane({
2633 const [body, setBody] = useState("");
2734 const endRef = useRef<HTMLDivElement>(null);
2835 const textareaRef = useRef<HTMLTextAreaElement>(null);
36+ const fileRef = useRef<HTMLInputElement>(null);
2937
3038 useEffect(() => {
3139 endRef.current?.scrollIntoView();
@@ -38,6 +46,35 @@ export default function ChatPane({
3846 el.style.height = `${Math.min(el.scrollHeight, maxInputHeight)}px`;
3947 }, [body]);
4048
49+ function insert(text: string) {
50+ const el = textareaRef.current;
51+ if (!el) {
52+ setBody((b) => b + text);
53+ return;
54+ }
55+ const { selectionStart: start, selectionEnd: end } = el;
56+ setBody((b) => b.slice(0, start) + text + b.slice(end));
57+ }
58+
59+ async function attach(files: File[]) {
60+ for (const file of files) {
61+ if (!file.type.startsWith("image/")) continue;
62+ try {
63+ const { url } = await upload(file);
64+ insert(`![${file.name}](${url})\n`);
65+ } catch {
66+ // ignore failed uploads
67+ }
68+ }
69+ }
70+
71+ function onPaste(e: ClipboardEvent<HTMLTextAreaElement>) {
72+ const images = [...e.clipboardData.files].filter((f) => f.type.startsWith("image/"));
73+ if (images.length === 0) return;
74+ e.preventDefault();
75+ attach(images);
76+ }
77+
4178 async function send() {
4279 const text = body.trim();
4380 if (!text || !channel) return;
@@ -85,6 +122,26 @@ export default function ChatPane({
85122 <div ref={endRef} />
86123 </div>
87124 <form onSubmit={submit} className="flex items-end gap-2 border-t border-sepia/15 p-3">
125+ <input
126+ ref={fileRef}
127+ type="file"
128+ accept="image/*"
129+ multiple
130+ hidden
131+ onChange={(e) => {
132+ attach([...(e.target.files ?? [])]);
133+ e.target.value = "";
134+ }}
135+ />
136+ <Button
137+ type="button"
138+ variant="ghost"
139+ size="icon"
140+ title="attach image"
141+ onClick={() => fileRef.current?.click()}
142+ >
143+ <Paperclip />
144+ </Button>
88145 <textarea
89146 ref={textareaRef}
90147 rows={1}
@@ -92,6 +149,7 @@ export default function ChatPane({
92149 value={body}
93150 onChange={(e) => setBody(e.target.value)}
94151 onKeyDown={onKeyDown}
152+ onPaste={onPaste}
95153 className="max-h-[200px] w-full resize-none rounded-lg border border-input bg-transparent px-2.5 py-1 text-base leading-6 outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30 md:text-sm"
96154 />
97155 <Button type="submit" size="icon" title="send">
web/src/components/Markdown.tsx+27−4
@@ -1,17 +1,40 @@
1-import { Component, type ReactNode } from "react";
1+import { Component, useState, type ReactNode } from "react";
22 import ReactMarkdown from "react-markdown";
33 import remarkBreaks from "remark-breaks";
44 import remarkGfm from "remark-gfm";
55
6-// Images are deferred: render only their alt text so `![]()` never injects an
7-// <img> yet.
6+// Images render inline; clicking one opens it in a full-window focus dialog.
7+function Image({ src, alt }: { src?: string; alt?: string }) {
8+ const [open, setOpen] = useState(false);
9+ if (!src) return alt ? <span>{alt}</span> : null;
10+ return (
11+ <>
12+ <img
13+ src={src}
14+ alt={alt ?? ""}
15+ loading="lazy"
16+ onClick={() => setOpen(true)}
17+ className="my-1 max-h-80 max-w-full cursor-zoom-in rounded border border-sepia/15"
18+ />
19+ {open && (
20+ <div
21+ className="fixed inset-0 z-50 grid cursor-zoom-out place-items-center bg-black/80 p-4"
22+ onClick={() => setOpen(false)}
23+ >
24+ <img src={src} alt={alt ?? ""} className="max-h-full max-w-full rounded" />
25+ </div>
26+ )}
27+ </>
28+ );
29+}
30+
831 const components = {
932 a: ({ href, children }: { href?: string; children?: ReactNode }) => (
1033 <a href={href} target="_blank" rel="noopener noreferrer">
1134 {children}
1235 </a>
1336 ),
14- img: ({ alt }: { alt?: string }) => (alt ? <span>{alt}</span> : null),
37+ img: Image,
1538 };
1639
1740 class Fallback extends Component<{ text: string; children: ReactNode }, { failed: boolean }> {
web/src/lib/api.ts+15−0
@@ -11,3 +11,18 @@ export async function api<T>(path: string, init?: RequestInit): Promise<T> {
1111 if (res.status === 204) return undefined as T;
1212 return res.json() as Promise<T>;
1313 }
14+
15+export async function upload(file: File): Promise<{ url: string }> {
16+ const form = new FormData();
17+ form.append("file", file);
18+ const res = await fetch("/api/upload", {
19+ method: "POST",
20+ credentials: "same-origin",
21+ body: form,
22+ });
23+ if (!res.ok) {
24+ const body = await res.json().catch(() => ({ error: res.statusText }));
25+ throw new Error(body.error ?? "upload failed");
26+ }
27+ return res.json();
28+}