]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/downloader/http.py
e68f20c9f46a93ebfeca2ff47dc0843f4ab94874
[youtubedl] / youtube_dl / downloader / http.py
1 from __future__ import unicode_literals
2
3 import os
4 import time
5
6 from .common import FileDownloader
7 from ..compat import (
8 compat_urllib_request,
9 compat_urllib_error,
10 )
11 from ..utils import (
12 ContentTooShortError,
13 encodeFilename,
14 sanitize_open,
15 format_bytes,
16 )
17
18
19 class HttpFD(FileDownloader):
20 def real_download(self, filename, info_dict):
21 url = info_dict['url']
22 tmpfilename = self.temp_name(filename)
23 stream = None
24
25 # Do not include the Accept-Encoding header
26 headers = {'Youtubedl-no-compression': 'True'}
27 if 'user_agent' in info_dict:
28 headers['Youtubedl-user-agent'] = info_dict['user_agent']
29 if 'http_referer' in info_dict:
30 headers['Referer'] = info_dict['http_referer']
31 add_headers = info_dict.get('http_headers')
32 if add_headers:
33 headers.update(add_headers)
34 data = info_dict.get('http_post_data')
35 http_method = info_dict.get('http_method')
36 basic_request = compat_urllib_request.Request(url, data, headers)
37 request = compat_urllib_request.Request(url, data, headers)
38 if http_method is not None:
39 basic_request.get_method = lambda: http_method
40 request.get_method = lambda: http_method
41
42 is_test = self.params.get('test', False)
43
44 if is_test:
45 request.add_header('Range', 'bytes=0-%s' % str(self._TEST_FILE_SIZE - 1))
46
47 # Establish possible resume length
48 if os.path.isfile(encodeFilename(tmpfilename)):
49 resume_len = os.path.getsize(encodeFilename(tmpfilename))
50 else:
51 resume_len = 0
52
53 open_mode = 'wb'
54 if resume_len != 0:
55 if self.params.get('continuedl', False):
56 self.report_resuming_byte(resume_len)
57 request.add_header('Range', 'bytes=%d-' % resume_len)
58 open_mode = 'ab'
59 else:
60 resume_len = 0
61
62 count = 0
63 retries = self.params.get('retries', 0)
64 while count <= retries:
65 # Establish connection
66 try:
67 data = self.ydl.urlopen(request)
68 break
69 except (compat_urllib_error.HTTPError, ) as err:
70 if (err.code < 500 or err.code >= 600) and err.code != 416:
71 # Unexpected HTTP error
72 raise
73 elif err.code == 416:
74 # Unable to resume (requested range not satisfiable)
75 try:
76 # Open the connection again without the range header
77 data = self.ydl.urlopen(basic_request)
78 content_length = data.info()['Content-Length']
79 except (compat_urllib_error.HTTPError, ) as err:
80 if err.code < 500 or err.code >= 600:
81 raise
82 else:
83 # Examine the reported length
84 if (content_length is not None and
85 (resume_len - 100 < int(content_length) < resume_len + 100)):
86 # The file had already been fully downloaded.
87 # Explanation to the above condition: in issue #175 it was revealed that
88 # YouTube sometimes adds or removes a few bytes from the end of the file,
89 # changing the file size slightly and causing problems for some users. So
90 # I decided to implement a suggested change and consider the file
91 # completely downloaded if the file size differs less than 100 bytes from
92 # the one in the hard drive.
93 self.report_file_already_downloaded(filename)
94 self.try_rename(tmpfilename, filename)
95 self._hook_progress({
96 'filename': filename,
97 'status': 'finished',
98 })
99 return True
100 else:
101 # The length does not match, we start the download over
102 self.report_unable_to_resume()
103 resume_len = 0
104 open_mode = 'wb'
105 break
106 # Retry
107 count += 1
108 if count <= retries:
109 self.report_retry(count, retries)
110
111 if count > retries:
112 self.report_error('giving up after %s retries' % retries)
113 return False
114
115 data_len = data.info().get('Content-length', None)
116
117 # Range HTTP header may be ignored/unsupported by a webserver
118 # (e.g. extractor/scivee.py, extractor/bambuser.py).
119 # However, for a test we still would like to download just a piece of a file.
120 # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control
121 # block size when downloading a file.
122 if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):
123 data_len = self._TEST_FILE_SIZE
124
125 if data_len is not None:
126 data_len = int(data_len) + resume_len
127 min_data_len = self.params.get("min_filesize", None)
128 max_data_len = self.params.get("max_filesize", None)
129 if min_data_len is not None and data_len < min_data_len:
130 self.to_screen('\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
131 return False
132 if max_data_len is not None and data_len > max_data_len:
133 self.to_screen('\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
134 return False
135
136 data_len_str = format_bytes(data_len)
137 byte_counter = 0 + resume_len
138 block_size = self.params.get('buffersize', 1024)
139 start = time.time()
140
141 # measure time over whole while-loop, so slow_down() and best_block_size() work together properly
142 now = None # needed for slow_down() in the first loop run
143 before = start # start measuring
144 while True:
145
146 # Download and write
147 data_block = data.read(block_size if not is_test else min(block_size, data_len - byte_counter))
148 byte_counter += len(data_block)
149
150 # exit loop when download is finished
151 if len(data_block) == 0:
152 break
153
154 # Open destination file just in time
155 if stream is None:
156 try:
157 (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
158 assert stream is not None
159 filename = self.undo_temp_name(tmpfilename)
160 self.report_destination(filename)
161 except (OSError, IOError) as err:
162 self.report_error('unable to open for writing: %s' % str(err))
163 return False
164 try:
165 stream.write(data_block)
166 except (IOError, OSError) as err:
167 self.to_stderr('\n')
168 self.report_error('unable to write data: %s' % str(err))
169 return False
170
171 # Apply rate limit
172 self.slow_down(start, now, byte_counter - resume_len)
173
174 # end measuring of one loop run
175 now = time.time()
176 after = now
177
178 # Adjust block size
179 if not self.params.get('noresizebuffer', False):
180 block_size = self.best_block_size(after - before, len(data_block))
181
182 before = after
183
184 # Progress message
185 speed = self.calc_speed(start, now, byte_counter - resume_len)
186 if data_len is None:
187 eta = percent = None
188 else:
189 percent = self.calc_percent(byte_counter, data_len)
190 eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
191 self.report_progress(percent, data_len_str, speed, eta)
192
193 self._hook_progress({
194 'downloaded_bytes': byte_counter,
195 'total_bytes': data_len,
196 'tmpfilename': tmpfilename,
197 'filename': filename,
198 'status': 'downloading',
199 'eta': eta,
200 'speed': speed,
201 })
202
203 if is_test and byte_counter == data_len:
204 break
205
206 if stream is None:
207 self.to_stderr('\n')
208 self.report_error('Did not get any data blocks')
209 return False
210 if tmpfilename != '-':
211 stream.close()
212 self.report_finish(data_len_str, (time.time() - start))
213 if data_len is not None and byte_counter != data_len:
214 raise ContentTooShortError(byte_counter, int(data_len))
215 self.try_rename(tmpfilename, filename)
216
217 # Update file modification time
218 if self.params.get('updatetime', True):
219 info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
220
221 self._hook_progress({
222 'downloaded_bytes': byte_counter,
223 'total_bytes': byte_counter,
224 'filename': filename,
225 'status': 'finished',
226 })
227
228 return True