Debian Codegraph @

isenkramd

raw
1 #!/usr/bin/python3
2 # -*- coding: utf-8 -*-
3 """
4 User Daemon to suggest packages to install when new hardware
5 is inserted into the machine.
6 """
7 # Copyright (C) 2013,2015-2016 Petter Reinholdtsen <[email protected]>
8 # AptDaemon gtk client code based on gtk-demo, copyright (C) 2008-2009
9 # Sebastian Heinlein <[email protected]>
10 #
11 # Licensed under the GNU General Public License Version 2
12 #
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
17 #
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26
27 __author__ = "Petter Reinholdtsen <[email protected]>"
28
29 use_apt_daemon = False
30
31 import string
32 import subprocess
33 import glob
34 import fnmatch
35 import os
36
37 import gi
38 from gi.repository import GLib
39 gi.require_version('Gtk', '3.0')
40 from gi.repository import Gtk
41 gi.require_version('GUdev', '1.0')
42 from gi.repository import GUdev
43 gi.require_version('Notify', '0.7')
44 from gi.repository import Notify
45 gi.require_version('PackageKitGlib', '1.0')
46 from gi.repository import PackageKitGlib as packagekit
47 from gi.repository import Gio
48
49 import isenkram.lookup
50 import isenkram.usb
51
52 if use_apt_daemon:
53 import aptdaemon.client
54 from aptdaemon.gtk3widgets import AptErrorDialog, \
55 AptConfirmDialog, \
56 AptProgressDialog
57 import aptdaemon.errors
58
59 class AptDaemonGUIClient(object):
60
61 """Provides a graphical interface to aptdaemon."""
62
63 def _run_transaction(self, transaction):
64 dia = AptProgressDialog(transaction, parent=self.win)
65 dia.run(close_on_finished=True, show_error=True,
66 reply_handler=lambda: True,
67 error_handler=self._on_error)
68
69 def _simulate_trans(self, trans):
70 trans.simulate(reply_handler=lambda: self._confirm_deps(trans),
71 error_handler=self._on_error)
72
73 def _confirm_deps(self, trans):
74 if [pkgs for pkgs in trans.dependencies if pkgs]:
75 dia = AptConfirmDialog(trans, parent=self.win)
76 res = dia.run()
77 dia.hide()
78 if res != Gtk.ResponseType.OK:
79 return
80 self._run_transaction(trans)
81
82 def _on_error(self, error):
83 try:
84 raise error
85 except aptdaemon.errors.NotAuthorizedError:
86 # Silently ignore auth failures
87 return
88 except aptdaemon.errors.TransactionFailed as error:
89 pass
90 except Exception as error:
91 error = aptdaemon.errors.TransactionFailed(aptdaemon.enums.ERROR_UNKNOWN,
92 str(error))
93 dia = AptErrorDialog(error)
94 dia.run()
95 dia.hide()
96
97 def request_installation(self, *args):
98 self.ac.install_packages([self.package],
99 reply_handler=self._simulate_trans,
100 error_handler=self._on_error)
101
102 def __init__(self, package):
103 self.win = None
104 self.package = package
105 self.loop = GLib.MainLoop()
106 self.ac = aptdaemon.client.AptClient()
107
108 def run(self):
109 self.loop.run()
110
111
112 # Good references for programming with PackageKit:
113 # https://lazka.github.io/pgi-docs/
114 # https://www.freedesktop.org/software/PackageKit/gtk-doc/libpackagekit-gobject.html
115 class PackageException(Exception):
116 """A package operation has failed."""
117
118 def __init__(self, error_string=None, error_details=None, *args, **kwargs):
119 """Store packagekit error string and details."""
120 super(PackageException, self).__init__(*args, **kwargs)
121
122 self.error_string = error_string
123 self.error_details = error_details
124
125 def __str__(self):
126 """Return the strin representation of the exception."""
127 return 'PackageException(error_string="{0}", error_details="{1}")' \
128 .format(self.error_string, self.error_details)
129
130
131 class PackageKitInstaller(object):
132 """Helper to install packages using PackageKit."""
133
134 def __init__(self, package_names):
135 """Initialize transaction object.
136
137 Set most values to None until they are sent as progress update.
138 """
139 self.package_names = package_names
140
141 # Progress
142 self.allow_cancel = None
143 self.percentage = None
144 self.status = None
145 self.status_string = None
146 self.flags = None
147 self.package = None
148 self.package_id = None
149 self.item_progress = None
150 self.role = None
151 self.caller_active = None
152 self.download_size_remaining = None
153 self.speed = None
154
155 def get_id(self):
156 """Return a identifier to use as a key in a map of transactions."""
157 return frozenset(self.package_names)
158
159 def __str__(self):
160 """Return the string representation of the object"""
161 return ('Transaction(packages={0}, allow_cancel={1}, status={2}, '
162 ' percentage={3}, package={4}, item_progress={5})').format(
163 self.package_names, self.allow_cancel, self.status_string,
164 self.percentage, self.package, self.item_progress)
165
166 def request_installation(self):
167 """Notify, start installation and then notify success/error."""
168 start_notification = Notify.Notification(
169 summary='Installing packages',
170 body='Installing packages - {packages}'.format(
171 packages=', '.join(self.package_names)))
172 start_notification.set_timeout(10000)
173 start_notification.show()
174
175 error = None
176 try:
177 self.install()
178 except PackageException as exception:
179 error = exception
180
181 start_notification.close()
182 if not error:
183 final_notification = Notify.Notification(
184 summary='Installation successful',
185 body='Packages have been successfully installed - {packages}'.
186 format(packages=', '.join(self.package_names)))
187 else:
188 final_notification = Notify.Notification(
189 summary='Installation failed',
190 body='Error installing packages: {string}, {details}'.format(
191 string=error.error_string, details=error.error_details))
192 final_notification.set_timeout(10000)
193 final_notification.show()
194
195 def install(self):
196 """Run a PackageKit transaction to install given packages."""
197 try:
198 self._do_install()
199 except GLib.Error as exception:
200 raise PackageException(exception.message)
201
202 def _do_install(self):
203 """Run a PackageKit transaction to install given packages.
204
205 Raise exception in case of error.
206 """
207 client = packagekit.Client()
208 client.set_interactive(False)
209
210 # Refresh package cache from all enabled repositories
211 results = client.refresh_cache(
212 False, None, self.progress_callback, self)
213 self._assert_success(results)
214
215 # Resolve packages again to get the latest versions after refresh
216 results = client.resolve(packagekit.FilterEnum.INSTALLED,
217 tuple(self.package_names) + (None, ),
218 None, self.progress_callback, self)
219 self._assert_success(results)
220
221 packages_resolved = {}
222 for package in results.get_package_array():
223 packages_resolved[package.get_name()] = package
224
225 package_ids = []
226 for package_name in self.package_names:
227 if package_name not in packages_resolved or \
228 not packages_resolved[package_name]:
229 raise PackageException('packages not found')
230
231 package_ids.append(packages_resolved[package_name].get_id())
232
233 # Start package installation
234 results = client.install_packages(
235 1 << packagekit.TransactionFlagEnum.ONLY_TRUSTED,
236 package_ids + [None],
237 None, self.progress_callback, self)
238 self._assert_success(results)
239
240 def _assert_success(self, results):
241 """Check that the most recent operation was a success."""
242 if results and results.get_error_code() is not None:
243 error = results.get_error_code()
244 error_code = error.get_code() if error else None
245 error_string = packagekit.ErrorEnum.to_string(error_code) \
246 if error_code else None
247 error_details = error.get_details() if error else None
248 raise PackageException(error_string, error_details)
249
250 def progress_callback(self, progress, progress_type, user_data):
251 """Process progress updates on package resolve operation"""
252 return
253 if progress_type == packagekit.ProgressType.PERCENTAGE:
254 self.percentage = progress.props.percentage
255 elif progress_type == packagekit.ProgressType.PACKAGE:
256 self.package = progress.props.package
257 elif progress_type == packagekit.ProgressType.ALLOW_CANCEL:
258 self.allow_cancel = progress.props.allow_cancel
259 elif progress_type == packagekit.ProgressType.PACKAGE_ID:
260 self.package_id = progress.props.package_id
261 elif progress_type == packagekit.ProgressType.ITEM_PROGRESS:
262 self.item_progress = progress.props.item_progress
263 elif progress_type == packagekit.ProgressType.STATUS:
264 self.status = progress.props.status
265 self.status_string = \
266 packagekit.StatusEnum.to_string(progress.props.status)
267 elif progress_type == packagekit.ProgressType.TRANSACTION_FLAGS:
268 self.flags = progress.props.transaction_flags
269 elif progress_type == packagekit.ProgressType.ROLE:
270 self.role = progress.props.role
271 elif progress_type == packagekit.ProgressType.CALLER_ACTIVE:
272 self.caller_active = progress.props.caller_active
273 elif progress_type == packagekit.ProgressType.DOWNLOAD_SIZE_REMAINING:
274 self.download_size_remaining = \
275 progress.props.download_size_remaining
276 elif progress_type == packagekit.ProgressType.SPEED:
277 self.speed = progress.props.speed
278 else:
279 print(('Unhandled packagekit progress callback - %s, %s',
280 progress, progress_type))
281
282
283 # Keep refs needed for callback to work
284 n = None
285 npkgs = None
286
287 def notify_pleaseinstall(notification=None, action=None, data=None):
288 pkgs = data
289 pkgsstr = " ".join(pkgs)
290 # print pkgs
291 print("info: button clicked, installing %s" % pkgsstr)
292 if use_apt_daemon:
293 installer = AptDaemonGUIClient(pkgs[0])
294 else:
295 installer = PackageKitInstaller(pkgs)
296 installer.request_installation()
297 def notify(bus, vendor, device, pkgs):
298 pkgstr = " ".join(pkgs)
299 if 'usb' == bus:
300 usbdb = isenkram.usb.usbdb()
301 usbinfo = usbdb.product(vendor, device)
302 usbdb = None
303 if usbinfo['vendorname'] is None:
304 usbinfo['vendorname'] = 'N/A'
305 if usbinfo['productname'] is None:
306 usbinfo['productname'] = 'N/A'
307
308 title = "New %s device inserted" % bus
309 text = "%s from vendor %s [%04x:%04x] supported by package(s) %s." \
310 % (usbinfo['productname'], usbinfo['vendorname'],
311 vendor, device, pkgstr)
312 else:
313 title = "New %s device inserted" % bus
314 text = "Device [%04x:%04x] supported by package(s) %s." \
315 % (vendor, device, pkgstr)
316
317 print("info: " + text)
318
319 # Initializite pynotify
320 if not Notify.init("isenkramd"):
321 return False
322 global n
323 global npkgs
324 npkgs = pkgs
325 n = Notify.Notification(summary=title, body=text)
326 n.set_timeout(10000)
327 n.add_action("clicked",
328 "Install program(s)",
329 notify_pleaseinstall, npkgs)
330 n.show()
331 return True
332
333 def is_pkg_installed(packagename):
334 cmd = ["dpkg", "-l", packagename]
335 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
336 retval = False
337 while True:
338 retcode = p.poll()
339 line = p.stdout.readline()
340 if 0 == line.find(b"ii "):
341 retval = True
342 if(retcode is not None):
343 break
344 return retval
345
346 def devid2modalias(bus, vendor, device):
347 target = "%s:v%04xp%04xd*" % (bus, vendor, device)
348 modalias = None
349 for filename in glob.iglob("/sys/bus/%s/devices/*/modalias" % bus):
350 f = open(filename)
351 line = f.readline().strip()
352 # print line, target
353 if fnmatch.fnmatch(line, target):
354 modalias = line
355 # print filename
356 f.close()
357 return modalias
358
359 def get_pkg_suggestions_aptmodaliases(modalias):
360 print("info: checking appstream modaliases info")
361 return isenkram.lookup.pkgs_handling_appstream_modaliases([modalias])
362
363 def get_pkg_suggestions_mymodaliases(modalias):
364 print("info: checking my modaliases file (from svn)")
365 return isenkram.lookup.pkgs_handling_extra_modaliases([modalias])
366
367 def get_pkg_suggestions(modalias):
368 pkgs = []
369 # discoverpkgs = get_pkg_suggestions_discover(bus, vendor, device)
370 # pkgs.extend(discoverpkgs)
371 aptpkgs = get_pkg_suggestions_aptmodaliases(modalias)
372 pkgs.extend(aptpkgs)
373 mypkgs = get_pkg_suggestions_mymodaliases(modalias)
374 pkgs.extend(mypkgs)
375 # Avoid duplicates in package list
376 phash = {}
377 for p in pkgs:
378 phash[p] = 1
379 pkgs = list(phash.keys())
380 return sorted(pkgs)
381
382 def uevent_callback(client, action, device, user_data):
383 modalias = device.get_property("MODALIAS")
384 # Map loaded kernel modules to lkmodule:modulename "modalias"
385 if ("add" == action and "module" == device.get_subsystem()):
386 modalias = "lkmodule:%s" % (device.get_property("DEVPATH").split("/"))[2]
387 if ("add" == action and modalias is not None):
388 device_vendor = device.get_property("ID_VENDOR_ENC")
389 device_model = device.get_property("ID_MODEL_ENC")
390 print("uevent %s %s %s" % (device_vendor, device_model, modalias))
391 bus = device.get_subsystem()
392 if "usb" == bus:
393 print("info: discovered USB device %s %s" % (device_vendor,
394 device_model))
395 pkgs = get_pkg_suggestions(modalias)
396 # print "Suggestions: ", pkgs
397 newpkg = []
398 alreadyinstalled = []
399 for pkg in pkgs:
400 if not is_pkg_installed(pkg):
401 newpkg.append(pkg)
402 else:
403 alreadyinstalled.append(pkg)
404 print("info: not proposing already installed package(s) %s" % \
405 ', '.join(alreadyinstalled))
406 if 0 < len(newpkg):
407 vendorid, deviceid, bcdevice = \
408 device.get_property("PRODUCT").split("/")
409 notify(bus, int(vendorid, 16), int(deviceid, 16), newpkg)
410
411 def restart_daemon(monitor, file1, file2, evt_type):
412 if (evt_type == Gio.FileMonitorEvent.CHANGED):
413 scriptname = file1.get_path()
414 os.execl(scriptname, scriptname)
415
416 def main():
417 client = GUdev.Client(subsystems=[])
418 client.connect("uevent", uevent_callback, None)
419
420 # Restart daemon if the file on disk changes, to handle package upgrades
421 scriptname = os.path.realpath(__file__)
422 gfile = Gio.File.new_for_path(scriptname)
423 monitor = gfile.monitor_file(Gio.FileMonitorFlags.NONE, None)
424 monitor.connect("changed", restart_daemon)
425
426 loop = GLib.MainLoop()
427 print("info: ready to accept hardware events")
428 loop.run()
429
430 if __name__ == '__main__':
431 main()