From 1fdb2f07795d8370ba9619ae6011edab6d539b0b Mon Sep 17 00:00:00 2001 From: Bernhard Tittelbach Date: Tue, 25 Nov 2014 19:37:52 +0000 Subject: [PATCH] better command parsing (case, word separators, etc) and error recovery --- go/r3-netstatus/main.go | 392 ++++++++-------- go/r3-netstatus/r3xmppbot/r3xmppbot.go | 793 +++++++++++++++++--------------- 2 files changed, 626 insertions(+), 559 deletions(-) diff --git a/go/r3-netstatus/main.go b/go/r3-netstatus/main.go index 143f62b..23bcce0 100644 --- a/go/r3-netstatus/main.go +++ b/go/r3-netstatus/main.go @@ -3,31 +3,35 @@ package main import ( - "./r3xmppbot" - pubsub "github.com/tuxychandru/pubsub" - "flag" - "time" - "fmt" - //~ "./brain" - r3events "svn.spreadspace.org/realraum/go.svn/r3events" - zmq "github.com/vaughan0/go-zmq" + "flag" + "fmt" + "time" + + "./r3xmppbot" + pubsub "github.com/tuxychandru/pubsub" + //~ "./brain" + zmq "github.com/vaughan0/go-zmq" + r3events "svn.spreadspace.org/realraum/go.svn/r3events" ) type SpaceState struct { - present bool - buttonpress_until int64 - door_locked bool - door_shut bool + present bool + buttonpress_until int64 + door_locked bool + door_shut bool } var ( - xmpp_login_ struct {jid string; pass string} - xmpp_bot_authstring_ string - xmpp_state_save_dir_ string - r3eventssub_port_ string - button_press_timeout_ int64 = 3600 - brain_connect_addr_ string - enable_syslog_, enable_debug_ bool + xmpp_login_ struct { + jid string + pass string + } + xmpp_bot_authstring_ string + xmpp_state_save_dir_ string + r3eventssub_port_ string + button_press_timeout_ int64 = 3600 + brain_connect_addr_ string + enable_syslog_, enable_debug_ bool ) type EventToXMPPStartupFinished struct{} @@ -35,196 +39,214 @@ type EventToXMPPStartupFinished struct{} //------- func init() { - flag.StringVar(&xmpp_login_.jid, "xjid", "realrauminfo@realraum.at/Tuer", "XMPP Bot Login JID") - flag.StringVar(&xmpp_login_.pass, "xpass", "", "XMPP Bot Login Password") - flag.StringVar(&xmpp_bot_authstring_, "xbotauth", "", "String that user use to authenticate themselves to the bot") - flag.StringVar(&xmpp_state_save_dir_,"xstatedir","/flash/var/lib/r3netstatus/", "Directory to save XMPP bot state in") - flag.StringVar(&r3eventssub_port_, "eventsubport", "tcp://torwaechter.realraum.at:4244", "zmq address to subscribe r3events") - flag.StringVar(&brain_connect_addr_, "brainconnect", "tcp://torwaechter.realraum.at:4245", "address to ask about most recent stored events") - flag.BoolVar(&enable_syslog_, "syslog", false, "enable logging to syslog") - flag.BoolVar(&enable_debug_, "debug", false, "enable debug output") - flag.Parse() + flag.StringVar(&xmpp_login_.jid, "xjid", "realrauminfo@realraum.at/Tuer", "XMPP Bot Login JID") + flag.StringVar(&xmpp_login_.pass, "xpass", "", "XMPP Bot Login Password") + flag.StringVar(&xmpp_bot_authstring_, "xbotauth", "", "String that users use to authenticate themselves to the bot") + flag.StringVar(&xmpp_state_save_dir_, "xstatedir", "/flash/var/lib/r3netstatus/", "Directory to save XMPP bot state in") + flag.StringVar(&r3eventssub_port_, "eventsubport", "tcp://torwaechter.realraum.at:4244", "zmq address to subscribe r3events") + flag.StringVar(&brain_connect_addr_, "brainconnect", "tcp://torwaechter.realraum.at:4245", "address to ask about most recent stored events") + flag.BoolVar(&enable_syslog_, "syslog", false, "enable logging to syslog") + flag.BoolVar(&enable_debug_, "debug", false, "enable debug output") + flag.Parse() } //------- func IfThenElseStr(c bool, strue, sfalse string) string { - if c {return strue} else {return sfalse} + if c { + return strue + } else { + return sfalse + } } func composeDoorLockMessage(locked bool, frontshut r3events.DoorAjarUpdate, doorcmd r3events.DoorCommandEvent, ts int64) string { - var ajarstring string = ""; - if frontshut.Shut == false && frontshut.Ts < doorcmd.Ts { - ajarstring = " (still ajar)" - } - if ts - doorcmd.Ts < 30 { - if len(doorcmd.Who) == 0 || doorcmd.Who == "-" { - return fmt.Sprintf("The%s frontdoor was %s by %s at %s.",ajarstring, IfThenElseStr(locked, "locked","unlocked"), doorcmd.Using, time.Unix(ts,0).String()) - } else { - return fmt.Sprintf("%s %s the%s frontdoor by %s at %s.",doorcmd.Who, IfThenElseStr(locked, "locked","unlocked"), ajarstring, doorcmd.Using, time.Unix(ts,0).String()) - } - } else { - return fmt.Sprintf("The%s frontdoor was %s manually at %s.", ajarstring, IfThenElseStr(locked, "locked","unlocked"), time.Unix(ts,0).String()) - } + var ajarstring string = "" + if frontshut.Shut == false && frontshut.Ts < doorcmd.Ts { + ajarstring = " (still ajar)" + } + if ts-doorcmd.Ts < 30 { + if len(doorcmd.Who) == 0 || doorcmd.Who == "-" { + return fmt.Sprintf("The%s frontdoor was %s by %s at %s.", ajarstring, IfThenElseStr(locked, "locked", "unlocked"), doorcmd.Using, time.Unix(ts, 0).String()) + } else { + return fmt.Sprintf("%s %s the%s frontdoor by %s at %s.", doorcmd.Who, IfThenElseStr(locked, "locked", "unlocked"), ajarstring, doorcmd.Using, time.Unix(ts, 0).String()) + } + } else { + return fmt.Sprintf("The%s frontdoor was %s manually at %s.", ajarstring, IfThenElseStr(locked, "locked", "unlocked"), time.Unix(ts, 0).String()) + } } func composePresence(present bool, temp_cx float64, light_lothr, last_buttonpress int64) r3xmppbot.XMPPStatusEvent { - present_msg := "Somebody is present" - notpresent_msg := "Nobody is here" - button_msg := "The button has been pressed :-)" - msg := "%s (CX: %.2f°C, LoTHR light: %d)" - - if present { - if last_buttonpress > 0 && time.Now().Unix() - last_buttonpress < button_press_timeout_ { - return r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowFreeForChat, fmt.Sprintf(msg, button_msg, temp_cx, light_lothr)} - } else { - return r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowOnline, fmt.Sprintf(msg, present_msg, temp_cx, light_lothr)} - } - } else { - return r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe, fmt.Sprintf(msg, notpresent_msg, temp_cx, light_lothr)} - } + present_msg := "Somebody is present" + notpresent_msg := "Nobody is here" + button_msg := "The button has been pressed :-)" + msg := "%s (CX: %.2f°C, LoTHR light: %d)" + + if present { + if last_buttonpress > 0 && time.Now().Unix()-last_buttonpress < button_press_timeout_ { + return r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowFreeForChat, fmt.Sprintf(msg, button_msg, temp_cx, light_lothr)} + } else { + return r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowOnline, fmt.Sprintf(msg, present_msg, temp_cx, light_lothr)} + } + } else { + return r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe, fmt.Sprintf(msg, notpresent_msg, temp_cx, light_lothr)} + } } -func EventToXMPP(bot *r3xmppbot.XmppBot, events <- chan interface{}, xmpp_presence_events_chan chan <- interface{}) { - button_msg := "Dooom ! The button has been pressed ! Propably someone is bored and in need of company ! ;-)" - defer func() { - if x := recover(); x != nil { - //defer ist called _after_ EventToXMPP function has returned. Thus we recover after returning from this function. - Syslog_.Printf("handleIncomingXMPPStanzas: run time panic: %v", x) - } - }() - - var present, frontlock bool = false, true - var last_buttonpress, light_lothr int64 = 0, 0 - var temp_cx float64 = 0.0 - var last_door_cmd r3events.DoorCommandEvent - var last_frontdoor_ajar r3events.DoorAjarUpdate = r3events.DoorAjarUpdate{true, 0} - var standard_distribute_level r3xmppbot.R3JIDDesire = r3xmppbot.R3DebugInfo // initial state, changed after startup finished event recieved - - xmpp_presence_events_chan <- r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe, "Nobody is here"} - - for eventinterface := range(events) { - Debug_.Printf("event2xmpp: %T %+v", eventinterface, eventinterface) - switch event := eventinterface.(type) { - case EventToXMPPStartupFinished: - //after we received all events from QueryLatestEventsAndInjectThem, we get this event and start sending new events normally - standard_distribute_level = r3xmppbot.R3OnlineOnlyInfo - case r3events.PresenceUpdate: - present = event.Present - if ! present { last_buttonpress = 0 } - xmpp_presence_events_chan <- composePresence(present, temp_cx, light_lothr, last_buttonpress) - case r3events.DoorCommandEvent: - last_door_cmd = event - xmpp_presence_events_chan <- fmt.Sprintln("DoorCommand:",event.Command, "using", event.Using, "by", event.Who, time.Unix(event.Ts,0)) - case r3events.DoorLockUpdate: - if frontlock != event.Locked { - xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: composeDoorLockMessage(event.Locked, last_frontdoor_ajar, last_door_cmd, event.Ts), DistributeLevel:standard_distribute_level, RememberAsStatus: true} - } - frontlock = event.Locked - case r3events.DoorAjarUpdate: - if last_frontdoor_ajar.Shut != event.Shut { - xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: fmt.Sprintf("Frontdoor is %s (%s)",IfThenElseStr(event.Shut,"now shut.","ajar."),time.Unix(event.Ts,0).String()), DistributeLevel: r3xmppbot.R3DebugInfo, RememberAsStatus: false} - } - last_frontdoor_ajar = event - case r3events.BackdoorAjarUpdate: - xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: fmt.Sprintf("Backdoor is %s (%s)",IfThenElseStr(event.Shut,"now shut.","ajar!"),time.Unix(event.Ts,0).String()), DistributeLevel: standard_distribute_level, RememberAsStatus: false} - case r3events.GasLeakAlert: - xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: fmt.Sprintf("ALERT !! GasLeak Detected !!! (%s)", time.Unix(event.Ts,0).String()), DistributeLevel: r3xmppbot.R3NeverInfo, RememberAsStatus: false} - case r3events.IlluminationSensorUpdate: - light_lothr = event.Value - case r3events.TempSensorUpdate: - if event.Sensorindex == 1 { - temp_cx = event.Value - } - case r3events.BoreDoomButtonPressEvent: - last_buttonpress = event.Ts - xmpp_presence_events_chan <- composePresence(present, temp_cx, light_lothr, last_buttonpress) - xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: button_msg, DistributeLevel: standard_distribute_level} - case r3events.TimeTick: - // update presence text with sensor and button info - xmpp_presence_events_chan <- composePresence(present, temp_cx, light_lothr, last_buttonpress) - // Try to XMPP Ping the server and if that fails, quit XMPPBot - if bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false { return } - case r3events.DoorProblemEvent: - xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: fmt.Sprintf("Door Problem: %s. SeverityLevel: %d (%s)",event.Problem, event.Severity, time.Unix(event.Ts,0).String()), DistributeLevel: r3xmppbot.R3OnlineOnlyInfo, RememberAsStatus: false} - } +func EventToXMPP(bot *r3xmppbot.XmppBot, events <-chan interface{}, xmpp_presence_events_chan chan<- interface{}) { + button_msg := "Dooom ! The button has been pressed ! Propably someone is bored and in need of company ! ;-)" + defer func() { + if x := recover(); x != nil { + //defer ist called _after_ EventToXMPP function has returned. Thus we recover after returning from this function. + Syslog_.Printf("handleIncomingXMPPStanzas: run time panic: %v", x) + } + }() + + var present, frontlock bool = false, true + var last_buttonpress, light_lothr int64 = 0, 0 + var temp_cx float64 = 0.0 + var last_door_cmd r3events.DoorCommandEvent + var last_frontdoor_ajar r3events.DoorAjarUpdate = r3events.DoorAjarUpdate{true, 0} + var standard_distribute_level r3xmppbot.R3JIDDesire = r3xmppbot.R3DebugInfo // initial state, changed after startup finished event recieved + + xmpp_presence_events_chan <- r3xmppbot.XMPPStatusEvent{r3xmppbot.ShowNotAvailabe, "Nobody is here"} + + for eventinterface := range events { + Debug_.Printf("event2xmpp: %T %+v", eventinterface, eventinterface) + switch event := eventinterface.(type) { + case EventToXMPPStartupFinished: + //after we received all events from QueryLatestEventsAndInjectThem, we get this event and start sending new events normally + standard_distribute_level = r3xmppbot.R3OnlineOnlyInfo + case r3events.PresenceUpdate: + present = event.Present + if !present { + last_buttonpress = 0 + } + xmpp_presence_events_chan <- composePresence(present, temp_cx, light_lothr, last_buttonpress) + case r3events.DoorCommandEvent: + last_door_cmd = event + xmpp_presence_events_chan <- fmt.Sprintln("DoorCommand:", event.Command, "using", event.Using, "by", event.Who, time.Unix(event.Ts, 0)) + case r3events.DoorLockUpdate: + if frontlock != event.Locked { + xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: composeDoorLockMessage(event.Locked, last_frontdoor_ajar, last_door_cmd, event.Ts), DistributeLevel: standard_distribute_level, RememberAsStatus: true} + } + frontlock = event.Locked + case r3events.DoorAjarUpdate: + if last_frontdoor_ajar.Shut != event.Shut { + xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: fmt.Sprintf("Frontdoor is %s (%s)", IfThenElseStr(event.Shut, "now shut.", "ajar."), time.Unix(event.Ts, 0).String()), DistributeLevel: r3xmppbot.R3DebugInfo, RememberAsStatus: false} + } + last_frontdoor_ajar = event + case r3events.BackdoorAjarUpdate: + xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: fmt.Sprintf("Backdoor is %s (%s)", IfThenElseStr(event.Shut, "now shut.", "ajar!"), time.Unix(event.Ts, 0).String()), DistributeLevel: standard_distribute_level, RememberAsStatus: false} + case r3events.GasLeakAlert: + xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: fmt.Sprintf("ALERT !! GasLeak Detected !!! (%s)", time.Unix(event.Ts, 0).String()), DistributeLevel: r3xmppbot.R3NeverInfo, RememberAsStatus: false} + case r3events.IlluminationSensorUpdate: + light_lothr = event.Value + case r3events.TempSensorUpdate: + if event.Sensorindex == 1 { + temp_cx = event.Value + } + case r3events.BoreDoomButtonPressEvent: + last_buttonpress = event.Ts + xmpp_presence_events_chan <- composePresence(present, temp_cx, light_lothr, last_buttonpress) + xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: button_msg, DistributeLevel: standard_distribute_level} + case r3events.TimeTick: + // update presence text with sensor and button info + xmpp_presence_events_chan <- composePresence(present, temp_cx, light_lothr, last_buttonpress) + // Try to XMPP Ping the server and if that fails, quit XMPPBot + if bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false && bot.PingServer(900) == false { + return + } + case r3events.DoorProblemEvent: + xmpp_presence_events_chan <- r3xmppbot.XMPPMsgEvent{Msg: fmt.Sprintf("Door Problem: %s. SeverityLevel: %d (%s)", event.Problem, event.Severity, time.Unix(event.Ts, 0).String()), DistributeLevel: r3xmppbot.R3OnlineOnlyInfo, RememberAsStatus: false} + } } } func RunXMPPBot(ps *pubsub.PubSub, zmqctx *zmq.Context) { - var xmpperr error - var bot *r3xmppbot.XmppBot - var xmpp_presence_events_chan chan interface{} - for { - bot, xmpp_presence_events_chan, xmpperr = r3xmppbot.NewStartedBot(xmpp_login_.jid, xmpp_login_.pass, xmpp_bot_authstring_, xmpp_state_save_dir_, true) - if xmpperr == nil { - Syslog_.Printf("Successfully (re)started XMPP Bot") - // subscribe before QueryLatestEventsAndInjectThem and EventToXMPP - psevents := ps.Sub("presence","door","buttons","updateinterval","sensors","xmppmeta") - QueryLatestEventsAndInjectThem(ps, zmqctx) - ps.Pub(EventToXMPPStartupFinished{}, "xmppmeta") - EventToXMPP(bot, psevents, xmpp_presence_events_chan) - // unsubscribe right away, since we don't known when reconnect will succeed and we don't want to block PubSub - ps.Unsub(psevents, "presence","door","buttons","updateinterval","sensors","xmppmeta") - bot.StopBot() - } else { - Syslog_.Printf("Error starting XMPP Bot: %s", xmpperr.Error()) - } - time.Sleep(10 * time.Second) - } + var xmpperr error + var bot *r3xmppbot.XmppBot + var xmpp_presence_events_chan chan interface{} + for { + bot, xmpp_presence_events_chan, xmpperr = r3xmppbot.NewStartedBot(xmpp_login_.jid, xmpp_login_.pass, xmpp_bot_authstring_, xmpp_state_save_dir_, true) + if xmpperr == nil { + Syslog_.Printf("Successfully (re)started XMPP Bot") + // subscribe before QueryLatestEventsAndInjectThem and EventToXMPP + psevents := ps.Sub("presence", "door", "buttons", "updateinterval", "sensors", "xmppmeta") + QueryLatestEventsAndInjectThem(ps, zmqctx) + ps.Pub(EventToXMPPStartupFinished{}, "xmppmeta") + EventToXMPP(bot, psevents, xmpp_presence_events_chan) + // unsubscribe right away, since we don't known when reconnect will succeed and we don't want to block PubSub + ps.Unsub(psevents, "presence", "door", "buttons", "updateinterval", "sensors", "xmppmeta") + bot.StopBot() + } else { + Syslog_.Printf("Error starting XMPP Bot: %s", xmpperr.Error()) + } + time.Sleep(10 * time.Second) + } } func ParseZMQr3Event(lines [][]byte, ps *pubsub.PubSub) { - evnt, pubsubcat, err := r3events.UnmarshalByteByte2Event(lines) - Debug_.Printf("ParseZMQr3Event: %s %s %s", evnt, pubsubcat, err) - if err != nil { return } - ps.Pub(evnt, pubsubcat) + evnt, pubsubcat, err := r3events.UnmarshalByteByte2Event(lines) + Debug_.Printf("ParseZMQr3Event: %s %s %s", evnt, pubsubcat, err) + if err != nil { + return + } + ps.Pub(evnt, pubsubcat) } func QueryLatestEventsAndInjectThem(ps *pubsub.PubSub, zmqctx *zmq.Context) { - answ := ZmqsAskQuestionsAndClose(zmqctx, brain_connect_addr_, [][][]byte{ - [][]byte{[]byte("BackdoorAjarUpdate")}, - [][]byte{[]byte("DoorCommandEvent")}, - [][]byte{[]byte("DoorLockUpdate")}, - [][]byte{[]byte("DoorAjarUpdate")}, - [][]byte{[]byte("PresenceUpdate")}, - [][]byte{[]byte("IlluminationSensorUpdate")}, - [][]byte{[]byte("TempSensorUpdate")}}) - for _, a := range(answ) { - ParseZMQr3Event(a, ps) - } + answ := ZmqsAskQuestionsAndClose(zmqctx, brain_connect_addr_, [][][]byte{ + [][]byte{[]byte("BackdoorAjarUpdate")}, + [][]byte{[]byte("DoorCommandEvent")}, + [][]byte{[]byte("DoorLockUpdate")}, + [][]byte{[]byte("DoorAjarUpdate")}, + [][]byte{[]byte("PresenceUpdate")}, + [][]byte{[]byte("IlluminationSensorUpdate")}, + [][]byte{[]byte("TempSensorUpdate")}}) + for _, a := range answ { + ParseZMQr3Event(a, ps) + } } func main() { - if enable_syslog_ { LogEnableSyslog(); r3xmppbot.LogEnableSyslog() } - if enable_debug_ { LogEnableDebuglog(); r3xmppbot.LogEnableDebuglog() } - Syslog_.Print("started") - defer Syslog_.Print("exiting") - zmqctx, zmqsub := ZmqsInit(r3eventssub_port_) - defer zmqctx.Close() - if zmqsub != nil {defer zmqsub.Close()} - if zmqsub == nil { - panic("zmq sockets must not be nil !!") - } - - ps := pubsub.New(10) - defer ps.Shutdown() - //~ brn := brain.New() - //~ defer brn.Shutdown() - - go EventToWeb(ps) - // --- get update on most recent events --- - QueryLatestEventsAndInjectThem(ps, zmqctx) - go RunXMPPBot(ps, zmqctx) - - // --- receive and distribute events --- - ticker := time.NewTicker(time.Duration(6) * time.Minute) - for { - select { - case e := <-zmqsub.In(): - ParseZMQr3Event(e, ps) //, brn) - case <-ticker.C: - ps.Pub(r3events.TimeTick{time.Now().Unix()}, "updateinterval") - } - } + if enable_syslog_ { + LogEnableSyslog() + r3xmppbot.LogEnableSyslog() + } + if enable_debug_ { + LogEnableDebuglog() + r3xmppbot.LogEnableDebuglog() + } + Syslog_.Print("started") + defer Syslog_.Print("exiting") + zmqctx, zmqsub := ZmqsInit(r3eventssub_port_) + defer zmqctx.Close() + if zmqsub != nil { + defer zmqsub.Close() + } + if zmqsub == nil { + panic("zmq sockets must not be nil !!") + } + + ps := pubsub.New(10) + defer ps.Shutdown() + //~ brn := brain.New() + //~ defer brn.Shutdown() + + go EventToWeb(ps) + // --- get update on most recent events --- + QueryLatestEventsAndInjectThem(ps, zmqctx) + go RunXMPPBot(ps, zmqctx) + + // --- receive and distribute events --- + ticker := time.NewTicker(time.Duration(6) * time.Minute) + for { + select { + case e := <-zmqsub.In(): + ParseZMQr3Event(e, ps) //, brn) + case <-ticker.C: + ps.Pub(r3events.TimeTick{time.Now().Unix()}, "updateinterval") + } + } } diff --git a/go/r3-netstatus/r3xmppbot/r3xmppbot.go b/go/r3-netstatus/r3xmppbot/r3xmppbot.go index 3ad4177..177f4a1 100644 --- a/go/r3-netstatus/r3xmppbot/r3xmppbot.go +++ b/go/r3-netstatus/r3xmppbot/r3xmppbot.go @@ -3,246 +3,249 @@ package r3xmppbot import ( + "crypto/tls" + "encoding/json" + "os" + "path" + "strings" + "time" + xmpp "code.google.com/p/goexmpp" - "crypto/tls" - "os" - "time" - "encoding/json" - "path" ) func (botdata *XmppBot) makeXMPPMessage(to string, message interface{}, subject interface{}) *xmpp.Message { - xmppmsgheader := xmpp.Header{To: to, - From: botdata.my_jid_, - Id: <-xmpp.Id, - Type: "chat", - Lang: "", - Innerxml: "", - Error: nil, - Nested: make([]interface{},0)} - - var msgsubject, msgbody *xmpp.Generic - switch cast_msg := message.(type) { - case string: - msgbody = &xmpp.Generic{Chardata: cast_msg} - case *string: - msgbody = &xmpp.Generic{Chardata: *cast_msg} - case *xmpp.Generic: - msgbody = cast_msg - default: - msgbody = &xmpp.Generic{} - } - switch cast_msg := subject.(type) { - case string: - msgsubject = &xmpp.Generic{Chardata: cast_msg} - case *string: - msgsubject = &xmpp.Generic{Chardata: *cast_msg} - case *xmpp.Generic: - msgsubject = cast_msg - default: - msgsubject = &xmpp.Generic{} - } - return &xmpp.Message{Header: xmppmsgheader , Subject: msgsubject, Body: msgbody, Thread: &xmpp.Generic{}} + xmppmsgheader := xmpp.Header{To: to, + From: botdata.my_jid_, + Id: <-xmpp.Id, + Type: "chat", + Lang: "", + Innerxml: "", + Error: nil, + Nested: make([]interface{}, 0)} + + var msgsubject, msgbody *xmpp.Generic + switch cast_msg := message.(type) { + case string: + msgbody = &xmpp.Generic{Chardata: cast_msg} + case *string: + msgbody = &xmpp.Generic{Chardata: *cast_msg} + case *xmpp.Generic: + msgbody = cast_msg + default: + msgbody = &xmpp.Generic{} + } + switch cast_msg := subject.(type) { + case string: + msgsubject = &xmpp.Generic{Chardata: cast_msg} + case *string: + msgsubject = &xmpp.Generic{Chardata: *cast_msg} + case *xmpp.Generic: + msgsubject = cast_msg + default: + msgsubject = &xmpp.Generic{} + } + return &xmpp.Message{Header: xmppmsgheader, Subject: msgsubject, Body: msgbody, Thread: &xmpp.Generic{}} } func (botdata *XmppBot) makeXMPPPresence(to, ptype, show, status string) *xmpp.Presence { - xmppmsgheader := xmpp.Header{To: to, - From: botdata.my_jid_, - Id: <-xmpp.Id, - Type: ptype, - Lang: "", - Innerxml: "", - Error: nil, - Nested: make([]interface{},0)} - var gen_show, gen_status *xmpp.Generic - if len(show) == 0 { - gen_show = nil - } else { - gen_show = &xmpp.Generic{Chardata: show} - } - if len(status) == 0 { - gen_status = nil - } else { - gen_status = &xmpp.Generic{Chardata: status} - } - return &xmpp.Presence{Header: xmppmsgheader, Show: gen_show, Status: gen_status} + xmppmsgheader := xmpp.Header{To: to, + From: botdata.my_jid_, + Id: <-xmpp.Id, + Type: ptype, + Lang: "", + Innerxml: "", + Error: nil, + Nested: make([]interface{}, 0)} + var gen_show, gen_status *xmpp.Generic + if len(show) == 0 { + gen_show = nil + } else { + gen_show = &xmpp.Generic{Chardata: show} + } + if len(status) == 0 { + gen_status = nil + } else { + gen_status = &xmpp.Generic{Chardata: status} + } + return &xmpp.Presence{Header: xmppmsgheader, Show: gen_show, Status: gen_status} } type R3JIDDesire int const ( - R3NoChange R3JIDDesire = -1 - R3NeverInfo R3JIDDesire = iota // ignore first value by assigning to blank identifier - R3OnlineOnlyInfo - R3OnlineOnlyWithRecapInfo - R3AlwaysInfo - R3DebugInfo + R3NoChange R3JIDDesire = -1 + R3NeverInfo R3JIDDesire = iota // ignore first value by assigning to blank identifier + R3OnlineOnlyInfo + R3OnlineOnlyWithRecapInfo + R3AlwaysInfo + R3DebugInfo ) const ( - ShowOnline string = "" - ShowAway string = "away" - ShowNotAvailabe string = "xa" - ShowDoNotDisturb string = "dnd" - ShowFreeForChat string = "chat" + ShowOnline string = "" + ShowAway string = "away" + ShowNotAvailabe string = "xa" + ShowDoNotDisturb string = "dnd" + ShowFreeForChat string = "chat" ) type JidData struct { - Online bool - Wants R3JIDDesire + Online bool + Wants R3JIDDesire } type JabberEvent struct { - JID string - Online bool - Wants R3JIDDesire - StatusNow bool + JID string + Online bool + Wants R3JIDDesire + StatusNow bool } type XMPPMsgEvent struct { - Msg string - DistributeLevel R3JIDDesire - RememberAsStatus bool + Msg string + DistributeLevel R3JIDDesire + RememberAsStatus bool } type XMPPStatusEvent struct { - Show string - Status string + Show string + Status string } type RealraumXmppNotifierConfig map[string]JidData type XmppBot struct { - jid_lastauthtime_ map[string]int64 - realraum_jids_ RealraumXmppNotifierConfig - password_ string - auth_cmd_ string - auth_cmd2_ string - my_jid_ string - auth_timeout_ int64 - config_file_ string - my_login_password_ string - xmppclient_ *xmpp.Client - presence_events_ *chan interface{} + jid_lastauthtime_ map[string]int64 + realraum_jids_ RealraumXmppNotifierConfig + password_ string + my_jid_ string + auth_timeout_ int64 + config_file_ string + my_login_password_ string + xmppclient_ *xmpp.Client + presence_events_ *chan interface{} } - -func (data RealraumXmppNotifierConfig) saveTo(filepath string) () { - fh, err := os.Create(filepath) - if err != nil { - Syslog_.Println(err) - return - } - defer fh.Close() - enc := json.NewEncoder(fh) - if err = enc.Encode(&data); err != nil { - Syslog_.Println(err) - return - } +func (data RealraumXmppNotifierConfig) saveTo(filepath string) { + fh, err := os.Create(filepath) + if err != nil { + Syslog_.Println(err) + return + } + defer fh.Close() + enc := json.NewEncoder(fh) + if err = enc.Encode(&data); err != nil { + Syslog_.Println(err) + return + } } -func (data RealraumXmppNotifierConfig) loadFrom(filepath string) () { - fh, err := os.Open(filepath) - if err != nil { - Syslog_.Println(err) - return - } - defer fh.Close() - dec := json.NewDecoder(fh) - if err = dec.Decode(&data); err != nil { - Syslog_.Println(err) - return - } - for to, jiddata := range data { - jiddata.Online = false - data[to]=jiddata - } +func (data RealraumXmppNotifierConfig) loadFrom(filepath string) { + fh, err := os.Open(filepath) + if err != nil { + Syslog_.Println(err) + return + } + defer fh.Close() + dec := json.NewDecoder(fh) + if err = dec.Decode(&data); err != nil { + Syslog_.Println(err) + return + } + for to, jiddata := range data { + jiddata.Online = false + data[to] = jiddata + } } -func (botdata *XmppBot) handleEventsforXMPP(xmppout chan <- xmpp.Stanza, presence_events <- chan interface{}, jabber_events <- chan JabberEvent) { - var last_status_msg *string +func (botdata *XmppBot) handleEventsforXMPP(xmppout chan<- xmpp.Stanza, presence_events <-chan interface{}, jabber_events <-chan JabberEvent) { + var last_status_msg *string - defer func() { - if x := recover(); x != nil { - Syslog_.Printf("handleEventsforXMPP: run time panic: %v", x) - //FIXME: signal that xmpp bot has crashed - } - for _ = range(jabber_events) {} //cleanout jabber_events queue - }() + defer func() { + if x := recover(); x != nil { + Syslog_.Printf("handleEventsforXMPP: run time panic: %v", x) + } + for _ = range jabber_events { + } //cleanout jabber_events queue + }() for { select { case pe, pe_still_open := <-presence_events: - if ! pe_still_open { return } - Debug_.Printf("handleEventsforXMPP<-presence_events: %T %+v", pe, pe) - switch pec := pe.(type) { - case xmpp.Stanza: - xmppout <- pec - continue - case string: - for to, jiddata := range botdata.realraum_jids_ { - if jiddata.Wants >= R3DebugInfo { - xmppout <- botdata.makeXMPPMessage(to, pec, nil) - } - } - - case XMPPStatusEvent: - xmppout <- botdata.makeXMPPPresence("", "", pec.Show, pec.Status) - - case XMPPMsgEvent: - if pec.RememberAsStatus { - last_status_msg = &pec.Msg - } - for to, jiddata := range botdata.realraum_jids_ { - if jiddata.Wants >= pec.DistributeLevel && ((jiddata.Wants >= R3OnlineOnlyInfo && jiddata.Online) || jiddata.Wants >= R3AlwaysInfo) { - xmppout <- botdata.makeXMPPMessage(to, pec.Msg, nil) - } - } - default: - Debug_.Println("handleEventsforXMPP<-presence_events: unknown type received: quitting") - return - } + if !pe_still_open { + return + } + Debug_.Printf("handleEventsforXMPP<-presence_events: %T %+v", pe, pe) + switch pec := pe.(type) { + case xmpp.Stanza: + xmppout <- pec + continue + case string: + for to, jiddata := range botdata.realraum_jids_ { + if jiddata.Wants >= R3DebugInfo { + xmppout <- botdata.makeXMPPMessage(to, pec, nil) + } + } + + case XMPPStatusEvent: + xmppout <- botdata.makeXMPPPresence("", "", pec.Show, pec.Status) + + case XMPPMsgEvent: + if pec.RememberAsStatus { + last_status_msg = &pec.Msg + } + for to, jiddata := range botdata.realraum_jids_ { + if jiddata.Wants >= pec.DistributeLevel && ((jiddata.Wants >= R3OnlineOnlyInfo && jiddata.Online) || jiddata.Wants >= R3AlwaysInfo) { + xmppout <- botdata.makeXMPPMessage(to, pec.Msg, nil) + } + } + default: + Debug_.Println("handleEventsforXMPP<-presence_events: unknown type received: quitting") + return + } case je, je_still_open := <-jabber_events: - if ! je_still_open { return } - Debug_.Printf("handleEventsforXMPP<-jabber_events: %T %+v", je, je) - simple_jid := removeJIDResource(je.JID) - jid_data, jid_in_map := botdata.realraum_jids_[simple_jid] - - //send status if requested, even if user never changed any settings and thus is not in map - if last_status_msg != nil && je.StatusNow { - xmppout <- botdata.makeXMPPMessage(je.JID, last_status_msg, nil) - } - - if jid_in_map { - //if R3OnlineOnlyWithRecapInfo, we want a status update when coming online - if last_status_msg != nil && ! jid_data.Online && je.Online && jid_data.Wants == R3OnlineOnlyWithRecapInfo { - xmppout <- botdata.makeXMPPMessage(je.JID, last_status_msg, nil) - } - jid_data.Online = je.Online - if je.Wants > R3NoChange { - jid_data.Wants = je.Wants - } - botdata.realraum_jids_[simple_jid] = jid_data - botdata.realraum_jids_.saveTo(botdata.config_file_) - } else if je.Wants > R3NoChange { - botdata.realraum_jids_[simple_jid] = JidData{je.Online, je.Wants} - botdata.realraum_jids_.saveTo(botdata.config_file_) - } + if !je_still_open { + return + } + Debug_.Printf("handleEventsforXMPP<-jabber_events: %T %+v", je, je) + simple_jid := removeJIDResource(je.JID) + jid_data, jid_in_map := botdata.realraum_jids_[simple_jid] + + //send status if requested, even if user never changed any settings and thus is not in map + if last_status_msg != nil && je.StatusNow { + xmppout <- botdata.makeXMPPMessage(je.JID, last_status_msg, nil) + } + + if jid_in_map { + //if R3OnlineOnlyWithRecapInfo, we want a status update when coming online + if last_status_msg != nil && !jid_data.Online && je.Online && jid_data.Wants == R3OnlineOnlyWithRecapInfo { + xmppout <- botdata.makeXMPPMessage(je.JID, last_status_msg, nil) + } + jid_data.Online = je.Online + if je.Wants > R3NoChange { + jid_data.Wants = je.Wants + } + botdata.realraum_jids_[simple_jid] = jid_data + botdata.realraum_jids_.saveTo(botdata.config_file_) + } else if je.Wants > R3NoChange { + botdata.realraum_jids_[simple_jid] = JidData{je.Online, je.Wants} + botdata.realraum_jids_.saveTo(botdata.config_file_) + } } } } func removeJIDResource(jid string) string { - var jidjid xmpp.JID - jidjid.Set(jid) - jidjid.Resource = "" - return jidjid.String() + var jidjid xmpp.JID + jidjid.Set(jid) + jidjid.Resource = "" + return jidjid.String() } func (botdata *XmppBot) isAuthenticated(jid string) bool { - authtime, in_map := botdata.jid_lastauthtime_[jid] - return in_map && time.Now().Unix() - authtime < botdata.auth_timeout_ + authtime, in_map := botdata.jid_lastauthtime_[jid] + return in_map && time.Now().Unix()-authtime < botdata.auth_timeout_ } const help_text_ string = "\n*auth** ...Enables you to use more commands.\n*time* ...Returns bot time." @@ -251,202 +254,244 @@ const help_text_auth string = "You are authorized to use the following commands: //~ var re_msg_auth_ *regexp.Regexp = regexp.MustCompile("auth\s+(\S+)") func (botdata *XmppBot) handleIncomingMessageDialog(inmsg xmpp.Message, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) { - if inmsg.Body == nil || inmsg.GetHeader() == nil { - return - } - bodytext :=inmsg.Body.Chardata - if botdata.isAuthenticated(inmsg.GetHeader().From) { - switch bodytext { - case "on", "*on*": - jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyInfo, false} - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while online." , "Your New Status") - case "off", "*off*": - jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NeverInfo, false} - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Do not receive anything." , "Your New Status") - case "on_with_recap", "*on_with_recap*": - jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyWithRecapInfo, false} - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while and current status on coming, online." , "Your New Status") - case "on_while_offline", "*on_while_offline*": - jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3AlwaysInfo, false} - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive all r3 status updates, even if you are offline." , "Your New Status") - case "debug": - jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3DebugInfo, false} - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Debug mode enabled" , "Your New Status") - case "bye", "Bye", "quit", "logout", "*bye*": - botdata.jid_lastauthtime_[inmsg.GetHeader().From] = 0 - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Bye Bye !" ,nil) - case "open","close": - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, I can't operate the door for you." ,nil) - case "status", "*status*": - jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoChange, true} - case "time", "*time*": - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil) - default: - //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata) - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil) - } - } else { - switch bodytext { - case "Hilfe","hilfe","help","Help","?","hallo","Hallo","Yes","yes","ja","ja bitte","bitte","sowieso": - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_, "Available Commands") - case botdata.auth_cmd_, botdata.auth_cmd2_: - botdata.jid_lastauthtime_[inmsg.GetHeader().From] = time.Now().Unix() - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil) - case "status", "*status*", "off", "*off*", "on", "*on*", "on_while_offline", "*on_while_offline*", "on_with_recap", "*on_with_recap*": - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, you need to be authorized to do that." , nil) - case "time", "*time*": - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil) - default: - //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata) - xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "A nice day to you too !\nDo you need \"help\" ?", nil) - } - } + if inmsg.Body == nil || inmsg.GetHeader() == nil { + return + } + bodytext_args := strings.Split(strings.Replace(inmsg.Body.Chardata, "*", " ", -1), " ") + for len(bodytext_args) > 1 && len(bodytext_args[0]) == 0 { + bodytext_args = bodytext_args[1:len(bodytext_args)] //get rid of empty first strings resulting from " text" + } + bodytext_lc_cmd := strings.ToLower(bodytext_args[0]) + if botdata.isAuthenticated(inmsg.GetHeader().From) { + switch bodytext_lc_cmd { + case "on": + jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyInfo, false} + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while online.", "Your New Status") + case "off": + jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NeverInfo, false} + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Do not receive anything.", "Your New Status") + case "on_with_recap": + jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyWithRecapInfo, false} + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while and current status on coming, online.", "Your New Status") + case "on_while_offline": + jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3AlwaysInfo, false} + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive all r3 status updates, even if you are offline.", "Your New Status") + case "debug": + jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3DebugInfo, false} + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Debug mode enabled", "Your New Status") + case "bye", "quit", "logout": + botdata.jid_lastauthtime_[inmsg.GetHeader().From] = 0 + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Bye Bye !", nil) + case "open", "close": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, I'm just weak software, not strong enough to operate the door for you.", nil) + case "status": + jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoChange, true} + case "time": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String(), nil) + case "ping": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Pong with auth", nil) + default: + //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata) + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil) + } + } else { + switch bodytext_lc_cmd { + case "hilfe", "help", "?", "hallo", "yes", "ja", "ja bitte", "bitte", "sowieso": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_, "Available Commands") + case "auth": + authindex := 1 + for len(bodytext_args) > authindex && len(bodytext_args[authindex]) == 0 { + authindex++ + } + if len(bodytext_args) > authindex && bodytext_args[authindex] == botdata.password_ { + botdata.jid_lastauthtime_[inmsg.GetHeader().From] = time.Now().Unix() + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil) + } + case "status", "off", "on", "on_while_offline", "on_with_recap": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, you need to be authorized to do that.", nil) + case "time": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String(), nil) + case "ping": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Pong", nil) + case "": + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "You're a quiet one, aren't you?", nil) + default: + //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata) + xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "A nice day to you too !\nDo you need \"help\" ?", nil) + } + } } -func (botdata *XmppBot) handleIncomingXMPPStanzas(xmppin <- chan xmpp.Stanza, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) { - - defer func() { - if x := recover(); x != nil { - Syslog_.Printf("handleIncomingXMPPStanzas: run time panic: %v", x) - } - close(jabber_events) - }() - - var error_count int = 0 - var incoming_stanza interface{} - - handleStanzaError := func() bool { - error_count++ - if error_count > 15 { - Syslog_.Println("handleIncomingXMPPStanzas: too many errors in series.. bailing out") - botdata.StopBot() - return true - } - return false - } - - for incoming_stanza = range xmppin { - switch stanza := incoming_stanza.(type) { - case *xmpp.Message: - if stanza.GetHeader() == nil { continue } - if stanza.Type == "error" || stanza.Error != nil { - Syslog_.Printf("XMPP %T Error: %s", stanza, stanza) - if stanza.Error.Type == "cancel" { - // asume receipient not reachable -> disable - Syslog_.Printf("Error reaching %s. Disabling user, please reenable manually", stanza.From) - jabber_events <- JabberEvent{stanza.From, false, R3NeverInfo, false} - continue - } - if handleStanzaError() { return } - continue - } else { error_count = 0 } - botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events) - case *xmpp.Presence: - if stanza.GetHeader() == nil { continue } - if stanza.Type == "error" || stanza.Error != nil { - Syslog_.Printf("XMPP %T Error: %s", stanza, stanza) - if handleStanzaError() { return } - continue - } else { error_count = 0 } - switch stanza.GetHeader().Type { - case "subscribe": - xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed", "", "") - jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false} - xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribe", "", "") - case "unsubscribe", "unsubscribed": - jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NeverInfo, false} - botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout - xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "unsubscribe", "","") - case "unavailable": - jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NoChange, false} - botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout - default: - jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false} - } - - case *xmpp.Iq: - if stanza.GetHeader() == nil { continue } - if stanza.Type == "error" || stanza.Error != nil { - Syslog_.Printf("XMPP %T Error: %s", stanza, stanza) - if handleStanzaError() { return } - continue - } else { error_count = 0 } - - if HandleServerToClientPing(stanza, xmppout) {continue} //if true then routine handled it and we can continue - Debug_.Printf("Unhandled Iq: %s", stanza) - } - } +func (botdata *XmppBot) handleIncomingXMPPStanzas(xmppin <-chan xmpp.Stanza, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) { + + defer func() { + if x := recover(); x != nil { + Syslog_.Printf("handleIncomingXMPPStanzas: run time panic: %v", x) + } + }() + + var error_count int = 0 + var incoming_stanza interface{} + + handleStanzaError := func() bool { + error_count++ + if error_count > 15 { + Syslog_.Println("handleIncomingXMPPStanzas: too many errors in series.. bailing out") + botdata.StopBot() + return true + } + return false + } + + for incoming_stanza = range xmppin { + switch stanza := incoming_stanza.(type) { + case *xmpp.Message: + if stanza.GetHeader() == nil { + continue + } + if stanza.Type == "error" || stanza.Error != nil { + Syslog_.Printf("XMPP %T Error: %s", stanza, stanza) + if stanza.Error.Type == "cancel" { + // asume receipient not reachable -> disable + Syslog_.Printf("Error reaching %s. Disabling user, please reenable manually", stanza.From) + jabber_events <- JabberEvent{stanza.From, false, R3NeverInfo, false} + continue + } + if handleStanzaError() { + return + } + continue + } else { + error_count = 0 + } + botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events) + case *xmpp.Presence: + if stanza.GetHeader() == nil { + continue + } + if stanza.Type == "error" || stanza.Error != nil { + Syslog_.Printf("XMPP %T Error: %s", stanza, stanza) + if handleStanzaError() { + return + } + continue + } else { + error_count = 0 + } + switch stanza.GetHeader().Type { + case "subscribe": + xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed", "", "") + jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false} + xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribe", "", "") + case "unsubscribe", "unsubscribed": + jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NeverInfo, false} + botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout + xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "unsubscribe", "", "") + case "unavailable": + jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NoChange, false} + botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout + default: + jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false} + } + + case *xmpp.Iq: + if stanza.GetHeader() == nil { + continue + } + if stanza.Type == "error" || stanza.Error != nil { + Syslog_.Printf("XMPP %T Error: %s", stanza, stanza) + if handleStanzaError() { + return + } + continue + } else { + error_count = 0 + } + + if HandleServerToClientPing(stanza, xmppout) { + continue + } //if true then routine handled it and we can continue + Debug_.Printf("Unhandled Iq: %s", stanza) + } + } } func init() { - //~ xmpp.Debug = &XMPPDebugLogger{} - xmpp.Info = &XMPPDebugLogger{} - xmpp.Warn = &XMPPLogger{} + //~ xmpp.Debug = &XMPPDebugLogger{} + xmpp.Info = &XMPPDebugLogger{} + xmpp.Warn = &XMPPLogger{} } func NewStartedBot(loginjid, loginpwd, password, state_save_dir string, insecuretls bool) (*XmppBot, chan interface{}, error) { - var err error - botdata := new(XmppBot) - - botdata.realraum_jids_ = make(map[string]JidData, 1) - botdata.jid_lastauthtime_ = make(map[string]int64,1) - botdata.auth_cmd_ = "auth " + password - botdata.auth_cmd2_ = "*auth*" + password+"*" - botdata.my_jid_ = loginjid - botdata.my_login_password_ = loginpwd - botdata.auth_timeout_ = 3600*2 - - botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json") - - xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls} - botdata.realraum_jids_.loadFrom(botdata.config_file_) - - client_jid := new(xmpp.JID) - client_jid.Set(botdata.my_jid_) - botdata.xmppclient_, err = xmpp.NewClient(client_jid, botdata.my_login_password_, nil) - if err != nil { - Syslog_.Println("Error connecting to xmpp server", err) - return nil, nil, err - } - - err = botdata.xmppclient_.StartSession(true, &xmpp.Presence{}) - if err != nil { - Syslog_.Println("'Error StartSession:", err) - return nil, nil, err - } - - roster := xmpp.Roster(botdata.xmppclient_) - for _, entry := range roster { - Debug_.Print(entry) - if entry.Subscription == "from" { - botdata.xmppclient_.Out <- botdata.makeXMPPPresence(entry.Jid, "subscribe", "","") - } - if entry.Subscription == "none" { - delete(botdata.realraum_jids_, entry.Jid) - } - } - - presence_events := make(chan interface{},1) - jabber_events := make(chan JabberEvent,1) - - go botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events) - go botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events) - - botdata.presence_events_ = &presence_events - - return botdata, presence_events, nil + var err error + botdata := new(XmppBot) + + botdata.realraum_jids_ = make(map[string]JidData, 1) + botdata.jid_lastauthtime_ = make(map[string]int64, 1) + botdata.my_jid_ = loginjid + botdata.my_login_password_ = loginpwd + botdata.password_ = password + botdata.auth_timeout_ = 3600 * 2 + + botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json") + + xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls} + botdata.realraum_jids_.loadFrom(botdata.config_file_) + + client_jid := new(xmpp.JID) + client_jid.Set(botdata.my_jid_) + botdata.xmppclient_, err = xmpp.NewClient(client_jid, botdata.my_login_password_, nil) + if err != nil { + Syslog_.Println("Error connecting to xmpp server", err) + return nil, nil, err + } + + err = botdata.xmppclient_.StartSession(true, &xmpp.Presence{}) + if err != nil { + Syslog_.Println("'Error StartSession:", err) + return nil, nil, err + } + + roster := xmpp.Roster(botdata.xmppclient_) + for _, entry := range roster { + Debug_.Print(entry) + if entry.Subscription == "from" { + botdata.xmppclient_.Out <- botdata.makeXMPPPresence(entry.Jid, "subscribe", "", "") + } + if entry.Subscription == "none" { + delete(botdata.realraum_jids_, entry.Jid) + } + } + + presence_events := make(chan interface{}, 1) + jabber_events := make(chan JabberEvent, 1) + + go func() { + for { //auto recover from panic + botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events) + } + }() + go func() { + for { //auto recover from panic + botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events) + } + }() + + botdata.presence_events_ = &presence_events + + return botdata, presence_events, nil } func (botdata *XmppBot) StopBot() { - Syslog_.Println("Stopping XMPP Bot") - if botdata.xmppclient_ != nil { - close(botdata.xmppclient_.Out) - } - if botdata.presence_events_ != nil { - *botdata.presence_events_ <- false - close(*botdata.presence_events_) - } - botdata.config_file_ = "" - botdata.realraum_jids_ = nil - botdata.xmppclient_ = nil + Syslog_.Println("Stopping XMPP Bot") + if botdata.xmppclient_ != nil { + close(botdata.xmppclient_.Out) + } + if botdata.presence_events_ != nil { + *botdata.presence_events_ <- false + close(*botdata.presence_events_) + } + botdata.config_file_ = "" + botdata.realraum_jids_ = nil + botdata.xmppclient_ = nil } -- 1.7.10.4