1 // (c) Bernhard Tittelbach, 2013
6 xmpp "code.google.com/p/goexmpp"
15 //~ type StdLogger struct {
18 //~ func (s *StdLogger) Log(v ...interface{}) {
22 //~ func (s *StdLogger) Logf(fmt string, v ...interface{}) {
23 //~ log.Printf(fmt, v...)
27 func (botdata *XmppBot) makeXMPPMessage(to string, message interface{}, subject interface{}) *xmpp.Message {
28 xmppmsgheader := xmpp.Header{To: to,
29 From: botdata.my_jid_,
35 Nested: make([]interface{},0)}
37 var msgsubject, msgbody *xmpp.Generic
38 switch cast_msg := message.(type) {
40 msgbody = &xmpp.Generic{Chardata: cast_msg}
42 msgbody = &xmpp.Generic{Chardata: *cast_msg}
46 msgbody = &xmpp.Generic{}
48 switch cast_msg := subject.(type) {
50 msgsubject = &xmpp.Generic{Chardata: cast_msg}
52 msgsubject = &xmpp.Generic{Chardata: *cast_msg}
56 msgsubject = &xmpp.Generic{}
58 return &xmpp.Message{Header: xmppmsgheader , Subject: msgsubject, Body: msgbody, Thread: &xmpp.Generic{}}
61 func (botdata *XmppBot) makeXMPPPresence(to, ptype, show, status string) *xmpp.Presence {
62 xmppmsgheader := xmpp.Header{To: to,
63 From: botdata.my_jid_,
69 Nested: make([]interface{},0)}
70 var gen_show, gen_status *xmpp.Generic
74 gen_show = &xmpp.Generic{Chardata: show}
79 gen_status = &xmpp.Generic{Chardata: status}
81 return &xmpp.Presence{Header: xmppmsgheader, Show: gen_show, Status: gen_status}
87 R3NoChange R3JIDDesire = -1
88 R3NeverInfo R3JIDDesire = iota // ignore first value by assigning to blank identifier
90 R3OnlineOnlyWithRecapInfo
96 ShowOnline string = ""
97 ShowAway string = "away"
98 ShowNotAvailabe string = "xa"
99 ShowDoNotDisturb string = "dnd"
100 ShowFreeForChat string = "chat"
103 type JidData struct {
108 type JabberEvent struct {
115 type XMPPMsgEvent struct {
117 DistributeLevel R3JIDDesire
118 RememberAsStatus bool
121 type XMPPStatusEvent struct {
126 type RealraumXmppNotifierConfig map[string]JidData
128 type XmppBot struct {
129 jid_lastauthtime_ map[string]int64
130 realraum_jids_ RealraumXmppNotifierConfig
137 my_login_password_ string
138 xmppclient_ *xmpp.Client
139 presence_events_ *chan interface{}
143 func (data RealraumXmppNotifierConfig) saveTo(filepath string) () {
144 fh, err := os.Create(filepath)
150 enc := json.NewEncoder(fh)
151 if err = enc.Encode(&data); err != nil {
157 func (data RealraumXmppNotifierConfig) loadFrom(filepath string) () {
158 fh, err := os.Open(filepath)
164 dec := json.NewDecoder(fh)
165 if err = dec.Decode(&data); err != nil {
169 for to, jiddata := range data {
170 jiddata.Online = false
177 //~ logger := &StdLogger{}
178 //~ xmpp.Debug = logger
179 //~ xmpp.Info = logger
180 //~ xmpp.Warn = logger
183 func (botdata *XmppBot) handleEventsforXMPP(xmppout chan <- xmpp.Stanza, presence_events <- chan interface{}, jabber_events <- chan JabberEvent) {
184 var last_status_msg *string
187 if x := recover(); x != nil {
188 log.Printf("handleEventsforXMPP: run time panic: %v", x)
194 case pe := <-presence_events:
195 switch pec := pe.(type) {
200 for to, jiddata := range botdata.realraum_jids_ {
201 if jiddata.Wants >= R3DebugInfo {
202 xmppout <- botdata.makeXMPPMessage(to, pec, nil)
206 case XMPPStatusEvent:
207 xmppout <- botdata.makeXMPPPresence("", "", pec.Show, pec.Status)
210 if pec.RememberAsStatus {
211 last_status_msg = &pec.Msg
213 for to, jiddata := range botdata.realraum_jids_ {
214 if jiddata.Wants >= pec.DistributeLevel && ((jiddata.Wants >= R3OnlineOnlyInfo && jiddata.Online) || jiddata.Wants >= R3AlwaysInfo) {
215 xmppout <- botdata.makeXMPPMessage(to, pec.Msg, nil)
222 case je := <-jabber_events:
223 simple_jid := removeJIDResource(je.JID)
224 jid_data, jid_in_map := botdata.realraum_jids_[simple_jid]
226 if last_status_msg != nil && (je.StatusNow || (! jid_data.Online && je.Online && jid_data.Wants == R3OnlineOnlyWithRecapInfo) ) {
227 xmppout <- botdata.makeXMPPMessage(je.JID, last_status_msg, nil)
229 jid_data.Online = je.Online
230 if je.Wants > R3NoChange {
231 jid_data.Wants = je.Wants
233 botdata.realraum_jids_[simple_jid] = jid_data
234 botdata.realraum_jids_.saveTo(botdata.config_file_)
235 } else if je.Wants > R3NoChange {
236 botdata.realraum_jids_[simple_jid] = JidData{je.Online, je.Wants}
237 botdata.realraum_jids_.saveTo(botdata.config_file_)
243 func removeJIDResource(jid string) string {
247 return jidjid.String()
250 func (botdata *XmppBot) isAuthenticated(jid string) bool {
251 authtime, in_map := botdata.jid_lastauthtime_[jid]
252 //~ log.Println("isAuthenticated", in_map, authtime, time.Now().Unix(), auth_timeout_, time.Now().Unix() - authtime > auth_timeout_)
253 return in_map && time.Now().Unix() - authtime < botdata.auth_timeout_
256 const help_text_ string = "\n*auth*<password>* ...Enables you to use more commands.\n*time* ...Returns bot time."
257 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."
259 //~ var re_msg_auth_ *regexp.Regexp = regexp.MustCompile("auth\s+(\S+)")
261 func (botdata *XmppBot) handleIncomingMessageDialog(inmsg xmpp.Message, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
262 if inmsg.Body == nil || inmsg.GetHeader() == nil {
265 bodytext :=inmsg.Body.Chardata
266 //~ log.Println("Message Body:", bodytext)
267 if botdata.isAuthenticated(inmsg.GetHeader().From) {
270 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyInfo, false}
271 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while online." , "Your New Status")
273 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NeverInfo, false}
274 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Do not receive anything." , "Your New Status")
275 case "on_with_recap", "*on_with_recap*":
276 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyWithRecapInfo, false}
277 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while and current status on coming, online." , "Your New Status")
278 case "on_while_offline", "*on_while_offline*":
279 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3AlwaysInfo, false}
280 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive all r3 status updates, even if you are offline." , "Your New Status")
282 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3DebugInfo, false}
283 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Debug mode enabled" , "Your New Status")
284 case "bye", "Bye", "quit", "logout", "*bye*":
285 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = 0
286 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Bye Bye !" ,nil)
288 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, I can't operate the door for you." ,nil)
289 case "status", "*status*":
290 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoChange, true}
291 case "time", "*time*":
292 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
294 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
295 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
299 case "Hilfe","hilfe","help","Help","?","hallo","Hallo","Yes","yes","ja","ja bitte","bitte","sowieso":
300 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_, "Available Commands")
301 case botdata.auth_cmd_, botdata.auth_cmd2_:
302 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = time.Now().Unix()
303 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
304 case "status", "*status*", "off", "*off*", "on", "*on*", "on_while_offline", "*on_while_offline*", "on_with_recap", "*on_with_recap*":
305 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, you need to be authorized to do that." , nil)
306 case "time", "*time*":
307 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
309 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
310 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "A nice day to you too !\nDo you need \"help\" ?", nil)
315 func (botdata *XmppBot) handleIncomingXMPPStanzas(xmppin <- chan xmpp.Stanza, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
318 if x := recover(); x != nil {
319 log.Printf("handleIncomingXMPPStanzas: run time panic: %v", x)
324 var incoming_stanza interface{}
325 for incoming_stanza = range xmppin {
326 switch stanza := incoming_stanza.(type) {
328 botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events)
330 if stanza.GetHeader() == nil {
333 switch stanza.GetHeader().Type {
335 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed", "", "")
336 jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
337 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribe", "", "")
338 case "unsubscribe", "unsubscribed":
339 jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NeverInfo, false}
340 botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
341 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "unsubscribe", "","")
343 jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NoChange, false}
344 botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
346 jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
349 if stanza.GetHeader() == nil {
356 func NewStartedBot(loginjid, loginpwd, password, state_save_dir string, insecuretls bool) (*XmppBot, chan interface{}, error) {
358 botdata := new(XmppBot)
360 botdata.realraum_jids_ = make(map[string]JidData, 1)
361 botdata.jid_lastauthtime_ = make(map[string]int64,1)
362 botdata.auth_cmd_ = "auth " + password
363 botdata.auth_cmd2_ = "*auth*" + password+"*"
364 botdata.my_jid_ = loginjid
365 botdata.my_login_password_ = loginpwd
366 botdata.auth_timeout_ = 3600*2
368 botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json")
370 //~ log.Println(botdata.config_file_)
372 //~ logger := &StdLogger{}
373 //~ xmpp.Debug = logger
374 //~ xmpp.Info = logger
375 //~ xmpp.Warn = logger
377 xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls}
378 botdata.realraum_jids_.loadFrom(botdata.config_file_)
380 client_jid := new(xmpp.JID)
381 client_jid.Set(botdata.my_jid_)
382 botdata.xmppclient_, err = xmpp.NewClient(client_jid, botdata.my_login_password_, nil)
384 log.Println("Error connecting to xmpp server", err)
388 err = botdata.xmppclient_.StartSession(true, &xmpp.Presence{})
390 log.Println("'Error StartSession:", err)
394 roster := xmpp.Roster(botdata.xmppclient_)
395 for _, entry := range roster {
396 if entry.Subscription == "from" {
397 botdata.xmppclient_.Out <- botdata.makeXMPPPresence(entry.Jid, "subscribe", "","")
399 if entry.Subscription == "none" {
400 delete(botdata.realraum_jids_, entry.Jid)
404 presence_events := make(chan interface{},1)
405 jabber_events := make(chan JabberEvent,1)
407 go botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events)
408 go botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events)
410 botdata.presence_events_ = &presence_events
412 return botdata, presence_events, nil
415 func (botdata *XmppBot) StopBot() {
416 if botdata.xmppclient_ != nil {
417 close(botdata.xmppclient_.Out)
419 if botdata.presence_events_ != nil {
420 *botdata.presence_events_ <- false
421 close(*botdata.presence_events_)