1 from __future__ import unicode_literals
10 from .common import FileDownloader
11 from ..compat import (
23 XAttrUnavailableError,
27 class HttpFD(FileDownloader):
28 def real_download(self, filename, info_dict):
29 url = info_dict['url']
31 class DownloadContext(dict):
32 __getattr__ = dict.get
33 __setattr__ = dict.__setitem__
34 __delattr__ = dict.__delitem__
36 ctx = DownloadContext()
37 ctx.filename = filename
38 ctx.tmpfilename = self.temp_name(filename)
41 # Do not include the Accept-Encoding header
42 headers = {'Youtubedl-no-compression': 'True'}
43 add_headers = info_dict.get('http_headers')
45 headers.update(add_headers)
47 is_test = self.params.get('test', False)
48 chunk_size = self._TEST_FILE_SIZE if is_test else (
49 info_dict.get('downloader_options', {}).get('http_chunk_size')
50 or self.params.get('http_chunk_size') or 0)
55 ctx.block_size = self.params.get('buffersize', 1024)
56 ctx.start_time = time.time()
59 if self.params.get('continuedl', True):
60 # Establish possible resume length
61 if os.path.isfile(encodeFilename(ctx.tmpfilename)):
62 ctx.resume_len = os.path.getsize(
63 encodeFilename(ctx.tmpfilename))
65 ctx.is_resume = ctx.resume_len > 0
68 retries = self.params.get('retries', 0)
70 class SucceedDownload(Exception):
73 class RetryDownload(Exception):
74 def __init__(self, source_error):
75 self.source_error = source_error
77 class NextFragment(Exception):
80 def set_range(req, start, end):
81 range_header = 'bytes=%d-' % start
83 range_header += compat_str(end)
84 req.add_header('Range', range_header)
86 def establish_connection():
87 ctx.chunk_size = (random.randint(int(chunk_size * 0.95), chunk_size)
88 if not is_test and chunk_size else chunk_size)
89 if ctx.resume_len > 0:
90 range_start = ctx.resume_len
92 self.report_resuming_byte(ctx.resume_len)
94 elif ctx.chunk_size > 0:
99 range_end = range_start + ctx.chunk_size - 1 if ctx.chunk_size else None
100 if range_end and ctx.data_len is not None and range_end >= ctx.data_len:
101 range_end = ctx.data_len - 1
102 has_range = range_start is not None
103 ctx.has_range = has_range
104 request = sanitized_Request(url, None, headers)
106 set_range(request, range_start, range_end)
107 # Establish connection
110 ctx.data = self.ydl.urlopen(request)
111 except (compat_urllib_error.URLError, ) as err:
112 if isinstance(err.reason, socket.timeout):
113 raise RetryDownload(err)
115 # When trying to resume, Content-Range HTTP header of response has to be checked
116 # to match the value of requested Range HTTP header. This is due to a webservers
117 # that don't support resuming and serve a whole file with no Content-Range
118 # set in response despite of requested Range (see
119 # https://github.com/ytdl-org/youtube-dl/issues/6057#issuecomment-126129799)
121 content_range = ctx.data.headers.get('Content-Range')
123 content_range_m = re.search(r'bytes (\d+)-(\d+)?(?:/(\d+))?', content_range)
124 # Content-Range is present and matches requested Range, resume is possible
126 if range_start == int(content_range_m.group(1)):
127 content_range_end = int_or_none(content_range_m.group(2))
128 content_len = int_or_none(content_range_m.group(3))
129 accept_content_len = (
130 # Non-chunked download
132 # Chunked download and requested piece or
133 # its part is promised to be served
134 or content_range_end == range_end
135 or content_len < range_end)
136 if accept_content_len:
137 ctx.data_len = content_len
139 # Content-Range is either not present or invalid. Assuming remote webserver is
140 # trying to send the whole file, resume is not possible, so wiping the local file
141 # and performing entire redownload
142 self.report_unable_to_resume()
145 ctx.data_len = int_or_none(ctx.data.info().get('Content-length', None))
147 except (compat_urllib_error.HTTPError, ) as err:
149 # Unable to resume (requested range not satisfiable)
151 # Open the connection again without the range header
152 ctx.data = self.ydl.urlopen(
153 sanitized_Request(url, None, headers))
154 content_length = ctx.data.info()['Content-Length']
155 except (compat_urllib_error.HTTPError, ) as err:
156 if err.code < 500 or err.code >= 600:
159 # Examine the reported length
160 if (content_length is not None
161 and (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)):
162 # The file had already been fully downloaded.
163 # Explanation to the above condition: in issue #175 it was revealed that
164 # YouTube sometimes adds or removes a few bytes from the end of the file,
165 # changing the file size slightly and causing problems for some users. So
166 # I decided to implement a suggested change and consider the file
167 # completely downloaded if the file size differs less than 100 bytes from
168 # the one in the hard drive.
169 self.report_file_already_downloaded(ctx.filename)
170 self.try_rename(ctx.tmpfilename, ctx.filename)
171 self._hook_progress({
172 'filename': ctx.filename,
173 'status': 'finished',
174 'downloaded_bytes': ctx.resume_len,
175 'total_bytes': ctx.resume_len,
177 raise SucceedDownload()
179 # The length does not match, we start the download over
180 self.report_unable_to_resume()
184 elif err.code < 500 or err.code >= 600:
185 # Unexpected HTTP error
187 raise RetryDownload(err)
188 except socket.error as err:
189 if err.errno != errno.ECONNRESET:
190 # Connection reset is no problem, just retry
192 raise RetryDownload(err)
195 data_len = ctx.data.info().get('Content-length', None)
197 # Range HTTP header may be ignored/unsupported by a webserver
198 # (e.g. extractor/scivee.py, extractor/bambuser.py).
199 # However, for a test we still would like to download just a piece of a file.
200 # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control
201 # block size when downloading a file.
202 if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):
203 data_len = self._TEST_FILE_SIZE
205 if data_len is not None:
206 data_len = int(data_len) + ctx.resume_len
207 min_data_len = self.params.get('min_filesize')
208 max_data_len = self.params.get('max_filesize')
209 if min_data_len is not None and data_len < min_data_len:
210 self.to_screen('\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
212 if max_data_len is not None and data_len > max_data_len:
213 self.to_screen('\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
216 byte_counter = 0 + ctx.resume_len
217 block_size = ctx.block_size
220 # measure time over whole while-loop, so slow_down() and best_block_size() work together properly
221 now = None # needed for slow_down() in the first loop run
222 before = start # start measuring
225 to_stdout = ctx.tmpfilename == '-'
229 ctx.resume_len = byte_counter if to_stdout else os.path.getsize(encodeFilename(ctx.tmpfilename))
230 raise RetryDownload(e)
235 data_block = ctx.data.read(block_size if data_len is None else min(block_size, data_len - byte_counter))
236 # socket.timeout is a subclass of socket.error but may not have
238 except socket.timeout as e:
240 except socket.error as e:
241 # SSLError on python 2 (inherits socket.error) may have
242 # no errno set but this error message
243 if e.errno in (errno.ECONNRESET, errno.ETIMEDOUT) or getattr(e, 'message') == 'The read operation timed out':
247 byte_counter += len(data_block)
249 # exit loop when download is finished
250 if len(data_block) == 0:
253 # Open destination file just in time
254 if ctx.stream is None:
256 ctx.stream, ctx.tmpfilename = sanitize_open(
257 ctx.tmpfilename, ctx.open_mode)
258 assert ctx.stream is not None
259 ctx.filename = self.undo_temp_name(ctx.tmpfilename)
260 self.report_destination(ctx.filename)
261 except (OSError, IOError) as err:
262 self.report_error('unable to open for writing: %s' % str(err))
265 if self.params.get('xattr_set_filesize', False) and data_len is not None:
267 write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode('utf-8'))
268 except (XAttrUnavailableError, XAttrMetadataError) as err:
269 self.report_error('unable to set filesize xattr: %s' % str(err))
272 ctx.stream.write(data_block)
273 except (IOError, OSError) as err:
275 self.report_error('unable to write data: %s' % str(err))
279 self.slow_down(start, now, byte_counter - ctx.resume_len)
281 # end measuring of one loop run
286 if not self.params.get('noresizebuffer', False):
287 block_size = self.best_block_size(after - before, len(data_block))
292 speed = self.calc_speed(start, now, byte_counter - ctx.resume_len)
293 if ctx.data_len is None:
296 eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len)
298 self._hook_progress({
299 'status': 'downloading',
300 'downloaded_bytes': byte_counter,
301 'total_bytes': ctx.data_len,
302 'tmpfilename': ctx.tmpfilename,
303 'filename': ctx.filename,
306 'elapsed': now - ctx.start_time,
309 if data_len is not None and byte_counter == data_len:
312 if not is_test and ctx.chunk_size and ctx.data_len is not None and byte_counter < ctx.data_len:
313 ctx.resume_len = byte_counter
314 # ctx.block_size = block_size
317 if ctx.stream is None:
319 self.report_error('Did not get any data blocks')
321 if ctx.tmpfilename != '-':
324 if data_len is not None and byte_counter != data_len:
325 err = ContentTooShortError(byte_counter, int(data_len))
330 self.try_rename(ctx.tmpfilename, ctx.filename)
332 # Update file modification time
333 if self.params.get('updatetime', True):
334 info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None))
336 self._hook_progress({
337 'downloaded_bytes': byte_counter,
338 'total_bytes': byte_counter,
339 'filename': ctx.filename,
340 'status': 'finished',
341 'elapsed': time.time() - ctx.start_time,
346 while count <= retries:
348 establish_connection()
350 except RetryDownload as e:
353 self.report_retry(e.source_error, count, retries)
357 except SucceedDownload:
360 self.report_error('giving up after %s retries' % retries)