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