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