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