]>
Commit | Line | Data |
---|---|---|
4d2d638d PH |
1 | from __future__ import unicode_literals |
2 | ||
16e7711e | 3 | import errno |
3bc2ddcc | 4 | import os |
16e7711e | 5 | import socket |
3bc2ddcc | 6 | import time |
b91a7a4e | 7 | import random |
8d5b8b47 | 8 | import re |
3bc2ddcc JMF |
9 | |
10 | from .common import FileDownloader | |
ba515388 S |
11 | from ..compat import ( |
12 | compat_str, | |
13 | compat_urllib_error, | |
14 | ) | |
1cc79574 | 15 | from ..utils import ( |
3bc2ddcc | 16 | ContentTooShortError, |
3bc2ddcc | 17 | encodeFilename, |
ba515388 | 18 | int_or_none, |
5c2266df | 19 | sanitized_Request, |
51d9739f | 20 | ThrottledDownload, |
d7753d19 YCH |
21 | write_xattr, |
22 | XAttrMetadataError, | |
23 | XAttrUnavailableError, | |
3bc2ddcc JMF |
24 | ) |
25 | ||
26 | ||
27 | class HttpFD(FileDownloader): | |
d3f0687c | 28 | def real_download(self, filename, info_dict): |
3bc2ddcc | 29 | url = info_dict['url'] |
273762c8 | 30 | request_data = info_dict.get('request_data', None) |
a3c3a1e1 S |
31 | |
32 | class DownloadContext(dict): | |
33 | __getattr__ = dict.get | |
34 | __setattr__ = dict.__setitem__ | |
35 | __delattr__ = dict.__delitem__ | |
36 | ||
37 | ctx = DownloadContext() | |
38 | ctx.filename = filename | |
39 | ctx.tmpfilename = self.temp_name(filename) | |
40 | ctx.stream = None | |
3bc2ddcc JMF |
41 | |
42 | # Do not include the Accept-Encoding header | |
43 | headers = {'Youtubedl-no-compression': 'True'} | |
d769be6c PH |
44 | add_headers = info_dict.get('http_headers') |
45 | if add_headers: | |
46 | headers.update(add_headers) | |
3bc2ddcc | 47 | |
df297c87 | 48 | is_test = self.params.get('test', False) |
ba515388 | 49 | chunk_size = self._TEST_FILE_SIZE if is_test else ( |
b5ae35ee | 50 | self.params.get('http_chunk_size') |
51 | or info_dict.get('downloader_options', {}).get('http_chunk_size') | |
b922db9f | 52 | or 0) |
3bc2ddcc | 53 | |
a3c3a1e1 S |
54 | ctx.open_mode = 'wb' |
55 | ctx.resume_len = 0 | |
ba515388 S |
56 | ctx.data_len = None |
57 | ctx.block_size = self.params.get('buffersize', 1024) | |
58 | ctx.start_time = time.time() | |
b91a7a4e | 59 | ctx.chunk_size = None |
21186af7 | 60 | throttle_start = 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 | 192 | raise RetryDownload(err) |
9fab498f | 193 | except socket.timeout as err: |
194 | raise RetryDownload(err) | |
a3c3a1e1 | 195 | except socket.error as err: |
9fab498f | 196 | if err.errno in (errno.ECONNRESET, errno.ETIMEDOUT): |
12832049 | 197 | # Connection reset is no problem, just retry |
9fab498f | 198 | raise RetryDownload(err) |
199 | raise | |
a3c3a1e1 S |
200 | |
201 | def download(): | |
21186af7 | 202 | nonlocal throttle_start |
a3c3a1e1 S |
203 | data_len = ctx.data.info().get('Content-length', None) |
204 | ||
205 | # Range HTTP header may be ignored/unsupported by a webserver | |
206 | # (e.g. extractor/scivee.py, extractor/bambuser.py). | |
207 | # However, for a test we still would like to download just a piece of a file. | |
208 | # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control | |
209 | # block size when downloading a file. | |
210 | if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE): | |
211 | data_len = self._TEST_FILE_SIZE | |
212 | ||
213 | if data_len is not None: | |
214 | data_len = int(data_len) + ctx.resume_len | |
215 | min_data_len = self.params.get('min_filesize') | |
216 | max_data_len = self.params.get('max_filesize') | |
217 | if min_data_len is not None and data_len < min_data_len: | |
218 | self.to_screen('\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len)) | |
219 | return False | |
220 | if max_data_len is not None and data_len > max_data_len: | |
221 | self.to_screen('\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len)) | |
222 | return False | |
12832049 | 223 | |
a3c3a1e1 | 224 | byte_counter = 0 + ctx.resume_len |
ba515388 | 225 | block_size = ctx.block_size |
a3c3a1e1 | 226 | start = time.time() |
c7667c2d | 227 | |
a3c3a1e1 S |
228 | # measure time over whole while-loop, so slow_down() and best_block_size() work together properly |
229 | now = None # needed for slow_down() in the first loop run | |
230 | before = start # start measuring | |
c7667c2d | 231 | |
a3c3a1e1 | 232 | def retry(e): |
5d6c81b6 | 233 | to_stdout = ctx.tmpfilename == '-' |
0837992a S |
234 | if ctx.stream is not None: |
235 | if not to_stdout: | |
236 | ctx.stream.close() | |
237 | ctx.stream = None | |
5d6c81b6 | 238 | ctx.resume_len = byte_counter if to_stdout else os.path.getsize(encodeFilename(ctx.tmpfilename)) |
a3c3a1e1 | 239 | raise RetryDownload(e) |
c7667c2d | 240 | |
a3c3a1e1 S |
241 | while True: |
242 | try: | |
243 | # Download and write | |
0715f7e1 | 244 | data_block = ctx.data.read(block_size if not is_test else min(block_size, data_len - byte_counter)) |
a3c3a1e1 S |
245 | # socket.timeout is a subclass of socket.error but may not have |
246 | # errno set | |
247 | except socket.timeout as e: | |
248 | retry(e) | |
249 | except socket.error as e: | |
cdc55e66 S |
250 | # SSLError on python 2 (inherits socket.error) may have |
251 | # no errno set but this error message | |
c5764b3f | 252 | if e.errno in (errno.ECONNRESET, errno.ETIMEDOUT) or getattr(e, 'message', None) == 'The read operation timed out': |
cdc55e66 S |
253 | retry(e) |
254 | raise | |
a3c3a1e1 S |
255 | |
256 | byte_counter += len(data_block) | |
257 | ||
258 | # exit loop when download is finished | |
259 | if len(data_block) == 0: | |
260 | break | |
261 | ||
262 | # Open destination file just in time | |
263 | if ctx.stream is None: | |
264 | try: | |
205a0654 | 265 | ctx.stream, ctx.tmpfilename = self.sanitize_open( |
a3c3a1e1 S |
266 | ctx.tmpfilename, ctx.open_mode) |
267 | assert ctx.stream is not None | |
268 | ctx.filename = self.undo_temp_name(ctx.tmpfilename) | |
269 | self.report_destination(ctx.filename) | |
270 | except (OSError, IOError) as err: | |
271 | self.report_error('unable to open for writing: %s' % str(err)) | |
272 | return False | |
273 | ||
274 | if self.params.get('xattr_set_filesize', False) and data_len is not None: | |
275 | try: | |
276 | write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode('utf-8')) | |
277 | except (XAttrUnavailableError, XAttrMetadataError) as err: | |
278 | self.report_error('unable to set filesize xattr: %s' % str(err)) | |
3bc2ddcc | 279 | |
3bc2ddcc | 280 | try: |
a3c3a1e1 S |
281 | ctx.stream.write(data_block) |
282 | except (IOError, OSError) as err: | |
283 | self.to_stderr('\n') | |
284 | self.report_error('unable to write data: %s' % str(err)) | |
3bc2ddcc | 285 | return False |
881e6a1f | 286 | |
a3c3a1e1 S |
287 | # Apply rate limit |
288 | self.slow_down(start, now, byte_counter - ctx.resume_len) | |
289 | ||
290 | # end measuring of one loop run | |
291 | now = time.time() | |
292 | after = now | |
293 | ||
294 | # Adjust block size | |
295 | if not self.params.get('noresizebuffer', False): | |
296 | block_size = self.best_block_size(after - before, len(data_block)) | |
297 | ||
298 | before = after | |
299 | ||
300 | # Progress message | |
301 | speed = self.calc_speed(start, now, byte_counter - ctx.resume_len) | |
ba515388 | 302 | if ctx.data_len is None: |
a3c3a1e1 S |
303 | eta = None |
304 | else: | |
ba515388 | 305 | eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len) |
a3c3a1e1 S |
306 | |
307 | self._hook_progress({ | |
308 | 'status': 'downloading', | |
309 | 'downloaded_bytes': byte_counter, | |
ba515388 | 310 | 'total_bytes': ctx.data_len, |
a3c3a1e1 S |
311 | 'tmpfilename': ctx.tmpfilename, |
312 | 'filename': ctx.filename, | |
313 | 'eta': eta, | |
314 | 'speed': speed, | |
ba515388 | 315 | 'elapsed': now - ctx.start_time, |
bd50a52b | 316 | 'ctx_id': info_dict.get('ctx_id'), |
3ba7740d | 317 | }, info_dict) |
a3c3a1e1 | 318 | |
f7b42518 | 319 | if data_len is not None and byte_counter == data_len: |
a3c3a1e1 S |
320 | break |
321 | ||
51d9739f | 322 | if speed and speed < (self.params.get('throttledratelimit') or 0): |
323 | # The speed must stay below the limit for 3 seconds | |
324 | # This prevents raising error when the speed temporarily goes down | |
325 | if throttle_start is None: | |
326 | throttle_start = now | |
327 | elif now - throttle_start > 3: | |
328 | if ctx.stream is not None and ctx.tmpfilename != '-': | |
329 | ctx.stream.close() | |
330 | raise ThrottledDownload() | |
21186af7 | 331 | elif speed: |
51d9739f | 332 | throttle_start = None |
333 | ||
b91a7a4e | 334 | if not is_test and ctx.chunk_size and ctx.data_len is not None and byte_counter < ctx.data_len: |
ba515388 S |
335 | ctx.resume_len = byte_counter |
336 | # ctx.block_size = block_size | |
337 | raise NextFragment() | |
338 | ||
a3c3a1e1 | 339 | if ctx.stream is None: |
4d2d638d | 340 | self.to_stderr('\n') |
a3c3a1e1 | 341 | self.report_error('Did not get any data blocks') |
3bc2ddcc | 342 | return False |
a3c3a1e1 S |
343 | if ctx.tmpfilename != '-': |
344 | ctx.stream.close() | |
c7667c2d | 345 | |
a3c3a1e1 S |
346 | if data_len is not None and byte_counter != data_len: |
347 | err = ContentTooShortError(byte_counter, int(data_len)) | |
348 | if count <= retries: | |
349 | retry(err) | |
350 | raise err | |
c7667c2d | 351 | |
a3c3a1e1 | 352 | self.try_rename(ctx.tmpfilename, ctx.filename) |
c7667c2d | 353 | |
a3c3a1e1 S |
354 | # Update file modification time |
355 | if self.params.get('updatetime', True): | |
356 | info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None)) | |
3bc2ddcc JMF |
357 | |
358 | self._hook_progress({ | |
359 | 'downloaded_bytes': byte_counter, | |
a3c3a1e1 S |
360 | 'total_bytes': byte_counter, |
361 | 'filename': ctx.filename, | |
362 | 'status': 'finished', | |
ba515388 | 363 | 'elapsed': time.time() - ctx.start_time, |
bd50a52b | 364 | 'ctx_id': info_dict.get('ctx_id'), |
3ba7740d | 365 | }, info_dict) |
3bc2ddcc | 366 | |
a3c3a1e1 S |
367 | return True |
368 | ||
369 | while count <= retries: | |
370 | try: | |
371 | establish_connection() | |
bec49996 | 372 | return download() |
a3c3a1e1 S |
373 | except RetryDownload as e: |
374 | count += 1 | |
375 | if count <= retries: | |
376 | self.report_retry(e.source_error, count, retries) | |
d5a39f0b | 377 | else: |
378 | self.to_screen(f'[download] Got server HTTP error: {e.source_error}') | |
a3c3a1e1 | 379 | continue |
ba515388 S |
380 | except NextFragment: |
381 | continue | |
a3c3a1e1 S |
382 | except SucceedDownload: |
383 | return True | |
384 | ||
385 | self.report_error('giving up after %s retries' % retries) | |
386 | return False |