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 if inmsg.Type == "error" || inmsg.Error != nil {
258 Syslog_.Printf("XMPP Message Error: %s", inmsg.Error.Error())
260 bodytext :=inmsg.Body.Chardata
261 if botdata.isAuthenticated(inmsg.GetHeader().From) {
264 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyInfo, false}
265 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while online." , "Your New Status")
267 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NeverInfo, false}
268 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Do not receive anything." , "Your New Status")
269 case "on_with_recap", "*on_with_recap*":
270 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyWithRecapInfo, false}
271 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while and current status on coming, online." , "Your New Status")
272 case "on_while_offline", "*on_while_offline*":
273 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3AlwaysInfo, false}
274 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive all r3 status updates, even if you are offline." , "Your New Status")
276 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3DebugInfo, false}
277 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Debug mode enabled" , "Your New Status")
278 case "bye", "Bye", "quit", "logout", "*bye*":
279 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = 0
280 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Bye Bye !" ,nil)
282 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, I can't operate the door for you." ,nil)
283 case "status", "*status*":
284 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoChange, true}
285 case "time", "*time*":
286 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
288 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
289 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
293 case "Hilfe","hilfe","help","Help","?","hallo","Hallo","Yes","yes","ja","ja bitte","bitte","sowieso":
294 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_, "Available Commands")
295 case botdata.auth_cmd_, botdata.auth_cmd2_:
296 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = time.Now().Unix()
297 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
298 case "status", "*status*", "off", "*off*", "on", "*on*", "on_while_offline", "*on_while_offline*", "on_with_recap", "*on_with_recap*":
299 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, you need to be authorized to do that." , nil)
300 case "time", "*time*":
301 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
303 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
304 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "A nice day to you too !\nDo you need \"help\" ?", nil)
309 func (botdata *XmppBot) handleIncomingXMPPStanzas(xmppin <- chan xmpp.Stanza, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
312 if x := recover(); x != nil {
313 Syslog_.Printf("handleIncomingXMPPStanzas: run time panic: %v", x)
318 var incoming_stanza interface{}
319 for incoming_stanza = range xmppin {
320 switch stanza := incoming_stanza.(type) {
322 botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events)
324 if stanza.GetHeader() == nil { continue }
325 if stanza.Type == "error" || stanza.Error != nil {
326 Syslog_.Printf("XMPP Presence Error: %s", stanza.Error.Error())
328 switch stanza.GetHeader().Type {
330 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed", "", "")
331 jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
332 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribe", "", "")
333 case "unsubscribe", "unsubscribed":
334 jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NeverInfo, false}
335 botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
336 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "unsubscribe", "","")
338 jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NoChange, false}
339 botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
341 jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
344 if stanza.GetHeader() == nil { continue }
345 if stanza.Type == "error" || stanza.Error != nil {
346 Syslog_.Printf("XMPP Iq Error: %s", stanza.Error.Error())
348 if HandleServerToClientPing(stanza, xmppout) {continue} //if true then routine handled it and we can continue
349 Debug_.Printf("Unhandled Iq: %s", stanza)
355 //~ xmpp.Debug = &XMPPDebugLogger{}
356 xmpp.Info = &XMPPDebugLogger{}
357 xmpp.Warn = &XMPPLogger{}
360 func NewStartedBot(loginjid, loginpwd, password, state_save_dir string, insecuretls bool) (*XmppBot, chan interface{}, error) {
362 botdata := new(XmppBot)
364 botdata.realraum_jids_ = make(map[string]JidData, 1)
365 botdata.jid_lastauthtime_ = make(map[string]int64,1)
366 botdata.auth_cmd_ = "auth " + password
367 botdata.auth_cmd2_ = "*auth*" + password+"*"
368 botdata.my_jid_ = loginjid
369 botdata.my_login_password_ = loginpwd
370 botdata.auth_timeout_ = 3600*2
372 botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json")
374 xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls}
375 botdata.realraum_jids_.loadFrom(botdata.config_file_)
377 client_jid := new(xmpp.JID)
378 client_jid.Set(botdata.my_jid_)
379 botdata.xmppclient_, err = xmpp.NewClient(client_jid, botdata.my_login_password_, nil)
381 Syslog_.Println("Error connecting to xmpp server", err)
385 err = botdata.xmppclient_.StartSession(true, &xmpp.Presence{})
387 Syslog_.Println("'Error StartSession:", err)
391 roster := xmpp.Roster(botdata.xmppclient_)
392 for _, entry := range roster {
394 if entry.Subscription == "from" {
395 botdata.xmppclient_.Out <- botdata.makeXMPPPresence(entry.Jid, "subscribe", "","")
397 if entry.Subscription == "none" {
398 delete(botdata.realraum_jids_, entry.Jid)
402 presence_events := make(chan interface{},1)
403 jabber_events := make(chan JabberEvent,1)
405 go botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events)
406 go botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events)
408 botdata.presence_events_ = &presence_events
410 return botdata, presence_events, nil
413 func (botdata *XmppBot) StopBot() {
414 Syslog_.Println("Stopping XMPP Bot")
415 if botdata.xmppclient_ != nil {
416 close(botdata.xmppclient_.Out)
418 if botdata.presence_events_ != nil {
419 *botdata.presence_events_ <- false
420 close(*botdata.presence_events_)
422 botdata.config_file_ = ""
423 botdata.realraum_jids_ = nil
424 botdata.xmppclient_ = nil