This repository has been archived by the owner on Dec 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.go
82 lines (68 loc) · 1.49 KB
/
socket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"encoding/json"
"fmt"
"tpbt/models"
"tpbt/services"
)
var (
Users = make(map[string]*models.BTStreamer)
)
func ListenWS(prv *services.Provider, user *models.BTStreamer) {
user.IsConnected = true
Users[user.TwitchID] = user
user.Websocket.SetCloseHandler(func(code int, text string) error {
if _, ok := Users[user.TwitchID]; ok {
delete(Users, user.TwitchID)
}
user.IsConnected = false
user.Websocket.Close()
return nil
})
user.Game = &models.Game{}
go ReceiveCommands(prv, user)
}
func ReceiveCommands(prv *services.Provider, user *models.BTStreamer) {
for user.IsConnected {
_, msg, err := user.Websocket.ReadMessage()
if err != nil {
fmt.Println(err)
continue
}
cmd := &models.Command{}
err = json.Unmarshal(msg, cmd)
if err != nil {
fmt.Println(err)
continue
}
ExecuteCommand(prv, user, cmd)
}
}
func ExecuteCommand(prv *services.Provider, user *models.BTStreamer, cmd *models.Command) {
switch cmd.Command {
case "PING":
break
case "TOGGLE_BOT":
ProcessToggleBot(prv, user, cmd)
break
case "TOGGLE_TURN":
ProcessToggleTurn(prv, user, cmd)
break
default:
fmt.Println("Unhandled command: " + cmd.Command)
break
}
}
func SendCommand(u *models.BTStreamer, cmd string, payload interface{}) error {
content, err := json.Marshal(payload)
if err != nil {
return err
}
u.MutexWS.Lock()
err = u.Websocket.WriteJSON(models.Command{
Command: cmd,
Arguments: string(content),
})
u.MutexWS.Unlock()
return err
}