Merge pull request #1350 from Jaiz909/description-keyerror-fix
[youtube-dl] / youtube_dl / FileDownloader.py
1 import math
2 import os
3 import re
4 import subprocess
5 import sys
6 import time
7 import traceback
8
9 if os.name == 'nt':
10     import ctypes
11
12 from .utils import *
13
14
15 class FileDownloader(object):
16     """File Downloader class.
17
18     File downloader objects are the ones responsible of downloading the
19     actual video file and writing it to disk.
20
21     File downloaders accept a lot of parameters. In order not to saturate
22     the object constructor with arguments, it receives a dictionary of
23     options instead.
24
25     Available options:
26
27     verbose:           Print additional info to stdout.
28     quiet:             Do not print messages to stdout.
29     ratelimit:         Download speed limit, in bytes/sec.
30     retries:           Number of times to retry for HTTP error 5xx
31     buffersize:        Size of download buffer in bytes.
32     noresizebuffer:    Do not automatically resize the download buffer.
33     continuedl:        Try to continue downloads if possible.
34     noprogress:        Do not print the progress bar.
35     logtostderr:       Log messages to stderr instead of stdout.
36     consoletitle:      Display progress in console window's titlebar.
37     nopart:            Do not use temporary .part files.
38     updatetime:        Use the Last-modified header to set output file timestamps.
39     test:              Download only first bytes to test the downloader.
40     min_filesize:      Skip files smaller than this size
41     max_filesize:      Skip files larger than this size
42     """
43
44     params = None
45
46     def __init__(self, ydl, params):
47         """Create a FileDownloader object with the given options."""
48         self.ydl = ydl
49         self._progress_hooks = []
50         self.params = params
51
52     @staticmethod
53     def format_bytes(bytes):
54         if bytes is None:
55             return 'N/A'
56         if type(bytes) is str:
57             bytes = float(bytes)
58         if bytes == 0.0:
59             exponent = 0
60         else:
61             exponent = int(math.log(bytes, 1024.0))
62         suffix = ['B','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'][exponent]
63         converted = float(bytes) / float(1024 ** exponent)
64         return '%.2f%s' % (converted, suffix)
65
66     @staticmethod
67     def format_seconds(seconds):
68         (mins, secs) = divmod(seconds, 60)
69         (hours, mins) = divmod(mins, 60)
70         if hours > 99:
71             return '--:--:--'
72         if hours == 0:
73             return '%02d:%02d' % (mins, secs)
74         else:
75             return '%02d:%02d:%02d' % (hours, mins, secs)
76
77     @staticmethod
78     def calc_percent(byte_counter, data_len):
79         if data_len is None:
80             return '---.-%'
81         return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
82
83     @staticmethod
84     def calc_eta(start, now, total, current):
85         if total is None:
86             return '--:--'
87         dif = now - start
88         if current == 0 or dif < 0.001: # One millisecond
89             return '--:--'
90         rate = float(current) / dif
91         eta = int((float(total) - float(current)) / rate)
92         return FileDownloader.format_seconds(eta)
93
94     @staticmethod
95     def calc_speed(start, now, bytes):
96         dif = now - start
97         if bytes == 0 or dif < 0.001: # One millisecond
98             return '%10s' % '---b/s'
99         return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
100
101     @staticmethod
102     def best_block_size(elapsed_time, bytes):
103         new_min = max(bytes / 2.0, 1.0)
104         new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
105         if elapsed_time < 0.001:
106             return int(new_max)
107         rate = bytes / elapsed_time
108         if rate > new_max:
109             return int(new_max)
110         if rate < new_min:
111             return int(new_min)
112         return int(rate)
113
114     @staticmethod
115     def parse_bytes(bytestr):
116         """Parse a string indicating a byte quantity into an integer."""
117         matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
118         if matchobj is None:
119             return None
120         number = float(matchobj.group(1))
121         multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
122         return int(round(number * multiplier))
123
124     def to_screen(self, *args, **kargs):
125         self.ydl.to_screen(*args, **kargs)
126
127     def to_stderr(self, message):
128         self.ydl.to_screen(message)
129
130     def to_cons_title(self, message):
131         """Set console/terminal window title to message."""
132         if not self.params.get('consoletitle', False):
133             return
134         if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
135             # c_wchar_p() might not be necessary if `message` is
136             # already of type unicode()
137             ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
138         elif 'TERM' in os.environ:
139             self.to_screen('\033]0;%s\007' % message, skip_eol=True)
140
141     def trouble(self, *args, **kargs):
142         self.ydl.trouble(*args, **kargs)
143
144     def report_warning(self, *args, **kargs):
145         self.ydl.report_warning(*args, **kargs)
146
147     def report_error(self, *args, **kargs):
148         self.ydl.report_error(*args, **kargs)
149
150     def slow_down(self, start_time, byte_counter):
151         """Sleep if the download speed is over the rate limit."""
152         rate_limit = self.params.get('ratelimit', None)
153         if rate_limit is None or byte_counter == 0:
154             return
155         now = time.time()
156         elapsed = now - start_time
157         if elapsed <= 0.0:
158             return
159         speed = float(byte_counter) / elapsed
160         if speed > rate_limit:
161             time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
162
163     def temp_name(self, filename):
164         """Returns a temporary filename for the given filename."""
165         if self.params.get('nopart', False) or filename == u'-' or \
166                 (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
167             return filename
168         return filename + u'.part'
169
170     def undo_temp_name(self, filename):
171         if filename.endswith(u'.part'):
172             return filename[:-len(u'.part')]
173         return filename
174
175     def try_rename(self, old_filename, new_filename):
176         try:
177             if old_filename == new_filename:
178                 return
179             os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
180         except (IOError, OSError) as err:
181             self.report_error(u'unable to rename file')
182
183     def try_utime(self, filename, last_modified_hdr):
184         """Try to set the last-modified time of the given file."""
185         if last_modified_hdr is None:
186             return
187         if not os.path.isfile(encodeFilename(filename)):
188             return
189         timestr = last_modified_hdr
190         if timestr is None:
191             return
192         filetime = timeconvert(timestr)
193         if filetime is None:
194             return filetime
195         # Ignore obviously invalid dates
196         if filetime == 0:
197             return
198         try:
199             os.utime(filename, (time.time(), filetime))
200         except:
201             pass
202         return filetime
203
204     def report_destination(self, filename):
205         """Report destination filename."""
206         self.to_screen(u'[download] Destination: ' + filename)
207
208     def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
209         """Report download progress."""
210         if self.params.get('noprogress', False):
211             return
212         clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
213         if self.params.get('progress_with_newline', False):
214             self.to_screen(u'[download] %s of %s at %s ETA %s' %
215                 (percent_str, data_len_str, speed_str, eta_str))
216         else:
217             self.to_screen(u'\r%s[download] %s of %s at %s ETA %s' %
218                 (clear_line, percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
219         self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
220                 (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
221
222     def report_resuming_byte(self, resume_len):
223         """Report attempt to resume at given byte."""
224         self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
225
226     def report_retry(self, count, retries):
227         """Report retry in case of HTTP error 5xx"""
228         self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
229
230     def report_file_already_downloaded(self, file_name):
231         """Report file has already been fully downloaded."""
232         try:
233             self.to_screen(u'[download] %s has already been downloaded' % file_name)
234         except (UnicodeEncodeError) as err:
235             self.to_screen(u'[download] The file has already been downloaded')
236
237     def report_unable_to_resume(self):
238         """Report it was impossible to resume download."""
239         self.to_screen(u'[download] Unable to resume')
240
241     def report_finish(self, data_len_str, tot_time):
242         """Report download finished."""
243         if self.params.get('noprogress', False):
244             self.to_screen(u'[download] Download completed')
245         else:
246             clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
247             self.to_screen(u'\r%s[download] 100%% of %s in %s' %
248                 (clear_line, data_len_str, self.format_seconds(tot_time)))
249
250     def _download_with_rtmpdump(self, filename, url, player_url, page_url, play_path, tc_url):
251         self.report_destination(filename)
252         tmpfilename = self.temp_name(filename)
253
254         # Check for rtmpdump first
255         try:
256             subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
257         except (OSError, IOError):
258             self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
259             return False
260         verbosity_option = '--verbose' if self.params.get('verbose', False) else '--quiet'
261
262         # Download using rtmpdump. rtmpdump returns exit code 2 when
263         # the connection was interrumpted and resuming appears to be
264         # possible. This is part of rtmpdump's normal usage, AFAIK.
265         basic_args = ['rtmpdump', verbosity_option, '-r', url, '-o', tmpfilename]
266         if player_url is not None:
267             basic_args += ['--swfVfy', player_url]
268         if page_url is not None:
269             basic_args += ['--pageUrl', page_url]
270         if play_path is not None:
271             basic_args += ['--playpath', play_path]
272         if tc_url is not None:
273             basic_args += ['--tcUrl', url]
274         args = basic_args + [[], ['--resume', '--skip', '1']][self.params.get('continuedl', False)]
275         if self.params.get('verbose', False):
276             try:
277                 import pipes
278                 shell_quote = lambda args: ' '.join(map(pipes.quote, args))
279             except ImportError:
280                 shell_quote = repr
281             self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
282         retval = subprocess.call(args)
283         while retval == 2 or retval == 1:
284             prevsize = os.path.getsize(encodeFilename(tmpfilename))
285             self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
286             time.sleep(5.0) # This seems to be needed
287             retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
288             cursize = os.path.getsize(encodeFilename(tmpfilename))
289             if prevsize == cursize and retval == 1:
290                 break
291              # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
292             if prevsize == cursize and retval == 2 and cursize > 1024:
293                 self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
294                 retval = 0
295                 break
296         if retval == 0:
297             fsize = os.path.getsize(encodeFilename(tmpfilename))
298             self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
299             self.try_rename(tmpfilename, filename)
300             self._hook_progress({
301                 'downloaded_bytes': fsize,
302                 'total_bytes': fsize,
303                 'filename': filename,
304                 'status': 'finished',
305             })
306             return True
307         else:
308             self.to_stderr(u"\n")
309             self.report_error(u'rtmpdump exited with code %d' % retval)
310             return False
311
312     def _download_with_mplayer(self, filename, url):
313         self.report_destination(filename)
314         tmpfilename = self.temp_name(filename)
315
316         args = ['mplayer', '-really-quiet', '-vo', 'null', '-vc', 'dummy', '-dumpstream', '-dumpfile', tmpfilename, url]
317         # Check for mplayer first
318         try:
319             subprocess.call(['mplayer', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
320         except (OSError, IOError):
321             self.report_error(u'MMS or RTSP download detected but "%s" could not be run' % args[0] )
322             return False
323
324         # Download using mplayer. 
325         retval = subprocess.call(args)
326         if retval == 0:
327             fsize = os.path.getsize(encodeFilename(tmpfilename))
328             self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
329             self.try_rename(tmpfilename, filename)
330             self._hook_progress({
331                 'downloaded_bytes': fsize,
332                 'total_bytes': fsize,
333                 'filename': filename,
334                 'status': 'finished',
335             })
336             return True
337         else:
338             self.to_stderr(u"\n")
339             self.report_error(u'mplayer exited with code %d' % retval)
340             return False
341
342     def _download_m3u8_with_ffmpeg(self, filename, url):
343         self.report_destination(filename)
344         tmpfilename = self.temp_name(filename)
345
346         args = ['ffmpeg', '-y', '-i', url, '-f', 'mp4', tmpfilename]
347         # Check for ffmpeg first
348         try:
349             subprocess.call(['ffmpeg', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
350         except (OSError, IOError):
351             self.report_error(u'm3u8 download detected but "%s" could not be run' % args[0] )
352             return False
353
354         retval = subprocess.call(args)
355         if retval == 0:
356             fsize = os.path.getsize(encodeFilename(tmpfilename))
357             self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
358             self.try_rename(tmpfilename, filename)
359             self._hook_progress({
360                 'downloaded_bytes': fsize,
361                 'total_bytes': fsize,
362                 'filename': filename,
363                 'status': 'finished',
364             })
365             return True
366         else:
367             self.to_stderr(u"\n")
368             self.report_error(u'ffmpeg exited with code %d' % retval)
369             return False
370
371
372     def _do_download(self, filename, info_dict):
373         url = info_dict['url']
374
375         # Check file already present
376         if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
377             self.report_file_already_downloaded(filename)
378             self._hook_progress({
379                 'filename': filename,
380                 'status': 'finished',
381             })
382             return True
383
384         # Attempt to download using rtmpdump
385         if url.startswith('rtmp'):
386             return self._download_with_rtmpdump(filename, url,
387                                                 info_dict.get('player_url', None),
388                                                 info_dict.get('page_url', None),
389                                                 info_dict.get('play_path', None),
390                                                 info_dict.get('tc_url', None))
391
392         # Attempt to download using mplayer
393         if url.startswith('mms') or url.startswith('rtsp'):
394             return self._download_with_mplayer(filename, url)
395
396         # m3u8 manifest are downloaded with ffmpeg
397         if determine_ext(url) == u'm3u8':
398             return self._download_m3u8_with_ffmpeg(filename, url)
399
400         tmpfilename = self.temp_name(filename)
401         stream = None
402
403         # Do not include the Accept-Encoding header
404         headers = {'Youtubedl-no-compression': 'True'}
405         if 'user_agent' in info_dict:
406             headers['Youtubedl-user-agent'] = info_dict['user_agent']
407         basic_request = compat_urllib_request.Request(url, None, headers)
408         request = compat_urllib_request.Request(url, None, headers)
409
410         if self.params.get('test', False):
411             request.add_header('Range','bytes=0-10240')
412
413         # Establish possible resume length
414         if os.path.isfile(encodeFilename(tmpfilename)):
415             resume_len = os.path.getsize(encodeFilename(tmpfilename))
416         else:
417             resume_len = 0
418
419         open_mode = 'wb'
420         if resume_len != 0:
421             if self.params.get('continuedl', False):
422                 self.report_resuming_byte(resume_len)
423                 request.add_header('Range','bytes=%d-' % resume_len)
424                 open_mode = 'ab'
425             else:
426                 resume_len = 0
427
428         count = 0
429         retries = self.params.get('retries', 0)
430         while count <= retries:
431             # Establish connection
432             try:
433                 if count == 0 and 'urlhandle' in info_dict:
434                     data = info_dict['urlhandle']
435                 data = compat_urllib_request.urlopen(request)
436                 break
437             except (compat_urllib_error.HTTPError, ) as err:
438                 if (err.code < 500 or err.code >= 600) and err.code != 416:
439                     # Unexpected HTTP error
440                     raise
441                 elif err.code == 416:
442                     # Unable to resume (requested range not satisfiable)
443                     try:
444                         # Open the connection again without the range header
445                         data = compat_urllib_request.urlopen(basic_request)
446                         content_length = data.info()['Content-Length']
447                     except (compat_urllib_error.HTTPError, ) as err:
448                         if err.code < 500 or err.code >= 600:
449                             raise
450                     else:
451                         # Examine the reported length
452                         if (content_length is not None and
453                                 (resume_len - 100 < int(content_length) < resume_len + 100)):
454                             # The file had already been fully downloaded.
455                             # Explanation to the above condition: in issue #175 it was revealed that
456                             # YouTube sometimes adds or removes a few bytes from the end of the file,
457                             # changing the file size slightly and causing problems for some users. So
458                             # I decided to implement a suggested change and consider the file
459                             # completely downloaded if the file size differs less than 100 bytes from
460                             # the one in the hard drive.
461                             self.report_file_already_downloaded(filename)
462                             self.try_rename(tmpfilename, filename)
463                             self._hook_progress({
464                                 'filename': filename,
465                                 'status': 'finished',
466                             })
467                             return True
468                         else:
469                             # The length does not match, we start the download over
470                             self.report_unable_to_resume()
471                             open_mode = 'wb'
472                             break
473             # Retry
474             count += 1
475             if count <= retries:
476                 self.report_retry(count, retries)
477
478         if count > retries:
479             self.report_error(u'giving up after %s retries' % retries)
480             return False
481
482         data_len = data.info().get('Content-length', None)
483         if data_len is not None:
484             data_len = int(data_len) + resume_len
485             min_data_len = self.params.get("min_filesize", None)
486             max_data_len =  self.params.get("max_filesize", None)
487             if min_data_len is not None and data_len < min_data_len:
488                 self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
489                 return False
490             if max_data_len is not None and data_len > max_data_len:
491                 self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
492                 return False
493
494         data_len_str = self.format_bytes(data_len)
495         byte_counter = 0 + resume_len
496         block_size = self.params.get('buffersize', 1024)
497         start = time.time()
498         while True:
499             # Download and write
500             before = time.time()
501             data_block = data.read(block_size)
502             after = time.time()
503             if len(data_block) == 0:
504                 break
505             byte_counter += len(data_block)
506
507             # Open file just in time
508             if stream is None:
509                 try:
510                     (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
511                     assert stream is not None
512                     filename = self.undo_temp_name(tmpfilename)
513                     self.report_destination(filename)
514                 except (OSError, IOError) as err:
515                     self.report_error(u'unable to open for writing: %s' % str(err))
516                     return False
517             try:
518                 stream.write(data_block)
519             except (IOError, OSError) as err:
520                 self.to_stderr(u"\n")
521                 self.report_error(u'unable to write data: %s' % str(err))
522                 return False
523             if not self.params.get('noresizebuffer', False):
524                 block_size = self.best_block_size(after - before, len(data_block))
525
526             # Progress message
527             speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
528             if data_len is None:
529                 self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
530             else:
531                 percent_str = self.calc_percent(byte_counter, data_len)
532                 eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
533                 self.report_progress(percent_str, data_len_str, speed_str, eta_str)
534
535             self._hook_progress({
536                 'downloaded_bytes': byte_counter,
537                 'total_bytes': data_len,
538                 'tmpfilename': tmpfilename,
539                 'filename': filename,
540                 'status': 'downloading',
541             })
542
543             # Apply rate limit
544             self.slow_down(start, byte_counter - resume_len)
545
546         if stream is None:
547             self.to_stderr(u"\n")
548             self.report_error(u'Did not get any data blocks')
549             return False
550         stream.close()
551         self.report_finish(data_len_str, (time.time() - start))
552         if data_len is not None and byte_counter != data_len:
553             raise ContentTooShortError(byte_counter, int(data_len))
554         self.try_rename(tmpfilename, filename)
555
556         # Update file modification time
557         if self.params.get('updatetime', True):
558             info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
559
560         self._hook_progress({
561             'downloaded_bytes': byte_counter,
562             'total_bytes': byte_counter,
563             'filename': filename,
564             'status': 'finished',
565         })
566
567         return True
568
569     def _hook_progress(self, status):
570         for ph in self._progress_hooks:
571             ph(status)
572
573     def add_progress_hook(self, ph):
574         """ ph gets called on download progress, with a dictionary with the entries
575         * filename: The final filename
576         * status: One of "downloading" and "finished"
577
578         It can also have some of the following entries:
579
580         * downloaded_bytes: Bytes on disks
581         * total_bytes: Total bytes, None if unknown
582         * tmpfilename: The filename we're currently writing to
583
584         Hooks are guaranteed to be called at least once (with status "finished")
585         if the download is successful.
586         """
587         self._progress_hooks.append(ph)