2 PackageKit integration.
5 # Copyright (C) 2010, Aleksey Lim
6 # See the README file for details, or visit http://0install.net.
11 from zeroinstall
import _
, SafeException
13 from zeroinstall
.support
import tasks
14 from zeroinstall
.injector
import download
, model
16 _logger_pk
= logging
.getLogger('packagekit')
20 import dbus
.mainloop
.glib
21 dbus
.mainloop
.glib
.DBusGMainLoop(set_as_default
=True)
22 except Exception as ex
:
23 _logger_pk
.info("D-BUS not available: %s", ex
)
26 class PackageKit(object):
30 self
._candidates
= {} # { package_name : (version, arch, size) | Blocker }
34 return self
.pk
is not None
40 self
._pk
= dbus
.Interface(dbus
.SystemBus().get_object(
41 'org.freedesktop.PackageKit',
42 '/org/freedesktop/PackageKit', False),
43 'org.freedesktop.PackageKit')
44 _logger_pk
.info(_('PackageKit dbus service found'))
45 except Exception as ex
:
46 _logger_pk
.info(_('PackageKit dbus service not found: %s'), ex
)
50 def get_candidates(self
, package_name
, factory
, prefix
):
51 """Add any cached candidates.
52 The candidates are those discovered by a previous call to L{fetch_candidates}.
53 @param package_name: the distribution's name for the package
54 @param factory: a function to add a new implementation to the feed
55 @param prefix: the prefix for the implementation's ID
57 candidate
= self
._candidates
.get(package_name
, None)
61 if isinstance(candidate
, tasks
.Blocker
):
62 return # Fetch still in progress
64 impl_name
= '%s:%s:%s:%s' % (prefix
, package_name
, candidate
['version'], candidate
['arch'])
66 impl
= factory(impl_name
, only_if_missing
= True, installed
= candidate
['installed'])
68 # (checking this way because the cached candidate['installed'] may be stale)
69 return # Already installed
71 impl
.version
= model
.parse_version(candidate
['version'])
72 if candidate
['arch'] != '*':
73 impl
.machine
= candidate
['arch']
76 packagekit_id
= candidate
['packagekit_id']
77 def download_factory(url
, hint
):
78 return PackageKitDownload(url
, hint
, pk
= self
.pk
, packagekit_id
= packagekit_id
)
79 dl
= handler
.get_download('packagekit:' + packagekit_id
, factory
= download_factory
, hint
= impl
)
80 dl
.expected_size
= candidate
['size']
82 impl
.download_sources
.append(model
.DistributionSource(package_name
, candidate
['size'], install
))
85 def fetch_candidates(self
, package_names
):
88 known
= [self
._candidates
[p
] for p
in package_names
if p
in self
._candidates
]
89 # (use set because a single task may be checking multiple packages and we need
90 # to avoid duplicates).
91 in_progress
= list(set([b
for b
in known
if isinstance(b
, tasks
.Blocker
)]))
92 _logger_pk
.debug('Already downloading: %s', in_progress
)
94 # Filter out the ones we've already fetched
95 package_names
= [p
for p
in package_names
if p
not in self
._candidates
]
102 def error_cb(sender
):
103 # Note: probably just means the package wasn't found
104 _logger_pk
.info(_('Transaction failed: %s(%s)'), sender
.error_code
, sender
.error_details
)
107 def details_cb(sender
):
108 for packagekit_id
, info
in versions
.items():
109 if packagekit_id
in sender
.details
:
110 info
.update(sender
.details
[packagekit_id
])
111 info
['packagekit_id'] = packagekit_id
112 self
._candidates
[info
['name']] = info
114 _logger_pk
.info(_('Empty details for %s'), packagekit_id
)
117 def resolve_cb(sender
):
119 versions
.update(sender
.package
)
120 tran
= _PackageKitTransaction(self
.pk
, details_cb
, error_cb
)
121 tran
.proxy
.GetDetails(versions
.keys())
123 _logger_pk
.info(_('Empty resolve for %s'), package_names
)
127 blocker
= tasks
.Blocker('PackageKit %s' % package_names
)
128 for package
in package_names
:
129 self
._candidates
[package
] = blocker
131 _logger_pk
.debug(_('Ask for %s'), package_names
)
132 tran
= _PackageKitTransaction(self
.pk
, resolve_cb
, error_cb
)
133 tran
.proxy
.Resolve('none', package_names
)
135 in_progress
.append(blocker
)
139 in_progress
= [b
for b
in in_progress
if not b
.happened
]
141 class PackageKitDownload(download
.Download
):
142 def __init__(self
, url
, hint
, pk
, packagekit_id
):
143 download
.Download
.__init
__(self
, url
, hint
)
145 self
.packagekit_id
= packagekit_id
147 self
._transaction
= None
151 assert self
.status
== download
.download_starting
152 assert self
.downloaded
is None
154 def error_cb(sender
):
155 self
.status
= download
.download_failed
156 ex
= SafeException('PackageKit install failed: %s' % (sender
.error_details
or sender
.error_code
))
157 self
.downloaded
.trigger(exception
= (ex
, None))
159 def installed_cb(sender
):
160 self
._impl
.installed
= True;
161 self
.status
= download
.download_complete
162 self
.downloaded
.trigger()
164 def install_packages():
165 package_name
= self
.packagekit_id
166 self
._transaction
= _PackageKitTransaction(self
.pk
, installed_cb
, error_cb
)
167 self
._transaction
.compat_call([
168 ('InstallPackages', [package_name
]),
169 ('InstallPackages', False, [package_name
]),
172 _auth_wrapper(install_packages
)
174 self
.status
= download
.download_fetching
175 self
.downloaded
= tasks
.Blocker('PackageKit install %s' % self
.packagekit_id
)
178 _logger_pk
.debug(_('Cancel transaction'))
179 self
.aborted_by_user
= True
180 self
._transaction
.proxy
.Cancel()
181 self
.status
= download
.download_failed
182 self
.downloaded
.trigger()
184 def get_current_fraction(self
):
185 if self
._transaction
is None:
187 percentage
= self
._transaction
.getPercentage()
191 return float(percentage
) / 100.
193 def get_bytes_downloaded_so_far(self
):
194 fraction
= self
.get_current_fraction()
198 if self
.expected_size
is None:
200 return int(self
.expected_size
* fraction
)
202 def _auth_wrapper(method
, *args
):
205 except dbus
.exceptions
.DBusException
as e
:
206 if e
.get_dbus_name() != \
207 'org.freedesktop.PackageKit.Transaction.RefusedByPolicy':
210 iface
, auth
= e
.get_dbus_message().split()
211 if not auth
.startswith('auth_'):
214 _logger_pk
.debug(_('Authentication required for %s'), auth
)
216 pk_auth
= dbus
.SessionBus().get_object(
217 'org.freedesktop.PolicyKit.AuthenticationAgent', '/',
218 'org.gnome.PolicyKit.AuthorizationManager.SingleInstance')
220 if not pk_auth
.ObtainAuthorization(iface
, dbus
.UInt32(0),
221 dbus
.UInt32(os
.getpid()), timeout
=300):
226 class _PackageKitTransaction(object):
227 def __init__(self
, pk
, finished_cb
=None, error_cb
=None):
228 self
._finished
_cb
= finished_cb
229 self
._error
_cb
= error_cb
230 self
.error_code
= None
231 self
.error_details
= None
236 self
.object = dbus
.SystemBus().get_object(
237 'org.freedesktop.PackageKit', pk
.GetTid(), False)
238 self
.proxy
= dbus
.Interface(self
.object,
239 'org.freedesktop.PackageKit.Transaction')
240 self
._props
= dbus
.Interface(self
.object, dbus
.PROPERTIES_IFACE
)
243 for signal
, cb
in [('Finished', self
.__finished
_cb
),
244 ('ErrorCode', self
.__error
_code
_cb
),
245 ('StatusChanged', self
.__status
_changed
_cb
),
246 ('Package', self
.__package
_cb
),
247 ('Details', self
.__details
_cb
),
248 ('Files', self
.__files
_cb
)]:
249 self
._signals
.append(self
.proxy
.connect_to_signal(signal
, cb
))
251 defaultlocale
= locale
.getdefaultlocale()[0]
252 if defaultlocale
is not None:
254 ('SetLocale', defaultlocale
),
255 ('SetHints', ['locale=%s' % defaultlocale
]),
258 def getPercentage(self
):
259 result
= self
.get_prop('Percentage')
261 result
, __
, __
, __
= self
.proxy
.GetProgress()
264 def get_prop(self
, prop
, default
= None):
266 return self
._props
.Get('org.freedesktop.PackageKit.Transaction', prop
)
270 def compat_call(self
, calls
):
275 dbus_method
= self
.proxy
.get_dbus_method(method
)
276 return dbus_method(*args
)
277 except dbus
.exceptions
.DBusException
as e
:
278 if e
.get_dbus_name() != \
279 'org.freedesktop.DBus.Error.UnknownMethod':
281 raise Exception('Cannot call %r DBus method' % calls
)
283 def __finished_cb(self
, exit
, runtime
):
284 _logger_pk
.debug(_('Transaction finished: %s'), exit
)
286 for i
in self
._signals
:
289 if self
.error_code
is not None:
292 self
._finished
_cb
(self
)
294 def __error_code_cb(self
, code
, details
):
295 _logger_pk
.info(_('Transaction failed: %s(%s)'), details
, code
)
296 self
.error_code
= code
297 self
.error_details
= details
299 def __package_cb(self
, status
, id, summary
):
300 from zeroinstall
.injector
import distro
302 package_name
, version
, arch
, repo_
= id.split(';')
303 clean_version
= distro
.try_cleanup_distro_version(version
)
304 if not clean_version
:
305 _logger_pk
.warn(_("Can't parse distribution version '%(version)s' for package '%(package)s'"), {'version': version
, 'package': package_name
})
306 clean_arch
= distro
.canonical_machine(arch
)
307 package
= {'version': clean_version
,
308 'name': package_name
,
310 'installed': (status
== 'installed')}
311 _logger_pk
.debug(_('Package: %s %r'), id, package
)
312 self
.package
[str(id)] = package
314 def __details_cb(self
, id, licence
, group
, detail
, url
, size
):
315 details
= {'licence': str(licence
),
317 'detail': str(detail
),
320 _logger_pk
.debug(_('Details: %s %r'), id, details
)
321 self
.details
[id] = details
323 def __files_cb(self
, id, files
):
324 self
.files
[id] = files
.split(';')
326 def __status_changed_cb(self
, status
):