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