5
0
mirror of https://github.com/cwinfo/matterbridge.git synced 2024-09-19 21:32:31 +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 (
"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"
@ -26,14 +26,7 @@ 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
@ -50,10 +43,10 @@ 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
}
@ -92,7 +85,7 @@ 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)
}

View File

@ -1,19 +1,7 @@
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"
@ -34,15 +22,13 @@ 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, ".")
@ -52,49 +38,6 @@ 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
}
@ -106,7 +49,7 @@ 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

View File

@ -2,7 +2,7 @@ package config
import (
"github.com/BurntSushi/toml"
"log"
log "github.com/sirupsen/logrus"
"os"
"reflect"
"strings"
@ -143,7 +143,7 @@ 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
@ -164,6 +164,7 @@ type BridgeConfig struct {
General *Protocol
Account string
Remote chan Message
Log *log.Entry
}
func NewConfig(cfgfile string) *Config {

View File

@ -3,10 +3,10 @@ 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"
@ -26,19 +26,12 @@ 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
@ -46,11 +39,11 @@ 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
@ -59,7 +52,7 @@ 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)
@ -103,7 +96,7 @@ 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 == "" {
@ -132,7 +125,7 @@ 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,
@ -145,7 +138,7 @@ 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 {
@ -187,8 +180,8 @@ 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
}
@ -198,7 +191,7 @@ 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))
}
@ -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}
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()
}
}
@ -268,15 +261,15 @@ 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()
@ -367,7 +360,7 @@ 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]
}

View File

@ -3,9 +3,9 @@ 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"
)
@ -17,20 +17,13 @@ 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 {
@ -40,7 +33,7 @@ func (b *Bgitter) Connect() error {
if err != nil {
return err
}
flog.Info("Connection succeeded")
b.Log.Info("Connection succeeded")
return nil
}
@ -78,7 +71,7 @@ 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}
@ -86,11 +79,11 @@ 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)
@ -98,10 +91,10 @@ 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
}
@ -130,7 +123,7 @@ 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

View File

@ -4,13 +4,13 @@ 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"
@ -33,14 +33,7 @@ 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
@ -71,7 +64,7 @@ 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
@ -112,8 +105,8 @@ 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) {
@ -129,7 +122,7 @@ 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")
}
@ -149,7 +142,7 @@ 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)
@ -163,7 +156,7 @@ 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, "!") {
@ -175,7 +168,7 @@ 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)
@ -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}
} 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
@ -259,7 +252,7 @@ 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]
@ -278,31 +271,31 @@ 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) {
@ -317,7 +310,7 @@ 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
}
@ -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":
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)
}
}
@ -359,7 +352,7 @@ 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() {
@ -382,10 +375,10 @@ 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 {
@ -394,13 +387,13 @@ 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
}
@ -408,13 +401,13 @@ 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 {

View File

@ -3,10 +3,10 @@ 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"
@ -21,14 +21,7 @@ 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
@ -36,7 +29,7 @@ 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
@ -51,7 +44,7 @@ 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
}
@ -72,10 +65,10 @@ 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 {
@ -139,7 +132,7 @@ 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)
}
}
}()
@ -147,13 +140,13 @@ 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
}
@ -164,7 +157,7 @@ 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
}
@ -192,11 +185,11 @@ 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
}
}
@ -246,7 +239,7 @@ 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
}
@ -256,7 +249,7 @@ 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
}
@ -272,30 +265,30 @@ 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

View File

@ -3,11 +3,11 @@ 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"
)
@ -19,14 +19,7 @@ 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
}
@ -38,24 +31,24 @@ 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})
@ -64,19 +57,19 @@ 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
@ -85,14 +78,14 @@ 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
@ -122,7 +115,7 @@ 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 {
@ -174,13 +167,13 @@ 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)
}
@ -192,18 +185,18 @@ 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
}
@ -212,7 +205,7 @@ 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{})}
@ -240,7 +233,7 @@ 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)
}
}
}
@ -251,7 +244,7 @@ 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}
}
}
@ -268,12 +261,12 @@ 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()
@ -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,
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
@ -307,15 +300,15 @@ 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
}
}
@ -327,7 +320,7 @@ 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
}
@ -335,7 +328,7 @@ 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
}
@ -395,7 +388,7 @@ 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
@ -407,7 +400,7 @@ 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
}
@ -420,7 +413,7 @@ 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
}
}

View File

@ -1,11 +1,11 @@
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 {
@ -18,14 +18,7 @@ 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}
}
@ -34,7 +27,7 @@ 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})
@ -57,7 +50,7 @@ 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,
@ -81,7 +74,7 @@ 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
@ -90,12 +83,12 @@ 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}
}
}

View File

@ -4,11 +4,11 @@ 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"
@ -25,16 +25,9 @@ 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}
}
@ -45,21 +38,21 @@ 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})
@ -68,19 +61,19 @@ 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()
@ -115,7 +108,7 @@ 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 {
@ -197,6 +190,7 @@ 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
@ -243,16 +237,16 @@ 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)
@ -264,7 +258,7 @@ 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
}
}
@ -272,22 +266,22 @@ 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:
@ -303,9 +297,9 @@ 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:
}
}
@ -314,7 +308,7 @@ 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
}
@ -403,7 +397,7 @@ 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
}
@ -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)
}
// 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
}
@ -429,7 +423,7 @@ 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
@ -444,7 +438,7 @@ 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
}
@ -543,7 +537,7 @@ 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)
}
}
@ -593,7 +587,7 @@ 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

View File

@ -2,10 +2,11 @@ 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"
)
@ -16,20 +17,13 @@ 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)
@ -41,10 +35,10 @@ 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
}
@ -61,7 +55,7 @@ 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"))
@ -93,10 +87,10 @@ 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
@ -130,7 +124,7 @@ 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
}

View File

@ -2,11 +2,11 @@ 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"
@ -21,14 +21,7 @@ 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{})
@ -36,13 +29,13 @@ 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")
}
@ -95,11 +88,11 @@ 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)
@ -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)}
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()
@ -118,47 +111,47 @@ 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)
}
}
}

View File

@ -5,10 +5,10 @@ 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 {
@ -17,33 +17,26 @@ 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
}
@ -57,7 +50,7 @@ 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)
@ -106,11 +99,11 @@ 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)
@ -126,10 +119,10 @@ 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
}
@ -189,7 +182,7 @@ 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
@ -233,8 +226,8 @@ 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
}
}
@ -256,26 +249,26 @@ 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
}
}
@ -345,12 +338,12 @@ 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
}
@ -358,7 +351,7 @@ 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
}
@ -376,7 +369,7 @@ 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)
@ -388,11 +381,11 @@ 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)
@ -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,
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

View File

@ -2,11 +2,11 @@ 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"
)
@ -17,14 +17,7 @@ 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
@ -32,13 +25,13 @@ 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{
@ -52,7 +45,7 @@ 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 {
@ -79,7 +72,7 @@ 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 {
@ -131,10 +124,10 @@ 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
@ -167,8 +160,8 @@ 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:

View File

@ -4,13 +4,26 @@ 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"
@ -36,6 +49,21 @@ 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"})
}
@ -52,7 +80,17 @@ 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
@ -412,3 +450,11 @@ 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)
}