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