X-Git-Url: http://git.cielonegro.org/gitweb.cgi?a=blobdiff_plain;f=youtube-dl;h=7527a470442db2aca73cc9540a450b680b4983fe;hb=f807dc157e1215c3dbaf82333f6e86a8f98ea76b;hp=2c1d1aa3b84b5e3cda680e22fe0a6a39dc91c777;hpb=90663284b2c742ae84d3dd00876af9b681ee78ee;p=youtube-dl.git diff --git a/youtube-dl b/youtube-dl index 2c1d1aa3b..7527a4704 100755 --- a/youtube-dl +++ b/youtube-dl @@ -78,6 +78,7 @@ class FileDownloader(object): format: Video format code. outtmpl: Template for output names. ignoreerrors: Do not stop on download errors. + ratelimit: Download speed limit, in bytes/sec. """ _params = None @@ -93,6 +94,7 @@ class FileDownloader(object): """Create directory components in filename. Similar to Unix "mkdir -p".""" components = filename.split(os.sep) aggregate = [os.sep.join(components[0:x]) for x in xrange(1, len(components))] + aggregate = ['%s%s' % (x, os.sep) for x in aggregate] # Finish names with separator for dir in aggregate: if not os.path.exists(dir): os.mkdir(dir) @@ -149,6 +151,16 @@ class FileDownloader(object): return int(new_min) return int(rate) + @staticmethod + def parse_bytes(bytestr): + """Parse a string indicating a byte quantity into a long integer.""" + matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr) + if matchobj is None: + return None + number = float(matchobj.group(1)) + multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower()) + return long(round(number * multiplier)) + def set_params(self, params): """Sets parameters.""" if type(params) != dict: @@ -167,12 +179,12 @@ class FileDownloader(object): def to_stdout(self, message, skip_eol=False): """Print message to stdout if not in quiet mode.""" if not self._params.get('quiet', False): - sys.stdout.write('%s%s' % (message, ['\n', ''][skip_eol])) + print u'%s%s' % (message, [u'\n', u''][skip_eol]), sys.stdout.flush() def to_stderr(self, message): """Print message to stderr.""" - sys.stderr.write('%s\n' % message) + print >>sys.stderr, message def fixed_template(self): """Checks if the output template is fixed.""" @@ -193,6 +205,32 @@ class FileDownloader(object): raise DownloadError(message) return 1 + def slow_down(self, start_time, byte_counter): + """Sleep if the download speed is over the rate limit.""" + rate_limit = self._params.get('ratelimit', None) + if rate_limit is None or byte_counter == 0: + return + now = time.time() + elapsed = now - start_time + if elapsed <= 0.0: + return + speed = float(byte_counter) / elapsed + if speed > rate_limit: + time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit) + + def report_destination(self, filename): + """Report destination filename.""" + self.to_stdout(u'[download] Destination: %s' % filename) + + def report_progress(self, percent_str, data_len_str, speed_str, eta_str): + """Report download progress.""" + self.to_stdout(u'\r[download] %s of %s at %s ETA %s' % + (percent_str, data_len_str, speed_str, eta_str), skip_eol=True) + + def report_finish(self): + """Report download finished.""" + self.to_stdout(u'') + def download(self, url_list): """Download a given list of URLs.""" retcode = 0 @@ -215,7 +253,6 @@ class FileDownloader(object): raise SameFileError(self._params['outtmpl']) for result in results: - # Forced printings if self._params.get('forcetitle', False): print result['title'] @@ -228,7 +265,7 @@ class FileDownloader(object): try: filename = self._params['outtmpl'] % result - self.to_stdout('[download] Destination: %s' % filename) + self.report_destination(filename) except (ValueError, KeyError), err: retcode = self.trouble('ERROR: invalid output template: %s' % str(err)) continue @@ -266,12 +303,13 @@ class FileDownloader(object): block_size = 1024 start = time.time() while True: + # Progress message percent_str = self.calc_percent(byte_counter, data_len) eta_str = self.calc_eta(start, time.time(), data_len, byte_counter) speed_str = self.calc_speed(start, time.time(), byte_counter) - self.to_stdout('\r[download] %s of %s at %s ETA %s' % - (percent_str, data_len_str, speed_str, eta_str), skip_eol=True) + self.report_progress(percent_str, data_len_str, speed_str, eta_str) + # Download and write before = time.time() data_block = data.read(block_size) after = time.time() @@ -282,7 +320,10 @@ class FileDownloader(object): stream.write(data_block) block_size = self.best_block_size(after - before, data_block_len) - self.to_stdout('') + # Apply rate limit + self.slow_down(start, byte_counter) + + self.report_finish() if data_len is not None and str(byte_counter) != data_len: raise ValueError('Content too short: %s/%s bytes' % (byte_counter, data_len)) @@ -321,7 +362,7 @@ class InfoExtractor(object): @staticmethod def suitable(url): """Receives a URL and returns True if suitable for this IE.""" - return True + return False def initialize(self): """Initializes an instance (authentication, etc).""" @@ -345,7 +386,7 @@ class InfoExtractor(object): def to_stderr(self, message): """Print message to stderr.""" - sys.stderr.write('%s\n' % message) + print >>sys.stderr, message def _real_initialize(self): """Real initialization process. Redefine in subclasses.""" @@ -358,10 +399,35 @@ class InfoExtractor(object): class YoutubeIE(InfoExtractor): """Information extractor for youtube.com.""" + _VALID_URL = r'^((?:http://)?(?:\w+\.)?youtube\.com/(?:(?:v/)|(?:(?:watch(?:\.php)?)?\?(?:.+&)?v=)))?([0-9A-Za-z_-]+)(?(1).+)?$' _LOGIN_URL = 'http://www.youtube.com/login?next=/' _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/' _NETRC_MACHINE = 'youtube' + @staticmethod + def suitable(url): + return (re.match(YoutubeIE._VALID_URL, url) is not None) + + def report_login(self): + """Report attempt to log in.""" + self.to_stdout(u'[youtube] Logging in') + + def report_age_confirmation(self): + """Report attempt to confirm age.""" + self.to_stdout(u'[youtube] Confirming age') + + def report_webpage_download(self, video_id): + """Report attempt to download webpage.""" + self.to_stdout(u'[youtube] %s: Downloading video webpage' % video_id) + + def report_information_extraction(self, video_id): + """Report attempt to extract video information.""" + self.to_stdout(u'[youtube] %s: Extracting video information' % video_id) + + def report_video_url(self, video_id, video_real_url): + """Report extracted video URL.""" + self.to_stdout(u'[youtube] %s: URL: %s' % (video_id, video_real_url)) + def _real_initialize(self): if self._downloader is None: return @@ -383,7 +449,7 @@ class YoutubeIE(InfoExtractor): else: raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE) except (IOError, netrc.NetrcParseError), err: - self.to_stderr('WARNING: parsing .netrc: %s' % str(err)) + self.to_stderr(u'WARNING: parsing .netrc: %s' % str(err)) return # No authentication to be performed @@ -400,13 +466,13 @@ class YoutubeIE(InfoExtractor): } request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form), std_headers) try: - self.to_stdout('[youtube] Logging in') + self.report_login() login_results = urllib2.urlopen(request).read() if re.search(r'(?i)