Thumbnail

rani/matterbridge.git

Clone URL: https://git.buni.party/rani/matterbridge.git

commit fb570a841d3bba9f89edad18e29435731839476e Author: Wim <wim@42.be> Date: Tue Feb 27 00:33:21 2018 +0000 Refactor using factory diff --git a/bridge/api/api.go b/bridge/api/api.go index 531315a..b441526 100644 --- a/bridge/api/api.go +++ b/bridge/api/api.go @@ -210 +210 @@ package api    import (   "encoding/json" + "github.com/42wim/matterbridge/bridge"   "github.com/42wim/matterbridge/bridge/config"   "github.com/labstack/echo"   "github.com/labstack/echo/middleware" - log "github.com/sirupsen/logrus"   "github.com/zfjagann/golang-ring"   "net/http"   "sync" @@ -2614 +267 @@ type ApiMessage struct {   Gateway string `json:"gateway"`  }   -var flog *log.Entry -var protocol = "api" - -func init() { - flog = log.WithFields(log.Fields{"prefix": protocol}) -} - -func New(cfg *config.BridgeConfig) *Api { +func New(cfg *config.BridgeConfig) bridge.Bridger {   b := &Api{BridgeConfig: cfg}   e := echo.New()   e.HideBanner = true @@ -5010 +4310 @@ func New(cfg *config.BridgeConfig) *Api {   e.POST("/api/message", b.handlePostMessage)   go func() {   if b.Config.BindAddress == "" { - flog.Fatalf("No BindAddress configured.") + b.Log.Fatalf("No BindAddress configured.")   } - flog.Infof("Listening on %s", b.Config.BindAddress) - flog.Fatal(e.Start(b.Config.BindAddress)) + b.Log.Infof("Listening on %s", b.Config.BindAddress) + b.Log.Fatal(e.Start(b.Config.BindAddress))   }()   return b  } @@ -927 +857 @@ func (b *Api) handlePostMessage(c echo.Context) error {   message.Account = b.Account   message.ID = ""   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   return c.JSON(http.StatusOK, message)  } diff --git a/bridge/bridge.go b/bridge/bridge.go index 87db37e..93e1cd8 100644 --- a/bridge/bridge.go +++ b/bridge/bridge.go @@ -119 +17 @@  package bridge    import ( - "github.com/42wim/matterbridge/bridge/api"   "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"     "strings" @@ -3415 +2213 @@ type Bridge struct {   Protocol string   Channels map[string]config.ChannelInfo   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() { - flog = log.WithFields(log.Fields{"prefix": "bridge"}) -} - -func New(cfg *config.Config, bridge *config.Bridge, c chan config.Message) *Bridge { +func New(bridge *config.Bridge) *Bridge {   b := new(Bridge)   b.Channels = make(map[string]config.ChannelInfo)   accInfo := strings.Split(bridge.Account, ".") @@ -5249 +386 @@ func New(cfg *config.Config, bridge *config.Bridge, c chan config.Message) *Brid   b.Protocol = protocol   b.Account = bridge.Account   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  }   @@ -1067 +497 @@ func (b *Bridge) JoinChannels() error {  func (b *Bridge) joinChannels(channels map[string]config.ChannelInfo, exists map[string]bool) error {   for ID, channel := range channels {   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)   if err != nil {   return err diff --git a/bridge/config/config.go b/bridge/config/config.go index 72ac4bb..2a596cc 100644 --- a/bridge/config/config.go +++ b/bridge/config/config.go @@ -27 +27 @@ package config    import (   "github.com/BurntSushi/toml" - "log" + log "github.com/sirupsen/logrus"   "os"   "reflect"   "strings" @@ -1437 +1437 @@ type SameChannelGateway struct {    type Config struct {   Api map[string]Protocol - IRC map[string]Protocol + Irc map[string]Protocol   Mattermost map[string]Protocol   Matrix map[string]Protocol   Slack map[string]Protocol @@ -1646 +1647 @@ type BridgeConfig struct {   General *Protocol   Account string   Remote chan Message + Log *log.Entry  }    func NewConfig(cfgfile string) *Config { diff --git a/bridge/discord/discord.go b/bridge/discord/discord.go index 7e5a01d..3c4d540 100644 --- a/bridge/discord/discord.go +++ b/bridge/discord/discord.go @@ -310 +310 @@ package bdiscord  import (   "bytes"   "fmt" + "github.com/42wim/matterbridge/bridge"   "github.com/42wim/matterbridge/bridge/config"   "github.com/42wim/matterbridge/bridge/helper"   "github.com/bwmarrin/discordgo" - log "github.com/sirupsen/logrus"   "regexp"   "strings"   "sync" @@ -2619 +2612 @@ type Bdiscord struct {   *config.BridgeConfig  }   -var flog *log.Entry -var protocol = "discord" - -func init() { - flog = log.WithFields(log.Fields{"prefix": protocol}) -} - -func New(cfg *config.BridgeConfig) *Bdiscord { +func New(cfg *config.BridgeConfig) bridge.Bridger {   b := &Bdiscord{BridgeConfig: cfg}   b.userMemberMap = make(map[string]*discordgo.Member)   b.channelInfoMap = make(map[string]*config.ChannelInfo)   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)   }   return b @@ -4611 +3911 @@ func New(cfg *config.BridgeConfig) *Bdiscord {    func (b *Bdiscord) Connect() error {   var err error - flog.Info("Connecting") + b.Log.Info("Connecting")   if b.Config.WebhookURL == "" { - flog.Info("Connecting using token") + b.Log.Info("Connecting using token")   } 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 ") {   b.Config.Token = "Bot " + b.Config.Token @@ -597 +527 @@ func (b *Bdiscord) Connect() error {   if err != nil {   return err   } - flog.Info("Connection succeeded") + b.Log.Info("Connection succeeded")   b.c.AddHandler(b.messageCreate)   b.c.AddHandler(b.memberUpdate)   b.c.AddHandler(b.messageUpdate) @@ -1037 +967 @@ func (b *Bdiscord) JoinChannel(channel config.ChannelInfo) 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)   if channelID == "" { @@ -1327 +1257 @@ func (b *Bdiscord) Send(msg config.Message) (string, error) {   if msg.Event != "" {   return "", nil   } - flog.Debugf("Broadcasting using Webhook") + b.Log.Debugf("Broadcasting using Webhook")   err := b.c.WebhookExecute(   wID,   wToken, @@ -1457 +1387 @@ func (b *Bdiscord) Send(msg config.Message) (string, error) {   return "", err   }   - flog.Debugf("Broadcasting using token (API)") + b.Log.Debugf("Broadcasting using token (API)")     // Delete message   if msg.Event == config.EVENT_MSG_DELETE { @@ -1878 +1808 @@ func (b *Bdiscord) messageDelete(s *discordgo.Session, m *discordgo.MessageDelet   if b.UseChannelID {   rmsg.Channel = "ID:" + m.ChannelID   } - flog.Debugf("Sending message from %s to gateway", b.Account) - flog.Debugf("Message is %#v", rmsg) + b.Log.Debugf("Sending message from %s to gateway", b.Account) + b.Log.Debugf("Message is %#v", rmsg)   b.Remote <- rmsg  }   @@ -1987 +1917 @@ func (b *Bdiscord) messageUpdate(s *discordgo.Session, m *discordgo.MessageUpdat   }   // only when message is actually edited   if m.Message.EditedTimestamp != "" { - flog.Debugf("Sending edit message") + b.Log.Debugf("Sending edit message")   m.Content = m.Content + b.Config.EditSuffix   b.messageCreate(s, (*discordgo.MessageCreate)(m))   } @@ -22612 +21912 @@ 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}     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.replaceChannelMentions(m.Message.Content)   rmsg.Text, err = m.ContentWithMoreMentionsReplaced(b.c)   if err != nil { - flog.Errorf("ContentWithMoreMentionsReplaced failed: %s", err) + b.Log.Errorf("ContentWithMoreMentionsReplaced failed: %s", err)   rmsg.Text = m.ContentWithMentionsReplaced()   }   } @@ -26815 +26115 @@ func (b *Bdiscord) messageCreate(s *discordgo.Session, m *discordgo.MessageCreat   rmsg.Event = config.EVENT_USER_ACTION   }   - flog.Debugf("Sending message from %s on %s to gateway", m.Author.Username, b.Account) - flog.Debugf("Message is %#v", rmsg) + b.Log.Debugf("Sending message from %s on %s to gateway", m.Author.Username, b.Account) + b.Log.Debugf("Message is %#v", rmsg)   b.Remote <- rmsg  }    func (b *Bdiscord) memberUpdate(s *discordgo.Session, m *discordgo.GuildMemberUpdate) {   b.Lock()   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.Unlock() @@ -3677 +3607 @@ func (b *Bdiscord) stripCustomoji(text string) string {  func (b *Bdiscord) splitURL(url string) (string, string) {   webhookURLSplit := strings.Split(url, "/")   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]  } diff --git a/bridge/gitter/gitter.go b/bridge/gitter/gitter.go index 69af8d2..0cd8e52 100644 --- a/bridge/gitter/gitter.go +++ b/bridge/gitter/gitter.go @@ -39 +39 @@ package bgitter  import (   "fmt"   "github.com/42wim/go-gitter" + "github.com/42wim/matterbridge/bridge"   "github.com/42wim/matterbridge/bridge/config"   "github.com/42wim/matterbridge/bridge/helper" - log "github.com/sirupsen/logrus"   "strings"  )   @@ -1720 +1713 @@ type Bgitter struct {   *config.BridgeConfig  }   -var flog *log.Entry -var protocol = "gitter" - -func init() { - flog = log.WithFields(log.Fields{"prefix": protocol}) -} - -func New(cfg *config.BridgeConfig) *Bgitter { +func New(cfg *config.BridgeConfig) bridge.Bridger {   return &Bgitter{BridgeConfig: cfg}  }    func (b *Bgitter) Connect() error {   var err error - flog.Info("Connecting") + b.Log.Info("Connecting")   b.c = gitter.New(b.Config.Token)   b.User, err = b.c.GetUser()   if err != nil { @@ -407 +337 @@ func (b *Bgitter) Connect() error {   if err != nil {   return err   } - flog.Info("Connection succeeded") + b.Log.Info("Connection succeeded")   return nil  }   @@ -787 +717 @@ func (b *Bgitter) JoinChannel(channel config.ChannelInfo) error {   case *gitter.MessageReceived:   // ignore message sent from ourselves   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,   Account: b.Account, Avatar: b.getAvatar(ev.Message.From.Username), UserID: ev.Message.From.ID,   ID: ev.Message.ID} @@ -8611 +7911 @@ func (b *Bgitter) JoinChannel(channel config.ChannelInfo) error {   rmsg.Event = config.EVENT_USER_ACTION   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   }   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) @@ -9810 +9110 @@ func (b *Bgitter) JoinChannel(channel config.ChannelInfo) 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)   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   }   @@ -1307 +1237 @@ func (b *Bgitter) Send(msg config.Message) (string, error) {     // Edit message   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)   if err != nil {   return "", err diff --git a/bridge/irc/irc.go b/bridge/irc/irc.go index fe51733..afe436b 100644 --- a/bridge/irc/irc.go +++ b/bridge/irc/irc.go @@ -413 +413 @@ import (   "bytes"   "crypto/tls"   "fmt" + "github.com/42wim/matterbridge/bridge"   "github.com/42wim/matterbridge/bridge/config"   "github.com/42wim/matterbridge/bridge/helper"   "github.com/lrstanley/girc"   "github.com/paulrosania/go-charset/charset"   _ "github.com/paulrosania/go-charset/data"   "github.com/saintfish/chardet" - log "github.com/sirupsen/logrus"   "io"   "io/ioutil"   "net" @@ -3314 +337 @@ type Birc struct {   *config.BridgeConfig  }   -var flog *log.Entry -var protocol = "irc" - -func init() { - flog = log.WithFields(log.Fields{"prefix": protocol}) -} - -func New(cfg *config.BridgeConfig) *Birc { +func New(cfg *config.BridgeConfig) bridge.Bridger {   b := &Birc{}   b.BridgeConfig = cfg   b.Nick = b.Config.Nick @@ -717 +647 @@ func (b *Birc) Command(msg *config.Message) string {    func (b *Birc) Connect() error {   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)   if err != nil {   return err @@ -1128 +1058 @@ func (b *Birc) Connect() error {   go func() {   for {   if err := i.Connect(); err != nil { - flog.Errorf("error: %s", err) - flog.Info("reconnecting in 30 seconds...") + b.Log.Errorf("error: %s", err) + b.Log.Info("reconnecting in 30 seconds...")   time.Sleep(30 * time.Second)   i.Handlers.Clear(girc.RPL_WELCOME)   i.Handlers.Add(girc.RPL_WELCOME, func(client *girc.Client, event girc.Event) { @@ -1297 +1227 @@ func (b *Birc) Connect() error {   b.i = i   select {   case <-b.connected: - flog.Info("Connection succeeded") + b.Log.Info("Connection succeeded")   case <-time.After(time.Second * 30):   return fmt.Errorf("connection timed out")   } @@ -1497 +1427 @@ func (b *Birc) Disconnect() error {    func (b *Birc) JoinChannel(channel config.ChannelInfo) error {   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)   } else {   b.i.Cmd.Join(channel.Name) @@ -1637 +1567 @@ func (b *Birc) Send(msg config.Message) (string, error) {   return "", nil   }   - flog.Debugf("Receiving %#v", msg) + b.Log.Debugf("Receiving %#v", msg)     // Execute a command   if strings.HasPrefix(msg.Text, "!") { @@ -1757 +1687 @@ func (b *Birc) Send(msg config.Message) (string, error) {   buf := new(bytes.Buffer)   w, err := charset.NewWriter(b.Config.Charset, buf)   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   }   fmt.Fprintf(w, msg.Text) @@ -2217 +2147 @@ func (b *Birc) Send(msg config.Message) (string, error) {   }   b.Local <- config.Message{Text: text, Username: msg.Username, Channel: msg.Channel, Event: msg.Event}   } 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 @@ -2597 +2527 @@ func (b *Birc) endNames(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   b.Nick = event.Params[0]   @@ -27831 +27131 @@ func (b *Birc) handleNewConnection(client *girc.Client, event girc.Event) {    func (b *Birc) handleJoinPart(client *girc.Client, event girc.Event) {   if len(event.Params) == 0 { - flog.Debugf("handleJoinPart: empty Params? %#v", event) + b.Log.Debugf("handleJoinPart: empty Params? %#v", event)   return   }   channel := strings.ToLower(event.Params[0])   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)   b.Remote <- config.Message{Username: "system", Text: "rejoin", Channel: channel, Account: b.Account, Event: config.EVENT_REJOIN_CHANNELS}   return   }   if event.Command == "QUIT" {   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}   return   }   }   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} - flog.Debugf("Message is %#v", msg) + b.Log.Debugf("Message is %#v", msg)   b.Remote <- msg   return   } - flog.Debugf("handle %#v", event) + b.Log.Debugf("handle %#v", event)  }    func (b *Birc) handleNotice(client *girc.Client, event girc.Event) { @@ -3177 +3107 @@ func (b *Birc) handleOther(client *girc.Client, event girc.Event) {   if b.Config.DebugLevel == 1 {   if event.Command != "CLIENT_STATE_UPDATED" &&   event.Command != "CLIENT_GENERAL_UPDATED" { - flog.Debugf("%#v", event.String()) + b.Log.Debugf("%#v", event.String())   }   return   } @@ -32512 +31812 @@ 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":   return   } - flog.Debugf("%#v", event.String()) + b.Log.Debugf("%#v", event.String())  }    func (b *Birc) handleOtherAuth(client *girc.Client, event girc.Event) {   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)   }  } @@ -3597 +3527 @@ func (b *Birc) handlePrivMsg(client *girc.Client, event girc.Event) {   return   }   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   if event.IsAction() { @@ -38210 +37510 @@ func (b *Birc) handlePrivMsg(client *girc.Client, event girc.Event) {   detector := chardet.NewTextDetector()   result, err := detector.DetectBest([]byte(rmsg.Text))   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   } - flog.Debugf("detected %s confidence %#v", result.Charset, result.Confidence) + b.Log.Debugf("detected %s confidence %#v", result.Charset, result.Confidence)   mycharset = result.Charset   // if we're not sure, just pick ISO-8859-1   if result.Confidence < 80 { @@ -39413 +38713 @@ func (b *Birc) handlePrivMsg(client *girc.Client, event girc.Event) {   }   r, err = charset.NewReader(mycharset, strings.NewReader(rmsg.Text))   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   }   output, _ := ioutil.ReadAll(r)   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  }   @@ -40813 +40113 @@ func (b *Birc) handleTopicWhoTime(client *girc.Client, event girc.Event) {   parts := strings.Split(event.Params[2], "!")   t, err := strconv.ParseInt(event.Params[3], 10, 64)   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]   if len(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 { diff --git a/bridge/matrix/matrix.go b/bridge/matrix/matrix.go index 6e1f0cc..e7f7159 100644 --- a/bridge/matrix/matrix.go +++ b/bridge/matrix/matrix.go @@ -310 +310 @@ package bmatrix  import (   "bytes"   "fmt" + "github.com/42wim/matterbridge/bridge"   "github.com/42wim/matterbridge/bridge/config"   "github.com/42wim/matterbridge/bridge/helper"   matrix "github.com/matterbridge/gomatrix" - log "github.com/sirupsen/logrus"   "mime"   "regexp"   "strings" @@ -2114 +217 @@ type Bmatrix struct {   *config.BridgeConfig  }   -var flog *log.Entry -var protocol = "matrix" - -func init() { - flog = log.WithFields(log.Fields{"prefix": protocol}) -} - -func New(cfg *config.BridgeConfig) *Bmatrix { +func New(cfg *config.BridgeConfig) bridge.Bridger {   b := &Bmatrix{BridgeConfig: cfg}   b.RoomMap = make(map[string]string)   return b @@ -367 +297 @@ func New(cfg *config.BridgeConfig) *Bmatrix {    func (b *Bmatrix) Connect() 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, "", "")   if err != nil {   return err @@ -517 +447 @@ func (b *Bmatrix) Connect() error {   }   b.mc.SetCredentials(resp.UserID, resp.AccessToken)   b.UserID = resp.UserID - flog.Info("Connection succeeded") + b.Log.Info("Connection succeeded")   go b.handlematrix()   return nil  } @@ -7210 +6510 @@ func (b *Bmatrix) JoinChannel(channel config.ChannelInfo) 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) - 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   if msg.Event == config.EVENT_USER_ACTION { @@ -1397 +1327 @@ func (b *Bmatrix) handlematrix() error {   go func() {   for {   if err := b.mc.Sync(); err != nil { - flog.Println("Sync() returned ", err) + b.Log.Println("Sync() returned ", err)   }   }   }() @@ -14713 +14013 @@ func (b *Bmatrix) handlematrix() error {  }    func (b *Bmatrix) handleEvent(ev *matrix.Event) { - flog.Debugf("Received: %#v", ev) + b.Log.Debugf("Received: %#v", ev)   if ev.Sender != b.UserID {   b.RLock()   channel, ok := b.RoomMap[ev.RoomID]   b.RUnlock()   if !ok { - flog.Debugf("Unknown room %s", ev.RoomID) + b.Log.Debugf("Unknown room %s", ev.RoomID)   return   }   @@ -1647 +1577 @@ func (b *Bmatrix) handleEvent(ev *matrix.Event) {     // Text must be a string   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   }   @@ -19211 +18511 @@ func (b *Bmatrix) handleEvent(ev *matrix.Event) {   if b.containsAttachment(ev.Content) {   err := b.handleDownloadFile(&rmsg, ev.Content)   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   }  } @@ -2467 +2397 @@ func (b *Bmatrix) handleDownloadFile(rmsg *config.Message, content map[string]in   }     // 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 {   return err   } @@ -2567 +2497 @@ func (b *Bmatrix) handleDownloadFile(rmsg *config.Message, content map[string]in   return fmt.Errorf("download %s failed %#v", url, err)   }   // 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  }   @@ -27230 +26530 @@ func (b *Bmatrix) handleUploadFile(msg *config.Message, channel string) (string,   if fi.Comment != "" {   _, err := b.mc.SendText(channel, msg.Username+fi.Comment)   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)))   if err != nil { - flog.Errorf("file upload failed: %#v", err) + b.Log.Errorf("file upload failed: %#v", err)   continue   }   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)   if err != nil { - flog.Errorf("sendVideo failed: %#v", err) + b.Log.Errorf("sendVideo failed: %#v", err)   }   }   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)   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 diff --git a/bridge/mattermost/mattermost.go b/bridge/mattermost/mattermost.go index e333580..af52270 100644 --- a/bridge/mattermost/mattermost.go +++ b/bridge/mattermost/mattermost.go @@ -311 +311 @@ package bmattermost  import (   "errors"   "fmt" + "github.com/42wim/matterbridge/bridge"   "github.com/42wim/matterbridge/bridge/config"   "github.com/42wim/matterbridge/bridge/helper"   "github.com/42wim/matterbridge/matterclient"   "github.com/42wim/matterbridge/matterhook" - log "github.com/sirupsen/logrus"   "strings"  )   @@ -1914 +197 @@ type Bmattermost struct {   avatarMap map[string]string  }   -var flog *log.Entry -var protocol = "mattermost" - -func init() { - flog = log.WithFields(log.Fields{"prefix": protocol}) -} - -func New(cfg *config.BridgeConfig) *Bmattermost { +func New(cfg *config.BridgeConfig) bridge.Bridger {   b := &Bmattermost{BridgeConfig: cfg, avatarMap: make(map[string]string)}   return b  } @@ -3824 +3124 @@ func (b *Bmattermost) Command(cmd string) string {  func (b *Bmattermost) Connect() error {   if b.Config.WebhookBindAddress != "" {   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,   matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,   BindAddress: b.Config.WebhookBindAddress})   } else if b.Config.Token != "" { - flog.Info("Connecting using token (sending)") + b.Log.Info("Connecting using token (sending)")   err := b.apiLogin()   if err != nil {   return err   }   } else if b.Config.Login != "" { - flog.Info("Connecting using login/password (sending)") + b.Log.Info("Connecting using login/password (sending)")   err := b.apiLogin()   if err != nil {   return err   }   } else { - flog.Info("Connecting using webhookbindaddress (receiving)") + b.Log.Info("Connecting using webhookbindaddress (receiving)")   b.mh = matterhook.New(b.Config.WebhookURL,   matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,   BindAddress: b.Config.WebhookBindAddress}) @@ -6419 +5719 @@ func (b *Bmattermost) Connect() error {   return nil   }   if b.Config.WebhookURL != "" { - flog.Info("Connecting using webhookurl (sending)") + b.Log.Info("Connecting using webhookurl (sending)")   b.mh = matterhook.New(b.Config.WebhookURL,   matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,   DisableServer: true})   if b.Config.Token != "" { - flog.Info("Connecting using token (receiving)") + b.Log.Info("Connecting using token (receiving)")   err := b.apiLogin()   if err != nil {   return err   }   go b.handleMatter()   } else if b.Config.Login != "" { - flog.Info("Connecting using login/password (receiving)") + b.Log.Info("Connecting using login/password (receiving)")   err := b.apiLogin()   if err != nil {   return err @@ -8514 +7814 @@ func (b *Bmattermost) Connect() error {   }   return nil   } 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()   if err != nil {   return err   }   go b.handleMatter()   } 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()   if err != nil {   return err @@ -1227 +1157 @@ func (b *Bmattermost) JoinChannel(channel config.ChannelInfo) 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   if msg.Event == config.EVENT_USER_ACTION { @@ -17413 +16713 @@ func (b *Bmattermost) Send(msg config.Message) (string, error) {  func (b *Bmattermost) handleMatter() {   messages := make(chan *config.Message)   if b.Config.WebhookBindAddress != "" { - flog.Debugf("Choosing webhooks based receiving") + b.Log.Debugf("Choosing webhooks based receiving")   go b.handleMatterHook(messages)   } else {   if b.Config.Token != "" { - flog.Debugf("Choosing token based receiving") + b.Log.Debugf("Choosing token based receiving")   } else { - flog.Debugf("Choosing login/password based receiving") + b.Log.Debugf("Choosing login/password based receiving")   }   go b.handleMatterClient(messages)   } @@ -19218 +18518 @@ func (b *Bmattermost) handleMatter() {   if ok {   message.Event = config.EVENT_USER_ACTION   } - flog.Debugf("Sending message from %s on %s to gateway", message.Username, b.Account) - flog.Debugf("Message is %#v", message) + b.Log.Debugf("Sending message from %s on %s to gateway", message.Username, b.Account) + b.Log.Debugf("Message is %#v", message)   b.Remote <- *message   }  }    func (b *Bmattermost) handleMatterClient(messages chan *config.Message) {   for message := range b.mc.MessageChan { - flog.Debugf("%#v", message.Raw.Data) + b.Log.Debugf("%#v", message.Raw.Data)     if b.skipMessage(message) { - flog.Debugf("Skipped message: %#v", message) + b.Log.Debugf("Skipped message: %#v", message)   continue   }   @@ -2127 +2057 @@ func (b *Bmattermost) handleMatterClient(messages chan *config.Message) {   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{})}   @@ -2407 +2337 @@ func (b *Bmattermost) handleMatterClient(messages chan *config.Message) {   for _, id := range message.Post.FileIds {   err := b.handleDownloadFile(rmsg, id)   if err != nil { - flog.Errorf("download failed: %s", err) + b.Log.Errorf("download failed: %s", err)   }   }   } @@ -2517 +2447 @@ func (b *Bmattermost) handleMatterClient(messages chan *config.Message) {  func (b *Bmattermost) handleMatterHook(messages chan *config.Message) {   for {   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}   }  } @@ -26812 +26112 @@ func (b *Bmattermost) apiLogin() error {   }   b.mc.SkipTLSVerify = b.Config.SkipTLSVerify   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()   if err != nil {   return err   } - flog.Info("Connection succeeded") + b.Log.Info("Connection succeeded")   b.TeamID = b.mc.GetTeamId()   go b.mc.WsReceiver()   go b.mc.StatusLoop() @@ -2937 +2867 @@ func (b *Bmattermost) cacheAvatar(msg *config.Message) (string, error) {   /* if we have a sha we have successfully uploaded the file to the media server,   so we can now cache the 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   }   return "", nil @@ -30715 +30015 @@ func (b *Bmattermost) handleDownloadAvatar(userid string, channel string) {   if _, ok := b.avatarMap[userid]; !ok {   data, resp := b.mc.Client.GetProfileImage(userid, "")   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   } - 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 { - flog.Error(err) + b.Log.Error(err)   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   }  } @@ -3277 +3207 @@ func (b *Bmattermost) handleDownloadFile(rmsg *config.Message, id string) error   if resp.Error != nil {   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 {   return err   } @@ -3357 +3287 @@ func (b *Bmattermost) handleDownloadFile(rmsg *config.Message, id string) error   if resp.Error != nil {   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  }   @@ -3957 +3887 @@ func (b *Bmattermost) sendWebhook(msg config.Message) (string, error) {   matterMessage.Props["matterbridge"] = true   err := b.mh.Send(matterMessage)   if err != nil { - flog.Info(err) + b.Log.Info(err)   return "", err   }   return "", nil @@ -4077 +4007 @@ func (b *Bmattermost) skipMessage(message *matterclient.Message) bool {   if message.Type == "system_join_leave" ||   message.Type == "system_join_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}   return true   } @@ -4207 +4137 @@ func (b *Bmattermost) skipMessage(message *matterclient.Message) bool {   // Ignore messages sent from matterbridge   if message.Post.Props != nil {   if _, ok := message.Post.Props["matterbridge"].(bool); ok { - flog.Debugf("sent by matterbridge, ignoring") + b.Log.Debugf("sent by matterbridge, ignoring")   return true   }   } diff --git a/bridge/rocketchat/rocketchat.go b/bridge/rocketchat/rocketchat.go index dec02e5..8f025d2 100644 --- a/bridge/rocketchat/rocketchat.go +++ b/bridge/rocketchat/rocketchat.go @@ -111 +111 @@  package brocketchat    import ( + "github.com/42wim/matterbridge/bridge"   "github.com/42wim/matterbridge/bridge/config"   "github.com/42wim/matterbridge/bridge/helper"   "github.com/42wim/matterbridge/hook/rockethook"   "github.com/42wim/matterbridge/matterhook" - log "github.com/sirupsen/logrus"  )    type MMhook struct { @@ -1814 +187 @@ type Brocketchat struct {   *config.BridgeConfig  }   -var flog *log.Entry -var protocol = "rocketchat" - -func init() { - flog = log.WithFields(log.Fields{"prefix": protocol}) -} - -func New(cfg *config.BridgeConfig) *Brocketchat { +func New(cfg *config.BridgeConfig) bridge.Bridger {   return &Brocketchat{BridgeConfig: cfg}  }   @@ -347 +277 @@ func (b *Brocketchat) Command(cmd string) string {  }    func (b *Brocketchat) Connect() error { - flog.Info("Connecting webhooks") + b.Log.Info("Connecting webhooks")   b.mh = matterhook.New(b.Config.WebhookURL,   matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,   DisableServer: true}) @@ -577 +507 @@ func (b *Brocketchat) Send(msg config.Message) (string, error) {   if msg.Event == config.EVENT_MSG_DELETE {   return "", nil   } - flog.Debugf("Receiving %#v", msg) + b.Log.Debugf("Receiving %#v", msg)   if msg.Extra != nil {   for _, rmsg := range helper.HandleExtra(&msg, b.General) {   matterMessage := matterhook.OMessage{IconURL: b.Config.IconURL, Channel: rmsg.Channel, UserName: rmsg.Username, @@ -817 +747 @@ func (b *Brocketchat) Send(msg config.Message) (string, error) {   matterMessage.Text = msg.Text   err := b.mh.Send(matterMessage)   if err != nil { - flog.Info(err) + b.Log.Info(err)   return "", err   }   return "", nil @@ -9012 +8312 @@ func (b *Brocketchat) Send(msg config.Message) (string, error) {  func (b *Brocketchat) handleRocketHook() {   for {   message := b.rh.Receive() - flog.Debugf("Receiving from rockethook %#v", message) + b.Log.Debugf("Receiving from rockethook %#v", message)   // do not loop   if message.UserName == b.Config.Nick {   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}   }  } diff --git a/bridge/slack/slack.go b/bridge/slack/slack.go index bf2e93c..7f50640 100644 --- a/bridge/slack/slack.go +++ b/bridge/slack/slack.go @@ -411 +411 @@ import (   "bytes"   "errors"   "fmt" + "github.com/42wim/matterbridge/bridge"   "github.com/42wim/matterbridge/bridge/config"   "github.com/42wim/matterbridge/bridge/helper"   "github.com/42wim/matterbridge/matterhook"   "github.com/nlopes/slack" - log "github.com/sirupsen/logrus"   "html"   "regexp"   "strings" @@ -2516 +259 @@ type Bslack struct {   *config.BridgeConfig  }   -var flog *log.Entry -var protocol = "slack" +const messageDeleted = "message_deleted"   -const messageDeleted = "messsage_deleted" - -func init() { - flog = log.WithFields(log.Fields{"prefix": protocol}) -} - -func New(cfg *config.BridgeConfig) *Bslack { +func New(cfg *config.BridgeConfig) bridge.Bridger {   return &Bslack{BridgeConfig: cfg}  }   @@ -4521 +3821 @@ func (b *Bslack) Command(cmd string) string {  func (b *Bslack) Connect() error {   if b.Config.WebhookBindAddress != "" {   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,   matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,   BindAddress: b.Config.WebhookBindAddress})   } 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.rtm = b.sc.NewRTM()   go b.rtm.ManageConnection() - flog.Info("Connecting using webhookbindaddress (receiving)") + b.Log.Info("Connecting using webhookbindaddress (receiving)")   b.mh = matterhook.New(b.Config.WebhookURL,   matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,   BindAddress: b.Config.WebhookBindAddress})   } else { - flog.Info("Connecting using webhookbindaddress (receiving)") + b.Log.Info("Connecting using webhookbindaddress (receiving)")   b.mh = matterhook.New(b.Config.WebhookURL,   matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,   BindAddress: b.Config.WebhookBindAddress}) @@ -6819 +6119 @@ func (b *Bslack) Connect() error {   return nil   }   if b.Config.WebhookURL != "" { - flog.Info("Connecting using webhookurl (sending)") + b.Log.Info("Connecting using webhookurl (sending)")   b.mh = matterhook.New(b.Config.WebhookURL,   matterhook.Config{InsecureSkipVerify: b.Config.SkipTLSVerify,   DisableServer: true})   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.rtm = b.sc.NewRTM()   go b.rtm.ManageConnection()   go b.handleSlack()   }   } 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.rtm = b.sc.NewRTM()   go b.rtm.ManageConnection() @@ -1157 +1087 @@ func (b *Bslack) JoinChannel(channel config.ChannelInfo) 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   if msg.Event == config.EVENT_USER_ACTION { @@ -1976 +1907 @@ func (b *Bslack) Send(msg config.Message) (string, error) {   }     // Post normal message + b.Log.Debugf("NP IS %#v", np)   _, id, err := b.sc.PostMessage(schannel.ID, msg.Text, np)   if err != nil {   return "", err @@ -24316 +23716 @@ func (b *Bslack) getChannelByID(ID string) (*slack.Channel, error) {  func (b *Bslack) handleSlack() {   messages := make(chan *config.Message)   if b.Config.WebhookBindAddress != "" { - flog.Debugf("Choosing webhooks based receiving") + b.Log.Debugf("Choosing webhooks based receiving")   go b.handleMatterHook(messages)   } else { - flog.Debugf("Choosing token based receiving") + b.Log.Debugf("Choosing token based receiving")   go b.handleSlackClient(messages)   }   time.Sleep(time.Second) - flog.Debug("Start listening for Slack messages") + b.Log.Debug("Start listening for Slack 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   message.Text = b.replaceURL(message.Text) @@ -2647 +2587 @@ func (b *Bslack) handleSlack() {   // Add the avatar   message.Avatar = b.getAvatar(message.Username)   - flog.Debugf("Message is %#v", message) + b.Log.Debugf("Message is %#v", message)   b.Remote <- *message   }  } @@ -27222 +26622 @@ func (b *Bslack) handleSlack() {  func (b *Bslack) handleSlackClient(messages chan *config.Message) {   for msg := range b.rtm.IncomingEvents {   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) {   case *slack.MessageEvent:   if b.skipMessageEvent(ev) { - flog.Debugf("Skipped message: %#v", ev) + b.Log.Debugf("Skipped message: %#v", ev)   continue   }   rmsg, err := b.handleMessageEvent(ev)   if err != nil { - flog.Errorf("%#v", err) + b.Log.Errorf("%#v", err)   continue   }   messages <- rmsg   case *slack.OutgoingErrorEvent: - flog.Debugf("%#v", ev.Error()) + b.Log.Debugf("%#v", ev.Error())   case *slack.ChannelJoinedEvent:   b.Users, _ = b.sc.GetUsers()   case *slack.ConnectedEvent: @@ -3039 +2979 @@ func (b *Bslack) handleSlackClient(messages chan *config.Message) {   b.channels = append(b.channels, *channel)   }   case *slack.InvalidAuthEvent: - flog.Fatalf("Invalid Token %#v", ev) + b.Log.Fatalf("Invalid Token %#v", ev)   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:   }   } @@ -3147 +3087 @@ func (b *Bslack) handleSlackClient(messages chan *config.Message) {  func (b *Bslack) handleMatterHook(messages chan *config.Message) {   for {   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" {   continue   } @@ -4037 +3977 @@ func (b *Bslack) handleDownloadFile(rmsg *config.Message, file *slack.File) erro   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 {   return err   } @@ -4137 +4077 @@ func (b *Bslack) handleDownloadFile(rmsg *config.Message, file *slack.File) erro   return fmt.Errorf("download %s failed %#v", file.URLPrivateDownload, err)   }   // 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  }   @@ -4297 +4237 @@ func (b *Bslack) handleUploadFile(msg *config.Message, channelID string) (string   InitialComment: fi.Comment,   })   if err != nil { - flog.Errorf("uploadfile %#v", err) + b.Log.Errorf("uploadfile %#v", err)   }   }   return "", nil @@ -4447 +4387 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er     // Edit message   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.Text = ev.SubMessage.Text + b.Config.EditSuffix   } @@ -5437 +5377 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er   if ev.File != nil {   err := b.handleDownloadFile(&rmsg, ev.File)   if err != nil { - flog.Errorf("download failed: %s", err) + b.Log.Errorf("download failed: %s", err)   }   }   @@ -5937 +5877 @@ func (b *Bslack) sendWebhook(msg config.Message) (string, error) {   }   err := b.mh.Send(matterMessage)   if err != nil { - flog.Error(err) + b.Log.Error(err)   return "", err   }   return "", nil diff --git a/bridge/sshchat/sshchat.go b/bridge/sshchat/sshchat.go index cce4da5..ab6b06c 100644 --- a/bridge/sshchat/sshchat.go +++ b/bridge/sshchat/sshchat.go @@ -210 +211 @@ package bsshchat    import (   "bufio" + "github.com/42wim/matterbridge/bridge"   "github.com/42wim/matterbridge/bridge/config"   "github.com/42wim/matterbridge/bridge/helper" - log "github.com/sirupsen/logrus"   "github.com/shazow/ssh-chat/sshd" + log "github.com/sirupsen/logrus"   "io"   "strings"  ) @@ -1620 +1713 @@ type Bsshchat struct {   *config.BridgeConfig  }   -var flog *log.Entry -var protocol = "sshchat" - -func init() { - flog = log.WithFields(log.Fields{"prefix": protocol}) -} - -func New(cfg *config.BridgeConfig) *Bsshchat { +func New(cfg *config.BridgeConfig) bridge.Bridger {   return &Bsshchat{BridgeConfig: cfg}  }    func (b *Bsshchat) Connect() error {   var err error - flog.Infof("Connecting %s", b.Config.Server) + b.Log.Infof("Connecting %s", b.Config.Server)   go func() {   err = sshd.ConnectShell(b.Config.Server, b.Config.Nick, func(r io.Reader, w io.WriteCloser) error {   b.r = bufio.NewScanner(r) @@ -4110 +3510 @@ func (b *Bsshchat) Connect() error {   })   }()   if err != nil { - flog.Debugf("%#v", err) + b.Log.Debugf("%#v", err)   return err   } - flog.Info("Connection succeeded") + b.Log.Info("Connection succeeded")   return nil  }   @@ -617 +557 @@ func (b *Bsshchat) Send(msg config.Message) (string, error) {   if msg.Event == config.EVENT_MSG_DELETE {   return "", nil   } - flog.Debugf("Receiving %#v", msg) + b.Log.Debugf("Receiving %#v", msg)   if msg.Extra != nil {   for _, rmsg := range helper.HandleExtra(&msg, b.General) {   b.w.Write([]byte(rmsg.Username + rmsg.Text + "\r\n")) @@ -9310 +8710 @@ func (b *Bsshchat) sshchatKeepAlive() chan bool {   for {   select {   case <-ticker.C: - flog.Debugf("PING") + b.Log.Debugf("PING")   err := b.xc.PingC2S("", "")   if err != nil { - flog.Debugf("PING failed %#v", err) + b.Log.Debugf("PING failed %#v", err)   }   case <-done:   return @@ -1307 +1247 @@ func (b *Bsshchat) handleSshChat() error {   continue   }   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"}   b.Remote <- rmsg   } diff --git a/bridge/steam/steam.go b/bridge/steam/steam.go index b630c42..0a3a03e 100644 --- a/bridge/steam/steam.go +++ b/bridge/steam/steam.go @@ -211 +211 @@ package bsteam    import (   "fmt" + "github.com/42wim/matterbridge/bridge"   "github.com/42wim/matterbridge/bridge/config"   "github.com/Philipp15b/go-steam"   "github.com/Philipp15b/go-steam/protocol/steamlang"   "github.com/Philipp15b/go-steam/steamid" - log "github.com/sirupsen/logrus"   //"io/ioutil"   "strconv"   "sync" @@ -2114 +217 @@ type Bsteam struct {   *config.BridgeConfig  }   -var flog *log.Entry -var protocol = "steam" - -func init() { - flog = log.WithFields(log.Fields{"prefix": protocol}) -} - -func New(cfg *config.BridgeConfig) *Bsteam { +func New(cfg *config.BridgeConfig) bridge.Bridger {   b := &Bsteam{BridgeConfig: cfg}   b.userMap = make(map[steamid.SteamId]string)   b.connected = make(chan struct{}) @@ -3613 +2913 @@ func New(cfg *config.BridgeConfig) *Bsteam {  }    func (b *Bsteam) Connect() error { - flog.Info("Connecting") + b.Log.Info("Connecting")   b.c = steam.NewClient()   go b.handleEvents()   go b.c.Connect()   select {   case <-b.connected: - flog.Info("Connection succeeded") + b.Log.Info("Connection succeeded")   case <-time.After(time.Second * 30):   return fmt.Errorf("connection timed out")   } @@ -9511 +8811 @@ func (b *Bsteam) handleEvents() {   // Maybe works   //myLoginInfo.SentryFileHash, _ = ioutil.ReadFile("sentry")   for event := range b.c.Events() { - //flog.Info(event) + //b.Log.Info(event)   switch e := event.(type) {   case *steam.ChatMsgEvent: - flog.Debugf("Receiving ChatMsgEvent: %#v", e) - flog.Debugf("Sending message from %s on %s to gateway", b.getNick(e.ChatterId), b.Account) + b.Log.Debugf("Receiving ChatMsgEvent: %#v", e) + b.Log.Debugf("Sending message from %s on %s to gateway", b.getNick(e.ChatterId), b.Account)   var channel int64   if e.ChatRoomId == 0 {   channel = int64(e.ChatterId) @@ -1107 +1037 @@ 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)}   b.Remote <- msg   case *steam.PersonaStateEvent: - flog.Debugf("PersonaStateEvent: %#v\n", e) + b.Log.Debugf("PersonaStateEvent: %#v\n", e)   b.Lock()   b.userMap[e.FriendId] = e.Name   b.Unlock() @@ -11847 +11147 @@ func (b *Bsteam) handleEvents() {   b.c.Auth.LogOn(myLoginInfo)   case *steam.MachineAuthUpdateEvent:   /* - flog.Info("authupdate", e) - flog.Info("hash", e.Hash) + b.Log.Info("authupdate", e) + b.Log.Info("hash", e.Hash)   ioutil.WriteFile("sentry", e.Hash, 0666)   */   case *steam.LogOnFailedEvent: - flog.Info("Logon failed", e) + b.Log.Info("Logon failed", e)   switch e.Result {   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   fmt.Scanf("%s", &code)   myLoginInfo.TwoFactorCode = code   }   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   fmt.Scanf("%s", &code)   myLoginInfo.AuthCode = code   }   default: - log.Errorf("LogOnFailedEvent: %#v ", e.Result) + b.Log.Errorf("LogOnFailedEvent: %#v ", e.Result)   // TODO: Handle EResult_InvalidLoginAuthCode   return   }   case *steam.LoggedOnEvent: - flog.Debugf("LoggedOnEvent: %#v", e) + b.Log.Debugf("LoggedOnEvent: %#v", e)   b.connected <- struct{}{} - flog.Debugf("setting online") + b.Log.Debugf("setting online")   b.c.Social.SetPersonaState(steamlang.EPersonaState_Online)   case *steam.DisconnectedEvent: - flog.Info("Disconnected") - flog.Info("Attempting to reconnect...") + b.Log.Info("Disconnected") + b.Log.Info("Attempting to reconnect...")   b.c.Connect()   case steam.FatalErrorEvent: - flog.Error(e) + b.Log.Error(e)   case error: - flog.Error(e) + b.Log.Error(e)   default: - flog.Debugf("unknown event %#v", e) + b.Log.Debugf("unknown event %#v", e)   }   }  } diff --git a/bridge/telegram/telegram.go b/bridge/telegram/telegram.go index 49dab1a..b407e0c 100644 --- a/bridge/telegram/telegram.go +++ b/bridge/telegram/telegram.go @@ -510 +510 @@ import (   "strconv"   "strings"   + "github.com/42wim/matterbridge/bridge"   "github.com/42wim/matterbridge/bridge/config"   "github.com/42wim/matterbridge/bridge/helper"   "github.com/go-telegram-bot-api/telegram-bot-api" - log "github.com/sirupsen/logrus"  )    type Btelegram struct { @@ -1733 +1726 @@ type Btelegram struct {   avatarMap map[string]string // keep cache of userid and avatar sha  }   -var flog *log.Entry -var protocol = "telegram" - -func init() { - flog = log.WithFields(log.Fields{"prefix": protocol}) -} - -func New(cfg *config.BridgeConfig) *Btelegram { +func New(cfg *config.BridgeConfig) bridge.Bridger {   return &Btelegram{BridgeConfig: cfg, avatarMap: make(map[string]string)}  }    func (b *Btelegram) Connect() error {   var err error - flog.Info("Connecting") + b.Log.Info("Connecting")   b.c, err = tgbotapi.NewBotAPI(b.Config.Token)   if err != nil { - flog.Debugf("%#v", err) + b.Log.Debugf("%#v", err)   return err   }   u := tgbotapi.NewUpdate(0)   u.Timeout = 60   updates, err := b.c.GetUpdatesChan(u)   if err != nil { - flog.Debugf("%#v", err) + b.Log.Debugf("%#v", err)   return err   } - flog.Info("Connection succeeded") + b.Log.Info("Connection succeeded")   go b.handleRecv(updates)   return nil  } @@ -577 +507 @@ func (b *Btelegram) JoinChannel(channel config.ChannelInfo) error {  }    func (b *Btelegram) Send(msg config.Message) (string, error) { - flog.Debugf("Receiving %#v", msg) + b.Log.Debugf("Receiving %#v", msg)     // get the chatid   chatid, err := strconv.ParseInt(msg.Channel, 10, 64) @@ -10611 +9911 @@ func (b *Btelegram) Send(msg config.Message) (string, error) {   }   m := tgbotapi.NewEditMessageText(chatid, msgid, msg.Username+msg.Text)   if b.Config.MessageFormat == "HTML" { - flog.Debug("Using mode HTML") + b.Log.Debug("Using mode HTML")   m.ParseMode = tgbotapi.ModeHTML   }   if b.Config.MessageFormat == "Markdown" { - flog.Debug("Using mode markdown") + b.Log.Debug("Using mode markdown")   m.ParseMode = tgbotapi.ModeMarkdown   }   _, err = b.c.Send(m) @@ -12610 +11910 @@ func (b *Btelegram) Send(msg config.Message) (string, error) {    func (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {   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 { - flog.Error("Getting nil messages, this shouldn't happen.") + b.Log.Error("Getting nil messages, this shouldn't happen.")   continue   }   @@ -1897 +1827 @@ func (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {   // handle any downloads   err := b.handleDownload(message, &rmsg)   if err != nil { - flog.Errorf("download failed: %s", err) + b.Log.Errorf("download failed: %s", err)   }     // handle forwarded messages @@ -2338 +2268 @@ func (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {   if rmsg.Text != "" || len(rmsg.Extra) > 0 {   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) - flog.Debugf("Message is %#v", rmsg) + b.Log.Debugf("Sending message from %s on %s to gateway", rmsg.Username, b.Account) + b.Log.Debugf("Message is %#v", rmsg)   b.Remote <- rmsg   }   } @@ -25626 +24926 @@ func (b *Btelegram) handleDownloadAvatar(userid int, channel string) {   if _, ok := b.avatarMap[strconv.Itoa(userid)]; !ok {   photos, err := b.c.GetUserProfilePhotos(tgbotapi.UserProfilePhotosConfig{UserID: userid, Limit: 1})   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 {   photo := photos.Photos[0][0]   url := b.getFileDirectURL(photo.FileID)   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 { - flog.Error(err) + b.Log.Error(err)   return   }   data, err := helper.DownloadFile(url)   if err != nil { - flog.Errorf("download %s failed %#v", url, err) + b.Log.Errorf("download %s failed %#v", url, err)   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   }   } @@ -34512 +33812 @@ func (b *Btelegram) handleDownload(message *tgbotapi.Message, rmsg *config.Messa   }   // use the URL instead of native upload   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   return nil   }   // 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 {   return err   } @@ -3587 +3517 @@ func (b *Btelegram) handleDownload(message *tgbotapi.Message, rmsg *config.Messa   if err != nil {   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  }   @@ -3767 +3697 @@ func (b *Btelegram) handleUploadFile(msg *config.Message, chatid int64) (string,   }   _, err := b.c.Send(c)   if err != nil { - log.Errorf("file upload failed: %#v", err) + b.Log.Errorf("file upload failed: %#v", err)   }   if fi.Comment != "" {   b.sendMessage(chatid, msg.Username+fi.Comment) @@ -38811 +38111 @@ func (b *Btelegram) handleUploadFile(msg *config.Message, chatid int64) (string,  func (b *Btelegram) sendMessage(chatid int64, text string) (string, error) {   m := tgbotapi.NewMessage(chatid, text)   if b.Config.MessageFormat == "HTML" { - flog.Debug("Using mode HTML") + b.Log.Debug("Using mode HTML")   m.ParseMode = tgbotapi.ModeHTML   }   if b.Config.MessageFormat == "Markdown" { - flog.Debug("Using mode markdown") + b.Log.Debug("Using mode markdown")   m.ParseMode = tgbotapi.ModeMarkdown   }   res, err := b.c.Send(m) @@ -4077 +4007 @@ func (b *Btelegram) cacheAvatar(msg *config.Message) (string, error) {   /* if we have a sha we have successfully uploaded the file to the media server,   so we can now cache the 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   }   return "", nil diff --git a/bridge/xmpp/xmpp.go b/bridge/xmpp/xmpp.go index 03d8159..1363096 100644 --- a/bridge/xmpp/xmpp.go +++ b/bridge/xmpp/xmpp.go @@ -211 +211 @@ package bxmpp    import (   "crypto/tls" + "github.com/42wim/matterbridge/bridge"   "github.com/42wim/matterbridge/bridge/config"   "github.com/42wim/matterbridge/bridge/helper"   "github.com/jpillora/backoff"   "github.com/mattn/go-xmpp" - log "github.com/sirupsen/logrus"   "strings"   "time"  ) @@ -1714 +177 @@ type Bxmpp struct {   *config.BridgeConfig  }   -var flog *log.Entry -var protocol = "xmpp" - -func init() { - flog = log.WithFields(log.Fields{"prefix": protocol}) -} - -func New(cfg *config.BridgeConfig) *Bxmpp { +func New(cfg *config.BridgeConfig) bridge.Bridger {   b := &Bxmpp{BridgeConfig: cfg}   b.xmppMap = make(map[string]string)   return b @@ -3213 +2513 @@ func New(cfg *config.BridgeConfig) *Bxmpp {    func (b *Bxmpp) Connect() error {   var err error - flog.Infof("Connecting %s", b.Config.Server) + b.Log.Infof("Connecting %s", b.Config.Server)   b.xc, err = b.createXMPP()   if err != nil { - flog.Debugf("%#v", err) + b.Log.Debugf("%#v", err)   return err   } - flog.Info("Connection succeeded") + b.Log.Info("Connection succeeded")   go func() {   initial := true   bf := &backoff.Backoff{ @@ -527 +457 @@ func (b *Bxmpp) Connect() error {   initial = false   }   d := bf.Duration() - flog.Infof("Disconnected. Reconnecting in %s", d) + b.Log.Infof("Disconnected. Reconnecting in %s", d)   time.Sleep(d)   b.xc, err = b.createXMPP()   if err == nil { @@ -797 +727 @@ func (b *Bxmpp) Send(msg config.Message) (string, error) {   if msg.Event == config.EVENT_MSG_DELETE {   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)   if msg.Extra != nil { @@ -13110 +12410 @@ func (b *Bxmpp) xmppKeepAlive() chan bool {   for {   select {   case <-ticker.C: - flog.Debugf("PING") + b.Log.Debugf("PING")   err := b.xc.PingC2S("", "")   if err != nil { - flog.Debugf("PING failed %#v", err) + b.Log.Debugf("PING failed %#v", err)   }   case <-done:   return @@ -1678 +1608 @@ func (b *Bxmpp) handleXMPP() error {   if ok {   rmsg.Event = config.EVENT_USER_ACTION   } - flog.Debugf("Sending message from %s on %s to gateway", rmsg.Username, b.Account) - flog.Debugf("Message is %#v", rmsg) + b.Log.Debugf("Sending message from %s on %s to gateway", rmsg.Username, b.Account) + b.Log.Debugf("Message is %#v", rmsg)   b.Remote <- rmsg   }   case xmpp.Presence: diff --git a/gateway/gateway.go b/gateway/gateway.go index f11d4dc..581b638 100644 --- a/gateway/gateway.go +++ b/gateway/gateway.go @@ -413 +426 @@ import (   "bytes"   "fmt"   "github.com/42wim/matterbridge/bridge" + "github.com/42wim/matterbridge/bridge/api"   "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"   // "github.com/davecgh/go-spew/spew"   "crypto/sha1"   "github.com/hashicorp/golang-lru"   "github.com/peterhellberg/emojilib"   "net/http" + "reflect"   "regexp"   "strings"   "time" @@ -366 +4921 @@ type BrMsgID struct {    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() {   flog = log.WithFields(log.Fields{"prefix": "gateway"})  } @@ -527 +8017 @@ func New(cfg config.Gateway, r *Router) *Gateway {  func (gw *Gateway) AddBridge(cfg *config.Bridge) error {   br := gw.Router.getBridge(cfg.Account)   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.Bridges[cfg.Account] = br @@ -4123 +45011 @@ func (gw *Gateway) validGatewayDest(msg *config.Message, channel *config.Channel  func isApi(account string) bool {   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) +}