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