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