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.

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