From 1eca8a84b42f126909839d8c640887c846f94424 Mon Sep 17 00:00:00 2001 From: Martin Dosch Date: Sat, 28 Jul 2018 21:38:48 +0200 Subject: [PATCH] Added check if bot is still joined to MUC. --- feed-to-muc.go | 65 +++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 56 insertions(+), 9 deletions(-) diff --git a/feed-to-muc.go b/feed-to-muc.go index 437ecb5..f220013 100644 --- a/feed-to-muc.go +++ b/feed-to-muc.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "github.com/chilts/sid" "github.com/mattn/go-xmpp" ) @@ -108,14 +109,12 @@ func main() { Debug: false, } + // Connect to server. client, err = options.NewClient() if err != nil { log.Fatal(err) } - // Starting goroutine to ping the server every 30 seconds. - go ping(client, config.ServerAddress, config.BotJid) - // Join the MUC mucStatus, err := client.JoinMUCNoHistory(config.Muc, config.MucNick) if err != nil { @@ -127,11 +126,13 @@ func main() { os.Exit(mucStatus) } + // Starting goroutine to ping the server every 30 seconds. + go pingServer(client, config.ServerAddress, config.BotJid) + + // Starting goroutine to ping the MUC every 30 seconds. + go pingMUC(client, config.BotJid, config.Muc, config.MucNick) + for { - _, err := client.Recv() - if err != nil { - log.Fatal(err) - } for i := 0; i < len(config.Feeds); i++ { output, err := getArticles(config.Feeds[i], config.MaxArticles) @@ -151,13 +152,59 @@ func main() { } } -// Send a ping every 30 seconds to check if the server is still available. -func ping(client *xmpp.Client, server string, botJid string) { +// Send a ping every 30 seconds after last successful ping to check if the MUC is still available. +func pingMUC(client *xmpp.Client, botJid string, Muc string, MucNick string) { for { time.Sleep(30 * time.Second) + + // Send ping to own MUC participant to check we are still joined. + id, err := client.RawInformation(botJid, Muc+"/"+MucNick, sid.Id(), "get", "") + if err != nil { + log.Fatal(err) + } + + pingSent := time.Now() + pingReceived := false + + // Check for result IQ as long as there was no reply yet. + for (time.Since(pingSent).Seconds() < 10.0) && (pingReceived == false) { + // Receive Stanzas. + stanza, err := client.Recv() + if err != nil { + log.Fatal(err) + } + + // Check IQs for type result and UID. + switch v := stanza.(type) { + case xmpp.IQ: + if (v.Type == "error") && (v.ID == id) { + log.Fatal("MUC not available.") + } + if (v.Type == "result") && (v.ID == id) { + pingReceived = true + } + break + default: + break + } + } + // Quit if no ping reply was received. + if pingReceived == false { + log.Fatal("MUC not available.") + } + } +} + +// Send a ping to the server every 30 seconds to check if the connection is still alive. +func pingServer(client *xmpp.Client, server string, botJid string) { + for { + time.Sleep(30 * time.Second) + + // Send ping to server to check if connection still exists. err := client.PingC2S(botJid, strings.Split(server, ":")[0]) if err != nil { log.Fatal(err) } } + }