xonecas.io
8058
Ir

irvc / commit 78e6aee

feat: channels crud

xonecas2026-10-15 78e6aee9df7e5946c7445710ebf0bcfd17540ce0 parent 7119599

7 files changed

channels.go+98−2
@@ -36,13 +36,26 @@ func (s *Server) notifyChannel(channelType, channelName string, ev event) {
3636 s.hub.broadcast(ev)
3737 }
3838
39+func validChannelName(name string) bool {
40+ if len(name) < 1 || len(name) > 32 {
41+ return false
42+ }
43+ for _, r := range name {
44+ ok := r == '_' || r == '-' || (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9')
45+ if !ok {
46+ return false
47+ }
48+ }
49+ return true
50+}
51+
3952 func (s *Server) handleChannels(c *gin.Context) {
4053 user := c.MustGet("user").(User)
4154 users := map[int64]string{}
4255 for _, u := range s.hub.roster() {
4356 users[u.ID] = u.Username
4457 }
45- rows, err := s.db.Query(`SELECT id, type, name, position FROM channels ORDER BY position, id`)
58+ rows, err := s.db.Query(`SELECT id, type, name, position, permanent FROM channels ORDER BY position, id`)
4659 if err != nil {
4760 c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
4861 return
@@ -51,7 +64,7 @@ func (s *Server) handleChannels(c *gin.Context) {
5164 channels := []Channel{}
5265 for rows.Next() {
5366 var ch Channel
54- if err := rows.Scan(&ch.ID, &ch.Type, &ch.Name, &ch.Position); err != nil {
67+ if err := rows.Scan(&ch.ID, &ch.Type, &ch.Name, &ch.Position, &ch.Permanent); err != nil {
5568 c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
5669 return
5770 }
@@ -74,6 +87,89 @@ func (s *Server) handleChannels(c *gin.Context) {
7487 c.JSON(http.StatusOK, channels)
7588 }
7689
90+type createChannelRequest struct {
91+ Type string `json:"type"`
92+ Name string `json:"name"`
93+}
94+
95+func (s *Server) handleCreateChannel(c *gin.Context) {
96+ var req createChannelRequest
97+ if err := c.ShouldBindJSON(&req); err != nil {
98+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
99+ return
100+ }
101+ if req.Type != "text" && req.Type != "voice" {
102+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid channel type"})
103+ return
104+ }
105+ name := strings.TrimSpace(req.Name)
106+ if !validChannelName(name) {
107+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid channel name"})
108+ return
109+ }
110+ var pos int
111+ if err := s.db.QueryRow(
112+ `SELECT COALESCE(MAX(position), 0) + 1 FROM channels WHERE type = ?`, req.Type,
113+ ).Scan(&pos); err != nil {
114+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
115+ return
116+ }
117+ res, err := s.db.Exec(
118+ `INSERT INTO channels (type, name, position, created_at) VALUES (?, ?, ?, ?)`,
119+ req.Type, name, pos, time.Now().Unix(),
120+ )
121+ if err != nil {
122+ c.JSON(http.StatusConflict, gin.H{"error": "channel already exists"})
123+ return
124+ }
125+ id, _ := res.LastInsertId()
126+ ch := Channel{ID: id, Type: req.Type, Name: name, Position: pos}
127+ s.hub.broadcast(event{Type: "channel", Channel: &ch})
128+ c.JSON(http.StatusOK, ch)
129+}
130+
131+func (s *Server) handleDeleteChannel(c *gin.Context) {
132+ channelID, err := strconv.ParseInt(c.Param("id"), 10, 64)
133+ if err != nil {
134+ c.JSON(http.StatusBadRequest, gin.H{"error": "bad channel"})
135+ return
136+ }
137+ var ch Channel
138+ err = s.db.QueryRow(
139+ `SELECT id, type, name, position, permanent FROM channels WHERE id = ?`, channelID,
140+ ).Scan(&ch.ID, &ch.Type, &ch.Name, &ch.Position, &ch.Permanent)
141+ if err != nil {
142+ if err == sql.ErrNoRows {
143+ c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
144+ return
145+ }
146+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
147+ return
148+ }
149+ if ch.Type == "dm" {
150+ c.JSON(http.StatusBadRequest, gin.H{"error": "not a channel"})
151+ return
152+ }
153+ if ch.Permanent {
154+ c.JSON(http.StatusForbidden, gin.H{"error": "channel is permanent"})
155+ return
156+ }
157+ if ch.Type == "voice" && s.hub.voiceOccupied(channelID) {
158+ c.JSON(http.StatusConflict, gin.H{"error": "channel is not empty"})
159+ return
160+ }
161+ if _, err := s.db.Exec(`DELETE FROM messages WHERE channel_id = ?`, channelID); err != nil {
162+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
163+ return
164+ }
165+ if _, err := s.db.Exec(`DELETE FROM channels WHERE id = ?`, channelID); err != nil {
166+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
167+ return
168+ }
169+ s.hub.broadcast(event{Type: "channel_delete", ChannelID: channelID})
170+ c.Status(http.StatusNoContent)
171+}
172+
77173 func (s *Server) handleOpenDM(c *gin.Context) {
78174 peerID, err := strconv.ParseInt(c.Param("userId"), 10, 64)
79175 if err != nil {
db.go+11−6
@@ -16,10 +16,11 @@ type User struct {
1616 }
1717
1818 type Channel struct {
19- ID int64 `json:"id"`
20- Type string `json:"type"`
21- Name string `json:"name"`
22- Position int `json:"position"`
19+ ID int64 `json:"id"`
20+ Type string `json:"type"`
21+ Name string `json:"name"`
22+ Position int `json:"position"`
23+ Permanent bool `json:"permanent"`
2324 }
2425
2526 type Message struct {
@@ -70,7 +71,8 @@ CREATE TABLE IF NOT EXISTS channels (
7071 type TEXT NOT NULL,
7172 name TEXT NOT NULL,
7273 position INTEGER NOT NULL,
73- created_at INTEGER NOT NULL
74+ created_at INTEGER NOT NULL,
75+ permanent INTEGER NOT NULL DEFAULT 0
7476 );
7577 CREATE TABLE IF NOT EXISTS messages (
7678 id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -88,6 +90,7 @@ CREATE TABLE IF NOT EXISTS reactions (
8890 );
8991 CREATE INDEX IF NOT EXISTS idx_messages_channel ON messages(channel_id, id);
9092 CREATE UNIQUE INDEX IF NOT EXISTS idx_channels_dm ON channels(name) WHERE type = 'dm';
93+CREATE UNIQUE INDEX IF NOT EXISTS idx_channels_name ON channels(type, name) WHERE type != 'dm';
9194 `
9295
9396 func migrate(db *sql.DB) {
@@ -95,6 +98,8 @@ func migrate(db *sql.DB) {
9598 log.Fatalf("migrate: %v", err)
9699 }
97100 db.Exec(`ALTER TABLE messages ADD COLUMN edited_at INTEGER`)
101+ db.Exec(`ALTER TABLE channels ADD COLUMN permanent INTEGER NOT NULL DEFAULT 0`)
102+ db.Exec(`UPDATE channels SET permanent = 1 WHERE name = 'general' AND type IN ('text', 'voice')`)
98103 var n int
99104 if err := db.QueryRow(`SELECT COUNT(*) FROM channels WHERE type != 'dm'`).Scan(&n); err != nil {
100105 log.Fatalf("count channels: %v", err)
@@ -112,7 +117,7 @@ func migrate(db *sql.DB) {
112117 }
113118 for _, c := range seed {
114119 if _, err := db.Exec(
115- `INSERT INTO channels (type, name, position, created_at) VALUES (?, ?, ?, ?)`,
120+ `INSERT INTO channels (type, name, position, created_at, permanent) VALUES (?, ?, ?, ?, 1)`,
116121 c.kind, c.name, c.pos, now,
117122 ); err != nil {
118123 log.Fatalf("seed channels: %v", err)
main.go+2−0
@@ -132,6 +132,8 @@ func runServer(cfg *Config, db *sql.DB) {
132132 authed.GET("/users", s.handleUsers)
133133 authed.POST("/logout", s.handleLogout)
134134 authed.GET("/channels", s.handleChannels)
135+ authed.POST("/channels", s.handleCreateChannel)
136+ authed.DELETE("/channels/:id", s.handleDeleteChannel)
135137 authed.POST("/dms/:userId", s.handleOpenDM)
136138 authed.GET("/channels/:id/messages", s.handleMessages)
137139 authed.POST("/channels/:id/messages", s.handleSendMessage)
web/src/components/Sidebar.tsx+150−18
@@ -9,15 +9,18 @@ import {
99 MicOff,
1010 Moon,
1111 PhoneOff,
12+ Plus,
1213 ScreenShare,
1314 ScreenShareOff,
1415 Settings,
1516 Sun,
17+ Trash2,
1618 UserPlus,
1719 Volume2,
1820 X,
1921 } from "lucide-react";
2022 import { Button } from "@/components/ui/button";
23+import { Input } from "@/components/ui/input";
2124 import { api } from "../lib/api";
2225 import type { Channel, UserSummary } from "../lib/types";
2326 import type { Mode } from "../lib/theme";
@@ -34,6 +37,8 @@ interface Invite {
3437 // button still renders, disabled, so its absence is never a silent mystery.
3538 const canShare = typeof navigator.mediaDevices?.getDisplayMedia === "function";
3639
40+const byName = (a: Channel, b: Channel) => a.name.localeCompare(b.name);
41+
3742 export default function Sidebar({
3843 channels,
3944 selected,
@@ -73,6 +78,29 @@ export default function Sidebar({
7378 }) {
7479 const [label, setLabel] = useState("create invite");
7580 const [showUsers, setShowUsers] = useState(true);
81+ const [creating, setCreating] = useState<"text" | "voice" | null>(null);
82+ const [draft, setDraft] = useState("");
83+
84+ const texts = channels.filter((c) => c.type === "text").sort(byName);
85+ const voices = channels.filter((c) => c.type === "voice").sort(byName);
86+ const dms = channels.filter((c) => c.type === "dm").sort(byName);
87+
88+ async function createChannel(type: "text" | "voice") {
89+ const name = draft.trim();
90+ if (!name) return;
91+ try {
92+ await api("/channels", { method: "POST", body: JSON.stringify({ type, name }) });
93+ setCreating(null);
94+ setDraft("");
95+ } catch {
96+ return;
97+ }
98+ }
99+
100+ async function deleteChannel(c: Channel) {
101+ if (c.type === "text" && !window.confirm(`Delete #${c.name}? This is irreversible.`)) return;
102+ await api(`/channels/${c.id}`, { method: "DELETE" }).catch(() => {});
103+ }
76104
77105 async function invite() {
78106 try {
@@ -91,31 +119,64 @@ export default function Sidebar({
91119 <nav className="flex-1 space-y-4 overflow-y-auto px-2 pb-3">
92120 <Group
93121 label="Text"
94- channels={channels.filter((c) => c.type === "text")}
122+ channels={texts}
95123 selected={selected}
96124 onSelect={onSelect}
125+ onDelete={deleteChannel}
126+ onCreate={() => {
127+ setCreating("text");
128+ setDraft("");
129+ }}
97130 icon={<Hash size={14} />}
98131 />
132+ {creating === "text" && (
133+ <ChannelForm
134+ value={draft}
135+ onChange={setDraft}
136+ onSubmit={() => createChannel("text")}
137+ onCancel={() => setCreating(null)}
138+ />
139+ )}
99140 <div>
100- <div className="px-2 py-1 text-[10px] uppercase tracking-widest text-sepia/40">Voice</div>
101- {channels
102- .filter((c) => c.type === "voice")
103- .map((c) => (
104- <VoiceChannel
105- key={c.id}
106- channel={c}
107- voice={voice}
108- occupants={voiceRooms[String(c.id)] ?? []}
109- openShare={openShare}
110- onOpenShare={onOpenShare}
111- username={username}
112- />
113- ))}
141+ <div className="flex items-center justify-between px-2 py-1">
142+ <span className="text-[10px] uppercase tracking-widest text-sepia/40">Voice</span>
143+ <Button
144+ variant="ghost"
145+ size="icon-xs"
146+ onClick={() => {
147+ setCreating("voice");
148+ setDraft("");
149+ }}
150+ title="new voice channel"
151+ >
152+ <Plus />
153+ </Button>
154+ </div>
155+ {voices.map((c) => (
156+ <VoiceChannel
157+ key={c.id}
158+ channel={c}
159+ voice={voice}
160+ occupants={voiceRooms[String(c.id)] ?? []}
161+ openShare={openShare}
162+ onOpenShare={onOpenShare}
163+ username={username}
164+ onDelete={deleteChannel}
165+ />
166+ ))}
114167 </div>
115- {channels.some((c) => c.type === "dm") && (
168+ {creating === "voice" && (
169+ <ChannelForm
170+ value={draft}
171+ onChange={setDraft}
172+ onSubmit={() => createChannel("voice")}
173+ onCancel={() => setCreating(null)}
174+ />
175+ )}
176+ {dms.length > 0 && (
116177 <Group
117178 label="DMs"
118- channels={channels.filter((c) => c.type === "dm")}
179+ channels={dms}
119180 selected={selected}
120181 onSelect={onSelect}
121182 onClose={onCloseDM}
@@ -176,6 +237,8 @@ function Group({
176237 selected,
177238 onSelect,
178239 onClose,
240+ onDelete,
241+ onCreate,
179242 icon,
180243 }: {
181244 label: string;
@@ -183,11 +246,25 @@ function Group({
183246 selected: Channel | null;
184247 onSelect: (c: Channel) => void;
185248 onClose?: (c: Channel) => void;
249+ onDelete?: (c: Channel) => void;
250+ onCreate?: () => void;
186251 icon: ReactNode;
187252 }) {
188253 return (
189254 <div>
190- <div className="px-2 py-1 text-[10px] uppercase tracking-widest text-sepia/40">{label}</div>
255+ <div className="flex items-center justify-between px-2 py-1">
256+ <span className="text-[10px] uppercase tracking-widest text-sepia/40">{label}</span>
257+ {onCreate && (
258+ <Button
259+ variant="ghost"
260+ size="icon-xs"
261+ onClick={onCreate}
262+ title={`new ${label.toLowerCase()} channel`}
263+ >
264+ <Plus />
265+ </Button>
266+ )}
267+ </div>
191268 {channels.map((c) => (
192269 <div key={c.id} className="group/dm relative">
193270 <Button
@@ -209,12 +286,55 @@ function Group({
209286 <X />
210287 </Button>
211288 )}
289+ {onDelete && !c.permanent && (
290+ <Button
291+ variant="ghost"
292+ size="icon-xs"
293+ onClick={() => onDelete(c)}
294+ title="delete channel"
295+ className="absolute top-1/2 right-1 -translate-y-1/2 opacity-0 group-hover/dm:opacity-100"
296+ >
297+ <Trash2 />
298+ </Button>
299+ )}
212300 </div>
213301 ))}
214302 </div>
215303 );
216304 }
217305
306+function ChannelForm({
307+ value,
308+ onChange,
309+ onSubmit,
310+ onCancel,
311+}: {
312+ value: string;
313+ onChange: (v: string) => void;
314+ onSubmit: () => void;
315+ onCancel: () => void;
316+}) {
317+ return (
318+ <form
319+ className="px-2 py-1"
320+ onSubmit={(e) => {
321+ e.preventDefault();
322+ onSubmit();
323+ }}
324+ >
325+ <Input
326+ autoFocus
327+ value={value}
328+ placeholder="channel name"
329+ onChange={(e) => onChange(e.target.value)}
330+ onKeyDown={(e) => {
331+ if (e.key === "Escape") onCancel();
332+ }}
333+ />
334+ </form>
335+ );
336+}
337+
218338 function VoiceChannel({
219339 channel,
220340 voice,
@@ -222,6 +342,7 @@ function VoiceChannel({
222342 openShare,
223343 onOpenShare,
224344 username,
345+ onDelete,
225346 }: {
226347 channel: Channel;
227348 voice: Voice;
@@ -229,6 +350,7 @@ function VoiceChannel({
229350 openShare: string | null;
230351 onOpenShare: (id: string) => void;
231352 username: string;
353+ onDelete: (c: Channel) => void;
232354 }) {
233355 const active = voice.channel?.id === channel.id;
234356 return (
@@ -277,6 +399,16 @@ function VoiceChannel({
277399 join
278400 </Button>
279401 )}
402+ {!channel.permanent && occupants.length === 0 && (
403+ <Button
404+ size="icon-xs"
405+ variant="ghost"
406+ onClick={() => onDelete(channel)}
407+ title="delete channel"
408+ >
409+ <Trash2 />
410+ </Button>
411+ )}
280412 </div>
281413 {active && (
282414 <div className="flex flex-col gap-0.5 px-2 pb-0.5">
web/src/lib/types.ts+11−1
@@ -14,6 +14,7 @@ export interface Channel {
1414 type: "text" | "voice" | "dm";
1515 name: string;
1616 position: number;
17+ permanent: boolean;
1718 }
1819
1920 export type Reaction = "+1" | "-1" | "heart" | "laugh";
@@ -30,9 +31,18 @@ export interface Message {
3031 }
3132
3233 export interface WSEvent {
33- type: "message" | "message_edit" | "message_delete" | "presence" | "pong";
34+ type:
35+ | "message"
36+ | "message_edit"
37+ | "message_delete"
38+ | "presence"
39+ | "pong"
40+ | "channel"
41+ | "channel_delete";
3442 message?: Message;
3543 users?: string[];
3644 roster?: UserSummary[];
3745 voice?: Record<string, string[]>;
46+ channel?: Channel;
47+ channelId?: number;
3848 }
web/src/views/Chat.tsx+10−0
@@ -47,6 +47,10 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
4747 setOnline(new Set(ev.users ?? []));
4848 if (ev.roster) setUsers(ev.roster);
4949 setVoiceRooms(ev.voice ?? {});
50+ } else if (ev.type === "channel" && ev.channel) {
51+ setChannels((cs) => (cs.some((c) => c.id === ev.channel!.id) ? cs : [...cs, ev.channel!]));
52+ } else if (ev.type === "channel_delete" && ev.channelId) {
53+ setChannels((cs) => cs.filter((c) => c.id !== ev.channelId));
5054 } else if (ev.message) {
5155 if (ev.type === "message") {
5256 setChannels((cs) => {
@@ -94,6 +98,12 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
9498 selectedId.current = selected?.id ?? null;
9599 }, [selected]);
96100
101+ useEffect(() => {
102+ if (selected && !channels.some((c) => c.id === selected.id)) {
103+ setSelected(channels.find((c) => c.type === "text") ?? channels[0] ?? null);
104+ }
105+ }, [channels, selected]);
106+
97107 useEffect(() => {
98108 api<Channel[]>("/channels")
99109 .then((cs) => {
ws.go+13−5
@@ -16,11 +16,13 @@ import (
1616 )
1717
1818 type event struct {
19- Type string `json:"type"`
20- Message *Message `json:"message,omitempty"`
21- Users []string `json:"users,omitempty"`
22- Roster []userSummary `json:"roster,omitempty"`
23- Voice map[string][]string `json:"voice,omitempty"`
19+ Type string `json:"type"`
20+ Message *Message `json:"message,omitempty"`
21+ Users []string `json:"users,omitempty"`
22+ Roster []userSummary `json:"roster,omitempty"`
23+ Voice map[string][]string `json:"voice,omitempty"`
24+ Channel *Channel `json:"channel,omitempty"`
25+ ChannelID int64 `json:"channelId,omitempty"`
2426 }
2527
2628 // wsIn is a message sent from a client over the socket.
@@ -172,6 +174,12 @@ func (h *hub) roster() []userSummary {
172174 return users
173175 }
174176
177+func (h *hub) voiceOccupied(channelID int64) bool {
178+ h.mu.Lock()
179+ defer h.mu.Unlock()
180+ return len(h.voice[channelID]) > 0
181+}
182+
175183 func (h *hub) voiceUsers() map[string][]string {
176184 h.mu.Lock()
177185 defer h.mu.Unlock()