xonecas.io
8058
Ir

irvc / files

irvc / ws.go

8.5 KB
1package main
2
3import (
4	"database/sql"
5	"encoding/json"
6	"net"
7	"net/http"
8	"net/url"
9	"sort"
10	"strconv"
11	"sync"
12	"time"
13
14	"github.com/gin-gonic/gin"
15	"github.com/gorilla/websocket"
16)
17
18type 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][]VoiceOccupant `json:"voice,omitempty"`
24	Channel   *Channel                   `json:"channel,omitempty"`
25	ChannelID int64                      `json:"channelId,omitempty"`
26	Username  string                     `json:"username,omitempty"`
27}
28
29// VoiceOccupant is one user in a voice channel, as broadcast with presence.
30// A user with several connections counts as muted or deafened only when every
31// one of them is, so a second unmuted tab is never hidden.
32type VoiceOccupant struct {
33	Name     string `json:"name"`
34	Muted    bool   `json:"muted"`
35	Deafened bool   `json:"deafened"`
36}
37
38// wsIn is a message sent from a client over the socket.
39type wsIn struct {
40	Type      string `json:"type"`
41	ChannelID int64  `json:"channelId"`
42	Muted     bool   `json:"muted"`
43	Deafened  bool   `json:"deafened"`
44}
45
46type client struct {
47	hub      *hub
48	userID   int64
49	username string
50	voiceID  int64
51	typedAt  time.Time // last accepted typing event; only touched by readPump
52	muted    bool
53	deafened bool
54	conn     *websocket.Conn
55	send     chan []byte
56}
57
58type hub struct {
59	mu      sync.Mutex
60	clients map[int64]map[*client]bool
61	voice   map[int64]map[*client]bool
62	db      *sql.DB
63}
64
65func newHub(db *sql.DB) *hub {
66	return &hub{clients: map[int64]map[*client]bool{}, voice: map[int64]map[*client]bool{}, db: db}
67}
68
69func (h *hub) register(c *client) {
70	h.mu.Lock()
71	if h.clients[c.userID] == nil {
72		h.clients[c.userID] = map[*client]bool{}
73	}
74	h.clients[c.userID][c] = true
75	h.mu.Unlock()
76	h.broadcastPresence()
77}
78
79func (h *hub) unregister(c *client) {
80	h.mu.Lock()
81	if set, ok := h.clients[c.userID]; ok {
82		delete(set, c)
83		if len(set) == 0 {
84			delete(h.clients, c.userID)
85		}
86	}
87	h.clearVoiceLocked(c)
88	h.mu.Unlock()
89	close(c.send)
90	h.broadcastPresence()
91}
92
93// clearVoiceLocked drops a client's voice occupancy. Caller holds h.mu.
94func (h *hub) clearVoiceLocked(c *client) {
95	if c.voiceID == 0 {
96		return
97	}
98	if set := h.voice[c.voiceID]; set != nil {
99		delete(set, c)
100		if len(set) == 0 {
101			delete(h.voice, c.voiceID)
102		}
103	}
104	c.voiceID = 0
105}
106
107// setVoice moves a client into a voice channel (0 for none) with its current
108// mute and deafen state, and rebroadcasts. Occupancy is keyed by connection,
109// not user, so one tab leaving a channel does not evict another tab that is
110// still in it.
111func (h *hub) setVoice(c *client, channelID int64, muted, deafened bool) {
112	h.mu.Lock()
113	h.clearVoiceLocked(c)
114	c.voiceID = channelID
115	c.muted = muted
116	c.deafened = deafened
117	if channelID != 0 {
118		if h.voice[channelID] == nil {
119			h.voice[channelID] = map[*client]bool{}
120		}
121		h.voice[channelID][c] = true
122	}
123	h.mu.Unlock()
124	h.broadcastPresence()
125}
126
127// typingEvery is the shortest gap between typing events relayed for one
128// connection, so a client cannot flood a channel with them.
129const typingEvery = 2 * time.Second
130
131// typing tells everyone who can see channelID that c's user is typing in it.
132// It is ephemeral: nothing is stored, and it is relayed only to people who are
133// allowed in the channel (everyone for text, the two participants for a DM).
134func (h *hub) typing(c *client, channelID int64) {
135	if time.Since(c.typedAt) < typingEvery {
136		return
137	}
138	var chType, chName string
139	if h.db.QueryRow(`SELECT type, name FROM channels WHERE id = ?`, channelID).Scan(&chType, &chName) != nil {
140		return
141	}
142	ev := event{Type: "typing", ChannelID: channelID, Username: c.username}
143	switch chType {
144	case "text":
145		h.broadcast(ev)
146	case "dm":
147		if u1, u2, ok := parseDM(chName); ok && (u1 == c.userID || u2 == c.userID) {
148			h.sendTo(ev, u1, u2)
149		} else {
150			return
151		}
152	default:
153		return
154	}
155	c.typedAt = time.Now()
156}
157
158func (h *hub) users() []string {
159	h.mu.Lock()
160	defer h.mu.Unlock()
161	seen := map[string]bool{}
162	users := []string{}
163	for _, set := range h.clients {
164		for c := range set {
165			if !seen[c.username] {
166				seen[c.username] = true
167				users = append(users, c.username)
168			}
169			break
170		}
171	}
172	return users
173}
174
175func (h *hub) broadcast(ev event) {
176	data, err := json.Marshal(ev)
177	if err != nil {
178		return
179	}
180	h.mu.Lock()
181	defer h.mu.Unlock()
182	for _, set := range h.clients {
183		for c := range set {
184			select {
185			case c.send <- data:
186			default:
187			}
188		}
189	}
190}
191
192func (h *hub) sendTo(ev event, userIDs ...int64) {
193	data, err := json.Marshal(ev)
194	if err != nil {
195		return
196	}
197	h.mu.Lock()
198	defer h.mu.Unlock()
199	for _, uid := range userIDs {
200		for c := range h.clients[uid] {
201			select {
202			case c.send <- data:
203			default:
204			}
205		}
206	}
207}
208
209func (h *hub) roster() []userSummary {
210	rows, err := h.db.Query(`SELECT id, username FROM users ORDER BY username`)
211	if err != nil {
212		return nil
213	}
214	defer rows.Close()
215	users := []userSummary{}
216	for rows.Next() {
217		var u userSummary
218		if err := rows.Scan(&u.ID, &u.Username); err != nil {
219			return users
220		}
221		users = append(users, u)
222	}
223	return users
224}
225
226func (h *hub) voiceOccupied(channelID int64) bool {
227	h.mu.Lock()
228	defer h.mu.Unlock()
229	return len(h.voice[channelID]) > 0
230}
231
232func (h *hub) voiceUsers() map[string][]VoiceOccupant {
233	h.mu.Lock()
234	defer h.mu.Unlock()
235	out := map[string][]VoiceOccupant{}
236	for channelID, set := range h.voice {
237		byName := map[string]*VoiceOccupant{}
238		for c := range set {
239			o := byName[c.username]
240			if o == nil {
241				o = &VoiceOccupant{Name: c.username, Muted: true, Deafened: true}
242				byName[c.username] = o
243			}
244			o.Muted = o.Muted && c.muted
245			o.Deafened = o.Deafened && c.deafened
246		}
247		names := make([]string, 0, len(byName))
248		for name := range byName {
249			names = append(names, name)
250		}
251		sort.Strings(names)
252		occupants := make([]VoiceOccupant, 0, len(names))
253		for _, name := range names {
254			occupants = append(occupants, *byName[name])
255		}
256		out[strconv.FormatInt(channelID, 10)] = occupants
257	}
258	return out
259}
260
261func (h *hub) broadcastPresence() {
262	h.broadcast(event{
263		Type:   "presence",
264		Users:  h.users(),
265		Roster: h.roster(),
266		Voice:  h.voiceUsers(),
267	})
268}
269
270// checkOrigin allows same-host origins. It lives on the (shared) upgrader, so
271// it must not be reassigned per request: concurrent upgrades would race.
272func checkOrigin(r *http.Request) bool {
273	origin := r.Header.Get("Origin")
274	if origin == "" {
275		return true
276	}
277	u, err := url.Parse(origin)
278	if err != nil {
279		return false
280	}
281	host := r.Host
282	if h, _, err := net.SplitHostPort(host); err == nil {
283		host = h
284	}
285	return u.Hostname() == host
286}
287
288var upgrader = websocket.Upgrader{
289	ReadBufferSize:  1024,
290	WriteBufferSize: 1024,
291	CheckOrigin:     checkOrigin,
292}
293
294func (s *Server) handleWS(c *gin.Context) {
295	user := c.MustGet("user").(User)
296	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
297	if err != nil {
298		return
299	}
300	cl := &client{hub: s.hub, userID: user.ID, username: user.Username, conn: conn, send: make(chan []byte, 64)}
301	s.hub.register(cl)
302	go cl.writePump()
303	cl.readPump()
304}
305
306const (
307	writeWait  = 10 * time.Second
308	pongWait   = 30 * time.Second
309	pingPeriod = (pongWait * 9) / 10
310)
311
312func (c *client) readPump() {
313	defer func() {
314		c.hub.unregister(c)
315		c.conn.Close()
316	}()
317	c.conn.SetReadLimit(4096)
318	c.conn.SetReadDeadline(time.Now().Add(pongWait))
319	c.conn.SetPongHandler(func(string) error {
320		c.conn.SetReadDeadline(time.Now().Add(pongWait))
321		return nil
322	})
323	for {
324		_, msg, err := c.conn.ReadMessage()
325		if err != nil {
326			return
327		}
328		var in wsIn
329		if json.Unmarshal(msg, &in) != nil {
330			continue
331		}
332		switch in.Type {
333		case "voice":
334			c.hub.setVoice(c, in.ChannelID, in.Muted, in.Deafened)
335		case "typing":
336			c.hub.typing(c, in.ChannelID)
337		case "ping":
338			// Application-level heartbeat: the browser answers protocol pings
339			// itself, so a client cannot see them. This lets it detect a
340			// half-open socket (sleep, dead network) instead of trusting it.
341			select {
342			case c.send <- []byte(`{"type":"pong"}`):
343			default:
344			}
345		}
346	}
347}
348
349func (c *client) writePump() {
350	ticker := time.NewTicker(pingPeriod)
351	defer ticker.Stop()
352	for {
353		select {
354		case data, ok := <-c.send:
355			c.conn.SetWriteDeadline(time.Now().Add(writeWait))
356			if !ok {
357				c.conn.WriteMessage(websocket.CloseMessage, []byte{})
358				return
359			}
360			if err := c.conn.WriteMessage(websocket.TextMessage, data); err != nil {
361				return
362			}
363		case <-ticker.C:
364			c.conn.SetWriteDeadline(time.Now().Add(writeWait))
365			if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
366				return
367			}
368		}
369	}
370}