You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2957 lines
99 KiB

13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
13 years ago
13 years ago
13 years ago
13 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import datetime
  4. import HTMLParser
  5. import httplib
  6. import netrc
  7. import os
  8. import re
  9. import socket
  10. import time
  11. import urllib
  12. import urllib2
  13. import email.utils
  14. import xml.etree.ElementTree
  15. from urlparse import parse_qs
  16. try:
  17. import cStringIO as StringIO
  18. except ImportError:
  19. import StringIO
  20. from utils import *
  21. class InfoExtractor(object):
  22. """Information Extractor class.
  23. Information extractors are the classes that, given a URL, extract
  24. information from the video (or videos) the URL refers to. This
  25. information includes the real video URL, the video title and simplified
  26. title, author and others. The information is stored in a dictionary
  27. which is then passed to the FileDownloader. The FileDownloader
  28. processes this information possibly downloading the video to the file
  29. system, among other possible outcomes. The dictionaries must include
  30. the following fields:
  31. id: Video identifier.
  32. url: Final video URL.
  33. uploader: Nickname of the video uploader.
  34. title: Literal title.
  35. ext: Video filename extension.
  36. format: Video format.
  37. player_url: SWF Player URL (may be None).
  38. The following fields are optional. Their primary purpose is to allow
  39. youtube-dl to serve as the backend for a video search function, such
  40. as the one in youtube2mp3. They are only used when their respective
  41. forced printing functions are called:
  42. thumbnail: Full URL to a video thumbnail image.
  43. description: One-line video description.
  44. Subclasses of this one should re-define the _real_initialize() and
  45. _real_extract() methods and define a _VALID_URL regexp.
  46. Probably, they should also be added to the list of extractors.
  47. """
  48. _ready = False
  49. _downloader = None
  50. def __init__(self, downloader=None):
  51. """Constructor. Receives an optional downloader."""
  52. self._ready = False
  53. self.set_downloader(downloader)
  54. def suitable(self, url):
  55. """Receives a URL and returns True if suitable for this IE."""
  56. return re.match(self._VALID_URL, url) is not None
  57. def initialize(self):
  58. """Initializes an instance (authentication, etc)."""
  59. if not self._ready:
  60. self._real_initialize()
  61. self._ready = True
  62. def extract(self, url):
  63. """Extracts URL information and returns it in list of dicts."""
  64. self.initialize()
  65. return self._real_extract(url)
  66. def set_downloader(self, downloader):
  67. """Sets the downloader for this IE."""
  68. self._downloader = downloader
  69. def _real_initialize(self):
  70. """Real initialization process. Redefine in subclasses."""
  71. pass
  72. def _real_extract(self, url):
  73. """Real extraction process. Redefine in subclasses."""
  74. pass
  75. class YoutubeIE(InfoExtractor):
  76. """Information extractor for youtube.com."""
  77. _VALID_URL = r'^((?:https?://)?(?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|tube\.majestyc\.net/)(?!view_play_list|my_playlists|artist|playlist)(?:(?:(?:v|embed|e)/)|(?:(?:watch(?:_popup)?(?:\.php)?)?(?:\?|#!?)(?:.+&)?v=))?)?([0-9A-Za-z_-]+)(?(1).+)?$'
  78. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  79. _LOGIN_URL = 'https://www.youtube.com/signup?next=/&gl=US&hl=en'
  80. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  81. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  82. _NETRC_MACHINE = 'youtube'
  83. # Listed in order of quality
  84. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  85. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
  86. _video_extensions = {
  87. '13': '3gp',
  88. '17': 'mp4',
  89. '18': 'mp4',
  90. '22': 'mp4',
  91. '37': 'mp4',
  92. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  93. '43': 'webm',
  94. '44': 'webm',
  95. '45': 'webm',
  96. '46': 'webm',
  97. }
  98. _video_dimensions = {
  99. '5': '240x400',
  100. '6': '???',
  101. '13': '???',
  102. '17': '144x176',
  103. '18': '360x640',
  104. '22': '720x1280',
  105. '34': '360x640',
  106. '35': '480x854',
  107. '37': '1080x1920',
  108. '38': '3072x4096',
  109. '43': '360x640',
  110. '44': '480x854',
  111. '45': '720x1280',
  112. '46': '1080x1920',
  113. }
  114. IE_NAME = u'youtube'
  115. def report_lang(self):
  116. """Report attempt to set language."""
  117. self._downloader.to_screen(u'[youtube] Setting language')
  118. def report_login(self):
  119. """Report attempt to log in."""
  120. self._downloader.to_screen(u'[youtube] Logging in')
  121. def report_age_confirmation(self):
  122. """Report attempt to confirm age."""
  123. self._downloader.to_screen(u'[youtube] Confirming age')
  124. def report_video_webpage_download(self, video_id):
  125. """Report attempt to download video webpage."""
  126. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  127. def report_video_info_webpage_download(self, video_id):
  128. """Report attempt to download video info webpage."""
  129. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  130. def report_video_subtitles_download(self, video_id):
  131. """Report attempt to download video info webpage."""
  132. self._downloader.to_screen(u'[youtube] %s: Downloading video subtitles' % video_id)
  133. def report_information_extraction(self, video_id):
  134. """Report attempt to extract video information."""
  135. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  136. def report_unavailable_format(self, video_id, format):
  137. """Report extracted video URL."""
  138. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  139. def report_rtmp_download(self):
  140. """Indicate the download will use the RTMP protocol."""
  141. self._downloader.to_screen(u'[youtube] RTMP download detected')
  142. def _closed_captions_xml_to_srt(self, xml_string):
  143. srt = ''
  144. texts = re.findall(r'<text start="([\d\.]+)"( dur="([\d\.]+)")?>([^<]+)</text>', xml_string, re.MULTILINE)
  145. # TODO parse xml instead of regex
  146. for n, (start, dur_tag, dur, caption) in enumerate(texts):
  147. if not dur: dur = '4'
  148. start = float(start)
  149. end = start + float(dur)
  150. start = "%02i:%02i:%02i,%03i" %(start/(60*60), start/60%60, start%60, start%1*1000)
  151. end = "%02i:%02i:%02i,%03i" %(end/(60*60), end/60%60, end%60, end%1*1000)
  152. caption = unescapeHTML(caption)
  153. caption = unescapeHTML(caption) # double cycle, intentional
  154. srt += str(n+1) + '\n'
  155. srt += start + ' --> ' + end + '\n'
  156. srt += caption + '\n\n'
  157. return srt
  158. def _print_formats(self, formats):
  159. print 'Available formats:'
  160. for x in formats:
  161. print '%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???'))
  162. def _real_initialize(self):
  163. if self._downloader is None:
  164. return
  165. username = None
  166. password = None
  167. downloader_params = self._downloader.params
  168. # Attempt to use provided username and password or .netrc data
  169. if downloader_params.get('username', None) is not None:
  170. username = downloader_params['username']
  171. password = downloader_params['password']
  172. elif downloader_params.get('usenetrc', False):
  173. try:
  174. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  175. if info is not None:
  176. username = info[0]
  177. password = info[2]
  178. else:
  179. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  180. except (IOError, netrc.NetrcParseError), err:
  181. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  182. return
  183. # Set language
  184. request = urllib2.Request(self._LANG_URL)
  185. try:
  186. self.report_lang()
  187. urllib2.urlopen(request).read()
  188. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  189. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % str(err))
  190. return
  191. # No authentication to be performed
  192. if username is None:
  193. return
  194. # Log in
  195. login_form = {
  196. 'current_form': 'loginForm',
  197. 'next': '/',
  198. 'action_login': 'Log In',
  199. 'username': username,
  200. 'password': password,
  201. }
  202. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  203. try:
  204. self.report_login()
  205. login_results = urllib2.urlopen(request).read()
  206. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  207. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  208. return
  209. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  210. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  211. return
  212. # Confirm age
  213. age_form = {
  214. 'next_url': '/',
  215. 'action_confirm': 'Confirm',
  216. }
  217. request = urllib2.Request(self._AGE_URL, urllib.urlencode(age_form))
  218. try:
  219. self.report_age_confirmation()
  220. age_results = urllib2.urlopen(request).read()
  221. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  222. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  223. return
  224. def _real_extract(self, url):
  225. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  226. mobj = re.search(self._NEXT_URL_RE, url)
  227. if mobj:
  228. url = 'http://www.youtube.com/' + urllib.unquote(mobj.group(1)).lstrip('/')
  229. # Extract video id from URL
  230. mobj = re.match(self._VALID_URL, url)
  231. if mobj is None:
  232. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  233. return
  234. video_id = mobj.group(2)
  235. # Get video webpage
  236. self.report_video_webpage_download(video_id)
  237. request = urllib2.Request('http://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id)
  238. try:
  239. video_webpage = urllib2.urlopen(request).read()
  240. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  241. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  242. return
  243. # Attempt to extract SWF player URL
  244. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  245. if mobj is not None:
  246. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  247. else:
  248. player_url = None
  249. # Get video info
  250. self.report_video_info_webpage_download(video_id)
  251. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  252. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  253. % (video_id, el_type))
  254. request = urllib2.Request(video_info_url)
  255. try:
  256. video_info_webpage = urllib2.urlopen(request).read()
  257. video_info = parse_qs(video_info_webpage)
  258. if 'token' in video_info:
  259. break
  260. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  261. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  262. return
  263. if 'token' not in video_info:
  264. if 'reason' in video_info:
  265. self._downloader.trouble(u'ERROR: YouTube said: %s' % video_info['reason'][0].decode('utf-8'))
  266. else:
  267. self._downloader.trouble(u'ERROR: "token" parameter not in video info for unknown reason')
  268. return
  269. # Check for "rental" videos
  270. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  271. self._downloader.trouble(u'ERROR: "rental" videos not supported')
  272. return
  273. # Start extracting information
  274. self.report_information_extraction(video_id)
  275. # uploader
  276. if 'author' not in video_info:
  277. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  278. return
  279. video_uploader = urllib.unquote_plus(video_info['author'][0])
  280. # title
  281. if 'title' not in video_info:
  282. self._downloader.trouble(u'ERROR: unable to extract video title')
  283. return
  284. video_title = urllib.unquote_plus(video_info['title'][0])
  285. video_title = video_title.decode('utf-8')
  286. # thumbnail image
  287. if 'thumbnail_url' not in video_info:
  288. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  289. video_thumbnail = ''
  290. else: # don't panic if we can't find it
  291. video_thumbnail = urllib.unquote_plus(video_info['thumbnail_url'][0])
  292. # upload date
  293. upload_date = u'NA'
  294. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  295. if mobj is not None:
  296. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  297. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  298. for expression in format_expressions:
  299. try:
  300. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  301. except:
  302. pass
  303. # description
  304. video_description = get_element_by_id("eow-description", video_webpage.decode('utf8'))
  305. if video_description: video_description = clean_html(video_description)
  306. else: video_description = ''
  307. # closed captions
  308. video_subtitles = None
  309. if self._downloader.params.get('writesubtitles', False):
  310. try:
  311. self.report_video_subtitles_download(video_id)
  312. request = urllib2.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  313. try:
  314. srt_list = urllib2.urlopen(request).read()
  315. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  316. raise Trouble(u'WARNING: unable to download video subtitles: %s' % str(err))
  317. srt_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', srt_list)
  318. srt_lang_list = dict((l[1], l[0]) for l in srt_lang_list)
  319. if not srt_lang_list:
  320. raise Trouble(u'WARNING: video has no closed captions')
  321. if self._downloader.params.get('subtitleslang', False):
  322. srt_lang = self._downloader.params.get('subtitleslang')
  323. elif 'en' in srt_lang_list:
  324. srt_lang = 'en'
  325. else:
  326. srt_lang = srt_lang_list.keys()[0]
  327. if not srt_lang in srt_lang_list:
  328. raise Trouble(u'WARNING: no closed captions found in the specified language')
  329. request = urllib2.Request('http://www.youtube.com/api/timedtext?lang=%s&name=%s&v=%s' % (srt_lang, srt_lang_list[srt_lang], video_id))
  330. try:
  331. srt_xml = urllib2.urlopen(request).read()
  332. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  333. raise Trouble(u'WARNING: unable to download video subtitles: %s' % str(err))
  334. if not srt_xml:
  335. raise Trouble(u'WARNING: unable to download video subtitles')
  336. video_subtitles = self._closed_captions_xml_to_srt(srt_xml.decode('utf-8'))
  337. except Trouble as trouble:
  338. self._downloader.trouble(trouble[0])
  339. # token
  340. video_token = urllib.unquote_plus(video_info['token'][0])
  341. # Decide which formats to download
  342. req_format = self._downloader.params.get('format', None)
  343. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  344. self.report_rtmp_download()
  345. video_url_list = [(None, video_info['conn'][0])]
  346. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  347. url_data_strs = video_info['url_encoded_fmt_stream_map'][0].split(',')
  348. url_data = [parse_qs(uds) for uds in url_data_strs]
  349. url_data = filter(lambda ud: 'itag' in ud and 'url' in ud, url_data)
  350. url_map = dict((ud['itag'][0], ud['url'][0]) for ud in url_data)
  351. format_limit = self._downloader.params.get('format_limit', None)
  352. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  353. if format_limit is not None and format_limit in available_formats:
  354. format_list = available_formats[available_formats.index(format_limit):]
  355. else:
  356. format_list = available_formats
  357. existing_formats = [x for x in format_list if x in url_map]
  358. if len(existing_formats) == 0:
  359. self._downloader.trouble(u'ERROR: no known formats available for video')
  360. return
  361. if self._downloader.params.get('listformats', None):
  362. self._print_formats(existing_formats)
  363. return
  364. if req_format is None or req_format == 'best':
  365. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  366. elif req_format == 'worst':
  367. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  368. elif req_format in ('-1', 'all'):
  369. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  370. else:
  371. # Specific formats. We pick the first in a slash-delimeted sequence.
  372. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  373. req_formats = req_format.split('/')
  374. video_url_list = None
  375. for rf in req_formats:
  376. if rf in url_map:
  377. video_url_list = [(rf, url_map[rf])]
  378. break
  379. if video_url_list is None:
  380. self._downloader.trouble(u'ERROR: requested format not available')
  381. return
  382. else:
  383. self._downloader.trouble(u'ERROR: no conn or url_encoded_fmt_stream_map information found in video info')
  384. return
  385. results = []
  386. for format_param, video_real_url in video_url_list:
  387. # Extension
  388. video_extension = self._video_extensions.get(format_param, 'flv')
  389. results.append({
  390. 'id': video_id.decode('utf-8'),
  391. 'url': video_real_url.decode('utf-8'),
  392. 'uploader': video_uploader.decode('utf-8'),
  393. 'upload_date': upload_date,
  394. 'title': video_title,
  395. 'ext': video_extension.decode('utf-8'),
  396. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  397. 'thumbnail': video_thumbnail.decode('utf-8'),
  398. 'description': video_description,
  399. 'player_url': player_url,
  400. 'subtitles': video_subtitles
  401. })
  402. return results
  403. class MetacafeIE(InfoExtractor):
  404. """Information Extractor for metacafe.com."""
  405. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  406. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  407. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  408. IE_NAME = u'metacafe'
  409. def __init__(self, downloader=None):
  410. InfoExtractor.__init__(self, downloader)
  411. def report_disclaimer(self):
  412. """Report disclaimer retrieval."""
  413. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  414. def report_age_confirmation(self):
  415. """Report attempt to confirm age."""
  416. self._downloader.to_screen(u'[metacafe] Confirming age')
  417. def report_download_webpage(self, video_id):
  418. """Report webpage download."""
  419. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  420. def report_extraction(self, video_id):
  421. """Report information extraction."""
  422. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  423. def _real_initialize(self):
  424. # Retrieve disclaimer
  425. request = urllib2.Request(self._DISCLAIMER)
  426. try:
  427. self.report_disclaimer()
  428. disclaimer = urllib2.urlopen(request).read()
  429. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  430. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % str(err))
  431. return
  432. # Confirm age
  433. disclaimer_form = {
  434. 'filters': '0',
  435. 'submit': "Continue - I'm over 18",
  436. }
  437. request = urllib2.Request(self._FILTER_POST, urllib.urlencode(disclaimer_form))
  438. try:
  439. self.report_age_confirmation()
  440. disclaimer = urllib2.urlopen(request).read()
  441. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  442. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  443. return
  444. def _real_extract(self, url):
  445. # Extract id and simplified title from URL
  446. mobj = re.match(self._VALID_URL, url)
  447. if mobj is None:
  448. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  449. return
  450. video_id = mobj.group(1)
  451. # Check if video comes from YouTube
  452. mobj2 = re.match(r'^yt-(.*)$', video_id)
  453. if mobj2 is not None:
  454. self._downloader.download(['http://www.youtube.com/watch?v=%s' % mobj2.group(1)])
  455. return
  456. # Retrieve video webpage to extract further information
  457. request = urllib2.Request('http://www.metacafe.com/watch/%s/' % video_id)
  458. try:
  459. self.report_download_webpage(video_id)
  460. webpage = urllib2.urlopen(request).read()
  461. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  462. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  463. return
  464. # Extract URL, uploader and title from webpage
  465. self.report_extraction(video_id)
  466. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  467. if mobj is not None:
  468. mediaURL = urllib.unquote(mobj.group(1))
  469. video_extension = mediaURL[-3:]
  470. # Extract gdaKey if available
  471. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  472. if mobj is None:
  473. video_url = mediaURL
  474. else:
  475. gdaKey = mobj.group(1)
  476. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  477. else:
  478. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  479. if mobj is None:
  480. self._downloader.trouble(u'ERROR: unable to extract media URL')
  481. return
  482. vardict = parse_qs(mobj.group(1))
  483. if 'mediaData' not in vardict:
  484. self._downloader.trouble(u'ERROR: unable to extract media URL')
  485. return
  486. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  487. if mobj is None:
  488. self._downloader.trouble(u'ERROR: unable to extract media URL')
  489. return
  490. mediaURL = mobj.group(1).replace('\\/', '/')
  491. video_extension = mediaURL[-3:]
  492. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  493. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  494. if mobj is None:
  495. self._downloader.trouble(u'ERROR: unable to extract title')
  496. return
  497. video_title = mobj.group(1).decode('utf-8')
  498. mobj = re.search(r'(?ms)By:\s*<a .*?>(.+?)<', webpage)
  499. if mobj is None:
  500. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  501. return
  502. video_uploader = mobj.group(1)
  503. return [{
  504. 'id': video_id.decode('utf-8'),
  505. 'url': video_url.decode('utf-8'),
  506. 'uploader': video_uploader.decode('utf-8'),
  507. 'upload_date': u'NA',
  508. 'title': video_title,
  509. 'ext': video_extension.decode('utf-8'),
  510. 'format': u'NA',
  511. 'player_url': None,
  512. }]
  513. class DailymotionIE(InfoExtractor):
  514. """Information Extractor for Dailymotion"""
  515. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^_/]+)_([^/]+)'
  516. IE_NAME = u'dailymotion'
  517. def __init__(self, downloader=None):
  518. InfoExtractor.__init__(self, downloader)
  519. def report_download_webpage(self, video_id):
  520. """Report webpage download."""
  521. self._downloader.to_screen(u'[dailymotion] %s: Downloading webpage' % video_id)
  522. def report_extraction(self, video_id):
  523. """Report information extraction."""
  524. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  525. def _real_extract(self, url):
  526. # Extract id and simplified title from URL
  527. mobj = re.match(self._VALID_URL, url)
  528. if mobj is None:
  529. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  530. return
  531. video_id = mobj.group(1)
  532. video_extension = 'flv'
  533. # Retrieve video webpage to extract further information
  534. request = urllib2.Request(url)
  535. request.add_header('Cookie', 'family_filter=off')
  536. try:
  537. self.report_download_webpage(video_id)
  538. webpage = urllib2.urlopen(request).read()
  539. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  540. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  541. return
  542. # Extract URL, uploader and title from webpage
  543. self.report_extraction(video_id)
  544. mobj = re.search(r'(?i)addVariable\(\"sequence\"\s*,\s*\"([^\"]+?)\"\)', webpage)
  545. if mobj is None:
  546. self._downloader.trouble(u'ERROR: unable to extract media URL')
  547. return
  548. sequence = urllib.unquote(mobj.group(1))
  549. mobj = re.search(r',\"sdURL\"\:\"([^\"]+?)\",', sequence)
  550. if mobj is None:
  551. self._downloader.trouble(u'ERROR: unable to extract media URL')
  552. return
  553. mediaURL = urllib.unquote(mobj.group(1)).replace('\\', '')
  554. # if needed add http://www.dailymotion.com/ if relative URL
  555. video_url = mediaURL
  556. mobj = re.search(r'<meta property="og:title" content="(?P<title>[^"]*)" />', webpage)
  557. if mobj is None:
  558. self._downloader.trouble(u'ERROR: unable to extract title')
  559. return
  560. video_title = unescapeHTML(mobj.group('title').decode('utf-8'))
  561. mobj = re.search(r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a></span>', webpage)
  562. if mobj is None:
  563. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  564. return
  565. video_uploader = mobj.group(1)
  566. return [{
  567. 'id': video_id.decode('utf-8'),
  568. 'url': video_url.decode('utf-8'),
  569. 'uploader': video_uploader.decode('utf-8'),
  570. 'upload_date': u'NA',
  571. 'title': video_title,
  572. 'ext': video_extension.decode('utf-8'),
  573. 'format': u'NA',
  574. 'player_url': None,
  575. }]
  576. class GoogleIE(InfoExtractor):
  577. """Information extractor for video.google.com."""
  578. _VALID_URL = r'(?:http://)?video\.google\.(?:com(?:\.au)?|co\.(?:uk|jp|kr|cr)|ca|de|es|fr|it|nl|pl)/videoplay\?docid=([^\&]+).*'
  579. IE_NAME = u'video.google'
  580. def __init__(self, downloader=None):
  581. InfoExtractor.__init__(self, downloader)
  582. def report_download_webpage(self, video_id):
  583. """Report webpage download."""
  584. self._downloader.to_screen(u'[video.google] %s: Downloading webpage' % video_id)
  585. def report_extraction(self, video_id):
  586. """Report information extraction."""
  587. self._downloader.to_screen(u'[video.google] %s: Extracting information' % video_id)
  588. def _real_extract(self, url):
  589. # Extract id from URL
  590. mobj = re.match(self._VALID_URL, url)
  591. if mobj is None:
  592. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  593. return
  594. video_id = mobj.group(1)
  595. video_extension = 'mp4'
  596. # Retrieve video webpage to extract further information
  597. request = urllib2.Request('http://video.google.com/videoplay?docid=%s&hl=en&oe=utf-8' % video_id)
  598. try:
  599. self.report_download_webpage(video_id)
  600. webpage = urllib2.urlopen(request).read()
  601. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  602. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  603. return
  604. # Extract URL, uploader, and title from webpage
  605. self.report_extraction(video_id)
  606. mobj = re.search(r"download_url:'([^']+)'", webpage)
  607. if mobj is None:
  608. video_extension = 'flv'
  609. mobj = re.search(r"(?i)videoUrl\\x3d(.+?)\\x26", webpage)
  610. if mobj is None:
  611. self._downloader.trouble(u'ERROR: unable to extract media URL')
  612. return
  613. mediaURL = urllib.unquote(mobj.group(1))
  614. mediaURL = mediaURL.replace('\\x3d', '\x3d')
  615. mediaURL = mediaURL.replace('\\x26', '\x26')
  616. video_url = mediaURL
  617. mobj = re.search(r'<title>(.*)</title>', webpage)
  618. if mobj is None:
  619. self._downloader.trouble(u'ERROR: unable to extract title')
  620. return
  621. video_title = mobj.group(1).decode('utf-8')
  622. # Extract video description
  623. mobj = re.search(r'<span id=short-desc-content>([^<]*)</span>', webpage)
  624. if mobj is None:
  625. self._downloader.trouble(u'ERROR: unable to extract video description')
  626. return
  627. video_description = mobj.group(1).decode('utf-8')
  628. if not video_description:
  629. video_description = 'No description available.'
  630. # Extract video thumbnail
  631. if self._downloader.params.get('forcethumbnail', False):
  632. request = urllib2.Request('http://video.google.com/videosearch?q=%s+site:video.google.com&hl=en' % abs(int(video_id)))
  633. try:
  634. webpage = urllib2.urlopen(request).read()
  635. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  636. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  637. return
  638. mobj = re.search(r'<img class=thumbnail-img (?:.* )?src=(http.*)>', webpage)
  639. if mobj is None:
  640. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  641. return
  642. video_thumbnail = mobj.group(1)
  643. else: # we need something to pass to process_info
  644. video_thumbnail = ''
  645. return [{
  646. 'id': video_id.decode('utf-8'),
  647. 'url': video_url.decode('utf-8'),
  648. 'uploader': u'NA',
  649. 'upload_date': u'NA',
  650. 'title': video_title,
  651. 'ext': video_extension.decode('utf-8'),
  652. 'format': u'NA',
  653. 'player_url': None,
  654. }]
  655. class PhotobucketIE(InfoExtractor):
  656. """Information extractor for photobucket.com."""
  657. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  658. IE_NAME = u'photobucket'
  659. def __init__(self, downloader=None):
  660. InfoExtractor.__init__(self, downloader)
  661. def report_download_webpage(self, video_id):
  662. """Report webpage download."""
  663. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  664. def report_extraction(self, video_id):
  665. """Report information extraction."""
  666. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  667. def _real_extract(self, url):
  668. # Extract id from URL
  669. mobj = re.match(self._VALID_URL, url)
  670. if mobj is None:
  671. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  672. return
  673. video_id = mobj.group(1)
  674. video_extension = 'flv'
  675. # Retrieve video webpage to extract further information
  676. request = urllib2.Request(url)
  677. try:
  678. self.report_download_webpage(video_id)
  679. webpage = urllib2.urlopen(request).read()
  680. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  681. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  682. return
  683. # Extract URL, uploader, and title from webpage
  684. self.report_extraction(video_id)
  685. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  686. if mobj is None:
  687. self._downloader.trouble(u'ERROR: unable to extract media URL')
  688. return
  689. mediaURL = urllib.unquote(mobj.group(1))
  690. video_url = mediaURL
  691. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  692. if mobj is None:
  693. self._downloader.trouble(u'ERROR: unable to extract title')
  694. return
  695. video_title = mobj.group(1).decode('utf-8')
  696. video_uploader = mobj.group(2).decode('utf-8')
  697. return [{
  698. 'id': video_id.decode('utf-8'),
  699. 'url': video_url.decode('utf-8'),
  700. 'uploader': video_uploader,
  701. 'upload_date': u'NA',
  702. 'title': video_title,
  703. 'ext': video_extension.decode('utf-8'),
  704. 'format': u'NA',
  705. 'player_url': None,
  706. }]
  707. class YahooIE(InfoExtractor):
  708. """Information extractor for video.yahoo.com."""
  709. # _VALID_URL matches all Yahoo! Video URLs
  710. # _VPAGE_URL matches only the extractable '/watch/' URLs
  711. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  712. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  713. IE_NAME = u'video.yahoo'
  714. def __init__(self, downloader=None):
  715. InfoExtractor.__init__(self, downloader)
  716. def report_download_webpage(self, video_id):
  717. """Report webpage download."""
  718. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  719. def report_extraction(self, video_id):
  720. """Report information extraction."""
  721. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  722. def _real_extract(self, url, new_video=True):
  723. # Extract ID from URL
  724. mobj = re.match(self._VALID_URL, url)
  725. if mobj is None:
  726. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  727. return
  728. video_id = mobj.group(2)
  729. video_extension = 'flv'
  730. # Rewrite valid but non-extractable URLs as
  731. # extractable English language /watch/ URLs
  732. if re.match(self._VPAGE_URL, url) is None:
  733. request = urllib2.Request(url)
  734. try:
  735. webpage = urllib2.urlopen(request).read()
  736. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  737. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  738. return
  739. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  740. if mobj is None:
  741. self._downloader.trouble(u'ERROR: Unable to extract id field')
  742. return
  743. yahoo_id = mobj.group(1)
  744. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  745. if mobj is None:
  746. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  747. return
  748. yahoo_vid = mobj.group(1)
  749. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  750. return self._real_extract(url, new_video=False)
  751. # Retrieve video webpage to extract further information
  752. request = urllib2.Request(url)
  753. try:
  754. self.report_download_webpage(video_id)
  755. webpage = urllib2.urlopen(request).read()
  756. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  757. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  758. return
  759. # Extract uploader and title from webpage
  760. self.report_extraction(video_id)
  761. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  762. if mobj is None:
  763. self._downloader.trouble(u'ERROR: unable to extract video title')
  764. return
  765. video_title = mobj.group(1).decode('utf-8')
  766. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  767. if mobj is None:
  768. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  769. return
  770. video_uploader = mobj.group(1).decode('utf-8')
  771. # Extract video thumbnail
  772. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  773. if mobj is None:
  774. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  775. return
  776. video_thumbnail = mobj.group(1).decode('utf-8')
  777. # Extract video description
  778. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  779. if mobj is None:
  780. self._downloader.trouble(u'ERROR: unable to extract video description')
  781. return
  782. video_description = mobj.group(1).decode('utf-8')
  783. if not video_description:
  784. video_description = 'No description available.'
  785. # Extract video height and width
  786. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  787. if mobj is None:
  788. self._downloader.trouble(u'ERROR: unable to extract video height')
  789. return
  790. yv_video_height = mobj.group(1)
  791. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  792. if mobj is None:
  793. self._downloader.trouble(u'ERROR: unable to extract video width')
  794. return
  795. yv_video_width = mobj.group(1)
  796. # Retrieve video playlist to extract media URL
  797. # I'm not completely sure what all these options are, but we
  798. # seem to need most of them, otherwise the server sends a 401.
  799. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  800. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  801. request = urllib2.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  802. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  803. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  804. try:
  805. self.report_download_webpage(video_id)
  806. webpage = urllib2.urlopen(request).read()
  807. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  808. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  809. return
  810. # Extract media URL from playlist XML
  811. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  812. if mobj is None:
  813. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  814. return
  815. video_url = urllib.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  816. video_url = unescapeHTML(video_url)
  817. return [{
  818. 'id': video_id.decode('utf-8'),
  819. 'url': video_url,
  820. 'uploader': video_uploader,
  821. 'upload_date': u'NA',
  822. 'title': video_title,
  823. 'ext': video_extension.decode('utf-8'),
  824. 'thumbnail': video_thumbnail.decode('utf-8'),
  825. 'description': video_description,
  826. 'thumbnail': video_thumbnail,
  827. 'player_url': None,
  828. }]
  829. class VimeoIE(InfoExtractor):
  830. """Information extractor for vimeo.com."""
  831. # _VALID_URL matches Vimeo URLs
  832. _VALID_URL = r'(?:https?://)?(?:(?:www|player).)?vimeo\.com/(?:groups/[^/]+/)?(?:videos?/)?([0-9]+)'
  833. IE_NAME = u'vimeo'
  834. def __init__(self, downloader=None):
  835. InfoExtractor.__init__(self, downloader)
  836. def report_download_webpage(self, video_id):
  837. """Report webpage download."""
  838. self._downloader.to_screen(u'[vimeo] %s: Downloading webpage' % video_id)
  839. def report_extraction(self, video_id):
  840. """Report information extraction."""
  841. self._downloader.to_screen(u'[vimeo] %s: Extracting information' % video_id)
  842. def _real_extract(self, url, new_video=True):
  843. # Extract ID from URL
  844. mobj = re.match(self._VALID_URL, url)
  845. if mobj is None:
  846. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  847. return
  848. video_id = mobj.group(1)
  849. # Retrieve video webpage to extract further information
  850. request = urllib2.Request(url, None, std_headers)
  851. try:
  852. self.report_download_webpage(video_id)
  853. webpage = urllib2.urlopen(request).read()
  854. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  855. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  856. return
  857. # Now we begin extracting as much information as we can from what we
  858. # retrieved. First we extract the information common to all extractors,
  859. # and latter we extract those that are Vimeo specific.
  860. self.report_extraction(video_id)
  861. # Extract the config JSON
  862. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  863. try:
  864. config = json.loads(config)
  865. except:
  866. self._downloader.trouble(u'ERROR: unable to extract info section')
  867. return
  868. # Extract title
  869. video_title = config["video"]["title"]
  870. # Extract uploader
  871. video_uploader = config["video"]["owner"]["name"]
  872. # Extract video thumbnail
  873. video_thumbnail = config["video"]["thumbnail"]
  874. # Extract video description
  875. video_description = get_element_by_id("description", webpage.decode('utf8'))
  876. if video_description: video_description = clean_html(video_description)
  877. else: video_description = ''
  878. # Extract upload date
  879. video_upload_date = u'NA'
  880. mobj = re.search(r'<span id="clip-date" style="display:none">[^:]*: (.*?)( \([^\(]*\))?</span>', webpage)
  881. if mobj is not None:
  882. video_upload_date = mobj.group(1)
  883. # Vimeo specific: extract request signature and timestamp
  884. sig = config['request']['signature']
  885. timestamp = config['request']['timestamp']
  886. # Vimeo specific: extract video codec and quality information
  887. # TODO bind to format param
  888. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  889. for codec in codecs:
  890. if codec[0] in config["video"]["files"]:
  891. video_codec = codec[0]
  892. video_extension = codec[1]
  893. if 'hd' in config["video"]["files"][codec[0]]: quality = 'hd'
  894. else: quality = 'sd'
  895. break
  896. else:
  897. self._downloader.trouble(u'ERROR: no known codec found')
  898. return
  899. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  900. %(video_id, sig, timestamp, quality, video_codec.upper())
  901. return [{
  902. 'id': video_id,
  903. 'url': video_url,
  904. 'uploader': video_uploader,
  905. 'upload_date': video_upload_date,
  906. 'title': video_title,
  907. 'ext': video_extension,
  908. 'thumbnail': video_thumbnail,
  909. 'description': video_description,
  910. 'player_url': None,
  911. }]
  912. class GenericIE(InfoExtractor):
  913. """Generic last-resort information extractor."""
  914. _VALID_URL = r'.*'
  915. IE_NAME = u'generic'
  916. def __init__(self, downloader=None):
  917. InfoExtractor.__init__(self, downloader)
  918. def report_download_webpage(self, video_id):
  919. """Report webpage download."""
  920. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  921. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  922. def report_extraction(self, video_id):
  923. """Report information extraction."""
  924. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  925. def report_following_redirect(self, new_url):
  926. """Report information extraction."""
  927. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  928. def _test_redirect(self, url):
  929. """Check if it is a redirect, like url shorteners, in case restart chain."""
  930. class HeadRequest(urllib2.Request):
  931. def get_method(self):
  932. return "HEAD"
  933. class HEADRedirectHandler(urllib2.HTTPRedirectHandler):
  934. """
  935. Subclass the HTTPRedirectHandler to make it use our
  936. HeadRequest also on the redirected URL
  937. """
  938. def redirect_request(self, req, fp, code, msg, headers, newurl):
  939. if code in (301, 302, 303, 307):
  940. newurl = newurl.replace(' ', '%20')
  941. newheaders = dict((k,v) for k,v in req.headers.items()
  942. if k.lower() not in ("content-length", "content-type"))
  943. return HeadRequest(newurl,
  944. headers=newheaders,
  945. origin_req_host=req.get_origin_req_host(),
  946. unverifiable=True)
  947. else:
  948. raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
  949. class HTTPMethodFallback(urllib2.BaseHandler):
  950. """
  951. Fallback to GET if HEAD is not allowed (405 HTTP error)
  952. """
  953. def http_error_405(self, req, fp, code, msg, headers):
  954. fp.read()
  955. fp.close()
  956. newheaders = dict((k,v) for k,v in req.headers.items()
  957. if k.lower() not in ("content-length", "content-type"))
  958. return self.parent.open(urllib2.Request(req.get_full_url(),
  959. headers=newheaders,
  960. origin_req_host=req.get_origin_req_host(),
  961. unverifiable=True))
  962. # Build our opener
  963. opener = urllib2.OpenerDirector()
  964. for handler in [urllib2.HTTPHandler, urllib2.HTTPDefaultErrorHandler,
  965. HTTPMethodFallback, HEADRedirectHandler,
  966. urllib2.HTTPErrorProcessor, urllib2.HTTPSHandler]:
  967. opener.add_handler(handler())
  968. response = opener.open(HeadRequest(url))
  969. new_url = response.geturl()
  970. if url == new_url: return False
  971. self.report_following_redirect(new_url)
  972. self._downloader.download([new_url])
  973. return True
  974. def _real_extract(self, url):
  975. if self._test_redirect(url): return
  976. video_id = url.split('/')[-1]
  977. request = urllib2.Request(url)
  978. try:
  979. self.report_download_webpage(video_id)
  980. webpage = urllib2.urlopen(request).read()
  981. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  982. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  983. return
  984. except ValueError, err:
  985. # since this is the last-resort InfoExtractor, if
  986. # this error is thrown, it'll be thrown here
  987. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  988. return
  989. self.report_extraction(video_id)
  990. # Start with something easy: JW Player in SWFObject
  991. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  992. if mobj is None:
  993. # Broaden the search a little bit
  994. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  995. if mobj is None:
  996. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  997. return
  998. # It's possible that one of the regexes
  999. # matched, but returned an empty group:
  1000. if mobj.group(1) is None:
  1001. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1002. return
  1003. video_url = urllib.unquote(mobj.group(1))
  1004. video_id = os.path.basename(video_url)
  1005. # here's a fun little line of code for you:
  1006. video_extension = os.path.splitext(video_id)[1][1:]
  1007. video_id = os.path.splitext(video_id)[0]
  1008. # it's tempting to parse this further, but you would
  1009. # have to take into account all the variations like
  1010. # Video Title - Site Name
  1011. # Site Name | Video Title
  1012. # Video Title - Tagline | Site Name
  1013. # and so on and so forth; it's just not practical
  1014. mobj = re.search(r'<title>(.*)</title>', webpage)
  1015. if mobj is None:
  1016. self._downloader.trouble(u'ERROR: unable to extract title')
  1017. return
  1018. video_title = mobj.group(1).decode('utf-8')
  1019. # video uploader is domain name
  1020. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1021. if mobj is None:
  1022. self._downloader.trouble(u'ERROR: unable to extract title')
  1023. return
  1024. video_uploader = mobj.group(1).decode('utf-8')
  1025. return [{
  1026. 'id': video_id.decode('utf-8'),
  1027. 'url': video_url.decode('utf-8'),
  1028. 'uploader': video_uploader,
  1029. 'upload_date': u'NA',
  1030. 'title': video_title,
  1031. 'ext': video_extension.decode('utf-8'),
  1032. 'format': u'NA',
  1033. 'player_url': None,
  1034. }]
  1035. class YoutubeSearchIE(InfoExtractor):
  1036. """Information Extractor for YouTube search queries."""
  1037. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1038. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1039. _max_youtube_results = 1000
  1040. IE_NAME = u'youtube:search'
  1041. def __init__(self, downloader=None):
  1042. InfoExtractor.__init__(self, downloader)
  1043. def report_download_page(self, query, pagenum):
  1044. """Report attempt to download search page with given number."""
  1045. query = query.decode(preferredencoding())
  1046. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1047. def _real_extract(self, query):
  1048. mobj = re.match(self._VALID_URL, query)
  1049. if mobj is None:
  1050. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1051. return
  1052. prefix, query = query.split(':')
  1053. prefix = prefix[8:]
  1054. query = query.encode('utf-8')
  1055. if prefix == '':
  1056. self._download_n_results(query, 1)
  1057. return
  1058. elif prefix == 'all':
  1059. self._download_n_results(query, self._max_youtube_results)
  1060. return
  1061. else:
  1062. try:
  1063. n = long(prefix)
  1064. if n <= 0:
  1065. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1066. return
  1067. elif n > self._max_youtube_results:
  1068. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1069. n = self._max_youtube_results
  1070. self._download_n_results(query, n)
  1071. return
  1072. except ValueError: # parsing prefix as integer fails
  1073. self._download_n_results(query, 1)
  1074. return
  1075. def _download_n_results(self, query, n):
  1076. """Downloads a specified number of results for a query"""
  1077. video_ids = []
  1078. pagenum = 0
  1079. limit = n
  1080. while (50 * pagenum) < limit:
  1081. self.report_download_page(query, pagenum+1)
  1082. result_url = self._API_URL % (urllib.quote_plus(query), (50*pagenum)+1)
  1083. request = urllib2.Request(result_url)
  1084. try:
  1085. data = urllib2.urlopen(request).read()
  1086. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1087. self._downloader.trouble(u'ERROR: unable to download API page: %s' % str(err))
  1088. return
  1089. api_response = json.loads(data)['data']
  1090. new_ids = list(video['id'] for video in api_response['items'])
  1091. video_ids += new_ids
  1092. limit = min(n, api_response['totalItems'])
  1093. pagenum += 1
  1094. if len(video_ids) > n:
  1095. video_ids = video_ids[:n]
  1096. for id in video_ids:
  1097. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1098. return
  1099. class GoogleSearchIE(InfoExtractor):
  1100. """Information Extractor for Google Video search queries."""
  1101. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1102. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1103. _VIDEO_INDICATOR = r'<a href="http://video\.google\.com/videoplay\?docid=([^"\&]+)'
  1104. _MORE_PAGES_INDICATOR = r'class="pn" id="pnnext"'
  1105. _max_google_results = 1000
  1106. IE_NAME = u'video.google:search'
  1107. def __init__(self, downloader=None):
  1108. InfoExtractor.__init__(self, downloader)
  1109. def report_download_page(self, query, pagenum):
  1110. """Report attempt to download playlist page with given number."""
  1111. query = query.decode(preferredencoding())
  1112. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1113. def _real_extract(self, query):
  1114. mobj = re.match(self._VALID_URL, query)
  1115. if mobj is None:
  1116. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1117. return
  1118. prefix, query = query.split(':')
  1119. prefix = prefix[8:]
  1120. query = query.encode('utf-8')
  1121. if prefix == '':
  1122. self._download_n_results(query, 1)
  1123. return
  1124. elif prefix == 'all':
  1125. self._download_n_results(query, self._max_google_results)
  1126. return
  1127. else:
  1128. try:
  1129. n = long(prefix)
  1130. if n <= 0:
  1131. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1132. return
  1133. elif n > self._max_google_results:
  1134. self._downloader.to_stderr(u'WARNING: gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1135. n = self._max_google_results
  1136. self._download_n_results(query, n)
  1137. return
  1138. except ValueError: # parsing prefix as integer fails
  1139. self._download_n_results(query, 1)
  1140. return
  1141. def _download_n_results(self, query, n):
  1142. """Downloads a specified number of results for a query"""
  1143. video_ids = []
  1144. pagenum = 0
  1145. while True:
  1146. self.report_download_page(query, pagenum)
  1147. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum*10)
  1148. request = urllib2.Request(result_url)
  1149. try:
  1150. page = urllib2.urlopen(request).read()
  1151. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1152. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1153. return
  1154. # Extract video identifiers
  1155. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1156. video_id = mobj.group(1)
  1157. if video_id not in video_ids:
  1158. video_ids.append(video_id)
  1159. if len(video_ids) == n:
  1160. # Specified n videos reached
  1161. for id in video_ids:
  1162. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1163. return
  1164. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1165. for id in video_ids:
  1166. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1167. return
  1168. pagenum = pagenum + 1
  1169. class YahooSearchIE(InfoExtractor):
  1170. """Information Extractor for Yahoo! Video search queries."""
  1171. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  1172. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1173. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1174. _MORE_PAGES_INDICATOR = r'\s*Next'
  1175. _max_yahoo_results = 1000
  1176. IE_NAME = u'video.yahoo:search'
  1177. def __init__(self, downloader=None):
  1178. InfoExtractor.__init__(self, downloader)
  1179. def report_download_page(self, query, pagenum):
  1180. """Report attempt to download playlist page with given number."""
  1181. query = query.decode(preferredencoding())
  1182. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1183. def _real_extract(self, query):
  1184. mobj = re.match(self._VALID_URL, query)
  1185. if mobj is None:
  1186. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1187. return
  1188. prefix, query = query.split(':')
  1189. prefix = prefix[8:]
  1190. query = query.encode('utf-8')
  1191. if prefix == '':
  1192. self._download_n_results(query, 1)
  1193. return
  1194. elif prefix == 'all':
  1195. self._download_n_results(query, self._max_yahoo_results)
  1196. return
  1197. else:
  1198. try:
  1199. n = long(prefix)
  1200. if n <= 0:
  1201. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1202. return
  1203. elif n > self._max_yahoo_results:
  1204. self._downloader.to_stderr(u'WARNING: yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1205. n = self._max_yahoo_results
  1206. self._download_n_results(query, n)
  1207. return
  1208. except ValueError: # parsing prefix as integer fails
  1209. self._download_n_results(query, 1)
  1210. return
  1211. def _download_n_results(self, query, n):
  1212. """Downloads a specified number of results for a query"""
  1213. video_ids = []
  1214. already_seen = set()
  1215. pagenum = 1
  1216. while True:
  1217. self.report_download_page(query, pagenum)
  1218. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1219. request = urllib2.Request(result_url)
  1220. try:
  1221. page = urllib2.urlopen(request).read()
  1222. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1223. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1224. return
  1225. # Extract video identifiers
  1226. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1227. video_id = mobj.group(1)
  1228. if video_id not in already_seen:
  1229. video_ids.append(video_id)
  1230. already_seen.add(video_id)
  1231. if len(video_ids) == n:
  1232. # Specified n videos reached
  1233. for id in video_ids:
  1234. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1235. return
  1236. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1237. for id in video_ids:
  1238. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1239. return
  1240. pagenum = pagenum + 1
  1241. class YoutubePlaylistIE(InfoExtractor):
  1242. """Information Extractor for YouTube playlists."""
  1243. _VALID_URL = r'(?:https?://)?(?:\w+\.)?youtube\.com/(?:(?:course|view_play_list|my_playlists|artist|playlist)\?.*?(p|a|list)=|user/.*?/user/|p/|user/.*?#[pg]/c/)(?:PL)?([0-9A-Za-z-_]+)(?:/.*?/([0-9A-Za-z_-]+))?.*'
  1244. _TEMPLATE_URL = 'http://www.youtube.com/%s?%s=%s&page=%s&gl=US&hl=en'
  1245. _VIDEO_INDICATOR_TEMPLATE = r'/watch\?v=(.+?)&amp;list=(PL)?%s&'
  1246. _MORE_PAGES_INDICATOR = r'yt-uix-pager-next'
  1247. IE_NAME = u'youtube:playlist'
  1248. def __init__(self, downloader=None):
  1249. InfoExtractor.__init__(self, downloader)
  1250. def report_download_page(self, playlist_id, pagenum):
  1251. """Report attempt to download playlist page with given number."""
  1252. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1253. def _real_extract(self, url):
  1254. # Extract playlist id
  1255. mobj = re.match(self._VALID_URL, url)
  1256. if mobj is None:
  1257. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1258. return
  1259. # Single video case
  1260. if mobj.group(3) is not None:
  1261. self._downloader.download([mobj.group(3)])
  1262. return
  1263. # Download playlist pages
  1264. # prefix is 'p' as default for playlists but there are other types that need extra care
  1265. playlist_prefix = mobj.group(1)
  1266. if playlist_prefix == 'a':
  1267. playlist_access = 'artist'
  1268. else:
  1269. playlist_prefix = 'p'
  1270. playlist_access = 'view_play_list'
  1271. playlist_id = mobj.group(2)
  1272. video_ids = []
  1273. pagenum = 1
  1274. while True:
  1275. self.report_download_page(playlist_id, pagenum)
  1276. url = self._TEMPLATE_URL % (playlist_access, playlist_prefix, playlist_id, pagenum)
  1277. request = urllib2.Request(url)
  1278. try:
  1279. page = urllib2.urlopen(request).read()
  1280. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1281. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1282. return
  1283. # Extract video identifiers
  1284. ids_in_page = []
  1285. for mobj in re.finditer(self._VIDEO_INDICATOR_TEMPLATE % playlist_id, page):
  1286. if mobj.group(1) not in ids_in_page:
  1287. ids_in_page.append(mobj.group(1))
  1288. video_ids.extend(ids_in_page)
  1289. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1290. break
  1291. pagenum = pagenum + 1
  1292. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1293. playlistend = self._downloader.params.get('playlistend', -1)
  1294. if playlistend == -1:
  1295. video_ids = video_ids[playliststart:]
  1296. else:
  1297. video_ids = video_ids[playliststart:playlistend]
  1298. for id in video_ids:
  1299. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1300. return
  1301. class YoutubeUserIE(InfoExtractor):
  1302. """Information Extractor for YouTube users."""
  1303. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1304. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1305. _GDATA_PAGE_SIZE = 50
  1306. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1307. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1308. IE_NAME = u'youtube:user'
  1309. def __init__(self, downloader=None):
  1310. InfoExtractor.__init__(self, downloader)
  1311. def report_download_page(self, username, start_index):
  1312. """Report attempt to download user page."""
  1313. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1314. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1315. def _real_extract(self, url):
  1316. # Extract username
  1317. mobj = re.match(self._VALID_URL, url)
  1318. if mobj is None:
  1319. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1320. return
  1321. username = mobj.group(1)
  1322. # Download video ids using YouTube Data API. Result size per
  1323. # query is limited (currently to 50 videos) so we need to query
  1324. # page by page until there are no video ids - it means we got
  1325. # all of them.
  1326. video_ids = []
  1327. pagenum = 0
  1328. while True:
  1329. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1330. self.report_download_page(username, start_index)
  1331. request = urllib2.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1332. try:
  1333. page = urllib2.urlopen(request).read()
  1334. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1335. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1336. return
  1337. # Extract video identifiers
  1338. ids_in_page = []
  1339. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1340. if mobj.group(1) not in ids_in_page:
  1341. ids_in_page.append(mobj.group(1))
  1342. video_ids.extend(ids_in_page)
  1343. # A little optimization - if current page is not
  1344. # "full", ie. does not contain PAGE_SIZE video ids then
  1345. # we can assume that this page is the last one - there
  1346. # are no more ids on further pages - no need to query
  1347. # again.
  1348. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1349. break
  1350. pagenum += 1
  1351. all_ids_count = len(video_ids)
  1352. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1353. playlistend = self._downloader.params.get('playlistend', -1)
  1354. if playlistend == -1:
  1355. video_ids = video_ids[playliststart:]
  1356. else:
  1357. video_ids = video_ids[playliststart:playlistend]
  1358. self._downloader.to_screen(u"[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1359. (username, all_ids_count, len(video_ids)))
  1360. for video_id in video_ids:
  1361. self._downloader.download(['http://www.youtube.com/watch?v=%s' % video_id])
  1362. class BlipTVUserIE(InfoExtractor):
  1363. """Information Extractor for blip.tv users."""
  1364. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1365. _PAGE_SIZE = 12
  1366. IE_NAME = u'blip.tv:user'
  1367. def __init__(self, downloader=None):
  1368. InfoExtractor.__init__(self, downloader)
  1369. def report_download_page(self, username, pagenum):
  1370. """Report attempt to download user page."""
  1371. self._downloader.to_screen(u'[%s] user %s: Downloading video ids from page %d' %
  1372. (self.IE_NAME, username, pagenum))
  1373. def _real_extract(self, url):
  1374. # Extract username
  1375. mobj = re.match(self._VALID_URL, url)
  1376. if mobj is None:
  1377. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1378. return
  1379. username = mobj.group(1)
  1380. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1381. request = urllib2.Request(url)
  1382. try:
  1383. page = urllib2.urlopen(request).read().decode('utf-8')
  1384. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1385. page_base = page_base % mobj.group(1)
  1386. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1387. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1388. return
  1389. # Download video ids using BlipTV Ajax calls. Result size per
  1390. # query is limited (currently to 12 videos) so we need to query
  1391. # page by page until there are no video ids - it means we got
  1392. # all of them.
  1393. video_ids = []
  1394. pagenum = 1
  1395. while True:
  1396. self.report_download_page(username, pagenum)
  1397. request = urllib2.Request( page_base + "&page=" + str(pagenum) )
  1398. try:
  1399. page = urllib2.urlopen(request).read().decode('utf-8')
  1400. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1401. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1402. return
  1403. # Extract video identifiers
  1404. ids_in_page = []
  1405. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1406. if mobj.group(1) not in ids_in_page:
  1407. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1408. video_ids.extend(ids_in_page)
  1409. # A little optimization - if current page is not
  1410. # "full", ie. does not contain PAGE_SIZE video ids then
  1411. # we can assume that this page is the last one - there
  1412. # are no more ids on further pages - no need to query
  1413. # again.
  1414. if len(ids_in_page) < self._PAGE_SIZE:
  1415. break
  1416. pagenum += 1
  1417. all_ids_count = len(video_ids)
  1418. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1419. playlistend = self._downloader.params.get('playlistend', -1)
  1420. if playlistend == -1:
  1421. video_ids = video_ids[playliststart:]
  1422. else:
  1423. video_ids = video_ids[playliststart:playlistend]
  1424. self._downloader.to_screen(u"[%s] user %s: Collected %d video ids (downloading %d of them)" %
  1425. (self.IE_NAME, username, all_ids_count, len(video_ids)))
  1426. for video_id in video_ids:
  1427. self._downloader.download([u'http://blip.tv/'+video_id])
  1428. class DepositFilesIE(InfoExtractor):
  1429. """Information extractor for depositfiles.com"""
  1430. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1431. IE_NAME = u'DepositFiles'
  1432. def __init__(self, downloader=None):
  1433. InfoExtractor.__init__(self, downloader)
  1434. def report_download_webpage(self, file_id):
  1435. """Report webpage download."""
  1436. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1437. def report_extraction(self, file_id):
  1438. """Report information extraction."""
  1439. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1440. def _real_extract(self, url):
  1441. file_id = url.split('/')[-1]
  1442. # Rebuild url in english locale
  1443. url = 'http://depositfiles.com/en/files/' + file_id
  1444. # Retrieve file webpage with 'Free download' button pressed
  1445. free_download_indication = { 'gateway_result' : '1' }
  1446. request = urllib2.Request(url, urllib.urlencode(free_download_indication))
  1447. try:
  1448. self.report_download_webpage(file_id)
  1449. webpage = urllib2.urlopen(request).read()
  1450. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1451. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % str(err))
  1452. return
  1453. # Search for the real file URL
  1454. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1455. if (mobj is None) or (mobj.group(1) is None):
  1456. # Try to figure out reason of the error.
  1457. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1458. if (mobj is not None) and (mobj.group(1) is not None):
  1459. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1460. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  1461. else:
  1462. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  1463. return
  1464. file_url = mobj.group(1)
  1465. file_extension = os.path.splitext(file_url)[1][1:]
  1466. # Search for file title
  1467. mobj = re.search(r'<b title="(.*?)">', webpage)
  1468. if mobj is None:
  1469. self._downloader.trouble(u'ERROR: unable to extract title')
  1470. return
  1471. file_title = mobj.group(1).decode('utf-8')
  1472. return [{
  1473. 'id': file_id.decode('utf-8'),
  1474. 'url': file_url.decode('utf-8'),
  1475. 'uploader': u'NA',
  1476. 'upload_date': u'NA',
  1477. 'title': file_title,
  1478. 'ext': file_extension.decode('utf-8'),
  1479. 'format': u'NA',
  1480. 'player_url': None,
  1481. }]
  1482. class FacebookIE(InfoExtractor):
  1483. """Information Extractor for Facebook"""
  1484. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1485. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1486. _NETRC_MACHINE = 'facebook'
  1487. _available_formats = ['video', 'highqual', 'lowqual']
  1488. _video_extensions = {
  1489. 'video': 'mp4',
  1490. 'highqual': 'mp4',
  1491. 'lowqual': 'mp4',
  1492. }
  1493. IE_NAME = u'facebook'
  1494. def __init__(self, downloader=None):
  1495. InfoExtractor.__init__(self, downloader)
  1496. def _reporter(self, message):
  1497. """Add header and report message."""
  1498. self._downloader.to_screen(u'[facebook] %s' % message)
  1499. def report_login(self):
  1500. """Report attempt to log in."""
  1501. self._reporter(u'Logging in')
  1502. def report_video_webpage_download(self, video_id):
  1503. """Report attempt to download video webpage."""
  1504. self._reporter(u'%s: Downloading video webpage' % video_id)
  1505. def report_information_extraction(self, video_id):
  1506. """Report attempt to extract video information."""
  1507. self._reporter(u'%s: Extracting video information' % video_id)
  1508. def _parse_page(self, video_webpage):
  1509. """Extract video information from page"""
  1510. # General data
  1511. data = {'title': r'\("video_title", "(.*?)"\)',
  1512. 'description': r'<div class="datawrap">(.*?)</div>',
  1513. 'owner': r'\("video_owner_name", "(.*?)"\)',
  1514. 'thumbnail': r'\("thumb_url", "(?P<THUMB>.*?)"\)',
  1515. }
  1516. video_info = {}
  1517. for piece in data.keys():
  1518. mobj = re.search(data[piece], video_webpage)
  1519. if mobj is not None:
  1520. video_info[piece] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1521. # Video urls
  1522. video_urls = {}
  1523. for fmt in self._available_formats:
  1524. mobj = re.search(r'\("%s_src\", "(.+?)"\)' % fmt, video_webpage)
  1525. if mobj is not None:
  1526. # URL is in a Javascript segment inside an escaped Unicode format within
  1527. # the generally utf-8 page
  1528. video_urls[fmt] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1529. video_info['video_urls'] = video_urls
  1530. return video_info
  1531. def _real_initialize(self):
  1532. if self._downloader is None:
  1533. return
  1534. useremail = None
  1535. password = None
  1536. downloader_params = self._downloader.params
  1537. # Attempt to use provided username and password or .netrc data
  1538. if downloader_params.get('username', None) is not None:
  1539. useremail = downloader_params['username']
  1540. password = downloader_params['password']
  1541. elif downloader_params.get('usenetrc', False):
  1542. try:
  1543. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1544. if info is not None:
  1545. useremail = info[0]
  1546. password = info[2]
  1547. else:
  1548. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1549. except (IOError, netrc.NetrcParseError), err:
  1550. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  1551. return
  1552. if useremail is None:
  1553. return
  1554. # Log in
  1555. login_form = {
  1556. 'email': useremail,
  1557. 'pass': password,
  1558. 'login': 'Log+In'
  1559. }
  1560. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  1561. try:
  1562. self.report_login()
  1563. login_results = urllib2.urlopen(request).read()
  1564. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1565. self._downloader.to_stderr(u'WARNING: unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1566. return
  1567. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1568. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  1569. return
  1570. def _real_extract(self, url):
  1571. mobj = re.match(self._VALID_URL, url)
  1572. if mobj is None:
  1573. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1574. return
  1575. video_id = mobj.group('ID')
  1576. # Get video webpage
  1577. self.report_video_webpage_download(video_id)
  1578. request = urllib2.Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  1579. try:
  1580. page = urllib2.urlopen(request)
  1581. video_webpage = page.read()
  1582. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1583. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  1584. return
  1585. # Start extracting information
  1586. self.report_information_extraction(video_id)
  1587. # Extract information
  1588. video_info = self._parse_page(video_webpage)
  1589. # uploader
  1590. if 'owner' not in video_info:
  1591. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1592. return
  1593. video_uploader = video_info['owner']
  1594. # title
  1595. if 'title' not in video_info:
  1596. self._downloader.trouble(u'ERROR: unable to extract video title')
  1597. return
  1598. video_title = video_info['title']
  1599. video_title = video_title.decode('utf-8')
  1600. # thumbnail image
  1601. if 'thumbnail' not in video_info:
  1602. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  1603. video_thumbnail = ''
  1604. else:
  1605. video_thumbnail = video_info['thumbnail']
  1606. # upload date
  1607. upload_date = u'NA'
  1608. if 'upload_date' in video_info:
  1609. upload_time = video_info['upload_date']
  1610. timetuple = email.utils.parsedate_tz(upload_time)
  1611. if timetuple is not None:
  1612. try:
  1613. upload_date = time.strftime('%Y%m%d', timetuple[0:9])
  1614. except:
  1615. pass
  1616. # description
  1617. video_description = video_info.get('description', 'No description available.')
  1618. url_map = video_info['video_urls']
  1619. if len(url_map.keys()) > 0:
  1620. # Decide which formats to download
  1621. req_format = self._downloader.params.get('format', None)
  1622. format_limit = self._downloader.params.get('format_limit', None)
  1623. if format_limit is not None and format_limit in self._available_formats:
  1624. format_list = self._available_formats[self._available_formats.index(format_limit):]
  1625. else:
  1626. format_list = self._available_formats
  1627. existing_formats = [x for x in format_list if x in url_map]
  1628. if len(existing_formats) == 0:
  1629. self._downloader.trouble(u'ERROR: no known formats available for video')
  1630. return
  1631. if req_format is None:
  1632. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1633. elif req_format == 'worst':
  1634. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  1635. elif req_format == '-1':
  1636. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1637. else:
  1638. # Specific format
  1639. if req_format not in url_map:
  1640. self._downloader.trouble(u'ERROR: requested format not available')
  1641. return
  1642. video_url_list = [(req_format, url_map[req_format])] # Specific format
  1643. results = []
  1644. for format_param, video_real_url in video_url_list:
  1645. # Extension
  1646. video_extension = self._video_extensions.get(format_param, 'mp4')
  1647. results.append({
  1648. 'id': video_id.decode('utf-8'),
  1649. 'url': video_real_url.decode('utf-8'),
  1650. 'uploader': video_uploader.decode('utf-8'),
  1651. 'upload_date': upload_date,
  1652. 'title': video_title,
  1653. 'ext': video_extension.decode('utf-8'),
  1654. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  1655. 'thumbnail': video_thumbnail.decode('utf-8'),
  1656. 'description': video_description.decode('utf-8'),
  1657. 'player_url': None,
  1658. })
  1659. return results
  1660. class BlipTVIE(InfoExtractor):
  1661. """Information extractor for blip.tv"""
  1662. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  1663. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1664. IE_NAME = u'blip.tv'
  1665. def report_extraction(self, file_id):
  1666. """Report information extraction."""
  1667. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  1668. def report_direct_download(self, title):
  1669. """Report information extraction."""
  1670. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  1671. def _real_extract(self, url):
  1672. mobj = re.match(self._VALID_URL, url)
  1673. if mobj is None:
  1674. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1675. return
  1676. if '?' in url:
  1677. cchar = '&'
  1678. else:
  1679. cchar = '?'
  1680. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1681. request = urllib2.Request(json_url.encode('utf-8'))
  1682. self.report_extraction(mobj.group(1))
  1683. info = None
  1684. try:
  1685. urlh = urllib2.urlopen(request)
  1686. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1687. basename = url.split('/')[-1]
  1688. title,ext = os.path.splitext(basename)
  1689. title = title.decode('UTF-8')
  1690. ext = ext.replace('.', '')
  1691. self.report_direct_download(title)
  1692. info = {
  1693. 'id': title,
  1694. 'url': url,
  1695. 'title': title,
  1696. 'ext': ext,
  1697. 'urlhandle': urlh
  1698. }
  1699. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1700. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  1701. return
  1702. if info is None: # Regular URL
  1703. try:
  1704. json_code = urlh.read()
  1705. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1706. self._downloader.trouble(u'ERROR: unable to read video info webpage: %s' % str(err))
  1707. return
  1708. try:
  1709. json_data = json.loads(json_code)
  1710. if 'Post' in json_data:
  1711. data = json_data['Post']
  1712. else:
  1713. data = json_data
  1714. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1715. video_url = data['media']['url']
  1716. umobj = re.match(self._URL_EXT, video_url)
  1717. if umobj is None:
  1718. raise ValueError('Can not determine filename extension')
  1719. ext = umobj.group(1)
  1720. info = {
  1721. 'id': data['item_id'],
  1722. 'url': video_url,
  1723. 'uploader': data['display_name'],
  1724. 'upload_date': upload_date,
  1725. 'title': data['title'],
  1726. 'ext': ext,
  1727. 'format': data['media']['mimeType'],
  1728. 'thumbnail': data['thumbnailUrl'],
  1729. 'description': data['description'],
  1730. 'player_url': data['embedUrl']
  1731. }
  1732. except (ValueError,KeyError), err:
  1733. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  1734. return
  1735. std_headers['User-Agent'] = 'iTunes/10.6.1'
  1736. return [info]
  1737. class MyVideoIE(InfoExtractor):
  1738. """Information Extractor for myvideo.de."""
  1739. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1740. IE_NAME = u'myvideo'
  1741. def __init__(self, downloader=None):
  1742. InfoExtractor.__init__(self, downloader)
  1743. def report_download_webpage(self, video_id):
  1744. """Report webpage download."""
  1745. self._downloader.to_screen(u'[myvideo] %s: Downloading webpage' % video_id)
  1746. def report_extraction(self, video_id):
  1747. """Report information extraction."""
  1748. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  1749. def _real_extract(self,url):
  1750. mobj = re.match(self._VALID_URL, url)
  1751. if mobj is None:
  1752. self._download.trouble(u'ERROR: invalid URL: %s' % url)
  1753. return
  1754. video_id = mobj.group(1)
  1755. # Get video webpage
  1756. request = urllib2.Request('http://www.myvideo.de/watch/%s' % video_id)
  1757. try:
  1758. self.report_download_webpage(video_id)
  1759. webpage = urllib2.urlopen(request).read()
  1760. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1761. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1762. return
  1763. self.report_extraction(video_id)
  1764. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/[^.]+\.jpg\' />',
  1765. webpage)
  1766. if mobj is None:
  1767. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1768. return
  1769. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  1770. mobj = re.search('<title>([^<]+)</title>', webpage)
  1771. if mobj is None:
  1772. self._downloader.trouble(u'ERROR: unable to extract title')
  1773. return
  1774. video_title = mobj.group(1)
  1775. return [{
  1776. 'id': video_id,
  1777. 'url': video_url,
  1778. 'uploader': u'NA',
  1779. 'upload_date': u'NA',
  1780. 'title': video_title,
  1781. 'ext': u'flv',
  1782. 'format': u'NA',
  1783. 'player_url': None,
  1784. }]
  1785. class ComedyCentralIE(InfoExtractor):
  1786. """Information extractor for The Daily Show and Colbert Report """
  1787. _VALID_URL = r'^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport))|(https?://)?(www\.)?(?P<showname>thedailyshow|colbertnation)\.com/full-episodes/(?P<episode>.*)$'
  1788. IE_NAME = u'comedycentral'
  1789. def report_extraction(self, episode_id):
  1790. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  1791. def report_config_download(self, episode_id):
  1792. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration' % episode_id)
  1793. def report_index_download(self, episode_id):
  1794. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  1795. def report_player_url(self, episode_id):
  1796. self._downloader.to_screen(u'[comedycentral] %s: Determining player URL' % episode_id)
  1797. def _real_extract(self, url):
  1798. mobj = re.match(self._VALID_URL, url)
  1799. if mobj is None:
  1800. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1801. return
  1802. if mobj.group('shortname'):
  1803. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  1804. url = u'http://www.thedailyshow.com/full-episodes/'
  1805. else:
  1806. url = u'http://www.colbertnation.com/full-episodes/'
  1807. mobj = re.match(self._VALID_URL, url)
  1808. assert mobj is not None
  1809. dlNewest = not mobj.group('episode')
  1810. if dlNewest:
  1811. epTitle = mobj.group('showname')
  1812. else:
  1813. epTitle = mobj.group('episode')
  1814. req = urllib2.Request(url)
  1815. self.report_extraction(epTitle)
  1816. try:
  1817. htmlHandle = urllib2.urlopen(req)
  1818. html = htmlHandle.read()
  1819. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1820. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % unicode(err))
  1821. return
  1822. if dlNewest:
  1823. url = htmlHandle.geturl()
  1824. mobj = re.match(self._VALID_URL, url)
  1825. if mobj is None:
  1826. self._downloader.trouble(u'ERROR: Invalid redirected URL: ' + url)
  1827. return
  1828. if mobj.group('episode') == '':
  1829. self._downloader.trouble(u'ERROR: Redirected URL is still not specific: ' + url)
  1830. return
  1831. epTitle = mobj.group('episode')
  1832. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*episode.*?:.*?))"', html)
  1833. if len(mMovieParams) == 0:
  1834. self._downloader.trouble(u'ERROR: unable to find Flash URL in webpage ' + url)
  1835. return
  1836. playerUrl_raw = mMovieParams[0][0]
  1837. self.report_player_url(epTitle)
  1838. try:
  1839. urlHandle = urllib2.urlopen(playerUrl_raw)
  1840. playerUrl = urlHandle.geturl()
  1841. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1842. self._downloader.trouble(u'ERROR: unable to find out player URL: ' + unicode(err))
  1843. return
  1844. uri = mMovieParams[0][1]
  1845. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + urllib.urlencode({'uri': uri})
  1846. self.report_index_download(epTitle)
  1847. try:
  1848. indexXml = urllib2.urlopen(indexUrl).read()
  1849. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1850. self._downloader.trouble(u'ERROR: unable to download episode index: ' + unicode(err))
  1851. return
  1852. results = []
  1853. idoc = xml.etree.ElementTree.fromstring(indexXml)
  1854. itemEls = idoc.findall('.//item')
  1855. for itemEl in itemEls:
  1856. mediaId = itemEl.findall('./guid')[0].text
  1857. shortMediaId = mediaId.split(':')[-1]
  1858. showId = mediaId.split(':')[-2].replace('.com', '')
  1859. officialTitle = itemEl.findall('./title')[0].text
  1860. officialDate = itemEl.findall('./pubDate')[0].text
  1861. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  1862. urllib.urlencode({'uri': mediaId}))
  1863. configReq = urllib2.Request(configUrl)
  1864. self.report_config_download(epTitle)
  1865. try:
  1866. configXml = urllib2.urlopen(configReq).read()
  1867. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1868. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % unicode(err))
  1869. return
  1870. cdoc = xml.etree.ElementTree.fromstring(configXml)
  1871. turls = []
  1872. for rendition in cdoc.findall('.//rendition'):
  1873. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  1874. turls.append(finfo)
  1875. if len(turls) == 0:
  1876. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId + ': No videos found')
  1877. continue
  1878. # For now, just pick the highest bitrate
  1879. format,video_url = turls[-1]
  1880. effTitle = showId + u'-' + epTitle
  1881. info = {
  1882. 'id': shortMediaId,
  1883. 'url': video_url,
  1884. 'uploader': showId,
  1885. 'upload_date': officialDate,
  1886. 'title': effTitle,
  1887. 'ext': 'mp4',
  1888. 'format': format,
  1889. 'thumbnail': None,
  1890. 'description': officialTitle,
  1891. 'player_url': playerUrl
  1892. }
  1893. results.append(info)
  1894. return results
  1895. class EscapistIE(InfoExtractor):
  1896. """Information extractor for The Escapist """
  1897. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  1898. IE_NAME = u'escapist'
  1899. def report_extraction(self, showName):
  1900. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  1901. def report_config_download(self, showName):
  1902. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  1903. def _real_extract(self, url):
  1904. mobj = re.match(self._VALID_URL, url)
  1905. if mobj is None:
  1906. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1907. return
  1908. showName = mobj.group('showname')
  1909. videoId = mobj.group('episode')
  1910. self.report_extraction(showName)
  1911. try:
  1912. webPage = urllib2.urlopen(url)
  1913. webPageBytes = webPage.read()
  1914. m = re.match(r'text/html; charset="?([^"]+)"?', webPage.headers['Content-Type'])
  1915. webPage = webPageBytes.decode(m.group(1) if m else 'utf-8')
  1916. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1917. self._downloader.trouble(u'ERROR: unable to download webpage: ' + unicode(err))
  1918. return
  1919. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  1920. description = unescapeHTML(descMatch.group(1))
  1921. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  1922. imgUrl = unescapeHTML(imgMatch.group(1))
  1923. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  1924. playerUrl = unescapeHTML(playerUrlMatch.group(1))
  1925. configUrlMatch = re.search('config=(.*)$', playerUrl)
  1926. configUrl = urllib2.unquote(configUrlMatch.group(1))
  1927. self.report_config_download(showName)
  1928. try:
  1929. configJSON = urllib2.urlopen(configUrl).read()
  1930. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1931. self._downloader.trouble(u'ERROR: unable to download configuration: ' + unicode(err))
  1932. return
  1933. # Technically, it's JavaScript, not JSON
  1934. configJSON = configJSON.replace("'", '"')
  1935. try:
  1936. config = json.loads(configJSON)
  1937. except (ValueError,), err:
  1938. self._downloader.trouble(u'ERROR: Invalid JSON in configuration file: ' + unicode(err))
  1939. return
  1940. playlist = config['playlist']
  1941. videoUrl = playlist[1]['url']
  1942. info = {
  1943. 'id': videoId,
  1944. 'url': videoUrl,
  1945. 'uploader': showName,
  1946. 'upload_date': None,
  1947. 'title': showName,
  1948. 'ext': 'flv',
  1949. 'format': 'flv',
  1950. 'thumbnail': imgUrl,
  1951. 'description': description,
  1952. 'player_url': playerUrl,
  1953. }
  1954. return [info]
  1955. class CollegeHumorIE(InfoExtractor):
  1956. """Information extractor for collegehumor.com"""
  1957. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  1958. IE_NAME = u'collegehumor'
  1959. def report_webpage(self, video_id):
  1960. """Report information extraction."""
  1961. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  1962. def report_extraction(self, video_id):
  1963. """Report information extraction."""
  1964. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  1965. def _real_extract(self, url):
  1966. mobj = re.match(self._VALID_URL, url)
  1967. if mobj is None:
  1968. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1969. return
  1970. video_id = mobj.group('videoid')
  1971. self.report_webpage(video_id)
  1972. request = urllib2.Request(url)
  1973. try:
  1974. webpage = urllib2.urlopen(request).read()
  1975. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1976. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  1977. return
  1978. m = re.search(r'id="video:(?P<internalvideoid>[0-9]+)"', webpage)
  1979. if m is None:
  1980. self._downloader.trouble(u'ERROR: Cannot extract internal video ID')
  1981. return
  1982. internal_video_id = m.group('internalvideoid')
  1983. info = {
  1984. 'id': video_id,
  1985. 'internal_id': internal_video_id,
  1986. }
  1987. self.report_extraction(video_id)
  1988. xmlUrl = 'http://www.collegehumor.com/moogaloop/video:' + internal_video_id
  1989. try:
  1990. metaXml = urllib2.urlopen(xmlUrl).read()
  1991. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1992. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % str(err))
  1993. return
  1994. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  1995. try:
  1996. videoNode = mdoc.findall('./video')[0]
  1997. info['description'] = videoNode.findall('./description')[0].text
  1998. info['title'] = videoNode.findall('./caption')[0].text
  1999. info['url'] = videoNode.findall('./file')[0].text
  2000. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2001. info['ext'] = info['url'].rpartition('.')[2]
  2002. info['format'] = info['ext']
  2003. except IndexError:
  2004. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2005. return
  2006. return [info]
  2007. class XVideosIE(InfoExtractor):
  2008. """Information extractor for xvideos.com"""
  2009. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2010. IE_NAME = u'xvideos'
  2011. def report_webpage(self, video_id):
  2012. """Report information extraction."""
  2013. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2014. def report_extraction(self, video_id):
  2015. """Report information extraction."""
  2016. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2017. def _real_extract(self, url):
  2018. mobj = re.match(self._VALID_URL, url)
  2019. if mobj is None:
  2020. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2021. return
  2022. video_id = mobj.group(1).decode('utf-8')
  2023. self.report_webpage(video_id)
  2024. request = urllib2.Request(r'http://www.xvideos.com/video' + video_id)
  2025. try:
  2026. webpage = urllib2.urlopen(request).read()
  2027. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2028. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2029. return
  2030. self.report_extraction(video_id)
  2031. # Extract video URL
  2032. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2033. if mobj is None:
  2034. self._downloader.trouble(u'ERROR: unable to extract video url')
  2035. return
  2036. video_url = urllib2.unquote(mobj.group(1).decode('utf-8'))
  2037. # Extract title
  2038. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2039. if mobj is None:
  2040. self._downloader.trouble(u'ERROR: unable to extract video title')
  2041. return
  2042. video_title = mobj.group(1).decode('utf-8')
  2043. # Extract video thumbnail
  2044. mobj = re.search(r'http://(?:img.*?\.)xvideos.com/videos/thumbs/[a-fA-F0-9]+/[a-fA-F0-9]+/[a-fA-F0-9]+/[a-fA-F0-9]+/([a-fA-F0-9.]+jpg)', webpage)
  2045. if mobj is None:
  2046. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2047. return
  2048. video_thumbnail = mobj.group(0).decode('utf-8')
  2049. info = {
  2050. 'id': video_id,
  2051. 'url': video_url,
  2052. 'uploader': None,
  2053. 'upload_date': None,
  2054. 'title': video_title,
  2055. 'ext': 'flv',
  2056. 'format': 'flv',
  2057. 'thumbnail': video_thumbnail,
  2058. 'description': None,
  2059. 'player_url': None,
  2060. }
  2061. return [info]
  2062. class SoundcloudIE(InfoExtractor):
  2063. """Information extractor for soundcloud.com
  2064. To access the media, the uid of the song and a stream token
  2065. must be extracted from the page source and the script must make
  2066. a request to media.soundcloud.com/crossdomain.xml. Then
  2067. the media can be grabbed by requesting from an url composed
  2068. of the stream token and uid
  2069. """
  2070. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2071. IE_NAME = u'soundcloud'
  2072. def __init__(self, downloader=None):
  2073. InfoExtractor.__init__(self, downloader)
  2074. def report_webpage(self, video_id):
  2075. """Report information extraction."""
  2076. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2077. def report_extraction(self, video_id):
  2078. """Report information extraction."""
  2079. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2080. def _real_extract(self, url):
  2081. mobj = re.match(self._VALID_URL, url)
  2082. if mobj is None:
  2083. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2084. return
  2085. # extract uploader (which is in the url)
  2086. uploader = mobj.group(1).decode('utf-8')
  2087. # extract simple title (uploader + slug of song title)
  2088. slug_title = mobj.group(2).decode('utf-8')
  2089. simple_title = uploader + u'-' + slug_title
  2090. self.report_webpage('%s/%s' % (uploader, slug_title))
  2091. request = urllib2.Request('http://soundcloud.com/%s/%s' % (uploader, slug_title))
  2092. try:
  2093. webpage = urllib2.urlopen(request).read()
  2094. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2095. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2096. return
  2097. self.report_extraction('%s/%s' % (uploader, slug_title))
  2098. # extract uid and stream token that soundcloud hands out for access
  2099. mobj = re.search('"uid":"([\w\d]+?)".*?stream_token=([\w\d]+)', webpage)
  2100. if mobj:
  2101. video_id = mobj.group(1)
  2102. stream_token = mobj.group(2)
  2103. # extract unsimplified title
  2104. mobj = re.search('"title":"(.*?)",', webpage)
  2105. if mobj:
  2106. title = mobj.group(1).decode('utf-8')
  2107. else:
  2108. title = simple_title
  2109. # construct media url (with uid/token)
  2110. mediaURL = "http://media.soundcloud.com/stream/%s?stream_token=%s"
  2111. mediaURL = mediaURL % (video_id, stream_token)
  2112. # description
  2113. description = u'No description available'
  2114. mobj = re.search('track-description-value"><p>(.*?)</p>', webpage)
  2115. if mobj:
  2116. description = mobj.group(1)
  2117. # upload date
  2118. upload_date = None
  2119. mobj = re.search("pretty-date'>on ([\w]+ [\d]+, [\d]+ \d+:\d+)</abbr></h2>", webpage)
  2120. if mobj:
  2121. try:
  2122. upload_date = datetime.datetime.strptime(mobj.group(1), '%B %d, %Y %H:%M').strftime('%Y%m%d')
  2123. except Exception, e:
  2124. self._downloader.to_stderr(str(e))
  2125. # for soundcloud, a request to a cross domain is required for cookies
  2126. request = urllib2.Request('http://media.soundcloud.com/crossdomain.xml', std_headers)
  2127. return [{
  2128. 'id': video_id.decode('utf-8'),
  2129. 'url': mediaURL,
  2130. 'uploader': uploader.decode('utf-8'),
  2131. 'upload_date': upload_date,
  2132. 'title': title,
  2133. 'ext': u'mp3',
  2134. 'format': u'NA',
  2135. 'player_url': None,
  2136. 'description': description.decode('utf-8')
  2137. }]
  2138. class InfoQIE(InfoExtractor):
  2139. """Information extractor for infoq.com"""
  2140. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2141. IE_NAME = u'infoq'
  2142. def report_webpage(self, video_id):
  2143. """Report information extraction."""
  2144. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2145. def report_extraction(self, video_id):
  2146. """Report information extraction."""
  2147. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2148. def _real_extract(self, url):
  2149. mobj = re.match(self._VALID_URL, url)
  2150. if mobj is None:
  2151. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2152. return
  2153. self.report_webpage(url)
  2154. request = urllib2.Request(url)
  2155. try:
  2156. webpage = urllib2.urlopen(request).read()
  2157. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2158. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2159. return
  2160. self.report_extraction(url)
  2161. # Extract video URL
  2162. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  2163. if mobj is None:
  2164. self._downloader.trouble(u'ERROR: unable to extract video url')
  2165. return
  2166. video_url = 'rtmpe://video.infoq.com/cfx/st/' + urllib2.unquote(mobj.group(1).decode('base64'))
  2167. # Extract title
  2168. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  2169. if mobj is None:
  2170. self._downloader.trouble(u'ERROR: unable to extract video title')
  2171. return
  2172. video_title = mobj.group(1).decode('utf-8')
  2173. # Extract description
  2174. video_description = u'No description available.'
  2175. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  2176. if mobj is not None:
  2177. video_description = mobj.group(1).decode('utf-8')
  2178. video_filename = video_url.split('/')[-1]
  2179. video_id, extension = video_filename.split('.')
  2180. info = {
  2181. 'id': video_id,
  2182. 'url': video_url,
  2183. 'uploader': None,
  2184. 'upload_date': None,
  2185. 'title': video_title,
  2186. 'ext': extension,
  2187. 'format': extension, # Extension is always(?) mp4, but seems to be flv
  2188. 'thumbnail': None,
  2189. 'description': video_description,
  2190. 'player_url': None,
  2191. }
  2192. return [info]
  2193. class MixcloudIE(InfoExtractor):
  2194. """Information extractor for www.mixcloud.com"""
  2195. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2196. IE_NAME = u'mixcloud'
  2197. def __init__(self, downloader=None):
  2198. InfoExtractor.__init__(self, downloader)
  2199. def report_download_json(self, file_id):
  2200. """Report JSON download."""
  2201. self._downloader.to_screen(u'[%s] Downloading json' % self.IE_NAME)
  2202. def report_extraction(self, file_id):
  2203. """Report information extraction."""
  2204. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2205. def get_urls(self, jsonData, fmt, bitrate='best'):
  2206. """Get urls from 'audio_formats' section in json"""
  2207. file_url = None
  2208. try:
  2209. bitrate_list = jsonData[fmt]
  2210. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2211. bitrate = max(bitrate_list) # select highest
  2212. url_list = jsonData[fmt][bitrate]
  2213. except TypeError: # we have no bitrate info.
  2214. url_list = jsonData[fmt]
  2215. return url_list
  2216. def check_urls(self, url_list):
  2217. """Returns 1st active url from list"""
  2218. for url in url_list:
  2219. try:
  2220. urllib2.urlopen(url)
  2221. return url
  2222. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2223. url = None
  2224. return None
  2225. def _print_formats(self, formats):
  2226. print 'Available formats:'
  2227. for fmt in formats.keys():
  2228. for b in formats[fmt]:
  2229. try:
  2230. ext = formats[fmt][b][0]
  2231. print '%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1])
  2232. except TypeError: # we have no bitrate info
  2233. ext = formats[fmt][0]
  2234. print '%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1])
  2235. break
  2236. def _real_extract(self, url):
  2237. mobj = re.match(self._VALID_URL, url)
  2238. if mobj is None:
  2239. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2240. return
  2241. # extract uploader & filename from url
  2242. uploader = mobj.group(1).decode('utf-8')
  2243. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2244. # construct API request
  2245. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2246. # retrieve .json file with links to files
  2247. request = urllib2.Request(file_url)
  2248. try:
  2249. self.report_download_json(file_url)
  2250. jsonData = urllib2.urlopen(request).read()
  2251. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2252. self._downloader.trouble(u'ERROR: Unable to retrieve file: %s' % str(err))
  2253. return
  2254. # parse JSON
  2255. json_data = json.loads(jsonData)
  2256. player_url = json_data['player_swf_url']
  2257. formats = dict(json_data['audio_formats'])
  2258. req_format = self._downloader.params.get('format', None)
  2259. bitrate = None
  2260. if self._downloader.params.get('listformats', None):
  2261. self._print_formats(formats)
  2262. return
  2263. if req_format is None or req_format == 'best':
  2264. for format_param in formats.keys():
  2265. url_list = self.get_urls(formats, format_param)
  2266. # check urls
  2267. file_url = self.check_urls(url_list)
  2268. if file_url is not None:
  2269. break # got it!
  2270. else:
  2271. if req_format not in formats.keys():
  2272. self._downloader.trouble(u'ERROR: format is not available')
  2273. return
  2274. url_list = self.get_urls(formats, req_format)
  2275. file_url = self.check_urls(url_list)
  2276. format_param = req_format
  2277. return [{
  2278. 'id': file_id.decode('utf-8'),
  2279. 'url': file_url.decode('utf-8'),
  2280. 'uploader': uploader.decode('utf-8'),
  2281. 'upload_date': u'NA',
  2282. 'title': json_data['name'],
  2283. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2284. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2285. 'thumbnail': json_data['thumbnail_url'],
  2286. 'description': json_data['description'],
  2287. 'player_url': player_url.decode('utf-8'),
  2288. }]
  2289. class StanfordOpenClassroomIE(InfoExtractor):
  2290. """Information extractor for Stanford's Open ClassRoom"""
  2291. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2292. IE_NAME = u'stanfordoc'
  2293. def report_download_webpage(self, objid):
  2294. """Report information extraction."""
  2295. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, objid))
  2296. def report_extraction(self, video_id):
  2297. """Report information extraction."""
  2298. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2299. def _real_extract(self, url):
  2300. mobj = re.match(self._VALID_URL, url)
  2301. if mobj is None:
  2302. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2303. return
  2304. if mobj.group('course') and mobj.group('video'): # A specific video
  2305. course = mobj.group('course')
  2306. video = mobj.group('video')
  2307. info = {
  2308. 'id': course + '_' + video,
  2309. }
  2310. self.report_extraction(info['id'])
  2311. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2312. xmlUrl = baseUrl + video + '.xml'
  2313. try:
  2314. metaXml = urllib2.urlopen(xmlUrl).read()
  2315. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2316. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % unicode(err))
  2317. return
  2318. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2319. try:
  2320. info['title'] = mdoc.findall('./title')[0].text
  2321. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2322. except IndexError:
  2323. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2324. return
  2325. info['ext'] = info['url'].rpartition('.')[2]
  2326. info['format'] = info['ext']
  2327. return [info]
  2328. elif mobj.group('course'): # A course page
  2329. course = mobj.group('course')
  2330. info = {
  2331. 'id': course,
  2332. 'type': 'playlist',
  2333. }
  2334. self.report_download_webpage(info['id'])
  2335. try:
  2336. coursepage = urllib2.urlopen(url).read()
  2337. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2338. self._downloader.trouble(u'ERROR: unable to download course info page: ' + unicode(err))
  2339. return
  2340. m = re.search('<h1>([^<]+)</h1>', coursepage)
  2341. if m:
  2342. info['title'] = unescapeHTML(m.group(1))
  2343. else:
  2344. info['title'] = info['id']
  2345. m = re.search('<description>([^<]+)</description>', coursepage)
  2346. if m:
  2347. info['description'] = unescapeHTML(m.group(1))
  2348. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2349. info['list'] = [
  2350. {
  2351. 'type': 'reference',
  2352. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2353. }
  2354. for vpage in links]
  2355. results = []
  2356. for entry in info['list']:
  2357. assert entry['type'] == 'reference'
  2358. results += self.extract(entry['url'])
  2359. return results
  2360. else: # Root page
  2361. info = {
  2362. 'id': 'Stanford OpenClassroom',
  2363. 'type': 'playlist',
  2364. }
  2365. self.report_download_webpage(info['id'])
  2366. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2367. try:
  2368. rootpage = urllib2.urlopen(rootURL).read()
  2369. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2370. self._downloader.trouble(u'ERROR: unable to download course info page: ' + unicode(err))
  2371. return
  2372. info['title'] = info['id']
  2373. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2374. info['list'] = [
  2375. {
  2376. 'type': 'reference',
  2377. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2378. }
  2379. for cpage in links]
  2380. results = []
  2381. for entry in info['list']:
  2382. assert entry['type'] == 'reference'
  2383. results += self.extract(entry['url'])
  2384. return results
  2385. class MTVIE(InfoExtractor):
  2386. """Information extractor for MTV.com"""
  2387. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2388. IE_NAME = u'mtv'
  2389. def report_webpage(self, video_id):
  2390. """Report information extraction."""
  2391. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2392. def report_extraction(self, video_id):
  2393. """Report information extraction."""
  2394. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2395. def _real_extract(self, url):
  2396. mobj = re.match(self._VALID_URL, url)
  2397. if mobj is None:
  2398. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2399. return
  2400. if not mobj.group('proto'):
  2401. url = 'http://' + url
  2402. video_id = mobj.group('videoid')
  2403. self.report_webpage(video_id)
  2404. request = urllib2.Request(url)
  2405. try:
  2406. webpage = urllib2.urlopen(request).read()
  2407. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2408. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2409. return
  2410. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  2411. if mobj is None:
  2412. self._downloader.trouble(u'ERROR: unable to extract song name')
  2413. return
  2414. song_name = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2415. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  2416. if mobj is None:
  2417. self._downloader.trouble(u'ERROR: unable to extract performer')
  2418. return
  2419. performer = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2420. video_title = performer + ' - ' + song_name
  2421. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  2422. if mobj is None:
  2423. self._downloader.trouble(u'ERROR: unable to mtvn_uri')
  2424. return
  2425. mtvn_uri = mobj.group(1)
  2426. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  2427. if mobj is None:
  2428. self._downloader.trouble(u'ERROR: unable to extract content id')
  2429. return
  2430. content_id = mobj.group(1)
  2431. videogen_url = 'http://www.mtv.com/player/includes/mediaGen.jhtml?uri=' + mtvn_uri + '&id=' + content_id + '&vid=' + video_id + '&ref=www.mtvn.com&viewUri=' + mtvn_uri
  2432. self.report_extraction(video_id)
  2433. request = urllib2.Request(videogen_url)
  2434. try:
  2435. metadataXml = urllib2.urlopen(request).read()
  2436. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2437. self._downloader.trouble(u'ERROR: unable to download video metadata: %s' % str(err))
  2438. return
  2439. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2440. renditions = mdoc.findall('.//rendition')
  2441. # For now, always pick the highest quality.
  2442. rendition = renditions[-1]
  2443. try:
  2444. _,_,ext = rendition.attrib['type'].partition('/')
  2445. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2446. video_url = rendition.find('./src').text
  2447. except KeyError:
  2448. self._downloader.trouble('Invalid rendition field.')
  2449. return
  2450. info = {
  2451. 'id': video_id,
  2452. 'url': video_url,
  2453. 'uploader': performer,
  2454. 'title': video_title,
  2455. 'ext': ext,
  2456. 'format': format,
  2457. }
  2458. return [info]