sircd/irc/message.go

72 lines
1.3 KiB
Go
Raw Normal View History

2020-02-25 15:51:22 +00:00
package irc
2019-08-20 03:48:43 +00:00
import (
2019-08-21 06:15:12 +00:00
"errors"
"fmt"
2019-08-20 03:48:43 +00:00
"regexp"
2019-08-21 06:15:12 +00:00
"strings"
2019-08-20 03:48:43 +00:00
)
type ircMessage struct {
from *ircClient
//received
2019-08-21 06:15:12 +00:00
tags string
source string
raw string
2019-08-20 03:48:43 +00:00
command string
2019-08-21 06:15:12 +00:00
params []string
2019-08-20 03:48:43 +00:00
}
2019-08-21 06:15:12 +00:00
func parseIrcLine(line string) (*ircMessage, error) {
//FIXME do this at compile or start time instead of every message
ircregex, err := regexp.Compile(`^(\@(\S+) )?(?:[:](\S+) )?(\S+)(?: ([^:].+?))?(?: [:](.+))?$`)
2019-08-20 03:48:43 +00:00
2019-08-21 06:15:12 +00:00
if err != nil {
panic("can't happen")
}
2019-08-20 03:48:43 +00:00
2019-08-21 06:15:12 +00:00
line = strings.TrimRight(line, "\r\n")
2019-08-20 03:48:43 +00:00
2019-08-21 06:15:12 +00:00
m := new(ircMessage)
m.raw = line
2019-08-20 03:48:43 +00:00
2019-08-21 06:15:12 +00:00
if ircregex.MatchString(m.raw) == false {
return nil, errors.New("parse error")
}
matches := ircregex.FindAllStringSubmatch(m.raw, -1)
2019-08-20 03:48:43 +00:00
2019-08-21 06:15:12 +00:00
if len(matches) == 0 {
return nil, errors.New("parse error")
}
2019-08-20 03:48:43 +00:00
2019-08-21 06:15:12 +00:00
match := matches[0]
fmt.Printf("%+v\n", match)
fmt.Printf("%+v\n", len(match))
m.tags = match[2]
m.source = match[3]
m.command = strings.ToUpper(match[4])
if len(match[5]) > 0 {
m.params = strings.Fields(match[5])
}
if len(match[6]) > 0 {
m.params = append(m.params, match[6])
}
2019-08-20 03:48:43 +00:00
2019-08-21 06:15:12 +00:00
return m, nil
2019-08-20 03:48:43 +00:00
}
2019-08-21 06:15:12 +00:00
func NewIrcMessageFromString(line string, from *ircClient) *ircMessage {
2019-08-21 08:15:45 +00:00
2019-08-21 06:15:12 +00:00
msg, err := parseIrcLine(line)
2019-08-21 08:15:45 +00:00
msg.from = from
2019-08-21 06:15:12 +00:00
if err != nil {
panic("wat")
}
return msg
}
2019-08-20 03:48:43 +00:00
func (m *ircMessage) String() string {
2019-08-21 06:15:12 +00:00
return fmt.Sprintf("IRCMessage<%s>('%s')", m.command, strings.Join(m.params, ","))
2019-08-20 03:48:43 +00:00
}