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