5
0
mirror of https://github.com/cwinfo/matterbridge.git synced 2024-11-22 12:50:27 +00:00

Refactor using factory

This commit is contained in:
Wim 2018-02-27 00:33:21 +01:00
parent 5fbd8a3be0
commit 2bac867382
15 changed files with 279 additions and 371 deletions

View File

@ -2,10 +2,10 @@ package api
import ( import (
"encoding/json" "encoding/json"
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/labstack/echo" "github.com/labstack/echo"
"github.com/labstack/echo/middleware" "github.com/labstack/echo/middleware"
log "github.com/sirupsen/logrus"
"github.com/zfjagann/golang-ring" "github.com/zfjagann/golang-ring"
"net/http" "net/http"
"sync" "sync"
@ -26,14 +26,7 @@ type ApiMessage struct {
Gateway string `json:"gateway"` Gateway string `json:"gateway"`
} }
var flog *log.Entry func New(cfg *config.BridgeConfig) bridge.Bridger {
var protocol = "api"
func init() {
flog = log.WithFields(log.Fields{"prefix": protocol})
}
func New(cfg *config.BridgeConfig) *Api {
b := &Api{BridgeConfig: cfg} b := &Api{BridgeConfig: cfg}
e := echo.New() e := echo.New()
e.HideBanner = true e.HideBanner = true
@ -50,10 +43,10 @@ func New(cfg *config.BridgeConfig) *Api {
e.POST("/api/message", b.handlePostMessage) e.POST("/api/message", b.handlePostMessage)
go func() { go func() {
if b.Config.BindAddress == "" { if b.Config.BindAddress == "" {
flog.Fatalf("No BindAddress configured.") b.Log.Fatalf("No BindAddress configured.")
} }
flog.Infof("Listening on %s", b.Config.BindAddress) b.Log.Infof("Listening on %s", b.Config.BindAddress)
flog.Fatal(e.Start(b.Config.BindAddress)) b.Log.Fatal(e.Start(b.Config.BindAddress))
}() }()
return b return b
} }
@ -92,7 +85,7 @@ func (b *Api) handlePostMessage(c echo.Context) error {
message.Account = b.Account message.Account = b.Account
message.ID = "" message.ID = ""
message.Timestamp = time.Now() message.Timestamp = time.Now()
flog.Debugf("Sending message from %s on %s to gateway", message.Username, "api") b.Log.Debugf("Sending message from %s on %s to gateway", message.Username, "api")
b.Remote <- message b.Remote <- message
return c.JSON(http.StatusOK, message) return c.JSON(http.StatusOK, message)
} }

View File

@ -1,19 +1,7 @@
package bridge package bridge
import ( import (
"github.com/42wim/matterbridge/bridge/api"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/bridge/discord"
"github.com/42wim/matterbridge/bridge/gitter"
"github.com/42wim/matterbridge/bridge/irc"
"github.com/42wim/matterbridge/bridge/matrix"
"github.com/42wim/matterbridge/bridge/mattermost"
"github.com/42wim/matterbridge/bridge/rocketchat"
"github.com/42wim/matterbridge/bridge/slack"
"github.com/42wim/matterbridge/bridge/sshchat"
"github.com/42wim/matterbridge/bridge/steam"
"github.com/42wim/matterbridge/bridge/telegram"
"github.com/42wim/matterbridge/bridge/xmpp"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"strings" "strings"
@ -34,15 +22,13 @@ type Bridge struct {
Protocol string Protocol string
Channels map[string]config.ChannelInfo Channels map[string]config.ChannelInfo
Joined map[string]bool Joined map[string]bool
Log *log.Entry
} }
var flog *log.Entry // Factory is the factory function to create a bridge
type Factory func(*config.BridgeConfig) Bridger
func init() { func New(bridge *config.Bridge) *Bridge {
flog = log.WithFields(log.Fields{"prefix": "bridge"})
}
func New(cfg *config.Config, bridge *config.Bridge, c chan config.Message) *Bridge {
b := new(Bridge) b := new(Bridge)
b.Channels = make(map[string]config.ChannelInfo) b.Channels = make(map[string]config.ChannelInfo)
accInfo := strings.Split(bridge.Account, ".") accInfo := strings.Split(bridge.Account, ".")
@ -52,49 +38,6 @@ func New(cfg *config.Config, bridge *config.Bridge, c chan config.Message) *Brid
b.Protocol = protocol b.Protocol = protocol
b.Account = bridge.Account b.Account = bridge.Account
b.Joined = make(map[string]bool) b.Joined = make(map[string]bool)
bridgeConfig := &config.BridgeConfig{General: &cfg.General, Account: bridge.Account, Remote: c}
// override config from environment
config.OverrideCfgFromEnv(cfg, protocol, name)
switch protocol {
case "mattermost":
bridgeConfig.Config = cfg.Mattermost[name]
b.Bridger = bmattermost.New(bridgeConfig)
case "irc":
bridgeConfig.Config = cfg.IRC[name]
b.Bridger = birc.New(bridgeConfig)
case "gitter":
bridgeConfig.Config = cfg.Gitter[name]
b.Bridger = bgitter.New(bridgeConfig)
case "slack":
bridgeConfig.Config = cfg.Slack[name]
b.Bridger = bslack.New(bridgeConfig)
case "xmpp":
bridgeConfig.Config = cfg.Xmpp[name]
b.Bridger = bxmpp.New(bridgeConfig)
case "discord":
bridgeConfig.Config = cfg.Discord[name]
b.Bridger = bdiscord.New(bridgeConfig)
case "telegram":
bridgeConfig.Config = cfg.Telegram[name]
b.Bridger = btelegram.New(bridgeConfig)
case "rocketchat":
bridgeConfig.Config = cfg.Rocketchat[name]
b.Bridger = brocketchat.New(bridgeConfig)
case "matrix":
bridgeConfig.Config = cfg.Matrix[name]
b.Bridger = bmatrix.New(bridgeConfig)
case "steam":
bridgeConfig.Config = cfg.Steam[name]
b.Bridger = bsteam.New(bridgeConfig)
case "sshchat":
bridgeConfig.Config = cfg.Sshchat[name]
b.Bridger = bsshchat.New(bridgeConfig)
case "api":
bridgeConfig.Config = cfg.Api[name]
b.Bridger = api.New(bridgeConfig)
}
b.Config = bridgeConfig.Config
return b return b
} }
@ -106,7 +49,7 @@ func (b *Bridge) JoinChannels() error {
func (b *Bridge) joinChannels(channels map[string]config.ChannelInfo, exists map[string]bool) error { func (b *Bridge) joinChannels(channels map[string]config.ChannelInfo, exists map[string]bool) error {
for ID, channel := range channels { for ID, channel := range channels {
if !exists[ID] { if !exists[ID] {
flog.Infof("%s: joining %s (ID: %s)", b.Account, channel.Name, ID) b.Log.Infof("%s: joining %s (ID: %s)", b.Account, channel.Name, ID)
err := b.JoinChannel(channel) err := b.JoinChannel(channel)
if err != nil { if err != nil {
return err return err

View File

@ -2,7 +2,7 @@ package config
import ( import (
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"log" log "github.com/sirupsen/logrus"
"os" "os"
"reflect" "reflect"
"strings" "strings"
@ -143,7 +143,7 @@ type SameChannelGateway struct {
type Config struct { type Config struct {
Api map[string]Protocol Api map[string]Protocol
IRC map[string]Protocol Irc map[string]Protocol
Mattermost map[string]Protocol Mattermost map[string]Protocol
Matrix map[string]Protocol Matrix map[string]Protocol
Slack map[string]Protocol Slack map[string]Protocol
@ -164,6 +164,7 @@ type BridgeConfig struct {
General *Protocol General *Protocol
Account string Account string
Remote chan Message Remote chan Message
Log *log.Entry
} }
func NewConfig(cfgfile string) *Config { func NewConfig(cfgfile string) *Config {

View File

@ -3,10 +3,10 @@ package bdiscord
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/bridge/helper" "github.com/42wim/matterbridge/bridge/helper"
"github.com/bwmarrin/discordgo" "github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
"regexp" "regexp"
"strings" "strings"
"sync" "sync"
@ -26,19 +26,12 @@ type Bdiscord struct {
*config.BridgeConfig *config.BridgeConfig
} }
var flog *log.Entry func New(cfg *config.BridgeConfig) bridge.Bridger {
var protocol = "discord"
func init() {
flog = log.WithFields(log.Fields{"prefix": protocol})
}
func New(cfg *config.BridgeConfig) *Bdiscord {
b := &Bdiscord{BridgeConfig: cfg} b := &Bdiscord{BridgeConfig: cfg}
b.userMemberMap = make(map[string]*discordgo.Member) b.userMemberMap = make(map[string]*discordgo.Member)
b.channelInfoMap = make(map[string]*config.ChannelInfo) b.channelInfoMap = make(map[string]*config.ChannelInfo)
if b.Config.WebhookURL != "" { if b.Config.WebhookURL != "" {
flog.Debug("Configuring Discord Incoming Webhook") b.Log.Debug("Configuring Discord Incoming Webhook")
b.webhookID, b.webhookToken = b.splitURL(b.Config.WebhookURL) b.webhookID, b.webhookToken = b.splitURL(b.Config.WebhookURL)
} }
return b return b
@ -46,11 +39,11 @@ func New(cfg *config.BridgeConfig) *Bdiscord {
func (b *Bdiscord) Connect() error { func (b *Bdiscord) Connect() error {
var err error var err error
flog.Info("Connecting") b.Log.Info("Connecting")
if b.Config.WebhookURL == "" { if b.Config.WebhookURL == "" {
flog.Info("Connecting using token") b.Log.Info("Connecting using token")
} else { } else {
flog.Info("Connecting using webhookurl (for posting) and token") b.Log.Info("Connecting using webhookurl (for posting) and token")
} }
if !strings.HasPrefix(b.Config.Token, "Bot ") { if !strings.HasPrefix(b.Config.Token, "Bot ") {
b.Config.Token = "Bot " + b.Config.Token b.Config.Token = "Bot " + b.Config.Token
@ -59,7 +52,7 @@ func (b *Bdiscord) Connect() error {
if err != nil { if err != nil {
return err return err
} }
flog.Info("Connection succeeded") b.Log.Info("Connection succeeded")
b.c.AddHandler(b.messageCreate) b.c.AddHandler(b.messageCreate)
b.c.AddHandler(b.memberUpdate) b.c.AddHandler(b.memberUpdate)
b.c.AddHandler(b.messageUpdate) b.c.AddHandler(b.messageUpdate)
@ -103,7 +96,7 @@ func (b *Bdiscord) JoinChannel(channel config.ChannelInfo) error {
} }
func (b *Bdiscord) Send(msg config.Message) (string, error) { func (b *Bdiscord) Send(msg config.Message) (string, error) {
flog.Debugf("Receiving %#v", msg) b.Log.Debugf("Receiving %#v", msg)
channelID := b.getChannelID(msg.Channel) channelID := b.getChannelID(msg.Channel)
if channelID == "" { if channelID == "" {
@ -132,7 +125,7 @@ func (b *Bdiscord) Send(msg config.Message) (string, error) {
if msg.Event != "" { if msg.Event != "" {
return "", nil return "", nil
} }
flog.Debugf("Broadcasting using Webhook") b.Log.Debugf("Broadcasting using Webhook")
err := b.c.WebhookExecute( err := b.c.WebhookExecute(
wID, wID,
wToken, wToken,
@ -145,7 +138,7 @@ func (b *Bdiscord) Send(msg config.Message) (string, error) {
return "", err return "", err
} }
flog.Debugf("Broadcasting using token (API)") b.Log.Debugf("Broadcasting using token (API)")
// Delete message // Delete message
if msg.Event == config.EVENT_MSG_DELETE { if msg.Event == config.EVENT_MSG_DELETE {
@ -187,8 +180,8 @@ func (b *Bdiscord) messageDelete(s *discordgo.Session, m *discordgo.MessageDelet
if b.UseChannelID { if b.UseChannelID {
rmsg.Channel = "ID:" + m.ChannelID rmsg.Channel = "ID:" + m.ChannelID
} }
flog.Debugf("Sending message from %s to gateway", b.Account) b.Log.Debugf("Sending message from %s to gateway", b.Account)
flog.Debugf("Message is %#v", rmsg) b.Log.Debugf("Message is %#v", rmsg)
b.Remote <- rmsg b.Remote <- rmsg
} }
@ -198,7 +191,7 @@ func (b *Bdiscord) messageUpdate(s *discordgo.Session, m *discordgo.MessageUpdat
} }
// only when message is actually edited // only when message is actually edited
if m.Message.EditedTimestamp != "" { if m.Message.EditedTimestamp != "" {
flog.Debugf("Sending edit message") b.Log.Debugf("Sending edit message")
m.Content = m.Content + b.Config.EditSuffix m.Content = m.Content + b.Config.EditSuffix
b.messageCreate(s, (*discordgo.MessageCreate)(m)) b.messageCreate(s, (*discordgo.MessageCreate)(m))
} }
@ -226,12 +219,12 @@ func (b *Bdiscord) messageCreate(s *discordgo.Session, m *discordgo.MessageCreat
rmsg := config.Message{Account: b.Account, Avatar: "https://cdn.discordapp.com/avatars/" + m.Author.ID + "/" + m.Author.Avatar + ".jpg", UserID: m.Author.ID, ID: m.ID} rmsg := config.Message{Account: b.Account, Avatar: "https://cdn.discordapp.com/avatars/" + m.Author.ID + "/" + m.Author.Avatar + ".jpg", UserID: m.Author.ID, ID: m.ID}
if m.Content != "" { if m.Content != "" {
flog.Debugf("Receiving message %#v", m.Message) b.Log.Debugf("Receiving message %#v", m.Message)
m.Message.Content = b.stripCustomoji(m.Message.Content) m.Message.Content = b.stripCustomoji(m.Message.Content)
m.Message.Content = b.replaceChannelMentions(m.Message.Content) m.Message.Content = b.replaceChannelMentions(m.Message.Content)
rmsg.Text, err = m.ContentWithMoreMentionsReplaced(b.c) rmsg.Text, err = m.ContentWithMoreMentionsReplaced(b.c)
if err != nil { if err != nil {
flog.Errorf("ContentWithMoreMentionsReplaced failed: %s", err) b.Log.Errorf("ContentWithMoreMentionsReplaced failed: %s", err)
rmsg.Text = m.ContentWithMentionsReplaced() rmsg.Text = m.ContentWithMentionsReplaced()
} }
} }
@ -268,15 +261,15 @@ func (b *Bdiscord) messageCreate(s *discordgo.Session, m *discordgo.MessageCreat
rmsg.Event = config.EVENT_USER_ACTION rmsg.Event = config.EVENT_USER_ACTION
} }
flog.Debugf("Sending message from %s on %s to gateway", m.Author.Username, b.Account) b.Log.Debugf("Sending message from %s on %s to gateway", m.Author.Username, b.Account)
flog.Debugf("Message is %#v", rmsg) b.Log.Debugf("Message is %#v", rmsg)
b.Remote <- rmsg b.Remote <- rmsg
} }
func (b *Bdiscord) memberUpdate(s *discordgo.Session, m *discordgo.GuildMemberUpdate) { func (b *Bdiscord) memberUpdate(s *discordgo.Session, m *discordgo.GuildMemberUpdate) {
b.Lock() b.Lock()
if _, ok := b.userMemberMap[m.Member.User.ID]; ok { if _, ok := b.userMemberMap[m.Member.User.ID]; ok {
flog.Debugf("%s: memberupdate: user %s (nick %s) changes nick to %s", b.Account, m.Member.User.Username, b.userMemberMap[m.Member.User.ID].Nick, m.Member.Nick) b.Log.Debugf("%s: memberupdate: user %s (nick %s) changes nick to %s", b.Account, m.Member.User.Username, b.userMemberMap[m.Member.User.ID].Nick, m.Member.Nick)
} }
b.userMemberMap[m.Member.User.ID] = m.Member b.userMemberMap[m.Member.User.ID] = m.Member
b.Unlock() b.Unlock()
@ -367,7 +360,7 @@ func (b *Bdiscord) stripCustomoji(text string) string {
func (b *Bdiscord) splitURL(url string) (string, string) { func (b *Bdiscord) splitURL(url string) (string, string) {
webhookURLSplit := strings.Split(url, "/") webhookURLSplit := strings.Split(url, "/")
if len(webhookURLSplit) != 7 { if len(webhookURLSplit) != 7 {
log.Fatalf("%s is no correct discord WebhookURL", url) b.Log.Fatalf("%s is no correct discord WebhookURL", url)
} }
return webhookURLSplit[len(webhookURLSplit)-2], webhookURLSplit[len(webhookURLSplit)-1] return webhookURLSplit[len(webhookURLSplit)-2], webhookURLSplit[len(webhookURLSplit)-1]
} }

View File

@ -3,9 +3,9 @@ package bgitter
import ( import (
"fmt" "fmt"
"github.com/42wim/go-gitter" "github.com/42wim/go-gitter"
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/bridge/helper" "github.com/42wim/matterbridge/bridge/helper"
log "github.com/sirupsen/logrus"
"strings" "strings"
) )
@ -17,20 +17,13 @@ type Bgitter struct {
*config.BridgeConfig *config.BridgeConfig
} }
var flog *log.Entry func New(cfg *config.BridgeConfig) bridge.Bridger {
var protocol = "gitter"
func init() {
flog = log.WithFields(log.Fields{"prefix": protocol})
}
func New(cfg *config.BridgeConfig) *Bgitter {
return &Bgitter{BridgeConfig: cfg} return &Bgitter{BridgeConfig: cfg}
} }
func (b *Bgitter) Connect() error { func (b *Bgitter) Connect() error {
var err error var err error
flog.Info("Connecting") b.Log.Info("Connecting")
b.c = gitter.New(b.Config.Token) b.c = gitter.New(b.Config.Token)
b.User, err = b.c.GetUser() b.User, err = b.c.GetUser()
if err != nil { if err != nil {
@ -40,7 +33,7 @@ func (b *Bgitter) Connect() error {
if err != nil { if err != nil {
return err return err
} }
flog.Info("Connection succeeded") b.Log.Info("Connection succeeded")
return nil return nil
} }
@ -78,7 +71,7 @@ func (b *Bgitter) JoinChannel(channel config.ChannelInfo) error {
case *gitter.MessageReceived: case *gitter.MessageReceived:
// ignore message sent from ourselves // ignore message sent from ourselves
if ev.Message.From.ID != b.User.ID { if ev.Message.From.ID != b.User.ID {
flog.Debugf("Sending message from %s on %s to gateway", ev.Message.From.Username, b.Account) b.Log.Debugf("Sending message from %s on %s to gateway", ev.Message.From.Username, b.Account)
rmsg := config.Message{Username: ev.Message.From.Username, Text: ev.Message.Text, Channel: room, rmsg := config.Message{Username: ev.Message.From.Username, Text: ev.Message.Text, Channel: room,
Account: b.Account, Avatar: b.getAvatar(ev.Message.From.Username), UserID: ev.Message.From.ID, Account: b.Account, Avatar: b.getAvatar(ev.Message.From.Username), UserID: ev.Message.From.ID,
ID: ev.Message.ID} ID: ev.Message.ID}
@ -86,11 +79,11 @@ func (b *Bgitter) JoinChannel(channel config.ChannelInfo) error {
rmsg.Event = config.EVENT_USER_ACTION rmsg.Event = config.EVENT_USER_ACTION
rmsg.Text = strings.Replace(rmsg.Text, "@"+ev.Message.From.Username+" ", "", -1) rmsg.Text = strings.Replace(rmsg.Text, "@"+ev.Message.From.Username+" ", "", -1)
} }
flog.Debugf("Message is %#v", rmsg) b.Log.Debugf("Message is %#v", rmsg)
b.Remote <- rmsg b.Remote <- rmsg
} }
case *gitter.GitterConnectionClosed: case *gitter.GitterConnectionClosed:
flog.Errorf("connection with gitter closed for room %s", room) b.Log.Errorf("connection with gitter closed for room %s", room)
} }
} }
}(stream, room.URI) }(stream, room.URI)
@ -98,10 +91,10 @@ func (b *Bgitter) JoinChannel(channel config.ChannelInfo) error {
} }
func (b *Bgitter) Send(msg config.Message) (string, error) { func (b *Bgitter) Send(msg config.Message) (string, error) {
flog.Debugf("Receiving %#v", msg) b.Log.Debugf("Receiving %#v", msg)
roomID := b.getRoomID(msg.Channel) roomID := b.getRoomID(msg.Channel)
if roomID == "" { if roomID == "" {
flog.Errorf("Could not find roomID for %v", msg.Channel) b.Log.Errorf("Could not find roomID for %v", msg.Channel)
return "", nil return "", nil
} }
@ -130,7 +123,7 @@ func (b *Bgitter) Send(msg config.Message) (string, error) {
// Edit message // Edit message
if msg.ID != "" { if msg.ID != "" {
flog.Debugf("updating message with id %s", msg.ID) b.Log.Debugf("updating message with id %s", msg.ID)
_, err := b.c.UpdateMessage(roomID, msg.ID, msg.Username+msg.Text) _, err := b.c.UpdateMessage(roomID, msg.ID, msg.Username+msg.Text)
if err != nil { if err != nil {
return "", err return "", err

View File

@ -4,13 +4,13 @@ import (
"bytes" "bytes"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/bridge/helper" "github.com/42wim/matterbridge/bridge/helper"
"github.com/lrstanley/girc" "github.com/lrstanley/girc"
"github.com/paulrosania/go-charset/charset" "github.com/paulrosania/go-charset/charset"
_ "github.com/paulrosania/go-charset/data" _ "github.com/paulrosania/go-charset/data"
"github.com/saintfish/chardet" "github.com/saintfish/chardet"
log "github.com/sirupsen/logrus"
"io" "io"
"io/ioutil" "io/ioutil"
"net" "net"
@ -33,14 +33,7 @@ type Birc struct {
*config.BridgeConfig *config.BridgeConfig
} }
var flog *log.Entry func New(cfg *config.BridgeConfig) bridge.Bridger {
var protocol = "irc"
func init() {
flog = log.WithFields(log.Fields{"prefix": protocol})
}
func New(cfg *config.BridgeConfig) *Birc {
b := &Birc{} b := &Birc{}
b.BridgeConfig = cfg b.BridgeConfig = cfg
b.Nick = b.Config.Nick b.Nick = b.Config.Nick
@ -71,7 +64,7 @@ func (b *Birc) Command(msg *config.Message) string {
func (b *Birc) Connect() error { func (b *Birc) Connect() error {
b.Local = make(chan config.Message, b.Config.MessageQueue+10) b.Local = make(chan config.Message, b.Config.MessageQueue+10)
flog.Infof("Connecting %s", b.Config.Server) b.Log.Infof("Connecting %s", b.Config.Server)
server, portstr, err := net.SplitHostPort(b.Config.Server) server, portstr, err := net.SplitHostPort(b.Config.Server)
if err != nil { if err != nil {
return err return err
@ -112,8 +105,8 @@ func (b *Birc) Connect() error {
go func() { go func() {
for { for {
if err := i.Connect(); err != nil { if err := i.Connect(); err != nil {
flog.Errorf("error: %s", err) b.Log.Errorf("error: %s", err)
flog.Info("reconnecting in 30 seconds...") b.Log.Info("reconnecting in 30 seconds...")
time.Sleep(30 * time.Second) time.Sleep(30 * time.Second)
i.Handlers.Clear(girc.RPL_WELCOME) i.Handlers.Clear(girc.RPL_WELCOME)
i.Handlers.Add(girc.RPL_WELCOME, func(client *girc.Client, event girc.Event) { i.Handlers.Add(girc.RPL_WELCOME, func(client *girc.Client, event girc.Event) {
@ -129,7 +122,7 @@ func (b *Birc) Connect() error {
b.i = i b.i = i
select { select {
case <-b.connected: case <-b.connected:
flog.Info("Connection succeeded") b.Log.Info("Connection succeeded")
case <-time.After(time.Second * 30): case <-time.After(time.Second * 30):
return fmt.Errorf("connection timed out") return fmt.Errorf("connection timed out")
} }
@ -149,7 +142,7 @@ func (b *Birc) Disconnect() error {
func (b *Birc) JoinChannel(channel config.ChannelInfo) error { func (b *Birc) JoinChannel(channel config.ChannelInfo) error {
if channel.Options.Key != "" { if channel.Options.Key != "" {
flog.Debugf("using key %s for channel %s", channel.Options.Key, channel.Name) b.Log.Debugf("using key %s for channel %s", channel.Options.Key, channel.Name)
b.i.Cmd.JoinKey(channel.Name, channel.Options.Key) b.i.Cmd.JoinKey(channel.Name, channel.Options.Key)
} else { } else {
b.i.Cmd.Join(channel.Name) b.i.Cmd.Join(channel.Name)
@ -163,7 +156,7 @@ func (b *Birc) Send(msg config.Message) (string, error) {
return "", nil return "", nil
} }
flog.Debugf("Receiving %#v", msg) b.Log.Debugf("Receiving %#v", msg)
// Execute a command // Execute a command
if strings.HasPrefix(msg.Text, "!") { if strings.HasPrefix(msg.Text, "!") {
@ -175,7 +168,7 @@ func (b *Birc) Send(msg config.Message) (string, error) {
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
w, err := charset.NewWriter(b.Config.Charset, buf) w, err := charset.NewWriter(b.Config.Charset, buf)
if err != nil { if err != nil {
flog.Errorf("charset from utf-8 conversion failed: %s", err) b.Log.Errorf("charset from utf-8 conversion failed: %s", err)
return "", err return "", err
} }
fmt.Fprintf(w, msg.Text) fmt.Fprintf(w, msg.Text)
@ -221,7 +214,7 @@ func (b *Birc) Send(msg config.Message) (string, error) {
} }
b.Local <- config.Message{Text: text, Username: msg.Username, Channel: msg.Channel, Event: msg.Event} b.Local <- config.Message{Text: text, Username: msg.Username, Channel: msg.Channel, Event: msg.Event}
} else { } else {
flog.Debugf("flooding, dropping message (queue at %d)", len(b.Local)) b.Log.Debugf("flooding, dropping message (queue at %d)", len(b.Local))
} }
} }
return "", nil return "", nil
@ -259,7 +252,7 @@ func (b *Birc) endNames(client *girc.Client, event girc.Event) {
} }
func (b *Birc) handleNewConnection(client *girc.Client, event girc.Event) { func (b *Birc) handleNewConnection(client *girc.Client, event girc.Event) {
flog.Debug("Registering callbacks") b.Log.Debug("Registering callbacks")
i := b.i i := b.i
b.Nick = event.Params[0] b.Nick = event.Params[0]
@ -278,31 +271,31 @@ func (b *Birc) handleNewConnection(client *girc.Client, event girc.Event) {
func (b *Birc) handleJoinPart(client *girc.Client, event girc.Event) { func (b *Birc) handleJoinPart(client *girc.Client, event girc.Event) {
if len(event.Params) == 0 { if len(event.Params) == 0 {
flog.Debugf("handleJoinPart: empty Params? %#v", event) b.Log.Debugf("handleJoinPart: empty Params? %#v", event)
return return
} }
channel := strings.ToLower(event.Params[0]) channel := strings.ToLower(event.Params[0])
if event.Command == "KICK" { if event.Command == "KICK" {
flog.Infof("Got kicked from %s by %s", channel, event.Source.Name) b.Log.Infof("Got kicked from %s by %s", channel, event.Source.Name)
time.Sleep(time.Duration(b.Config.RejoinDelay) * time.Second) time.Sleep(time.Duration(b.Config.RejoinDelay) * time.Second)
b.Remote <- config.Message{Username: "system", Text: "rejoin", Channel: channel, Account: b.Account, Event: config.EVENT_REJOIN_CHANNELS} b.Remote <- config.Message{Username: "system", Text: "rejoin", Channel: channel, Account: b.Account, Event: config.EVENT_REJOIN_CHANNELS}
return return
} }
if event.Command == "QUIT" { if event.Command == "QUIT" {
if event.Source.Name == b.Nick && strings.Contains(event.Trailing, "Ping timeout") { if event.Source.Name == b.Nick && strings.Contains(event.Trailing, "Ping timeout") {
flog.Infof("%s reconnecting ..", b.Account) b.Log.Infof("%s reconnecting ..", b.Account)
b.Remote <- config.Message{Username: "system", Text: "reconnect", Channel: channel, Account: b.Account, Event: config.EVENT_FAILURE} b.Remote <- config.Message{Username: "system", Text: "reconnect", Channel: channel, Account: b.Account, Event: config.EVENT_FAILURE}
return return
} }
} }
if event.Source.Name != b.Nick { if event.Source.Name != b.Nick {
flog.Debugf("Sending JOIN_LEAVE event from %s to gateway", b.Account) b.Log.Debugf("Sending JOIN_LEAVE event from %s to gateway", b.Account)
msg := config.Message{Username: "system", Text: event.Source.Name + " " + strings.ToLower(event.Command) + "s", Channel: channel, Account: b.Account, Event: config.EVENT_JOIN_LEAVE} msg := config.Message{Username: "system", Text: event.Source.Name + " " + strings.ToLower(event.Command) + "s", Channel: channel, Account: b.Account, Event: config.EVENT_JOIN_LEAVE}
flog.Debugf("Message is %#v", msg) b.Log.Debugf("Message is %#v", msg)
b.Remote <- msg b.Remote <- msg
return return
} }
flog.Debugf("handle %#v", event) b.Log.Debugf("handle %#v", event)
} }
func (b *Birc) handleNotice(client *girc.Client, event girc.Event) { func (b *Birc) handleNotice(client *girc.Client, event girc.Event) {
@ -317,7 +310,7 @@ func (b *Birc) handleOther(client *girc.Client, event girc.Event) {
if b.Config.DebugLevel == 1 { if b.Config.DebugLevel == 1 {
if event.Command != "CLIENT_STATE_UPDATED" && if event.Command != "CLIENT_STATE_UPDATED" &&
event.Command != "CLIENT_GENERAL_UPDATED" { event.Command != "CLIENT_GENERAL_UPDATED" {
flog.Debugf("%#v", event.String()) b.Log.Debugf("%#v", event.String())
} }
return return
} }
@ -325,12 +318,12 @@ func (b *Birc) handleOther(client *girc.Client, event girc.Event) {
case "372", "375", "376", "250", "251", "252", "253", "254", "255", "265", "266", "002", "003", "004", "005": case "372", "375", "376", "250", "251", "252", "253", "254", "255", "265", "266", "002", "003", "004", "005":
return return
} }
flog.Debugf("%#v", event.String()) b.Log.Debugf("%#v", event.String())
} }
func (b *Birc) handleOtherAuth(client *girc.Client, event girc.Event) { func (b *Birc) handleOtherAuth(client *girc.Client, event girc.Event) {
if strings.EqualFold(b.Config.NickServNick, "Q@CServe.quakenet.org") { if strings.EqualFold(b.Config.NickServNick, "Q@CServe.quakenet.org") {
flog.Debugf("Authenticating %s against %s", b.Config.NickServUsername, b.Config.NickServNick) b.Log.Debugf("Authenticating %s against %s", b.Config.NickServUsername, b.Config.NickServNick)
b.i.Cmd.Message(b.Config.NickServNick, "AUTH "+b.Config.NickServUsername+" "+b.Config.NickServPassword) b.i.Cmd.Message(b.Config.NickServNick, "AUTH "+b.Config.NickServUsername+" "+b.Config.NickServPassword)
} }
} }
@ -359,7 +352,7 @@ func (b *Birc) handlePrivMsg(client *girc.Client, event girc.Event) {
return return
} }
rmsg := config.Message{Username: event.Source.Name, Channel: strings.ToLower(event.Params[0]), Account: b.Account, UserID: event.Source.Ident + "@" + event.Source.Host} rmsg := config.Message{Username: event.Source.Name, Channel: strings.ToLower(event.Params[0]), Account: b.Account, UserID: event.Source.Ident + "@" + event.Source.Host}
flog.Debugf("Receiving PRIVMSG: %s %s %#v", event.Source.Name, event.Trailing, event) b.Log.Debugf("Receiving PRIVMSG: %s %s %#v", event.Source.Name, event.Trailing, event)
// set action event // set action event
if event.IsAction() { if event.IsAction() {
@ -382,10 +375,10 @@ func (b *Birc) handlePrivMsg(client *girc.Client, event girc.Event) {
detector := chardet.NewTextDetector() detector := chardet.NewTextDetector()
result, err := detector.DetectBest([]byte(rmsg.Text)) result, err := detector.DetectBest([]byte(rmsg.Text))
if err != nil { if err != nil {
flog.Infof("detection failed for rmsg.Text: %#v", rmsg.Text) b.Log.Infof("detection failed for rmsg.Text: %#v", rmsg.Text)
return return
} }
flog.Debugf("detected %s confidence %#v", result.Charset, result.Confidence) b.Log.Debugf("detected %s confidence %#v", result.Charset, result.Confidence)
mycharset = result.Charset mycharset = result.Charset
// if we're not sure, just pick ISO-8859-1 // if we're not sure, just pick ISO-8859-1
if result.Confidence < 80 { if result.Confidence < 80 {
@ -394,13 +387,13 @@ func (b *Birc) handlePrivMsg(client *girc.Client, event girc.Event) {
} }
r, err = charset.NewReader(mycharset, strings.NewReader(rmsg.Text)) r, err = charset.NewReader(mycharset, strings.NewReader(rmsg.Text))
if err != nil { if err != nil {
flog.Errorf("charset to utf-8 conversion failed: %s", err) b.Log.Errorf("charset to utf-8 conversion failed: %s", err)
return return
} }
output, _ := ioutil.ReadAll(r) output, _ := ioutil.ReadAll(r)
rmsg.Text = string(output) rmsg.Text = string(output)
flog.Debugf("Sending message from %s on %s to gateway", event.Params[0], b.Account) b.Log.Debugf("Sending message from %s on %s to gateway", event.Params[0], b.Account)
b.Remote <- rmsg b.Remote <- rmsg
} }
@ -408,13 +401,13 @@ func (b *Birc) handleTopicWhoTime(client *girc.Client, event girc.Event) {
parts := strings.Split(event.Params[2], "!") parts := strings.Split(event.Params[2], "!")
t, err := strconv.ParseInt(event.Params[3], 10, 64) t, err := strconv.ParseInt(event.Params[3], 10, 64)
if err != nil { if err != nil {
flog.Errorf("Invalid time stamp: %s", event.Params[3]) b.Log.Errorf("Invalid time stamp: %s", event.Params[3])
} }
user := parts[0] user := parts[0]
if len(parts) > 1 { if len(parts) > 1 {
user += " [" + parts[1] + "]" user += " [" + parts[1] + "]"
} }
flog.Debugf("%s: Topic set by %s [%s]", event.Command, user, time.Unix(t, 0)) b.Log.Debugf("%s: Topic set by %s [%s]", event.Command, user, time.Unix(t, 0))
} }
func (b *Birc) nicksPerRow() int { func (b *Birc) nicksPerRow() int {

View File

@ -3,10 +3,10 @@ package bmatrix
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/bridge/helper" "github.com/42wim/matterbridge/bridge/helper"
matrix "github.com/matterbridge/gomatrix" matrix "github.com/matterbridge/gomatrix"
log "github.com/sirupsen/logrus"
"mime" "mime"
"regexp" "regexp"
"strings" "strings"
@ -21,14 +21,7 @@ type Bmatrix struct {
*config.BridgeConfig *config.BridgeConfig
} }
var flog *log.Entry func New(cfg *config.BridgeConfig) bridge.Bridger {
var protocol = "matrix"
func init() {
flog = log.WithFields(log.Fields{"prefix": protocol})
}
func New(cfg *config.BridgeConfig) *Bmatrix {
b := &Bmatrix{BridgeConfig: cfg} b := &Bmatrix{BridgeConfig: cfg}
b.RoomMap = make(map[string]string) b.RoomMap = make(map[string]string)
return b return b
@ -36,7 +29,7 @@ func New(cfg *config.BridgeConfig) *Bmatrix {
func (b *Bmatrix) Connect() error { func (b *Bmatrix) Connect() error {
var err error var err error
flog.Infof("Connecting %s", b.Config.Server) b.Log.Infof("Connecting %s", b.Config.Server)
b.mc, err = matrix.NewClient(b.Config.Server, "", "") b.mc, err = matrix.NewClient(b.Config.Server, "", "")
if err != nil { if err != nil {
return err return err
@ -51,7 +44,7 @@ func (b *Bmatrix) Connect() error {
} }
b.mc.SetCredentials(resp.UserID, resp.AccessToken) b.mc.SetCredentials(resp.UserID, resp.AccessToken)
b.UserID = resp.UserID b.UserID = resp.UserID
flog.Info("Connection succeeded") b.Log.Info("Connection succeeded")
go b.handlematrix() go b.handlematrix()
return nil return nil
} }
@ -72,10 +65,10 @@ func (b *Bmatrix) JoinChannel(channel config.ChannelInfo) error {
} }
func (b *Bmatrix) Send(msg config.Message) (string, error) { func (b *Bmatrix) Send(msg config.Message) (string, error) {
flog.Debugf("Receiving %#v", msg) b.Log.Debugf("Receiving %#v", msg)
channel := b.getRoomID(msg.Channel) channel := b.getRoomID(msg.Channel)
flog.Debugf("Channel %s maps to channel id %s", msg.Channel, channel) b.Log.Debugf("Channel %s maps to channel id %s", msg.Channel, channel)
// Make a action /me of the message // Make a action /me of the message
if msg.Event == config.EVENT_USER_ACTION { if msg.Event == config.EVENT_USER_ACTION {
@ -139,7 +132,7 @@ func (b *Bmatrix) handlematrix() error {
go func() { go func() {
for { for {
if err := b.mc.Sync(); err != nil { if err := b.mc.Sync(); err != nil {
flog.Println("Sync() returned ", err) b.Log.Println("Sync() returned ", err)
} }
} }
}() }()
@ -147,13 +140,13 @@ func (b *Bmatrix) handlematrix() error {
} }
func (b *Bmatrix) handleEvent(ev *matrix.Event) { func (b *Bmatrix) handleEvent(ev *matrix.Event) {
flog.Debugf("Received: %#v", ev) b.Log.Debugf("Received: %#v", ev)
if ev.Sender != b.UserID { if ev.Sender != b.UserID {
b.RLock() b.RLock()
channel, ok := b.RoomMap[ev.RoomID] channel, ok := b.RoomMap[ev.RoomID]
b.RUnlock() b.RUnlock()
if !ok { if !ok {
flog.Debugf("Unknown room %s", ev.RoomID) b.Log.Debugf("Unknown room %s", ev.RoomID)
return return
} }
@ -164,7 +157,7 @@ func (b *Bmatrix) handleEvent(ev *matrix.Event) {
// Text must be a string // Text must be a string
if rmsg.Text, ok = ev.Content["body"].(string); !ok { if rmsg.Text, ok = ev.Content["body"].(string); !ok {
flog.Errorf("Content[body] wasn't a %T ?", rmsg.Text) b.Log.Errorf("Content[body] wasn't a %T ?", rmsg.Text)
return return
} }
@ -192,11 +185,11 @@ func (b *Bmatrix) handleEvent(ev *matrix.Event) {
if b.containsAttachment(ev.Content) { if b.containsAttachment(ev.Content) {
err := b.handleDownloadFile(&rmsg, ev.Content) err := b.handleDownloadFile(&rmsg, ev.Content)
if err != nil { if err != nil {
flog.Errorf("download failed: %#v", err) b.Log.Errorf("download failed: %#v", err)
} }
} }
flog.Debugf("Sending message from %s on %s to gateway", ev.Sender, b.Account) b.Log.Debugf("Sending message from %s on %s to gateway", ev.Sender, b.Account)
b.Remote <- rmsg b.Remote <- rmsg
} }
} }
@ -246,7 +239,7 @@ func (b *Bmatrix) handleDownloadFile(rmsg *config.Message, content map[string]in
} }
// check if the size is ok // check if the size is ok
err := helper.HandleDownloadSize(flog, rmsg, name, int64(size), b.General) err := helper.HandleDownloadSize(b.Log, rmsg, name, int64(size), b.General)
if err != nil { if err != nil {
return err return err
} }
@ -256,7 +249,7 @@ func (b *Bmatrix) handleDownloadFile(rmsg *config.Message, content map[string]in
return fmt.Errorf("download %s failed %#v", url, err) return fmt.Errorf("download %s failed %#v", url, err)
} }
// add the downloaded data to the message // add the downloaded data to the message
helper.HandleDownloadData(flog, rmsg, name, "", url, data, b.General) helper.HandleDownloadData(b.Log, rmsg, name, "", url, data, b.General)
return nil return nil
} }
@ -272,30 +265,30 @@ func (b *Bmatrix) handleUploadFile(msg *config.Message, channel string) (string,
if fi.Comment != "" { if fi.Comment != "" {
_, err := b.mc.SendText(channel, msg.Username+fi.Comment) _, err := b.mc.SendText(channel, msg.Username+fi.Comment)
if err != nil { if err != nil {
flog.Errorf("file comment failed: %#v", err) b.Log.Errorf("file comment failed: %#v", err)
} }
} }
flog.Debugf("uploading file: %s %s", fi.Name, mtype) b.Log.Debugf("uploading file: %s %s", fi.Name, mtype)
res, err := b.mc.UploadToContentRepo(content, mtype, int64(len(*fi.Data))) res, err := b.mc.UploadToContentRepo(content, mtype, int64(len(*fi.Data)))
if err != nil { if err != nil {
flog.Errorf("file upload failed: %#v", err) b.Log.Errorf("file upload failed: %#v", err)
continue continue
} }
if strings.Contains(mtype, "video") { if strings.Contains(mtype, "video") {
flog.Debugf("sendVideo %s", res.ContentURI) b.Log.Debugf("sendVideo %s", res.ContentURI)
_, err = b.mc.SendVideo(channel, fi.Name, res.ContentURI) _, err = b.mc.SendVideo(channel, fi.Name, res.ContentURI)
if err != nil { if err != nil {
flog.Errorf("sendVideo failed: %#v", err) b.Log.Errorf("sendVideo failed: %#v", err)
} }
} }
if strings.Contains(mtype, "image") { if strings.Contains(mtype, "image") {
flog.Debugf("sendImage %s", res.ContentURI) b.Log.Debugf("sendImage %s", res.ContentURI)
_, err = b.mc.SendImage(channel, fi.Name, res.ContentURI) _, err = b.mc.SendImage(channel, fi.Name, res.ContentURI)
if err != nil { if err != nil {
flog.Errorf("sendImage failed: %#v", err) b.Log.Errorf("sendImage failed: %#v", err)
} }
} }
flog.Debugf("result: %#v", res) b.Log.Debugf("result: %#v", res)
} }
} }
return "", nil return "", nil

View File

@ -3,11 +3,11 @@ package bmattermost
import ( import (
"errors" "errors"
"fmt" "fmt"
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/bridge/helper" "github.com/42wim/matterbridge/bridge/helper"
"github.com/42wim/matterbridge/matterclient" "github.com/42wim/matterbridge/matterclient"
"github.com/42wim/matterbridge/matterhook" "github.com/42wim/matterbridge/matterhook"
log "github.com/sirupsen/logrus"
"strings" "strings"
) )
@ -19,14 +19,7 @@ type Bmattermost struct {
avatarMap map[string]string avatarMap map[string]string
} }
var flog *log.Entry func New(cfg *config.BridgeConfig) bridge.Bridger {
var protocol = "mattermost"
func init() {
flog = log.WithFields(log.Fields{"prefix": protocol})
}
func New(cfg *config.BridgeConfig) *Bmattermost {
b := &Bmattermost{BridgeConfig: cfg, avatarMap: make(map[string]string)} b := &Bmattermost{BridgeConfig: cfg, avatarMap: make(map[string]string)}
return b return b
} }
@ -38,24 +31,24 @@ func (b *Bmattermost) Command(cmd string) string {
func (b *Bmattermost) Connect() error { func (b *Bmattermost) Connect() error {
if b.Config.WebhookBindAddress != "" { if b.Config.WebhookBindAddress != "" {
if b.Config.WebhookURL != "" { if b.Config.WebhookURL != "" {
flog.Info("Connecting using webhookurl (sending) and webhookbindaddress (receiving)") b.Log.Info("Connecting using webhookurl (sending) and webhookbindaddress (receiving)")
b.mh = matterhook.New(b.Config.WebhookURL, b.mh = matterhook.New(b.Config.WebhookURL,
matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify, matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,
BindAddress: b.Config.WebhookBindAddress}) BindAddress: b.Config.WebhookBindAddress})
} else if b.Config.Token != "" { } else if b.Config.Token != "" {
flog.Info("Connecting using token (sending)") b.Log.Info("Connecting using token (sending)")
err := b.apiLogin() err := b.apiLogin()
if err != nil { if err != nil {
return err return err
} }
} else if b.Config.Login != "" { } else if b.Config.Login != "" {
flog.Info("Connecting using login/password (sending)") b.Log.Info("Connecting using login/password (sending)")
err := b.apiLogin() err := b.apiLogin()
if err != nil { if err != nil {
return err return err
} }
} else { } else {
flog.Info("Connecting using webhookbindaddress (receiving)") b.Log.Info("Connecting using webhookbindaddress (receiving)")
b.mh = matterhook.New(b.Config.WebhookURL, b.mh = matterhook.New(b.Config.WebhookURL,
matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify, matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,
BindAddress: b.Config.WebhookBindAddress}) BindAddress: b.Config.WebhookBindAddress})
@ -64,19 +57,19 @@ func (b *Bmattermost) Connect() error {
return nil return nil
} }
if b.Config.WebhookURL != "" { if b.Config.WebhookURL != "" {
flog.Info("Connecting using webhookurl (sending)") b.Log.Info("Connecting using webhookurl (sending)")
b.mh = matterhook.New(b.Config.WebhookURL, b.mh = matterhook.New(b.Config.WebhookURL,
matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify, matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,
DisableServer: true}) DisableServer: true})
if b.Config.Token != "" { if b.Config.Token != "" {
flog.Info("Connecting using token (receiving)") b.Log.Info("Connecting using token (receiving)")
err := b.apiLogin() err := b.apiLogin()
if err != nil { if err != nil {
return err return err
} }
go b.handleMatter() go b.handleMatter()
} else if b.Config.Login != "" { } else if b.Config.Login != "" {
flog.Info("Connecting using login/password (receiving)") b.Log.Info("Connecting using login/password (receiving)")
err := b.apiLogin() err := b.apiLogin()
if err != nil { if err != nil {
return err return err
@ -85,14 +78,14 @@ func (b *Bmattermost) Connect() error {
} }
return nil return nil
} else if b.Config.Token != "" { } else if b.Config.Token != "" {
flog.Info("Connecting using token (sending and receiving)") b.Log.Info("Connecting using token (sending and receiving)")
err := b.apiLogin() err := b.apiLogin()
if err != nil { if err != nil {
return err return err
} }
go b.handleMatter() go b.handleMatter()
} else if b.Config.Login != "" { } else if b.Config.Login != "" {
flog.Info("Connecting using login/password (sending and receiving)") b.Log.Info("Connecting using login/password (sending and receiving)")
err := b.apiLogin() err := b.apiLogin()
if err != nil { if err != nil {
return err return err
@ -122,7 +115,7 @@ func (b *Bmattermost) JoinChannel(channel config.ChannelInfo) error {
} }
func (b *Bmattermost) Send(msg config.Message) (string, error) { func (b *Bmattermost) Send(msg config.Message) (string, error) {
flog.Debugf("Receiving %#v", msg) b.Log.Debugf("Receiving %#v", msg)
// Make a action /me of the message // Make a action /me of the message
if msg.Event == config.EVENT_USER_ACTION { if msg.Event == config.EVENT_USER_ACTION {
@ -174,13 +167,13 @@ func (b *Bmattermost) Send(msg config.Message) (string, error) {
func (b *Bmattermost) handleMatter() { func (b *Bmattermost) handleMatter() {
messages := make(chan *config.Message) messages := make(chan *config.Message)
if b.Config.WebhookBindAddress != "" { if b.Config.WebhookBindAddress != "" {
flog.Debugf("Choosing webhooks based receiving") b.Log.Debugf("Choosing webhooks based receiving")
go b.handleMatterHook(messages) go b.handleMatterHook(messages)
} else { } else {
if b.Config.Token != "" { if b.Config.Token != "" {
flog.Debugf("Choosing token based receiving") b.Log.Debugf("Choosing token based receiving")
} else { } else {
flog.Debugf("Choosing login/password based receiving") b.Log.Debugf("Choosing login/password based receiving")
} }
go b.handleMatterClient(messages) go b.handleMatterClient(messages)
} }
@ -192,18 +185,18 @@ func (b *Bmattermost) handleMatter() {
if ok { if ok {
message.Event = config.EVENT_USER_ACTION message.Event = config.EVENT_USER_ACTION
} }
flog.Debugf("Sending message from %s on %s to gateway", message.Username, b.Account) b.Log.Debugf("Sending message from %s on %s to gateway", message.Username, b.Account)
flog.Debugf("Message is %#v", message) b.Log.Debugf("Message is %#v", message)
b.Remote <- *message b.Remote <- *message
} }
} }
func (b *Bmattermost) handleMatterClient(messages chan *config.Message) { func (b *Bmattermost) handleMatterClient(messages chan *config.Message) {
for message := range b.mc.MessageChan { for message := range b.mc.MessageChan {
flog.Debugf("%#v", message.Raw.Data) b.Log.Debugf("%#v", message.Raw.Data)
if b.skipMessage(message) { if b.skipMessage(message) {
flog.Debugf("Skipped message: %#v", message) b.Log.Debugf("Skipped message: %#v", message)
continue continue
} }
@ -212,7 +205,7 @@ func (b *Bmattermost) handleMatterClient(messages chan *config.Message) {
b.handleDownloadAvatar(message.UserID, message.Channel) b.handleDownloadAvatar(message.UserID, message.Channel)
} }
flog.Debugf("Receiving from matterclient %#v", message) b.Log.Debugf("Receiving from matterclient %#v", message)
rmsg := &config.Message{Username: message.Username, UserID: message.UserID, Channel: message.Channel, Text: message.Text, ID: message.Post.Id, Extra: make(map[string][]interface{})} rmsg := &config.Message{Username: message.Username, UserID: message.UserID, Channel: message.Channel, Text: message.Text, ID: message.Post.Id, Extra: make(map[string][]interface{})}
@ -240,7 +233,7 @@ func (b *Bmattermost) handleMatterClient(messages chan *config.Message) {
for _, id := range message.Post.FileIds { for _, id := range message.Post.FileIds {
err := b.handleDownloadFile(rmsg, id) err := b.handleDownloadFile(rmsg, id)
if err != nil { if err != nil {
flog.Errorf("download failed: %s", err) b.Log.Errorf("download failed: %s", err)
} }
} }
} }
@ -251,7 +244,7 @@ func (b *Bmattermost) handleMatterClient(messages chan *config.Message) {
func (b *Bmattermost) handleMatterHook(messages chan *config.Message) { func (b *Bmattermost) handleMatterHook(messages chan *config.Message) {
for { for {
message := b.mh.Receive() message := b.mh.Receive()
flog.Debugf("Receiving from matterhook %#v", message) b.Log.Debugf("Receiving from matterhook %#v", message)
messages <- &config.Message{UserID: message.UserID, Username: message.UserName, Text: message.Text, Channel: message.ChannelName} messages <- &config.Message{UserID: message.UserID, Username: message.UserName, Text: message.Text, Channel: message.ChannelName}
} }
} }
@ -268,12 +261,12 @@ func (b *Bmattermost) apiLogin() error {
} }
b.mc.SkipTLSVerify = b.Config.SkipTLSVerify b.mc.SkipTLSVerify = b.Config.SkipTLSVerify
b.mc.NoTLS = b.Config.NoTLS b.mc.NoTLS = b.Config.NoTLS
flog.Infof("Connecting %s (team: %s) on %s", b.Config.Login, b.Config.Team, b.Config.Server) b.Log.Infof("Connecting %s (team: %s) on %s", b.Config.Login, b.Config.Team, b.Config.Server)
err := b.mc.Login() err := b.mc.Login()
if err != nil { if err != nil {
return err return err
} }
flog.Info("Connection succeeded") b.Log.Info("Connection succeeded")
b.TeamID = b.mc.GetTeamId() b.TeamID = b.mc.GetTeamId()
go b.mc.WsReceiver() go b.mc.WsReceiver()
go b.mc.StatusLoop() go b.mc.StatusLoop()
@ -293,7 +286,7 @@ func (b *Bmattermost) cacheAvatar(msg *config.Message) (string, error) {
/* if we have a sha we have successfully uploaded the file to the media server, /* if we have a sha we have successfully uploaded the file to the media server,
so we can now cache the sha */ so we can now cache the sha */
if fi.SHA != "" { if fi.SHA != "" {
flog.Debugf("Added %s to %s in avatarMap", fi.SHA, msg.UserID) b.Log.Debugf("Added %s to %s in avatarMap", fi.SHA, msg.UserID)
b.avatarMap[msg.UserID] = fi.SHA b.avatarMap[msg.UserID] = fi.SHA
} }
return "", nil return "", nil
@ -307,15 +300,15 @@ func (b *Bmattermost) handleDownloadAvatar(userid string, channel string) {
if _, ok := b.avatarMap[userid]; !ok { if _, ok := b.avatarMap[userid]; !ok {
data, resp := b.mc.Client.GetProfileImage(userid, "") data, resp := b.mc.Client.GetProfileImage(userid, "")
if resp.Error != nil { if resp.Error != nil {
flog.Errorf("ProfileImage download failed for %#v %s", userid, resp.Error) b.Log.Errorf("ProfileImage download failed for %#v %s", userid, resp.Error)
return return
} }
err := helper.HandleDownloadSize(flog, &rmsg, userid+".png", int64(len(data)), b.General) err := helper.HandleDownloadSize(b.Log, &rmsg, userid+".png", int64(len(data)), b.General)
if err != nil { if err != nil {
flog.Error(err) b.Log.Error(err)
return return
} }
helper.HandleDownloadData(flog, &rmsg, userid+".png", rmsg.Text, "", &data, b.General) helper.HandleDownloadData(b.Log, &rmsg, userid+".png", rmsg.Text, "", &data, b.General)
b.Remote <- rmsg b.Remote <- rmsg
} }
} }
@ -327,7 +320,7 @@ func (b *Bmattermost) handleDownloadFile(rmsg *config.Message, id string) error
if resp.Error != nil { if resp.Error != nil {
return resp.Error return resp.Error
} }
err := helper.HandleDownloadSize(flog, rmsg, finfo.Name, finfo.Size, b.General) err := helper.HandleDownloadSize(b.Log, rmsg, finfo.Name, finfo.Size, b.General)
if err != nil { if err != nil {
return err return err
} }
@ -335,7 +328,7 @@ func (b *Bmattermost) handleDownloadFile(rmsg *config.Message, id string) error
if resp.Error != nil { if resp.Error != nil {
return resp.Error return resp.Error
} }
helper.HandleDownloadData(flog, rmsg, finfo.Name, rmsg.Text, url, &data, b.General) helper.HandleDownloadData(b.Log, rmsg, finfo.Name, rmsg.Text, url, &data, b.General)
return nil return nil
} }
@ -395,7 +388,7 @@ func (b *Bmattermost) sendWebhook(msg config.Message) (string, error) {
matterMessage.Props["matterbridge"] = true matterMessage.Props["matterbridge"] = true
err := b.mh.Send(matterMessage) err := b.mh.Send(matterMessage)
if err != nil { if err != nil {
flog.Info(err) b.Log.Info(err)
return "", err return "", err
} }
return "", nil return "", nil
@ -407,7 +400,7 @@ func (b *Bmattermost) skipMessage(message *matterclient.Message) bool {
if message.Type == "system_join_leave" || if message.Type == "system_join_leave" ||
message.Type == "system_join_channel" || message.Type == "system_join_channel" ||
message.Type == "system_leave_channel" { message.Type == "system_leave_channel" {
flog.Debugf("Sending JOIN_LEAVE event from %s to gateway", b.Account) b.Log.Debugf("Sending JOIN_LEAVE event from %s to gateway", b.Account)
b.Remote <- config.Message{Username: "system", Text: message.Text, Channel: message.Channel, Account: b.Account, Event: config.EVENT_JOIN_LEAVE} b.Remote <- config.Message{Username: "system", Text: message.Text, Channel: message.Channel, Account: b.Account, Event: config.EVENT_JOIN_LEAVE}
return true return true
} }
@ -420,7 +413,7 @@ func (b *Bmattermost) skipMessage(message *matterclient.Message) bool {
// Ignore messages sent from matterbridge // Ignore messages sent from matterbridge
if message.Post.Props != nil { if message.Post.Props != nil {
if _, ok := message.Post.Props["matterbridge"].(bool); ok { if _, ok := message.Post.Props["matterbridge"].(bool); ok {
flog.Debugf("sent by matterbridge, ignoring") b.Log.Debugf("sent by matterbridge, ignoring")
return true return true
} }
} }

View File

@ -1,11 +1,11 @@
package brocketchat package brocketchat
import ( import (
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/bridge/helper" "github.com/42wim/matterbridge/bridge/helper"
"github.com/42wim/matterbridge/hook/rockethook" "github.com/42wim/matterbridge/hook/rockethook"
"github.com/42wim/matterbridge/matterhook" "github.com/42wim/matterbridge/matterhook"
log "github.com/sirupsen/logrus"
) )
type MMhook struct { type MMhook struct {
@ -18,14 +18,7 @@ type Brocketchat struct {
*config.BridgeConfig *config.BridgeConfig
} }
var flog *log.Entry func New(cfg *config.BridgeConfig) bridge.Bridger {
var protocol = "rocketchat"
func init() {
flog = log.WithFields(log.Fields{"prefix": protocol})
}
func New(cfg *config.BridgeConfig) *Brocketchat {
return &Brocketchat{BridgeConfig: cfg} return &Brocketchat{BridgeConfig: cfg}
} }
@ -34,7 +27,7 @@ func (b *Brocketchat) Command(cmd string) string {
} }
func (b *Brocketchat) Connect() error { func (b *Brocketchat) Connect() error {
flog.Info("Connecting webhooks") b.Log.Info("Connecting webhooks")
b.mh = matterhook.New(b.Config.WebhookURL, b.mh = matterhook.New(b.Config.WebhookURL,
matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify, matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,
DisableServer: true}) DisableServer: true})
@ -57,7 +50,7 @@ func (b *Brocketchat) Send(msg config.Message) (string, error) {
if msg.Event == config.EVENT_MSG_DELETE { if msg.Event == config.EVENT_MSG_DELETE {
return "", nil return "", nil
} }
flog.Debugf("Receiving %#v", msg) b.Log.Debugf("Receiving %#v", msg)
if msg.Extra != nil { if msg.Extra != nil {
for _, rmsg := range helper.HandleExtra(&msg, b.General) { for _, rmsg := range helper.HandleExtra(&msg, b.General) {
matterMessage := matterhook.OMessage{IconURL: b.Config.IconURL, Channel: rmsg.Channel, UserName: rmsg.Username, matterMessage := matterhook.OMessage{IconURL: b.Config.IconURL, Channel: rmsg.Channel, UserName: rmsg.Username,
@ -81,7 +74,7 @@ func (b *Brocketchat) Send(msg config.Message) (string, error) {
matterMessage.Text = msg.Text matterMessage.Text = msg.Text
err := b.mh.Send(matterMessage) err := b.mh.Send(matterMessage)
if err != nil { if err != nil {
flog.Info(err) b.Log.Info(err)
return "", err return "", err
} }
return "", nil return "", nil
@ -90,12 +83,12 @@ func (b *Brocketchat) Send(msg config.Message) (string, error) {
func (b *Brocketchat) handleRocketHook() { func (b *Brocketchat) handleRocketHook() {
for { for {
message := b.rh.Receive() message := b.rh.Receive()
flog.Debugf("Receiving from rockethook %#v", message) b.Log.Debugf("Receiving from rockethook %#v", message)
// do not loop // do not loop
if message.UserName == b.Config.Nick { if message.UserName == b.Config.Nick {
continue continue
} }
flog.Debugf("Sending message from %s on %s to gateway", message.UserName, b.Account) b.Log.Debugf("Sending message from %s on %s to gateway", message.UserName, b.Account)
b.Remote <- config.Message{Text: message.Text, Username: message.UserName, Channel: message.ChannelName, Account: b.Account, UserID: message.UserID} b.Remote <- config.Message{Text: message.Text, Username: message.UserName, Channel: message.ChannelName, Account: b.Account, UserID: message.UserID}
} }
} }

View File

@ -4,11 +4,11 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/bridge/helper" "github.com/42wim/matterbridge/bridge/helper"
"github.com/42wim/matterbridge/matterhook" "github.com/42wim/matterbridge/matterhook"
"github.com/nlopes/slack" "github.com/nlopes/slack"
log "github.com/sirupsen/logrus"
"html" "html"
"regexp" "regexp"
"strings" "strings"
@ -25,16 +25,9 @@ type Bslack struct {
*config.BridgeConfig *config.BridgeConfig
} }
var flog *log.Entry const messageDeleted = "message_deleted"
var protocol = "slack"
const messageDeleted = "messsage_deleted" func New(cfg *config.BridgeConfig) bridge.Bridger {
func init() {
flog = log.WithFields(log.Fields{"prefix": protocol})
}
func New(cfg *config.BridgeConfig) *Bslack {
return &Bslack{BridgeConfig: cfg} return &Bslack{BridgeConfig: cfg}
} }
@ -45,21 +38,21 @@ func (b *Bslack) Command(cmd string) string {
func (b *Bslack) Connect() error { func (b *Bslack) Connect() error {
if b.Config.WebhookBindAddress != "" { if b.Config.WebhookBindAddress != "" {
if b.Config.WebhookURL != "" { if b.Config.WebhookURL != "" {
flog.Info("Connecting using webhookurl (sending) and webhookbindaddress (receiving)") b.Log.Info("Connecting using webhookurl (sending) and webhookbindaddress (receiving)")
b.mh = matterhook.New(b.Config.WebhookURL, b.mh = matterhook.New(b.Config.WebhookURL,
matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify, matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,
BindAddress: b.Config.WebhookBindAddress}) BindAddress: b.Config.WebhookBindAddress})
} else if b.Config.Token != "" { } else if b.Config.Token != "" {
flog.Info("Connecting using token (sending)") b.Log.Info("Connecting using token (sending)")
b.sc = slack.New(b.Config.Token) b.sc = slack.New(b.Config.Token)
b.rtm = b.sc.NewRTM() b.rtm = b.sc.NewRTM()
go b.rtm.ManageConnection() go b.rtm.ManageConnection()
flog.Info("Connecting using webhookbindaddress (receiving)") b.Log.Info("Connecting using webhookbindaddress (receiving)")
b.mh = matterhook.New(b.Config.WebhookURL, b.mh = matterhook.New(b.Config.WebhookURL,
matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify, matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,
BindAddress: b.Config.WebhookBindAddress}) BindAddress: b.Config.WebhookBindAddress})
} else { } else {
flog.Info("Connecting using webhookbindaddress (receiving)") b.Log.Info("Connecting using webhookbindaddress (receiving)")
b.mh = matterhook.New(b.Config.WebhookURL, b.mh = matterhook.New(b.Config.WebhookURL,
matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify, matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,
BindAddress: b.Config.WebhookBindAddress}) BindAddress: b.Config.WebhookBindAddress})
@ -68,19 +61,19 @@ func (b *Bslack) Connect() error {
return nil return nil
} }
if b.Config.WebhookURL != "" { if b.Config.WebhookURL != "" {
flog.Info("Connecting using webhookurl (sending)") b.Log.Info("Connecting using webhookurl (sending)")
b.mh = matterhook.New(b.Config.WebhookURL, b.mh = matterhook.New(b.Config.WebhookURL,
matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify, matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,
DisableServer: true}) DisableServer: true})
if b.Config.Token != "" { if b.Config.Token != "" {
flog.Info("Connecting using token (receiving)") b.Log.Info("Connecting using token (receiving)")
b.sc = slack.New(b.Config.Token) b.sc = slack.New(b.Config.Token)
b.rtm = b.sc.NewRTM() b.rtm = b.sc.NewRTM()
go b.rtm.ManageConnection() go b.rtm.ManageConnection()
go b.handleSlack() go b.handleSlack()
} }
} else if b.Config.Token != "" { } else if b.Config.Token != "" {
flog.Info("Connecting using token (sending and receiving)") b.Log.Info("Connecting using token (sending and receiving)")
b.sc = slack.New(b.Config.Token) b.sc = slack.New(b.Config.Token)
b.rtm = b.sc.NewRTM() b.rtm = b.sc.NewRTM()
go b.rtm.ManageConnection() go b.rtm.ManageConnection()
@ -115,7 +108,7 @@ func (b *Bslack) JoinChannel(channel config.ChannelInfo) error {
} }
func (b *Bslack) Send(msg config.Message) (string, error) { func (b *Bslack) Send(msg config.Message) (string, error) {
flog.Debugf("Receiving %#v", msg) b.Log.Debugf("Receiving %#v", msg)
// Make a action /me of the message // Make a action /me of the message
if msg.Event == config.EVENT_USER_ACTION { if msg.Event == config.EVENT_USER_ACTION {
@ -197,6 +190,7 @@ func (b *Bslack) Send(msg config.Message) (string, error) {
} }
// Post normal message // Post normal message
b.Log.Debugf("NP IS %#v", np)
_, id, err := b.sc.PostMessage(schannel.ID, msg.Text, np) _, id, err := b.sc.PostMessage(schannel.ID, msg.Text, np)
if err != nil { if err != nil {
return "", err return "", err
@ -243,16 +237,16 @@ func (b *Bslack) getChannelByID(ID string) (*slack.Channel, error) {
func (b *Bslack) handleSlack() { func (b *Bslack) handleSlack() {
messages := make(chan *config.Message) messages := make(chan *config.Message)
if b.Config.WebhookBindAddress != "" { if b.Config.WebhookBindAddress != "" {
flog.Debugf("Choosing webhooks based receiving") b.Log.Debugf("Choosing webhooks based receiving")
go b.handleMatterHook(messages) go b.handleMatterHook(messages)
} else { } else {
flog.Debugf("Choosing token based receiving") b.Log.Debugf("Choosing token based receiving")
go b.handleSlackClient(messages) go b.handleSlackClient(messages)
} }
time.Sleep(time.Second) time.Sleep(time.Second)
flog.Debug("Start listening for Slack messages") b.Log.Debug("Start listening for Slack messages")
for message := range messages { for message := range messages {
flog.Debugf("Sending message from %s on %s to gateway", message.Username, b.Account) b.Log.Debugf("Sending message from %s on %s to gateway", message.Username, b.Account)
// cleanup the message // cleanup the message
message.Text = b.replaceURL(message.Text) message.Text = b.replaceURL(message.Text)
@ -264,7 +258,7 @@ func (b *Bslack) handleSlack() {
// Add the avatar // Add the avatar
message.Avatar = b.getAvatar(message.Username) message.Avatar = b.getAvatar(message.Username)
flog.Debugf("Message is %#v", message) b.Log.Debugf("Message is %#v", message)
b.Remote <- *message b.Remote <- *message
} }
} }
@ -272,22 +266,22 @@ func (b *Bslack) handleSlack() {
func (b *Bslack) handleSlackClient(messages chan *config.Message) { func (b *Bslack) handleSlackClient(messages chan *config.Message) {
for msg := range b.rtm.IncomingEvents { for msg := range b.rtm.IncomingEvents {
if msg.Type != "user_typing" && msg.Type != "latency_report" { if msg.Type != "user_typing" && msg.Type != "latency_report" {
flog.Debugf("Receiving from slackclient %#v", msg.Data) b.Log.Debugf("Receiving from slackclient %#v", msg.Data)
} }
switch ev := msg.Data.(type) { switch ev := msg.Data.(type) {
case *slack.MessageEvent: case *slack.MessageEvent:
if b.skipMessageEvent(ev) { if b.skipMessageEvent(ev) {
flog.Debugf("Skipped message: %#v", ev) b.Log.Debugf("Skipped message: %#v", ev)
continue continue
} }
rmsg, err := b.handleMessageEvent(ev) rmsg, err := b.handleMessageEvent(ev)
if err != nil { if err != nil {
flog.Errorf("%#v", err) b.Log.Errorf("%#v", err)
continue continue
} }
messages <- rmsg messages <- rmsg
case *slack.OutgoingErrorEvent: case *slack.OutgoingErrorEvent:
flog.Debugf("%#v", ev.Error()) b.Log.Debugf("%#v", ev.Error())
case *slack.ChannelJoinedEvent: case *slack.ChannelJoinedEvent:
b.Users, _ = b.sc.GetUsers() b.Users, _ = b.sc.GetUsers()
case *slack.ConnectedEvent: case *slack.ConnectedEvent:
@ -303,9 +297,9 @@ func (b *Bslack) handleSlackClient(messages chan *config.Message) {
b.channels = append(b.channels, *channel) b.channels = append(b.channels, *channel)
} }
case *slack.InvalidAuthEvent: case *slack.InvalidAuthEvent:
flog.Fatalf("Invalid Token %#v", ev) b.Log.Fatalf("Invalid Token %#v", ev)
case *slack.ConnectionErrorEvent: case *slack.ConnectionErrorEvent:
flog.Errorf("Connection failed %#v %#v", ev.Error(), ev.ErrorObj) b.Log.Errorf("Connection failed %#v %#v", ev.Error(), ev.ErrorObj)
default: default:
} }
} }
@ -314,7 +308,7 @@ func (b *Bslack) handleSlackClient(messages chan *config.Message) {
func (b *Bslack) handleMatterHook(messages chan *config.Message) { func (b *Bslack) handleMatterHook(messages chan *config.Message) {
for { for {
message := b.mh.Receive() message := b.mh.Receive()
flog.Debugf("receiving from matterhook (slack) %#v", message) b.Log.Debugf("receiving from matterhook (slack) %#v", message)
if message.UserName == "slackbot" { if message.UserName == "slackbot" {
continue continue
} }
@ -403,7 +397,7 @@ func (b *Bslack) handleDownloadFile(rmsg *config.Message, file *slack.File) erro
comment = results[0][1] comment = results[0][1]
} }
err := helper.HandleDownloadSize(flog, rmsg, file.Name, int64(file.Size), b.General) err := helper.HandleDownloadSize(b.Log, rmsg, file.Name, int64(file.Size), b.General)
if err != nil { if err != nil {
return err return err
} }
@ -413,7 +407,7 @@ func (b *Bslack) handleDownloadFile(rmsg *config.Message, file *slack.File) erro
return fmt.Errorf("download %s failed %#v", file.URLPrivateDownload, err) return fmt.Errorf("download %s failed %#v", file.URLPrivateDownload, err)
} }
// add the downloaded data to the message // add the downloaded data to the message
helper.HandleDownloadData(flog, rmsg, file.Name, comment, file.URLPrivateDownload, data, b.General) helper.HandleDownloadData(b.Log, rmsg, file.Name, comment, file.URLPrivateDownload, data, b.General)
return nil return nil
} }
@ -429,7 +423,7 @@ func (b *Bslack) handleUploadFile(msg *config.Message, channelID string) (string
InitialComment: fi.Comment, InitialComment: fi.Comment,
}) })
if err != nil { if err != nil {
flog.Errorf("uploadfile %#v", err) b.Log.Errorf("uploadfile %#v", err)
} }
} }
return "", nil return "", nil
@ -444,7 +438,7 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er
// Edit message // Edit message
if !b.Config.EditDisable && ev.SubMessage != nil && ev.SubMessage.ThreadTimestamp != ev.SubMessage.Timestamp { if !b.Config.EditDisable && ev.SubMessage != nil && ev.SubMessage.ThreadTimestamp != ev.SubMessage.Timestamp {
flog.Debugf("SubMessage %#v", ev.SubMessage) b.Log.Debugf("SubMessage %#v", ev.SubMessage)
ev.User = ev.SubMessage.User ev.User = ev.SubMessage.User
ev.Text = ev.SubMessage.Text + b.Config.EditSuffix ev.Text = ev.SubMessage.Text + b.Config.EditSuffix
} }
@ -543,7 +537,7 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er
if ev.File != nil { if ev.File != nil {
err := b.handleDownloadFile(&rmsg, ev.File) err := b.handleDownloadFile(&rmsg, ev.File)
if err != nil { if err != nil {
flog.Errorf("download failed: %s", err) b.Log.Errorf("download failed: %s", err)
} }
} }
@ -593,7 +587,7 @@ func (b *Bslack) sendWebhook(msg config.Message) (string, error) {
} }
err := b.mh.Send(matterMessage) err := b.mh.Send(matterMessage)
if err != nil { if err != nil {
flog.Error(err) b.Log.Error(err)
return "", err return "", err
} }
return "", nil return "", nil

View File

@ -2,10 +2,11 @@ package bsshchat
import ( import (
"bufio" "bufio"
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/bridge/helper" "github.com/42wim/matterbridge/bridge/helper"
log "github.com/sirupsen/logrus"
"github.com/shazow/ssh-chat/sshd" "github.com/shazow/ssh-chat/sshd"
log "github.com/sirupsen/logrus"
"io" "io"
"strings" "strings"
) )
@ -16,20 +17,13 @@ type Bsshchat struct {
*config.BridgeConfig *config.BridgeConfig
} }
var flog *log.Entry func New(cfg *config.BridgeConfig) bridge.Bridger {
var protocol = "sshchat"
func init() {
flog = log.WithFields(log.Fields{"prefix": protocol})
}
func New(cfg *config.BridgeConfig) *Bsshchat {
return &Bsshchat{BridgeConfig: cfg} return &Bsshchat{BridgeConfig: cfg}
} }
func (b *Bsshchat) Connect() error { func (b *Bsshchat) Connect() error {
var err error var err error
flog.Infof("Connecting %s", b.Config.Server) b.Log.Infof("Connecting %s", b.Config.Server)
go func() { go func() {
err = sshd.ConnectShell(b.Config.Server, b.Config.Nick, func(r io.Reader, w io.WriteCloser) error { err = sshd.ConnectShell(b.Config.Server, b.Config.Nick, func(r io.Reader, w io.WriteCloser) error {
b.r = bufio.NewScanner(r) b.r = bufio.NewScanner(r)
@ -41,10 +35,10 @@ func (b *Bsshchat) Connect() error {
}) })
}() }()
if err != nil { if err != nil {
flog.Debugf("%#v", err) b.Log.Debugf("%#v", err)
return err return err
} }
flog.Info("Connection succeeded") b.Log.Info("Connection succeeded")
return nil return nil
} }
@ -61,7 +55,7 @@ func (b *Bsshchat) Send(msg config.Message) (string, error) {
if msg.Event == config.EVENT_MSG_DELETE { if msg.Event == config.EVENT_MSG_DELETE {
return "", nil return "", nil
} }
flog.Debugf("Receiving %#v", msg) b.Log.Debugf("Receiving %#v", msg)
if msg.Extra != nil { if msg.Extra != nil {
for _, rmsg := range helper.HandleExtra(&msg, b.General) { for _, rmsg := range helper.HandleExtra(&msg, b.General) {
b.w.Write([]byte(rmsg.Username + rmsg.Text + "\r\n")) b.w.Write([]byte(rmsg.Username + rmsg.Text + "\r\n"))
@ -93,10 +87,10 @@ func (b *Bsshchat) sshchatKeepAlive() chan bool {
for { for {
select { select {
case <-ticker.C: case <-ticker.C:
flog.Debugf("PING") b.Log.Debugf("PING")
err := b.xc.PingC2S("", "") err := b.xc.PingC2S("", "")
if err != nil { if err != nil {
flog.Debugf("PING failed %#v", err) b.Log.Debugf("PING failed %#v", err)
} }
case <-done: case <-done:
return return
@ -130,7 +124,7 @@ func (b *Bsshchat) handleSshChat() error {
continue continue
} }
if !wait { if !wait {
flog.Debugf("message %#v", res) b.Log.Debugf("message %#v", res)
rmsg := config.Message{Username: res[0], Text: strings.Join(res[1:], ":"), Channel: "sshchat", Account: b.Account, UserID: "nick"} rmsg := config.Message{Username: res[0], Text: strings.Join(res[1:], ":"), Channel: "sshchat", Account: b.Account, UserID: "nick"}
b.Remote <- rmsg b.Remote <- rmsg
} }

View File

@ -2,11 +2,11 @@ package bsteam
import ( import (
"fmt" "fmt"
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/Philipp15b/go-steam" "github.com/Philipp15b/go-steam"
"github.com/Philipp15b/go-steam/protocol/steamlang" "github.com/Philipp15b/go-steam/protocol/steamlang"
"github.com/Philipp15b/go-steam/steamid" "github.com/Philipp15b/go-steam/steamid"
log "github.com/sirupsen/logrus"
//"io/ioutil" //"io/ioutil"
"strconv" "strconv"
"sync" "sync"
@ -21,14 +21,7 @@ type Bsteam struct {
*config.BridgeConfig *config.BridgeConfig
} }
var flog *log.Entry func New(cfg *config.BridgeConfig) bridge.Bridger {
var protocol = "steam"
func init() {
flog = log.WithFields(log.Fields{"prefix": protocol})
}
func New(cfg *config.BridgeConfig) *Bsteam {
b := &Bsteam{BridgeConfig: cfg} b := &Bsteam{BridgeConfig: cfg}
b.userMap = make(map[steamid.SteamId]string) b.userMap = make(map[steamid.SteamId]string)
b.connected = make(chan struct{}) b.connected = make(chan struct{})
@ -36,13 +29,13 @@ func New(cfg *config.BridgeConfig) *Bsteam {
} }
func (b *Bsteam) Connect() error { func (b *Bsteam) Connect() error {
flog.Info("Connecting") b.Log.Info("Connecting")
b.c = steam.NewClient() b.c = steam.NewClient()
go b.handleEvents() go b.handleEvents()
go b.c.Connect() go b.c.Connect()
select { select {
case <-b.connected: case <-b.connected:
flog.Info("Connection succeeded") b.Log.Info("Connection succeeded")
case <-time.After(time.Second * 30): case <-time.After(time.Second * 30):
return fmt.Errorf("connection timed out") return fmt.Errorf("connection timed out")
} }
@ -95,11 +88,11 @@ func (b *Bsteam) handleEvents() {
// Maybe works // Maybe works
//myLoginInfo.SentryFileHash, _ = ioutil.ReadFile("sentry") //myLoginInfo.SentryFileHash, _ = ioutil.ReadFile("sentry")
for event := range b.c.Events() { for event := range b.c.Events() {
//flog.Info(event) //b.Log.Info(event)
switch e := event.(type) { switch e := event.(type) {
case *steam.ChatMsgEvent: case *steam.ChatMsgEvent:
flog.Debugf("Receiving ChatMsgEvent: %#v", e) b.Log.Debugf("Receiving ChatMsgEvent: %#v", e)
flog.Debugf("Sending message from %s on %s to gateway", b.getNick(e.ChatterId), b.Account) b.Log.Debugf("Sending message from %s on %s to gateway", b.getNick(e.ChatterId), b.Account)
var channel int64 var channel int64
if e.ChatRoomId == 0 { if e.ChatRoomId == 0 {
channel = int64(e.ChatterId) channel = int64(e.ChatterId)
@ -110,7 +103,7 @@ func (b *Bsteam) handleEvents() {
msg := config.Message{Username: b.getNick(e.ChatterId), Text: e.Message, Channel: strconv.FormatInt(channel, 10), Account: b.Account, UserID: strconv.FormatInt(int64(e.ChatterId), 10)} msg := config.Message{Username: b.getNick(e.ChatterId), Text: e.Message, Channel: strconv.FormatInt(channel, 10), Account: b.Account, UserID: strconv.FormatInt(int64(e.ChatterId), 10)}
b.Remote <- msg b.Remote <- msg
case *steam.PersonaStateEvent: case *steam.PersonaStateEvent:
flog.Debugf("PersonaStateEvent: %#v\n", e) b.Log.Debugf("PersonaStateEvent: %#v\n", e)
b.Lock() b.Lock()
b.userMap[e.FriendId] = e.Name b.userMap[e.FriendId] = e.Name
b.Unlock() b.Unlock()
@ -118,47 +111,47 @@ func (b *Bsteam) handleEvents() {
b.c.Auth.LogOn(myLoginInfo) b.c.Auth.LogOn(myLoginInfo)
case *steam.MachineAuthUpdateEvent: case *steam.MachineAuthUpdateEvent:
/* /*
flog.Info("authupdate", e) b.Log.Info("authupdate", e)
flog.Info("hash", e.Hash) b.Log.Info("hash", e.Hash)
ioutil.WriteFile("sentry", e.Hash, 0666) ioutil.WriteFile("sentry", e.Hash, 0666)
*/ */
case *steam.LogOnFailedEvent: case *steam.LogOnFailedEvent:
flog.Info("Logon failed", e) b.Log.Info("Logon failed", e)
switch e.Result { switch e.Result {
case steamlang.EResult_AccountLogonDeniedNeedTwoFactorCode: case steamlang.EResult_AccountLogonDeniedNeedTwoFactorCode:
{ {
flog.Info("Steam guard isn't letting me in! Enter 2FA code:") b.Log.Info("Steam guard isn't letting me in! Enter 2FA code:")
var code string var code string
fmt.Scanf("%s", &code) fmt.Scanf("%s", &code)
myLoginInfo.TwoFactorCode = code myLoginInfo.TwoFactorCode = code
} }
case steamlang.EResult_AccountLogonDenied: case steamlang.EResult_AccountLogonDenied:
{ {
flog.Info("Steam guard isn't letting me in! Enter auth code:") b.Log.Info("Steam guard isn't letting me in! Enter auth code:")
var code string var code string
fmt.Scanf("%s", &code) fmt.Scanf("%s", &code)
myLoginInfo.AuthCode = code myLoginInfo.AuthCode = code
} }
default: default:
log.Errorf("LogOnFailedEvent: %#v ", e.Result) b.Log.Errorf("LogOnFailedEvent: %#v ", e.Result)
// TODO: Handle EResult_InvalidLoginAuthCode // TODO: Handle EResult_InvalidLoginAuthCode
return return
} }
case *steam.LoggedOnEvent: case *steam.LoggedOnEvent:
flog.Debugf("LoggedOnEvent: %#v", e) b.Log.Debugf("LoggedOnEvent: %#v", e)
b.connected <- struct{}{} b.connected <- struct{}{}
flog.Debugf("setting online") b.Log.Debugf("setting online")
b.c.Social.SetPersonaState(steamlang.EPersonaState_Online) b.c.Social.SetPersonaState(steamlang.EPersonaState_Online)
case *steam.DisconnectedEvent: case *steam.DisconnectedEvent:
flog.Info("Disconnected") b.Log.Info("Disconnected")
flog.Info("Attempting to reconnect...") b.Log.Info("Attempting to reconnect...")
b.c.Connect() b.c.Connect()
case steam.FatalErrorEvent: case steam.FatalErrorEvent:
flog.Error(e) b.Log.Error(e)
case error: case error:
flog.Error(e) b.Log.Error(e)
default: default:
flog.Debugf("unknown event %#v", e) b.Log.Debugf("unknown event %#v", e)
} }
} }
} }

View File

@ -5,10 +5,10 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/bridge/helper" "github.com/42wim/matterbridge/bridge/helper"
"github.com/go-telegram-bot-api/telegram-bot-api" "github.com/go-telegram-bot-api/telegram-bot-api"
log "github.com/sirupsen/logrus"
) )
type Btelegram struct { type Btelegram struct {
@ -17,33 +17,26 @@ type Btelegram struct {
avatarMap map[string]string // keep cache of userid and avatar sha avatarMap map[string]string // keep cache of userid and avatar sha
} }
var flog *log.Entry func New(cfg *config.BridgeConfig) bridge.Bridger {
var protocol = "telegram"
func init() {
flog = log.WithFields(log.Fields{"prefix": protocol})
}
func New(cfg *config.BridgeConfig) *Btelegram {
return &Btelegram{BridgeConfig: cfg, avatarMap: make(map[string]string)} return &Btelegram{BridgeConfig: cfg, avatarMap: make(map[string]string)}
} }
func (b *Btelegram) Connect() error { func (b *Btelegram) Connect() error {
var err error var err error
flog.Info("Connecting") b.Log.Info("Connecting")
b.c, err = tgbotapi.NewBotAPI(b.Config.Token) b.c, err = tgbotapi.NewBotAPI(b.Config.Token)
if err != nil { if err != nil {
flog.Debugf("%#v", err) b.Log.Debugf("%#v", err)
return err return err
} }
u := tgbotapi.NewUpdate(0) u := tgbotapi.NewUpdate(0)
u.Timeout = 60 u.Timeout = 60
updates, err := b.c.GetUpdatesChan(u) updates, err := b.c.GetUpdatesChan(u)
if err != nil { if err != nil {
flog.Debugf("%#v", err) b.Log.Debugf("%#v", err)
return err return err
} }
flog.Info("Connection succeeded") b.Log.Info("Connection succeeded")
go b.handleRecv(updates) go b.handleRecv(updates)
return nil return nil
} }
@ -57,7 +50,7 @@ func (b *Btelegram) JoinChannel(channel config.ChannelInfo) error {
} }
func (b *Btelegram) Send(msg config.Message) (string, error) { func (b *Btelegram) Send(msg config.Message) (string, error) {
flog.Debugf("Receiving %#v", msg) b.Log.Debugf("Receiving %#v", msg)
// get the chatid // get the chatid
chatid, err := strconv.ParseInt(msg.Channel, 10, 64) chatid, err := strconv.ParseInt(msg.Channel, 10, 64)
@ -106,11 +99,11 @@ func (b *Btelegram) Send(msg config.Message) (string, error) {
} }
m := tgbotapi.NewEditMessageText(chatid, msgid, msg.Username+msg.Text) m := tgbotapi.NewEditMessageText(chatid, msgid, msg.Username+msg.Text)
if b.Config.MessageFormat == "HTML" { if b.Config.MessageFormat == "HTML" {
flog.Debug("Using mode HTML") b.Log.Debug("Using mode HTML")
m.ParseMode = tgbotapi.ModeHTML m.ParseMode = tgbotapi.ModeHTML
} }
if b.Config.MessageFormat == "Markdown" { if b.Config.MessageFormat == "Markdown" {
flog.Debug("Using mode markdown") b.Log.Debug("Using mode markdown")
m.ParseMode = tgbotapi.ModeMarkdown m.ParseMode = tgbotapi.ModeMarkdown
} }
_, err = b.c.Send(m) _, err = b.c.Send(m)
@ -126,10 +119,10 @@ func (b *Btelegram) Send(msg config.Message) (string, error) {
func (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) { func (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {
for update := range updates { for update := range updates {
flog.Debugf("Receiving from telegram: %#v", update.Message) b.Log.Debugf("Receiving from telegram: %#v", update.Message)
if update.Message == nil && update.ChannelPost == nil { if update.Message == nil && update.ChannelPost == nil {
flog.Error("Getting nil messages, this shouldn't happen.") b.Log.Error("Getting nil messages, this shouldn't happen.")
continue continue
} }
@ -189,7 +182,7 @@ func (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {
// handle any downloads // handle any downloads
err := b.handleDownload(message, &rmsg) err := b.handleDownload(message, &rmsg)
if err != nil { if err != nil {
flog.Errorf("download failed: %s", err) b.Log.Errorf("download failed: %s", err)
} }
// handle forwarded messages // handle forwarded messages
@ -233,8 +226,8 @@ func (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {
if rmsg.Text != "" || len(rmsg.Extra) > 0 { if rmsg.Text != "" || len(rmsg.Extra) > 0 {
rmsg.Avatar = helper.GetAvatar(b.avatarMap, strconv.Itoa(message.From.ID), b.General) rmsg.Avatar = helper.GetAvatar(b.avatarMap, strconv.Itoa(message.From.ID), b.General)
flog.Debugf("Sending message from %s on %s to gateway", rmsg.Username, b.Account) b.Log.Debugf("Sending message from %s on %s to gateway", rmsg.Username, b.Account)
flog.Debugf("Message is %#v", rmsg) b.Log.Debugf("Message is %#v", rmsg)
b.Remote <- rmsg b.Remote <- rmsg
} }
} }
@ -256,26 +249,26 @@ func (b *Btelegram) handleDownloadAvatar(userid int, channel string) {
if _, ok := b.avatarMap[strconv.Itoa(userid)]; !ok { if _, ok := b.avatarMap[strconv.Itoa(userid)]; !ok {
photos, err := b.c.GetUserProfilePhotos(tgbotapi.UserProfilePhotosConfig{UserID: userid, Limit: 1}) photos, err := b.c.GetUserProfilePhotos(tgbotapi.UserProfilePhotosConfig{UserID: userid, Limit: 1})
if err != nil { if err != nil {
flog.Errorf("Userprofile download failed for %#v %s", userid, err) b.Log.Errorf("Userprofile download failed for %#v %s", userid, err)
} }
if len(photos.Photos) > 0 { if len(photos.Photos) > 0 {
photo := photos.Photos[0][0] photo := photos.Photos[0][0]
url := b.getFileDirectURL(photo.FileID) url := b.getFileDirectURL(photo.FileID)
name := strconv.Itoa(userid) + ".png" name := strconv.Itoa(userid) + ".png"
flog.Debugf("trying to download %#v fileid %#v with size %#v", name, photo.FileID, photo.FileSize) b.Log.Debugf("trying to download %#v fileid %#v with size %#v", name, photo.FileID, photo.FileSize)
err := helper.HandleDownloadSize(flog, &rmsg, name, int64(photo.FileSize), b.General) err := helper.HandleDownloadSize(b.Log, &rmsg, name, int64(photo.FileSize), b.General)
if err != nil { if err != nil {
flog.Error(err) b.Log.Error(err)
return return
} }
data, err := helper.DownloadFile(url) data, err := helper.DownloadFile(url)
if err != nil { if err != nil {
flog.Errorf("download %s failed %#v", url, err) b.Log.Errorf("download %s failed %#v", url, err)
return return
} }
helper.HandleDownloadData(flog, &rmsg, name, rmsg.Text, "", data, b.General) helper.HandleDownloadData(b.Log, &rmsg, name, rmsg.Text, "", data, b.General)
b.Remote <- rmsg b.Remote <- rmsg
} }
} }
@ -345,12 +338,12 @@ func (b *Btelegram) handleDownload(message *tgbotapi.Message, rmsg *config.Messa
} }
// use the URL instead of native upload // use the URL instead of native upload
if b.Config.UseInsecureURL { if b.Config.UseInsecureURL {
flog.Debugf("Setting message text to :%s", text) b.Log.Debugf("Setting message text to :%s", text)
rmsg.Text = rmsg.Text + text rmsg.Text = rmsg.Text + text
return nil return nil
} }
// if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra // if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra
err := helper.HandleDownloadSize(flog, rmsg, name, int64(size), b.General) err := helper.HandleDownloadSize(b.Log, rmsg, name, int64(size), b.General)
if err != nil { if err != nil {
return err return err
} }
@ -358,7 +351,7 @@ func (b *Btelegram) handleDownload(message *tgbotapi.Message, rmsg *config.Messa
if err != nil { if err != nil {
return err return err
} }
helper.HandleDownloadData(flog, rmsg, name, message.Caption, "", data, b.General) helper.HandleDownloadData(b.Log, rmsg, name, message.Caption, "", data, b.General)
return nil return nil
} }
@ -376,7 +369,7 @@ func (b *Btelegram) handleUploadFile(msg *config.Message, chatid int64) (string,
} }
_, err := b.c.Send(c) _, err := b.c.Send(c)
if err != nil { if err != nil {
log.Errorf("file upload failed: %#v", err) b.Log.Errorf("file upload failed: %#v", err)
} }
if fi.Comment != "" { if fi.Comment != "" {
b.sendMessage(chatid, msg.Username+fi.Comment) b.sendMessage(chatid, msg.Username+fi.Comment)
@ -388,11 +381,11 @@ func (b *Btelegram) handleUploadFile(msg *config.Message, chatid int64) (string,
func (b *Btelegram) sendMessage(chatid int64, text string) (string, error) { func (b *Btelegram) sendMessage(chatid int64, text string) (string, error) {
m := tgbotapi.NewMessage(chatid, text) m := tgbotapi.NewMessage(chatid, text)
if b.Config.MessageFormat == "HTML" { if b.Config.MessageFormat == "HTML" {
flog.Debug("Using mode HTML") b.Log.Debug("Using mode HTML")
m.ParseMode = tgbotapi.ModeHTML m.ParseMode = tgbotapi.ModeHTML
} }
if b.Config.MessageFormat == "Markdown" { if b.Config.MessageFormat == "Markdown" {
flog.Debug("Using mode markdown") b.Log.Debug("Using mode markdown")
m.ParseMode = tgbotapi.ModeMarkdown m.ParseMode = tgbotapi.ModeMarkdown
} }
res, err := b.c.Send(m) res, err := b.c.Send(m)
@ -407,7 +400,7 @@ func (b *Btelegram) cacheAvatar(msg *config.Message) (string, error) {
/* if we have a sha we have successfully uploaded the file to the media server, /* if we have a sha we have successfully uploaded the file to the media server,
so we can now cache the sha */ so we can now cache the sha */
if fi.SHA != "" { if fi.SHA != "" {
flog.Debugf("Added %s to %s in avatarMap", fi.SHA, msg.UserID) b.Log.Debugf("Added %s to %s in avatarMap", fi.SHA, msg.UserID)
b.avatarMap[msg.UserID] = fi.SHA b.avatarMap[msg.UserID] = fi.SHA
} }
return "", nil return "", nil

View File

@ -2,11 +2,11 @@ package bxmpp
import ( import (
"crypto/tls" "crypto/tls"
"github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/bridge/helper" "github.com/42wim/matterbridge/bridge/helper"
"github.com/jpillora/backoff" "github.com/jpillora/backoff"
"github.com/mattn/go-xmpp" "github.com/mattn/go-xmpp"
log "github.com/sirupsen/logrus"
"strings" "strings"
"time" "time"
) )
@ -17,14 +17,7 @@ type Bxmpp struct {
*config.BridgeConfig *config.BridgeConfig
} }
var flog *log.Entry func New(cfg *config.BridgeConfig) bridge.Bridger {
var protocol = "xmpp"
func init() {
flog = log.WithFields(log.Fields{"prefix": protocol})
}
func New(cfg *config.BridgeConfig) *Bxmpp {
b := &Bxmpp{BridgeConfig: cfg} b := &Bxmpp{BridgeConfig: cfg}
b.xmppMap = make(map[string]string) b.xmppMap = make(map[string]string)
return b return b
@ -32,13 +25,13 @@ func New(cfg *config.BridgeConfig) *Bxmpp {
func (b *Bxmpp) Connect() error { func (b *Bxmpp) Connect() error {
var err error var err error
flog.Infof("Connecting %s", b.Config.Server) b.Log.Infof("Connecting %s", b.Config.Server)
b.xc, err = b.createXMPP() b.xc, err = b.createXMPP()
if err != nil { if err != nil {
flog.Debugf("%#v", err) b.Log.Debugf("%#v", err)
return err return err
} }
flog.Info("Connection succeeded") b.Log.Info("Connection succeeded")
go func() { go func() {
initial := true initial := true
bf := &backoff.Backoff{ bf := &backoff.Backoff{
@ -52,7 +45,7 @@ func (b *Bxmpp) Connect() error {
initial = false initial = false
} }
d := bf.Duration() d := bf.Duration()
flog.Infof("Disconnected. Reconnecting in %s", d) b.Log.Infof("Disconnected. Reconnecting in %s", d)
time.Sleep(d) time.Sleep(d)
b.xc, err = b.createXMPP() b.xc, err = b.createXMPP()
if err == nil { if err == nil {
@ -79,7 +72,7 @@ func (b *Bxmpp) Send(msg config.Message) (string, error) {
if msg.Event == config.EVENT_MSG_DELETE { if msg.Event == config.EVENT_MSG_DELETE {
return "", nil return "", nil
} }
flog.Debugf("Receiving %#v", msg) b.Log.Debugf("Receiving %#v", msg)
// Upload a file (in xmpp case send the upload URL because xmpp has no native upload support) // Upload a file (in xmpp case send the upload URL because xmpp has no native upload support)
if msg.Extra != nil { if msg.Extra != nil {
@ -131,10 +124,10 @@ func (b *Bxmpp) xmppKeepAlive() chan bool {
for { for {
select { select {
case <-ticker.C: case <-ticker.C:
flog.Debugf("PING") b.Log.Debugf("PING")
err := b.xc.PingC2S("", "") err := b.xc.PingC2S("", "")
if err != nil { if err != nil {
flog.Debugf("PING failed %#v", err) b.Log.Debugf("PING failed %#v", err)
} }
case <-done: case <-done:
return return
@ -167,8 +160,8 @@ func (b *Bxmpp) handleXMPP() error {
if ok { if ok {
rmsg.Event = config.EVENT_USER_ACTION rmsg.Event = config.EVENT_USER_ACTION
} }
flog.Debugf("Sending message from %s on %s to gateway", rmsg.Username, b.Account) b.Log.Debugf("Sending message from %s on %s to gateway", rmsg.Username, b.Account)
flog.Debugf("Message is %#v", rmsg) b.Log.Debugf("Message is %#v", rmsg)
b.Remote <- rmsg b.Remote <- rmsg
} }
case xmpp.Presence: case xmpp.Presence:

View File

@ -4,13 +4,26 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"github.com/42wim/matterbridge/bridge" "github.com/42wim/matterbridge/bridge"
"github.com/42wim/matterbridge/bridge/api"
"github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/bridge/discord"
"github.com/42wim/matterbridge/bridge/gitter"
"github.com/42wim/matterbridge/bridge/irc"
"github.com/42wim/matterbridge/bridge/matrix"
"github.com/42wim/matterbridge/bridge/mattermost"
"github.com/42wim/matterbridge/bridge/rocketchat"
"github.com/42wim/matterbridge/bridge/slack"
"github.com/42wim/matterbridge/bridge/sshchat"
"github.com/42wim/matterbridge/bridge/steam"
"github.com/42wim/matterbridge/bridge/telegram"
"github.com/42wim/matterbridge/bridge/xmpp"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
// "github.com/davecgh/go-spew/spew" // "github.com/davecgh/go-spew/spew"
"crypto/sha1" "crypto/sha1"
"github.com/hashicorp/golang-lru" "github.com/hashicorp/golang-lru"
"github.com/peterhellberg/emojilib" "github.com/peterhellberg/emojilib"
"net/http" "net/http"
"reflect"
"regexp" "regexp"
"strings" "strings"
"time" "time"
@ -36,6 +49,21 @@ type BrMsgID struct {
var flog *log.Entry var flog *log.Entry
var bridgeMap = map[string]bridge.Factory{
"mattermost": bmattermost.New,
"irc": birc.New,
"gitter": bgitter.New,
"matrix": bmatrix.New,
"slack": bslack.New,
"api": api.New,
"telegram": btelegram.New,
"discord": bdiscord.New,
"steam": bsteam.New,
"sshchat": bsshchat.New,
"rocketchat": brocketchat.New,
"xmpp": bxmpp.New,
}
func init() { func init() {
flog = log.WithFields(log.Fields{"prefix": "gateway"}) flog = log.WithFields(log.Fields{"prefix": "gateway"})
} }
@ -52,7 +80,17 @@ func New(cfg config.Gateway, r *Router) *Gateway {
func (gw *Gateway) AddBridge(cfg *config.Bridge) error { func (gw *Gateway) AddBridge(cfg *config.Bridge) error {
br := gw.Router.getBridge(cfg.Account) br := gw.Router.getBridge(cfg.Account)
if br == nil { if br == nil {
br = bridge.New(gw.Config, cfg, gw.Message) br = bridge.New(cfg)
// set logging
br.Log = log.WithFields(log.Fields{"prefix": "bridge"})
// get the protocol configuration (eg irc)
pcfg := getField(gw.Config, strings.Title(br.Protocol))
// get the config for this name (eg freenode, from irc.freenode)
br.Config = pcfg[br.Name]
// create the bridge config
brconfig := &config.BridgeConfig{General: &gw.Config.General, Account: br.Account, Remote: gw.Message, Config: br.Config, Log: log.WithFields(log.Fields{"prefix": br.Protocol})}
// add the actual bridger for this protocol to this bridge using the bridgeMap
br.Bridger = bridgeMap[br.Protocol](brconfig)
} }
gw.mapChannelsToBridge(br) gw.mapChannelsToBridge(br)
gw.Bridges[cfg.Account] = br gw.Bridges[cfg.Account] = br
@ -412,3 +450,11 @@ func (gw *Gateway) validGatewayDest(msg *config.Message, channel *config.Channel
func isApi(account string) bool { func isApi(account string) bool {
return strings.HasPrefix(account, "api.") return strings.HasPrefix(account, "api.")
} }
//getField returns the Protocol configuration for a specific protocol (field)
func getField(cfg *config.Config, field string) map[string]config.Protocol {
r := reflect.ValueOf(cfg)
f := reflect.Indirect(r).FieldByName(field)
i := f.Interface()
return i.(map[string]config.Protocol)
}