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