mirror of
https://codeberg.org/SafeTwitch/safetwitch-backend.git
synced 2024-12-22 13:13:00 -05:00
88 lines
1.5 KiB
Go
88 lines
1.5 KiB
Go
package chat
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/gorilla/websocket"
|
|
uuid "github.com/satori/go.uuid"
|
|
)
|
|
|
|
var ClientStreamerList map[string]Client
|
|
|
|
type Client struct {
|
|
ID string
|
|
Conn *websocket.Conn
|
|
send chan string
|
|
FollowingStreamers map[string]bool
|
|
}
|
|
|
|
var upgrader = websocket.Upgrader{
|
|
ReadBufferSize: 1024,
|
|
WriteBufferSize: 1024,
|
|
CheckOrigin: func(r *http.Request) bool {
|
|
return true
|
|
},
|
|
}
|
|
|
|
func newClient(conn *websocket.Conn) *Client {
|
|
client := &Client{
|
|
ID: uuid.NewV1().String(),
|
|
Conn: conn,
|
|
send: make(chan string, 256),
|
|
FollowingStreamers: map[string]bool{},
|
|
}
|
|
|
|
ClientHandler.AddClient(client)
|
|
return client
|
|
}
|
|
|
|
func (c *Client) Read() {
|
|
defer c.Conn.Close()
|
|
|
|
for {
|
|
_, msg, err := c.Conn.ReadMessage()
|
|
if err != nil {
|
|
DisconnectClient(c)
|
|
break
|
|
}
|
|
ClientMessageHandler(c, string(msg))
|
|
}
|
|
}
|
|
|
|
func (c *Client) Write() {
|
|
ticker := time.NewTicker(time.Second)
|
|
defer ticker.Stop()
|
|
|
|
for {
|
|
select {
|
|
case message := <-c.send:
|
|
err := c.Conn.WriteMessage(websocket.TextMessage, []byte(message))
|
|
if err != nil {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (c *Client) Close() {
|
|
close(c.send)
|
|
c.Conn.Close()
|
|
}
|
|
|
|
func DisconnectClient(c *Client) {
|
|
ClientHandler.DeleteClient(c.ID)
|
|
}
|
|
|
|
func ServeWS(context *gin.Context) {
|
|
ws, err := upgrader.Upgrade(context.Writer, context.Request, nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
client := newClient(ws)
|
|
|
|
go client.Write()
|
|
go client.Read()
|
|
}
|