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