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