more cosmetic changes
[svn42.git] / r3-netstatus / r3xmppbot / r3xmppbot.go
1 package r3xmppbot
2
3 import (
4         xmpp "code.google.com/p/goexmpp"
5         "fmt"
6     "log"
7     "crypto/tls"
8     "os"
9     "time"
10     "encoding/json"
11     "path"
12 )
13
14 //~ type StdLogger struct {
15 //~ }
16
17 //~ func (s *StdLogger) Log(v ...interface{}) {
18         //~ log.Println(v...)
19 //~ }
20
21 //~ func (s *StdLogger) Logf(fmt string, v ...interface{}) {
22         //~ log.Printf(fmt, v...)
23 //~ }
24
25 func IfThenElseStr(c bool, strue, sfalse string) string {
26     if c {return strue} else {return sfalse}
27 }
28
29 func (botdata *XmppBot) makeXMPPMessage(to string, message interface{}, subject interface{}) *xmpp.Message {
30     xmppmsgheader := xmpp.Header{To: to,
31                                                             From: botdata.my_jid_,
32                                                             Id: <-xmpp.Id,
33                                                             Type: "chat",
34                                                             Lang: "",
35                                                             Innerxml: "",
36                                                             Error: nil,
37                                                             Nested: make([]interface{},0)}
38
39     var msgsubject, msgbody *xmpp.Generic
40     switch cast_msg := message.(type) {
41         case string:
42             msgbody = &xmpp.Generic{Chardata: cast_msg}
43         case *string:
44             msgbody = &xmpp.Generic{Chardata: *cast_msg}
45         case *xmpp.Generic:
46             msgbody = cast_msg
47         default:
48             msgbody = &xmpp.Generic{}
49     }
50     switch cast_msg := subject.(type) {
51         case string:
52             msgsubject = &xmpp.Generic{Chardata: cast_msg}
53         case *string:
54             msgsubject = &xmpp.Generic{Chardata: *cast_msg}
55         case *xmpp.Generic:
56             msgsubject = cast_msg
57         default:
58             msgsubject = &xmpp.Generic{}
59     }
60     return &xmpp.Message{Header: xmppmsgheader , Subject: msgsubject, Body: msgbody, Thread: &xmpp.Generic{}}
61 }
62
63 func (botdata *XmppBot) makeXMPPPresence(to, ptype string) *xmpp.Presence {
64     xmppmsgheader := xmpp.Header{To: to,
65                                                             From: botdata.my_jid_,
66                                                             Id: <-xmpp.Id,
67                                                             Type: ptype,
68                                                             Lang: "",
69                                                             Innerxml: "",
70                                                             Error: nil,
71                                                             Nested: make([]interface{},0)}
72     return &xmpp.Presence{Header: xmppmsgheader}
73 }
74
75 type R3JIDDesire int
76
77 const (
78     R3NoChange R3JIDDesire = -1
79     R3NoInfo R3JIDDesire = iota // ignore first value by assigning to blank identifier
80     R3NoOfflineInfo
81     R3AllInfo
82     R3DebugInfo
83 )
84
85 type JidData struct {
86         Online  bool
87     Wants   R3JIDDesire
88 }
89
90 type JabberEvent struct {
91     JID      string
92     Online   bool
93     Wants    R3JIDDesire
94     StatusNow bool
95 }
96
97 type XMPPPresenceEvent struct {
98     Present bool
99     Who string
100     DoorLock bool
101     DoorShut bool
102     Button bool
103     Ts  int64
104 }
105
106 type RealraumXmppNotifierConfig map[string]JidData
107
108 type XmppBot struct {
109     jid_lastauthtime_ map[string]int64
110     realraum_jids_ RealraumXmppNotifierConfig
111     password_ string
112     auth_cmd_ string
113     auth_cmd2_ string
114     my_jid_ string
115     auth_timeout_ int64
116     config_file_ string
117     my_login_password_ string
118     xmppclient_ *xmpp.Client
119     presence_events_ *chan interface{}
120 }
121
122
123 func (data RealraumXmppNotifierConfig) saveTo(filepath string) () {
124     fh, err := os.Create(filepath)
125     if err != nil {
126         log.Println(err)
127         return
128     }
129     defer fh.Close()
130     enc := json.NewEncoder(fh)
131     if err = enc.Encode(&data); err != nil {
132         log.Println(err)
133         return
134     }
135 }
136
137 func (data RealraumXmppNotifierConfig) loadFrom(filepath string) () {
138     fh, err := os.Open(filepath)
139     if err != nil {
140         log.Println(err)
141         return
142     }
143     defer fh.Close()
144     dec := json.NewDecoder(fh)
145     if err = dec.Decode(&data); err != nil {
146         log.Println(err)
147         return
148     }
149     for to, jiddata := range data  {
150         jiddata.Online = false
151         data[to]=jiddata
152     }
153 }
154
155
156 func init() {
157         //~ logger := &StdLogger{}
158         //~ xmpp.Debug = logger
159         //~ xmpp.Info = logger
160         //~ xmpp.Warn = logger
161 }
162
163 func composeMessage(pec *XMPPPresenceEvent, both bool) *string {
164     var msg string
165     msg = ""
166     if pec.Button {
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()
170             return &msg;
171         }
172     }
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"),
177         pec.Who,
178         time.Unix(pec.Ts,0).String())
179     return &msg
180 }
181
182 func (botdata *XmppBot) handleEventsforXMPP(xmppout chan <- xmpp.Stanza, presence_events <- chan interface{}, jabber_events <- chan JabberEvent) {
183     var debug_msg bool
184     var last_presence_event *XMPPPresenceEvent
185     var msg *string
186
187         for {
188         debug_msg = false
189                 select {
190                 case pe := <-presence_events:
191             switch pec := pe.(type) {
192                 case xmpp.Stanza:
193                     xmppout <- pec
194                     continue
195                 case string:
196                     msg = &pec
197                     debug_msg = true
198                 case XMPPPresenceEvent:
199                     last_presence_event = &pec
200                     msg = composeMessage(last_presence_event, false)
201                 default:
202                     break
203                 }
204
205                 if msg == nil { continue }
206
207                 for to, jiddata := range botdata.realraum_jids_  {
208                     if debug_msg && jiddata.Wants < R3DebugInfo {
209                         continue
210                     }
211                     if (jiddata.Wants == R3NoOfflineInfo && jiddata.Online) || jiddata.Wants > R3NoOfflineInfo {
212                         xmppout <-  botdata.makeXMPPMessage(to, msg, nil)
213                     }
214                 }
215
216                 case je := <-jabber_events:
217             simple_jid := removeJIDResource(je.JID)
218             jid_data, jid_in_map := botdata.realraum_jids_[simple_jid]
219             if jid_in_map {
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)
223                 }
224                 if je.Wants > R3NoChange {
225                     jid_data.Wants = je.Wants
226                 }
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_)
232             }
233                 }
234         }
235 }
236
237 func removeJIDResource(jid string) string {
238     var jidjid xmpp.JID
239     jidjid.Set(jid)
240     jidjid.Resource = ""
241     return jidjid.String()
242 }
243
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_
248 }
249
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."
252
253 //~ var re_msg_auth_    *regexp.Regexp     = regexp.MustCompile("auth\s+(\S+)")
254
255 func (botdata *XmppBot) handleIncomingMessageDialog(inmsg xmpp.Message, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
256     if inmsg.Body == nil || inmsg.GetHeader() == nil {
257         return
258     }
259     bodytext :=inmsg.Body.Chardata
260     //~ log.Println("Message Body:", bodytext)
261     if botdata.isAuthenticated(inmsg.GetHeader().From) {
262         switch bodytext {
263             case "on", "*on*":
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")
266             case "off", "*off*":
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")
272             case "debug":
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)
278             case "open","close":
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)
284             default:
285                 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
286                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
287         }
288     } else {
289         switch bodytext {
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)
299             default:
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)
302         }
303     }
304 }
305
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) {
310             case *xmpp.Message:
311                 botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events)
312             case *xmpp.Presence:
313                 if stanza.GetHeader() == nil {
314                     continue
315                 }
316                 if stanza.GetHeader().Type == "subscribe" {
317                     xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed")
318                 }
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
321             case *xmpp.Iq:
322                 if stanza.GetHeader() == nil {
323                     continue
324                 }
325         }
326     }
327 }
328
329 func NewStartedBot(loginjid, loginpwd, password, state_save_dir string, insecuretls bool) (*XmppBot, chan interface{}, error) {
330     var err error
331     botdata := new(XmppBot)
332
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
340
341     botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json")
342
343     //~ log.Println(botdata.config_file_)
344
345     //~ logger := &StdLogger{}
346     //~ xmpp.Debug = logger
347     //~ xmpp.Info = logger
348     //~ xmpp.Warn = logger
349
350     xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls}
351     botdata.realraum_jids_.loadFrom(botdata.config_file_)
352
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)
356     if err != nil {
357         log.Println("Error connecting to xmpp server", err)
358         return nil, nil, err
359     }
360
361     err = botdata.xmppclient_.StartSession(false, &xmpp.Presence{})
362     if err != nil {
363         log.Println("'Error StartSession:", err)
364         return nil, nil, err
365     }
366
367     presence_events := make(chan interface{},1)
368     jabber_events := make(chan JabberEvent,1)
369
370     go botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events)
371     go botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events)
372
373     botdata.presence_events_ = &presence_events
374
375     return botdata, presence_events, nil
376 }
377
378 func (botdata *XmppBot) StopBot() {
379     if botdata.xmppclient_ != nil {
380         close(botdata.xmppclient_.Out)
381     }
382     if botdata.presence_events_ != nil {
383         *botdata.presence_events_ <- false
384         close(*botdata.presence_events_)
385     }
386 }