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