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