chirpnest/client.go
2019-07-31 14:19:09 +08:00

109 lines
2.4 KiB
Go

package main
import (
"errors"
"strings"
)
func getLockedClient(id int64, createMissing bool) (*ChirpClient, bool) {
muxClients.RLock()
if c, ok := clients[id]; ok {
c.Mux.Lock()
muxClients.RUnlock()
return c, true
} else if createMissing {
c := new(ChirpClient)
c.TGUserID64 = id
c.Active = false
c.Lock()
muxClients.RUnlock()
muxClients.Lock()
clients[id] = c
muxClients.Unlock()
return c, true
} else {
muxClients.RUnlock()
return 0, false
}
}
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 clt, ok := getLockedClient(m.Msg.UserID64, false); ok {
if clt.Active {
if clt.CWLastUpdate.Before(m.Msg.Date) {
clt.CWGuildID64 = m.GuildID64
clt.CWUserID64 = m.UserID64
clt.CWState = m.State
clt.CWLastUpdate = m.Msg.Date
if getObjGuildID(``) != m.GuildID64 && strings.Compare(clt.CWRole, ``) == 0 {
clientSendCWMsg(m.Msg.UserID64, "/g_roles")
}
}
}
clt.Unlock()
}
}
func clientMsgGoQuestAck(m *ChatWarsMessageGoQuestAck) {
if clt, ok := getLockedClient(m.Msg.UserID64, false); ok {
if clt.Active {
if clt.CWLastUpdate.Before(m.Msg.Date) {
clt.CWLastUpdate = m.Msg.Date
clt.CWBusyUntil = m.Msg.Date.Add(m.Duration)
}
}
clt.Unlock()
}
}
func clientMsgGRolesAck(m *ChatWarsMessageGRolesAck) {
if clt, ok := getLockedClient(m.Msg.UserID64, false); ok {
if clt.Active {
if clt.CWLastUpdate.Before(m.Msg.Date) {
if m.CommanderID64 == clt.CWUserID64 {
c.Role = `commander`
} else if m.BartenderID64 == clt.CWUserID64 {
c.Role = `bartender`
} else if m.SquireID64 == clt.CWUserID64 {
c.Role = `squire`
} else if m.TreasurerID64 == clt.CWUserID64 {
c.Role = `treasurer`
} else {
c.Role = `none`
}
clt.CWLastUpdate = m.Msg.Date
}
}
clt.Unlock()
}
}
func clientGetCWUserID64(tgUserID64 int64) (int64, error) {
if clt, ok := getLockedClient(m.Msg.UserID64, false); ok {
i := clt.CWUserID64
clt.Unlock()
return i, nil
}
return 0, errors.New("Unknown user_id.")
}