some defers in case jabber server disappears
[svn42.git] / r3-netstatus / r3xmppbot / r3xmppbot.go
1 package r3xmppbot
2
3 import (
4         xmpp "code.google.com/p/goexmpp"
5     "log"
6     "crypto/tls"
7     "os"
8     "time"
9     "encoding/json"
10     "path"
11 )
12
13 //~ type StdLogger struct {
14 //~ }
15
16 //~ func (s *StdLogger) Log(v ...interface{}) {
17         //~ log.Println(v...)
18 //~ }
19
20 //~ func (s *StdLogger) Logf(fmt string, v ...interface{}) {
21         //~ log.Printf(fmt, v...)
22 //~ }
23
24
25 func (botdata *XmppBot) makeXMPPMessage(to string, message interface{}, subject interface{}) *xmpp.Message {
26     xmppmsgheader := xmpp.Header{To: to,
27                                                             From: botdata.my_jid_,
28                                                             Id: <-xmpp.Id,
29                                                             Type: "chat",
30                                                             Lang: "",
31                                                             Innerxml: "",
32                                                             Error: nil,
33                                                             Nested: make([]interface{},0)}
34
35     var msgsubject, msgbody *xmpp.Generic
36     switch cast_msg := message.(type) {
37         case string:
38             msgbody = &xmpp.Generic{Chardata: cast_msg}
39         case *string:
40             msgbody = &xmpp.Generic{Chardata: *cast_msg}
41         case *xmpp.Generic:
42             msgbody = cast_msg
43         default:
44             msgbody = &xmpp.Generic{}
45     }
46     switch cast_msg := subject.(type) {
47         case string:
48             msgsubject = &xmpp.Generic{Chardata: cast_msg}
49         case *string:
50             msgsubject = &xmpp.Generic{Chardata: *cast_msg}
51         case *xmpp.Generic:
52             msgsubject = cast_msg
53         default:
54             msgsubject = &xmpp.Generic{}
55     }
56     return &xmpp.Message{Header: xmppmsgheader , Subject: msgsubject, Body: msgbody, Thread: &xmpp.Generic{}}
57 }
58
59 func (botdata *XmppBot) makeXMPPPresence(to, ptype string) *xmpp.Presence {
60     xmppmsgheader := xmpp.Header{To: to,
61                                                             From: botdata.my_jid_,
62                                                             Id: <-xmpp.Id,
63                                                             Type: ptype,
64                                                             Lang: "",
65                                                             Innerxml: "",
66                                                             Error: nil,
67                                                             Nested: make([]interface{},0)}
68     return &xmpp.Presence{Header: xmppmsgheader}
69 }
70
71 type R3JIDDesire int
72
73 const (
74     R3NoChange R3JIDDesire = -1
75     R3NeverInfo R3JIDDesire = iota // ignore first value by assigning to blank identifier
76     R3OnlineOnlyInfo
77     R3OnlineOnlyWithRecapInfo
78     R3AlwaysInfo
79     R3DebugInfo
80 )
81
82 type JidData struct {
83         Online  bool
84     Wants   R3JIDDesire
85 }
86
87 type JabberEvent struct {
88     JID      string
89     Online   bool
90     Wants    R3JIDDesire
91     StatusNow bool
92 }
93
94 type XMPPMsgEvent struct {
95     Msg string
96     DistributeLevel R3JIDDesire
97     RememberAsStatus bool
98 }
99
100 type RealraumXmppNotifierConfig map[string]JidData
101
102 type XmppBot struct {
103     jid_lastauthtime_ map[string]int64
104     realraum_jids_ RealraumXmppNotifierConfig
105     password_ string
106     auth_cmd_ string
107     auth_cmd2_ string
108     my_jid_ string
109     auth_timeout_ int64
110     config_file_ string
111     my_login_password_ string
112     xmppclient_ *xmpp.Client
113     presence_events_ *chan interface{}
114 }
115
116
117 func (data RealraumXmppNotifierConfig) saveTo(filepath string) () {
118     fh, err := os.Create(filepath)
119     if err != nil {
120         log.Println(err)
121         return
122     }
123     defer fh.Close()
124     enc := json.NewEncoder(fh)
125     if err = enc.Encode(&data); err != nil {
126         log.Println(err)
127         return
128     }
129 }
130
131 func (data RealraumXmppNotifierConfig) loadFrom(filepath string) () {
132     fh, err := os.Open(filepath)
133     if err != nil {
134         log.Println(err)
135         return
136     }
137     defer fh.Close()
138     dec := json.NewDecoder(fh)
139     if err = dec.Decode(&data); err != nil {
140         log.Println(err)
141         return
142     }
143     for to, jiddata := range data  {
144         jiddata.Online = false
145         data[to]=jiddata
146     }
147 }
148
149
150 func init() {
151         //~ logger := &StdLogger{}
152         //~ xmpp.Debug = logger
153         //~ xmpp.Info = logger
154         //~ xmpp.Warn = logger
155 }
156
157 func (botdata *XmppBot) handleEventsforXMPP(xmppout chan <- xmpp.Stanza, presence_events <- chan interface{}, jabber_events <- chan JabberEvent) {
158     var last_status_msg *string
159
160     defer func() {
161         if x := recover(); x != nil {
162             log.Printf("handleEventsforXMPP: run time panic: %v", x)
163         }
164     }()
165
166         for {
167                 select {
168                 case pe := <-presence_events:
169             switch pec := pe.(type) {
170                 case xmpp.Stanza:
171                     xmppout <- pec
172                     continue
173                 case string:
174                     for to, jiddata := range botdata.realraum_jids_  {
175                         if  jiddata.Wants >= R3DebugInfo {
176                             xmppout <-  botdata.makeXMPPMessage(to, pec, nil)
177                         }
178                     }
179                     
180                 case XMPPMsgEvent:
181                     if pec.RememberAsStatus {
182                         last_status_msg = &pec.Msg
183                     }
184                     for to, jiddata := range botdata.realraum_jids_  {
185                         if  jiddata.Wants >= pec.DistributeLevel && ((jiddata.Wants >= R3OnlineOnlyInfo && jiddata.Online) || jiddata.Wants >= R3AlwaysInfo) {
186                             xmppout <-  botdata.makeXMPPMessage(to, pec.Msg, nil)
187                         }
188                     }
189                 default:
190                     break
191                 }
192
193                 case je := <-jabber_events:
194             simple_jid := removeJIDResource(je.JID)
195             jid_data, jid_in_map := botdata.realraum_jids_[simple_jid]
196             if jid_in_map {
197                 if last_status_msg != nil && (je.StatusNow || (! jid_data.Online && je.Online && jid_data.Wants == R3OnlineOnlyWithRecapInfo) ) {
198                     xmppout <-  botdata.makeXMPPMessage(je.JID, last_status_msg, nil)
199                 }
200                 jid_data.Online = je.Online
201                 if je.Wants > R3NoChange {
202                     jid_data.Wants = je.Wants
203                 }
204                 botdata.realraum_jids_[simple_jid] = jid_data
205                 botdata.realraum_jids_.saveTo(botdata.config_file_)
206             } else if je.Wants > R3NoChange {
207                 botdata.realraum_jids_[simple_jid] = JidData{je.Online, je.Wants}
208                 botdata.realraum_jids_.saveTo(botdata.config_file_)
209             }
210                 }
211         }
212 }
213
214 func removeJIDResource(jid string) string {
215     var jidjid xmpp.JID
216     jidjid.Set(jid)
217     jidjid.Resource = ""
218     return jidjid.String()
219 }
220
221 func (botdata *XmppBot) isAuthenticated(jid string) bool {
222     authtime, in_map := botdata.jid_lastauthtime_[jid]
223     //~ log.Println("isAuthenticated", in_map, authtime, time.Now().Unix(), auth_timeout_, time.Now().Unix() - authtime > auth_timeout_)
224     return in_map && time.Now().Unix() - authtime < botdata.auth_timeout_
225 }
226
227 const help_text_ string = "\n*auth*<password>* ...Enables you to use more commands.\n*time* ...Returns bot time."
228 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."
229
230 //~ var re_msg_auth_    *regexp.Regexp     = regexp.MustCompile("auth\s+(\S+)")
231
232 func (botdata *XmppBot) handleIncomingMessageDialog(inmsg xmpp.Message, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
233     if inmsg.Body == nil || inmsg.GetHeader() == nil {
234         return
235     }
236     bodytext :=inmsg.Body.Chardata
237     //~ log.Println("Message Body:", bodytext)
238     if botdata.isAuthenticated(inmsg.GetHeader().From) {
239         switch bodytext {
240             case "on", "*on*":
241                 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyInfo, false}
242                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while online." , "Your New Status")
243             case "off", "*off*":
244                 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NeverInfo, false}
245                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Do not receive anything." , "Your New Status")
246             case "on_with_recap", "*on_with_recap*":
247                 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyWithRecapInfo, false}
248                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while and current status on coming, online." , "Your New Status")
249             case "on_while_offline", "*on_while_offline*":
250                 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3AlwaysInfo, false}
251                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive all r3 status updates, even if you are offline." , "Your New Status")
252             case "debug":
253                 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3DebugInfo, false}
254                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Debug mode enabled" , "Your New Status")
255             case "bye", "Bye", "quit", "logout", "*bye*":
256                 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = 0
257                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Bye Bye !" ,nil)
258             case "open","close":
259                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, I can't operate the door for you." ,nil)
260             case "status", "*status*":
261                 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoChange, true}
262             case "time", "*time*":
263                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
264             default:
265                 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
266                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
267         }
268     } else {
269         switch bodytext {
270             case "Hilfe","hilfe","help","Help","?","hallo","Hallo","Yes","yes","ja","ja bitte","bitte","sowieso":
271                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_, "Available Commands")
272             case botdata.auth_cmd_, botdata.auth_cmd2_:
273                 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = time.Now().Unix()
274                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
275             case "status", "*status*", "off", "*off*", "on", "*on*", "on_while_offline", "*on_while_offline*", "on_with_recap", "*on_with_recap*":
276                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, you need to be authorized to do that." , nil)
277             case "time", "*time*":
278                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
279             default:
280                 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
281                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "A nice day to you too !\nDo you need \"help\" ?", nil)
282         }
283     }
284 }
285
286 func (botdata *XmppBot) handleIncomingXMPPStanzas(xmppin <- chan xmpp.Stanza, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
287
288     defer func() {
289         if x := recover(); x != nil {
290             log.Printf("handleIncomingXMPPStanzas: run time panic: %v", x)
291             close(jabber_events)
292         }
293     }()
294
295     var incoming_stanza interface{}
296     for incoming_stanza = range xmppin {
297         switch stanza := incoming_stanza.(type) {
298             case *xmpp.Message:
299                 botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events)
300             case *xmpp.Presence:
301                 if stanza.GetHeader() == nil {
302                     continue
303                 }
304                 switch stanza.GetHeader().Type {
305                     case "subscribe":
306                         xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed")
307                         jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}                        
308                         xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribe")
309                     case "unsubscribe", "unsubscribed":
310                         jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NeverInfo, false}
311                         botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
312                         xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "unsubscribe")
313                     case "unavailable":
314                         jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NoChange, false}
315                         botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
316                     default:
317                         jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
318                 }
319             case *xmpp.Iq:
320                 if stanza.GetHeader() == nil {
321                     continue
322                 }
323         }
324     }
325 }
326
327 func NewStartedBot(loginjid, loginpwd, password, state_save_dir string, insecuretls bool) (*XmppBot, chan interface{}, error) {
328     var err error
329     botdata := new(XmppBot)
330
331     botdata.realraum_jids_ = make(map[string]JidData, 1)
332     botdata.jid_lastauthtime_ = make(map[string]int64,1)
333     botdata.auth_cmd_ = "auth " + password
334     botdata.auth_cmd2_ = "*auth*" + password+"*"
335     botdata.my_jid_ = loginjid
336     botdata.my_login_password_ = loginpwd
337     botdata.auth_timeout_ = 3600*2
338
339     botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json")
340
341     //~ log.Println(botdata.config_file_)
342
343     //~ logger := &StdLogger{}
344     //~ xmpp.Debug = logger
345     //~ xmpp.Info = logger
346     //~ xmpp.Warn = logger
347
348     xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls}
349     botdata.realraum_jids_.loadFrom(botdata.config_file_)
350
351     client_jid := new(xmpp.JID)
352     client_jid.Set(botdata.my_jid_)
353     botdata.xmppclient_, err = xmpp.NewClient(client_jid, botdata.my_login_password_, nil)
354     if err != nil {
355         log.Println("Error connecting to xmpp server", err)
356         return nil, nil, err
357     }
358
359     err = botdata.xmppclient_.StartSession(true, &xmpp.Presence{})
360     if err != nil {
361         log.Println("'Error StartSession:", err)
362         return nil, nil, err
363     }
364
365     roster := xmpp.Roster(botdata.xmppclient_)
366     for _, entry := range roster {
367         if entry.Subscription == "from" {
368             botdata.xmppclient_.Out <- botdata.makeXMPPPresence(entry.Jid, "subscribe")
369         }
370         if entry.Subscription == "none" {
371             delete(botdata.realraum_jids_, entry.Jid)
372         }
373     }
374
375     presence_events := make(chan interface{},1)
376     jabber_events := make(chan JabberEvent,1)
377
378     go botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events)
379     go botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events)
380
381     botdata.presence_events_ = &presence_events
382
383     return botdata, presence_events, nil
384 }
385
386 func (botdata *XmppBot) StopBot() {
387     if botdata.xmppclient_ != nil {
388         close(botdata.xmppclient_.Out)
389     }
390     if botdata.presence_events_ != nil {
391         *botdata.presence_events_ <- false
392         close(*botdata.presence_events_)
393     }
394 }