Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance IRC join/part message support #1872

Draft
wants to merge 16 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions bridge/discord/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ type Bdiscord struct {
userMemberMap map[string]*discordgo.Member
nickMemberMap map[string]*discordgo.Member

noEmbedPartUrls bool
noEmbedUrls bool

// Webhook specific logic
useAutoWebhooks bool
transmitter *transmitter.Transmitter
Expand All @@ -57,6 +60,12 @@ func New(cfg *bridge.Config) bridge.Bridger {
b.nickMemberMap = make(map[string]*discordgo.Member)
b.channelInfoMap = make(map[string]*config.ChannelInfo)

b.noEmbedPartUrls = b.GetBool(("NoEmbedPartUrls"))
b.noEmbedUrls = b.GetBool(("NoEmbedUrls"))
if b.noEmbedPartUrls && b.noEmbedUrls {
b.Log.Info("NoEmbedUrls supersedes NoEmbedPartUrls")
}

b.useAutoWebhooks = b.GetBool("AutoWebhooks")
if b.useAutoWebhooks {
b.Log.Debug("Using automatic webhooks")
Expand Down Expand Up @@ -269,6 +278,10 @@ func (b *Bdiscord) Send(msg config.Message) (string, error) {
msg.Text = "_" + msg.Text + "_"
}

if b.noEmbedUrls || (msg.Event == config.EventJoinLeave && b.noEmbedPartUrls) {
disableEmbedUrls(&msg.Text)
}

// Handle prefix hint for unthreaded messages.
if msg.ParentNotFound() {
msg.ParentID = ""
Expand Down
5 changes: 5 additions & 0 deletions bridge/discord/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,11 @@ func (b *Bdiscord) splitURL(url string) (string, string, bool) {
return webhookURLSplit[webhookIdxID], webhookURLSplit[webhookIdxToken], true
}

func disableEmbedUrls(msg *string) {
regex := regexp.MustCompile(`(\w+://\S+)`)
*msg = regex.ReplaceAllString(*msg, "<$1>")
Kufat marked this conversation as resolved.
Show resolved Hide resolved
}

func enumerateUsernames(s string) []string {
onlySpace := true
for _, r := range s {
Expand Down
105 changes: 85 additions & 20 deletions bridge/irc/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,33 +80,48 @@ func (b *Birc) handleInvite(client *girc.Client, event girc.Event) {
}
}

func isKill(quitmsg string) bool {
return (strings.HasPrefix(quitmsg, "Killed") ||
strings.HasPrefix(quitmsg, "Local kill") ||
(len(quitmsg) > 7 && strings.HasPrefix(quitmsg[1:], "-lined")))
}

func (b *Birc) handleJoinPart(client *girc.Client, event girc.Event) {
if len(event.Params) == 0 {
b.Log.Debugf("handleJoinPart: empty Params? %#v", event)
return
}
channel := strings.ToLower(event.Params[0])
if event.Command == "KICK" && event.Params[1] == b.Nick {
b.Log.Infof("Got kicked from %s by %s", channel, event.Source.Name)
time.Sleep(time.Duration(b.GetInt("RejoinDelay")) * time.Second)
b.Remote <- config.Message{Username: "system", Text: "rejoin", Channel: channel, Account: b.Account, Event: config.EventRejoinChannels}
return
}
if event.Command == "QUIT" {
if event.Source.Name == b.Nick && strings.Contains(event.Last(), "Ping timeout") {
b.Log.Infof("%s reconnecting ..", b.Account)
b.Remote <- config.Message{Username: "system", Text: "reconnect", Channel: channel, Account: b.Account, Event: config.EventFailure}
return
if event.Command == "KICK" {
if event.Params[1] == b.Nick {
b.Log.Infof("Got kicked from %s by %s", channel, event.Source.Name)
time.Sleep(time.Duration(b.GetInt("RejoinDelay")) * time.Second)
b.Remote <- config.Message{Username: "system", Text: "rejoin", Channel: channel, Account: b.Account, Event: config.EventRejoinChannels}
} else {
Kufat marked this conversation as resolved.
Show resolved Hide resolved
msg := config.Message{
Username: "system",
Text: event.Source.Name + " kicked " + event.Params[1] + " with message: " + event.Last(),
Channel: channel,
Account: b.Account,
Event: config.EventJoinLeave,
Kufat marked this conversation as resolved.
Show resolved Hide resolved
}
b.Log.Debugf("<= Message is %#v", msg)
b.Remote <- msg
}
return
}
if event.Source.Name != b.Nick {
if b.GetBool("nosendjoinpart") {
if isActive, _ := b.isUserActive(event.Source.Name); !isActive || b.GetBool("nosendjoinpart") {
return
}
msg := config.Message{Username: "system", Text: event.Source.Name + " " + strings.ToLower(event.Command) + "s", Channel: channel, Account: b.Account, Event: config.EventJoinLeave}
partmsg := ""
if event.Command == "PART" && len(event.Params) >= 2 {
partmsg = " with message: " + event.Last()
}
msg := config.Message{Username: "system", Text: event.Source.Name + " " + strings.ToLower(event.Command) + "s" + partmsg, Channel: channel, Account: b.Account, Event: config.EventJoinLeave}
if b.GetBool("verbosejoinpart") {
b.Log.Debugf("<= Sending verbose JOIN_LEAVE event from %s to gateway", b.Account)
msg = config.Message{Username: "system", Text: event.Source.Name + " (" + event.Source.Ident + "@" + event.Source.Host + ") " + strings.ToLower(event.Command) + "s", Channel: channel, Account: b.Account, Event: config.EventJoinLeave}
msg = config.Message{Username: "system", Text: event.Source.Name + " (" + event.Source.Ident + "@" + event.Source.Host + ") " + strings.ToLower(event.Command) + "s" + partmsg, Channel: channel, Account: b.Account, Event: config.EventJoinLeave}
} else {
b.Log.Debugf("<= Sending JOIN_LEAVE event from %s to gateway", b.Account)
}
Expand All @@ -122,15 +137,37 @@ func (b *Birc) handleNewConnection(client *girc.Client, event girc.Event) {
i := b.i
b.Nick = event.Params[0]

i.Handlers.AddBg("PRIVMSG", b.handlePrivMsg)
i.Handlers.AddBg("CTCP_ACTION", b.handlePrivMsg)
i.Handlers.Add(girc.RPL_TOPICWHOTIME, b.handleTopicWhoTime)
i.Handlers.AddBg(girc.NOTICE, b.handleNotice)
i.Handlers.Add("INVITE", b.handleInvite)
i.Handlers.AddBg("JOIN", b.handleJoinPart)
i.Handlers.AddBg("PART", b.handleJoinPart)
i.Handlers.AddBg("QUIT", b.handleJoinPart)
i.Handlers.AddBg("KICK", b.handleJoinPart)
i.Handlers.Add("INVITE", b.handleInvite)
i.Handlers.AddBg("NICK", b.handleNick)
i.Handlers.AddBg(girc.NOTICE, b.handleNotice)
i.Handlers.AddBg("PRIVMSG", b.handlePrivMsg)
i.Handlers.AddBg("CTCP_ACTION", b.handlePrivMsg)
i.Handlers.AddBg("QUIT", b.handleQuit)
i.Handlers.Add(girc.RPL_TOPICWHOTIME, b.handleTopicWhoTime)
}

func (b *Birc) handleNick(client *girc.Client, event girc.Event) {
if len(event.Params) != 1 {
b.Log.Debugf("handleJoinPart: malformed nick change? %#v", event)
return
} else if isActive, activeTime := b.isUserActive(event.Source.Name); isActive {
Kufat marked this conversation as resolved.
Show resolved Hide resolved
msg := config.Message{
Username: "system",
Text: event.Source.Name + " changed nick to " + event.Params[0],
Channel: b.getPseudoChannel(),
Account: b.Account,
Event: config.EventJoinLeave,
Kufat marked this conversation as resolved.
Show resolved Hide resolved
}
b.Log.Debugf("<= Message is %#v", msg)
b.Remote <- msg
if b.ActivityTimeout != 0 {
// This doesn't count as new activity, but it does preserve the value
b.markUserActive(event.Params[0], activeTime)
}
}
}

func (b *Birc) handleNickServ() {
Expand Down Expand Up @@ -238,7 +275,35 @@ func (b *Birc) handlePrivMsg(client *girc.Client, event girc.Event) {
}

b.Log.Debugf("<= Sending message from %s on %s to gateway", event.Params[0], b.Account)
if b.ActivityTimeout > 0 {
b.Log.Debugf("<= Updating last-active time for user %s", event.Source.Name)
b.markUserActive(event.Source.Name, time.Now().Unix())
}
b.Remote <- rmsg
b.cleanActiveMap()
}

func (b *Birc) handleQuit(client *girc.Client, event girc.Event) {
if event.Source.Name == b.Nick && strings.Contains(event.Last(), "Ping timeout") {
b.Log.Infof("%s reconnecting ..", b.Account)
b.Remote <- config.Message{Username: "system", Text: "reconnect", Channel: b.getPseudoChannel(), Account: b.Account, Event: config.EventFailure}
return
} else if b.GetBool("nosendjoinpart") {
return
} else if isActive, _ := b.isUserActive(event.Source.Name); isActive || isKill(event.Last()) {
verbosequit := ""
quitmsg := ""
if len(event.Params) >= 1 {
quitmsg = " with message: " + event.Last()
}
if b.GetBool("verbosejoinpart") {
verbosequit = " (" + event.Source.Ident + "@" + event.Source.Host + ")"
}
msg := config.Message{Username: "system", Text: event.Source.Name + verbosequit + " quit" + quitmsg, Channel: b.getPseudoChannel(), Account: b.Account, Event: config.EventJoinLeave}
b.Log.Debugf("<= Message is %#v", msg)
b.Remote <- msg
return
}
}

func (b *Birc) handleRunCommands() {
Expand Down
70 changes: 70 additions & 0 deletions bridge/irc/irc.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"sort"
"strconv"
"strings"
"sync"
"time"

"github.com/42wim/matterbridge/bridge"
Expand All @@ -27,10 +28,14 @@ type Birc struct {
i *girc.Client
Nick string
names map[string][]string
activeUsers map[string]int64
activeUsersLastCleaned int64
activeUsersMutex sync.RWMutex
connected chan error
Local chan config.Message // local queue for flood control
FirstConnection, authDone bool
MessageDelay, MessageQueue, MessageLength int
ActivityTimeout int64
channels map[string]bool

*bridge.Config
Expand All @@ -41,6 +46,7 @@ func New(cfg *bridge.Config) bridge.Bridger {
b.Config = cfg
b.Nick = b.GetString("Nick")
b.names = make(map[string][]string)
b.activeUsers = make(map[string]int64)
b.connected = make(chan error)
b.channels = make(map[string]bool)

Expand All @@ -59,6 +65,16 @@ func New(cfg *bridge.Config) bridge.Bridger {
} else {
b.MessageLength = b.GetInt("MessageLength")
}
if b.GetBool("ShowActiveUserEvents") {
if b.GetInt("ActivityTimeout") == 0 {
b.ActivityTimeout = 1800 // 30 minutes
} else {
b.ActivityTimeout = int64(b.GetInt("ActivityTimeout"))
}
b.activeUsersLastCleaned = time.Now().Unix()
} else {
b.ActivityTimeout = 0 // Disable
}
b.FirstConnection = true
return b
}
Expand All @@ -77,6 +93,10 @@ func (b *Birc) Connect() error {
return errors.New("you can't enable SASL and TLSClientCertificate at the same time")
}

if b.GetBool("NoSendJoinPart") && b.GetBool("ShowActiveUserEvents") {
return errors.New("you must disable NoSendJoinPart to use ShowActiveUserEvents")
}

b.Local = make(chan config.Message, b.MessageQueue+10)
b.Log.Infof("Connecting %s", b.GetString("Server"))

Expand Down Expand Up @@ -413,3 +433,53 @@ func (b *Birc) getTLSConfig() (*tls.Config, error) {

return tlsConfig, nil
}

func (b *Birc) isUserActive(nick string) (bool, int64) {
b.Log.Debugf("checking activity for %s", nick)
if b.ActivityTimeout == 0 {
return true, 0
}
b.activeUsersMutex.RLock()
defer b.activeUsersMutex.RUnlock()
if activeTime, ok := b.activeUsers[nick]; ok {
now := time.Now().Unix()
b.Log.Debugf("last activity for %s was %d, currently %d", nick, activeTime, now)
if now < activeTime {
b.Log.Errorf("User %s has active time in the future: %d", nick, activeTime)
return true, now // err on the side of caution
}
return (now - activeTime) < b.ActivityTimeout, activeTime
}
return false, 0
}

func (b *Birc) getPseudoChannel() string {
for channelname, active := range b.channels {
if active {
return channelname
}
}
b.Log.Warningf("Bot not active in any channels!")
return ""
}

func (b *Birc) cleanActiveMap() {
now := time.Now().Unix()
if b.ActivityTimeout == 0 || (b.activeUsersLastCleaned-now < b.ActivityTimeout) {
return
}
b.activeUsersMutex.Lock()
defer b.activeUsersMutex.Unlock()
for nick, activeTime := range b.activeUsers {
if now-activeTime > b.ActivityTimeout {
b.Log.Debugf("last activity for %s was %d, currently %d. Deleting.", nick, activeTime, now)
delete(b.activeUsers, nick)
}
}
}

func (b *Birc) markUserActive(nick string, activeTime int64) {
b.activeUsersMutex.Lock()
defer b.activeUsersMutex.Unlock()
b.activeUsers[nick] = activeTime
}
17 changes: 17 additions & 0 deletions matterbridge.toml.sample
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,14 @@ RemoteNickFormat="[{PROTOCOL}] <{NICK}> "
#OPTIONAL (default false)
ShowJoinPart=false

#Only show join/part/quit information for users who have been active recently.
#OPTIONAL (default false)
ShowActiveUserEvents=false

#A user is considered active for ShowActiveUserEvents if they've spoken within this number of seconds.
#OPTIONAL (default 1800, which is 30 minutes)
ActivityTimeout=1800

#Enable to show verbose users joins/parts (ident@host) from other bridges
#Currently works for messages from the following bridges: irc
#OPTIONAL (default false)
Expand Down Expand Up @@ -939,6 +947,15 @@ IgnoreNicks=""
# IgnoreMessages="^~~ badword"
IgnoreMessages=""

# Prevent URL embeds by encasing URLs in <> angle brackets.
# Useful if trolls are a problem on the other end of your bridge.
NoEmbedUrls=false

# Prevent URL embeds in part/quit messages by encasing URLs in <> angle brackets.
# Useful if trolls spam in their quit messages or you're tired of seeing embeds for
# IRC client homepages.
NoEmbedPartUrls=false

# ReplaceMessages replaces substrings of messages in outgoing messages.
# Regular expressions are supported.
#
Expand Down