TerraOceanPlugin/GoBot/server/hub.go

94 lines
1.8 KiB
Go

2019-10-12 14:07:40 +07:00
package server
import (
"fmt"
2019-10-17 09:08:57 +07:00
"strconv"
"strings"
"github.com/gorilla/websocket"
2019-10-17 09:08:57 +07:00
"TerraOceanBot/db"
)
2019-10-12 14:07:40 +07:00
var clients = make(map[*websocket.Conn]bool)
var connectedUsers = make(map[string]bool)
2019-10-12 14:07:40 +07:00
func newSession(who *websocket.Conn) {
clients[who] = true
2019-10-13 13:31:06 +07:00
who.WriteMessage(websocket.TextMessage, []byte("sync"))
2019-10-12 14:07:40 +07:00
}
func disconnectSession(who *websocket.Conn) {
delete(clients, who)
}
func handleIncomingMessage(who *websocket.Conn, msg string) {
message := strings.SplitN(msg, " ", 2)
switch message[0] {
case "query":
if len(message) < 2 {
return
}
if !connectedUsers[message[1]] {
2019-10-15 14:58:58 +07:00
fmt.Println(message[1], "tried to connect. Disconnecting!")
fmt.Println(connectedUsers)
who.WriteMessage(websocket.TextMessage, []byte("leave "+message[1]))
}
2019-10-17 09:08:57 +07:00
case "active":
arg := strings.Split(msg, " ")
if len(arg) < 3 {
2019-10-17 09:08:57 +07:00
return
}
arg[1] = strings.Join(arg[1:len(arg)-1], " ")
arg[2] = arg[len(arg)-1]
2019-10-17 09:08:57 +07:00
id, err := db.GetDiscordID(arg[1])
if err != nil {
fmt.Println(err)
return
}
value, err := strconv.Atoi(arg[2])
2019-10-17 09:08:57 +07:00
if err != nil {
fmt.Println(err)
return
}
err = db.AddActiveLevel(id, value)
if err != nil {
fmt.Println(err)
return
}
default:
fmt.Println("Unknown message:" + msg)
}
}
func broadcast(message string) {
for k, _ := range clients {
k.WriteMessage(websocket.TextMessage, []byte(message))
}
}
func ConnectUser(mcUsername string) {
connectedUsers[mcUsername] = true
}
func DisconnectUser(mcUsername string) {
delete(connectedUsers, mcUsername)
broadcast("leave " + mcUsername)
}
func RequestSync() {
broadcast("sync")
2019-10-12 14:07:40 +07:00
}
func VoteNotification() {
broadcast("vote")
}
func WhitelistAdd(minecraftUsername string) {
broadcast("whitelistadd " + minecraftUsername)
}
func WhitelistRemove(minecraftUsername string) {
broadcast("whitelistremove " + minecraftUsername)
}