Backend/modules/structs/WebClient.go

92 lines
2.0 KiB
Go

package structs
import (
"errors"
"sync"
"github.com/gofiber/websocket/v2"
"krakatoa.net/backend/modules/logger"
)
type WebClientDb struct {
Uuid string
VoiceSessionToken string
MobileSessionToken string
}
type WebClient struct {
Uuid string
MobileConn *websocket.Conn
mobileConnMu sync.Mutex
VoiceConn *websocket.Conn
voiceConnMu sync.Mutex
MobileCmdIDs []int
mobileCmdMu sync.Mutex
VoiceCmdIDs []int
voiceCmdMu sync.Mutex
}
func (webClient *WebClient) SendBinaryMessage(conn *websocket.Conn, msg []byte) error {
if conn == webClient.MobileConn {
webClient.mobileConnMu.Lock()
defer webClient.mobileConnMu.Unlock()
return conn.WriteMessage(websocket.BinaryMessage, msg)
}
webClient.voiceConnMu.Lock()
defer webClient.voiceConnMu.Unlock()
return conn.WriteMessage(websocket.BinaryMessage, msg)
}
func (webClient *WebClient) RemoveVoiceCmdID(cmdID int) {
webClient.voiceCmdMu.Lock()
defer webClient.voiceCmdMu.Unlock()
newArr, err := removeCmdIDFromList(webClient.VoiceCmdIDs, cmdID)
if err != nil {
logger.WebVoice.Warnln("removeCmdIDFromList:", err)
} else {
webClient.VoiceCmdIDs = newArr
}
}
func (webClient *WebClient) RemoveMobileCmdID(cmdID int) {
webClient.mobileCmdMu.Lock()
defer webClient.mobileCmdMu.Unlock()
newArr, err := removeCmdIDFromList(webClient.MobileCmdIDs, cmdID)
if err != nil {
logger.WebMobile.Warnln("removeCmdIDFromList:", err)
} else {
webClient.MobileCmdIDs = newArr
}
}
func removeCmdIDFromList(arr []int, cmdID int) ([]int, error) {
index := getCmdIDIndexFromList(arr, cmdID)
if index == -1 {
logger.Web.Warnln("index", index)
return []int{}, errors.New("index not found")
}
logger.Web.Debugln("removeFromList before append", arr)
newArr := append(arr[:index], arr[index+1:]...)
logger.Web.Debugln("removeFromList after append", newArr)
return newArr, nil
}
func getCmdIDIndexFromList(arr []int, cmdID int) int {
for i := 0; i < len(arr); i++ {
if arr[i] == cmdID {
logger.Web.Debugln("getCmdIDIndexFromList", i)
return i
}
}
return -1
}