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

Add Platform Agnostic Commands #1997

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 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
8 changes: 5 additions & 3 deletions bridge/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
)

const (
EventWelcomeMsg = "welcome"
EventJoinLeave = "join_leave"
EventTopicChange = "topic_change"
EventFailure = "failure"
Expand Down Expand Up @@ -179,9 +180,10 @@ type Protocol struct {
}

type ChannelOptions struct {
Key string // irc, xmpp
WebhookURL string // discord
Topic string // zulip
Key string // irc, xmpp
WebhookURL string // discord
Topic string // zulip
WelcomeMessage string // all
}

type Bridge struct {
Expand Down
49 changes: 49 additions & 0 deletions bridge/telegram/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,8 @@ func (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {
spew.Dump(update.Message)
}

b.handleGroupUpdate(update)

var message *tgbotapi.Message

rmsg := config.Message{Account: b.Account, Extra: make(map[string][]interface{})}
Expand Down Expand Up @@ -261,6 +263,53 @@ func (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {
}
}

func (b *Btelegram) handleGroupUpdate(update tgbotapi.Update) {
msg := update.Message

switch {
case msg.NewChatMembers != nil:
b.handleUserJoin(update)
case msg.LeftChatMember != nil:
b.handleUserLeave(update)
}
}
func (b *Btelegram) handleUserJoin(update tgbotapi.Update) {
msg := update.Message

for _, user := range msg.NewChatMembers {

rmsg := config.Message{
UserID: strconv.FormatInt(user.ID, 10),
Username: user.FirstName, // for some reason all the other name felids are empty on this event (at least for me)
Channel: strconv.FormatInt(msg.Chat.ID, 10),
Account: b.Account,
Protocol: b.Protocol,
Event: config.EventJoinLeave,
Text: "joined chat",
}
b.Remote <- rmsg

rmsg.Event = config.EventWelcomeMsg
b.Remote <- rmsg
}
}
func (b *Btelegram) handleUserLeave(update tgbotapi.Update) {
msg := update.Message
user := msg.LeftChatMember

rmsg := config.Message{
UserID: strconv.FormatInt(user.ID, 10),
Username: user.FirstName, // for some reason all the other name felids are empty on this event (at least for me)
Channel: strconv.FormatInt(msg.Chat.ID, 10),
Account: b.Account,
Protocol: b.Protocol,
Event: config.EventJoinLeave,
Text: "left chat",
}

b.Remote <- rmsg
}

// handleDownloadAvatar downloads the avatar of userid from channel
// sends a EVENT_AVATAR_DOWNLOAD message to the gateway if successful.
// logs an error message if it fails
Expand Down
2 changes: 2 additions & 0 deletions bridge/whatsappmulti/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ func (b *Bwhatsapp) handleUserJoin(event *events.GroupInfo) {
Event: config.EventJoinLeave,
Text: "joined chat",
}
b.Remote <- rmsg

rmsg.Event = config.EventWelcomeMsg
b.Remote <- rmsg
}
}
Expand Down
68 changes: 68 additions & 0 deletions gateway/channelstore.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package gateway

import (
"encoding/gob"

"github.com/42wim/matterbridge/bridge/config"
"github.com/philippgille/gokv"
"github.com/philippgille/gokv/bbolt"
"github.com/philippgille/gokv/encoding"
)

type ChannelData struct {
HasWelcomeMessage bool
WelcomeMessage config.Message
}

func (r *Router) getChannelStore(path string) gokv.Store {
gob.Register(map[string]interface{}{})
gob.Register(config.FileInfo{})

options := bbolt.Options{
BucketName: "ChannelData",
Path: path,
Codec: encoding.Gob,
}

gob.Register(map[string]interface{}{})

store, err := bbolt.NewStore(options)
if err != nil {
r.logger.Errorf("Could not connect to db: %s", path)
}

return store
}

func (r *Router) getWelcomeMessage(Channel string) *config.Message {
channelData := new(ChannelData)
found, err := r.ChannelStore.Get(Channel, channelData)
if err != nil {
r.logger.Error(err)
}

if found && channelData.HasWelcomeMessage {
return &channelData.WelcomeMessage
}

return nil
}

func (r *Router) setWelcomeMessage(Channel string, newWelcomeMessage *config.Message) error {
channelData := new(ChannelData)
r.ChannelStore.Get(Channel, channelData)

if newWelcomeMessage == nil {
channelData.HasWelcomeMessage = false
channelData.WelcomeMessage = config.Message{}
} else {
channelData.HasWelcomeMessage = true
channelData.WelcomeMessage = *newWelcomeMessage
}

err := r.ChannelStore.Set(Channel, channelData)
if err != nil {
r.logger.Errorf(err.Error())
}
return err
}
171 changes: 171 additions & 0 deletions gateway/command.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
package gateway

import (
"strings"

"github.com/42wim/matterbridge/bridge/config"
)

// returns true if a command was registered (therefore a should not be relayed
func (r *Router) handleCommand(msg *config.Message) bool {
help := `!optout - opt out from all message relaying
!optoutmedia - only opt out from relaying attachments
!optin - opt back into chat relaying
!setwelcome - set channel welcome message (admin)
!unsetwelcome - clear channel welcome message (admin)
!help - display this message`

isAdmin := r.isAdmin(msg)
addTextFromCaptions(msg)
cmd := msg.Text

switch {
case cmd == "!help":
r.logger.Debug("!help")
r.replyCmd(msg, help)
case cmd == "!chatId":
r.logger.Infof("!chatId: %s", msg.Channel)
case cmd == "!userId":
r.logger.Infof("!userId: %s", msg.UserID)
case cmd == "!ping":
r.logger.Debug("!pong: %s,%s", msg.Channel, msg.UserID)
r.replyCmd(msg, "pong!")
case cmd == "!pingdm":
r.logger.Debug("!pongdm: %s,%s", msg.Channel, msg.UserID)
r.replyDM(msg, "pong!")
case cmd == "!optin":
r.logger.Debugf("!optin: %s", msg.UserID)
r.handleOptOutCmd(msg, OptIn)
case cmd == "!optout":
r.logger.Debugf("!optout: %s", msg.UserID)
r.handleOptOutCmd(msg, OptOut)
case cmd == "!optoutmedia":
r.logger.Debugf("!optoutmedia: %s", msg.UserID)
r.handleOptOutCmd(msg, OptOutMediaOnly)
case isAdmin && strings.HasPrefix(cmd, "!setwelcome"):
r.logger.Debugf("!setwelcome: %s - %+v", msg.Channel, msg)
r.handleWelcomeCmd(msg, msg)
case isAdmin && strings.HasPrefix(cmd, "!unsetwelcome"):
r.logger.Debugf("!unsetwelcome: %s", msg.Channel)
r.handleWelcomeCmd(msg, nil)
case cmd == "!echowelcome":
r.logger.Debugf("!echowelcome: %s,%s", msg.Channel, msg.UserID)
r.handleEchoWelcomeCmd(msg)
default:
return false
}

return true
}

func (r *Router) isAdmin(msg *config.Message) bool {
admins, _ := r.GetStringSlice("Admins")

for _, ID := range admins {
if msg.UserID == ID {
return true
}
}
return false
}

func addTextFromCaptions(msg *config.Message) {
for _, f := range msg.Extra["file"] {
fi := f.(config.FileInfo)

msg.Text += fi.Comment
}
}

func (r *Router) replyCmd(msg *config.Message, str string) {
srcBridge := r.getBridge(msg.Account)

reply := config.Message{
Text: str,
Channel: msg.Channel,
Account: msg.Account,
Username: "",
UserID: "",
Protocol: msg.Protocol,
Gateway: msg.Gateway,
ParentID: msg.ID,
}

srcBridge.Send(reply)
}

func (r *Router) replyDM(msg *config.Message, str string) {
srcBridge := r.getBridge(msg.Account)

reply := config.Message{
Text: str,
Channel: msg.UserID,
Account: msg.Account,
Username: "",
UserID: "",
Protocol: msg.Protocol,
Gateway: msg.Gateway,
}

srcBridge.Send(reply)
}

func (r *Router) sendDM(msg *config.Message, dmChannel string) {
srcBridge := r.getBridge(msg.Account)

msg.Channel = dmChannel
msg.Username = ""
msg.UserID = ""
msg.ID = ""
msg.Event = ""

srcBridge.Send(*msg)
}

func (r *Router) handleOptOutCmd(msg *config.Message, newStatus OptOutStatus) {
err := r.setOptOutStatus(msg.UserID, newStatus)

reply := "Successfully set message relay preferences."
if err != nil {
reply = "Error setting message relay preferences, try again later or contact the moderators."
}

r.replyCmd(msg, reply)
}

func (r *Router) handleWelcomeCmd(msg *config.Message, welcomeMsg *config.Message) {

if welcomeMsg != nil {
welcomeMsg.Text = strings.Replace(welcomeMsg.Text, "!setwelcome ", "", 1)

for i, f := range welcomeMsg.Extra["file"] {
fi := f.(config.FileInfo)
fi.Comment = strings.Replace(fi.Comment, "!setwelcome ", "", 1)

welcomeMsg.Extra["file"][i] = fi
}
}

err := r.setWelcomeMessage(msg.Channel, welcomeMsg)

reply := "Successfully set welcome message for channel."
if welcomeMsg == nil {
reply = "Successfully removed welcome message for channel."
}
if err != nil {
reply = "Error setting channel welcome message, try again later or contact the moderators."
}

r.replyCmd(msg, reply)
}

func (r *Router) handleEchoWelcomeCmd(msg *config.Message) {
msg.Event = config.EventWelcomeMsg

if r.getWelcomeMessage(msg.Channel) == nil {
r.replyCmd(msg, "No welcome message configured, set with !setwelcome")
return
}

r.handleEventWelcome(msg)
}
Loading