xonecas.io
8058
Ir

irvc / commit a4f740b

Merge pull request #8 from sacenox/feat/video-uploads

feat: upload videos

xonecas2026-10-21 a4f740b676ff6c3e19dab642c272b0ef8d772eca parent 83a6252parent 12846de

10 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 {
preview.go+3−2
@@ -308,8 +308,9 @@ func (p *previewer) cacheImage(ctx context.Context, src string) string {
308308 if err != nil || len(data) > maxPreviewImage || len(data) == 0 {
309309 return ""
310310 }
311- ext, ok := imageExt[http.DetectContentType(data)]
312- if !ok {
311+ ct := http.DetectContentType(data)
312+ ext, ok := mediaExt[ct]
313+ if !ok || !strings.HasPrefix(ct, "image/") {
313314 return ""
314315 }
315316 name := randToken() + ext
web/src/components/Composer.tsx+20−10
@@ -79,16 +79,26 @@ export default function Composer({
7979 });
8080 }
8181
82+ // media reports whether a file is worth uploading: a raster image or a
83+ // browser-playable video. The name check catches files the browser gave no
84+ // type, so the server can refuse them out loud instead of them vanishing.
85+ const media = (f: File) =>
86+ f.type.startsWith("image/") || f.type.startsWith("video/") || /\.(png|jpe?g|gif|webp|mp4|webm)$/i.test(f.name);
87+
8288 async function attach(files: File[]) {
89+ const failed: string[] = [];
8390 for (const f of files) {
84- if (!f.type.startsWith("image/")) continue;
91+ if (!media(f)) continue;
8592 try {
8693 const { url } = await upload(f);
8794 insert(`![${f.name}](${url})\n`);
88- } catch {
89- // a failed upload should not block the rest
95+ } catch (e) {
96+ // a failed upload should not block the rest, but say why
97+ failed.push(e instanceof Error ? e.message : "could not upload");
9098 }
9199 }
100+ if (failed.length === 1) toast(failed[0]);
101+ else if (failed.length > 1) toast(`${failed.length} uploads failed: ${failed[0]}`);
92102 }
93103
94104 async function openGifs(query: string) {
@@ -148,15 +158,15 @@ export default function Composer({
148158 }
149159 }
150160
151- // Images pasted anywhere in the composer are uploaded and inlined.
161+ // Media pasted anywhere in the composer is uploaded and inlined.
152162 function onPaste(e: ClipboardEvent<HTMLTextAreaElement>) {
153- const images = [...e.clipboardData.files].filter((f) => f.type.startsWith("image/"));
154- if (images.length === 0) return;
163+ const files = [...e.clipboardData.files].filter(media);
164+ if (files.length === 0) return;
155165 e.preventDefault();
156- attach(images);
166+ attach(files);
157167 }
158168
159- // Dropping an image anywhere on the page attaches it. The listener is
169+ // Dropping media anywhere on the page attaches it. The listener is
160170 // registered once and reads attach through a ref.
161171 const attachRef = useRef(attach);
162172 attachRef.current = attach;
@@ -214,7 +224,7 @@ export default function Composer({
214224 <input
215225 ref={file}
216226 type="file"
217- accept="image/*"
227+ accept="image/*,video/*"
218228 multiple
219229 hidden
220230 onChange={(e) => {
@@ -223,7 +233,7 @@ export default function Composer({
223233 }}
224234 />
225235 <IconButton
226- label="attach image"
236+ label="attach media"
227237 size="sm"
228238 onClick={() => file.current?.click()}
229239 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
@@ -20,11 +20,6 @@ export function isMentioned(body: string, username: string) {
2020 return new RegExp(`(^|[^\\w-])@${username}(?![\\w-])`, "i").test(body);
2121 }
2222
23-// hasImage reports whether body contains a markdown image.
24-export function hasImage(body: string) {
25- return /!\[[^\]]*\]\([^)]+\)/.test(body);
26-}
27-
2823 export default function MessageList({
2924 messages,
3025 username,
@@ -238,7 +233,7 @@ function Row({
238233 // selected, and when the tap lands on a link or the actions button.
239234 onClick={(e) => {
240235 if (!window.getSelection()?.isCollapsed) return;
241- if ((e.target as HTMLElement).closest("a,button")) return;
236+ if ((e.target as HTMLElement).closest("a,button,video")) return;
242237 onSelect();
243238 }}
244239 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+3−2
@@ -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";
@@ -440,7 +441,7 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
440441 // /collapse: fold every image and link preview in the open channel.
441442 function collapseAll() {
442443 setCollapsed(
443- (prev) => new Set([...prev, ...messages.filter((m) => hasImage(m.body)).map((m) => m.id)]),
444+ (prev) => new Set([...prev, ...messages.filter((m) => hasMedia(m.body)).map((m) => m.id)]),
444445 );
445446 const cards = messages.filter((m) => m.preview?.kind === "card").map((m) => [m.id, true]);
446447 setPreviewState((prev) => ({ ...prev, ...Object.fromEntries(cards) }));