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