chirpnest/client.go
2019-07-31 09:24:01 +08:00

116 lines
2.6 KiB
Go

package main
import (
"errors"
"fmt"
"strings"
"time"
)
func getLockedClient(int64 id, bool createMissing) (*ChirpClient, bool) {
muxClients.Lock()
if c, ok := clients[id]; ok {
c.Mux.Lock()
return c, true
} else if createMissing {
c := new(ChirpClient)
clients[id] = c
c.TGUserID64 = id
c.Lock()
return c, true
} else {
return 0, false
}
defer muxClients.Unlock()
}
func clientSendCWMsg(userID64 int64, s string) {
c := TGCommand{
Type: commandSendMsg,
Text: s,
FromUserID64: userID64,
ToChatID64: userID64ChtWrsBot,
}
MQTGCmdQueue <- c
}
func clientRefreshCWMsg(userID64 int64, chatID64 int64, msgID64 int64) {
c := TGCommand{
Type: commandRefreshMsg,
FromUserID64: userID64,
FromChatID64: chatID64,
FromMsgID64: msgID64,
}
MQTGCmdQueue <- c
}
func clientMsgMeAck(m *ChatWarsMessageMeAck) {
if _, ok := clientsQueue[m.Msg.UserID64]; ok {
if v, ok := clientsCW.Load(m.Msg.UserID64); ok {
c := v.(*ChatWarsClient)
if c.LastUpdate.Before(m.Msg.Date) {
c.GuildID64 = m.GuildID64
c.State = m.State
c.LastUpdate = m.Msg.Date
if getObjGuildID(``) != m.GuildID64 && strings.Compare(c.Role, ``) == 0 {
clientSendCWMsg(m.Msg.UserID64, "/g_roles")
}
}
} else {
c := ChatWarsClient{
UserID64: m.UserID64,
TelegramID64: m.Msg.UserID64,
GuildID64: m.GuildID64,
State: m.State,
LastUpdate: m.Msg.Date,
}
clientsCW.Store(m.Msg.UserID64, &c)
if getObjGuildID(``) != m.GuildID64 {
clientSendCWMsg(m.Msg.UserID64, "/g_roles")
}
}
}
}
func clientMsgGoQuestAck(m *ChatWarsMessageGoQuestAck) {
if _, ok := clientsQueue[m.Msg.UserID64]; ok {
if v, ok := clientsCW.Load(m.Msg.UserID64); ok {
c := v.(*ChatWarsClient)
if c.LastUpdate.Before(m.Msg.Date) {
c.LastUpdate = m.Msg.Date
c.BusyUntil = m.Msg.Date.Add(m.Duration)
}
}
}
}
func clientMsgGRolesAck(m *ChatWarsMessageGRolesAck) {
if _, ok := clientsQueue[m.Msg.UserID64]; ok {
if v, ok := clientsCW.Load(m.Msg.UserID64); ok {
c := v.(*ChatWarsClient)
if c.LastUpdate.Before(m.Msg.Date) {
if m.CommanderID64 == c.UserID64 {
c.Role = `commander`
} else if m.BartenderID64 == c.UserID64 {
c.Role = `bartender`
} else if m.SquireID64 == c.UserID64 {
c.Role = `squire`
} else if m.TreasurerID64 == c.UserID64 {
c.Role = `treasurer`
} else {
c.Role = `none`
}
c.LastUpdate = m.Msg.Date
}
}
}
}
func clientGetUserID64(tgUserID64 int64) (int64, error) {
if v, ok := clientsCW.Load(tgUserID64); ok {
c := v.(*ChatWarsClient)
return c.UserID64, nil
}
return 0, errors.New("Unknown user_id.")
}