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 last_presence_event = &pec
200 msg = composeMessage(last_presence_event, false)
205 if msg == nil { continue }
207 for to, jiddata := range botdata.realraum_jids_ {
208 if debug_msg && jiddata.Wants < R3DebugInfo {
211 if (jiddata.Wants == R3NoOfflineInfo && jiddata.Online) || jiddata.Wants > R3NoOfflineInfo {
212 xmppout <- botdata.makeXMPPMessage(to, msg, nil)
216 case je := <-jabber_events:
217 simple_jid := removeJIDResource(je.JID)
218 jid_data, jid_in_map := botdata.realraum_jids_[simple_jid]
220 jid_data.Online = je.Online
221 if je.StatusNow && last_presence_event != nil {
222 xmppout <- botdata.makeXMPPMessage(je.JID, composeMessage(last_presence_event, true), nil)
224 if je.Wants > R3NoChange {
225 jid_data.Wants = je.Wants
227 botdata.realraum_jids_[simple_jid] = jid_data
228 botdata.realraum_jids_.saveTo(botdata.config_file_)
229 } else if je.Wants > R3NoChange {
230 botdata.realraum_jids_[simple_jid] = JidData{je.Online, je.Wants}
231 botdata.realraum_jids_.saveTo(botdata.config_file_)
237 func removeJIDResource(jid string) string {
241 return jidjid.String()
244 func (botdata *XmppBot) isAuthenticated(jid string) bool {
245 authtime, in_map := botdata.jid_lastauthtime_[jid]
246 //~ log.Println("isAuthenticated", in_map, authtime, time.Now().Unix(), auth_timeout_, time.Now().Unix() - authtime > auth_timeout_)
247 return in_map && time.Now().Unix() - authtime < botdata.auth_timeout_
250 const help_text_ string = "\n*auth*<password>* ...Enables you to use more commands.\n*time* ...Returns bot time."
251 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."
253 //~ var re_msg_auth_ *regexp.Regexp = regexp.MustCompile("auth\s+(\S+)")
255 func (botdata *XmppBot) handleIncomingMessageDialog(inmsg xmpp.Message, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
256 if inmsg.Body == nil || inmsg.GetHeader() == nil {
259 bodytext :=inmsg.Body.Chardata
260 //~ log.Println("Message Body:", bodytext)
261 if botdata.isAuthenticated(inmsg.GetHeader().From) {
264 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoOfflineInfo, false}
265 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 information while online" , "Your New Status")
267 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoInfo, false}
268 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Do not receive r3 information" , "Your New Status")
269 case "on_while_offline", "*on_while_offline*":
270 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3AllInfo, false}
271 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 information even while 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*":
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) {
307 var incoming_stanza interface{}
308 for incoming_stanza = range xmppin {
309 switch stanza := incoming_stanza.(type) {
311 botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events)
313 if stanza.GetHeader() == nil {
316 if stanza.GetHeader().Type == "subscribe" {
317 xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed")
319 jabber_events <- JabberEvent{stanza.GetHeader().From, stanza.GetHeader().Type != "unavailable", R3NoChange, false}
320 if stanza.GetHeader().Type == "unavailable" { botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0} //logout if offline
322 if stanza.GetHeader() == nil {
329 func NewStartedBot(loginjid, loginpwd, password, state_save_dir string, insecuretls bool) (*XmppBot, chan interface{}, error) {
331 botdata := new(XmppBot)
333 botdata.realraum_jids_ = make(map[string]JidData, 1)
334 botdata.jid_lastauthtime_ = make(map[string]int64,1)
335 botdata.auth_cmd_ = "auth " + password
336 botdata.auth_cmd2_ = "*auth*" + password+"*"
337 botdata.my_jid_ = loginjid
338 botdata.my_login_password_ = loginpwd
339 botdata.auth_timeout_ = 3600*2
341 botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json")
343 //~ log.Println(botdata.config_file_)
345 //~ logger := &StdLogger{}
346 //~ xmpp.Debug = logger
347 //~ xmpp.Info = logger
348 //~ xmpp.Warn = logger
350 xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls}
351 botdata.realraum_jids_.loadFrom(botdata.config_file_)
353 client_jid := new(xmpp.JID)
354 client_jid.Set(botdata.my_jid_)
355 botdata.xmppclient_, err = xmpp.NewClient(client_jid, botdata.my_login_password_, nil)
357 log.Println("Error connecting to xmpp server", err)
361 err = botdata.xmppclient_.StartSession(false, &xmpp.Presence{})
363 log.Println("'Error StartSession:", err)
367 presence_events := make(chan interface{},1)
368 jabber_events := make(chan JabberEvent,1)
370 go botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events)
371 go botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events)
373 botdata.presence_events_ = &presence_events
375 return botdata, presence_events, nil
378 func (botdata *XmppBot) StopBot() {
379 if botdata.xmppclient_ != nil {
380 close(botdata.xmppclient_.Out)
382 if botdata.presence_events_ != nil {
383 *botdata.presence_events_ <- false
384 close(*botdata.presence_events_)