4 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...)
25 func IfThenElseStr(c bool, strue, sfalse string) string {
26 if c {return strue} else {return sfalse}
29 func (botdata *XmppBot) makeXMPPMessage(to string, message interface{}, subject interface{}) *xmpp.Message {
30 xmppmsgheader := xmpp.Header{To: to,
31 From: botdata.my_jid_,
37 Nested: make([]interface{},0)}
39 var msgsubject, msgbody *xmpp.Generic
40 switch cast_msg := message.(type) {
42 msgbody = &xmpp.Generic{Chardata: cast_msg}
44 msgbody = &xmpp.Generic{Chardata: *cast_msg}
48 msgbody = &xmpp.Generic{}
50 switch cast_msg := subject.(type) {
52 msgsubject = &xmpp.Generic{Chardata: cast_msg}
54 msgsubject = &xmpp.Generic{Chardata: *cast_msg}
58 msgsubject = &xmpp.Generic{}
60 return &xmpp.Message{Header: xmppmsgheader , Subject: msgsubject, Body: msgbody, Thread: &xmpp.Generic{}}
63 func (botdata *XmppBot) makeXMPPPresence(to, ptype string) *xmpp.Presence {
64 xmppmsgheader := xmpp.Header{To: to,
65 From: botdata.my_jid_,
71 Nested: make([]interface{},0)}
72 return &xmpp.Presence{Header: xmppmsgheader}
78 R3NoChange R3JIDDesire = -1
79 R3NoInfo R3JIDDesire = iota // ignore first value by assigning to blank identifier
90 type JabberEvent struct {
97 type XMPPPresenceEvent struct {
106 type RealraumXmppNotifierConfig map[string]JidData
108 type XmppBot struct {
109 jid_lastauthtime_ map[string]int64
110 realraum_jids_ RealraumXmppNotifierConfig
117 my_login_password_ string
118 xmppclient_ *xmpp.Client
119 presence_events_ *chan interface{}
123 func (data RealraumXmppNotifierConfig) saveTo(filepath string) () {
124 fh, err := os.Create(filepath)
130 enc := json.NewEncoder(fh)
131 if err = enc.Encode(&data); err != nil {
137 func (data RealraumXmppNotifierConfig) loadFrom(filepath string) () {
138 fh, err := os.Open(filepath)
144 dec := json.NewDecoder(fh)
145 if err = dec.Decode(&data); err != nil {
149 for to, jiddata := range data {
150 jiddata.Online = false
157 //~ logger := &StdLogger{}
158 //~ xmpp.Debug = logger
159 //~ xmpp.Info = logger
160 //~ xmpp.Warn = logger
163 func composeMessage(pec *XMPPPresenceEvent, both bool) *string {
167 msg = "The button has been pressed ! Propably someone is bored and in need of company ! ;-)"
168 if both { msg += "\n"; } else {
169 msg += " --- " + time.Unix(pec.Ts,0).String()
173 msg += fmt.Sprintf("%s (Door is %s and %s and was last used by %s at %s)",
174 IfThenElseStr(pec.Present, "Somebody is present!" , "Everybody left."),
175 IfThenElseStr(pec.DoorLock, "locked","unlocked"),
176 IfThenElseStr(pec.DoorShut, "shut","ajar"),
178 time.Unix(pec.Ts,0).String())
182 func (botdata *XmppBot) handleEventsforXMPP(xmppout chan <- xmpp.Stanza, presence_events <- chan interface{}, jabber_events <- chan JabberEvent) {
184 var last_presence_event *XMPPPresenceEvent
190 case pe := <-presence_events:
191 switch pec := pe.(type) {
198 case XMPPPresenceEvent:
199 debug_msg = last_presence_event != nil && last_presence_event.Present == pec.Present
200 last_presence_event = &pec
201 msg = composeMessage(last_presence_event, false)
206 if msg == nil { continue }
208 for to, jiddata := range botdata.realraum_jids_ {
209 if debug_msg && jiddata.Wants < R3DebugInfo {
212 if (jiddata.Wants == R3NoOfflineInfo && jiddata.Online) || jiddata.Wants > R3NoOfflineInfo {
213 xmppout <- botdata.makeXMPPMessage(to, msg, nil)
217 case je := <-jabber_events:
218 simple_jid := removeJIDResource(je.JID)
219 jid_data, jid_in_map := botdata.realraum_jids_[simple_jid]
221 jid_data.Online = je.Online
222 if je.StatusNow && last_presence_event != nil {
223 xmppout <- botdata.makeXMPPMessage(je.JID, composeMessage(last_presence_event, true), nil)
225 if je.Wants > R3NoChange {
226 jid_data.Wants = je.Wants
228 botdata.realraum_jids_[simple_jid] = jid_data
229 botdata.realraum_jids_.saveTo(botdata.config_file_)
230 } else if je.Wants > R3NoChange {
231 botdata.realraum_jids_[simple_jid] = JidData{je.Online, je.Wants}
232 botdata.realraum_jids_.saveTo(botdata.config_file_)
238 func removeJIDResource(jid string) string {
242 return jidjid.String()
245 func (botdata *XmppBot) isAuthenticated(jid string) bool {
246 authtime, in_map := botdata.jid_lastauthtime_[jid]
247 //~ log.Println("isAuthenticated", in_map, authtime, time.Now().Unix(), auth_timeout_, time.Now().Unix() - authtime > auth_timeout_)
248 return in_map && time.Now().Unix() - authtime < botdata.auth_timeout_
251 const help_text_ string = "\n*auth*<password>* ...Enables you to use more commands.\n*time* ...Returns bot time."
252 const help_text_auth string = "You are authorized to use the following commands:\n*on* ...You will be notified of r3 status changes.\n*off* ...You will no longer recieve notifications.\n*on_while_offline* ...You will be notified of r3 status changes even if you are offline.\n*status* ...Query current status.\n*time* ...Returns bot time.\n*bye* ...Logout."
254 //~ var re_msg_auth_ *regexp.Regexp = regexp.MustCompile("auth\s+(\S+)")
256 func (botdata *XmppBot) handleIncomingMessageDialog(inmsg xmpp.Message, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
257 if inmsg.Body == nil || inmsg.GetHeader() == nil {
260 bodytext :=inmsg.Body.Chardata
261 //~ log.Println("Message Body:", bodytext)
262 if botdata.isAuthenticated(inmsg.GetHeader().From) {
265 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoOfflineInfo, false}
266 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 information while online" , "Your New Status")
268 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoInfo, false}
269 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Do not receive r3 information" , "Your New Status")
270 case "on_while_offline", "*on_while_offline*":
271 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3AllInfo, false}
272 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 information even while offline" , "Your New Status")
274 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3DebugInfo, false}
275 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Debug mode enabled" , "Your New Status")
276 case "bye", "Bye", "quit", "logout", "*bye*":
277 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = 0
278 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Bye Bye !" ,nil)
280 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, I can't operate the door for you." ,nil)
281 case "status", "*status*":
282 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoChange, true}
283 case "time", "*time*":
284 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
286 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
287 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
291 case "Hilfe","hilfe","help","Help","?","hallo","Hallo","Yes","yes","ja","ja bitte","bitte","sowieso":
292 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_, "Available Commands")
293 case botdata.auth_cmd_, botdata.auth_cmd2_:
294 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = time.Now().Unix()
295 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
296 case "status", "*status*", "off", "*off*", "on", "*on*", "on_while_offline", "*on_while_offline*":
297 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, you need to be authorized to do that." , nil)
298 case "time", "*time*":
299 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
301 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
302 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "A nice day to you too !\nDo you need \"help\" ?", nil)
307 func (botdata *XmppBot) handleIncomingXMPPStanzas(xmppin <- chan xmpp.Stanza, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
308 var incoming_stanza interface{}
309 for incoming_stanza = range xmppin {
310 switch stanza := incoming_stanza.(type) {
312 botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events)
314 if stanza.GetHeader() == nil {
317 switch stanza.GetHeader().Type {
319 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed")
320 jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
321 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribe")
322 case "unsubscribe", "unsubscribed":
323 jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NoInfo, false}
324 botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
325 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "unsubscribe")
327 jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NoChange, false}
328 botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
330 jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
333 if stanza.GetHeader() == nil {
340 func NewStartedBot(loginjid, loginpwd, password, state_save_dir string, insecuretls bool) (*XmppBot, chan interface{}, error) {
342 botdata := new(XmppBot)
344 botdata.realraum_jids_ = make(map[string]JidData, 1)
345 botdata.jid_lastauthtime_ = make(map[string]int64,1)
346 botdata.auth_cmd_ = "auth " + password
347 botdata.auth_cmd2_ = "*auth*" + password+"*"
348 botdata.my_jid_ = loginjid
349 botdata.my_login_password_ = loginpwd
350 botdata.auth_timeout_ = 3600*2
352 botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json")
354 //~ log.Println(botdata.config_file_)
356 //~ logger := &StdLogger{}
357 //~ xmpp.Debug = logger
358 //~ xmpp.Info = logger
359 //~ xmpp.Warn = logger
361 xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls}
362 botdata.realraum_jids_.loadFrom(botdata.config_file_)
364 client_jid := new(xmpp.JID)
365 client_jid.Set(botdata.my_jid_)
366 botdata.xmppclient_, err = xmpp.NewClient(client_jid, botdata.my_login_password_, nil)
368 log.Println("Error connecting to xmpp server", err)
372 err = botdata.xmppclient_.StartSession(true, &xmpp.Presence{})
374 log.Println("'Error StartSession:", err)
378 roster := xmpp.Roster(botdata.xmppclient_)
379 for _, entry := range roster {
380 if entry.Subscription == "from" {
381 botdata.xmppclient_.Out <- botdata.makeXMPPPresence(entry.Jid, "subscribe")
383 if entry.Subscription == "none" {
384 delete(botdata.realraum_jids_, entry.Jid)
388 presence_events := make(chan interface{},1)
389 jabber_events := make(chan JabberEvent,1)
391 go botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events)
392 go botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events)
394 botdata.presence_events_ = &presence_events
396 return botdata, presence_events, nil
399 func (botdata *XmppBot) StopBot() {
400 if botdata.xmppclient_ != nil {
401 close(botdata.xmppclient_.Out)
403 if botdata.presence_events_ != nil {
404 *botdata.presence_events_ <- false
405 close(*botdata.presence_events_)