]> jfr.im git - yt-dlp.git/blob - yt_dlp/downloader/http.py
[cleanup] Misc fixes (see desc)
[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 # Content-Range is present and matches requested Range, resume is possible
140 if range_start == content_range_start and (
141 # Non-chunked download
142 not ctx.chunk_size
143 # Chunked download and requested piece or
144 # its part is promised to be served
145 or content_range_end == range_end
146 or content_len < range_end):
147 ctx.content_len = content_len
148 if content_len or req_end:
149 ctx.data_len = min(content_len or req_end, req_end or content_len) - (req_start or 0)
150 return
151 # Content-Range is either not present or invalid. Assuming remote webserver is
152 # trying to send the whole file, resume is not possible, so wiping the local file
153 # and performing entire redownload
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 compat_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 compat_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 compat_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 download():
209 data_len = ctx.data.info().get('Content-length', None)
210
211 # Range HTTP header may be ignored/unsupported by a webserver
212 # (e.g. extractor/scivee.py, extractor/bambuser.py).
213 # However, for a test we still would like to download just a piece of a file.
214 # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control
215 # block size when downloading a file.
216 if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):
217 data_len = self._TEST_FILE_SIZE
218
219 if data_len is not None:
220 data_len = int(data_len) + ctx.resume_len
221 min_data_len = self.params.get('min_filesize')
222 max_data_len = self.params.get('max_filesize')
223 if min_data_len is not None and data_len < min_data_len:
224 self.to_screen(
225 f'\r[download] File is smaller than min-filesize ({data_len} bytes < {min_data_len} bytes). Aborting.')
226 return False
227 if max_data_len is not None and data_len > max_data_len:
228 self.to_screen(
229 f'\r[download] File is larger than max-filesize ({data_len} bytes > {max_data_len} bytes). Aborting.')
230 return False
231
232 byte_counter = 0 + ctx.resume_len
233 block_size = ctx.block_size
234 start = time.time()
235
236 # measure time over whole while-loop, so slow_down() and best_block_size() work together properly
237 now = None # needed for slow_down() in the first loop run
238 before = start # start measuring
239
240 def retry(e):
241 to_stdout = ctx.tmpfilename == '-'
242 if ctx.stream is not None:
243 if not to_stdout:
244 ctx.stream.close()
245 ctx.stream = None
246 ctx.resume_len = byte_counter if to_stdout else os.path.getsize(encodeFilename(ctx.tmpfilename))
247 raise RetryDownload(e)
248
249 while True:
250 try:
251 # Download and write
252 data_block = ctx.data.read(block_size if not is_test else min(block_size, data_len - byte_counter))
253 except RESPONSE_READ_EXCEPTIONS as err:
254 retry(err)
255
256 byte_counter += len(data_block)
257
258 # exit loop when download is finished
259 if len(data_block) == 0:
260 break
261
262 # Open destination file just in time
263 if ctx.stream is None:
264 try:
265 ctx.stream, ctx.tmpfilename = self.sanitize_open(
266 ctx.tmpfilename, ctx.open_mode)
267 assert ctx.stream is not None
268 ctx.filename = self.undo_temp_name(ctx.tmpfilename)
269 self.report_destination(ctx.filename)
270 except OSError as err:
271 self.report_error('unable to open for writing: %s' % str(err))
272 return False
273
274 if self.params.get('xattr_set_filesize', False) and data_len is not None:
275 try:
276 write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode())
277 except (XAttrUnavailableError, XAttrMetadataError) as err:
278 self.report_error('unable to set filesize xattr: %s' % str(err))
279
280 try:
281 ctx.stream.write(data_block)
282 except OSError as err:
283 self.to_stderr('\n')
284 self.report_error('unable to write data: %s' % str(err))
285 return False
286
287 # Apply rate limit
288 self.slow_down(start, now, byte_counter - ctx.resume_len)
289
290 # end measuring of one loop run
291 now = time.time()
292 after = now
293
294 # Adjust block size
295 if not self.params.get('noresizebuffer', False):
296 block_size = self.best_block_size(after - before, len(data_block))
297
298 before = after
299
300 # Progress message
301 speed = self.calc_speed(start, now, byte_counter - ctx.resume_len)
302 if ctx.data_len is None:
303 eta = None
304 else:
305 eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len)
306
307 self._hook_progress({
308 'status': 'downloading',
309 'downloaded_bytes': byte_counter,
310 'total_bytes': ctx.data_len,
311 'tmpfilename': ctx.tmpfilename,
312 'filename': ctx.filename,
313 'eta': eta,
314 'speed': speed,
315 'elapsed': now - ctx.start_time,
316 'ctx_id': info_dict.get('ctx_id'),
317 }, info_dict)
318
319 if data_len is not None and byte_counter == data_len:
320 break
321
322 if speed and speed < (self.params.get('throttledratelimit') or 0):
323 # The speed must stay below the limit for 3 seconds
324 # This prevents raising error when the speed temporarily goes down
325 if ctx.throttle_start is None:
326 ctx.throttle_start = now
327 elif now - ctx.throttle_start > 3:
328 if ctx.stream is not None and ctx.tmpfilename != '-':
329 ctx.stream.close()
330 raise ThrottledDownload()
331 elif speed:
332 ctx.throttle_start = None
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 # ctx.block_size = block_size
337 raise NextFragment()
338
339 if ctx.stream is None:
340 self.to_stderr('\n')
341 self.report_error('Did not get any data blocks')
342 return False
343 if ctx.tmpfilename != '-':
344 ctx.stream.close()
345
346 if data_len is not None and byte_counter != data_len:
347 err = ContentTooShortError(byte_counter, int(data_len))
348 if count <= retries:
349 retry(err)
350 raise err
351
352 self.try_rename(ctx.tmpfilename, ctx.filename)
353
354 # Update file modification time
355 if self.params.get('updatetime', True):
356 info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None))
357
358 self._hook_progress({
359 'downloaded_bytes': byte_counter,
360 'total_bytes': byte_counter,
361 'filename': ctx.filename,
362 'status': 'finished',
363 'elapsed': time.time() - ctx.start_time,
364 'ctx_id': info_dict.get('ctx_id'),
365 }, info_dict)
366
367 return True
368
369 while count <= retries:
370 try:
371 establish_connection()
372 return download()
373 except RetryDownload as e:
374 count += 1
375 if count <= retries:
376 self.report_retry(e.source_error, count, retries)
377 else:
378 self.to_screen(f'[download] Got server HTTP error: {e.source_error}')
379 continue
380 except NextFragment:
381 continue
382 except SucceedDownload:
383 return True
384
385 self.report_error('giving up after %s retries' % retries)
386 return False