From 1985873494ddcfb73ec04525ebc1b7ba0b1f428d Mon Sep 17 00:00:00 2001 From: Wim Date: Sun, 9 Feb 2020 22:11:46 +0100 Subject: Implement basic reconnect (whatsapp). Fixes #987 (#1003) --- bridge/whatsapp/handlers.go | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) (limited to 'bridge/whatsapp') diff --git a/bridge/whatsapp/handlers.go b/bridge/whatsapp/handlers.go index 2873f0c4..eaa3f6f9 100644 --- a/bridge/whatsapp/handlers.go +++ b/bridge/whatsapp/handlers.go @@ -9,6 +9,7 @@ import ( "github.com/42wim/matterbridge/bridge/config" "github.com/42wim/matterbridge/bridge/helper" "github.com/Rhymen/go-whatsapp" + "github.com/jpillora/backoff" ) /* @@ -25,7 +26,38 @@ func (b *Bwhatsapp) HandleError(err error) { if strings.Contains(err.Error(), "error processing data: received invalid data") { return } - b.Log.Errorf("%v", err) // TODO implement proper handling? at least respond to different error types + + switch err.(type) { + case *whatsapp.ErrConnectionClosed, *whatsapp.ErrConnectionFailed: + b.reconnect(err) + default: + switch err { + case whatsapp.ErrConnectionTimeout: + b.reconnect(err) + default: + b.Log.Errorf("%v", err) + } + } +} + +func (b *Bwhatsapp) reconnect(err error) { + bf := &backoff.Backoff{ + Min: time.Second, + Max: 5 * time.Minute, + Jitter: true, + } + for { + d := bf.Duration() + b.Log.Errorf("Connection failed, underlying error: %v", err) + b.Log.Infof("Waiting %s...", d) + time.Sleep(d) + b.Log.Info("Reconnecting...") + err := b.conn.Restore() + if err == nil { + bf.Reset() + return + } + } } // HandleTextMessage sent from WhatsApp, relay it to the brige -- cgit v1.2.3