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.

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