dispatch/irc/message.go

118 lines
1.9 KiB
Go
Raw Normal View History

2015-06-05 22:34:13 +00:00
package irc
import (
"strings"
2018-04-28 18:31:44 +00:00
"sync"
"github.com/spf13/cast"
2015-06-05 22:34:13 +00:00
)
type Message struct {
2016-12-12 06:19:22 +00:00
Prefix string
Nick string
Command string
Params []string
2015-06-05 22:34:13 +00:00
}
2016-12-16 23:11:44 +00:00
func (m *Message) LastParam() string {
if len(m.Params) > 0 {
return m.Params[len(m.Params)-1]
}
return ""
2016-12-16 23:11:44 +00:00
}
2015-06-05 22:34:13 +00:00
func parseMessage(line string) *Message {
2017-07-03 21:31:14 +00:00
line = strings.Trim(line, "\r\n ")
2015-06-05 22:34:13 +00:00
msg := Message{}
cmdStart := 0
cmdEnd := len(line)
if strings.HasPrefix(line, ":") {
cmdStart = strings.Index(line, " ") + 1
if cmdStart > 0 {
msg.Prefix = line[1 : cmdStart-1]
} else {
2017-07-03 05:35:38 +00:00
return nil
}
2015-06-05 22:34:13 +00:00
if i := strings.Index(msg.Prefix, "!"); i > 0 {
msg.Nick = msg.Prefix[:i]
} else if i := strings.Index(msg.Prefix, "@"); i > 0 {
msg.Nick = msg.Prefix[:i]
2015-06-05 22:34:13 +00:00
} else {
msg.Nick = msg.Prefix
}
}
2016-12-12 06:19:22 +00:00
var trailing string
2015-06-05 22:34:13 +00:00
if i := strings.Index(line, " :"); i > 0 {
cmdEnd = i
2016-12-12 06:19:22 +00:00
trailing = line[i+2:]
2015-06-05 22:34:13 +00:00
}
cmd := strings.Fields(line[cmdStart:cmdEnd])
if len(cmd) == 0 {
2017-07-03 05:35:38 +00:00
return nil
}
msg.Command = cmd[0]
2017-07-03 05:35:38 +00:00
2015-06-05 22:34:13 +00:00
if len(cmd) > 1 {
msg.Params = cmd[1:]
}
2017-07-03 05:35:38 +00:00
if cmdEnd != len(line) {
2016-12-12 06:19:22 +00:00
msg.Params = append(msg.Params, trailing)
2015-06-05 22:34:13 +00:00
}
return &msg
}
2018-04-28 18:31:44 +00:00
type iSupport struct {
support map[string]string
lock sync.Mutex
}
func newISupport() *iSupport {
return &iSupport{
support: map[string]string{},
}
}
func (i *iSupport) parse(params []string) {
for _, param := range params[1 : len(params)-1] {
parts := strings.SplitN(param, "=", 2)
i.lock.Lock()
if parts[0][0] == '-' {
delete(i.support, parts[0][1:])
} else if len(parts) == 2 {
i.support[parts[0]] = parts[1]
} else {
i.support[param] = ""
}
i.lock.Unlock()
}
}
func (i *iSupport) Has(key string) bool {
i.lock.Lock()
_, has := i.support[key]
i.lock.Unlock()
return has
}
func (i *iSupport) Get(key string) string {
i.lock.Lock()
v := i.support[key]
i.lock.Unlock()
return v
}
func (i *iSupport) GetInt(key string) int {
i.lock.Lock()
v := cast.ToInt(i.support[key])
i.lock.Unlock()
return v
}