1 from __future__ import unicode_literals
8 from .common import FileDownloader
10 compat_urllib_request,
20 class HttpFD(FileDownloader):
21 def real_download(self, filename, info_dict):
22 url = info_dict['url']
23 tmpfilename = self.temp_name(filename)
26 # Do not include the Accept-Encoding header
27 headers = {'Youtubedl-no-compression': 'True'}
28 add_headers = info_dict.get('http_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)
34 is_test = self.params.get('test', False)
37 request.add_header('Range', 'bytes=0-%s' % str(self._TEST_FILE_SIZE - 1))
39 # Establish possible resume length
40 if os.path.isfile(encodeFilename(tmpfilename)):
41 resume_len = os.path.getsize(encodeFilename(tmpfilename))
47 if self.params.get('continuedl', True):
48 self.report_resuming_byte(resume_len)
49 request.add_header('Range', 'bytes=%d-' % resume_len)
55 retries = self.params.get('retries', 0)
56 while count <= retries:
57 # Establish connection
59 data = self.ydl.urlopen(request)
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
66 # Unable to resume (requested range not satisfiable)
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:
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)
90 'downloaded_bytes': resume_len,
91 'total_bytes': resume_len,
95 # The length does not match, we start the download over
96 self.report_unable_to_resume()
100 except socket.error as e:
101 if e.errno != errno.ECONNRESET:
102 # Connection reset is no problem, just retry
108 self.report_retry(count, retries)
111 self.report_error('giving up after %s retries' % retries)
114 data_len = data.info().get('Content-length', None)
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
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))
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))
135 byte_counter = 0 + resume_len
136 block_size = self.params.get('buffersize', 1024)
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
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)
148 # exit loop when download is finished
149 if len(data_block) == 0:
152 # Open destination file just in time
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))
163 if self.params.get('xattr_set_filesize', False) and data_len is not None:
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))
171 stream.write(data_block)
172 except (IOError, OSError) as err:
174 self.report_error('unable to write data: %s' % str(err))
178 self.slow_down(start, now, byte_counter - resume_len)
180 # end measuring of one loop run
185 if not self.params.get('noresizebuffer', False):
186 block_size = self.best_block_size(after - before, len(data_block))
191 speed = self.calc_speed(start, now, byte_counter - resume_len)
195 eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
197 self._hook_progress({
198 'status': 'downloading',
199 'downloaded_bytes': byte_counter,
200 'total_bytes': data_len,
201 'tmpfilename': tmpfilename,
202 'filename': filename,
205 'elapsed': now - start,
208 if is_test and byte_counter == data_len:
213 self.report_error('Did not get any data blocks')
215 if tmpfilename != '-':
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)
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))
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,