1 // (c) Bernhard Tittelbach, 2013
6 xmpp "code.google.com/p/goexmpp"
14 //~ type StdLogger struct {
17 //~ func (s *StdLogger) Log(v ...interface{}) {
21 //~ func (s *StdLogger) Logf(fmt string, v ...interface{}) {
22 //~ log.Printf(fmt, v...)
26 func (botdata *XmppBot) makeXMPPMessage(to string, message interface{}, subject interface{}) *xmpp.Message {
27 xmppmsgheader := xmpp.Header{To: to,
28 From: botdata.my_jid_,
34 Nested: make([]interface{},0)}
36 var msgsubject, msgbody *xmpp.Generic
37 switch cast_msg := message.(type) {
39 msgbody = &xmpp.Generic{Chardata: cast_msg}
41 msgbody = &xmpp.Generic{Chardata: *cast_msg}
45 msgbody = &xmpp.Generic{}
47 switch cast_msg := subject.(type) {
49 msgsubject = &xmpp.Generic{Chardata: cast_msg}
51 msgsubject = &xmpp.Generic{Chardata: *cast_msg}
55 msgsubject = &xmpp.Generic{}
57 return &xmpp.Message{Header: xmppmsgheader , Subject: msgsubject, Body: msgbody, Thread: &xmpp.Generic{}}
60 func (botdata *XmppBot) makeXMPPPresence(to, ptype, show, status string) *xmpp.Presence {
61 xmppmsgheader := xmpp.Header{To: to,
62 From: botdata.my_jid_,
68 Nested: make([]interface{},0)}
69 var gen_show, gen_status *xmpp.Generic
73 gen_show = &xmpp.Generic{Chardata: show}
78 gen_status = &xmpp.Generic{Chardata: status}
80 return &xmpp.Presence{Header: xmppmsgheader, Show: gen_show, Status: gen_status}
86 R3NoChange R3JIDDesire = -1
87 R3NeverInfo R3JIDDesire = iota // ignore first value by assigning to blank identifier
89 R3OnlineOnlyWithRecapInfo
95 ShowOnline string = ""
96 ShowAway string = "away"
97 ShowNotAvailabe string = "xa"
98 ShowDoNotDisturb string = "dnd"
99 ShowFreeForChat string = "chat"
102 type JidData struct {
107 type JabberEvent struct {
114 type XMPPMsgEvent struct {
116 DistributeLevel R3JIDDesire
117 RememberAsStatus bool
120 type XMPPStatusEvent struct {
125 type RealraumXmppNotifierConfig map[string]JidData
127 type XmppBot struct {
128 jid_lastauthtime_ map[string]int64
129 realraum_jids_ RealraumXmppNotifierConfig
136 my_login_password_ string
137 xmppclient_ *xmpp.Client
138 presence_events_ *chan interface{}
142 func (data RealraumXmppNotifierConfig) saveTo(filepath string) () {
143 fh, err := os.Create(filepath)
149 enc := json.NewEncoder(fh)
150 if err = enc.Encode(&data); err != nil {
156 func (data RealraumXmppNotifierConfig) loadFrom(filepath string) () {
157 fh, err := os.Open(filepath)
163 dec := json.NewDecoder(fh)
164 if err = dec.Decode(&data); err != nil {
168 for to, jiddata := range data {
169 jiddata.Online = false
176 //~ logger := &StdLogger{}
177 //~ xmpp.Debug = logger
178 //~ xmpp.Info = logger
179 //~ xmpp.Warn = logger
182 func (botdata *XmppBot) handleEventsforXMPP(xmppout chan <- xmpp.Stanza, presence_events <- chan interface{}, jabber_events <- chan JabberEvent) {
183 var last_status_msg *string
186 if x := recover(); x != nil {
187 Syslog_.Printf("handleEventsforXMPP: run time panic: %v", x)
188 //FIXME: signal that xmpp bot has crashed
194 case pe, pe_still_open := <-presence_events:
195 if ! pe_still_open { break }
196 Debug_.Printf("handleEventsforXMPP<-presence_events: %T %+v", pe, pe)
197 switch pec := pe.(type) {
202 for to, jiddata := range botdata.realraum_jids_ {
203 if jiddata.Wants >= R3DebugInfo {
204 xmppout <- botdata.makeXMPPMessage(to, pec, nil)
208 case XMPPStatusEvent:
209 xmppout <- botdata.makeXMPPPresence("", "", pec.Show, pec.Status)
212 if pec.RememberAsStatus {
213 last_status_msg = &pec.Msg
215 for to, jiddata := range botdata.realraum_jids_ {
216 if jiddata.Wants >= pec.DistributeLevel && ((jiddata.Wants >= R3OnlineOnlyInfo && jiddata.Online) || jiddata.Wants >= R3AlwaysInfo) {
217 xmppout <- botdata.makeXMPPMessage(to, pec.Msg, nil)
224 case je, je_still_open := <-jabber_events:
225 if ! je_still_open { break }
226 Debug_.Printf("handleEventsforXMPP<-jabber_events: %T %+v", je, je)
227 simple_jid := removeJIDResource(je.JID)
228 jid_data, jid_in_map := botdata.realraum_jids_[simple_jid]
230 //send status if requested, even if user never changed any settings and thus is not in map
231 if last_status_msg != nil && je.StatusNow {
232 xmppout <- botdata.makeXMPPMessage(je.JID, last_status_msg, nil)
236 //if R3OnlineOnlyWithRecapInfo, we want a status update when coming online
237 if last_status_msg != nil && ! jid_data.Online && je.Online && jid_data.Wants == R3OnlineOnlyWithRecapInfo {
238 xmppout <- botdata.makeXMPPMessage(je.JID, last_status_msg, nil)
240 jid_data.Online = je.Online
241 if je.Wants > R3NoChange {
242 jid_data.Wants = je.Wants
244 botdata.realraum_jids_[simple_jid] = jid_data
245 botdata.realraum_jids_.saveTo(botdata.config_file_)
246 } else if je.Wants > R3NoChange {
247 botdata.realraum_jids_[simple_jid] = JidData{je.Online, je.Wants}
248 botdata.realraum_jids_.saveTo(botdata.config_file_)
254 func removeJIDResource(jid string) string {
258 return jidjid.String()
261 func (botdata *XmppBot) isAuthenticated(jid string) bool {
262 authtime, in_map := botdata.jid_lastauthtime_[jid]
263 return in_map && time.Now().Unix() - authtime < botdata.auth_timeout_
266 const help_text_ string = "\n*auth*<password>* ...Enables you to use more commands.\n*time* ...Returns bot time."
267 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."
269 //~ var re_msg_auth_ *regexp.Regexp = regexp.MustCompile("auth\s+(\S+)")
271 func (botdata *XmppBot) handleIncomingMessageDialog(inmsg xmpp.Message, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
272 if inmsg.Body == nil || inmsg.GetHeader() == nil {
275 bodytext :=inmsg.Body.Chardata
276 if botdata.isAuthenticated(inmsg.GetHeader().From) {
279 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyInfo, false}
280 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while online." , "Your New Status")
282 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NeverInfo, false}
283 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Do not receive anything." , "Your New Status")
284 case "on_with_recap", "*on_with_recap*":
285 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyWithRecapInfo, false}
286 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while and current status on coming, online." , "Your New Status")
287 case "on_while_offline", "*on_while_offline*":
288 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3AlwaysInfo, false}
289 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive all r3 status updates, even if you are offline." , "Your New Status")
291 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3DebugInfo, false}
292 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Debug mode enabled" , "Your New Status")
293 case "bye", "Bye", "quit", "logout", "*bye*":
294 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = 0
295 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Bye Bye !" ,nil)
297 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, I can't operate the door for you." ,nil)
298 case "status", "*status*":
299 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoChange, true}
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, help_text_auth, nil)
308 case "Hilfe","hilfe","help","Help","?","hallo","Hallo","Yes","yes","ja","ja bitte","bitte","sowieso":
309 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_, "Available Commands")
310 case botdata.auth_cmd_, botdata.auth_cmd2_:
311 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = time.Now().Unix()
312 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
313 case "status", "*status*", "off", "*off*", "on", "*on*", "on_while_offline", "*on_while_offline*", "on_with_recap", "*on_with_recap*":
314 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, you need to be authorized to do that." , nil)
315 case "time", "*time*":
316 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
318 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
319 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "A nice day to you too !\nDo you need \"help\" ?", nil)
324 func (botdata *XmppBot) handleIncomingXMPPStanzas(xmppin <- chan xmpp.Stanza, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
327 if x := recover(); x != nil {
328 Syslog_.Printf("handleIncomingXMPPStanzas: run time panic: %v", x)
333 var incoming_stanza interface{}
334 for incoming_stanza = range xmppin {
335 switch stanza := incoming_stanza.(type) {
337 botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events)
339 if stanza.GetHeader() == nil {
342 switch stanza.GetHeader().Type {
344 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed", "", "")
345 jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
346 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribe", "", "")
347 case "unsubscribe", "unsubscribed":
348 jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NeverInfo, false}
349 botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
350 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "unsubscribe", "","")
352 jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NoChange, false}
353 botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
355 jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
358 if stanza.GetHeader() == nil {
365 func NewStartedBot(loginjid, loginpwd, password, state_save_dir string, insecuretls bool) (*XmppBot, chan interface{}, error) {
367 botdata := new(XmppBot)
369 botdata.realraum_jids_ = make(map[string]JidData, 1)
370 botdata.jid_lastauthtime_ = make(map[string]int64,1)
371 botdata.auth_cmd_ = "auth " + password
372 botdata.auth_cmd2_ = "*auth*" + password+"*"
373 botdata.my_jid_ = loginjid
374 botdata.my_login_password_ = loginpwd
375 botdata.auth_timeout_ = 3600*2
377 botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json")
379 //~ logger := &StdLogger{}
380 //~ xmpp.Debug = logger
381 //~ xmpp.Info = logger
382 //~ xmpp.Warn = logger
384 xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls}
385 botdata.realraum_jids_.loadFrom(botdata.config_file_)
387 client_jid := new(xmpp.JID)
388 client_jid.Set(botdata.my_jid_)
389 botdata.xmppclient_, err = xmpp.NewClient(client_jid, botdata.my_login_password_, nil)
391 Syslog_.Println("Error connecting to xmpp server", err)
395 err = botdata.xmppclient_.StartSession(true, &xmpp.Presence{})
397 Syslog_.Println("'Error StartSession:", err)
401 roster := xmpp.Roster(botdata.xmppclient_)
402 for _, entry := range roster {
404 if entry.Subscription == "from" {
405 botdata.xmppclient_.Out <- botdata.makeXMPPPresence(entry.Jid, "subscribe", "","")
407 if entry.Subscription == "none" {
408 delete(botdata.realraum_jids_, entry.Jid)
412 presence_events := make(chan interface{},1)
413 jabber_events := make(chan JabberEvent,1)
415 go botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events)
416 go botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events)
418 botdata.presence_events_ = &presence_events
420 return botdata, presence_events, nil
423 func (botdata *XmppBot) StopBot() {
424 if botdata.xmppclient_ != nil {
425 close(botdata.xmppclient_.Out)
427 if botdata.presence_events_ != nil {
428 *botdata.presence_events_ <- false
429 close(*botdata.presence_events_)