From c654d2bac48f0dcdba25cfa8809b200c78a812be Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Mon, 17 Aug 2020 15:01:53 +0200 Subject: [PATCH] Format CTCP ACTION messages in logs --- irc.go | 22 ++++++++++++++++++++++ logger.go | 34 +++++++++++++++++++++++----------- 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/irc.go b/irc.go index 4b5f4d3..9a09da4 100644 --- a/irc.go +++ b/irc.go @@ -369,3 +369,25 @@ func (js *joinSorter) Swap(i, j int) { js.channels[i], js.channels[j] = js.channels[j], js.channels[i] js.keys[i], js.keys[j] = js.keys[j], js.keys[i] } + +// parseCTCPMessage parses a CTCP message. CTCP is defined in +// https://tools.ietf.org/html/draft-oakley-irc-ctcp-02 +func parseCTCPMessage(msg *irc.Message) (cmd string, params string, ok bool) { + if (msg.Command != "PRIVMSG" && msg.Command != "NOTICE") || len(msg.Params) < 2 { + return "", "", false + } + text := msg.Params[1] + + if !strings.HasPrefix(text, "\x01") { + return "", "", false + } + text = strings.Trim(text, "\x01") + + words := strings.SplitN(text, " ", 2) + cmd = strings.ToUpper(words[0]) + if len(words) > 1 { + params = words[1] + } + + return cmd, params, true +} diff --git a/logger.go b/logger.go index c0e69c8..f6a455e 100644 --- a/logger.go +++ b/logger.go @@ -130,7 +130,11 @@ func formatMessage(msg *irc.Message) string { case "NOTICE": return fmt.Sprintf("-%s- %s", msg.Prefix.Name, msg.Params[1]) case "PRIVMSG": - return fmt.Sprintf("<%s> %s", msg.Prefix.Name, msg.Params[1]) + if cmd, params, ok := parseCTCPMessage(msg); ok && cmd == "ACTION" { + return fmt.Sprintf("* %s %s", msg.Prefix.Name, params) + } else { + return fmt.Sprintf("<%s> %s", msg.Prefix.Name, msg.Params[1]) + } default: return "" } @@ -144,24 +148,32 @@ func parseMessage(line, entity string, ref time.Time) (*irc.Message, time.Time, } line = line[11:] - var cmd, suffix string + var cmd, sender, text string if strings.HasPrefix(line, "<") { cmd = "PRIVMSG" - suffix = "> " + parts := strings.SplitN(line[1:], "> ", 2) + if len(parts) != 2 { + return nil, time.Time{}, nil + } + sender, text = parts[0], parts[1] } else if strings.HasPrefix(line, "-") { cmd = "NOTICE" - suffix = "- " + parts := strings.SplitN(line[1:], "- ", 2) + if len(parts) != 2 { + return nil, time.Time{}, nil + } + sender, text = parts[0], parts[1] + } else if strings.HasPrefix(line, "* ") { + cmd = "PRIVMSG" + parts := strings.SplitN(line[2:], " ", 2) + if len(parts) != 2 { + return nil, time.Time{}, nil + } + sender, text = parts[0], "\x01ACTION "+parts[1]+"\x01" } else { return nil, time.Time{}, nil } - i := strings.Index(line, suffix) - if i < 0 { - return nil, time.Time{}, nil - } - sender := line[1:i] - text := line[i+2:] - year, month, day := ref.Date() t := time.Date(year, month, day, hour, minute, second, 0, time.Local)