2023-05-31 07:11:10 -05:00
|
|
|
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() {
|
2023-06-08 06:50:34 -05:00
|
|
|
_, ok := <-c.send
|
|
|
|
|
|
|
|
if ok {
|
|
|
|
close(c.send)
|
|
|
|
}
|
2023-05-31 07:11:10 -05:00
|
|
|
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()
|
|
|
|
}
|