X-Git-Url: https://git.rapsys.eu/youtubedl/blobdiff_plain/0a3f3e67f98ab8168fc7b80abf00ba5f04302532..b4c12b5580c7412a055e109387d704425557755b:/youtube-dl?ds=inline
diff --git a/youtube-dl b/youtube-dl
index 5afff4e..5fd331e 100755
--- a/youtube-dl
+++ b/youtube-dl
@@ -2,6 +2,7 @@
# -*- coding: utf-8 -*-
# Author: Ricardo Garcia Gonzalez
# Author: Danny Colligan
+# Author: Benjamin Johnson
# License: Public domain code
import htmlentitydefs
import httplib
@@ -13,15 +14,22 @@ import os.path
import re
import socket
import string
+import subprocess
import sys
import time
import urllib
import urllib2
+# parse_qs was moved from the cgi module to the urlparse module recently.
+try:
+ from urlparse import parse_qs
+except ImportError:
+ from cgi import parse_qs
+
std_headers = {
- 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2',
+ 'User-Agent': 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.7) Gecko/20100720 Firefox/3.6.7',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
- 'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-us,en;q=0.5',
}
@@ -33,15 +41,70 @@ def preferredencoding():
Returns the best encoding scheme for the system, based on
locale.getpreferredencoding() and some further tweaks.
"""
+ def yield_preferredencoding():
+ try:
+ pref = locale.getpreferredencoding()
+ u'TEST'.encode(pref)
+ except:
+ pref = 'UTF-8'
+ while True:
+ yield pref
+ return yield_preferredencoding().next()
+
+def htmlentity_transform(matchobj):
+ """Transforms an HTML entity to a Unicode character.
+
+ This function receives a match object and is intended to be used with
+ the re.sub() function.
+ """
+ entity = matchobj.group(1)
+
+ # Known non-numeric HTML entity
+ if entity in htmlentitydefs.name2codepoint:
+ return unichr(htmlentitydefs.name2codepoint[entity])
+
+ # Unicode character
+ mobj = re.match(ur'(?u)#(x?\d+)', entity)
+ if mobj is not None:
+ numstr = mobj.group(1)
+ if numstr.startswith(u'x'):
+ base = 16
+ numstr = u'0%s' % numstr
+ else:
+ base = 10
+ return unichr(long(numstr, base))
+
+ # Unknown entity in name, return its literal representation
+ return (u'&%s;' % entity)
+
+def sanitize_title(utitle):
+ """Sanitizes a video title so it could be used as part of a filename."""
+ utitle = re.sub(ur'(?u)&(.+?);', htmlentity_transform, utitle)
+ return utitle.replace(unicode(os.sep), u'%')
+
+def sanitize_open(filename, open_mode):
+ """Try to open the given filename, and slightly tweak it if this fails.
+
+ Attempts to open the given filename. If this fails, it tries to change
+ the filename slightly, step by step, until it's either able to open it
+ or it fails and raises a final exception, like the standard open()
+ function.
+
+ It returns the tuple (stream, definitive_file_name).
+ """
try:
- pref = locale.getpreferredencoding()
- # Mac OSX systems have this problem sometimes
- if pref == '':
- return 'UTF-8'
- return pref
- except:
- sys.stderr.write('WARNING: problem obtaining preferred encoding. Falling back to UTF-8.\n')
- return 'UTF-8'
+ if filename == u'-':
+ return (sys.stdout, filename)
+ stream = open(filename, open_mode)
+ return (stream, filename)
+ except (IOError, OSError), err:
+ # In case of error, try to remove win32 forbidden chars
+ filename = re.sub(ur'[/<>:"\|\?\*]', u'#', filename)
+
+ # An exception here should be caught in the caller
+ stream = open(filename, open_mode)
+ return (stream, filename)
+
class DownloadError(Exception):
"""Download Error exception.
@@ -68,7 +131,7 @@ class PostProcessingError(Exception):
"""
pass
-class UnavailableFormatError(Exception):
+class UnavailableVideoError(Exception):
"""Unavailable Format exception.
This exception will be thrown when a video is requested
@@ -126,23 +189,28 @@ class FileDownloader(object):
forcetitle: Force printing title.
simulate: Do not download the video files.
format: Video format code.
+ format_limit: Highest quality format to try.
outtmpl: Template for output names.
ignoreerrors: Do not stop on download errors.
ratelimit: Download speed limit, in bytes/sec.
nooverwrites: Prevent overwriting files.
+ retries: Number of times to retry for HTTP error 503
continuedl: Try to continue downloads if possible.
+ noprogress: Do not print the progress bar.
"""
params = None
_ies = []
_pps = []
_download_retcode = None
+ _num_downloads = None
def __init__(self, params):
"""Create a FileDownloader object with the given options."""
self._ies = []
self._pps = []
self._download_retcode = 0
+ self._num_downloads = 0
self.params = params
@staticmethod
@@ -239,11 +307,15 @@ class FileDownloader(object):
self._pps.append(pp)
pp.set_downloader(self)
- def to_stdout(self, message, skip_eol=False):
+ def to_stdout(self, message, skip_eol=False, ignore_encoding_errors=False):
"""Print message to stdout if not in quiet mode."""
- if not self.params.get('quiet', False):
- print (u'%s%s' % (message, [u'\n', u''][skip_eol])).encode(preferredencoding()),
+ try:
+ if not self.params.get('quiet', False):
+ print (u'%s%s' % (message, [u'\n', u''][skip_eol])).encode(preferredencoding()),
sys.stdout.flush()
+ except (UnicodeEncodeError), err:
+ if not ignore_encoding_errors:
+ raise
def to_stderr(self, message):
"""Print message to stderr."""
@@ -281,10 +353,12 @@ class FileDownloader(object):
def report_destination(self, filename):
"""Report destination filename."""
- self.to_stdout(u'[download] Destination: %s' % filename)
+ self.to_stdout(u'[download] Destination: %s' % filename, ignore_encoding_errors=True)
def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
"""Report download progress."""
+ if self.params.get('noprogress', False):
+ return
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)
@@ -292,9 +366,16 @@ class FileDownloader(object):
"""Report attemtp to resume at given byte."""
self.to_stdout(u'[download] Resuming download at byte %s' % resume_len)
+ def report_retry(self, count, retries):
+ """Report retry in case of HTTP error 503"""
+ self.to_stdout(u'[download] Got HTTP error 503. Retrying (attempt %d of %d)...' % (count, retries))
+
def report_file_already_downloaded(self, file_name):
"""Report file has already been fully downloaded."""
- self.to_stdout(u'[download] %s has already been downloaded' % file_name)
+ try:
+ self.to_stdout(u'[download] %s has already been downloaded' % file_name)
+ except (UnicodeEncodeError), err:
+ self.to_stdout(u'[download] The file has already been downloaded')
def report_unable_to_resume(self):
"""Report it was impossible to resume download."""
@@ -302,32 +383,46 @@ class FileDownloader(object):
def report_finish(self):
"""Report download finished."""
- self.to_stdout(u'')
+ if self.params.get('noprogress', False):
+ self.to_stdout(u'[download] Download completed')
+ else:
+ self.to_stdout(u'')
+
+ def increment_downloads(self):
+ """Increment the ordinal that assigns a number to each file."""
+ self._num_downloads += 1
def process_info(self, info_dict):
"""Process a single dictionary returned by an InfoExtractor."""
# Do nothing else if in simulate mode
if self.params.get('simulate', False):
- try:
- info_dict['url'] = self.verify_url(info_dict['url'])
- except (OSError, IOError, urllib2.URLError, httplib.HTTPException, socket.error), err:
- raise UnavailableFormatError
+ # Verify URL if it's an HTTP one
+ if info_dict['url'].startswith('http'):
+ try:
+ self.verify_url(info_dict['url'].encode('utf-8')).decode('utf-8')
+ except (OSError, IOError, urllib2.URLError, httplib.HTTPException, socket.error), err:
+ raise UnavailableVideoError
# Forced printings
if self.params.get('forcetitle', False):
- print info_dict['title'].encode(preferredencoding())
+ print info_dict['title'].encode(preferredencoding(), 'xmlcharrefreplace')
if self.params.get('forceurl', False):
- print info_dict['url'].encode(preferredencoding())
+ print info_dict['url'].encode(preferredencoding(), 'xmlcharrefreplace')
+ if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
+ print info_dict['thumbnail'].encode(preferredencoding(), 'xmlcharrefreplace')
+ if self.params.get('forcedescription', False) and 'description' in info_dict:
+ print info_dict['description'].encode(preferredencoding(), 'xmlcharrefreplace')
return
try:
template_dict = dict(info_dict)
template_dict['epoch'] = unicode(long(time.time()))
+ template_dict['ord'] = unicode('%05d' % self._num_downloads)
filename = self.params['outtmpl'] % template_dict
except (ValueError, KeyError), err:
self.trouble('ERROR: invalid output template or system charset: %s' % str(err))
- if self.params['nooverwrites'] and os.path.exists(filename):
+ if self.params.get('nooverwrites', False) and os.path.exists(filename):
self.to_stderr(u'WARNING: file exists: %s; skipping' % filename)
return
@@ -338,9 +433,9 @@ class FileDownloader(object):
return
try:
- success = self._do_download(filename, info_dict['url'])
+ success = self._do_download(filename, info_dict['url'].encode('utf-8'), info_dict.get('player_url', None))
except (OSError, IOError), err:
- raise UnavailableFormatError
+ raise UnavailableVideoError
except (urllib2.URLError, httplib.HTTPException, socket.error), err:
self.trouble('ERROR: unable to download video data: %s' % str(err))
return
@@ -390,36 +485,86 @@ class FileDownloader(object):
if info is None:
break
- def _do_download(self, filename, url):
- stream = None
- open_mode = 'ab'
+ def _download_with_rtmpdump(self, filename, url, player_url):
+ self.report_destination(filename)
+
+ # Check for rtmpdump first
+ try:
+ subprocess.call(['rtmpdump', '-h'], stdout=(file(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
+ except (OSError, IOError):
+ self.trouble(u'ERROR: RTMP download detected but "rtmpdump" could not be run')
+ return False
+
+ # Download using rtmpdump. rtmpdump returns exit code 2 when
+ # the connection was interrumpted and resuming appears to be
+ # possible. This is part of rtmpdump's normal usage, AFAIK.
+ basic_args = ['rtmpdump', '-q'] + [[], ['-W', player_url]][player_url is not None] + ['-r', url, '-o', filename]
+ retval = subprocess.call(basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)])
+ while retval == 2 or retval == 1:
+ prevsize = os.path.getsize(filename)
+ self.to_stdout(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
+ time.sleep(5.0) # This seems to be needed
+ retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
+ cursize = os.path.getsize(filename)
+ if prevsize == cursize and retval == 1:
+ break
+ if retval == 0:
+ self.to_stdout(u'\r[rtmpdump] %s bytes' % os.path.getsize(filename))
+ return True
+ else:
+ self.trouble('\nERROR: rtmpdump exited with code %d' % retval)
+ return False
+
+ def _do_download(self, filename, url, player_url):
+ # Attempt to download using rtmpdump
+ if url.startswith('rtmp'):
+ return self._download_with_rtmpdump(filename, url, player_url)
+ stream = None
+ open_mode = 'wb'
basic_request = urllib2.Request(url, None, std_headers)
request = urllib2.Request(url, None, std_headers)
- # Attempt to resume download with "continuedl" option
+ # Establish possible resume length
if os.path.isfile(filename):
resume_len = os.path.getsize(filename)
else:
resume_len = 0
- if self.params['continuedl'] and resume_len != 0:
+
+ # Request parameters in case of being able to resume
+ if self.params.get('continuedl', False) and resume_len != 0:
self.report_resuming_byte(resume_len)
request.add_header('Range','bytes=%d-' % resume_len)
+ open_mode = 'ab'
- # Establish connection
- try:
- data = urllib2.urlopen(request)
- except (urllib2.HTTPError, ), err:
- if err.code != 416: # 416 is 'Requested range not satisfiable'
- raise
- data = urllib2.urlopen(basic_request)
- content_length = data.info()['Content-Length']
- if content_length is not None and long(content_length) == resume_len:
- self.report_file_already_downloaded(filename)
- return True
- else:
- self.report_unable_to_resume()
- open_mode = 'wb'
+ count = 0
+ retries = self.params.get('retries', 0)
+ while True:
+ # Establish connection
+ try:
+ data = urllib2.urlopen(request)
+ break
+ except (urllib2.HTTPError, ), err:
+ if err.code == 503:
+ # Retry in case of HTTP error 503
+ count += 1
+ if count <= retries:
+ self.report_retry(count, retries)
+ continue
+ if err.code != 416: # 416 is 'Requested range not satisfiable'
+ raise
+ # Unable to resume
+ data = urllib2.urlopen(basic_request)
+ content_length = data.info()['Content-Length']
+
+ if content_length is not None and long(content_length) == resume_len:
+ # Because the file had already been fully downloaded
+ self.report_file_already_downloaded(filename)
+ return True
+ else:
+ # Because the server didn't let us
+ self.report_unable_to_resume()
+ open_mode = 'wb'
data_len = data.info().get('Content-length', None)
data_len_str = self.format_bytes(data_len)
@@ -439,12 +584,15 @@ class FileDownloader(object):
# Open file just in time
if stream is None:
try:
- stream = open(filename, open_mode)
+ (stream, filename) = sanitize_open(filename, open_mode)
self.report_destination(filename)
except (OSError, IOError), err:
self.trouble('ERROR: unable to open for writing: %s' % str(err))
return False
- stream.write(data_block)
+ try:
+ stream.write(data_block)
+ except (IOError, OSError), err:
+ self.trouble('\nERROR: unable to write data: %s' % str(err))
block_size = self.best_block_size(after - before, data_block_len)
# Progress message
@@ -479,6 +627,16 @@ class InfoExtractor(object):
title: Literal title.
stitle: Simplified title.
ext: Video filename extension.
+ format: Video format.
+ player_url: SWF Player URL (may be None).
+
+ The following fields are optional. Their primary purpose is to allow
+ youtube-dl to serve as the backend for a video search function, such
+ as the one in youtube2mp3. They are only used when their respective
+ forced printing functions are called:
+
+ thumbnail: Full URL to a video thumbnail image.
+ description: One-line video description.
Subclasses of this one should re-define the _real_initialize() and
_real_extract() methods, as well as the suitable() static method.
@@ -525,46 +683,28 @@ 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).+)?$'
- _LANG_URL = r'http://uk.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
+ _VALID_URL = r'^((?:http://)?(?:youtu\.be/|(?:\w+\.)?youtube\.com/(?:(?:v/)|(?:(?:watch(?:_popup)?(?:\.php)?)?[\?#](?:.+&)?v=))))?([0-9A-Za-z_-]+)(?(1).+)?$'
+ _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
_LOGIN_URL = 'http://www.youtube.com/signup?next=/&gl=US&hl=en'
_AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
_NETRC_MACHINE = 'youtube'
- _available_formats = ['22', '35', '18', '5', '17', '13', None] # listed in order of priority for -b flag
+ # Listed in order of quality
+ _available_formats = ['38', '37', '22', '45', '35', '34', '43', '18', '6', '5', '17', '13']
_video_extensions = {
'13': '3gp',
'17': 'mp4',
'18': 'mp4',
'22': 'mp4',
+ '37': 'mp4',
+ '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
+ '43': 'webm',
+ '45': 'webm',
}
@staticmethod
def suitable(url):
return (re.match(YoutubeIE._VALID_URL, url) is not None)
- @staticmethod
- def htmlentity_transform(matchobj):
- """Transforms an HTML entity to a Unicode character."""
- entity = matchobj.group(1)
-
- # Known non-numeric HTML entity
- if entity in htmlentitydefs.name2codepoint:
- return unichr(htmlentitydefs.name2codepoint[entity])
-
- # Unicode character
- mobj = re.match(ur'(?u)#(x?\d+)', entity)
- if mobj is not None:
- numstr = mobj.group(1)
- if numstr.startswith(u'x'):
- base = 16
- numstr = u'0%s' % numstr
- else:
- base = 10
- return unichr(long(numstr, base))
-
- # Unknown entity in name, return its literal representation
- return (u'&%s;' % entity)
-
def report_lang(self):
"""Report attempt to set language."""
self._downloader.to_stdout(u'[youtube] Setting language')
@@ -577,6 +717,10 @@ class YoutubeIE(InfoExtractor):
"""Report attempt to confirm age."""
self._downloader.to_stdout(u'[youtube] Confirming age')
+ def report_video_webpage_download(self, video_id):
+ """Report attempt to download video webpage."""
+ self._downloader.to_stdout(u'[youtube] %s: Downloading video webpage' % video_id)
+
def report_video_info_webpage_download(self, video_id):
"""Report attempt to download video info webpage."""
self._downloader.to_stdout(u'[youtube] %s: Downloading video info webpage' % video_id)
@@ -589,6 +733,10 @@ class YoutubeIE(InfoExtractor):
"""Report extracted video URL."""
self._downloader.to_stdout(u'[youtube] %s: Format %s not available' % (video_id, format))
+ def report_rtmp_download(self):
+ """Indicate the download will use the RTMP protocol."""
+ self._downloader.to_stdout(u'[youtube] RTMP download detected')
+
def _real_initialize(self):
if self._downloader is None:
return
@@ -666,72 +814,107 @@ class YoutubeIE(InfoExtractor):
return
video_id = mobj.group(2)
- # Downloader parameters
- best_quality = False
- format_param = None
- quality_index = 0
- if self._downloader is not None:
- params = self._downloader.params
- format_param = params.get('format', None)
- if format_param == '0':
- format_param = self._available_formats[quality_index]
- best_quality = True
+ # Get video webpage
+ self.report_video_webpage_download(video_id)
+ request = urllib2.Request('http://www.youtube.com/watch?v=%s&gl=US&hl=en' % video_id, None, std_headers)
+ try:
+ video_webpage = urllib2.urlopen(request).read()
+ except (urllib2.URLError, httplib.HTTPException, socket.error), err:
+ self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
+ return
- while True:
- # Extension
- video_extension = self._video_extensions.get(format_param, 'flv')
+ # Attempt to extract SWF player URL
+ mobj = re.search(r'swfConfig.*"(http://.*?watch.*?-.*?\.swf)"', video_webpage)
+ if mobj is not None:
+ player_url = mobj.group(1)
+ else:
+ player_url = None
- # Get video info
- video_info_url = 'http://www.youtube.com/get_video_info?&video_id=%s&el=detailpage&ps=default&eurl=&gl=US&hl=en' % video_id
+ # Get video info
+ self.report_video_info_webpage_download(video_id)
+ for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
+ video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
+ % (video_id, el_type))
request = urllib2.Request(video_info_url, None, std_headers)
try:
- self.report_video_info_webpage_download(video_id)
video_info_webpage = urllib2.urlopen(request).read()
+ video_info = parse_qs(video_info_webpage)
+ if 'token' in video_info:
+ break
except (urllib2.URLError, httplib.HTTPException, socket.error), err:
self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
return
- self.report_information_extraction(video_id)
+ self.report_information_extraction(video_id)
- # "t" param
- mobj = re.search(r'(?m)&token=([^&]+)(?:&|$)', video_info_webpage)
- if mobj is None:
- # Attempt to see if YouTube has issued an error message
- mobj = re.search(r'(?m)&reason=([^&]+)(?:&|$)', video_info_webpage)
- if mobj is None:
- self._downloader.trouble(u'ERROR: unable to extract "t" parameter for unknown reason')
- stream = open('reportme-ydl-%s.dat' % time.time(), 'wb')
- stream.write(video_info_webpage)
- stream.close()
- else:
- reason = urllib.unquote_plus(mobj.group(1))
- self._downloader.trouble(u'ERROR: YouTube said: %s' % reason.decode('utf-8'))
- return
- token = urllib.unquote(mobj.group(1))
- video_real_url = 'http://www.youtube.com/get_video?video_id=%s&t=%s&eurl=&el=detailpage&ps=default&gl=US&hl=en' % (video_id, token)
- if format_param is not None:
- video_real_url = '%s&fmt=%s' % (video_real_url, format_param)
+ # uploader
+ if 'author' not in video_info:
+ self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
+ return
+ video_uploader = urllib.unquote_plus(video_info['author'][0])
- # uploader
- mobj = re.search(r'(?m)&author=([^&]+)(?:&|$)', video_info_webpage)
- if mobj is None:
- self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
+ # title
+ if 'title' not in video_info:
+ self._downloader.trouble(u'ERROR: unable to extract video title')
+ return
+ video_title = urllib.unquote_plus(video_info['title'][0])
+ video_title = video_title.decode('utf-8')
+ video_title = sanitize_title(video_title)
+
+ # simplified title
+ simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
+ simple_title = simple_title.strip(ur'_')
+
+ # thumbnail image
+ if 'thumbnail_url' not in video_info:
+ self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
+ video_thumbnail = ''
+ else: # don't panic if we can't find it
+ video_thumbnail = urllib.unquote_plus(video_info['thumbnail_url'][0])
+
+ # description
+ video_description = 'No description available.'
+ if self._downloader.params.get('forcedescription', False):
+ mobj = re.search(r'', video_webpage)
+ if mobj is not None:
+ video_description = mobj.group(1)
+
+ # Decide which formats to download
+ if 'fmt_url_map' in video_info:
+ url_map = dict(tuple(pair.split('|')) for pair in video_info['fmt_url_map'][0].split(','))
+ format_limit = self._downloader.params.get('format_limit', None)
+ if format_limit is not None and format_limit in self._available_formats:
+ format_list = self._available_formats[self._available_formats.index(format_limit):]
+ else:
+ format_list = self._available_formats
+ existing_formats = [x for x in format_list if x in url_map]
+ if len(existing_formats) == 0:
+ self._downloader.trouble(u'ERROR: no known formats available for video')
return
- video_uploader = urllib.unquote(mobj.group(1))
+ requested_format = self._downloader.params.get('format', None)
+ if requested_format is None:
+ video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
+ elif requested_format == '-1':
+ video_url_list = url_map.items() # All formats
+ else:
+ if requested_format not in existing_formats:
+ self._downloader.trouble(u'ERROR: format not available for video')
+ return
+ video_url_list = [(requested_format, url_map[requested_format])] # Specific format
+ elif 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
+ self.report_rtmp_download()
+ video_url_list = [(None, video_info['conn'][0])]
+ else:
+ self._downloader.trouble(u'ERROR: no fmt_url_map or conn information found in video info')
+ return
- # title
- mobj = re.search(r'(?m)&title=([^&]+)(?:&|$)', video_info_webpage)
- if mobj is None:
- self._downloader.trouble(u'ERROR: unable to extract video title')
- return
- video_title = urllib.unquote(mobj.group(1))
- video_title = video_title.decode('utf-8')
- video_title = re.sub(ur'(?u)&(.+?);', self.htmlentity_transform, video_title)
- video_title = video_title.replace(os.sep, u'%')
+ for format_param, video_real_url in video_url_list:
+ # At this point we have a new video
+ self._downloader.increment_downloads()
- # simplified title
- simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
- simple_title = simple_title.strip(ur'_')
+ # Extension
+ video_extension = self._video_extensions.get(format_param, 'flv')
+ # Find the video URL in fmt_url_map or conn paramters
try:
# Process video information
self._downloader.process_info({
@@ -741,24 +924,13 @@ class YoutubeIE(InfoExtractor):
'title': video_title,
'stitle': simple_title,
'ext': video_extension.decode('utf-8'),
+ 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
+ 'thumbnail': video_thumbnail.decode('utf-8'),
+ 'description': video_description.decode('utf-8'),
+ 'player_url': player_url,
})
-
- return
-
- except UnavailableFormatError, err:
- if best_quality:
- if quality_index == len(self._available_formats) - 1:
- # I don't ever expect this to happen
- self._downloader.trouble(u'ERROR: no known formats available for video')
- return
- else:
- self.report_unavailable_format(video_id, format_param)
- quality_index += 1
- format_param = self._available_formats[quality_index]
- continue
- else:
- self._downloader.trouble('ERROR: format not available for video')
- return
+ except UnavailableVideoError, err:
+ self._downloader.trouble(u'ERROR: unable to download video')
class MetacafeIE(InfoExtractor):
@@ -831,6 +1003,9 @@ class MetacafeIE(InfoExtractor):
self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % mobj2.group(1))
return
+ # At this point we have a new video
+ self._downloader.increment_downloads()
+
simple_title = mobj.group(2).decode('utf-8')
video_extension = 'flv'
@@ -866,8 +1041,9 @@ class MetacafeIE(InfoExtractor):
self._downloader.trouble(u'ERROR: unable to extract title')
return
video_title = mobj.group(1).decode('utf-8')
+ video_title = sanitize_title(video_title)
- mobj = re.search(r'(?ms)
.*?Submitter:.*?(.*?)<', webpage)
+ mobj = re.search(r'(?ms)By:\s*(.+?)<', webpage)
if mobj is None:
self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
return
@@ -882,155 +1058,930 @@ class MetacafeIE(InfoExtractor):
'title': video_title,
'stitle': simple_title,
'ext': video_extension.decode('utf-8'),
+ 'format': u'NA',
+ 'player_url': None,
})
- except UnavailableFormatError:
- self._downloader.trouble(u'ERROR: format not available for video')
+ except UnavailableVideoError:
+ self._downloader.trouble(u'ERROR: unable to download video')
-class YoutubeSearchIE(InfoExtractor):
- """Information Extractor for YouTube search queries."""
- _VALID_QUERY = r'ytsearch(\d+|all)?:[\s\S]+'
- _TEMPLATE_URL = 'http://www.youtube.com/results?search_query=%s&page=%s&gl=US&hl=en'
- _VIDEO_INDICATOR = r'href="/watch\?v=.+?"'
- _MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*'
- _youtube_ie = None
- _max_youtube_results = 1000
+class DailymotionIE(InfoExtractor):
+ """Information Extractor for Dailymotion"""
- def __init__(self, youtube_ie, downloader=None):
+ _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^_/]+)_([^/]+)'
+
+ def __init__(self, downloader=None):
InfoExtractor.__init__(self, downloader)
- self._youtube_ie = youtube_ie
-
+
@staticmethod
def suitable(url):
- return (re.match(YoutubeSearchIE._VALID_QUERY, url) is not None)
+ return (re.match(DailymotionIE._VALID_URL, url) is not None)
- def report_download_page(self, query, pagenum):
- """Report attempt to download playlist page with given number."""
- self._downloader.to_stdout(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
+ def report_download_webpage(self, video_id):
+ """Report webpage download."""
+ self._downloader.to_stdout(u'[dailymotion] %s: Downloading webpage' % video_id)
+
+ def report_extraction(self, video_id):
+ """Report information extraction."""
+ self._downloader.to_stdout(u'[dailymotion] %s: Extracting information' % video_id)
def _real_initialize(self):
- self._youtube_ie.initialize()
-
- def _real_extract(self, query):
- mobj = re.match(self._VALID_QUERY, query)
+ 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._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
+ self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
return
- prefix, query = query.split(':')
- prefix = prefix[8:]
- if prefix == '':
- self._download_n_results(query, 1)
- return
- elif prefix == 'all':
- self._download_n_results(query, self._max_youtube_results)
+ # At this point we have a new video
+ self._downloader.increment_downloads()
+ video_id = mobj.group(1)
+
+ simple_title = mobj.group(2).decode('utf-8')
+ video_extension = 'flv'
+
+ # Retrieve video webpage to extract further information
+ request = urllib2.Request(url)
+ try:
+ self.report_download_webpage(video_id)
+ webpage = urllib2.urlopen(request).read()
+ except (urllib2.URLError, httplib.HTTPException, socket.error), err:
+ self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
return
- else:
- try:
- n = long(prefix)
- if n <= 0:
- self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
- return
- elif n > self._max_youtube_results:
- self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
- n = self._max_youtube_results
- self._download_n_results(query, n)
- return
- except ValueError: # parsing prefix as integer fails
- self._download_n_results(query, 1)
- return
- def _download_n_results(self, query, n):
- """Downloads a specified number of results for a query"""
+ # Extract URL, uploader and title from webpage
+ self.report_extraction(video_id)
+ mobj = re.search(r'(?i)addVariable\(\"video\"\s*,\s*\"([^\"]*)\"\)', webpage)
+ if mobj is None:
+ self._downloader.trouble(u'ERROR: unable to extract media URL')
+ return
+ mediaURL = urllib.unquote(mobj.group(1))
- video_ids = []
- already_seen = set()
- pagenum = 1
+ # if needed add http://www.dailymotion.com/ if relative URL
- while True:
- self.report_download_page(query, pagenum)
- result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
- request = urllib2.Request(result_url, None, std_headers)
- try:
- page = urllib2.urlopen(request).read()
- except (urllib2.URLError, httplib.HTTPException, socket.error), err:
- self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
- return
+ video_url = mediaURL
- # Extract video identifiers
- for mobj in re.finditer(self._VIDEO_INDICATOR, page):
- video_id = page[mobj.span()[0]:mobj.span()[1]].split('=')[2][:-1]
- if video_id not in already_seen:
- video_ids.append(video_id)
- already_seen.add(video_id)
- if len(video_ids) == n:
- # Specified n videos reached
- for id in video_ids:
- self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
- return
+ # ''
+ mobj = re.search(r'(?im)Dailymotion\s*[\-:]\s*(.+?)', webpage)
+ if mobj is None:
+ self._downloader.trouble(u'ERROR: unable to extract title')
+ return
+ video_title = mobj.group(1).decode('utf-8')
+ video_title = sanitize_title(video_title)
- if re.search(self._MORE_PAGES_INDICATOR, page) is None:
- for id in video_ids:
- self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
- return
+ mobj = re.search(r'(?im)