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