]> jfr.im git - yt-dlp.git/blame - youtube_dl/downloader/http.py
[youtube] Enforce using chunked HTTP downloading for DASH formats
[yt-dlp.git] / youtube_dl / downloader / http.py
CommitLineData
4d2d638d
PH
1from __future__ import unicode_literals
2
16e7711e 3import errno
3bc2ddcc 4import os
16e7711e 5import socket
3bc2ddcc 6import time
8d5b8b47 7import re
3bc2ddcc
JMF
8
9from .common import FileDownloader
ba515388
S
10from ..compat import (
11 compat_str,
12 compat_urllib_error,
13)
1cc79574 14from ..utils import (
3bc2ddcc 15 ContentTooShortError,
3bc2ddcc 16 encodeFilename,
ba515388 17 int_or_none,
3bc2ddcc 18 sanitize_open,
5c2266df 19 sanitized_Request,
d7753d19
YCH
20 write_xattr,
21 XAttrMetadataError,
22 XAttrUnavailableError,
3bc2ddcc
JMF
23)
24
25
26class HttpFD(FileDownloader):
d3f0687c 27 def real_download(self, filename, info_dict):
3bc2ddcc 28 url = info_dict['url']
a3c3a1e1
S
29
30 class DownloadContext(dict):
31 __getattr__ = dict.get
32 __setattr__ = dict.__setitem__
33 __delattr__ = dict.__delitem__
34
35 ctx = DownloadContext()
36 ctx.filename = filename
37 ctx.tmpfilename = self.temp_name(filename)
38 ctx.stream = None
3bc2ddcc
JMF
39
40 # Do not include the Accept-Encoding header
41 headers = {'Youtubedl-no-compression': 'True'}
d769be6c
PH
42 add_headers = info_dict.get('http_headers')
43 if add_headers:
44 headers.update(add_headers)
3bc2ddcc 45
df297c87 46 is_test = self.params.get('test', False)
ba515388 47 chunk_size = self._TEST_FILE_SIZE if is_test else (
00c97e3e 48 info_dict.get('downloader_options', {}).get('http_chunk_size') or
ba515388 49 self.params.get('http_chunk_size') or 0)
3bc2ddcc 50
a3c3a1e1
S
51 ctx.open_mode = 'wb'
52 ctx.resume_len = 0
ba515388
S
53 ctx.data_len = None
54 ctx.block_size = self.params.get('buffersize', 1024)
55 ctx.start_time = time.time()
a3c3a1e1
S
56
57 if self.params.get('continuedl', True):
58 # Establish possible resume length
59 if os.path.isfile(encodeFilename(ctx.tmpfilename)):
ba515388
S
60 ctx.resume_len = os.path.getsize(
61 encodeFilename(ctx.tmpfilename))
62
63 ctx.is_resume = ctx.resume_len > 0
3bc2ddcc
JMF
64
65 count = 0
66 retries = self.params.get('retries', 0)
a3c3a1e1
S
67
68 class SucceedDownload(Exception):
69 pass
70
71 class RetryDownload(Exception):
72 def __init__(self, source_error):
73 self.source_error = source_error
74
ba515388
S
75 class NextFragment(Exception):
76 pass
77
78 def set_range(req, start, end):
79 range_header = 'bytes=%d-' % start
80 if end:
81 range_header += compat_str(end)
82 req.add_header('Range', range_header)
83
a3c3a1e1 84 def establish_connection():
ba515388
S
85 if ctx.resume_len > 0:
86 range_start = ctx.resume_len
87 if ctx.is_resume:
88 self.report_resuming_byte(ctx.resume_len)
a3c3a1e1 89 ctx.open_mode = 'ab'
ba515388
S
90 elif chunk_size > 0:
91 range_start = 0
92 else:
93 range_start = None
94 ctx.is_resume = False
95 range_end = range_start + chunk_size - 1 if chunk_size else None
96 if range_end and ctx.data_len is not None and range_end >= ctx.data_len:
97 range_end = ctx.data_len - 1
98 has_range = range_start is not None
99 ctx.has_range = has_range
cf7259bc 100 request = sanitized_Request(url, None, headers)
ba515388
S
101 if has_range:
102 set_range(request, range_start, range_end)
3bc2ddcc
JMF
103 # Establish connection
104 try:
a3c3a1e1 105 ctx.data = self.ydl.urlopen(request)
84bc4dcb
S
106 # When trying to resume, Content-Range HTTP header of response has to be checked
107 # to match the value of requested Range HTTP header. This is due to a webservers
108 # that don't support resuming and serve a whole file with no Content-Range
109 # set in response despite of requested Range (see
110 # https://github.com/rg3/youtube-dl/issues/6057#issuecomment-126129799)
ba515388 111 if has_range:
a3c3a1e1 112 content_range = ctx.data.headers.get('Content-Range')
d7d2a9a3 113 if content_range:
ba515388 114 content_range_m = re.search(r'bytes (\d+)-(\d+)?(?:/(\d+))?', content_range)
84bc4dcb 115 # Content-Range is present and matches requested Range, resume is possible
ba515388
S
116 if content_range_m:
117 if range_start == int(content_range_m.group(1)):
118 content_range_end = int_or_none(content_range_m.group(2))
119 content_len = int_or_none(content_range_m.group(3))
120 accept_content_len = (
121 # Non-chunked download
122 not chunk_size or
123 # Chunked download and requested piece or
124 # its part is promised to be served
125 content_range_end == range_end or
126 content_len < range_end)
127 if accept_content_len:
128 ctx.data_len = content_len
129 return
84bc4dcb
S
130 # Content-Range is either not present or invalid. Assuming remote webserver is
131 # trying to send the whole file, resume is not possible, so wiping the local file
132 # and performing entire redownload
10eaa8ef 133 self.report_unable_to_resume()
a3c3a1e1
S
134 ctx.resume_len = 0
135 ctx.open_mode = 'wb'
ba515388 136 ctx.data_len = int_or_none(ctx.data.info().get('Content-length', None))
a3c3a1e1 137 return
3bc2ddcc 138 except (compat_urllib_error.HTTPError, ) as err:
ba515388 139 if err.code == 416:
3bc2ddcc
JMF
140 # Unable to resume (requested range not satisfiable)
141 try:
142 # Open the connection again without the range header
cf7259bc
S
143 ctx.data = self.ydl.urlopen(
144 sanitized_Request(url, None, headers))
a3c3a1e1 145 content_length = ctx.data.info()['Content-Length']
3bc2ddcc
JMF
146 except (compat_urllib_error.HTTPError, ) as err:
147 if err.code < 500 or err.code >= 600:
148 raise
149 else:
150 # Examine the reported length
151 if (content_length is not None and
a3c3a1e1 152 (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)):
3bc2ddcc
JMF
153 # The file had already been fully downloaded.
154 # Explanation to the above condition: in issue #175 it was revealed that
155 # YouTube sometimes adds or removes a few bytes from the end of the file,
156 # changing the file size slightly and causing problems for some users. So
157 # I decided to implement a suggested change and consider the file
158 # completely downloaded if the file size differs less than 100 bytes from
159 # the one in the hard drive.
a3c3a1e1
S
160 self.report_file_already_downloaded(ctx.filename)
161 self.try_rename(ctx.tmpfilename, ctx.filename)
3bc2ddcc 162 self._hook_progress({
a3c3a1e1 163 'filename': ctx.filename,
3bc2ddcc 164 'status': 'finished',
a3c3a1e1
S
165 'downloaded_bytes': ctx.resume_len,
166 'total_bytes': ctx.resume_len,
3bc2ddcc 167 })
a3c3a1e1 168 raise SucceedDownload()
3bc2ddcc
JMF
169 else:
170 # The length does not match, we start the download over
171 self.report_unable_to_resume()
a3c3a1e1
S
172 ctx.resume_len = 0
173 ctx.open_mode = 'wb'
174 return
ba515388
S
175 elif err.code < 500 or err.code >= 600:
176 # Unexpected HTTP error
177 raise
a3c3a1e1
S
178 raise RetryDownload(err)
179 except socket.error as err:
180 if err.errno != errno.ECONNRESET:
12832049
PH
181 # Connection reset is no problem, just retry
182 raise
a3c3a1e1
S
183 raise RetryDownload(err)
184
185 def download():
186 data_len = ctx.data.info().get('Content-length', None)
187
188 # Range HTTP header may be ignored/unsupported by a webserver
189 # (e.g. extractor/scivee.py, extractor/bambuser.py).
190 # However, for a test we still would like to download just a piece of a file.
191 # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control
192 # block size when downloading a file.
193 if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):
194 data_len = self._TEST_FILE_SIZE
195
196 if data_len is not None:
197 data_len = int(data_len) + ctx.resume_len
198 min_data_len = self.params.get('min_filesize')
199 max_data_len = self.params.get('max_filesize')
200 if min_data_len is not None and data_len < min_data_len:
201 self.to_screen('\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
202 return False
203 if max_data_len is not None and data_len > max_data_len:
204 self.to_screen('\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
205 return False
12832049 206
a3c3a1e1 207 byte_counter = 0 + ctx.resume_len
ba515388 208 block_size = ctx.block_size
a3c3a1e1 209 start = time.time()
c7667c2d 210
a3c3a1e1
S
211 # measure time over whole while-loop, so slow_down() and best_block_size() work together properly
212 now = None # needed for slow_down() in the first loop run
213 before = start # start measuring
c7667c2d 214
a3c3a1e1
S
215 def retry(e):
216 if ctx.tmpfilename != '-':
217 ctx.stream.close()
218 ctx.stream = None
219 ctx.resume_len = os.path.getsize(encodeFilename(ctx.tmpfilename))
220 raise RetryDownload(e)
c7667c2d 221
a3c3a1e1
S
222 while True:
223 try:
224 # Download and write
225 data_block = ctx.data.read(block_size if not is_test else min(block_size, data_len - byte_counter))
226 # socket.timeout is a subclass of socket.error but may not have
227 # errno set
228 except socket.timeout as e:
229 retry(e)
230 except socket.error as e:
231 if e.errno not in (errno.ECONNRESET, errno.ETIMEDOUT):
232 raise
233 retry(e)
234
235 byte_counter += len(data_block)
236
237 # exit loop when download is finished
238 if len(data_block) == 0:
239 break
240
241 # Open destination file just in time
242 if ctx.stream is None:
243 try:
244 ctx.stream, ctx.tmpfilename = sanitize_open(
245 ctx.tmpfilename, ctx.open_mode)
246 assert ctx.stream is not None
247 ctx.filename = self.undo_temp_name(ctx.tmpfilename)
248 self.report_destination(ctx.filename)
249 except (OSError, IOError) as err:
250 self.report_error('unable to open for writing: %s' % str(err))
251 return False
252
253 if self.params.get('xattr_set_filesize', False) and data_len is not None:
254 try:
255 write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode('utf-8'))
256 except (XAttrUnavailableError, XAttrMetadataError) as err:
257 self.report_error('unable to set filesize xattr: %s' % str(err))
3bc2ddcc 258
3bc2ddcc 259 try:
a3c3a1e1
S
260 ctx.stream.write(data_block)
261 except (IOError, OSError) as err:
262 self.to_stderr('\n')
263 self.report_error('unable to write data: %s' % str(err))
3bc2ddcc 264 return False
881e6a1f 265
a3c3a1e1
S
266 # Apply rate limit
267 self.slow_down(start, now, byte_counter - ctx.resume_len)
268
269 # end measuring of one loop run
270 now = time.time()
271 after = now
272
273 # Adjust block size
274 if not self.params.get('noresizebuffer', False):
275 block_size = self.best_block_size(after - before, len(data_block))
276
277 before = after
278
279 # Progress message
280 speed = self.calc_speed(start, now, byte_counter - ctx.resume_len)
ba515388 281 if ctx.data_len is None:
a3c3a1e1
S
282 eta = None
283 else:
ba515388 284 eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len)
a3c3a1e1
S
285
286 self._hook_progress({
287 'status': 'downloading',
288 'downloaded_bytes': byte_counter,
ba515388 289 'total_bytes': ctx.data_len,
a3c3a1e1
S
290 'tmpfilename': ctx.tmpfilename,
291 'filename': ctx.filename,
292 'eta': eta,
293 'speed': speed,
ba515388 294 'elapsed': now - ctx.start_time,
a3c3a1e1
S
295 })
296
297 if is_test and byte_counter == data_len:
298 break
299
ba515388
S
300 if not is_test and chunk_size and ctx.data_len is not None and byte_counter < ctx.data_len:
301 ctx.resume_len = byte_counter
302 # ctx.block_size = block_size
303 raise NextFragment()
304
a3c3a1e1 305 if ctx.stream is None:
4d2d638d 306 self.to_stderr('\n')
a3c3a1e1 307 self.report_error('Did not get any data blocks')
3bc2ddcc 308 return False
a3c3a1e1
S
309 if ctx.tmpfilename != '-':
310 ctx.stream.close()
c7667c2d 311
a3c3a1e1
S
312 if data_len is not None and byte_counter != data_len:
313 err = ContentTooShortError(byte_counter, int(data_len))
314 if count <= retries:
315 retry(err)
316 raise err
c7667c2d 317
a3c3a1e1 318 self.try_rename(ctx.tmpfilename, ctx.filename)
c7667c2d 319
a3c3a1e1
S
320 # Update file modification time
321 if self.params.get('updatetime', True):
322 info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None))
3bc2ddcc
JMF
323
324 self._hook_progress({
325 'downloaded_bytes': byte_counter,
a3c3a1e1
S
326 'total_bytes': byte_counter,
327 'filename': ctx.filename,
328 'status': 'finished',
ba515388 329 'elapsed': time.time() - ctx.start_time,
3bc2ddcc
JMF
330 })
331
a3c3a1e1
S
332 return True
333
334 while count <= retries:
335 try:
336 establish_connection()
bec49996 337 return download()
a3c3a1e1
S
338 except RetryDownload as e:
339 count += 1
340 if count <= retries:
341 self.report_retry(e.source_error, count, retries)
342 continue
ba515388
S
343 except NextFragment:
344 continue
a3c3a1e1
S
345 except SucceedDownload:
346 return True
347
348 self.report_error('giving up after %s retries' % retries)
349 return False