1 // (c) Bernhard Tittelbach, 2013
6 xmpp "code.google.com/p/goexmpp"
14 func (botdata *XmppBot) makeXMPPMessage(to string, message interface{}, subject interface{}) *xmpp.Message {
15 xmppmsgheader := xmpp.Header{To: to,
16 From: botdata.my_jid_,
22 Nested: make([]interface{},0)}
24 var msgsubject, msgbody *xmpp.Generic
25 switch cast_msg := message.(type) {
27 msgbody = &xmpp.Generic{Chardata: cast_msg}
29 msgbody = &xmpp.Generic{Chardata: *cast_msg}
33 msgbody = &xmpp.Generic{}
35 switch cast_msg := subject.(type) {
37 msgsubject = &xmpp.Generic{Chardata: cast_msg}
39 msgsubject = &xmpp.Generic{Chardata: *cast_msg}
43 msgsubject = &xmpp.Generic{}
45 return &xmpp.Message{Header: xmppmsgheader , Subject: msgsubject, Body: msgbody, Thread: &xmpp.Generic{}}
48 func (botdata *XmppBot) makeXMPPPresence(to, ptype, show, status string) *xmpp.Presence {
49 xmppmsgheader := xmpp.Header{To: to,
50 From: botdata.my_jid_,
56 Nested: make([]interface{},0)}
57 var gen_show, gen_status *xmpp.Generic
61 gen_show = &xmpp.Generic{Chardata: show}
66 gen_status = &xmpp.Generic{Chardata: status}
68 return &xmpp.Presence{Header: xmppmsgheader, Show: gen_show, Status: gen_status}
74 R3NoChange R3JIDDesire = -1
75 R3NeverInfo R3JIDDesire = iota // ignore first value by assigning to blank identifier
77 R3OnlineOnlyWithRecapInfo
83 ShowOnline string = ""
84 ShowAway string = "away"
85 ShowNotAvailabe string = "xa"
86 ShowDoNotDisturb string = "dnd"
87 ShowFreeForChat string = "chat"
95 type JabberEvent struct {
102 type XMPPMsgEvent struct {
104 DistributeLevel R3JIDDesire
105 RememberAsStatus bool
108 type XMPPStatusEvent struct {
113 type RealraumXmppNotifierConfig map[string]JidData
115 type XmppBot struct {
116 jid_lastauthtime_ map[string]int64
117 realraum_jids_ RealraumXmppNotifierConfig
124 my_login_password_ string
125 xmppclient_ *xmpp.Client
126 presence_events_ *chan interface{}
130 func (data RealraumXmppNotifierConfig) saveTo(filepath string) () {
131 fh, err := os.Create(filepath)
137 enc := json.NewEncoder(fh)
138 if err = enc.Encode(&data); err != nil {
144 func (data RealraumXmppNotifierConfig) loadFrom(filepath string) () {
145 fh, err := os.Open(filepath)
151 dec := json.NewDecoder(fh)
152 if err = dec.Decode(&data); err != nil {
156 for to, jiddata := range data {
157 jiddata.Online = false
162 func (botdata *XmppBot) handleEventsforXMPP(xmppout chan <- xmpp.Stanza, presence_events <- chan interface{}, jabber_events <- chan JabberEvent) {
163 var last_status_msg *string
166 if x := recover(); x != nil {
167 Syslog_.Printf("handleEventsforXMPP: run time panic: %v", x)
168 //FIXME: signal that xmpp bot has crashed
170 for _ = range(jabber_events) {} //cleanout jabber_events queue
175 case pe, pe_still_open := <-presence_events:
176 if ! pe_still_open { return }
177 Debug_.Printf("handleEventsforXMPP<-presence_events: %T %+v", pe, pe)
178 switch pec := pe.(type) {
183 for to, jiddata := range botdata.realraum_jids_ {
184 if jiddata.Wants >= R3DebugInfo {
185 xmppout <- botdata.makeXMPPMessage(to, pec, nil)
189 case XMPPStatusEvent:
190 xmppout <- botdata.makeXMPPPresence("", "", pec.Show, pec.Status)
193 if pec.RememberAsStatus {
194 last_status_msg = &pec.Msg
196 for to, jiddata := range botdata.realraum_jids_ {
197 if jiddata.Wants >= pec.DistributeLevel && ((jiddata.Wants >= R3OnlineOnlyInfo && jiddata.Online) || jiddata.Wants >= R3AlwaysInfo) {
198 xmppout <- botdata.makeXMPPMessage(to, pec.Msg, nil)
202 Debug_.Println("handleEventsforXMPP<-presence_events: unknown type received: quitting")
206 case je, je_still_open := <-jabber_events:
207 if ! je_still_open { return }
208 Debug_.Printf("handleEventsforXMPP<-jabber_events: %T %+v", je, je)
209 simple_jid := removeJIDResource(je.JID)
210 jid_data, jid_in_map := botdata.realraum_jids_[simple_jid]
212 //send status if requested, even if user never changed any settings and thus is not in map
213 if last_status_msg != nil && je.StatusNow {
214 xmppout <- botdata.makeXMPPMessage(je.JID, last_status_msg, nil)
218 //if R3OnlineOnlyWithRecapInfo, we want a status update when coming online
219 if last_status_msg != nil && ! jid_data.Online && je.Online && jid_data.Wants == R3OnlineOnlyWithRecapInfo {
220 xmppout <- botdata.makeXMPPMessage(je.JID, last_status_msg, nil)
222 jid_data.Online = je.Online
223 if je.Wants > R3NoChange {
224 jid_data.Wants = je.Wants
226 botdata.realraum_jids_[simple_jid] = jid_data
227 botdata.realraum_jids_.saveTo(botdata.config_file_)
228 } else if je.Wants > R3NoChange {
229 botdata.realraum_jids_[simple_jid] = JidData{je.Online, je.Wants}
230 botdata.realraum_jids_.saveTo(botdata.config_file_)
236 func removeJIDResource(jid string) string {
240 return jidjid.String()
243 func (botdata *XmppBot) isAuthenticated(jid string) bool {
244 authtime, in_map := botdata.jid_lastauthtime_[jid]
245 return in_map && time.Now().Unix() - authtime < botdata.auth_timeout_
248 const help_text_ string = "\n*auth*<password>* ...Enables you to use more commands.\n*time* ...Returns bot time."
249 const help_text_auth string = "You are authorized to use the following commands:\n*off* ...You will no longer receive notifications.\n*on* ...You will be notified of r3 status changes while you are online.\n*on_with_recap* ...Like *on* but additionally you will receive the current status when you come online.\n*on_while_offline* ...You will receive all r3 status changes, wether you are online or offline.\n*status* ...Use it to query the current status.\n*time* ...Returns bot time.\n*bye* ...Logout."
251 //~ var re_msg_auth_ *regexp.Regexp = regexp.MustCompile("auth\s+(\S+)")
253 func (botdata *XmppBot) handleIncomingMessageDialog(inmsg xmpp.Message, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
254 if inmsg.Body == nil || inmsg.GetHeader() == nil {
257 bodytext :=inmsg.Body.Chardata
258 if botdata.isAuthenticated(inmsg.GetHeader().From) {
261 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyInfo, false}
262 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while online." , "Your New Status")
264 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NeverInfo, false}
265 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Do not receive anything." , "Your New Status")
266 case "on_with_recap", "*on_with_recap*":
267 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyWithRecapInfo, false}
268 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while and current status on coming, online." , "Your New Status")
269 case "on_while_offline", "*on_while_offline*":
270 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3AlwaysInfo, false}
271 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive all r3 status updates, even if you are offline." , "Your New Status")
273 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3DebugInfo, false}
274 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Debug mode enabled" , "Your New Status")
275 case "bye", "Bye", "quit", "logout", "*bye*":
276 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = 0
277 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Bye Bye !" ,nil)
279 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, I can't operate the door for you." ,nil)
280 case "status", "*status*":
281 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoChange, true}
282 case "time", "*time*":
283 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
285 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
286 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
290 case "Hilfe","hilfe","help","Help","?","hallo","Hallo","Yes","yes","ja","ja bitte","bitte","sowieso":
291 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_, "Available Commands")
292 case botdata.auth_cmd_, botdata.auth_cmd2_:
293 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = time.Now().Unix()
294 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
295 case "status", "*status*", "off", "*off*", "on", "*on*", "on_while_offline", "*on_while_offline*", "on_with_recap", "*on_with_recap*":
296 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, you need to be authorized to do that." , nil)
297 case "time", "*time*":
298 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
300 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
301 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "A nice day to you too !\nDo you need \"help\" ?", nil)
306 func (botdata *XmppBot) handleIncomingXMPPStanzas(xmppin <- chan xmpp.Stanza, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
309 if x := recover(); x != nil {
310 Syslog_.Printf("handleIncomingXMPPStanzas: run time panic: %v", x)
315 var error_count int = 0
316 var incoming_stanza interface{}
318 handleStanzaError := func() bool {
320 if error_count > 15 {
321 Syslog_.Println("handleIncomingXMPPStanzas: too many errors in series.. bailing out")
328 for incoming_stanza = range xmppin {
329 switch stanza := incoming_stanza.(type) {
331 if stanza.GetHeader() == nil { continue }
332 if stanza.Type == "error" || stanza.Error != nil {
333 Syslog_.Printf("XMPP %T Error: %s", stanza, stanza)
334 if stanza.Error.Type == "cancel" {
335 // asume receipient not reachable -> disable
336 Syslog_.Printf("Error reaching %s. Disabling user, please reenable manually", stanza.From)
337 jabber_events <- JabberEvent{stanza.From, false, R3NeverInfo, false}
340 if handleStanzaError() { return }
342 } else { error_count = 0 }
343 botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events)
345 if stanza.GetHeader() == nil { continue }
346 if stanza.Type == "error" || stanza.Error != nil {
347 Syslog_.Printf("XMPP %T Error: %s", stanza, stanza)
348 if handleStanzaError() { return }
350 } else { error_count = 0 }
351 switch stanza.GetHeader().Type {
353 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed", "", "")
354 jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
355 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribe", "", "")
356 case "unsubscribe", "unsubscribed":
357 jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NeverInfo, false}
358 botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
359 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "unsubscribe", "","")
361 jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NoChange, false}
362 botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
364 jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
368 if stanza.GetHeader() == nil { continue }
369 if stanza.Type == "error" || stanza.Error != nil {
370 Syslog_.Printf("XMPP %T Error: %s", stanza, stanza)
371 if handleStanzaError() { return }
373 } else { error_count = 0 }
375 if HandleServerToClientPing(stanza, xmppout) {continue} //if true then routine handled it and we can continue
376 Debug_.Printf("Unhandled Iq: %s", stanza)
382 //~ xmpp.Debug = &XMPPDebugLogger{}
383 xmpp.Info = &XMPPDebugLogger{}
384 xmpp.Warn = &XMPPLogger{}
387 func NewStartedBot(loginjid, loginpwd, password, state_save_dir string, insecuretls bool) (*XmppBot, chan interface{}, error) {
389 botdata := new(XmppBot)
391 botdata.realraum_jids_ = make(map[string]JidData, 1)
392 botdata.jid_lastauthtime_ = make(map[string]int64,1)
393 botdata.auth_cmd_ = "auth " + password
394 botdata.auth_cmd2_ = "*auth*" + password+"*"
395 botdata.my_jid_ = loginjid
396 botdata.my_login_password_ = loginpwd
397 botdata.auth_timeout_ = 3600*2
399 botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json")
401 xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls}
402 botdata.realraum_jids_.loadFrom(botdata.config_file_)
404 client_jid := new(xmpp.JID)
405 client_jid.Set(botdata.my_jid_)
406 botdata.xmppclient_, err = xmpp.NewClient(client_jid, botdata.my_login_password_, nil)
408 Syslog_.Println("Error connecting to xmpp server", err)
412 err = botdata.xmppclient_.StartSession(true, &xmpp.Presence{})
414 Syslog_.Println("'Error StartSession:", err)
418 roster := xmpp.Roster(botdata.xmppclient_)
419 for _, entry := range roster {
421 if entry.Subscription == "from" {
422 botdata.xmppclient_.Out <- botdata.makeXMPPPresence(entry.Jid, "subscribe", "","")
424 if entry.Subscription == "none" {
425 delete(botdata.realraum_jids_, entry.Jid)
429 presence_events := make(chan interface{},1)
430 jabber_events := make(chan JabberEvent,1)
432 go botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events)
433 go botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events)
435 botdata.presence_events_ = &presence_events
437 return botdata, presence_events, nil
440 func (botdata *XmppBot) StopBot() {
441 Syslog_.Println("Stopping XMPP Bot")
442 if botdata.xmppclient_ != nil {
443 close(botdata.xmppclient_.Out)
445 if botdata.presence_events_ != nil {
446 *botdata.presence_events_ <- false
447 close(*botdata.presence_events_)
449 botdata.config_file_ = ""
450 botdata.realraum_jids_ = nil
451 botdata.xmppclient_ = nil