1 from __future__ import unicode_literals
6 from .common import FileDownloader
19 class HttpFD(FileDownloader):
20 def real_download(self, filename, info_dict):
21 url = info_dict['url']
22 tmpfilename = self.temp_name(filename)
25 # Do not include the Accept-Encoding header
26 headers = {'Youtubedl-no-compression': 'True'}
27 add_headers = info_dict.get('http_headers')
29 headers.update(add_headers)
30 data = info_dict.get('http_post_data')
31 http_method = info_dict.get('http_method')
32 basic_request = compat_urllib_request.Request(url, data, headers)
33 request = compat_urllib_request.Request(url, data, headers)
34 if http_method is not None:
35 basic_request.get_method = lambda: http_method
36 request.get_method = lambda: http_method
38 is_test = self.params.get('test', False)
41 request.add_header('Range', 'bytes=0-%s' % str(self._TEST_FILE_SIZE - 1))
43 # Establish possible resume length
44 if os.path.isfile(encodeFilename(tmpfilename)):
45 resume_len = os.path.getsize(encodeFilename(tmpfilename))
51 if self.params.get('continuedl', False):
52 self.report_resuming_byte(resume_len)
53 request.add_header('Range', 'bytes=%d-' % resume_len)
59 retries = self.params.get('retries', 0)
60 while count <= retries:
61 # Establish connection
63 data = self.ydl.urlopen(request)
65 except (compat_urllib_error.HTTPError, ) as err:
66 if (err.code < 500 or err.code >= 600) and err.code != 416:
67 # Unexpected HTTP error
70 # Unable to resume (requested range not satisfiable)
72 # Open the connection again without the range header
73 data = self.ydl.urlopen(basic_request)
74 content_length = data.info()['Content-Length']
75 except (compat_urllib_error.HTTPError, ) as err:
76 if err.code < 500 or err.code >= 600:
79 # Examine the reported length
80 if (content_length is not None and
81 (resume_len - 100 < int(content_length) < resume_len + 100)):
82 # The file had already been fully downloaded.
83 # Explanation to the above condition: in issue #175 it was revealed that
84 # YouTube sometimes adds or removes a few bytes from the end of the file,
85 # changing the file size slightly and causing problems for some users. So
86 # I decided to implement a suggested change and consider the file
87 # completely downloaded if the file size differs less than 100 bytes from
88 # the one in the hard drive.
89 self.report_file_already_downloaded(filename)
90 self.try_rename(tmpfilename, filename)
97 # The length does not match, we start the download over
98 self.report_unable_to_resume()
105 self.report_retry(count, retries)
108 self.report_error('giving up after %s retries' % retries)
111 data_len = data.info().get('Content-length', None)
113 # Range HTTP header may be ignored/unsupported by a webserver
114 # (e.g. extractor/scivee.py, extractor/bambuser.py).
115 # However, for a test we still would like to download just a piece of a file.
116 # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control
117 # block size when downloading a file.
118 if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):
119 data_len = self._TEST_FILE_SIZE
121 if data_len is not None:
122 data_len = int(data_len) + resume_len
123 min_data_len = self.params.get("min_filesize", None)
124 max_data_len = self.params.get("max_filesize", None)
125 if min_data_len is not None and data_len < min_data_len:
126 self.to_screen('\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
128 if max_data_len is not None and data_len > max_data_len:
129 self.to_screen('\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
132 data_len_str = format_bytes(data_len)
133 byte_counter = 0 + resume_len
134 block_size = self.params.get('buffersize', 1024)
137 # measure time over whole while-loop, so slow_down() and best_block_size() work together properly
138 now = None # needed for slow_down() in the first loop run
139 before = start # start measuring
143 data_block = data.read(block_size if not is_test else min(block_size, data_len - byte_counter))
144 byte_counter += len(data_block)
146 # exit loop when download is finished
147 if len(data_block) == 0:
150 # Open destination file just in time
153 (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
154 assert stream is not None
155 filename = self.undo_temp_name(tmpfilename)
156 self.report_destination(filename)
157 except (OSError, IOError) as err:
158 self.report_error('unable to open for writing: %s' % str(err))
161 if self.params.get('xattr_set_filesize', False) and data_len is not None:
164 xattr.setxattr(tmpfilename, 'user.ytdl.filesize', str(data_len))
165 except(OSError, IOError, ImportError) as err:
166 self.report_error('unable to set filesize xattr: %s' % str(err))
169 stream.write(data_block)
170 except (IOError, OSError) as err:
172 self.report_error('unable to write data: %s' % str(err))
176 self.slow_down(start, now, byte_counter - resume_len)
178 # end measuring of one loop run
183 if not self.params.get('noresizebuffer', False):
184 block_size = self.best_block_size(after - before, len(data_block))
189 speed = self.calc_speed(start, now, byte_counter - resume_len)
193 percent = self.calc_percent(byte_counter, data_len)
194 eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
195 self.report_progress(percent, data_len_str, speed, eta)
197 self._hook_progress({
198 'downloaded_bytes': byte_counter,
199 'total_bytes': data_len,
200 'tmpfilename': tmpfilename,
201 'filename': filename,
202 'status': 'downloading',
207 if is_test and byte_counter == data_len:
212 self.report_error('Did not get any data blocks')
214 if tmpfilename != '-':
216 self.report_finish(data_len_str, (time.time() - start))
217 if data_len is not None and byte_counter != data_len:
218 raise ContentTooShortError(byte_counter, int(data_len))
219 self.try_rename(tmpfilename, filename)
221 # Update file modification time
222 if self.params.get('updatetime', True):
223 info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
225 self._hook_progress({
226 'downloaded_bytes': byte_counter,
227 'total_bytes': byte_counter,
228 'filename': filename,
229 'status': 'finished',