comparison src/plugins/plugin_adhoc_dbus.py @ 822:30ed86ea1c82

plugin Ad-Hoc D-Bus: first draft: this plugin allow to easily use D-Bus with Ad-Hoc command. This first draft only allow to create a D-Bus remote for now.
author Goffi <goffi@goffi.org>
date Mon, 17 Feb 2014 18:57:06 +0100
parents
children 1a759096ccbd
comparison
equal deleted inserted replaced
821:38bc9abd6722 822:30ed86ea1c82
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # SAT plugin for adding D-Bus to Ad-Hoc Commands
5 # Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Jérôme Poisson (goffi@goffi.org)
6
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 from sat.core.i18n import _, D_
21 from logging import debug, info, warning, error
22 from twisted.words.protocols.jabber import jid
23 from twisted.internet import defer, reactor
24 from wokkel import data_form
25 from lxml import etree
26 from os import path
27 import uuid
28 import dbus
29 from dbus.mainloop.glib import DBusGMainLoop
30 DBusGMainLoop(set_as_default=True)
31
32 FD_NAME = "org.freedesktop.DBus"
33 FD_PATH = "/org/freedekstop/DBus"
34 INTROSPECT_IFACE = "org.freedesktop.DBus.Introspectable"
35
36 INTROSPECT_METHOD = "Introspect"
37 IGNORED_IFACES_START = ('org.freedesktop', 'org.qtproject', 'org.kde.KMainWindow') # commands in interface starting with these values will be ignored
38 FLAG_LOOP = 'LOOP'
39
40 PLUGIN_INFO = {
41 "name": "Ad-Hoc Commands - D-Bus",
42 "import_name": "AD_HOC_DBUS",
43 "type": "Misc",
44 "protocols": [],
45 "dependencies": ["XEP-0050"],
46 "main": "AdHocDBus",
47 "handler": "no",
48 "description": _("""Add D-Bus management to Ad-Hoc commands""")
49 }
50
51
52 class AdHocDBus(object):
53
54 def __init__(self, host):
55 info(_("plugin Ad-Hoc D-Bus initialization"))
56 self.host = host
57 host.bridge.addMethod("adHocDBusAddAuto", ".plugin", in_sign='sasasasasasass', out_sign='(sa(sss))',
58 method=self._adHocDBusAddAuto,
59 async=True)
60 self.session_bus = dbus.SessionBus()
61 self.fd_object = self.session_bus.get_object(FD_NAME, FD_PATH, introspect=False)
62 self.XEP_0050 = host.plugins['XEP-0050']
63
64 def _DBusAsyncCall(self, proxy, method, *args, **kwargs):
65 """ Call a DBus method asynchronously and return a deferred
66 @param proxy: DBus object proxy, as returner by get_object
67 @param method: name of the method to call
68 @param args: will be transmitted to the method
69 @param kwargs: will be transmetted to the method, except for the following poped values:
70 - interface: name of the interface to use
71 @return: a deferred
72
73 """
74 d = defer.Deferred()
75 interface = kwargs.pop('interface', None)
76 kwargs['reply_handler'] = lambda ret=None: d.callback(ret)
77 kwargs['error_handler'] = d.errback
78 proxy.get_dbus_method(method, dbus_interface=interface)(*args, **kwargs)
79 return d
80
81 def _DBusListNames(self):
82 return self._DBusAsyncCall(self.fd_object, "ListNames")
83
84 def _DBusIntrospect(self, proxy):
85 return self._DBusAsyncCall(proxy, INTROSPECT_METHOD, interface=INTROSPECT_IFACE)
86
87 def _acceptMethod(self, method):
88 """ Return True if we accept the method for a command
89 @param method: etree.Element
90 @return: True if the method is acceptable
91
92 """
93 if method.xpath("arg[@direction='in']"): # we don't accept method with argument for the moment
94 return False
95 return True
96
97 @defer.inlineCallbacks
98 def _introspect(self, methods, bus_name, proxy):
99 debug("introspecting path [%s]" % proxy.object_path)
100 introspect_xml = yield self._DBusIntrospect(proxy)
101 el = etree.fromstring(introspect_xml)
102 for node in el.iterchildren('node', 'interface'):
103 if node.tag == 'node':
104 new_path = path.join(proxy.object_path, node.get('name'))
105 new_proxy = self.session_bus.get_object(bus_name, new_path, introspect=False)
106 yield self._introspect(methods, bus_name, new_proxy)
107 elif node.tag == 'interface':
108 name = node.get('name')
109 if any(name.startswith(ignored) for ignored in IGNORED_IFACES_START):
110 debug('interface [%s] is ignored' % name)
111 continue
112 debug("introspecting interface [%s]" % name)
113 for method in node.iterchildren('method'):
114 if self._acceptMethod(method):
115 method_name = method.get('name')
116 debug("method accepted: [%s]" % method_name)
117 methods.add((proxy.object_path, name, method_name))
118
119 def _adHocDBusAddAuto(self, prog_name, allowed_jids, allowed_groups, allowed_magics, forbidden_jids, forbidden_groups, flags, profile_key):
120 return self.adHocDBusAddAuto(prog_name, allowed_jids, allowed_groups, allowed_magics, forbidden_jids, forbidden_groups, flags, profile_key)
121
122 @defer.inlineCallbacks
123 def adHocDBusAddAuto(self, prog_name, allowed_jids=None, allowed_groups=None, allowed_magics=None, forbidden_jids=None, forbidden_groups=None, flags=None, profile_key='@NONE@'):
124 bus_names = yield self._DBusListNames()
125 bus_names = [bus_name for bus_name in bus_names if '.' + prog_name in bus_name]
126 if not bus_names:
127 info("Can't find any bus for [%s]" % prog_name)
128 return
129 bus_names.sort()
130 for bus_name in bus_names:
131 if bus_name.endswith(prog_name):
132 break
133 info("bus name found: [%s]" % bus_name)
134 proxy = self.session_bus.get_object(bus_name, '/', introspect=False)
135 methods = set()
136
137 yield self._introspect(methods, bus_name, proxy)
138
139 if methods:
140 self._addCommand(prog_name, bus_name, methods,
141 allowed_jids = allowed_jids,
142 allowed_groups = allowed_groups,
143 allowed_magics = allowed_magics,
144 forbidden_jids = forbidden_jids,
145 forbidden_groups = forbidden_groups,
146 flags = flags,
147 profile_key = profile_key)
148
149 defer.returnValue((bus_name, methods))
150
151
152 def _addCommand(self, adhoc_name, bus_name, methods, allowed_jids=None, allowed_groups=None, allowed_magics=None, forbidden_jids=None, forbidden_groups=None, flags=None, profile_key='@NONE@'):
153 if flags is None:
154 flags = set()
155
156 def DBusCallback(command_elt, session_data, action, node, profile):
157 actions = session_data.setdefault('actions',[])
158 names_map = session_data.setdefault('names_map', {})
159 actions.append(action)
160
161 if len(actions) == 1:
162 # it's our first request, we ask the desired new status
163 status = self.XEP_0050.STATUS.EXECUTING
164 form = data_form.Form('form', title=_('Command selection'))
165 options = []
166 for path, iface, command in methods:
167 label = command.rsplit('.',1)[-1]
168 name = str(uuid.uuid4())
169 names_map[name] = (path, iface, command)
170 options.append(data_form.Option(name, label))
171
172 field = data_form.Field('list-single', 'command', options=options, required=True)
173 form.addField(field)
174
175 payload = form.toElement()
176 note = None
177
178 elif len(actions) == 2:
179 # we should have the answer here
180 try:
181 x_elt = command_elt.elements(data_form.NS_X_DATA,'x').next()
182 answer_form = data_form.Form.fromElement(x_elt)
183 command = answer_form['command']
184 except KeyError, StopIteration:
185 raise self.XEP_0050.AdHocError(self.XEP_0050.ERROR.BAD_PAYLOAD)
186
187 if command not in names_map:
188 raise self.XEP_0050.AdHocError(self.XEP_0050.ERROR.BAD_PAYLOAD)
189
190 path, iface, command = names_map[command]
191 proxy = self.session_bus.get_object(bus_name, path)
192
193 d = self._DBusAsyncCall(proxy, command, interface=iface)
194
195 # job done, we can end the session, except if we have FLAG_LOOP
196 if FLAG_LOOP in flags:
197 # We have a loop, so we clear everything and we execute again the command as we had a first call (command_elt is not used, so None is OK)
198 del actions[:]
199 names_map.clear()
200 return DBusCallback(None, session_data, self.XEP_0050.ACTION.EXECUTE, node, profile)
201 form = data_form.Form('form', title=_(u'Updated'))
202 form.addField(data_form.Field('fixed', u'Command sent'))
203 status = self.XEP_0050.STATUS.COMPLETED
204 payload = None
205 note = (self.XEP_0050.NOTE.INFO, _(u"Command sent"))
206 else:
207 raise self.XEP_0050.AdHocError(self.XEP_0050.ERROR.INTERNAL)
208
209 return (payload, status, None, note)
210
211 self.XEP_0050.addAdHocCommand(DBusCallback, adhoc_name,
212 allowed_jids = allowed_jids,
213 allowed_groups = allowed_groups,
214 allowed_magics = allowed_magics,
215 forbidden_jids = forbidden_jids,
216 forbidden_groups = forbidden_groups,
217 profile_key = profile_key)