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