X-Git-Url: http://git.cielonegro.org/gitweb.cgi?a=blobdiff_plain;f=youtube-dl;h=a19571c5ba0a6023e3861d99c598525b020ecd20;hb=d853063955454d27721cade9f75db4d8945dd78f;hp=7eaafdcd5f2c6ea8d55949850716c71f47c87a3c;hpb=0c2dc87d9e299fb413d103f08df0d03fed55adb1;p=youtube-dl.git diff --git a/youtube-dl b/youtube-dl index 7eaafdcd5..a19571c5b 100755 --- a/youtube-dl +++ b/youtube-dl @@ -4,6 +4,7 @@ # License: Public domain code import htmlentitydefs import httplib +import locale import math import netrc import os @@ -42,6 +43,14 @@ class SameFileError(Exception): """ pass +class PostProcessingError(Exception): + """Post Processing exception. + + This exception may be raised by PostProcessor's .run() method to + indicate an error in the postprocessing task. + """ + pass + class FileDownloader(object): """File Downloader class. @@ -83,10 +92,12 @@ class FileDownloader(object): _params = None _ies = [] + _pps = [] def __init__(self, params): """Create a FileDownloader object with the given options.""" self._ies = [] + self._pps = [] self.set_params(params) @staticmethod @@ -176,15 +187,20 @@ class FileDownloader(object): self._ies.append(ie) ie.set_downloader(self) + def add_post_processor(self, pp): + """Add a PostProcessor object to the end of the chain.""" + self._pps.append(pp) + pp.set_downloader(self) + 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.""" @@ -220,16 +236,16 @@ class FileDownloader(object): def report_destination(self, filename): """Report destination filename.""" - self.to_stdout('[download] Destination: %s' % 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('\r[download] %s of %s at %s ETA %s' % + 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('') + self.to_stdout(u'') def download(self, url_list): """Download a given list of URLs.""" @@ -267,7 +283,7 @@ class FileDownloader(object): filename = self._params['outtmpl'] % result self.report_destination(filename) except (ValueError, KeyError), err: - retcode = self.trouble('ERROR: invalid output template: %s' % str(err)) + retcode = self.trouble('ERROR: invalid output template or system charset: %s' % str(err)) continue try: self.pmkdir(filename) @@ -288,11 +304,26 @@ class FileDownloader(object): except (urllib2.URLError, httplib.HTTPException, socket.error), err: retcode = self.trouble('ERROR: unable to download video data: %s' % str(err)) continue + try: + self.post_process(filename, result) + except (PostProcessingError), err: + retcode = self.trouble('ERROR: postprocessing: %s' % str(err)) + continue + break if not suitable_found: retcode = self.trouble('ERROR: no suitable InfoExtractor: %s' % url) return retcode + + def post_process(self, filename, ie_info): + """Run the postprocessing chain on the given file.""" + info = dict(ie_info) + info['filepath'] = filename + for pp in self._pps: + info = pp.run(info) + if info is None: + break def _do_download(self, stream, url): request = urllib2.Request(url, None, std_headers) @@ -386,7 +417,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.""" @@ -410,23 +441,23 @@ class YoutubeIE(InfoExtractor): def report_login(self): """Report attempt to log in.""" - self.to_stdout('[youtube] Logging in') + self.to_stdout(u'[youtube] Logging in') def report_age_confirmation(self): """Report attempt to confirm age.""" - self.to_stdout('[youtube] Confirming age') + self.to_stdout(u'[youtube] Confirming age') def report_webpage_download(self, video_id): """Report attempt to download webpage.""" - self.to_stdout('[youtube] %s: Downloading video webpage' % video_id) + 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('[youtube] %s: Extracting video information' % video_id) + 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('[youtube] %s: URL: %s' % (video_id, video_real_url)) + self.to_stdout(u'[youtube] %s: URL: %s' % (video_id, video_real_url)) def _real_initialize(self): if self._downloader is None: @@ -449,7 +480,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 @@ -469,10 +500,10 @@ class YoutubeIE(InfoExtractor): self.report_login() login_results = urllib2.urlopen(request).read() if re.search(r'(?i)]* name="loginForm"', login_results) is not None: - self.to_stderr('WARNING: unable to log in: bad username or password') + self.to_stderr(u'WARNING: unable to log in: bad username or password') return except (urllib2.URLError, httplib.HTTPException, socket.error), err: - self.to_stderr('WARNING: unable to log in: %s' % str(err)) + self.to_stderr(u'WARNING: unable to log in: %s' % str(err)) return # Confirm age @@ -485,14 +516,14 @@ class YoutubeIE(InfoExtractor): self.report_age_confirmation() age_results = urllib2.urlopen(request).read() except (urllib2.URLError, httplib.HTTPException, socket.error), err: - self.to_stderr('ERROR: unable to confirm age: %s' % str(err)) + self.to_stderr(u'ERROR: unable to confirm age: %s' % str(err)) return def _real_extract(self, url): # Extract video id from URL mobj = re.match(self._VALID_URL, url) if mobj is None: - self.to_stderr('ERROR: invalid URL: %s' % url) + self.to_stderr(u'ERROR: invalid URL: %s' % url) return [None] video_id = mobj.group(2) @@ -514,14 +545,14 @@ class YoutubeIE(InfoExtractor): self.report_webpage_download(video_id) video_webpage = urllib2.urlopen(request).read() except (urllib2.URLError, httplib.HTTPException, socket.error), err: - self.to_stderr('ERROR: unable to download video webpage: %s' % str(err)) + self.to_stderr(u'ERROR: unable to download video webpage: %s' % str(err)) return [None] self.report_information_extraction(video_id) # "t" param mobj = re.search(r', "t": "([^"]+)"', video_webpage) if mobj is None: - self.to_stderr('ERROR: unable to extract "t" parameter') + self.to_stderr(u'ERROR: unable to extract "t" parameter') return [None] video_real_url = 'http://www.youtube.com/get_video?video_id=%s&t=%s' % (video_id, mobj.group(1)) if format_param is not None: @@ -529,16 +560,16 @@ class YoutubeIE(InfoExtractor): self.report_video_url(video_id, video_real_url) # uploader - mobj = re.search(r'More From: ([^<]*)<', video_webpage) + mobj = re.search(r"var watchUsername = '([^']+)';", video_webpage) if mobj is None: - self.to_stderr('ERROR: unable to extract uploader nickname') + self.to_stderr(u'ERROR: unable to extract uploader nickname') return [None] video_uploader = mobj.group(1) # title mobj = re.search(r'(?im)YouTube - ([^<]*)', video_webpage) if mobj is None: - self.to_stderr('ERROR: unable to extract video title') + self.to_stderr(u'ERROR: unable to extract video title') return [None] video_title = mobj.group(1).decode('utf-8') video_title = re.sub(ur'(?u)&(.+?);', lambda x: unichr(htmlentitydefs.name2codepoint[x.group(1)]), video_title) @@ -550,19 +581,19 @@ class YoutubeIE(InfoExtractor): # Return information return [{ - 'id': video_id, - 'url': video_real_url, - 'uploader': video_uploader, + 'id': video_id.decode('utf-8'), + 'url': video_real_url.decode('utf-8'), + 'uploader': video_uploader.decode('utf-8'), 'title': video_title, 'stitle': simple_title, - 'ext': video_extension, + 'ext': video_extension.decode('utf-8'), }] class MetacafeIE(InfoExtractor): """Information Extractor for metacafe.com.""" _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*' - _DISCLAIMER = 'http://www.metacafe.com/disclaimer' + _DISCLAIMER = 'http://www.metacafe.com/family_filter/' _youtube_ie = None def __init__(self, youtube_ie, downloader=None): @@ -575,19 +606,19 @@ class MetacafeIE(InfoExtractor): def report_disclaimer(self): """Report disclaimer retrieval.""" - self.to_stdout('[metacafe] Retrieving disclaimer') + self.to_stdout(u'[metacafe] Retrieving disclaimer') def report_age_confirmation(self): """Report attempt to confirm age.""" - self.to_stdout('[metacafe] Confirming age') + self.to_stdout(u'[metacafe] Confirming age') def report_download_webpage(self, video_id): """Report webpage download.""" - self.to_stdout('[metacafe] %s: Downloading webpage' % video_id) + self.to_stdout(u'[metacafe] %s: Downloading webpage' % video_id) def report_extraction(self, video_id): """Report information extraction.""" - self.to_stdout('[metacafe] %s: Extracting information' % video_id) + self.to_stdout(u'[metacafe] %s: Extracting information' % video_id) def _real_initialize(self): # Retrieve disclaimer @@ -596,27 +627,27 @@ class MetacafeIE(InfoExtractor): self.report_disclaimer() disclaimer = urllib2.urlopen(request).read() except (urllib2.URLError, httplib.HTTPException, socket.error), err: - self.to_stderr('ERROR: unable to retrieve disclaimer: %s' % str(err)) + self.to_stderr(u'ERROR: unable to retrieve disclaimer: %s' % str(err)) return # Confirm age disclaimer_form = { - 'allowAdultContent': '1', + 'filters': '0', 'submit': "Continue - I'm over 18", } - request = urllib2.Request('http://www.metacafe.com/watch/', urllib.urlencode(disclaimer_form), std_headers) + request = urllib2.Request('http://www.metacafe.com/', urllib.urlencode(disclaimer_form), std_headers) try: self.report_age_confirmation() disclaimer = urllib2.urlopen(request).read() except (urllib2.URLError, httplib.HTTPException, socket.error), err: - self.to_stderr('ERROR: unable to confirm age: %s' % str(err)) + self.to_stderr(u'ERROR: unable to confirm age: %s' % str(err)) return def _real_extract(self, url): # Extract id and simplified title from URL mobj = re.match(self._VALID_URL, url) if mobj is None: - self.to_stderr('ERROR: invalid URL: %s' % url) + self.to_stderr(u'ERROR: invalid URL: %s' % url) return [None] video_id = mobj.group(1) @@ -635,45 +666,45 @@ class MetacafeIE(InfoExtractor): self.report_download_webpage(video_id) webpage = urllib2.urlopen(request).read() except (urllib2.URLError, httplib.HTTPException, socket.error), err: - self.to_stderr('ERROR: unable retrieve video webpage: %s' % str(err)) + self.to_stderr(u'ERROR: unable retrieve video webpage: %s' % str(err)) return [None] # Extract URL, uploader and title from webpage self.report_extraction(video_id) mobj = re.search(r'(?m)"mediaURL":"(http.*?\.flv)"', webpage) if mobj is None: - self.to_stderr('ERROR: unable to extract media URL') + self.to_stderr(u'ERROR: unable to extract media URL') return [None] mediaURL = mobj.group(1).replace('\\', '') mobj = re.search(r'(?m)"gdaKey":"(.*?)"', webpage) if mobj is None: - self.to_stderr('ERROR: unable to extract gdaKey') + self.to_stderr(u'ERROR: unable to extract gdaKey') return [None] gdaKey = mobj.group(1) video_url = '%s?__gda__=%s' % (mediaURL, gdaKey) - mobj = re.search(r'(?im)(.*) - Video', webpage) if mobj is None: - self.to_stderr('ERROR: unable to extract title') + self.to_stderr(u'ERROR: unable to extract title') return [None] video_title = mobj.group(1).decode('utf-8') mobj = re.search(r'(?m)
  • .*?Submitter:
    (.*?)
  • ', webpage) if mobj is None: - self.to_stderr('ERROR: unable to extract uploader nickname') + self.to_stderr(u'ERROR: unable to extract uploader nickname') return [None] video_uploader = re.sub(r'<.*?>', '', mobj.group(1)) # Return information return [{ - 'id': video_id, - 'url': video_url, - 'uploader': video_uploader, + 'id': video_id.decode('utf-8'), + 'url': video_url.decode('utf-8'), + 'uploader': video_uploader.decode('utf-8'), 'title': video_title, 'stitle': simple_title, - 'ext': video_extension, + 'ext': video_extension.decode('utf-8'), }] class YoutubePlaylistIE(InfoExtractor): @@ -682,7 +713,7 @@ class YoutubePlaylistIE(InfoExtractor): _VALID_URL = r'(?:http://)?(?:\w+\.)?youtube.com/view_play_list\?p=(.+)' _TEMPLATE_URL = 'http://www.youtube.com/view_play_list?p=%s&page=%s' _VIDEO_INDICATOR = r'/watch\?v=(.+?)&' - _MORE_PAGES_INDICATOR = r'class="pagerNotCurrent">Next' + _MORE_PAGES_INDICATOR = r'/view_play_list?p=%s&page=%s' _youtube_ie = None def __init__(self, youtube_ie, downloader=None): @@ -695,7 +726,7 @@ class YoutubePlaylistIE(InfoExtractor): def report_download_page(self, playlist_id, pagenum): """Report attempt to download playlist page with given number.""" - self.to_stdout('[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum)) + self.to_stdout(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum)) def _real_initialize(self): self._youtube_ie.initialize() @@ -704,7 +735,7 @@ class YoutubePlaylistIE(InfoExtractor): # Extract playlist id mobj = re.match(self._VALID_URL, url) if mobj is None: - self.to_stderr('ERROR: invalid url: %s' % url) + self.to_stderr(u'ERROR: invalid url: %s' % url) return [None] # Download playlist pages @@ -718,7 +749,7 @@ class YoutubePlaylistIE(InfoExtractor): try: page = urllib2.urlopen(request).read() except (urllib2.URLError, httplib.HTTPException, socket.error), err: - self.to_stderr('ERROR: unable to download webpage: %s' % str(err)) + self.to_stderr(u'ERROR: unable to download webpage: %s' % str(err)) return [None] # Extract video identifiers @@ -727,7 +758,7 @@ class YoutubePlaylistIE(InfoExtractor): ids_in_page.add(mobj.group(1)) video_ids.extend(list(ids_in_page)) - if self._MORE_PAGES_INDICATOR not in page: + if (self._MORE_PAGES_INDICATOR % (playlist_id, pagenum + 1)) not in page: break pagenum = pagenum + 1 @@ -736,6 +767,62 @@ class YoutubePlaylistIE(InfoExtractor): information.extend(self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)) return information +class PostProcessor(object): + """Post Processor class. + + PostProcessor objects can be added to downloaders with their + add_post_processor() method. When the downloader has finished a + successful download, it will take its internal chain of PostProcessors + and start calling the run() method on each one of them, first with + an initial argument and then with the returned value of the previous + PostProcessor. + + The chain will be stopped if one of them ever returns None or the end + of the chain is reached. + + PostProcessor objects follow a "mutual registration" process similar + to InfoExtractor objects. + """ + + _downloader = None + + def __init__(self, downloader=None): + self._downloader = downloader + + def to_stdout(self, message): + """Print message to stdout if downloader is not in quiet mode.""" + if self._downloader is None or not self._downloader.get_params().get('quiet', False): + print message + + def to_stderr(self, message): + """Print message to stderr.""" + print >>sys.stderr, message + + def set_downloader(self, downloader): + """Sets the downloader for this PP.""" + self._downloader = downloader + + def run(self, information): + """Run the PostProcessor. + + The "information" argument is a dictionary like the ones + returned by InfoExtractors. The only difference is that this + one has an extra field called "filepath" that points to the + downloaded file. + + When this method returns None, the postprocessing chain is + stopped. However, this method may return an information + dictionary that will be passed to the next postprocessing + object in the chain. It can be the one it received after + changing some fields. + + In addition, this method may raise a PostProcessingError + exception that will be taken into account by the downloader + it was called from. + """ + return information # by default, do nothing + +### MAIN PROGRAM ### if __name__ == '__main__': try: # Modules needed only when running the main program @@ -750,7 +837,7 @@ if __name__ == '__main__': # Parse command line parser = optparse.OptionParser( usage='Usage: %prog [options] url...', - version='2008.07.22', + version='2008.09.20', conflict_handler='resolve', ) parser.add_option('-h', '--help', @@ -791,21 +878,21 @@ if __name__ == '__main__': # Conflicting, missing and erroneous options if len(args) < 1: - sys.exit('ERROR: you must provide at least one URL') + sys.exit(u'ERROR: you must provide at least one URL') if opts.usenetrc and (opts.username is not None or opts.password is not None): - sys.exit('ERROR: using .netrc conflicts with giving username/password') + sys.exit(u'ERROR: using .netrc conflicts with giving username/password') if opts.password is not None and opts.username is None: - sys.exit('ERROR: account username missing') + sys.exit(u'ERROR: account username missing') if opts.outtmpl is not None and (opts.useliteral or opts.usetitle): - sys.exit('ERROR: using output template conflicts with using title or literal title') + sys.exit(u'ERROR: using output template conflicts with using title or literal title') if opts.usetitle and opts.useliteral: - sys.exit('ERROR: using title conflicts with using literal title') + sys.exit(u'ERROR: using title conflicts with using literal title') if opts.username is not None and opts.password is None: - opts.password = getpass.getpass('Type account password and press return:') + opts.password = getpass.getpass(u'Type account password and press return:') if opts.ratelimit is not None: numeric_limit = FileDownloader.parse_bytes(opts.ratelimit) if numeric_limit is None: - sys.exit('ERROR: invalid rate limit specified') + sys.exit(u'ERROR: invalid rate limit specified') opts.ratelimit = numeric_limit # Information extractors @@ -823,10 +910,10 @@ if __name__ == '__main__': 'forcetitle': opts.gettitle, 'simulate': (opts.simulate or opts.geturl or opts.gettitle), 'format': opts.format, - 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl) - or (opts.usetitle and '%(stitle)s-%(id)s.%(ext)s') - or (opts.useliteral and '%(title)s-%(id)s.%(ext)s') - or '%(id)s.%(ext)s'), + 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(locale.getdefaultlocale()[1])) + or (opts.usetitle and u'%(stitle)s-%(id)s.%(ext)s') + or (opts.useliteral and u'%(title)s-%(id)s.%(ext)s') + or u'%(id)s.%(ext)s'), 'ignoreerrors': opts.ignoreerrors, 'ratelimit': opts.ratelimit, }) @@ -839,6 +926,6 @@ if __name__ == '__main__': except DownloadError: sys.exit(1) except SameFileError: - sys.exit('ERROR: fixed output name but more than one file to download') + sys.exit(u'ERROR: fixed output name but more than one file to download') except KeyboardInterrupt: - sys.exit('\nERROR: Interrupted by user') + sys.exit(u'\nERROR: Interrupted by user')