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