xonecas.io
8058
Ir

irvc / commit e31be5d

feat: DMs and 1to1 channels

xonecas2026-10-15 e31be5d4755f4fb5d9981a8a108eefdd85cd6407 parent 68d7913

10 files changed

channels.go+113−14
@@ -2,6 +2,7 @@ package main
22
33 import (
44 "database/sql"
5+ "fmt"
56 "net/http"
67 "strconv"
78 "strings"
@@ -10,7 +11,37 @@ import (
1011 "github.com/gin-gonic/gin"
1112 )
1213
14+func dmName(u1, u2 int64) string {
15+ if u1 > u2 {
16+ u1, u2 = u2, u1
17+ }
18+ return fmt.Sprintf("u:%d:%d", u1, u2)
19+}
20+
21+func parseDM(name string) (int64, int64, bool) {
22+ var u1, u2 int64
23+ if _, err := fmt.Sscanf(name, "u:%d:%d", &u1, &u2); err != nil {
24+ return 0, 0, false
25+ }
26+ return u1, u2, true
27+}
28+
29+func (s *Server) notifyChannel(channelType, channelName string, ev event) {
30+ if channelType == "dm" {
31+ if u1, u2, ok := parseDM(channelName); ok {
32+ s.hub.sendTo(ev, u1, u2)
33+ }
34+ return
35+ }
36+ s.hub.broadcast(ev)
37+}
38+
1339 func (s *Server) handleChannels(c *gin.Context) {
40+ user := c.MustGet("user").(User)
41+ users := map[int64]string{}
42+ for _, u := range s.hub.roster() {
43+ users[u.ID] = u.Username
44+ }
1445 rows, err := s.db.Query(`SELECT id, type, name, position FROM channels ORDER BY position, id`)
1546 if err != nil {
1647 c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
@@ -24,17 +55,90 @@ func (s *Server) handleChannels(c *gin.Context) {
2455 c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
2556 return
2657 }
58+ if ch.Type == "dm" {
59+ u1, u2, ok := parseDM(ch.Name)
60+ if !ok || (u1 != user.ID && u2 != user.ID) {
61+ continue
62+ }
63+ peerID := u1
64+ if u1 == user.ID {
65+ peerID = u2
66+ }
67+ ch.Name = users[peerID]
68+ if ch.Name == "" {
69+ continue
70+ }
71+ }
2772 channels = append(channels, ch)
2873 }
2974 c.JSON(http.StatusOK, channels)
3075 }
3176
77+func (s *Server) handleOpenDM(c *gin.Context) {
78+ peerID, err := strconv.ParseInt(c.Param("userId"), 10, 64)
79+ if err != nil {
80+ c.JSON(http.StatusBadRequest, gin.H{"error": "bad user"})
81+ return
82+ }
83+ user := c.MustGet("user").(User)
84+ var peerName string
85+ if err := s.db.QueryRow(`SELECT username FROM users WHERE id = ?`, peerID).Scan(&peerName); err != nil {
86+ if err == sql.ErrNoRows {
87+ c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
88+ return
89+ }
90+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
91+ return
92+ }
93+ name := dmName(user.ID, peerID)
94+ s.db.Exec(
95+ `INSERT OR IGNORE INTO channels (type, name, position, created_at) VALUES ('dm', ?, 0, ?)`,
96+ name, time.Now().Unix(),
97+ )
98+ var ch Channel
99+ if err := s.db.QueryRow(`SELECT id, type, position FROM channels WHERE type = 'dm' AND name = ?`, name).Scan(&ch.ID, &ch.Type, &ch.Position); err != nil {
100+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
101+ return
102+ }
103+ ch.Name = peerName
104+ c.JSON(http.StatusOK, ch)
105+}
106+
107+func (s *Server) checkTextOrDM(c *gin.Context, channelID, userID int64) (string, string, bool) {
108+ var chType, chName string
109+ if err := s.db.QueryRow(`SELECT type, name FROM channels WHERE id = ?`, channelID).Scan(&chType, &chName); err != nil {
110+ if err == sql.ErrNoRows {
111+ c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
112+ return "", "", false
113+ }
114+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
115+ return "", "", false
116+ }
117+ if chType == "dm" {
118+ u1, u2, ok := parseDM(chName)
119+ if !ok || (u1 != userID && u2 != userID) {
120+ c.JSON(http.StatusForbidden, gin.H{"error": "forbidden"})
121+ return "", "", false
122+ }
123+ return chType, chName, true
124+ }
125+ if chType != "text" {
126+ c.JSON(http.StatusBadRequest, gin.H{"error": "not a text channel"})
127+ return "", "", false
128+ }
129+ return chType, chName, true
130+}
131+
32132 func (s *Server) handleMessages(c *gin.Context) {
33133 channelID, err := strconv.ParseInt(c.Param("id"), 10, 64)
34134 if err != nil {
35135 c.JSON(http.StatusBadRequest, gin.H{"error": "bad channel"})
36136 return
37137 }
138+ user := c.MustGet("user").(User)
139+ if _, _, ok := s.checkTextOrDM(c, channelID, user.ID); !ok {
140+ return
141+ }
38142 rows, err := s.db.Query(
39143 `SELECT m.id, m.channel_id, m.user_id, u.username, m.body, m.created_at, COALESCE(m.edited_at, 0)
40144 FROM messages m JOIN users u ON u.id = m.user_id
@@ -83,17 +187,8 @@ func (s *Server) handleSendMessage(c *gin.Context) {
83187 return
84188 }
85189 user := c.MustGet("user").(User)
86- var channelType string
87- if err := s.db.QueryRow(`SELECT type FROM channels WHERE id = ?`, channelID).Scan(&channelType); err != nil {
88- if err == sql.ErrNoRows {
89- c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
90- return
91- }
92- c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
93- return
94- }
95- if channelType != "text" {
96- c.JSON(http.StatusBadRequest, gin.H{"error": "not a text channel"})
190+ chType, chName, ok := s.checkTextOrDM(c, channelID, user.ID)
191+ if !ok {
97192 return
98193 }
99194 now := time.Now().Unix()
@@ -107,7 +202,7 @@ func (s *Server) handleSendMessage(c *gin.Context) {
107202 }
108203 id, _ := res.LastInsertId()
109204 msg := Message{ID: id, ChannelID: channelID, UserID: user.ID, Username: user.Username, Body: body, CreatedAt: now}
110- s.hub.broadcast(event{Type: "message", Message: &msg})
205+ s.notifyChannel(chType, chName, event{Type: "message", Message: &msg})
111206 c.JSON(http.StatusOK, msg)
112207 }
113208
@@ -145,7 +240,9 @@ func (s *Server) handleEditMessage(c *gin.Context) {
145240 return
146241 }
147242 m.Username = user.Username
148- s.hub.broadcast(event{Type: "message_edit", Message: &m})
243+ var chType, chName string
244+ s.db.QueryRow(`SELECT type, name FROM channels WHERE id = ?`, m.ChannelID).Scan(&chType, &chName)
245+ s.notifyChannel(chType, chName, event{Type: "message_edit", Message: &m})
149246 c.JSON(http.StatusOK, m)
150247 }
151248
@@ -169,6 +266,8 @@ func (s *Server) handleDeleteMessage(c *gin.Context) {
169266 c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
170267 return
171268 }
172- s.hub.broadcast(event{Type: "message_delete", Message: &m})
269+ var chType, chName string
270+ s.db.QueryRow(`SELECT type, name FROM channels WHERE id = ?`, m.ChannelID).Scan(&chType, &chName)
271+ s.notifyChannel(chType, chName, event{Type: "message_delete", Message: &m})
173272 c.Status(http.StatusNoContent)
174273 }
db.go+2−1
@@ -80,6 +80,7 @@ CREATE TABLE IF NOT EXISTS messages (
8080 edited_at INTEGER
8181 );
8282 CREATE INDEX IF NOT EXISTS idx_messages_channel ON messages(channel_id, id);
83+CREATE UNIQUE INDEX IF NOT EXISTS idx_channels_dm ON channels(name) WHERE type = 'dm';
8384 `
8485
8586 func migrate(db *sql.DB) {
@@ -88,7 +89,7 @@ func migrate(db *sql.DB) {
8889 }
8990 db.Exec(`ALTER TABLE messages ADD COLUMN edited_at INTEGER`)
9091 var n int
91- if err := db.QueryRow(`SELECT COUNT(*) FROM channels`).Scan(&n); err != nil {
92+ if err := db.QueryRow(`SELECT COUNT(*) FROM channels WHERE type != 'dm'`).Scan(&n); err != nil {
9293 log.Fatalf("count channels: %v", err)
9394 }
9495 if n > 0 {
irvc.md+7−6
@@ -10,7 +10,7 @@ Small, private chat + voice for 4–6 people on one VPS. No data gathering, full
1010
1111 **In:**
1212 - Server-side accounts, invite-only.
13-- Text channels with persisted history (IRC-like), GFM markdown, multiline compose, mentions, message editing and deletion.
13+- Text channels and 1-on-1 DMs with persisted history (IRC-like), GFM markdown, multiline compose, mentions, message editing and deletion.
1414 - Image attachments (raster only), stored on disk.
1515 - Voice channels, ephemeral (not recorded), with mute, deafen, per-peer volume, mic processing, a level-based noise gate, and a join/leave tone.
1616 - Screen sharing into a voice channel, with tab/system audio, simulcast, and a 720p/1080p quality choice.
@@ -20,7 +20,7 @@ Small, private chat + voice for 4–6 people on one VPS. No data gathering, full
2020
2121 **Out (now):**
2222 - Large scale, multi-node, clustering.
23-- Recording, video, DMs.
23+- Recording, video.
2424 - Message search, channel CRUD.
2525 - Email, OAuth, passkeys.
2626 - Backups.
@@ -58,17 +58,18 @@ WAL mode, `busy_timeout`. One file, the only state; uploaded media lives in the
5858 users (id, username, pass_hash, created_at)
5959 invites (token, created_by, expires_at, used_by, used_at)
6060 sessions (id, user_id, expires_at)
61-channels (id, type, name, position, created_at) -- type: text | voice
61+channels (id, type, name, position, created_at) -- type: text | voice | dm
6262 messages (id, channel_id, user_id, body, created_at, edited_at)
6363 ```
6464
6565 - Messages are returned joined with their author's username.
6666 - Seed: one text channel `#general`, one voice channel `general`.
67+- DMs: `type = 'dm'` channels with canonical name `u:<min_id>:<max_id>`, resolved to the peer's username for each participant.
6768 - Uploaded images: random names, raster only (no SVG/HTML), served with `nosniff`.
6869
6970 ## Behavior
7071
71-- **Channels:** seeded only (`#general` text, `general` voice). Ordered by `position`. CRUD is out of scope.
72+- **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.
7273 - **Text:** GFM markdown; single newlines are hard breaks. Messages persist; live append over WS. Rendered as timestamp, author, content.
7374 - **Mentions:** `@username` highlights the message for that user; typing `@` opens an autocomplete.
7475 - **Commands:** `/me <action>` renders an emote as `* user action`; `/collapse` hides images in the current channel.
@@ -84,8 +85,8 @@ messages (id, channel_id, user_id, body, created_at, edited_at)
8485 - React, modern. oxlint + oxfmt. Tailwind + Shadcn. LiveKit client.
8586 - Two themes (`80s-nicotine` sepia default, `tuxedo` grayscale) × light/dark, applied before first paint. Monospace, minimalist, functional.
8687 - Layout:
87- - Left sidebar: text channels, voice channels (with occupants), then users (online/offline). Collapsible; overlays on mobile.
88- - Focus pane: chat for the selected text channel, the settings pane, or a screen share.
88+ - Left sidebar: text channels, voice channels (with occupants), DMs, then users (online/offline). Collapsible; overlays on mobile.
89+ - Focus pane: chat for the selected text channel or DM, the settings pane, or a screen share.
8990 - Header: sidebar toggle, current channel, settings, or the screen share being watched.
9091 - Settings pane: theme, font size, sounds, deafen, voice-activation meter/threshold, devices, quality (audio and screen share), mic processing.
9192
main.go+1−0
@@ -132,6 +132,7 @@ 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("/dms/:userId", s.handleOpenDM)
135136 authed.GET("/channels/:id/messages", s.handleMessages)
136137 authed.POST("/channels/:id/messages", s.handleSendMessage)
137138 authed.PATCH("/messages/:id", s.handleEditMessage)
web/src/components/ChatPane.tsx+1−1
@@ -412,7 +412,7 @@ export default function ChatPane({
412412 <textarea
413413 ref={textareaRef}
414414 rows={1}
415- placeholder={`message #${channel.name}`}
415+ placeholder={`message ${channel.type === "dm" ? "@" : "#"}${channel.name}`}
416416 value={body}
417417 onChange={(e) => {
418418 setBody(e.target.value);
web/src/components/Sidebar.tsx+13−1
@@ -1,5 +1,6 @@
11 import { useState, type ReactNode } from "react";
22 import {
3+ AtSign,
34 ChevronDown,
45 ChevronRight,
56 Hash,
@@ -36,6 +37,7 @@ export default function Sidebar({
3637 channels,
3738 selected,
3839 onSelect,
40+ onSelectUser,
3941 voice,
4042 voiceRooms,
4143 openShare,
@@ -52,6 +54,7 @@ export default function Sidebar({
5254 channels: Channel[];
5355 selected: Channel | null;
5456 onSelect: (c: Channel) => void;
57+ onSelectUser: (u: UserSummary) => void;
5558 voice: Voice;
5659 voiceRooms: Record<string, string[]>;
5760 openShare: string | null;
@@ -106,6 +109,15 @@ export default function Sidebar({
106109 />
107110 ))}
108111 </div>
112+ {channels.some((c) => c.type === "dm") && (
113+ <Group
114+ label="DMs"
115+ channels={channels.filter((c) => c.type === "dm")}
116+ selected={selected}
117+ onSelect={onSelect}
118+ icon={<AtSign size={14} />}
119+ />
120+ )}
109121 <div>
110122 <button
111123 type="button"
@@ -115,7 +127,7 @@ export default function Sidebar({
115127 {showUsers ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
116128 Users
117129 </button>
118- {showUsers && <UserList users={users} online={online} />}
130+ {showUsers && <UserList users={users} online={online} onSelectUser={onSelectUser} />}
119131 </div>
120132 </nav>
121133 <div className="space-y-2 p-2">
web/src/components/UserList.tsx+20−9
@@ -1,7 +1,15 @@
11 import type { UserSummary } from "../lib/types";
22 import Dot from "./Dot";
33
4-export default function UserList({ users, online }: { users: UserSummary[]; online: Set<string> }) {
4+export default function UserList({
5+ users,
6+ online,
7+ onSelectUser,
8+}: {
9+ users: UserSummary[];
10+ online: Set<string>;
11+ onSelectUser: (u: UserSummary) => void;
12+}) {
513 const sorted = [...users].sort(
614 (a, b) =>
715 Number(online.has(b.username)) - Number(online.has(a.username)) ||
@@ -13,14 +21,17 @@ export default function UserList({ users, online }: { users: UserSummary[]; onli
1321 {sorted.map((u) => {
1422 const isOnline = online.has(u.username);
1523 return (
16- <li
17- key={u.id}
18- className={`flex items-center gap-2 rounded px-2 py-1 text-sm ${
19- isOnline ? "text-sepia" : "text-sepia/35"
20- }`}
21- >
22- <Dot on={isOnline} />
23- {u.username}
24+ <li key={u.id}>
25+ <button
26+ type="button"
27+ onClick={() => onSelectUser(u)}
28+ className={`flex w-full items-center gap-2 rounded px-2 py-1 text-left text-sm hover:bg-sepia/10 ${
29+ isOnline ? "text-sepia" : "text-sepia/35"
30+ }`}
31+ >
32+ <Dot on={isOnline} />
33+ {u.username}
34+ </button>
2435 </li>
2536 );
2637 })}
web/src/lib/types.ts+1−1
@@ -11,7 +11,7 @@ export interface UserSummary {
1111
1212 export interface Channel {
1313 id: number;
14- type: "text" | "voice";
14+ type: "text" | "voice" | "dm";
1515 name: string;
1616 position: number;
1717 }
web/src/views/Chat.tsx+30−9
@@ -1,5 +1,5 @@
11 import { useEffect, useRef, useState } from "react";
2-import { Hash, Menu, ScreenShare, Settings } from "lucide-react";
2+import { AtSign, Hash, Menu, ScreenShare, Settings } from "lucide-react";
33 import { Button } from "@/components/ui/button";
44 import { api } from "../lib/api";
55 import { usePresence } from "../lib/presence";
@@ -37,13 +37,23 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
3737 setOnline(new Set(ev.users ?? []));
3838 if (ev.roster) setUsers(ev.roster);
3939 setVoiceRooms(ev.voice ?? {});
40- } else if (ev.message && ev.message.channelId === selectedId.current) {
40+ } else if (ev.message) {
4141 if (ev.type === "message") {
42- setMessages((prev) => [...prev, ev.message!]);
43- } else if (ev.type === "message_edit") {
44- setMessages((prev) => prev.map((m) => (m.id === ev.message!.id ? ev.message! : m)));
45- } else if (ev.type === "message_delete") {
46- setMessages((prev) => prev.filter((m) => m.id !== ev.message!.id));
42+ setChannels((cs) => {
43+ if (!cs.some((c) => c.id === ev.message!.channelId)) {
44+ api<Channel[]>("/channels").then(setChannels).catch(() => {});
45+ }
46+ return cs;
47+ });
48+ }
49+ if (ev.message.channelId === selectedId.current) {
50+ if (ev.type === "message") {
51+ setMessages((prev) => [...prev, ev.message!]);
52+ } else if (ev.type === "message_edit") {
53+ setMessages((prev) => prev.map((m) => (m.id === ev.message!.id ? ev.message! : m)));
54+ } else if (ev.type === "message_delete") {
55+ setMessages((prev) => prev.filter((m) => m.id !== ev.message!.id));
56+ }
4757 }
4858 }
4959 },
@@ -81,7 +91,7 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
8191 }, []);
8292
8393 useEffect(() => {
84- if (selected?.type !== "text") {
94+ if (selected?.type !== "text" && selected?.type !== "dm") {
8595 setMessages([]);
8696 return;
8797 }
@@ -90,6 +100,16 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
90100 .catch(() => {});
91101 }, [selected]);
92102
103+ async function selectUser(u: UserSummary) {
104+ try {
105+ const dm = await api<Channel>(`/dms/${u.id}`, { method: "POST" });
106+ setChannels((cs) => (cs.some((c) => c.id === dm.id) ? cs : [...cs, dm]));
107+ selectChannel(dm);
108+ } catch {
109+ // ignore
110+ }
111+ }
112+
93113 function selectChannel(c: Channel) {
94114 setSelected(c);
95115 setOpenShare(null);
@@ -126,6 +146,7 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
126146 channels={channels}
127147 selected={selected}
128148 onSelect={selectChannel}
149+ onSelectUser={selectUser}
129150 voice={voice}
130151 voiceRooms={voiceRooms}
131152 openShare={openShare}
@@ -163,7 +184,7 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
163184 </>
164185 ) : (
165186 <>
166- {selected && <Hash size={14} />}
187+ {selected && (selected.type === "dm" ? <AtSign size={14} /> : <Hash size={14} />)}
167188 {selected?.name}
168189 </>
169190 )}
ws.go+17−0
@@ -138,6 +138,23 @@ func (h *hub) broadcast(ev event) {
138138 }
139139 }
140140
141+func (h *hub) sendTo(ev event, userIDs ...int64) {
142+ data, err := json.Marshal(ev)
143+ if err != nil {
144+ return
145+ }
146+ h.mu.Lock()
147+ defer h.mu.Unlock()
148+ for _, uid := range userIDs {
149+ for c := range h.clients[uid] {
150+ select {
151+ case c.send <- data:
152+ default:
153+ }
154+ }
155+ }
156+}
157+
141158 func (h *hub) roster() []userSummary {
142159 rows, err := h.db.Query(`SELECT id, username FROM users ORDER BY username`)
143160 if err != nil {