2 Integrates download callbacks with an external mainloop.
3 While things are being downloaded, Zero Install returns control to your program.
4 Your mainloop is responsible for monitoring the state of the downloads and notifying
5 Zero Install when they are complete.
7 To do this, you supply a L{Handler} to the L{policy}.
10 # Copyright (C) 2009, Thomas Leonard
11 # See the README file for details, or visit http://0install.net.
13 from zeroinstall
import _
15 from logging
import warn
, info
17 from zeroinstall
import NeedDownload
, SafeException
18 from zeroinstall
.support
import tasks
19 from zeroinstall
.injector
import download
21 KEY_INFO_TIMEOUT
= 10 # Maximum time to wait for response from key-info-server
23 class NoTrustedKeys(SafeException
):
24 """Thrown by L{Handler.confirm_import_feed} on failure."""
27 class Handler(object):
29 This implementation uses the GLib mainloop. Note that QT4 can use the GLib mainloop too.
31 @ivar monitored_downloads: dict of downloads in progress
32 @type monitored_downloads: {URL: L{download.Download}}
33 @ivar n_completed_downloads: number of downloads which have finished for GUIs, etc (can be reset as desired).
34 @type n_completed_downloads: int
35 @ivar total_bytes_downloaded: informational counter for GUIs, etc (can be reset as desired). Updated when download finishes.
36 @type total_bytes_downloaded: int
37 @ivar dry_run: instead of starting a download, just report what we would have downloaded
41 __slots__
= ['monitored_downloads', 'dry_run', 'total_bytes_downloaded', 'n_completed_downloads', '_current_confirm']
43 def __init__(self
, mainloop
= None, dry_run
= False):
44 self
.monitored_downloads
= {}
45 self
.dry_run
= dry_run
46 self
.n_completed_downloads
= 0
47 self
.total_bytes_downloaded
= 0
48 self
._current
_confirm
= None
50 def monitor_download(self
, dl
):
51 """Called when a new L{download} is started.
52 This is mainly used by the GUI to display the progress bar."""
54 self
.monitored_downloads
[dl
.url
] = dl
55 self
.downloads_changed()
58 def download_done_stats():
60 # NB: we don't check for exceptions here; someone else should be doing that
62 self
.n_completed_downloads
+= 1
63 self
.total_bytes_downloaded
+= dl
.get_bytes_downloaded_so_far()
64 del self
.monitored_downloads
[dl
.url
]
65 self
.downloads_changed()
70 def impl_added_to_store(self
, impl
):
71 """Called by the L{fetch.Fetcher} when adding an implementation.
72 The GUI uses this to update its display.
73 @param impl: the implementation which has been added
74 @type impl: L{model.Implementation}
78 def downloads_changed(self
):
79 """This is just for the GUI to override to update its display."""
82 def wait_for_blocker(self
, blocker
):
83 """@deprecated: use tasks.wait_for_blocker instead"""
84 tasks
.wait_for_blocker(blocker
)
86 def get_download(self
, url
, force
= False, hint
= None, factory
= None):
87 """Return the Download object currently downloading 'url'.
88 If no download for this URL has been started, start one now (and
90 If the download failed and force is False, return it anyway.
91 If force is True, abort any current or failed download and start
93 @rtype: L{download.Download}
96 raise NeedDownload(url
)
99 dl
= self
.monitored_downloads
[url
]
105 dl
= download
.Download(url
, hint
)
107 dl
= factory(url
, hint
)
108 self
.monitor_download(dl
)
111 def confirm_keys(self
, pending
, fetch_key_info
):
112 """We don't trust any of the signatures yet. Ask the user.
113 When done update the L{trust} database, and then call L{trust.TrustDB.notify}.
114 This method starts downloading information about the signing keys and calls L{confirm_import_feed}.
116 @arg pending: an object holding details of the updated feed
117 @type pending: L{PendingFeed}
118 @arg fetch_key_info: a function which can be used to fetch information about a key fingerprint
119 @type fetch_key_info: str -> L{Blocker}
120 @return: A blocker that triggers when the user has chosen, or None if already done.
121 @rtype: None | L{Blocker}"""
125 from zeroinstall
.injector
import gpg
126 valid_sigs
= [s
for s
in pending
.sigs
if isinstance(s
, gpg
.ValidSig
)]
131 msg
+= "\nMessages from GPG:\n" + sig
.messages
133 raise SafeException(_('No valid signatures found on "%(url)s". Signatures:%(signatures)s') %
134 {'url': pending
.url
, 'signatures': ''.join(['\n- ' + format_sig(s
) for s
in pending
.sigs
])})
136 # Start downloading information about the keys...
138 for sig
in valid_sigs
:
139 kfs
[sig
] = fetch_key_info(sig
.fingerprint
)
141 return self
._queue
_confirm
_import
_feed
(pending
, kfs
)
144 def _queue_confirm_import_feed(self
, pending
, valid_sigs
):
145 # Wait up to KEY_INFO_TIMEOUT seconds for key information to arrive. Avoids having the dialog
146 # box update while the user is looking at it, and may allow it to be skipped completely in some
148 timeout
= tasks
.TimeoutBlocker(KEY_INFO_TIMEOUT
, "key info timeout")
150 key_info_blockers
= [sig_info
.blocker
for sig_info
in valid_sigs
.values() if sig_info
.blocker
is not None]
151 if not key_info_blockers
:
153 info("Waiting for response from key-info server: %s", key_info_blockers
)
154 yield [timeout
] + key_info_blockers
156 info("Timeout waiting for key info response")
159 # If we're already confirming something else, wait for that to finish...
160 while self
._current
_confirm
is not None:
161 info("Waiting for previous key confirmations to finish")
162 yield self
._current
_confirm
164 # Check whether we still need to confirm. The user may have
165 # already approved one of the keys while dealing with another
167 from zeroinstall
.injector
import trust
168 domain
= trust
.domain_from_url(pending
.url
)
169 for sig
in valid_sigs
:
170 is_trusted
= trust
.trust_db
.is_trusted(sig
.fingerprint
, domain
)
174 # Take the lock and confirm this feed
175 self
._current
_confirm
= lock
= tasks
.Blocker('confirm key lock')
177 done
= self
.confirm_import_feed(pending
, valid_sigs
)
182 self
._current
_confirm
= None
186 def confirm_import_feed(self
, pending
, valid_sigs
):
187 """Sub-classes should override this method to interact with the user about new feeds.
188 If multiple feeds need confirmation, L{confirm_keys} will only invoke one instance of this
190 @param pending: the new feed to be imported
191 @type pending: L{PendingFeed}
192 @param valid_sigs: maps signatures to a list of fetchers collecting information about the key
193 @type valid_sigs: {L{gpg.ValidSig} : L{fetch.KeyInfoFetcher}}
195 @see: L{confirm_keys}"""
196 from zeroinstall
.injector
import trust
200 domain
= trust
.domain_from_url(pending
.url
)
202 # Ask on stderr, because we may be writing XML to stdout
203 print >>sys
.stderr
, _("Feed: %s") % pending
.url
204 print >>sys
.stderr
, _("The feed is correctly signed with the following keys:")
206 print >>sys
.stderr
, "-", x
210 for node
in parent
.childNodes
:
211 if node
.nodeType
== node
.TEXT_NODE
:
212 text
= text
+ node
.data
216 key_info_fetchers
= valid_sigs
.values()
217 while key_info_fetchers
:
218 old_kfs
= key_info_fetchers
219 key_info_fetchers
= []
221 infos
= set(kf
.info
) - shown
223 if len(valid_sigs
) > 1:
224 print "%s: " % kf
.fingerprint
225 for key_info
in infos
:
226 print >>sys
.stderr
, "-", text(key_info
)
229 key_info_fetchers
.append(kf
)
230 if key_info_fetchers
:
231 for kf
in key_info_fetchers
: print >>sys
.stderr
, kf
.status
232 stdin
= tasks
.InputBlocker(0, 'console')
233 blockers
= [kf
.blocker
for kf
in key_info_fetchers
] + [stdin
]
238 except Exception, ex
:
239 warn(_("Failed to get key info: %s"), ex
)
241 print >>sys
.stderr
, _("Skipping remaining key lookups due to input from user")
244 if len(valid_sigs
) == 1:
245 print >>sys
.stderr
, _("Do you want to trust this key to sign feeds from '%s'?") % domain
247 print >>sys
.stderr
, _("Do you want to trust all of these keys to sign feeds from '%s'?") % domain
249 print >>sys
.stderr
, _("Trust [Y/N] "),
253 raise NoTrustedKeys(_('Not signed with a trusted key'))
256 for key
in valid_sigs
:
257 print >>sys
.stderr
, _("Trusting %(key_fingerprint)s for %(domain)s") % {'key_fingerprint': key
.fingerprint
, 'domain': domain
}
258 trust
.trust_db
.trust_key(key
.fingerprint
, domain
)
260 confirm_import_feed
.original
= True
263 def confirm_install(self
, msg
):
264 """We need to check something with the user before continuing with the install.
265 @raise download.DownloadAborted: if the user cancels"""
267 print >>sys
.stderr
, msg
269 sys
.stderr
.write(_("Install [Y/N] "))
273 raise download
.DownloadAborted()
277 def report_error(self
, exception
, tb
= None):
278 """Report an exception to the user.
279 @param exception: the exception to report
280 @type exception: L{SafeException}
281 @param tb: optional traceback
283 warn("%s", str(exception
) or type(exception
))
285 #traceback.print_exception(exception, None, tb)
287 class ConsoleHandler(Handler
):
288 """A Handler that displays progress on stdout (a tty).
295 def downloads_changed(self
):
297 if self
.monitored_downloads
and self
.update
is None:
298 if self
.screen_width
is None:
302 self
.screen_width
= curses
.tigetnum('cols') or 80
303 except Exception, ex
:
304 info("Failed to initialise curses library: %s", ex
)
305 self
.screen_width
= 80
307 self
.update
= gobject
.timeout_add(200, self
.show_progress
)
308 elif len(self
.monitored_downloads
) == 0:
310 gobject
.source_remove(self
.update
)
313 self
.last_msg_len
= None
315 def show_progress(self
):
316 urls
= self
.monitored_downloads
.keys()
317 if not urls
: return True
319 if self
.disable_progress
: return True
321 screen_width
= self
.screen_width
- 2
322 item_width
= max(16, screen_width
/ len(self
.monitored_downloads
))
323 url_width
= item_width
- 7
326 for url
in sorted(urls
):
327 dl
= self
.monitored_downloads
[url
]
328 so_far
= dl
.get_bytes_downloaded_so_far()
329 leaf
= url
.rsplit('/', 1)[-1]
330 if len(leaf
) >= url_width
:
331 display
= leaf
[:url_width
]
333 display
= url
[-url_width
:]
335 msg
+= "[%s %d%%] " % (display
, int(so_far
* 100 / dl
.expected_size
))
337 msg
+= "[%s] " % (display
)
338 msg
= msg
[:screen_width
]
340 if self
.last_msg_len
is None:
341 sys
.stdout
.write(msg
)
343 sys
.stdout
.write(chr(13) + msg
)
344 if len(msg
) < self
.last_msg_len
:
345 sys
.stdout
.write(" " * (self
.last_msg_len
- len(msg
)))
347 self
.last_msg_len
= len(msg
)
352 def clear_display(self
):
353 if self
.last_msg_len
!= None:
354 sys
.stdout
.write(chr(13) + " " * self
.last_msg_len
+ chr(13))
356 self
.last_msg_len
= None
358 def report_error(self
, exception
, tb
= None):
360 Handler
.report_error(self
, exception
, tb
)
362 def confirm_import_feed(self
, pending
, valid_sigs
):
364 self
.disable_progress
+= 1
365 blocker
= Handler
.confirm_import_feed(self
, pending
, valid_sigs
)
369 self
.disable_progress
-= 1