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