9 from .common
import FileDownloader
14 XAttrUnavailableError
,
23 RESPONSE_READ_EXCEPTIONS
= (
25 socket
.timeout
, # compat: py < 3.10
28 http
.client
.HTTPException
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)
37 class DownloadContext(dict):
38 __getattr__
= dict.get
39 __setattr__
= dict.__setitem
__
40 __delattr__
= dict.__delitem
__
42 ctx
= DownloadContext()
43 ctx
.filename
= filename
44 ctx
.tmpfilename
= self
.temp_name(filename
)
47 # Do not include the Accept-Encoding header
48 headers
= {'Youtubedl-no-compression': 'True'}
49 add_headers
= info_dict
.get('http_headers')
51 headers
.update(add_headers
)
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')
61 ctx
.block_size
= self
.params
.get('buffersize', 1024)
62 ctx
.start_time
= time
.time()
65 req_start
, req_end
, _
= parse_http_range(headers
.get('Range'))
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
))
73 ctx
.is_resume
= ctx
.resume_len
> 0
76 retries
= self
.params
.get('retries', 0)
78 class SucceedDownload(Exception):
81 class RetryDownload(Exception):
82 def __init__(self
, source_error
):
83 self
.source_error
= source_error
85 class NextFragment(Exception):
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
97 self
.report_resuming_byte(ctx
.resume_len
)
99 elif req_start
is not None:
100 range_start
= req_start
101 elif ctx
.chunk_size
> 0:
105 ctx
.is_resume
= False
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
117 if try_call(lambda: range_start
> range_end
):
120 raise RetryDownload(Exception(f
'Conflicting range. (start={range_start} > end={range_end})'))
122 if try_call(lambda: range_end
>= ctx
.content_len
):
123 range_end
= ctx
.content_len
- 1
125 request
= sanitized_Request(url
, request_data
, headers
)
126 has_range
= range_start
is not None
128 request
.add_header('Range', f
'bytes={int(range_start)}-{int_or_none(range_end) or ""}')
129 # Establish connection
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)
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
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)
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()
158 ctx
.data_len
= ctx
.content_len
= int_or_none(ctx
.data
.info().get('Content-length', None))
159 except urllib
.error
.HTTPError
as err
:
161 # Unable to resume (requested range not satisfiable)
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:
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
,
189 raise SucceedDownload()
191 # The length does not match, we start the download over
192 self
.report_unable_to_resume()
196 elif err
.code
< 500 or err
.code
>= 600:
197 # Unexpected HTTP error
199 raise RetryDownload(err
)
200 except urllib
.error
.URLError
as err
:
201 if isinstance(err
.reason
, ssl
.CertificateError
):
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
)
210 if ctx
.stream
is not None:
211 if not ctx
.tmpfilename
== '-':
216 data_len
= ctx
.data
.info().get('Content-length', None)
218 # Range HTTP header may be ignored/unsupported by a webserver
219 # (e.g. extractor/scivee.py, extractor/bambuser.py).
220 # However, for a test we still would like to download just a piece of a file.
221 # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control
222 # block size when downloading a file.
223 if is_test
and (data_len
is None or int(data_len
) > self
._TEST
_FILE
_SIZE
):
224 data_len
= self
._TEST
_FILE
_SIZE
226 if data_len
is not None:
227 data_len
= int(data_len
) + ctx
.resume_len
228 min_data_len
= self
.params
.get('min_filesize')
229 max_data_len
= self
.params
.get('max_filesize')
230 if min_data_len
is not None and data_len
< min_data_len
:
232 f
'\r[download] File is smaller than min-filesize ({data_len} bytes < {min_data_len} bytes). Aborting.')
234 if max_data_len
is not None and data_len
> max_data_len
:
236 f
'\r[download] File is larger than max-filesize ({data_len} bytes > {max_data_len} bytes). Aborting.')
239 byte_counter
= 0 + ctx
.resume_len
240 block_size
= ctx
.block_size
243 # measure time over whole while-loop, so slow_down() and best_block_size() work together properly
244 now
= None # needed for slow_down() in the first loop run
245 before
= start
# start measuring
249 ctx
.resume_len
= (byte_counter
if ctx
.tmpfilename
== '-'
250 else os
.path
.getsize(encodeFilename(ctx
.tmpfilename
)))
251 raise RetryDownload(e
)
256 data_block
= ctx
.data
.read(block_size
if not is_test
else min(block_size
, data_len
- byte_counter
))
257 except RESPONSE_READ_EXCEPTIONS
as err
:
260 byte_counter
+= len(data_block
)
262 # exit loop when download is finished
263 if len(data_block
) == 0:
266 # Open destination file just in time
267 if ctx
.stream
is None:
269 ctx
.stream
, ctx
.tmpfilename
= self
.sanitize_open(
270 ctx
.tmpfilename
, ctx
.open_mode
)
271 assert ctx
.stream
is not None
272 ctx
.filename
= self
.undo_temp_name(ctx
.tmpfilename
)
273 self
.report_destination(ctx
.filename
)
274 except OSError as err
:
275 self
.report_error('unable to open for writing: %s' % str(err
))
278 if self
.params
.get('xattr_set_filesize', False) and data_len
is not None:
280 write_xattr(ctx
.tmpfilename
, 'user.ytdl.filesize', str(data_len
).encode())
281 except (XAttrUnavailableError
, XAttrMetadataError
) as err
:
282 self
.report_error('unable to set filesize xattr: %s' % str(err
))
285 ctx
.stream
.write(data_block
)
286 except OSError as err
:
288 self
.report_error('unable to write data: %s' % str(err
))
292 self
.slow_down(start
, now
, byte_counter
- ctx
.resume_len
)
294 # end measuring of one loop run
299 if not self
.params
.get('noresizebuffer', False):
300 block_size
= self
.best_block_size(after
- before
, len(data_block
))
305 speed
= self
.calc_speed(start
, now
, byte_counter
- ctx
.resume_len
)
306 if ctx
.data_len
is None:
309 eta
= self
.calc_eta(start
, time
.time(), ctx
.data_len
- ctx
.resume_len
, byte_counter
- ctx
.resume_len
)
311 self
._hook
_progress
({
312 'status': 'downloading',
313 'downloaded_bytes': byte_counter
,
314 'total_bytes': ctx
.data_len
,
315 'tmpfilename': ctx
.tmpfilename
,
316 'filename': ctx
.filename
,
319 'elapsed': now
- ctx
.start_time
,
320 'ctx_id': info_dict
.get('ctx_id'),
323 if data_len
is not None and byte_counter
== data_len
:
326 if speed
and speed
< (self
.params
.get('throttledratelimit') or 0):
327 # The speed must stay below the limit for 3 seconds
328 # This prevents raising error when the speed temporarily goes down
329 if ctx
.throttle_start
is None:
330 ctx
.throttle_start
= now
331 elif now
- ctx
.throttle_start
> 3:
332 if ctx
.stream
is not None and ctx
.tmpfilename
!= '-':
334 raise ThrottledDownload()
336 ctx
.throttle_start
= None
338 if not is_test
and ctx
.chunk_size
and ctx
.content_len
is not None and byte_counter
< ctx
.content_len
:
339 ctx
.resume_len
= byte_counter
340 # ctx.block_size = block_size
343 if ctx
.stream
is None:
345 self
.report_error('Did not get any data blocks')
347 if ctx
.tmpfilename
!= '-':
350 if data_len
is not None and byte_counter
!= data_len
:
351 err
= ContentTooShortError(byte_counter
, int(data_len
))
356 self
.try_rename(ctx
.tmpfilename
, ctx
.filename
)
358 # Update file modification time
359 if self
.params
.get('updatetime', True):
360 info_dict
['filetime'] = self
.try_utime(ctx
.filename
, ctx
.data
.info().get('last-modified', None))
362 self
._hook
_progress
({
363 'downloaded_bytes': byte_counter
,
364 'total_bytes': byte_counter
,
365 'filename': ctx
.filename
,
366 'status': 'finished',
367 'elapsed': time
.time() - ctx
.start_time
,
368 'ctx_id': info_dict
.get('ctx_id'),
373 while count
<= retries
:
375 establish_connection()
377 except RetryDownload
as e
:
380 self
.report_retry(e
.source_error
, count
, retries
)
382 self
.to_screen(f
'[download] Got server HTTP error: {e.source_error}')
386 except SucceedDownload
:
392 self
.report_error('giving up after %s retries' % retries
)