]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/downloader/http.py
[thisav] Simplify and use unicode literals
[youtube-dl] / 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     def real_download(self, filename, info_dict):
18         url = info_dict['url']
19         tmpfilename = self.temp_name(filename)
20         stream = None
21
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)
28
29         if self.params.get('test', False):
30             request.add_header('Range', 'bytes=0-10240')
31
32         # Establish possible resume length
33         if os.path.isfile(encodeFilename(tmpfilename)):
34             resume_len = os.path.getsize(encodeFilename(tmpfilename))
35         else:
36             resume_len = 0
37
38         open_mode = 'wb'
39         if resume_len != 0:
40             if self.params.get('continuedl', False):
41                 self.report_resuming_byte(resume_len)
42                 request.add_header('Range', 'bytes=%d-' % resume_len)
43                 open_mode = 'ab'
44             else:
45                 resume_len = 0
46
47         count = 0
48         retries = self.params.get('retries', 0)
49         while count <= retries:
50             # Establish connection
51             try:
52                 data = compat_urllib_request.urlopen(request)
53                 break
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
57                     raise
58                 elif err.code == 416:
59                     # Unable to resume (requested range not satisfiable)
60                     try:
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:
66                             raise
67                     else:
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)
80                             self._hook_progress({
81                                 'filename': filename,
82                                 'status': 'finished',
83                             })
84                             return True
85                         else:
86                             # The length does not match, we start the download over
87                             self.report_unable_to_resume()
88                             open_mode = 'wb'
89                             break
90             # Retry
91             count += 1
92             if count <= retries:
93                 self.report_retry(count, retries)
94
95         if count > retries:
96             self.report_error(u'giving up after %s retries' % retries)
97             return False
98
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))
106                 return False
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))
109                 return False
110
111         data_len_str = format_bytes(data_len)
112         byte_counter = 0 + resume_len
113         block_size = self.params.get('buffersize', 1024)
114         start = time.time()
115         while True:
116             # Download and write
117             before = time.time()
118             data_block = data.read(block_size)
119             after = time.time()
120             if len(data_block) == 0:
121                 break
122             byte_counter += len(data_block)
123
124             # Open file just in time
125             if stream is None:
126                 try:
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))
133                     return False
134             try:
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))
139                 return False
140             if not self.params.get('noresizebuffer', False):
141                 block_size = self.best_block_size(after - before, len(data_block))
142
143             # Progress message
144             speed = self.calc_speed(start, time.time(), byte_counter - resume_len)
145             if data_len is None:
146                 eta = percent = None
147             else:
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)
151
152             self._hook_progress({
153                 'downloaded_bytes': byte_counter,
154                 'total_bytes': data_len,
155                 'tmpfilename': tmpfilename,
156                 'filename': filename,
157                 'status': 'downloading',
158                 'eta': eta,
159                 'speed': speed,
160             })
161
162             # Apply rate limit
163             self.slow_down(start, byte_counter - resume_len)
164
165         if stream is None:
166             self.to_stderr(u"\n")
167             self.report_error(u'Did not get any data blocks')
168             return False
169         stream.close()
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)
174
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))
178
179         self._hook_progress({
180             'downloaded_bytes': byte_counter,
181             'total_bytes': byte_counter,
182             'filename': filename,
183             'status': 'finished',
184         })
185
186         return True