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