Fixed support for setting --main with 0alias
[zeroinstall.git] / zeroinstall / injector / download.py
blobf942ee6320a166ff2d8956e25562b2bba99972a4
1 """
2 Handles URL downloads.
4 This is the low-level interface for downloading interfaces, implementations, icons, etc.
6 @see: L{fetch} higher-level API for downloads that uses this module
7 """
9 # Copyright (C) 2009, Thomas Leonard
10 # See the README file for details, or visit http://0install.net.
12 import tempfile, os, sys, threading, gobject
14 from zeroinstall import SafeException
15 from zeroinstall.support import tasks
16 from logging import info, debug
17 from zeroinstall import _
19 download_starting = "starting" # Waiting for UI to start it
20 download_fetching = "fetching" # In progress
21 download_complete = "complete" # Downloaded and cached OK
22 download_failed = "failed"
24 # NB: duplicated in _download_child.py
25 RESULT_OK = 0
26 RESULT_FAILED = 1
27 RESULT_NOT_MODIFIED = 2
29 class DownloadError(SafeException):
30 """Download process failed."""
31 pass
33 class DownloadAborted(DownloadError):
34 """Download aborted because of a call to L{Download.abort}"""
35 def __init__(self, message = None):
36 SafeException.__init__(self, message or _("Download aborted at user's request"))
38 class Download(object):
39 """A download of a single resource to a temporary file.
40 @ivar url: the URL of the resource being fetched
41 @type url: str
42 @ivar tempfile: the file storing the downloaded data
43 @type tempfile: file
44 @ivar status: the status of the download
45 @type status: (download_starting | download_fetching | download_failed | download_complete)
46 @ivar expected_size: the expected final size of the file
47 @type expected_size: int | None
48 @ivar downloaded: triggered when the download ends (on success or failure)
49 @type downloaded: L{tasks.Blocker}
50 @ivar hint: hint passed by and for caller
51 @type hint: object
52 @ivar aborted_by_user: whether anyone has called L{abort}
53 @type aborted_by_user: bool
54 @ivar unmodified: whether the resource was not modified since the modification_time given at construction
55 @type unmodified: bool
56 """
57 __slots__ = ['url', 'tempfile', 'status', 'expected_size', 'downloaded',
58 'hint', '_final_total_size', 'aborted_by_user',
59 'modification_time', 'unmodified']
61 def __init__(self, url, hint = None, modification_time = None):
62 """Create a new download object.
63 @param url: the resource to download
64 @param hint: object with which this download is associated (an optional hint for the GUI)
65 @param modification_time: string with HTTP date that indicates last modification time.
66 The resource will not be downloaded if it was not modified since that date.
67 @postcondition: L{status} == L{download_starting}."""
68 self.url = url
69 self.status = download_starting
70 self.hint = hint
71 self.aborted_by_user = False
72 self.modification_time = modification_time
73 self.unmodified = False
75 self.tempfile = None # Stream for result
76 self.downloaded = None
78 self.expected_size = None # Final size (excluding skipped bytes)
79 self._final_total_size = None # Set when download is finished
81 def start(self):
82 """Create a temporary file and begin the download.
83 @precondition: L{status} == L{download_starting}"""
84 assert self.status == download_starting
85 assert self.downloaded is None
87 self.status = download_fetching
88 self.tempfile = tempfile.TemporaryFile(prefix = 'injector-dl-data-')
90 task = tasks.Task(self._do_download(), "download " + self.url)
91 self.downloaded = task.finished
93 def _do_download(self):
94 """Will trigger L{downloaded} when done (on success or failure)."""
95 from ._download_child import download_in_thread
97 result = []
98 thread_blocker = tasks.Blocker("wait for thread " + self.url)
99 def notify_done(status, ex = None):
100 result.append(status)
101 def wake_up_main():
102 thread_blocker.trigger(ex)
103 return False
104 gobject.idle_add(wake_up_main)
105 child = threading.Thread(target = lambda: download_in_thread(self.url, self.tempfile, self.modification_time, notify_done))
106 child.daemon = True
107 child.start()
109 # Wait for child to complete download.
110 yield thread_blocker
112 # Download is complete...
113 child.join()
115 assert self.status is download_fetching
116 assert self.tempfile is not None
118 status, = result
120 if status == RESULT_NOT_MODIFIED:
121 debug("%s not modified", self.url)
122 self.tempfile = None
123 self.unmodified = True
124 self.status = download_complete
125 self._final_total_size = 0
126 self.downloaded.trigger()
127 return
129 self._final_total_size = self.get_bytes_downloaded_so_far()
131 self.tempfile = None
133 if self.aborted_by_user:
134 assert self.downloaded.happened
135 raise DownloadAborted()
137 try:
139 tasks.check(thread_blocker)
141 assert status == RESULT_OK
143 # Check that the download has the correct size, if we know what it should be.
144 if self.expected_size is not None:
145 if self._final_total_size != self.expected_size:
146 raise SafeException(_('Downloaded archive has incorrect size.\n'
147 'URL: %(url)s\n'
148 'Expected: %(expected_size)d bytes\n'
149 'Received: %(size)d bytes') % {'url': self.url, 'expected_size': self.expected_size, 'size': self._final_total_size})
150 except:
151 self.status = download_failed
152 _unused, ex, tb = sys.exc_info()
153 self.downloaded.trigger(exception = (ex, tb))
154 else:
155 self.status = download_complete
156 self.downloaded.trigger()
158 def abort(self):
159 """Signal the current download to stop.
160 @postcondition: L{aborted_by_user}"""
161 self.status = download_failed
163 if self.tempfile is not None:
164 info(_("Aborting download of %s"), self.url)
165 # TODO: we currently just close the output file; the thread will end when it tries to
166 # write to it. We should try harder to stop the thread immediately (e.g. by closing its
167 # socket when known), although we can never cover all cases (e.g. a stuck DNS lookup).
168 # In any case, we don't wait for the child to exit before notifying tasks that are waiting
169 # on us.
170 self.aborted_by_user = True
171 self.tempfile.close()
172 self.tempfile = None
173 self.downloaded.trigger((DownloadAborted(), None))
175 def get_current_fraction(self):
176 """Returns the current fraction of this download that has been fetched (from 0 to 1),
177 or None if the total size isn't known.
178 @return: fraction downloaded
179 @rtype: int | None"""
180 if self.status is download_starting:
181 return 0
182 if self.tempfile is None:
183 return 1
184 if self.expected_size is None:
185 return None # Unknown
186 current_size = self.get_bytes_downloaded_so_far()
187 return float(current_size) / self.expected_size
189 def get_bytes_downloaded_so_far(self):
190 """Get the download progress. Will be zero if the download has not yet started.
191 @rtype: int"""
192 if self.status is download_starting:
193 return 0
194 elif self.status is download_fetching:
195 return os.fstat(self.tempfile.fileno()).st_size
196 else:
197 return self._final_total_size or 0
199 def __str__(self):
200 return _("<Download from %s>") % self.url