]>
Commit | Line | Data |
---|---|---|
3bc2ddcc | 1 | import os |
f8271158 | 2 | import random |
3bc2ddcc JMF |
3 | import time |
4 | ||
5 | from .common import FileDownloader | |
3d2623a8 | 6 | from ..networking import Request |
7 | from ..networking.exceptions import ( | |
8 | CertificateVerifyError, | |
9 | HTTPError, | |
10 | TransportError, | |
11 | ) | |
1cc79574 | 12 | from ..utils import ( |
3bc2ddcc | 13 | ContentTooShortError, |
be5c1ae8 | 14 | RetryManager, |
f8271158 | 15 | ThrottledDownload, |
16 | XAttrMetadataError, | |
17 | XAttrUnavailableError, | |
3bc2ddcc | 18 | encodeFilename, |
ba515388 | 19 | int_or_none, |
93c8410d | 20 | parse_http_range, |
c4f60dd7 | 21 | try_call, |
d7753d19 | 22 | write_xattr, |
3bc2ddcc | 23 | ) |
3d2623a8 | 24 | from ..utils.networking import HTTPHeaderDict |
3bc2ddcc JMF |
25 | |
26 | ||
27 | class HttpFD(FileDownloader): | |
d3f0687c | 28 | def real_download(self, filename, info_dict): |
3bc2ddcc | 29 | url = info_dict['url'] |
273762c8 | 30 | request_data = info_dict.get('request_data', None) |
a3c3a1e1 S |
31 | |
32 | class DownloadContext(dict): | |
33 | __getattr__ = dict.get | |
34 | __setattr__ = dict.__setitem__ | |
35 | __delattr__ = dict.__delitem__ | |
36 | ||
37 | ctx = DownloadContext() | |
38 | ctx.filename = filename | |
39 | ctx.tmpfilename = self.temp_name(filename) | |
40 | ctx.stream = None | |
3bc2ddcc | 41 | |
955c8958 | 42 | # Disable compression |
3d2623a8 | 43 | headers = HTTPHeaderDict({'Accept-Encoding': 'identity'}, info_dict.get('http_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 | 66 | |
a3c3a1e1 S |
67 | class SucceedDownload(Exception): |
68 | pass | |
69 | ||
70 | class RetryDownload(Exception): | |
71 | def __init__(self, source_error): | |
72 | self.source_error = source_error | |
73 | ||
ba515388 S |
74 | class NextFragment(Exception): |
75 | pass | |
76 | ||
a3c3a1e1 | 77 | def establish_connection(): |
b91a7a4e S |
78 | ctx.chunk_size = (random.randint(int(chunk_size * 0.95), chunk_size) |
79 | if not is_test and chunk_size else chunk_size) | |
ba515388 S |
80 | if ctx.resume_len > 0: |
81 | range_start = ctx.resume_len | |
93c8410d LNO |
82 | if req_start is not None: |
83 | # offset the beginning of Range to be within request | |
84 | range_start += req_start | |
ba515388 S |
85 | if ctx.is_resume: |
86 | self.report_resuming_byte(ctx.resume_len) | |
a3c3a1e1 | 87 | ctx.open_mode = 'ab' |
be4685ab LNO |
88 | elif req_start is not None: |
89 | range_start = req_start | |
b91a7a4e | 90 | elif ctx.chunk_size > 0: |
ba515388 S |
91 | range_start = 0 |
92 | else: | |
93 | range_start = None | |
94 | ctx.is_resume = False | |
93c8410d LNO |
95 | |
96 | if ctx.chunk_size: | |
97 | chunk_aware_end = range_start + ctx.chunk_size - 1 | |
98 | # we're not allowed to download outside Range | |
99 | range_end = chunk_aware_end if req_end is None else min(chunk_aware_end, req_end) | |
100 | elif req_end is not None: | |
101 | # there's no need for chunked downloads, so download until the end of Range | |
102 | range_end = req_end | |
103 | else: | |
104 | range_end = None | |
105 | ||
c4f60dd7 | 106 | if try_call(lambda: range_start > range_end): |
be4685ab LNO |
107 | ctx.resume_len = 0 |
108 | ctx.open_mode = 'wb' | |
109 | raise RetryDownload(Exception(f'Conflicting range. (start={range_start} > end={range_end})')) | |
110 | ||
c4f60dd7 | 111 | if try_call(lambda: range_end >= ctx.content_len): |
be4685ab LNO |
112 | range_end = ctx.content_len - 1 |
113 | ||
3d2623a8 | 114 | request = Request(url, request_data, headers) |
be4685ab | 115 | has_range = range_start is not None |
ba515388 | 116 | if has_range: |
3d2623a8 | 117 | request.headers['Range'] = f'bytes={int(range_start)}-{int_or_none(range_end) or ""}' |
3bc2ddcc JMF |
118 | # Establish connection |
119 | try: | |
a2e77303 | 120 | ctx.data = self.ydl.urlopen(request) |
84bc4dcb S |
121 | # When trying to resume, Content-Range HTTP header of response has to be checked |
122 | # to match the value of requested Range HTTP header. This is due to a webservers | |
123 | # that don't support resuming and serve a whole file with no Content-Range | |
124 | # set in response despite of requested Range (see | |
067aa17e | 125 | # https://github.com/ytdl-org/youtube-dl/issues/6057#issuecomment-126129799) |
ba515388 | 126 | if has_range: |
a3c3a1e1 | 127 | content_range = ctx.data.headers.get('Content-Range') |
93c8410d | 128 | content_range_start, content_range_end, content_len = parse_http_range(content_range) |
c487cf00 | 129 | # Content-Range is present and matches requested Range, resume is possible |
130 | if range_start == content_range_start and ( | |
93c8410d LNO |
131 | # Non-chunked download |
132 | not ctx.chunk_size | |
133 | # Chunked download and requested piece or | |
134 | # its part is promised to be served | |
135 | or content_range_end == range_end | |
c487cf00 | 136 | or content_len < range_end): |
137 | ctx.content_len = content_len | |
138 | if content_len or req_end: | |
139 | ctx.data_len = min(content_len or req_end, req_end or content_len) - (req_start or 0) | |
140 | return | |
84bc4dcb S |
141 | # Content-Range is either not present or invalid. Assuming remote webserver is |
142 | # trying to send the whole file, resume is not possible, so wiping the local file | |
143 | # and performing entire redownload | |
4823ec9f | 144 | elif range_start > 0: |
145 | self.report_unable_to_resume() | |
a3c3a1e1 S |
146 | ctx.resume_len = 0 |
147 | ctx.open_mode = 'wb' | |
3d2623a8 | 148 | ctx.data_len = ctx.content_len = int_or_none(ctx.data.headers.get('Content-length', None)) |
149 | except HTTPError as err: | |
150 | if err.status == 416: | |
3bc2ddcc JMF |
151 | # Unable to resume (requested range not satisfiable) |
152 | try: | |
153 | # Open the connection again without the range header | |
cf7259bc | 154 | ctx.data = self.ydl.urlopen( |
3d2623a8 | 155 | Request(url, request_data, headers)) |
156 | content_length = ctx.data.headers['Content-Length'] | |
157 | except HTTPError as err: | |
158 | if err.status < 500 or err.status >= 600: | |
3bc2ddcc JMF |
159 | raise |
160 | else: | |
161 | # Examine the reported length | |
3089bc74 S |
162 | if (content_length is not None |
163 | and (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)): | |
3bc2ddcc JMF |
164 | # The file had already been fully downloaded. |
165 | # Explanation to the above condition: in issue #175 it was revealed that | |
166 | # YouTube sometimes adds or removes a few bytes from the end of the file, | |
167 | # changing the file size slightly and causing problems for some users. So | |
168 | # I decided to implement a suggested change and consider the file | |
169 | # completely downloaded if the file size differs less than 100 bytes from | |
170 | # the one in the hard drive. | |
a3c3a1e1 S |
171 | self.report_file_already_downloaded(ctx.filename) |
172 | self.try_rename(ctx.tmpfilename, ctx.filename) | |
3bc2ddcc | 173 | self._hook_progress({ |
a3c3a1e1 | 174 | 'filename': ctx.filename, |
3bc2ddcc | 175 | 'status': 'finished', |
a3c3a1e1 S |
176 | 'downloaded_bytes': ctx.resume_len, |
177 | 'total_bytes': ctx.resume_len, | |
3ba7740d | 178 | }, info_dict) |
a3c3a1e1 | 179 | raise SucceedDownload() |
3bc2ddcc JMF |
180 | else: |
181 | # The length does not match, we start the download over | |
182 | self.report_unable_to_resume() | |
a3c3a1e1 S |
183 | ctx.resume_len = 0 |
184 | ctx.open_mode = 'wb' | |
185 | return | |
3d2623a8 | 186 | elif err.status < 500 or err.status >= 600: |
ba515388 S |
187 | # Unexpected HTTP error |
188 | raise | |
a3c3a1e1 | 189 | raise RetryDownload(err) |
227bf1a3 | 190 | except CertificateVerifyError: |
191 | raise | |
192 | except TransportError as err: | |
9fab498f | 193 | raise RetryDownload(err) |
a3c3a1e1 | 194 | |
6d645b55 | 195 | def close_stream(): |
196 | if ctx.stream is not None: | |
197 | if not ctx.tmpfilename == '-': | |
198 | ctx.stream.close() | |
199 | ctx.stream = None | |
200 | ||
a3c3a1e1 | 201 | def download(): |
3d2623a8 | 202 | data_len = ctx.data.headers.get('Content-length') |
65e5c021 | 203 | |
3d2623a8 | 204 | if ctx.data.headers.get('Content-encoding'): |
65e5c021 FY |
205 | # Content-encoding is present, Content-length is not reliable anymore as we are |
206 | # doing auto decompression. (See: https://github.com/yt-dlp/yt-dlp/pull/6176) | |
207 | data_len = None | |
a3c3a1e1 S |
208 | |
209 | # Range HTTP header may be ignored/unsupported by a webserver | |
210 | # (e.g. extractor/scivee.py, extractor/bambuser.py). | |
211 | # However, for a test we still would like to download just a piece of a file. | |
212 | # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control | |
213 | # block size when downloading a file. | |
214 | if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE): | |
215 | data_len = self._TEST_FILE_SIZE | |
216 | ||
217 | if data_len is not None: | |
218 | data_len = int(data_len) + ctx.resume_len | |
219 | min_data_len = self.params.get('min_filesize') | |
220 | max_data_len = self.params.get('max_filesize') | |
221 | if min_data_len is not None and data_len < min_data_len: | |
86e5f3ed | 222 | self.to_screen( |
223 | f'\r[download] File is smaller than min-filesize ({data_len} bytes < {min_data_len} bytes). Aborting.') | |
a3c3a1e1 S |
224 | return False |
225 | if max_data_len is not None and data_len > max_data_len: | |
86e5f3ed | 226 | self.to_screen( |
227 | f'\r[download] File is larger than max-filesize ({data_len} bytes > {max_data_len} bytes). Aborting.') | |
a3c3a1e1 | 228 | return False |
12832049 | 229 | |
a3c3a1e1 | 230 | byte_counter = 0 + ctx.resume_len |
ba515388 | 231 | block_size = ctx.block_size |
a3c3a1e1 | 232 | start = time.time() |
c7667c2d | 233 | |
a3c3a1e1 S |
234 | # measure time over whole while-loop, so slow_down() and best_block_size() work together properly |
235 | now = None # needed for slow_down() in the first loop run | |
236 | before = start # start measuring | |
c7667c2d | 237 | |
a3c3a1e1 | 238 | def retry(e): |
6d645b55 | 239 | close_stream() |
240 | ctx.resume_len = (byte_counter if ctx.tmpfilename == '-' | |
241 | 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)) |
227bf1a3 | 248 | except TransportError as err: |
a2e77303 | 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: | |
0f06bcd7 | 271 | write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode()) |
a3c3a1e1 S |
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 | |
a3c3a1e1 | 329 | if ctx.stream is None: |
4d2d638d | 330 | self.to_stderr('\n') |
a3c3a1e1 | 331 | self.report_error('Did not get any data blocks') |
3bc2ddcc | 332 | return False |
662ef1e9 | 333 | |
334 | if not is_test and ctx.chunk_size and ctx.content_len is not None and byte_counter < ctx.content_len: | |
335 | ctx.resume_len = byte_counter | |
336 | raise NextFragment() | |
337 | ||
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)) | |
be5c1ae8 | 343 | retry(err) |
c7667c2d | 344 | |
a3c3a1e1 | 345 | self.try_rename(ctx.tmpfilename, ctx.filename) |
c7667c2d | 346 | |
a3c3a1e1 S |
347 | # Update file modification time |
348 | if self.params.get('updatetime', True): | |
3d2623a8 | 349 | info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.headers.get('last-modified', None)) |
3bc2ddcc JMF |
350 | |
351 | self._hook_progress({ | |
352 | 'downloaded_bytes': byte_counter, | |
a3c3a1e1 S |
353 | 'total_bytes': byte_counter, |
354 | 'filename': ctx.filename, | |
355 | 'status': 'finished', | |
ba515388 | 356 | 'elapsed': time.time() - ctx.start_time, |
bd50a52b | 357 | 'ctx_id': info_dict.get('ctx_id'), |
3ba7740d | 358 | }, info_dict) |
3bc2ddcc | 359 | |
a3c3a1e1 S |
360 | return True |
361 | ||
be5c1ae8 | 362 | for retry in RetryManager(self.params.get('retries'), self.report_retry): |
a3c3a1e1 S |
363 | try: |
364 | establish_connection() | |
bec49996 | 365 | return download() |
be5c1ae8 | 366 | except RetryDownload as err: |
367 | retry.error = err.source_error | |
a3c3a1e1 | 368 | continue |
ba515388 | 369 | except NextFragment: |
be5c1ae8 | 370 | retry.error = None |
371 | retry.attempt -= 1 | |
ba515388 | 372 | continue |
a3c3a1e1 S |
373 | except SucceedDownload: |
374 | return True | |
6d645b55 | 375 | except: # noqa: E722 |
376 | close_stream() | |
377 | raise | |
a3c3a1e1 | 378 | return False |