7863b70b61baf19d35a38d27ef55392eee2cf78a
[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 }
140
141
142 func (data RealraumXmppNotifierConfig) saveTo(filepath string) () {
143     fh, err := os.Create(filepath)
144     if err != nil {
145         Syslog_.Println(err)
146         return
147     }
148     defer fh.Close()
149     enc := json.NewEncoder(fh)
150     if err = enc.Encode(&data); err != nil {
151         Syslog_.Println(err)
152         return
153     }
154 }
155
156 func (data RealraumXmppNotifierConfig) loadFrom(filepath string) () {
157     fh, err := os.Open(filepath)
158     if err != nil {
159         Syslog_.Println(err)
160         return
161     }
162     defer fh.Close()
163     dec := json.NewDecoder(fh)
164     if err = dec.Decode(&data); err != nil {
165         Syslog_.Println(err)
166         return
167     }
168     for to, jiddata := range data  {
169         jiddata.Online = false
170         data[to]=jiddata
171     }
172 }
173
174
175 func init() {
176         //~ logger := &StdLogger{}
177         //~ xmpp.Debug = logger
178         //~ xmpp.Info = logger
179         //~ xmpp.Warn = logger
180 }
181
182 func (botdata *XmppBot) handleEventsforXMPP(xmppout chan <- xmpp.Stanza, presence_events <- chan interface{}, jabber_events <- chan JabberEvent) {
183     var last_status_msg *string
184
185     defer func() {
186         if x := recover(); x != nil {
187             Syslog_.Printf("handleEventsforXMPP: run time panic: %v", x)
188         }
189     }()
190
191         for {
192                 select {
193                 case pe := <-presence_events:
194             switch pec := pe.(type) {
195                 case xmpp.Stanza:
196                     xmppout <- pec
197                     continue
198                 case string:
199                     for to, jiddata := range botdata.realraum_jids_  {
200                         if  jiddata.Wants >= R3DebugInfo {
201                             xmppout <-  botdata.makeXMPPMessage(to, pec, nil)
202                         }
203                     }
204
205                 case XMPPStatusEvent:
206                     xmppout <- botdata.makeXMPPPresence("", "", pec.Show, pec.Status)
207
208                 case XMPPMsgEvent:
209                     if pec.RememberAsStatus {
210                         last_status_msg = &pec.Msg
211                     }
212                     for to, jiddata := range botdata.realraum_jids_  {
213                         if  jiddata.Wants >= pec.DistributeLevel && ((jiddata.Wants >= R3OnlineOnlyInfo && jiddata.Online) || jiddata.Wants >= R3AlwaysInfo) {
214                             xmppout <-  botdata.makeXMPPMessage(to, pec.Msg, nil)
215                         }
216                     }
217                 default:
218                     break
219                 }
220
221                 case je := <-jabber_events:
222             simple_jid := removeJIDResource(je.JID)
223             jid_data, jid_in_map := botdata.realraum_jids_[simple_jid]
224             if jid_in_map {
225                 if last_status_msg != nil && (je.StatusNow || (! jid_data.Online && je.Online && jid_data.Wants == R3OnlineOnlyWithRecapInfo) ) {
226                     xmppout <-  botdata.makeXMPPMessage(je.JID, last_status_msg, nil)
227                 }
228                 jid_data.Online = je.Online
229                 if je.Wants > R3NoChange {
230                     jid_data.Wants = je.Wants
231                 }
232                 botdata.realraum_jids_[simple_jid] = jid_data
233                 botdata.realraum_jids_.saveTo(botdata.config_file_)
234             } else if je.Wants > R3NoChange {
235                 botdata.realraum_jids_[simple_jid] = JidData{je.Online, je.Wants}
236                 botdata.realraum_jids_.saveTo(botdata.config_file_)
237             }
238                 }
239         }
240 }
241
242 func removeJIDResource(jid string) string {
243     var jidjid xmpp.JID
244     jidjid.Set(jid)
245     jidjid.Resource = ""
246     return jidjid.String()
247 }
248
249 func (botdata *XmppBot) isAuthenticated(jid string) bool {
250     authtime, in_map := botdata.jid_lastauthtime_[jid]
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     if botdata.isAuthenticated(inmsg.GetHeader().From) {
265         switch bodytext {
266             case "on", "*on*":
267                 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyInfo, false}
268                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while online." , "Your New Status")
269             case "off", "*off*":
270                 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NeverInfo, false}
271                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Do not receive anything." , "Your New Status")
272             case "on_with_recap", "*on_with_recap*":
273                 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3OnlineOnlyWithRecapInfo, false}
274                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive r3 status updates while and current status on coming, online." , "Your New Status")
275             case "on_while_offline", "*on_while_offline*":
276                 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3AlwaysInfo, false}
277                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Receive all r3 status updates, even if you are offline." , "Your New Status")
278             case "debug":
279                 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3DebugInfo, false}
280                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Debug mode enabled" , "Your New Status")
281             case "bye", "Bye", "quit", "logout", "*bye*":
282                 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = 0
283                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Bye Bye !" ,nil)
284             case "open","close":
285                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, I can't operate the door for you." ,nil)
286             case "status", "*status*":
287                 jabber_events <- JabberEvent{inmsg.GetHeader().From, true, R3NoChange, true}
288             case "time", "*time*":
289                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
290             default:
291                 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
292                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
293         }
294     } else {
295         switch bodytext {
296             case "Hilfe","hilfe","help","Help","?","hallo","Hallo","Yes","yes","ja","ja bitte","bitte","sowieso":
297                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_, "Available Commands")
298             case botdata.auth_cmd_, botdata.auth_cmd2_:
299                 botdata.jid_lastauthtime_[inmsg.GetHeader().From] = time.Now().Unix()
300                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, help_text_auth, nil)
301             case "status", "*status*", "off", "*off*", "on", "*on*", "on_while_offline", "*on_while_offline*", "on_with_recap", "*on_with_recap*":
302                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "Sorry, you need to be authorized to do that." , nil)
303             case "time", "*time*":
304                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, time.Now().String() , nil)
305             default:
306                 //~ auth_match = re_msg_auth_.FindStringSubmatch(inmsg.Body.Chardata)
307                 xmppout <- botdata.makeXMPPMessage(inmsg.GetHeader().From, "A nice day to you too !\nDo you need \"help\" ?", nil)
308         }
309     }
310 }
311
312 func (botdata *XmppBot) handleIncomingXMPPStanzas(xmppin <- chan xmpp.Stanza, xmppout chan<- xmpp.Stanza, jabber_events chan JabberEvent) {
313
314     defer func() {
315         if x := recover(); x != nil {
316             Syslog_.Printf("handleIncomingXMPPStanzas: run time panic: %v", x)
317             close(jabber_events)
318         }
319     }()
320
321     var incoming_stanza interface{}
322     for incoming_stanza = range xmppin {
323         switch stanza := incoming_stanza.(type) {
324             case *xmpp.Message:
325                 botdata.handleIncomingMessageDialog(*stanza, xmppout, jabber_events)
326             case *xmpp.Presence:
327                 if stanza.GetHeader() == nil {
328                     continue
329                 }
330                 switch stanza.GetHeader().Type {
331                     case "subscribe":
332                         xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribed", "", "")
333                         jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
334                         xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "subscribe", "", "")
335                     case "unsubscribe", "unsubscribed":
336                         jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NeverInfo, false}
337                         botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
338                         xmppout <- botdata.makeXMPPPresence(stanza.GetHeader().From, "unsubscribe", "","")
339                     case "unavailable":
340                         jabber_events <- JabberEvent{stanza.GetHeader().From, false, R3NoChange, false}
341                         botdata.jid_lastauthtime_[stanza.GetHeader().From] = 0 //logout
342                     default:
343                         jabber_events <- JabberEvent{stanza.GetHeader().From, true, R3NoChange, false}
344                 }
345             case *xmpp.Iq:
346                 if stanza.GetHeader() == nil {
347                     continue
348                 }
349         }
350     }
351 }
352
353 func NewStartedBot(loginjid, loginpwd, password, state_save_dir string, insecuretls bool) (*XmppBot, chan interface{}, error) {
354     var err error
355     botdata := new(XmppBot)
356
357     botdata.realraum_jids_ = make(map[string]JidData, 1)
358     botdata.jid_lastauthtime_ = make(map[string]int64,1)
359     botdata.auth_cmd_ = "auth " + password
360     botdata.auth_cmd2_ = "*auth*" + password+"*"
361     botdata.my_jid_ = loginjid
362     botdata.my_login_password_ = loginpwd
363     botdata.auth_timeout_ = 3600*2
364
365     botdata.config_file_ = path.Join(state_save_dir, "r3xmpp."+removeJIDResource(loginjid)+".json")
366
367     //~ logger := &StdLogger{}
368     //~ xmpp.Debug = logger
369     //~ xmpp.Info = logger
370     //~ xmpp.Warn = logger
371
372     xmpp.TlsConfig = tls.Config{InsecureSkipVerify: insecuretls}
373     botdata.realraum_jids_.loadFrom(botdata.config_file_)
374
375     client_jid := new(xmpp.JID)
376     client_jid.Set(botdata.my_jid_)
377     botdata.xmppclient_, err = xmpp.NewClient(client_jid, botdata.my_login_password_, nil)
378     if err != nil {
379         Syslog_.Println("Error connecting to xmpp server", err)
380         return nil, nil, err
381     }
382
383     err = botdata.xmppclient_.StartSession(true, &xmpp.Presence{})
384     if err != nil {
385         Syslog_.Println("'Error StartSession:", err)
386         return nil, nil, err
387     }
388
389     roster := xmpp.Roster(botdata.xmppclient_)
390     for _, entry := range roster {
391         if entry.Subscription == "from" {
392             botdata.xmppclient_.Out <- botdata.makeXMPPPresence(entry.Jid, "subscribe", "","")
393         }
394         if entry.Subscription == "none" {
395             delete(botdata.realraum_jids_, entry.Jid)
396         }
397     }
398
399     presence_events := make(chan interface{},1)
400     jabber_events := make(chan JabberEvent,1)
401
402     go botdata.handleEventsforXMPP(botdata.xmppclient_.Out, presence_events, jabber_events)
403     go botdata.handleIncomingXMPPStanzas(botdata.xmppclient_.In, botdata.xmppclient_.Out, jabber_events)
404
405     botdata.presence_events_ = &presence_events
406
407     return botdata, presence_events, nil
408 }
409
410 func (botdata *XmppBot) StopBot() {
411     if botdata.xmppclient_ != nil {
412         close(botdata.xmppclient_.Out)
413     }
414     if botdata.presence_events_ != nil {
415         *botdata.presence_events_ <- false
416         close(*botdata.presence_events_)
417     }
418 }