Mercurial > libervia-backend
annotate sat.tac @ 5:c0c92129a54b
connect and disconnect management
author | Goffi <goffi@goffi.org> |
---|---|
date | Mon, 19 Oct 2009 23:49:31 +0200 |
parents | c49345fd7737 |
children | 5799493fa548 |
rev | line source |
---|---|
0 | 1 #!/usr/bin/python |
2 # -*- coding: utf-8 -*- | |
3 | |
4 """ | |
5 SAT: a jabber client | |
6 Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org) | |
7 | |
8 This program is free software: you can redistribute it and/or modify | |
9 it under the terms of the GNU General Public License as published by | |
10 the Free Software Foundation, either version 3 of the License, or | |
11 (at your option) any later version. | |
12 | |
13 This program is distributed in the hope that it will be useful, | |
14 but WITHOUT ANY WARRANTY; without even the implied warranty of | |
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
16 GNU General Public License for more details. | |
17 | |
18 You should have received a copy of the GNU General Public License | |
19 along with this program. If not, see <http://www.gnu.org/licenses/>. | |
20 """ | |
21 | |
22 | |
2
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
23 from twisted.application import internet, service |
0 | 24 from twisted.internet import glib2reactor, protocol |
25 glib2reactor.install() | |
26 | |
27 from twisted.words.protocols.jabber import client, jid, xmlstream, error | |
28 from twisted.words.xish import domish | |
29 | |
30 from twisted.internet import reactor | |
31 import pdb | |
32 | |
33 from sat_bridge.DBus import DBusBridge | |
34 import logging | |
35 from logging import debug, info, error | |
36 | |
37 import signal, sys | |
38 import os.path | |
39 | |
40 from tools.memory import Memory | |
41 from glob import glob | |
42 | |
43 | |
44 ### logging configuration FIXME: put this elsewhere ### | |
45 logging.basicConfig(level=logging.DEBUG, | |
46 format='%(message)s') | |
47 ### | |
48 | |
49 | |
50 | |
51 | |
52 class SAT: | |
53 | |
54 def __init__(self): | |
2
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
55 #self.reactor=reactor |
0 | 56 self.memory=Memory() |
57 self.server_features=[] #XXX: temp dic, need to be transfered into self.memory in the future | |
58 self.connected=False #FIXME: use twisted var instead | |
59 | |
60 self._iq_cb_map = {} #callback called when ns is found on IQ | |
61 self._waiting_conf = {} #callback called when a confirmation is received | |
62 self._progress_cb_map = {} #callback called when a progress is requested (key = progress id) | |
63 self.plugins = {} | |
64 | |
65 self.bridge=DBusBridge() | |
66 self.bridge.register("connect", self.connect) | |
1 | 67 self.bridge.register("disconnect", self.disconnect) |
0 | 68 self.bridge.register("getContacts", self.memory.getContacts) |
69 self.bridge.register("getPresenceStatus", self.memory.getPresenceStatus) | |
70 self.bridge.register("sendMessage", self.sendMessage) | |
71 self.bridge.register("setParam", self.setParam) | |
72 self.bridge.register("getParam", self.memory.getParam) | |
73 self.bridge.register("getParams", self.memory.getParams) | |
74 self.bridge.register("getParamsCategories", self.memory.getParamsCategories) | |
75 self.bridge.register("getHistory", self.memory.getHistory) | |
76 self.bridge.register("setPresence", self.setPresence) | |
77 self.bridge.register("addContact", self.addContact) | |
78 self.bridge.register("delContact", self.delContact) | |
79 self.bridge.register("isConnected", self.isConnected) | |
80 self.bridge.register("confirmationAnswer", self.confirmationAnswer) | |
81 self.bridge.register("getProgress", self.getProgress) | |
82 | |
83 self._import_plugins() | |
5 | 84 #self.connect() |
0 | 85 |
86 | |
87 def _import_plugins(self): | |
88 """Import all plugins found in plugins directory""" | |
89 #TODO: manage dependencies | |
90 plug_lst = [os.path.splitext(plugin)[0] for plugin in map(os.path.basename,glob ("plugins/plugin*.py"))] | |
91 | |
92 for plug in plug_lst: | |
93 plug_path = 'plugins.'+plug | |
94 __import__(plug_path) | |
95 mod = sys.modules[plug_path] | |
96 plug_info = mod.PLUGIN_INFO | |
97 info ("importing plugin: %s", plug_info['name']) | |
98 self.plugins[plug_info['import_name']] = getattr(mod, plug_info['main'])(self) | |
99 | |
100 def connect(self): | |
2
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
101 print "connecting..." |
5 | 102 reactor.connectTCP(self.memory.getParamV("Server", "Connection"), 5222, self.factory) |
103 self.connectionStatus="online" #TODO: check if connection is OK | |
104 self.connected=True #TODO: use startedConnecting and clientConnectionLost of XMPPClientFactory | |
2
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
105 |
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
106 def getService(self): |
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
107 print "GetService !" |
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
108 """if (self.connected): |
0 | 109 info("already connected !") |
2
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
110 return""" |
5 | 111 info("Getting service...") |
0 | 112 self.me = jid.JID(self.memory.getParamV("JabberID", "Connection")) |
113 self.factory = client.XMPPClientFactory(self.me, self.memory.getParamV("Password", "Connection")) | |
114 self.factory.addBootstrap(xmlstream.STREAM_AUTHD_EVENT,self.authd) | |
115 self.factory.addBootstrap(xmlstream.INIT_FAILED_EVENT,self.failed) | |
116 self.connectionStatus="online" #TODO: check if connection is OK | |
117 self.connected=True #TODO: use startedConnecting and clientConnectionLost of XMPPClientFactory | |
2
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
118 return internet.TCPClient(self.memory.getParamV("Server", "Connection"), 5222, self.factory) |
0 | 119 |
1 | 120 def disconnect(self): |
121 if (not self.connected): | |
122 info("not connected !") | |
123 return | |
124 info("Disconnecting...") | |
5 | 125 self.factory.stopTrying() |
126 if self.xmlstream: | |
127 self.xmlstream.sendFooter() | |
128 self.connectionStatus="offline" #TODO: check if connection is OK | |
129 self.connected=False #TODO: use startedConnecting and clientConnectionLost of XMPPClientFactory | |
0 | 130 |
131 def run(self): | |
132 debug("running app") | |
133 reactor.run() | |
134 | |
135 def stop(self): | |
136 debug("stopping app") | |
137 reactor.stop() | |
138 | |
139 def authd(self,xmlstream): | |
140 self.xmlstream=xmlstream | |
141 roster=client.IQ(xmlstream,'get') | |
142 roster.addElement(('jabber:iq:roster', 'query')) | |
143 roster.addCallback(self.rosterCb) | |
144 roster.send() | |
145 debug("server = %s",self.memory.getParamV("Server", "Connection")) | |
146 | |
147 ###FIXME: tmp disco ### | |
148 self.memory.registerFeature("http://jabber.org/protocol/disco#info") | |
149 self.disco(self.memory.getParamV("Server", "Connection"), self.serverDisco) | |
150 | |
151 | |
152 #we now send our presence status | |
153 self.setPresence(status="Online") | |
154 | |
155 # add a callback for the messages | |
156 xmlstream.addObserver('/message', self.gotMessage) | |
157 xmlstream.addObserver('/presence', self.presenceCb) | |
158 xmlstream.addObserver("/iq[@type='set' or @type='get']", self.iqCb) | |
159 #reactor.callLater(2,self.sendFile,"goffi2@jabber.goffi.int/Psi", "/tmp/fakefile") | |
160 | |
161 def sendMessage(self,to,msg,type='chat'): | |
162 #FIXME: check validity of recipient | |
163 debug("Sending jabber message to %s...", to) | |
164 message = domish.Element(('jabber:client','message')) | |
165 message["to"] = jid.JID(to).full() | |
166 message["from"] = self.me.full() | |
167 message["type"] = type | |
168 message.addElement("body", "jabber:client", msg) | |
169 self.xmlstream.send(message) | |
170 self.memory.addToHistory(self.me, self.me, jid.JID(to), message["type"], unicode(msg)) | |
171 self.bridge.newMessage(message['from'], unicode(msg), to=message['to']) #We send back the message, so all clients are aware of it | |
172 | |
173 def setParam(self, name, value, namespace): | |
174 """set wanted paramater and notice observers""" | |
175 info ("setting param: %s=%s in namespace %s", name, value, namespace) | |
176 self.memory.setParam(name, value, namespace) | |
177 self.bridge.paramUpdate(name, value, namespace) | |
178 | |
179 def setRoster(self, to): | |
180 """Add a contact to roster list""" | |
181 to_jid=jid.JID(to) | |
182 roster=client.IQ(self.xmlstream,'set') | |
183 query=roster.addElement(('jabber:iq:roster', 'query')) | |
184 item=query.addElement("item") | |
185 item.attributes["jid"]=to_jid.userhost() | |
186 roster.send() | |
187 #TODO: check IQ result | |
188 | |
189 def delRoster(self, to): | |
190 """Remove a contact from roster list""" | |
191 to_jid=jid.JID(to) | |
192 roster=client.IQ(self.xmlstream,'set') | |
193 query=roster.addElement(('jabber:iq:roster', 'query')) | |
194 item=query.addElement("item") | |
195 item.attributes["jid"]=to_jid.userhost() | |
196 item.attributes["subscription"]="remove" | |
197 roster.send() | |
198 #TODO: check IQ result | |
199 | |
200 | |
201 def failed(self,xmlstream): | |
202 debug("failed: %s", xmlstream.getErrorMessage()) | |
203 debug("failed: %s", dir(xmlstream)) | |
204 | |
205 def isConnected(self): | |
206 return self.connected | |
207 | |
208 ## jabber methods ## | |
209 | |
210 def disco (self, item, callback, node=None): | |
211 """XEP-0030 Service discovery Feature.""" | |
212 disco=client.IQ(self.xmlstream,'get') | |
213 disco["from"]=self.me.full() | |
214 disco["to"]=item | |
215 disco.addElement(('http://jabber.org/protocol/disco#info', 'query')) | |
216 disco.addCallback(callback) | |
217 disco.send() | |
218 | |
219 | |
220 def setPresence(self, to="", type="", show="", status="", priority=0): | |
221 """Send our presence information""" | |
222 presence = domish.Element(('jabber:client', 'presence')) | |
223 if not type in ["", "unavailable", "subscribed", "subscribe", | |
224 "unsubscribe", "unsubscribed", "prob", "error"]: | |
225 error("Type error !") | |
226 #TODO: throw an error | |
227 return | |
228 | |
229 if to: | |
230 presence.attributes["to"]=to | |
231 if type: | |
232 presence.attributes["type"]=type | |
233 | |
234 for element in ["show", "status", "priority"]: | |
235 if locals()[element]: | |
236 presence.addElement(element).addContent(unicode(locals()[element])) | |
237 | |
238 self.xmlstream.send(presence) | |
239 | |
240 def addContact(self, to): | |
241 """Add a contact in roster list""" | |
242 to_jid=jid.JID(to) | |
243 self.setRoster(to_jid.userhost()) | |
244 self.setPresence(to_jid.userhost(), "subscribe") | |
245 | |
246 def delContact(self, to): | |
247 """Remove contact from roster list""" | |
248 to_jid=jid.JID(to) | |
249 self.delRoster(to_jid.userhost()) | |
250 self.bridge.contactDeleted(to) | |
251 | |
252 def gotMessage(self,message): | |
253 debug (u"got_message from: %s", message["from"]) | |
254 for e in message.elements(): | |
255 if e.name == "body": | |
256 self.bridge.newMessage(message["from"], e.children[0]) | |
257 self.memory.addToHistory(self.me, jid.JID(message["from"]), self.me, "chat", e.children[0]) | |
258 break | |
259 | |
260 ## callbacks ## | |
261 | |
262 def add_IQ_cb(self, ns, cb): | |
263 """Add an IQ callback on namespace ns""" | |
264 debug ("Registered callback for namespace %s", ns) | |
265 self._iq_cb_map[ns]=cb | |
266 | |
267 def iqCb(self, stanza): | |
268 info ("iqCb") | |
269 debug ("="*20) | |
270 debug ("DEBUG:\n") | |
271 debug (stanza.toXml().encode('utf-8')) | |
272 debug ("="*20) | |
273 #FIXME: temporary ugly code | |
274 uri = stanza.firstChildElement().uri | |
275 if self._iq_cb_map.has_key(uri): | |
276 self._iq_cb_map[uri](stanza) | |
277 #TODO: manage errors stanza | |
278 | |
279 def presenceCb(self, elem): | |
280 info ("presence update for [%s]", elem.getAttribute("from")) | |
281 debug("\n\nXML=\n%s\n\n", elem.toXml()) | |
282 presence={} | |
283 presence["jid"]=elem.getAttribute("from") | |
284 presence["type"]=elem.getAttribute("type") or "" | |
285 presence["show"]="" | |
286 presence["status"]="" | |
287 presence["priority"]=0 | |
288 | |
289 for item in elem.elements(): | |
290 if presence.has_key(item.name): | |
291 presence[item.name]=item.children[0] | |
292 | |
293 ### we check if the status is not about subscription ### | |
294 #TODO: check that from jid is one we wants to subscribe (ie: check a recent subscription asking) | |
295 if jid.JID(presence["jid"]).userhost()!=self.me.userhost(): | |
296 if presence["type"]=="subscribed": | |
297 debug ("subscription answer") | |
298 elif presence["type"]=="unsubscribed": | |
299 debug ("unsubscription answer") | |
300 elif presence["type"]=="subscribe": | |
301 #FIXME: auto answer for subscribe request, must be checked ! | |
302 debug ("subscription request") | |
303 self.setPresence(to=presence["jid"], type="subscribed") | |
304 else: | |
305 #We keep presence information only if it is not for subscription | |
306 self.memory.addPresenceStatus(presence["jid"], presence["type"], presence["show"], | |
307 presence["status"], int(presence["priority"])) | |
308 | |
309 #now it's time to notify frontends | |
310 self.bridge.presenceUpdate(presence["jid"], presence["type"], presence["show"], | |
311 presence["status"], int(presence["priority"])) | |
312 | |
313 def rosterCb(self,roster): | |
314 for contact in roster.firstChildElement().elements(): | |
315 info ("new contact in roster list: %s", contact['jid']) | |
316 #and now the groups | |
317 groups=[] | |
318 for group in contact.elements(): | |
319 if group.name!="group": | |
320 error("Unexpected element !") | |
321 break | |
322 groups.append(str(group)) | |
323 self.memory.addContact(contact['jid'], contact.attributes, groups) | |
324 self.bridge.newContact(contact['jid'], contact.attributes, groups) | |
325 | |
326 def serverDisco(self, disco): | |
327 """xep-0030 Discovery Protocol.""" | |
328 for element in disco.firstChildElement().elements(): | |
329 if element.name=="feature": | |
330 debug ("Feature dectetee: %s",element["var"]) | |
331 self.server_features.append(element["var"]) | |
332 elif element.name=="identity": | |
333 debug ("categorie= %s",element["category"]) | |
334 debug ("features= %s",self.server_features) | |
335 | |
336 ## Generic HMI ## | |
337 | |
338 def askConfirmation(self, id, type, data, cb): | |
339 """Add a confirmation callback""" | |
340 if self._waiting_conf.has_key(id): | |
341 error ("Attempt to register two callbacks for the same confirmation") | |
342 else: | |
343 self._waiting_conf[id] = cb | |
344 self.bridge.askConfirmation(type, id, data) | |
345 | |
346 | |
347 def confirmationAnswer(self, id, accepted, data): | |
348 """Called by frontends to answer confirmation requests""" | |
349 debug ("Received confirmation answer for id [%s]: %s", id, "accepted" if accepted else "refused") | |
350 if not self._waiting_conf.has_key(id): | |
351 error ("Received an unknown confirmation") | |
352 else: | |
353 cb = self._waiting_conf[id] | |
354 del self._waiting_conf[id] | |
355 cb(id, accepted, data) | |
356 | |
357 def registerProgressCB(self, id, CB): | |
358 """Register a callback called when progress is requested for id""" | |
359 self._progress_cb_map[id] = CB | |
360 | |
361 def removeProgressCB(self, id): | |
362 """Remove a progress callback""" | |
363 if not self._progress_cb_map.has_key(id): | |
364 error ("Trying to remove an unknow progress callback") | |
365 else: | |
366 del self._progress_cb_map[id] | |
367 | |
368 def getProgress(self, id): | |
369 """Return a dict with progress information | |
370 data['position'] : current possition | |
371 data['size'] : end_position | |
372 """ | |
373 data = {} | |
374 try: | |
375 self._progress_cb_map[id](data) | |
376 except KeyError: | |
377 pass | |
378 #debug("Requested progress for unknown id") | |
379 return data | |
380 | |
381 | |
2
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
382 application = service.Application('SàT') |
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
383 sat = SAT() |
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
384 service = sat.getService() |
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
385 service.setServiceParent(application) |
0 | 386 |
2
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
387 |
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
388 #app.memory.save() #FIXME: not the best place |
c49345fd7737
refactoring: moved sat to sat.tac, now a twisted application so we can use twistd.
Goffi <goffi@goffi.org>
parents:
1
diff
changeset
|
389 #debug("Good Bye") |