]> jfr.im git - yt-dlp.git/blob - yt_dlp/downloader/http.py
e785f0d4edadb85af85cada38bb7990d6c2db199
[yt-dlp.git] / yt_dlp / downloader / http.py
1 import http.client
2 import os
3 import random
4 import socket
5 import ssl
6 import time
7 import urllib.error
8
9 from .common import FileDownloader
10 from ..utils import (
11 ContentTooShortError,
12 RetryManager,
13 ThrottledDownload,
14 XAttrMetadataError,
15 XAttrUnavailableError,
16 encodeFilename,
17 int_or_none,
18 parse_http_range,
19 sanitized_Request,
20 try_call,
21 write_xattr,
22 )
23
24 RESPONSE_READ_EXCEPTIONS = (
25 TimeoutError,
26 socket.timeout, # compat: py < 3.10
27 ConnectionError,
28 ssl.SSLError,
29 http.client.HTTPException
30 )
31
32
33 class HttpFD(FileDownloader):
34 def real_download(self, filename, info_dict):
35 url = info_dict['url']
36 request_data = info_dict.get('request_data', None)
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
47
48 # Disable compression
49 headers = {'Accept-Encoding': 'identity'}
50 add_headers = info_dict.get('http_headers')
51 if add_headers:
52 headers.update(add_headers)
53
54 is_test = self.params.get('test', False)
55 chunk_size = self._TEST_FILE_SIZE if is_test else (
56 self.params.get('http_chunk_size')
57 or info_dict.get('downloader_options', {}).get('http_chunk_size')
58 or 0)
59
60 ctx.open_mode = 'wb'
61 ctx.resume_len = 0
62 ctx.block_size = self.params.get('buffersize', 1024)
63 ctx.start_time = time.time()
64
65 # parse given Range
66 req_start, req_end, _ = parse_http_range(headers.get('Range'))
67
68 if self.params.get('continuedl', True):
69 # Establish possible resume length
70 if os.path.isfile(encodeFilename(ctx.tmpfilename)):
71 ctx.resume_len = os.path.getsize(
72 encodeFilename(ctx.tmpfilename))
73
74 ctx.is_resume = ctx.resume_len > 0
75
76 class SucceedDownload(Exception):
77 pass
78
79 class RetryDownload(Exception):
80 def __init__(self, source_error):
81 self.source_error = source_error
82
83 class NextFragment(Exception):
84 pass
85
86 def establish_connection():
87 ctx.chunk_size = (random.randint(int(chunk_size * 0.95), chunk_size)
88 if not is_test and chunk_size else chunk_size)
89 if ctx.resume_len > 0:
90 range_start = ctx.resume_len
91 if req_start is not None:
92 # offset the beginning of Range to be within request
93 range_start += req_start
94 if ctx.is_resume:
95 self.report_resuming_byte(ctx.resume_len)
96 ctx.open_mode = 'ab'
97 elif req_start is not None:
98 range_start = req_start
99 elif ctx.chunk_size > 0:
100 range_start = 0
101 else:
102 range_start = None
103 ctx.is_resume = False
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
115 if try_call(lambda: range_start > range_end):
116 ctx.resume_len = 0
117 ctx.open_mode = 'wb'
118 raise RetryDownload(Exception(f'Conflicting range. (start={range_start} > end={range_end})'))
119
120 if try_call(lambda: range_end >= ctx.content_len):
121 range_end = ctx.content_len - 1
122
123 request = sanitized_Request(url, request_data, headers)
124 has_range = range_start is not None
125 if has_range:
126 request.add_header('Range', f'bytes={int(range_start)}-{int_or_none(range_end) or ""}')
127 # Establish connection
128 try:
129 ctx.data = self.ydl.urlopen(request)
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
134 # https://github.com/ytdl-org/youtube-dl/issues/6057#issuecomment-126129799)
135 if has_range:
136 content_range = ctx.data.headers.get('Content-Range')
137 content_range_start, content_range_end, content_len = parse_http_range(content_range)
138 # Content-Range is present and matches requested Range, resume is possible
139 if range_start == content_range_start and (
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
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
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
153 elif range_start > 0:
154 self.report_unable_to_resume()
155 ctx.resume_len = 0
156 ctx.open_mode = 'wb'
157 ctx.data_len = ctx.content_len = int_or_none(ctx.data.info().get('Content-length', None))
158 except urllib.error.HTTPError as err:
159 if err.code == 416:
160 # Unable to resume (requested range not satisfiable)
161 try:
162 # Open the connection again without the range header
163 ctx.data = self.ydl.urlopen(
164 sanitized_Request(url, request_data, headers))
165 content_length = ctx.data.info()['Content-Length']
166 except urllib.error.HTTPError as err:
167 if err.code < 500 or err.code >= 600:
168 raise
169 else:
170 # Examine the reported length
171 if (content_length is not None
172 and (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)):
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.
180 self.report_file_already_downloaded(ctx.filename)
181 self.try_rename(ctx.tmpfilename, ctx.filename)
182 self._hook_progress({
183 'filename': ctx.filename,
184 'status': 'finished',
185 'downloaded_bytes': ctx.resume_len,
186 'total_bytes': ctx.resume_len,
187 }, info_dict)
188 raise SucceedDownload()
189 else:
190 # The length does not match, we start the download over
191 self.report_unable_to_resume()
192 ctx.resume_len = 0
193 ctx.open_mode = 'wb'
194 return
195 elif err.code < 500 or err.code >= 600:
196 # Unexpected HTTP error
197 raise
198 raise RetryDownload(err)
199 except 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:
206 raise RetryDownload(err)
207
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
214 def download():
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
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:
235 self.to_screen(
236 f'\r[download] File is smaller than min-filesize ({data_len} bytes < {min_data_len} bytes). Aborting.')
237 return False
238 if max_data_len is not None and data_len > max_data_len:
239 self.to_screen(
240 f'\r[download] File is larger than max-filesize ({data_len} bytes > {max_data_len} bytes). Aborting.')
241 return False
242
243 byte_counter = 0 + ctx.resume_len
244 block_size = ctx.block_size
245 start = time.time()
246
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
250
251 def retry(e):
252 close_stream()
253 ctx.resume_len = (byte_counter if ctx.tmpfilename == '-'
254 else os.path.getsize(encodeFilename(ctx.tmpfilename)))
255 raise RetryDownload(e)
256
257 while True:
258 try:
259 # Download and write
260 data_block = ctx.data.read(block_size if not is_test else min(block_size, data_len - byte_counter))
261 except RESPONSE_READ_EXCEPTIONS as err:
262 retry(err)
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:
273 ctx.stream, ctx.tmpfilename = self.sanitize_open(
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)
278 except OSError as err:
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:
284 write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode())
285 except (XAttrUnavailableError, XAttrMetadataError) as err:
286 self.report_error('unable to set filesize xattr: %s' % str(err))
287
288 try:
289 ctx.stream.write(data_block)
290 except OSError as err:
291 self.to_stderr('\n')
292 self.report_error('unable to write data: %s' % str(err))
293 return False
294
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)
310 if ctx.data_len is None:
311 eta = None
312 else:
313 eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len)
314
315 self._hook_progress({
316 'status': 'downloading',
317 'downloaded_bytes': byte_counter,
318 'total_bytes': ctx.data_len,
319 'tmpfilename': ctx.tmpfilename,
320 'filename': ctx.filename,
321 'eta': eta,
322 'speed': speed,
323 'elapsed': now - ctx.start_time,
324 'ctx_id': info_dict.get('ctx_id'),
325 }, info_dict)
326
327 if data_len is not None and byte_counter == data_len:
328 break
329
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
333 if ctx.throttle_start is None:
334 ctx.throttle_start = now
335 elif now - ctx.throttle_start > 3:
336 if ctx.stream is not None and ctx.tmpfilename != '-':
337 ctx.stream.close()
338 raise ThrottledDownload()
339 elif speed:
340 ctx.throttle_start = None
341
342 if not is_test and ctx.chunk_size and ctx.content_len is not None and byte_counter < ctx.content_len:
343 ctx.resume_len = byte_counter
344 # ctx.block_size = block_size
345 raise NextFragment()
346
347 if ctx.stream is None:
348 self.to_stderr('\n')
349 self.report_error('Did not get any data blocks')
350 return False
351 if ctx.tmpfilename != '-':
352 ctx.stream.close()
353
354 if data_len is not None and byte_counter != data_len:
355 err = ContentTooShortError(byte_counter, int(data_len))
356 retry(err)
357
358 self.try_rename(ctx.tmpfilename, ctx.filename)
359
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))
363
364 self._hook_progress({
365 'downloaded_bytes': byte_counter,
366 'total_bytes': byte_counter,
367 'filename': ctx.filename,
368 'status': 'finished',
369 'elapsed': time.time() - ctx.start_time,
370 'ctx_id': info_dict.get('ctx_id'),
371 }, info_dict)
372
373 return True
374
375 for retry in RetryManager(self.params.get('retries'), self.report_retry):
376 try:
377 establish_connection()
378 return download()
379 except RetryDownload as err:
380 retry.error = err.source_error
381 continue
382 except NextFragment:
383 retry.error = None
384 retry.attempt -= 1
385 continue
386 except SucceedDownload:
387 return True
388 except: # noqa: E722
389 close_stream()
390 raise
391 return False