xonecas.io
8058
Ir

irvc / commit e7d0bff

feat: upload videos

xonecas2026-10-21 e7d0bfffe8fbd0919beeedb6d0f173cbb458c7a4 parent 947159d

9 files changed

README.md+2−2
@@ -58,8 +58,8 @@ Secrets come from the shell env:
5858 | `IRVC_LIVEKIT_URL` | — | e.g. `wss://livekit.example.com` (browser-facing) |
5959 | `IRVC_LIVEKIT_API_KEY` | — | must match livekit-server |
6060 | `IRVC_LIVEKIT_SECRET` | — | must match livekit-server |
61-| `IRVC_MEDIA_DIR` | `media` | uploaded image storage, the only other state |
62-| `IRVC_MAX_UPLOAD` | `8388608` | max image upload bytes |
61+| `IRVC_MEDIA_DIR` | `media` | uploaded media storage, the only other state |
62+| `IRVC_MAX_UPLOAD` | `8388608` | max media upload bytes |
6363 | `IRVC_GIPHY_API_KEY` | — | Giphy API key; `/gif` and the gif picker are disabled without it |
6464
6565 Voice is disabled if the LiveKit vars are unset.
irvc.md+5−5
@@ -12,7 +12,7 @@ Small, private chat + voice for 4–6 people on one VPS. No data gathering, full
1212 - Server-side accounts, invite-only.
1313 - Text channels and 1-on-1 DMs with persisted history (IRC-like), GFM markdown, multiline compose, mentions, message editing and deletion.
1414 - Text and voice channels created and deleted from the sidebar; the seeded channels are permanent.
15-- Image attachments (raster only), stored on disk.
15+- Image and video attachments, stored on disk.
1616 - Voice channels, ephemeral (not recorded), with mute, deafen, per-peer volume, mic processing, a level-based noise gate, and a join/leave tone.
1717 - Screen sharing into a voice channel, with tab/system audio, simulcast, and a 720p/1080p quality choice.
1818 - 1-on-1 voice and video calls inside a DM, with a ring tone the callee can switch off.
@@ -70,7 +70,7 @@ read_state (user_id, channel_id, last_read_message_id, updated_at)
7070 - Messages are returned joined with their author's username.
7171 - Seed: one text channel `#general` and one voice channel `general`, both marked permanent.
7272 - DMs: `type = 'dm'` channels with canonical name `u:<min_id>:<max_id>`, resolved to the peer's username for each participant.
73-- Uploaded images: random names, raster only (no SVG/HTML), served with `nosniff`.
73+- Uploaded media: random names, raster images and mp4/webm video only (no SVG/HTML), served with `nosniff` and Range support, so video streams and seeks.
7474
7575 ## Behavior
7676
@@ -78,8 +78,8 @@ read_state (user_id, channel_id, last_read_message_id, updated_at)
7878 - **Text:** GFM markdown; single newlines are hard breaks. Messages persist; live append over WS. Rendered as timestamp, author, content.
7979 - **Mentions:** `@username` highlights the message for that user; typing `@` opens an autocomplete.
8080 - **Unread:** `read_state` stores each user's last-read message per channel; `/channels` returns the count of newer messages by others. Opening a channel marks it read, so the count survives reload and is shared across devices.
81-- **Commands:** `/me <action>` renders an emote as `* user action`; `/collapse` hides images in the current channel; `/gif [query]` opens a picker with the top Giphy results (trending when no query) to insert one. The gif picker is disabled without `IRVC_GIPHY_API_KEY`.
82-- **Images:** pasted or attached, uploaded, rendered inline with a click-to-zoom dialog. Collapsible per message or channel-wide. Gifs from Giphy can also be inserted with the gif picker.
81+- **Commands:** `/me <action>` renders an emote as `* user action`; `/collapse` hides media in the current channel; `/gif [query]` opens a picker with the top Giphy results (trending when no query) to insert one. The gif picker is disabled without `IRVC_GIPHY_API_KEY`.
82+- **Media:** pasted or attached, uploaded, rendered inline. Images open in a click-to-zoom dialog; video renders as a player capped to the image size, showing its first frame as a thumbnail. Collapsible per message or channel-wide. Gifs from Giphy can also be inserted with the gif picker.
8383 - **Voice:** joining a voice channel connects to its LiveKit room (`voice-<id>`). Not persisted, not recorded. Occupants are visible to everyone without joining.
8484 - **Calls in DMs:** a DM holds a 1-on-1 voice or video call. It reuses the voice-token path — a DM call mints a token for the DM's own room — so a call is the same LiveKit machinery as a voice channel, attached to the DM instead. Starting one rings the peer with a slow repeating `beep()` (toggleable in settings) and signals them over the WS. Only one capture at a time, so starting a DM call leaves any voice channel first. The call pane is a horizontal split: peers' cameras fill the top, the …
8585 - **Screen share:** any participant may publish a screen share (with tab or system audio) into the room. It is not persisted and not recorded. Shares are visible only to participants, not to the rest of the server. Share audio plays through the normal audio path, so deafen and per-peer volume apply.
@@ -126,7 +126,7 @@ IRVC_SESSION_SECRET required to run
126126 IRVC_LIVEKIT_URL browser-facing
127127 IRVC_LIVEKIT_API_KEY
128128 IRVC_LIVEKIT_SECRET
129-IRVC_MEDIA_DIR uploaded image storage
129+IRVC_MEDIA_DIR uploaded media storage
130130 IRVC_MAX_UPLOAD max upload bytes
131131 IRVC_GIPHY_API_KEY Giphy API key; the gif picker is disabled without it
132132 ```
media.go+19−5
@@ -1,6 +1,8 @@
11 package main
22
33 import (
4+ "errors"
5+ "fmt"
46 "io"
57 "net/http"
68 "os"
@@ -10,20 +12,32 @@ import (
1012 "github.com/gin-gonic/gin"
1113 )
1214
13-// Raster only: SVG and HTML can carry script, so they are not accepted.
14-var imageExt = map[string]string{
15+// Raster images and browser-playable video. SVG and HTML can carry script, so
16+// they are not accepted. c.File serves these with Range support, so video
17+// seeks and streams without extra work.
18+var mediaExt = map[string]string{
1519 "image/png": ".png",
1620 "image/jpeg": ".jpg",
1721 "image/gif": ".gif",
1822 "image/webp": ".webp",
23+ "video/mp4": ".mp4",
24+ "video/webm": ".webm",
1925 }
2026
21-var mediaName = regexp.MustCompile(`^[A-Za-z0-9_-]+\.[a-z]+$`)
27+// The extension allows digits so mp4 serves; the stem is the token from upload.
28+var mediaName = regexp.MustCompile(`^[A-Za-z0-9_-]+\.[a-z0-9]+$`)
2229
2330 func (s *Server) handleUpload(c *gin.Context) {
2431 c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, s.cfg.MaxUpload)
2532 file, err := c.FormFile("file")
2633 if err != nil {
34+ var tooBig *http.MaxBytesError
35+ if errors.As(err, &tooBig) {
36+ c.JSON(http.StatusRequestEntityTooLarge, gin.H{
37+ "error": fmt.Sprintf("file is larger than %d MB", s.cfg.MaxUpload>>20),
38+ })
39+ return
40+ }
2741 c.JSON(http.StatusBadRequest, gin.H{"error": "invalid upload"})
2842 return
2943 }
@@ -35,9 +49,9 @@ func (s *Server) handleUpload(c *gin.Context) {
3549 defer f.Close()
3650 head := make([]byte, 512)
3751 n, _ := io.ReadFull(f, head)
38- ext, ok := imageExt[http.DetectContentType(head[:n])]
52+ ext, ok := mediaExt[http.DetectContentType(head[:n])]
3953 if !ok {
40- c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image"})
54+ c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported media"})
4155 return
4256 }
4357 if _, err := f.Seek(0, io.SeekStart); err != nil {
web/src/components/Composer.tsx+23−13
@@ -20,12 +20,12 @@ export default function Composer({
2020 channel,
2121 users,
2222 onEditLast,
23- onCollapseImages,
23+ onCollapseMedia,
2424 }: {
2525 channel: Channel;
2626 users: UserSummary[];
2727 onEditLast: () => void;
28- onCollapseImages: () => void;
28+ onCollapseMedia: () => void;
2929 }) {
3030 const [body, setBody] = useState("");
3131 const [mention, setMention] = useState<{ query: string; start: number; index: number } | null>(
@@ -77,16 +77,26 @@ export default function Composer({
7777 });
7878 }
7979
80+ // media reports whether a file is worth uploading: a raster image or a
81+ // browser-playable video. The name check catches files the browser gave no
82+ // type, so the server can refuse them out loud instead of them vanishing.
83+ const media = (f: File) =>
84+ f.type.startsWith("image/") || f.type.startsWith("video/") || /\.(png|jpe?g|gif|webp|mp4|webm)$/i.test(f.name);
85+
8086 async function attach(files: File[]) {
87+ const failed: string[] = [];
8188 for (const f of files) {
82- if (!f.type.startsWith("image/")) continue;
89+ if (!media(f)) continue;
8390 try {
8491 const { url } = await upload(f);
8592 insert(`![${f.name}](${url})\n`);
86- } catch {
87- // a failed upload should not block the rest
93+ } catch (e) {
94+ // a failed upload should not block the rest, but say why
95+ failed.push(e instanceof Error ? e.message : "could not upload");
8896 }
8997 }
98+ if (failed.length === 1) toast(failed[0]);
99+ else if (failed.length > 1) toast(`${failed.length} uploads failed: ${failed[0]}`);
90100 }
91101
92102 async function openGifs(query: string) {
@@ -108,7 +118,7 @@ export default function Composer({
108118 if (!text) return;
109119 setBody("");
110120 setMention(null);
111- if (text === "/collapse") return onCollapseImages();
121+ if (text === "/collapse") return onCollapseMedia();
112122 const gif = /^\/gif(?:\s+(.*))?$/.exec(text);
113123 if (gif) return void openGifs(gif[1]?.trim() ?? "");
114124 try {
@@ -146,15 +156,15 @@ export default function Composer({
146156 }
147157 }
148158
149- // Images pasted anywhere in the composer are uploaded and inlined.
159+ // Media pasted anywhere in the composer is uploaded and inlined.
150160 function onPaste(e: ClipboardEvent<HTMLTextAreaElement>) {
151- const images = [...e.clipboardData.files].filter((f) => f.type.startsWith("image/"));
152- if (images.length === 0) return;
161+ const files = [...e.clipboardData.files].filter(media);
162+ if (files.length === 0) return;
153163 e.preventDefault();
154- attach(images);
164+ attach(files);
155165 }
156166
157- // Dropping an image anywhere on the page attaches it. The listener is
167+ // Dropping media anywhere on the page attaches it. The listener is
158168 // registered once and reads attach through a ref.
159169 const attachRef = useRef(attach);
160170 attachRef.current = attach;
@@ -212,7 +222,7 @@ export default function Composer({
212222 <input
213223 ref={file}
214224 type="file"
215- accept="image/*"
225+ accept="image/*,video/*"
216226 multiple
217227 hidden
218228 onChange={(e) => {
@@ -221,7 +231,7 @@ export default function Composer({
221231 }}
222232 />
223233 <IconButton
224- label="attach image"
234+ label="attach media"
225235 size="sm"
226236 onClick={() => file.current?.click()}
227237 className="mb-0.5"
web/src/components/Markdown.tsx+20−9
@@ -3,13 +3,15 @@ import ReactMarkdown from "react-markdown";
33 import remarkBreaks from "remark-breaks";
44 import remarkGfm from "remark-gfm";
55 import { ChevronDown, ChevronRight } from "lucide-react";
6+import { attachmentNames, isVideo } from "../lib/media";
67
78 const Collapsed = createContext(false);
89
9-// Images render inline; clicking one opens it in a full-window focus dialog.
10-// When the message's header is collapsed, images are hidden and their names
11-// show as chips beside the header toggle.
12-function Image({ src, alt }: { src?: string; alt?: string }) {
10+// Media renders images inline and video as a player capped to the image size.
11+// Clicking an image opens it in a full-window focus dialog. When the message's
12+// header is collapsed, both are hidden and their names show as chips beside the
13+// header toggle.
14+function Media({ src, alt }: { src?: string; alt?: string }) {
1315 const [open, setOpen] = useState(false);
1416 const collapsed = useContext(Collapsed);
1517 // Esc closes the viewer. Capture phase + stopPropagation so it doesn't also
@@ -26,6 +28,15 @@ function Image({ src, alt }: { src?: string; alt?: string }) {
2628 }, [open]);
2729 if (!src) return alt ? <span>{alt}</span> : null;
2830 if (collapsed) return null; // names are shown in the header row instead
31+ if (isVideo(src)) {
32+ // preload=metadata with the #t=0.1 fragment asks the browser for the first
33+ // frame as a thumbnail, so no poster and no full download are needed.
34+ return (
35+ <video src={`${src}#t=0.1`} controls playsInline preload="metadata">
36+ <a href={src}>{alt || "video"}</a>
37+ </video>
38+ );
39+ }
2940 return (
3041 <>
3142 <img
@@ -53,7 +64,7 @@ const components = {
5364 {children}
5465 </a>
5566 ),
56- img: Image,
67+ img: Media,
5768 };
5869
5970 class Fallback extends Component<{ text: string; children: ReactNode }, { failed: boolean }> {
@@ -73,7 +84,7 @@ class Fallback extends Component<{ text: string; children: ReactNode }, { failed
7384
7485 // Markdown renders a message body as GFM. Single newlines become hard breaks so
7586 // multiline input shows as typed. If rendering ever throws, the raw text is
76-// shown instead. Messages containing images get a header to collapse them; the
87+// shown instead. Messages containing media get a header to collapse them; the
7788 // header lines up with the username column.
7889 export default function Markdown({
7990 text,
@@ -84,7 +95,7 @@ export default function Markdown({
8495 collapsed: boolean;
8596 onToggle: () => void;
8697 }) {
87- const names = [...text.matchAll(/!\[([^\]]*)\]\([^)]+\)/g)].map((m) => m[1] || "image");
98+ const names = attachmentNames(text);
8899 const count = names.length;
89100 return (
90101 <Fallback text={text}>
@@ -93,11 +104,11 @@ export default function Markdown({
93104 <button
94105 type="button"
95106 onClick={onToggle}
96- title={collapsed ? "show images" : "hide images"}
107+ title={collapsed ? "show media" : "hide media"}
97108 className="flex items-center gap-1 text-xs leading-6 text-faint hover:text-muted"
98109 >
99110 {collapsed ? <ChevronRight className="size-3" /> : <ChevronDown className="size-3" />}
100- {count} image{count > 1 ? "s" : ""}
111+ {count} attachment{count > 1 ? "s" : ""}
101112 </button>
102113 {collapsed &&
103114 names.map((name, i) => (
web/src/components/MessageList.tsx+1−6
@@ -19,11 +19,6 @@ export function isMentioned(body: string, username: string) {
1919 return new RegExp(`(^|[^\\w-])@${username}(?![\\w-])`, "i").test(body);
2020 }
2121
22-// hasImage reports whether body contains a markdown image.
23-export function hasImage(body: string) {
24- return /!\[[^\]]*\]\([^)]+\)/.test(body);
25-}
26-
2722 export default function MessageList({
2823 messages,
2924 username,
@@ -217,7 +212,7 @@ function Row({
217212 // selected, and when the tap lands on a link or the actions button.
218213 onClick={(e) => {
219214 if (!window.getSelection()?.isCollapsed) return;
220- if ((e.target as HTMLElement).closest("a,button")) return;
215+ if ((e.target as HTMLElement).closest("a,button,video")) return;
221216 onSelect();
222217 }}
223218 className={cn(
web/src/index.css+2−1
@@ -294,7 +294,8 @@
294294 .md td {
295295 @apply border border-line px-2 py-1 text-left;
296296 }
297- .md img {
297+ .md img,
298+ .md video {
298299 @apply my-1 max-h-80 max-w-full rounded-md border border-line;
299300 }
300301 }
web/src/lib/media.ts+16−0
@@ -0,0 +1,16 @@
1+// Uploaded media keeps the extension the server sniffed it into, so the url
2+// tells the markdown renderer whether image syntax should become a player.
3+export function isVideo(url: string) {
4+ return /\.(mp4|webm)(?:[?#]|$)/i.test(url);
5+}
6+
7+// hasMedia reports whether body contains an attachment: images and video share
8+// the markdown image syntax.
9+export function hasMedia(body: string) {
10+ return /!\[[^\]]*\]\([^)]+\)/.test(body);
11+}
12+
13+// attachmentNames lists the alt text of each attachment in body.
14+export function attachmentNames(body: string) {
15+ return [...body.matchAll(/!\[([^\]]*)\]\([^)]+\)/g)].map((m) => m[1] || "attachment");
16+}
web/src/views/Chat.tsx+4−3
@@ -13,7 +13,8 @@ import type { Channel, Message, Reaction, User, UserSummary, VoiceOccupant } fro
1313 import CallView from "../components/CallView";
1414 import Composer from "../components/Composer";
1515 import MessageActions from "../components/MessageActions";
16-import MessageList, { hasImage } from "../components/MessageList";
16+import MessageList from "../components/MessageList";
17+import { hasMedia } from "../lib/media";
1718 import ScreenShareView from "../components/ScreenShare";
1819 import Sidebar from "../components/Sidebar";
1920 import VoiceBar from "../components/VoiceBar";
@@ -525,10 +526,10 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
525526 channel={selected}
526527 users={users}
527528 onEditLast={startEditLast}
528- onCollapseImages={() =>
529+ onCollapseMedia={() =>
529530 setCollapsed(
530531 (prev) =>
531- new Set([...prev, ...messages.filter((m) => hasImage(m.body)).map((m) => m.id)]),
532+ new Set([...prev, ...messages.filter((m) => hasMedia(m.body)).map((m) => m.id)]),
532533 )
533534 }
534535 />