4 from .common import FileDownloader
16 class HttpFD(FileDownloader):
17 def real_download(self, filename, info_dict):
18 url = info_dict['url']
19 tmpfilename = self.temp_name(filename)
22 # Do not include the Accept-Encoding header
23 headers = {'Youtubedl-no-compression': 'True'}
24 if 'user_agent' in info_dict:
25 headers['Youtubedl-user-agent'] = info_dict['user_agent']
26 basic_request = compat_urllib_request.Request(url, None, headers)
27 request = compat_urllib_request.Request(url, None, headers)
29 if self.params.get('test', False):
30 request.add_header('Range', 'bytes=0-10240')
32 # Establish possible resume length
33 if os.path.isfile(encodeFilename(tmpfilename)):
34 resume_len = os.path.getsize(encodeFilename(tmpfilename))
40 if self.params.get('continuedl', False):
41 self.report_resuming_byte(resume_len)
42 request.add_header('Range', 'bytes=%d-' % resume_len)
48 retries = self.params.get('retries', 0)
49 while count <= retries:
50 # Establish connection
52 data = compat_urllib_request.urlopen(request)
54 except (compat_urllib_error.HTTPError, ) as err:
55 if (err.code < 500 or err.code >= 600) and err.code != 416:
56 # Unexpected HTTP error
59 # Unable to resume (requested range not satisfiable)
61 # Open the connection again without the range header
62 data = compat_urllib_request.urlopen(basic_request)
63 content_length = data.info()['Content-Length']
64 except (compat_urllib_error.HTTPError, ) as err:
65 if err.code < 500 or err.code >= 600:
68 # Examine the reported length
69 if (content_length is not None and
70 (resume_len - 100 < int(content_length) < resume_len + 100)):
71 # The file had already been fully downloaded.
72 # Explanation to the above condition: in issue #175 it was revealed that
73 # YouTube sometimes adds or removes a few bytes from the end of the file,
74 # changing the file size slightly and causing problems for some users. So
75 # I decided to implement a suggested change and consider the file
76 # completely downloaded if the file size differs less than 100 bytes from
77 # the one in the hard drive.
78 self.report_file_already_downloaded(filename)
79 self.try_rename(tmpfilename, filename)
86 # The length does not match, we start the download over
87 self.report_unable_to_resume()
93 self.report_retry(count, retries)
96 self.report_error(u'giving up after %s retries' % retries)
99 data_len = data.info().get('Content-length', None)
100 if data_len is not None:
101 data_len = int(data_len) + resume_len
102 min_data_len = self.params.get("min_filesize", None)
103 max_data_len = self.params.get("max_filesize", None)
104 if min_data_len is not None and data_len < min_data_len:
105 self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
107 if max_data_len is not None and data_len > max_data_len:
108 self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
111 data_len_str = format_bytes(data_len)
112 byte_counter = 0 + resume_len
113 block_size = self.params.get('buffersize', 1024)
118 data_block = data.read(block_size)
120 if len(data_block) == 0:
122 byte_counter += len(data_block)
124 # Open file just in time
127 (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
128 assert stream is not None
129 filename = self.undo_temp_name(tmpfilename)
130 self.report_destination(filename)
131 except (OSError, IOError) as err:
132 self.report_error(u'unable to open for writing: %s' % str(err))
135 stream.write(data_block)
136 except (IOError, OSError) as err:
137 self.to_stderr(u"\n")
138 self.report_error(u'unable to write data: %s' % str(err))
140 if not self.params.get('noresizebuffer', False):
141 block_size = self.best_block_size(after - before, len(data_block))
144 speed = self.calc_speed(start, time.time(), byte_counter - resume_len)
148 percent = self.calc_percent(byte_counter, data_len)
149 eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
150 self.report_progress(percent, data_len_str, speed, eta)
152 self._hook_progress({
153 'downloaded_bytes': byte_counter,
154 'total_bytes': data_len,
155 'tmpfilename': tmpfilename,
156 'filename': filename,
157 'status': 'downloading',
163 self.slow_down(start, byte_counter - resume_len)
166 self.to_stderr(u"\n")
167 self.report_error(u'Did not get any data blocks')
170 self.report_finish(data_len_str, (time.time() - start))
171 if data_len is not None and byte_counter != data_len:
172 raise ContentTooShortError(byte_counter, int(data_len))
173 self.try_rename(tmpfilename, filename)
175 # Update file modification time
176 if self.params.get('updatetime', True):
177 info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
179 self._hook_progress({
180 'downloaded_bytes': byte_counter,
181 'total_bytes': byte_counter,
182 'filename': filename,
183 'status': 'finished',