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