xonecas.io
8058
Ir

irvc / commit 5683048

feat: gif backed by GIPHY

xonecas2026-10-15 568304852b38e9cf6ea04fb9fbe1f17033daf3d1 parent 59176a7

10 files changed

AGENTS.md+5−0
@@ -21,3 +21,8 @@ This is ours.
2121 -d --build`, then <http://localhost:8080>. The container serves the built
2222 frontend; run `npm run dev` in `web/` for HMR. Details in
2323 `deploy/dev/README.md`. The bare-metal path in `DEPLOY.md` is unaffected.
24+
25+`podman-compose up -d --build` does not recreate the container when only the
26+built image changes, so it can keep serving a stale frontend. After changing
27+code, recreate with `podman-compose up -d --force-recreate` (and rebuild the
28+image with `podman-compose build --no-cache` if the build itself is cached).
README.md+1−0
@@ -60,6 +60,7 @@ Secrets come from the shell env:
6060 | `IRVC_LIVEKIT_SECRET` | — | must match livekit-server |
6161 | `IRVC_MEDIA_DIR` | `media` | uploaded image storage, the only other state |
6262 | `IRVC_MAX_UPLOAD` | `8388608` | max image upload bytes |
63+| `IRVC_GIPHY_API_KEY` | — | Giphy API key; `/gif` and the gif picker are disabled without it |
6364
6465 Voice is disabled if the LiveKit vars are unset.
6566
config.go+2−0
@@ -14,6 +14,7 @@ type Config struct {
1414 LiveKitSecret string
1515 MediaDir string
1616 MaxUpload int64
17+ GiphyKey string
1718 }
1819
1920 func LoadConfig() *Config {
@@ -26,6 +27,7 @@ func LoadConfig() *Config {
2627 LiveKitSecret: env("IRVC_LIVEKIT_SECRET", ""),
2728 MediaDir: env("IRVC_MEDIA_DIR", "media"),
2829 MaxUpload: envInt("IRVC_MAX_UPLOAD", 8<<20),
30+ GiphyKey: os.Getenv("IRVC_GIPHY_API_KEY"),
2931 }
3032 }
3133
deploy/dev/compose.yaml+1−0
@@ -13,6 +13,7 @@ services:
1313 IRVC_LIVEKIT_URL: ${IRVC_LIVEKIT_URL:-ws://localhost:7880}
1414 IRVC_LIVEKIT_API_KEY: irvc
1515 IRVC_LIVEKIT_SECRET: ${IRVC_LIVEKIT_SECRET:-irvc-dev-livekit-secret-000000000000}
16+ IRVC_GIPHY_API_KEY: ${IRVC_GIPHY_API_KEY:-}
1617 volumes:
1718 - irvc-data:/data
1819 depends_on:
giphy.go+68−0
@@ -0,0 +1,68 @@
1+package main
2+
3+import (
4+ "encoding/json"
5+ "net/http"
6+ "net/url"
7+ "strconv"
8+ "time"
9+
10+ "github.com/gin-gonic/gin"
11+)
12+
13+const gifLimit = 6
14+
15+type gif struct {
16+ URL string `json:"url"`
17+ Preview string `json:"preview"`
18+}
19+
20+func (s *Server) handleGifs(c *gin.Context) {
21+ if s.cfg.GiphyKey == "" {
22+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "gifs disabled"})
23+ return
24+ }
25+ query := c.Query("q")
26+ endpoint := "https://api.giphy.com/v1/gifs/trending"
27+ if query != "" {
28+ endpoint = "https://api.giphy.com/v1/gifs/search"
29+ }
30+ u, err := url.Parse(endpoint)
31+ if err != nil {
32+ c.JSON(http.StatusInternalServerError, gin.H{"error": "giphy"})
33+ return
34+ }
35+ params := u.Query()
36+ params.Set("api_key", s.cfg.GiphyKey)
37+ params.Set("limit", strconv.Itoa(gifLimit))
38+ params.Set("rating", "pg-13")
39+ if query != "" {
40+ params.Set("q", query)
41+ }
42+ u.RawQuery = params.Encode()
43+
44+ client := &http.Client{Timeout: 5 * time.Second}
45+ resp, err := client.Get(u.String())
46+ if err != nil {
47+ c.JSON(http.StatusBadGateway, gin.H{"error": "giphy"})
48+ return
49+ }
50+ defer resp.Body.Close()
51+ var body struct {
52+ Data []struct {
53+ Images struct {
54+ Original struct{ URL string } `json:"original"`
55+ FixedHeight struct{ URL string } `json:"fixed_height"`
56+ } `json:"images"`
57+ } `json:"data"`
58+ }
59+ if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
60+ c.JSON(http.StatusBadGateway, gin.H{"error": "giphy"})
61+ return
62+ }
63+ gifs := make([]gif, 0, len(body.Data))
64+ for _, g := range body.Data {
65+ gifs = append(gifs, gif{URL: g.Images.Original.URL, Preview: g.Images.FixedHeight.URL})
66+ }
67+ c.JSON(http.StatusOK, gin.H{"gifs": gifs})
68+}
irvc.md+2−2
@@ -72,8 +72,8 @@ messages (id, channel_id, user_id, body, created_at, edited_at)
7272 - **Channels:** seeded (`#general` text, `general` voice) plus on-demand 1-on-1 DMs opened by clicking a user. Ordered by `position`. Public channel CRUD is out of scope.
7373 - **Text:** GFM markdown; single newlines are hard breaks. Messages persist; live append over WS. Rendered as timestamp, author, content.
7474 - **Mentions:** `@username` highlights the message for that user; typing `@` opens an autocomplete.
75-- **Commands:** `/me <action>` renders an emote as `* user action`; `/collapse` hides images in the current channel.
76-- **Images:** pasted or attached, uploaded, rendered inline with a click-to-zoom dialog. Collapsible per message or channel-wide.
75+- **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.
76+- **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.
7777 - **Voice:** joining a voice channel connects to its LiveKit room (`voice-<id>`). Not persisted, not recorded. Occupants are visible to everyone without joining.
7878 - **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.
7979 - **Voice controls:** mute, deafen (local only), per-peer volume, mic/speaker device, quality preset, echo cancellation, noise suppression, auto gain, voice isolation, level-based noise gate, join/leave tone, start/stop screen share.
main.go+1−0
@@ -142,6 +142,7 @@ func runServer(cfg *Config, db *sql.DB) {
142142 authed.POST("/messages/:id/reactions", s.handleToggleReaction)
143143 authed.POST("/channels/:id/voice", s.handleVoiceToken)
144144 authed.POST("/invites", s.handleCreateInvite)
145+ authed.GET("/gifs", s.handleGifs)
145146 authed.POST("/upload", s.handleUpload)
146147 authed.GET("/media/:name", s.handleMedia)
147148 authed.GET("/ws", s.handleWS)
web/src/components/ChatPane.tsx+90−2
@@ -14,14 +14,16 @@ import {
1414 Paperclip,
1515 Pencil,
1616 SendHorizontal,
17+ Sticker,
1718 ThumbsDown,
1819 ThumbsUp,
1920 Trash2,
21+ X,
2022 } from "lucide-react";
2123 import { Button } from "@/components/ui/button";
2224 import { cn } from "cn";
23-import { api, upload } from "../lib/api";
24-import type { Channel, Message, Reaction, UserSummary } from "../lib/types";
25+import { api, gifs, upload } from "../lib/api";
26+import type { Channel, Gif, Message, Reaction, UserSummary } from "../lib/types";
2527 import Markdown from "./Markdown";
2628
2729 const reactions: { key: Reaction; label: string; Icon: typeof ThumbsUp }[] = [
@@ -71,6 +73,7 @@ export default function ChatPane({
7173 const [mention, setMention] = useState<{ query: string; start: number; index: number } | null>(
7274 null,
7375 );
76+ const [picker, setPicker] = useState<{ gifs: Gif[]; query: string } | null>(null);
7477 const listRef = useRef<HTMLDivElement>(null);
7578 const contentRef = useRef<HTMLDivElement>(null);
7679 const stickRef = useRef(true);
@@ -216,6 +219,26 @@ export default function ChatPane({
216219 setCollapsed(new Set(messages.filter((m) => hasImage(m.body)).map((m) => m.id)));
217220 }
218221
222+ async function openGifs(query: string) {
223+ try {
224+ const results = await gifs(query);
225+ setPicker({ gifs: results, query });
226+ } catch {
227+ // ignore fetch failures
228+ }
229+ }
230+
231+ function pickGif(g: Gif) {
232+ insert(`![gif](${g.url})\n`);
233+ setPicker(null);
234+ requestAnimationFrame(() => {
235+ const el = textareaRef.current;
236+ if (!el) return;
237+ el.focus();
238+ el.setSelectionRange(el.value.length, el.value.length);
239+ });
240+ }
241+
219242 function startEdit(m: Message) {
220243 setEditingId(m.id);
221244 setEditBody(m.body);
@@ -251,6 +274,11 @@ export default function ChatPane({
251274 collapseAll();
252275 return;
253276 }
277+ const gifCommand = /^\/gif(?:\s+(.*))?$/.exec(text);
278+ if (gifCommand) {
279+ openGifs(gifCommand[1]?.trim() ?? "");
280+ return;
281+ }
254282 try {
255283 await api(`/channels/${channel.id}/messages`, {
256284 method: "POST",
@@ -267,6 +295,11 @@ export default function ChatPane({
267295 }
268296
269297 function onKeyDown(e: KeyboardEvent<HTMLTextAreaElement>) {
298+ if (e.key === "Escape" && picker) {
299+ e.preventDefault();
300+ setPicker(null);
301+ return;
302+ }
270303 const matches = mention ? suggest(mention.query) : [];
271304 if (mention && matches.length > 0) {
272305 if (e.key === "ArrowDown") {
@@ -443,6 +476,58 @@ export default function ChatPane({
443476 onSubmit={submit}
444477 className="relative flex items-end gap-2 border-t border-sepia/15 p-3"
445478 >
479+ {picker && (
480+ <div className="absolute bottom-full left-2 mb-1 w-[min(24rem,90vw)] rounded-lg border border-border bg-panel p-2 shadow-lg">
481+ <div className="mb-1 flex items-center gap-1">
482+ <input
483+ autoFocus
484+ value={picker.query}
485+ onChange={(e) => setPicker({ ...picker, query: e.target.value })}
486+ onKeyDown={(e) => {
487+ if (e.key === "Enter") {
488+ e.preventDefault();
489+ openGifs(picker.query.trim());
490+ } else if (e.key === "Escape") {
491+ e.preventDefault();
492+ setPicker(null);
493+ }
494+ }}
495+ placeholder="search gifs"
496+ className="h-8 min-w-0 flex-1 rounded-lg border border-input bg-transparent px-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30"
497+ />
498+ <Button
499+ type="button"
500+ variant="ghost"
501+ size="icon-xs"
502+ title="cancel"
503+ onClick={() => setPicker(null)}
504+ >
505+ <X />
506+ </Button>
507+ </div>
508+ {picker.gifs.length === 0 ? (
509+ <div className="px-1 py-2 text-sm text-sepia/50">no results</div>
510+ ) : (
511+ <div className="grid grid-cols-3 gap-1">
512+ {picker.gifs.map((g) => (
513+ <button
514+ key={g.url}
515+ type="button"
516+ onClick={() => pickGif(g)}
517+ className="overflow-hidden rounded border border-sepia/15 hover:border-gold/50"
518+ >
519+ <img
520+ src={g.preview}
521+ alt=""
522+ loading="lazy"
523+ className="h-24 w-full object-cover"
524+ />
525+ </button>
526+ ))}
527+ </div>
528+ )}
529+ </div>
530+ )}
446531 {mention && suggest(mention.query).length > 0 && (
447532 <div className="absolute bottom-full left-2 mb-1 w-56 overflow-hidden rounded-lg border border-border bg-panel shadow-lg">
448533 {suggest(mention.query).map((u, i) => (
@@ -481,6 +566,9 @@ export default function ChatPane({
481566 >
482567 <Paperclip />
483568 </Button>
569+ <Button type="button" variant="ghost" size="icon" title="gif" onClick={() => openGifs("")}>
570+ <Sticker />
571+ </Button>
484572 <textarea
485573 ref={textareaRef}
486574 rows={1}
web/src/lib/api.ts+7−0
@@ -12,6 +12,13 @@ export async function api<T>(path: string, init?: RequestInit): Promise<T> {
1212 return res.json() as Promise<T>;
1313 }
1414
15+export async function gifs(query: string): Promise<{ url: string; preview: string }[]> {
16+ const { gifs } = await api<{ gifs: { url: string; preview: string }[] }>(
17+ `/gifs?q=${encodeURIComponent(query)}`,
18+ );
19+ return gifs;
20+}
21+
1522 export async function upload(file: File): Promise<{ url: string }> {
1623 const form = new FormData();
1724 form.append("file", file);
web/src/lib/types.ts+5−0
@@ -30,6 +30,11 @@ export interface Message {
3030 reactions?: Partial<Record<Reaction, string[]>>;
3131 }
3232
33+export interface Gif {
34+ url: string;
35+ preview: string;
36+}
37+
3338 export interface WSEvent {
3439 type:
3540 | "message"