]>
Commit | Line | Data |
---|---|---|
4d2d638d PH |
1 | from __future__ import unicode_literals |
2 | ||
16e7711e | 3 | import errno |
3bc2ddcc | 4 | import os |
16e7711e | 5 | import socket |
3bc2ddcc | 6 | import time |
b91a7a4e | 7 | import random |
8d5b8b47 | 8 | import re |
3bc2ddcc JMF |
9 | |
10 | from .common import FileDownloader | |
ba515388 S |
11 | from ..compat import ( |
12 | compat_str, | |
13 | compat_urllib_error, | |
14 | ) | |
1cc79574 | 15 | from ..utils import ( |
3bc2ddcc | 16 | ContentTooShortError, |
3bc2ddcc | 17 | encodeFilename, |
ba515388 | 18 | int_or_none, |
3bc2ddcc | 19 | sanitize_open, |
5c2266df | 20 | sanitized_Request, |
51d9739f | 21 | ThrottledDownload, |
d7753d19 YCH |
22 | write_xattr, |
23 | XAttrMetadataError, | |
24 | XAttrUnavailableError, | |
3bc2ddcc JMF |
25 | ) |
26 | ||
27 | ||
28 | class HttpFD(FileDownloader): | |
d3f0687c | 29 | def real_download(self, filename, info_dict): |
3bc2ddcc | 30 | url = info_dict['url'] |
273762c8 | 31 | request_data = info_dict.get('request_data', None) |
a3c3a1e1 S |
32 | |
33 | class DownloadContext(dict): | |
34 | __getattr__ = dict.get | |
35 | __setattr__ = dict.__setitem__ | |
36 | __delattr__ = dict.__delitem__ | |
37 | ||
38 | ctx = DownloadContext() | |
39 | ctx.filename = filename | |
40 | ctx.tmpfilename = self.temp_name(filename) | |
41 | ctx.stream = None | |
3bc2ddcc JMF |
42 | |
43 | # Do not include the Accept-Encoding header | |
44 | headers = {'Youtubedl-no-compression': 'True'} | |
d769be6c PH |
45 | add_headers = info_dict.get('http_headers') |
46 | if add_headers: | |
47 | headers.update(add_headers) | |
3bc2ddcc | 48 | |
df297c87 | 49 | is_test = self.params.get('test', False) |
ba515388 | 50 | chunk_size = self._TEST_FILE_SIZE if is_test else ( |
3089bc74 S |
51 | info_dict.get('downloader_options', {}).get('http_chunk_size') |
52 | or self.params.get('http_chunk_size') or 0) | |
3bc2ddcc | 53 | |
a3c3a1e1 S |
54 | ctx.open_mode = 'wb' |
55 | ctx.resume_len = 0 | |
ba515388 S |
56 | ctx.data_len = None |
57 | ctx.block_size = self.params.get('buffersize', 1024) | |
58 | ctx.start_time = time.time() | |
b91a7a4e | 59 | ctx.chunk_size = None |
a3c3a1e1 S |
60 | |
61 | if self.params.get('continuedl', True): | |
62 | # Establish possible resume length | |
63 | if os.path.isfile(encodeFilename(ctx.tmpfilename)): | |
ba515388 S |
64 | ctx.resume_len = os.path.getsize( |
65 | encodeFilename(ctx.tmpfilename)) | |
66 | ||
67 | ctx.is_resume = ctx.resume_len > 0 | |
3bc2ddcc JMF |
68 | |
69 | count = 0 | |
70 | retries = self.params.get('retries', 0) | |
a3c3a1e1 S |
71 | |
72 | class SucceedDownload(Exception): | |
73 | pass | |
74 | ||
75 | class RetryDownload(Exception): | |
76 | def __init__(self, source_error): | |
77 | self.source_error = source_error | |
78 | ||
ba515388 S |
79 | class NextFragment(Exception): |
80 | pass | |
81 | ||
82 | def set_range(req, start, end): | |
83 | range_header = 'bytes=%d-' % start | |
84 | if end: | |
85 | range_header += compat_str(end) | |
86 | req.add_header('Range', range_header) | |
87 | ||
a3c3a1e1 | 88 | def establish_connection(): |
b91a7a4e S |
89 | ctx.chunk_size = (random.randint(int(chunk_size * 0.95), chunk_size) |
90 | if not is_test and chunk_size else chunk_size) | |
ba515388 S |
91 | if ctx.resume_len > 0: |
92 | range_start = ctx.resume_len | |
93 | if ctx.is_resume: | |
94 | self.report_resuming_byte(ctx.resume_len) | |
a3c3a1e1 | 95 | ctx.open_mode = 'ab' |
b91a7a4e | 96 | elif ctx.chunk_size > 0: |
ba515388 S |
97 | range_start = 0 |
98 | else: | |
99 | range_start = None | |
100 | ctx.is_resume = False | |
b91a7a4e | 101 | range_end = range_start + ctx.chunk_size - 1 if ctx.chunk_size else None |
ba515388 S |
102 | if range_end and ctx.data_len is not None and range_end >= ctx.data_len: |
103 | range_end = ctx.data_len - 1 | |
104 | has_range = range_start is not None | |
105 | ctx.has_range = has_range | |
273762c8 | 106 | request = sanitized_Request(url, request_data, headers) |
ba515388 S |
107 | if has_range: |
108 | set_range(request, range_start, range_end) | |
3bc2ddcc JMF |
109 | # Establish connection |
110 | try: | |
86b7c00a OA |
111 | try: |
112 | ctx.data = self.ydl.urlopen(request) | |
113 | except (compat_urllib_error.URLError, ) as err: | |
a0566bbf | 114 | # reason may not be available, e.g. for urllib2.HTTPError on python 2.6 |
115 | reason = getattr(err, 'reason', None) | |
116 | if isinstance(reason, socket.timeout): | |
86b7c00a OA |
117 | raise RetryDownload(err) |
118 | raise err | |
84bc4dcb S |
119 | # When trying to resume, Content-Range HTTP header of response has to be checked |
120 | # to match the value of requested Range HTTP header. This is due to a webservers | |
121 | # that don't support resuming and serve a whole file with no Content-Range | |
122 | # set in response despite of requested Range (see | |
067aa17e | 123 | # https://github.com/ytdl-org/youtube-dl/issues/6057#issuecomment-126129799) |
ba515388 | 124 | if has_range: |
a3c3a1e1 | 125 | content_range = ctx.data.headers.get('Content-Range') |
d7d2a9a3 | 126 | if content_range: |
ba515388 | 127 | content_range_m = re.search(r'bytes (\d+)-(\d+)?(?:/(\d+))?', content_range) |
84bc4dcb | 128 | # Content-Range is present and matches requested Range, resume is possible |
ba515388 S |
129 | if content_range_m: |
130 | if range_start == int(content_range_m.group(1)): | |
131 | content_range_end = int_or_none(content_range_m.group(2)) | |
132 | content_len = int_or_none(content_range_m.group(3)) | |
133 | accept_content_len = ( | |
134 | # Non-chunked download | |
3089bc74 | 135 | not ctx.chunk_size |
ba515388 S |
136 | # Chunked download and requested piece or |
137 | # its part is promised to be served | |
3089bc74 S |
138 | or content_range_end == range_end |
139 | or content_len < range_end) | |
ba515388 S |
140 | if accept_content_len: |
141 | ctx.data_len = content_len | |
142 | return | |
84bc4dcb S |
143 | # Content-Range is either not present or invalid. Assuming remote webserver is |
144 | # trying to send the whole file, resume is not possible, so wiping the local file | |
145 | # and performing entire redownload | |
10eaa8ef | 146 | self.report_unable_to_resume() |
a3c3a1e1 S |
147 | ctx.resume_len = 0 |
148 | ctx.open_mode = 'wb' | |
ba515388 | 149 | ctx.data_len = int_or_none(ctx.data.info().get('Content-length', None)) |
a3c3a1e1 | 150 | return |
3bc2ddcc | 151 | except (compat_urllib_error.HTTPError, ) as err: |
ba515388 | 152 | if err.code == 416: |
3bc2ddcc JMF |
153 | # Unable to resume (requested range not satisfiable) |
154 | try: | |
155 | # Open the connection again without the range header | |
cf7259bc | 156 | ctx.data = self.ydl.urlopen( |
273762c8 | 157 | sanitized_Request(url, request_data, headers)) |
a3c3a1e1 | 158 | content_length = ctx.data.info()['Content-Length'] |
3bc2ddcc JMF |
159 | except (compat_urllib_error.HTTPError, ) as err: |
160 | if err.code < 500 or err.code >= 600: | |
161 | raise | |
162 | else: | |
163 | # Examine the reported length | |
3089bc74 S |
164 | if (content_length is not None |
165 | and (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)): | |
3bc2ddcc JMF |
166 | # The file had already been fully downloaded. |
167 | # Explanation to the above condition: in issue #175 it was revealed that | |
168 | # YouTube sometimes adds or removes a few bytes from the end of the file, | |
169 | # changing the file size slightly and causing problems for some users. So | |
170 | # I decided to implement a suggested change and consider the file | |
171 | # completely downloaded if the file size differs less than 100 bytes from | |
172 | # the one in the hard drive. | |
a3c3a1e1 S |
173 | self.report_file_already_downloaded(ctx.filename) |
174 | self.try_rename(ctx.tmpfilename, ctx.filename) | |
3bc2ddcc | 175 | self._hook_progress({ |
a3c3a1e1 | 176 | 'filename': ctx.filename, |
3bc2ddcc | 177 | 'status': 'finished', |
a3c3a1e1 S |
178 | 'downloaded_bytes': ctx.resume_len, |
179 | 'total_bytes': ctx.resume_len, | |
3ba7740d | 180 | }, info_dict) |
a3c3a1e1 | 181 | raise SucceedDownload() |
3bc2ddcc JMF |
182 | else: |
183 | # The length does not match, we start the download over | |
184 | self.report_unable_to_resume() | |
a3c3a1e1 S |
185 | ctx.resume_len = 0 |
186 | ctx.open_mode = 'wb' | |
187 | return | |
ba515388 S |
188 | elif err.code < 500 or err.code >= 600: |
189 | # Unexpected HTTP error | |
190 | raise | |
a3c3a1e1 S |
191 | raise RetryDownload(err) |
192 | except socket.error as err: | |
193 | if err.errno != errno.ECONNRESET: | |
12832049 PH |
194 | # Connection reset is no problem, just retry |
195 | raise | |
a3c3a1e1 S |
196 | raise RetryDownload(err) |
197 | ||
198 | def download(): | |
199 | data_len = ctx.data.info().get('Content-length', None) | |
200 | ||
201 | # Range HTTP header may be ignored/unsupported by a webserver | |
202 | # (e.g. extractor/scivee.py, extractor/bambuser.py). | |
203 | # However, for a test we still would like to download just a piece of a file. | |
204 | # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control | |
205 | # block size when downloading a file. | |
206 | if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE): | |
207 | data_len = self._TEST_FILE_SIZE | |
208 | ||
209 | if data_len is not None: | |
210 | data_len = int(data_len) + ctx.resume_len | |
211 | min_data_len = self.params.get('min_filesize') | |
212 | max_data_len = self.params.get('max_filesize') | |
213 | if min_data_len is not None and data_len < min_data_len: | |
214 | self.to_screen('\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len)) | |
215 | return False | |
216 | if max_data_len is not None and data_len > max_data_len: | |
217 | self.to_screen('\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len)) | |
218 | return False | |
12832049 | 219 | |
a3c3a1e1 | 220 | byte_counter = 0 + ctx.resume_len |
ba515388 | 221 | block_size = ctx.block_size |
a3c3a1e1 | 222 | start = time.time() |
c7667c2d | 223 | |
a3c3a1e1 S |
224 | # measure time over whole while-loop, so slow_down() and best_block_size() work together properly |
225 | now = None # needed for slow_down() in the first loop run | |
226 | before = start # start measuring | |
51d9739f | 227 | throttle_start = None |
c7667c2d | 228 | |
a3c3a1e1 | 229 | def retry(e): |
5d6c81b6 | 230 | to_stdout = ctx.tmpfilename == '-' |
0837992a S |
231 | if ctx.stream is not None: |
232 | if not to_stdout: | |
233 | ctx.stream.close() | |
234 | ctx.stream = None | |
5d6c81b6 | 235 | ctx.resume_len = byte_counter if to_stdout else os.path.getsize(encodeFilename(ctx.tmpfilename)) |
a3c3a1e1 | 236 | raise RetryDownload(e) |
c7667c2d | 237 | |
a3c3a1e1 S |
238 | while True: |
239 | try: | |
240 | # Download and write | |
6c907eb3 | 241 | data_block = ctx.data.read(block_size if data_len is None else min(block_size, data_len - byte_counter)) |
a3c3a1e1 S |
242 | # socket.timeout is a subclass of socket.error but may not have |
243 | # errno set | |
244 | except socket.timeout as e: | |
245 | retry(e) | |
246 | except socket.error as e: | |
cdc55e66 S |
247 | # SSLError on python 2 (inherits socket.error) may have |
248 | # no errno set but this error message | |
c5764b3f | 249 | if e.errno in (errno.ECONNRESET, errno.ETIMEDOUT) or getattr(e, 'message', None) == 'The read operation timed out': |
cdc55e66 S |
250 | retry(e) |
251 | raise | |
a3c3a1e1 S |
252 | |
253 | byte_counter += len(data_block) | |
254 | ||
255 | # exit loop when download is finished | |
256 | if len(data_block) == 0: | |
257 | break | |
258 | ||
259 | # Open destination file just in time | |
260 | if ctx.stream is None: | |
261 | try: | |
262 | ctx.stream, ctx.tmpfilename = sanitize_open( | |
263 | ctx.tmpfilename, ctx.open_mode) | |
264 | assert ctx.stream is not None | |
265 | ctx.filename = self.undo_temp_name(ctx.tmpfilename) | |
266 | self.report_destination(ctx.filename) | |
267 | except (OSError, IOError) as err: | |
268 | self.report_error('unable to open for writing: %s' % str(err)) | |
269 | return False | |
270 | ||
271 | if self.params.get('xattr_set_filesize', False) and data_len is not None: | |
272 | try: | |
273 | write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode('utf-8')) | |
274 | except (XAttrUnavailableError, XAttrMetadataError) as err: | |
275 | self.report_error('unable to set filesize xattr: %s' % str(err)) | |
3bc2ddcc | 276 | |
3bc2ddcc | 277 | try: |
a3c3a1e1 S |
278 | ctx.stream.write(data_block) |
279 | except (IOError, OSError) as err: | |
280 | self.to_stderr('\n') | |
281 | self.report_error('unable to write data: %s' % str(err)) | |
3bc2ddcc | 282 | return False |
881e6a1f | 283 | |
a3c3a1e1 S |
284 | # Apply rate limit |
285 | self.slow_down(start, now, byte_counter - ctx.resume_len) | |
286 | ||
287 | # end measuring of one loop run | |
288 | now = time.time() | |
289 | after = now | |
290 | ||
291 | # Adjust block size | |
292 | if not self.params.get('noresizebuffer', False): | |
293 | block_size = self.best_block_size(after - before, len(data_block)) | |
294 | ||
295 | before = after | |
296 | ||
297 | # Progress message | |
298 | speed = self.calc_speed(start, now, byte_counter - ctx.resume_len) | |
ba515388 | 299 | if ctx.data_len is None: |
a3c3a1e1 S |
300 | eta = None |
301 | else: | |
ba515388 | 302 | eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len) |
a3c3a1e1 S |
303 | |
304 | self._hook_progress({ | |
305 | 'status': 'downloading', | |
306 | 'downloaded_bytes': byte_counter, | |
ba515388 | 307 | 'total_bytes': ctx.data_len, |
a3c3a1e1 S |
308 | 'tmpfilename': ctx.tmpfilename, |
309 | 'filename': ctx.filename, | |
310 | 'eta': eta, | |
311 | 'speed': speed, | |
ba515388 | 312 | 'elapsed': now - ctx.start_time, |
3ba7740d | 313 | }, info_dict) |
a3c3a1e1 | 314 | |
f7b42518 | 315 | if data_len is not None and byte_counter == data_len: |
a3c3a1e1 S |
316 | break |
317 | ||
51d9739f | 318 | if speed and speed < (self.params.get('throttledratelimit') or 0): |
319 | # The speed must stay below the limit for 3 seconds | |
320 | # This prevents raising error when the speed temporarily goes down | |
321 | if throttle_start is None: | |
322 | throttle_start = now | |
323 | elif now - throttle_start > 3: | |
324 | if ctx.stream is not None and ctx.tmpfilename != '-': | |
325 | ctx.stream.close() | |
326 | raise ThrottledDownload() | |
327 | else: | |
328 | throttle_start = None | |
329 | ||
b91a7a4e | 330 | if not is_test and ctx.chunk_size and ctx.data_len is not None and byte_counter < ctx.data_len: |
ba515388 S |
331 | ctx.resume_len = byte_counter |
332 | # ctx.block_size = block_size | |
333 | raise NextFragment() | |
334 | ||
a3c3a1e1 | 335 | if ctx.stream is None: |
4d2d638d | 336 | self.to_stderr('\n') |
a3c3a1e1 | 337 | self.report_error('Did not get any data blocks') |
3bc2ddcc | 338 | return False |
a3c3a1e1 S |
339 | if ctx.tmpfilename != '-': |
340 | ctx.stream.close() | |
c7667c2d | 341 | |
a3c3a1e1 S |
342 | if data_len is not None and byte_counter != data_len: |
343 | err = ContentTooShortError(byte_counter, int(data_len)) | |
344 | if count <= retries: | |
345 | retry(err) | |
346 | raise err | |
c7667c2d | 347 | |
a3c3a1e1 | 348 | self.try_rename(ctx.tmpfilename, ctx.filename) |
c7667c2d | 349 | |
a3c3a1e1 S |
350 | # Update file modification time |
351 | if self.params.get('updatetime', True): | |
352 | info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None)) | |
3bc2ddcc JMF |
353 | |
354 | self._hook_progress({ | |
355 | 'downloaded_bytes': byte_counter, | |
a3c3a1e1 S |
356 | 'total_bytes': byte_counter, |
357 | 'filename': ctx.filename, | |
358 | 'status': 'finished', | |
ba515388 | 359 | 'elapsed': time.time() - ctx.start_time, |
3ba7740d | 360 | }, info_dict) |
3bc2ddcc | 361 | |
a3c3a1e1 S |
362 | return True |
363 | ||
364 | while count <= retries: | |
365 | try: | |
366 | establish_connection() | |
bec49996 | 367 | return download() |
a3c3a1e1 S |
368 | except RetryDownload as e: |
369 | count += 1 | |
370 | if count <= retries: | |
371 | self.report_retry(e.source_error, count, retries) | |
372 | continue | |
ba515388 S |
373 | except NextFragment: |
374 | continue | |
a3c3a1e1 S |
375 | except SucceedDownload: |
376 | return True | |
377 | ||
378 | self.report_error('giving up after %s retries' % retries) | |
379 | return False |