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.

2987 lines
115 KiB

12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import base64
  5. import datetime
  6. import itertools
  7. import netrc
  8. import os
  9. import re
  10. import socket
  11. import time
  12. import email.utils
  13. import xml.etree.ElementTree
  14. import random
  15. import math
  16. import operator
  17. import hashlib
  18. import binascii
  19. import urllib
  20. from .utils import *
  21. from .extractor.common import InfoExtractor, SearchInfoExtractor
  22. from .extractor.ard import ARDIE
  23. from .extractor.arte import ArteTvIE
  24. from .extractor.dailymotion import DailymotionIE
  25. from .extractor.gametrailers import GametrailersIE
  26. from .extractor.metacafe import MetacafeIE
  27. from .extractor.statigram import StatigramIE
  28. from .extractor.photobucket import PhotobucketIE
  29. from .extractor.vimeo import VimeoIE
  30. from .extractor.yahoo import YahooIE
  31. from .extractor.youtube import YoutubeIE, YoutubePlaylistIE, YoutubeSearchIE, YoutubeUserIE, YoutubeChannelIE
  32. from .extractor.zdf import ZDFIE
  33. class GenericIE(InfoExtractor):
  34. """Generic last-resort information extractor."""
  35. _VALID_URL = r'.*'
  36. IE_NAME = u'generic'
  37. def report_download_webpage(self, video_id):
  38. """Report webpage download."""
  39. if not self._downloader.params.get('test', False):
  40. self._downloader.report_warning(u'Falling back on generic information extractor.')
  41. super(GenericIE, self).report_download_webpage(video_id)
  42. def report_following_redirect(self, new_url):
  43. """Report information extraction."""
  44. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  45. def _test_redirect(self, url):
  46. """Check if it is a redirect, like url shorteners, in case return the new url."""
  47. class HeadRequest(compat_urllib_request.Request):
  48. def get_method(self):
  49. return "HEAD"
  50. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  51. """
  52. Subclass the HTTPRedirectHandler to make it use our
  53. HeadRequest also on the redirected URL
  54. """
  55. def redirect_request(self, req, fp, code, msg, headers, newurl):
  56. if code in (301, 302, 303, 307):
  57. newurl = newurl.replace(' ', '%20')
  58. newheaders = dict((k,v) for k,v in req.headers.items()
  59. if k.lower() not in ("content-length", "content-type"))
  60. return HeadRequest(newurl,
  61. headers=newheaders,
  62. origin_req_host=req.get_origin_req_host(),
  63. unverifiable=True)
  64. else:
  65. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  66. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  67. """
  68. Fallback to GET if HEAD is not allowed (405 HTTP error)
  69. """
  70. def http_error_405(self, req, fp, code, msg, headers):
  71. fp.read()
  72. fp.close()
  73. newheaders = dict((k,v) for k,v in req.headers.items()
  74. if k.lower() not in ("content-length", "content-type"))
  75. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  76. headers=newheaders,
  77. origin_req_host=req.get_origin_req_host(),
  78. unverifiable=True))
  79. # Build our opener
  80. opener = compat_urllib_request.OpenerDirector()
  81. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  82. HTTPMethodFallback, HEADRedirectHandler,
  83. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  84. opener.add_handler(handler())
  85. response = opener.open(HeadRequest(url))
  86. if response is None:
  87. raise ExtractorError(u'Invalid URL protocol')
  88. new_url = response.geturl()
  89. if url == new_url:
  90. return False
  91. self.report_following_redirect(new_url)
  92. return new_url
  93. def _real_extract(self, url):
  94. new_url = self._test_redirect(url)
  95. if new_url: return [self.url_result(new_url)]
  96. video_id = url.split('/')[-1]
  97. try:
  98. webpage = self._download_webpage(url, video_id)
  99. except ValueError as err:
  100. # since this is the last-resort InfoExtractor, if
  101. # this error is thrown, it'll be thrown here
  102. raise ExtractorError(u'Invalid URL: %s' % url)
  103. self.report_extraction(video_id)
  104. # Start with something easy: JW Player in SWFObject
  105. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  106. if mobj is None:
  107. # Broaden the search a little bit
  108. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  109. if mobj is None:
  110. # Broaden the search a little bit: JWPlayer JS loader
  111. mobj = re.search(r'[^A-Za-z0-9]?file:\s*["\'](http[^\'"&]*)', webpage)
  112. if mobj is None:
  113. # Try to find twitter cards info
  114. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  115. if mobj is None:
  116. # We look for Open Graph info:
  117. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  118. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  119. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  120. if m_video_type is not None:
  121. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  122. if mobj is None:
  123. raise ExtractorError(u'Invalid URL: %s' % url)
  124. # It's possible that one of the regexes
  125. # matched, but returned an empty group:
  126. if mobj.group(1) is None:
  127. raise ExtractorError(u'Invalid URL: %s' % url)
  128. video_url = compat_urllib_parse.unquote(mobj.group(1))
  129. video_id = os.path.basename(video_url)
  130. # here's a fun little line of code for you:
  131. video_extension = os.path.splitext(video_id)[1][1:]
  132. video_id = os.path.splitext(video_id)[0]
  133. # it's tempting to parse this further, but you would
  134. # have to take into account all the variations like
  135. # Video Title - Site Name
  136. # Site Name | Video Title
  137. # Video Title - Tagline | Site Name
  138. # and so on and so forth; it's just not practical
  139. video_title = self._html_search_regex(r'<title>(.*)</title>',
  140. webpage, u'video title')
  141. # video uploader is domain name
  142. video_uploader = self._search_regex(r'(?:https?://)?([^/]*)/.*',
  143. url, u'video uploader')
  144. return [{
  145. 'id': video_id,
  146. 'url': video_url,
  147. 'uploader': video_uploader,
  148. 'upload_date': None,
  149. 'title': video_title,
  150. 'ext': video_extension,
  151. }]
  152. class GoogleSearchIE(SearchInfoExtractor):
  153. """Information Extractor for Google Video search queries."""
  154. _MORE_PAGES_INDICATOR = r'id="pnnext" class="pn"'
  155. _MAX_RESULTS = 1000
  156. IE_NAME = u'video.google:search'
  157. _SEARCH_KEY = 'gvsearch'
  158. def _get_n_results(self, query, n):
  159. """Get a specified number of results for a query"""
  160. res = {
  161. '_type': 'playlist',
  162. 'id': query,
  163. 'entries': []
  164. }
  165. for pagenum in itertools.count(1):
  166. result_url = u'http://www.google.com/search?tbm=vid&q=%s&start=%s&hl=en' % (compat_urllib_parse.quote_plus(query), pagenum*10)
  167. webpage = self._download_webpage(result_url, u'gvsearch:' + query,
  168. note='Downloading result page ' + str(pagenum))
  169. for mobj in re.finditer(r'<h3 class="r"><a href="([^"]+)"', webpage):
  170. e = {
  171. '_type': 'url',
  172. 'url': mobj.group(1)
  173. }
  174. res['entries'].append(e)
  175. if (pagenum * 10 > n) or not re.search(self._MORE_PAGES_INDICATOR, webpage):
  176. return res
  177. class YahooSearchIE(SearchInfoExtractor):
  178. """Information Extractor for Yahoo! Video search queries."""
  179. _MAX_RESULTS = 1000
  180. IE_NAME = u'screen.yahoo:search'
  181. _SEARCH_KEY = 'yvsearch'
  182. def _get_n_results(self, query, n):
  183. """Get a specified number of results for a query"""
  184. res = {
  185. '_type': 'playlist',
  186. 'id': query,
  187. 'entries': []
  188. }
  189. for pagenum in itertools.count(0):
  190. result_url = u'http://video.search.yahoo.com/search/?p=%s&fr=screen&o=js&gs=0&b=%d' % (compat_urllib_parse.quote_plus(query), pagenum * 30)
  191. webpage = self._download_webpage(result_url, query,
  192. note='Downloading results page '+str(pagenum+1))
  193. info = json.loads(webpage)
  194. m = info[u'm']
  195. results = info[u'results']
  196. for (i, r) in enumerate(results):
  197. if (pagenum * 30) +i >= n:
  198. break
  199. mobj = re.search(r'(?P<url>screen\.yahoo\.com/.*?-\d*?\.html)"', r)
  200. e = self.url_result('http://' + mobj.group('url'), 'Yahoo')
  201. res['entries'].append(e)
  202. if (pagenum * 30 +i >= n) or (m[u'last'] >= (m[u'total'] -1 )):
  203. break
  204. return res
  205. class BlipTVUserIE(InfoExtractor):
  206. """Information Extractor for blip.tv users."""
  207. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  208. _PAGE_SIZE = 12
  209. IE_NAME = u'blip.tv:user'
  210. def _real_extract(self, url):
  211. # Extract username
  212. mobj = re.match(self._VALID_URL, url)
  213. if mobj is None:
  214. raise ExtractorError(u'Invalid URL: %s' % url)
  215. username = mobj.group(1)
  216. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  217. page = self._download_webpage(url, username, u'Downloading user page')
  218. mobj = re.search(r'data-users-id="([^"]+)"', page)
  219. page_base = page_base % mobj.group(1)
  220. # Download video ids using BlipTV Ajax calls. Result size per
  221. # query is limited (currently to 12 videos) so we need to query
  222. # page by page until there are no video ids - it means we got
  223. # all of them.
  224. video_ids = []
  225. pagenum = 1
  226. while True:
  227. url = page_base + "&page=" + str(pagenum)
  228. page = self._download_webpage(url, username,
  229. u'Downloading video ids from page %d' % pagenum)
  230. # Extract video identifiers
  231. ids_in_page = []
  232. for mobj in re.finditer(r'href="/([^"]+)"', page):
  233. if mobj.group(1) not in ids_in_page:
  234. ids_in_page.append(unescapeHTML(mobj.group(1)))
  235. video_ids.extend(ids_in_page)
  236. # A little optimization - if current page is not
  237. # "full", ie. does not contain PAGE_SIZE video ids then
  238. # we can assume that this page is the last one - there
  239. # are no more ids on further pages - no need to query
  240. # again.
  241. if len(ids_in_page) < self._PAGE_SIZE:
  242. break
  243. pagenum += 1
  244. urls = [u'http://blip.tv/%s' % video_id for video_id in video_ids]
  245. url_entries = [self.url_result(url, 'BlipTV') for url in urls]
  246. return [self.playlist_result(url_entries, playlist_title = username)]
  247. class DepositFilesIE(InfoExtractor):
  248. """Information extractor for depositfiles.com"""
  249. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  250. def _real_extract(self, url):
  251. file_id = url.split('/')[-1]
  252. # Rebuild url in english locale
  253. url = 'http://depositfiles.com/en/files/' + file_id
  254. # Retrieve file webpage with 'Free download' button pressed
  255. free_download_indication = { 'gateway_result' : '1' }
  256. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  257. try:
  258. self.report_download_webpage(file_id)
  259. webpage = compat_urllib_request.urlopen(request).read()
  260. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  261. raise ExtractorError(u'Unable to retrieve file webpage: %s' % compat_str(err))
  262. # Search for the real file URL
  263. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  264. if (mobj is None) or (mobj.group(1) is None):
  265. # Try to figure out reason of the error.
  266. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  267. if (mobj is not None) and (mobj.group(1) is not None):
  268. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  269. raise ExtractorError(u'%s' % restriction_message)
  270. else:
  271. raise ExtractorError(u'Unable to extract download URL from: %s' % url)
  272. file_url = mobj.group(1)
  273. file_extension = os.path.splitext(file_url)[1][1:]
  274. # Search for file title
  275. file_title = self._search_regex(r'<b title="(.*?)">', webpage, u'title')
  276. return [{
  277. 'id': file_id.decode('utf-8'),
  278. 'url': file_url.decode('utf-8'),
  279. 'uploader': None,
  280. 'upload_date': None,
  281. 'title': file_title,
  282. 'ext': file_extension.decode('utf-8'),
  283. }]
  284. class FacebookIE(InfoExtractor):
  285. """Information Extractor for Facebook"""
  286. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  287. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  288. _NETRC_MACHINE = 'facebook'
  289. IE_NAME = u'facebook'
  290. def report_login(self):
  291. """Report attempt to log in."""
  292. self.to_screen(u'Logging in')
  293. def _real_initialize(self):
  294. if self._downloader is None:
  295. return
  296. useremail = None
  297. password = None
  298. downloader_params = self._downloader.params
  299. # Attempt to use provided username and password or .netrc data
  300. if downloader_params.get('username', None) is not None:
  301. useremail = downloader_params['username']
  302. password = downloader_params['password']
  303. elif downloader_params.get('usenetrc', False):
  304. try:
  305. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  306. if info is not None:
  307. useremail = info[0]
  308. password = info[2]
  309. else:
  310. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  311. except (IOError, netrc.NetrcParseError) as err:
  312. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  313. return
  314. if useremail is None:
  315. return
  316. # Log in
  317. login_form = {
  318. 'email': useremail,
  319. 'pass': password,
  320. 'login': 'Log+In'
  321. }
  322. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  323. try:
  324. self.report_login()
  325. login_results = compat_urllib_request.urlopen(request).read()
  326. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  327. self._downloader.report_warning(u'unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  328. return
  329. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  330. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  331. return
  332. def _real_extract(self, url):
  333. mobj = re.match(self._VALID_URL, url)
  334. if mobj is None:
  335. raise ExtractorError(u'Invalid URL: %s' % url)
  336. video_id = mobj.group('ID')
  337. url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
  338. webpage = self._download_webpage(url, video_id)
  339. BEFORE = '{swf.addParam(param[0], param[1]);});\n'
  340. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  341. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  342. if not m:
  343. raise ExtractorError(u'Cannot parse data')
  344. data = dict(json.loads(m.group(1)))
  345. params_raw = compat_urllib_parse.unquote(data['params'])
  346. params = json.loads(params_raw)
  347. video_data = params['video_data'][0]
  348. video_url = video_data.get('hd_src')
  349. if not video_url:
  350. video_url = video_data['sd_src']
  351. if not video_url:
  352. raise ExtractorError(u'Cannot find video URL')
  353. video_duration = int(video_data['video_duration'])
  354. thumbnail = video_data['thumbnail_src']
  355. video_title = self._html_search_regex('<h2 class="uiHeaderTitle">([^<]+)</h2>',
  356. webpage, u'title')
  357. info = {
  358. 'id': video_id,
  359. 'title': video_title,
  360. 'url': video_url,
  361. 'ext': 'mp4',
  362. 'duration': video_duration,
  363. 'thumbnail': thumbnail,
  364. }
  365. return [info]
  366. class BlipTVIE(InfoExtractor):
  367. """Information extractor for blip.tv"""
  368. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(.+)$'
  369. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  370. IE_NAME = u'blip.tv'
  371. def report_direct_download(self, title):
  372. """Report information extraction."""
  373. self.to_screen(u'%s: Direct download detected' % title)
  374. def _real_extract(self, url):
  375. mobj = re.match(self._VALID_URL, url)
  376. if mobj is None:
  377. raise ExtractorError(u'Invalid URL: %s' % url)
  378. # See https://github.com/rg3/youtube-dl/issues/857
  379. api_mobj = re.match(r'http://a\.blip\.tv/api\.swf#(?P<video_id>[\d\w]+)', url)
  380. if api_mobj is not None:
  381. url = 'http://blip.tv/play/g_%s' % api_mobj.group('video_id')
  382. urlp = compat_urllib_parse_urlparse(url)
  383. if urlp.path.startswith('/play/'):
  384. request = compat_urllib_request.Request(url)
  385. response = compat_urllib_request.urlopen(request)
  386. redirecturl = response.geturl()
  387. rurlp = compat_urllib_parse_urlparse(redirecturl)
  388. file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
  389. url = 'http://blip.tv/a/a-' + file_id
  390. return self._real_extract(url)
  391. if '?' in url:
  392. cchar = '&'
  393. else:
  394. cchar = '?'
  395. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  396. request = compat_urllib_request.Request(json_url)
  397. request.add_header('User-Agent', 'iTunes/10.6.1')
  398. self.report_extraction(mobj.group(1))
  399. info = None
  400. try:
  401. urlh = compat_urllib_request.urlopen(request)
  402. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  403. basename = url.split('/')[-1]
  404. title,ext = os.path.splitext(basename)
  405. title = title.decode('UTF-8')
  406. ext = ext.replace('.', '')
  407. self.report_direct_download(title)
  408. info = {
  409. 'id': title,
  410. 'url': url,
  411. 'uploader': None,
  412. 'upload_date': None,
  413. 'title': title,
  414. 'ext': ext,
  415. 'urlhandle': urlh
  416. }
  417. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  418. raise ExtractorError(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  419. if info is None: # Regular URL
  420. try:
  421. json_code_bytes = urlh.read()
  422. json_code = json_code_bytes.decode('utf-8')
  423. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  424. raise ExtractorError(u'Unable to read video info webpage: %s' % compat_str(err))
  425. try:
  426. json_data = json.loads(json_code)
  427. if 'Post' in json_data:
  428. data = json_data['Post']
  429. else:
  430. data = json_data
  431. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  432. video_url = data['media']['url']
  433. umobj = re.match(self._URL_EXT, video_url)
  434. if umobj is None:
  435. raise ValueError('Can not determine filename extension')
  436. ext = umobj.group(1)
  437. info = {
  438. 'id': data['item_id'],
  439. 'url': video_url,
  440. 'uploader': data['display_name'],
  441. 'upload_date': upload_date,
  442. 'title': data['title'],
  443. 'ext': ext,
  444. 'format': data['media']['mimeType'],
  445. 'thumbnail': data['thumbnailUrl'],
  446. 'description': data['description'],
  447. 'player_url': data['embedUrl'],
  448. 'user_agent': 'iTunes/10.6.1',
  449. }
  450. except (ValueError,KeyError) as err:
  451. raise ExtractorError(u'Unable to parse video information: %s' % repr(err))
  452. return [info]
  453. class MyVideoIE(InfoExtractor):
  454. """Information Extractor for myvideo.de."""
  455. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  456. IE_NAME = u'myvideo'
  457. # Original Code from: https://github.com/dersphere/plugin.video.myvideo_de.git
  458. # Released into the Public Domain by Tristan Fischer on 2013-05-19
  459. # https://github.com/rg3/youtube-dl/pull/842
  460. def __rc4crypt(self,data, key):
  461. x = 0
  462. box = list(range(256))
  463. for i in list(range(256)):
  464. x = (x + box[i] + compat_ord(key[i % len(key)])) % 256
  465. box[i], box[x] = box[x], box[i]
  466. x = 0
  467. y = 0
  468. out = ''
  469. for char in data:
  470. x = (x + 1) % 256
  471. y = (y + box[x]) % 256
  472. box[x], box[y] = box[y], box[x]
  473. out += chr(compat_ord(char) ^ box[(box[x] + box[y]) % 256])
  474. return out
  475. def __md5(self,s):
  476. return hashlib.md5(s).hexdigest().encode()
  477. def _real_extract(self,url):
  478. mobj = re.match(self._VALID_URL, url)
  479. if mobj is None:
  480. raise ExtractorError(u'invalid URL: %s' % url)
  481. video_id = mobj.group(1)
  482. GK = (
  483. b'WXpnME1EZGhNRGhpTTJNM01XVmhOREU0WldNNVpHTTJOakpt'
  484. b'TW1FMU5tVTBNR05pWkRaa05XRXhNVFJoWVRVd1ptSXhaVEV3'
  485. b'TnpsbA0KTVRkbU1tSTRNdz09'
  486. )
  487. # Get video webpage
  488. webpage_url = 'http://www.myvideo.de/watch/%s' % video_id
  489. webpage = self._download_webpage(webpage_url, video_id)
  490. mobj = re.search('source src=\'(.+?)[.]([^.]+)\'', webpage)
  491. if mobj is not None:
  492. self.report_extraction(video_id)
  493. video_url = mobj.group(1) + '.flv'
  494. video_title = self._html_search_regex('<title>([^<]+)</title>',
  495. webpage, u'title')
  496. video_ext = self._search_regex('[.](.+?)$', video_url, u'extension')
  497. return [{
  498. 'id': video_id,
  499. 'url': video_url,
  500. 'uploader': None,
  501. 'upload_date': None,
  502. 'title': video_title,
  503. 'ext': u'flv',
  504. }]
  505. # try encxml
  506. mobj = re.search('var flashvars={(.+?)}', webpage)
  507. if mobj is None:
  508. raise ExtractorError(u'Unable to extract video')
  509. params = {}
  510. encxml = ''
  511. sec = mobj.group(1)
  512. for (a, b) in re.findall('(.+?):\'(.+?)\',?', sec):
  513. if not a == '_encxml':
  514. params[a] = b
  515. else:
  516. encxml = compat_urllib_parse.unquote(b)
  517. if not params.get('domain'):
  518. params['domain'] = 'www.myvideo.de'
  519. xmldata_url = '%s?%s' % (encxml, compat_urllib_parse.urlencode(params))
  520. if 'flash_playertype=MTV' in xmldata_url:
  521. self._downloader.report_warning(u'avoiding MTV player')
  522. xmldata_url = (
  523. 'http://www.myvideo.de/dynamic/get_player_video_xml.php'
  524. '?flash_playertype=D&ID=%s&_countlimit=4&autorun=yes'
  525. ) % video_id
  526. # get enc data
  527. enc_data = self._download_webpage(xmldata_url, video_id).split('=')[1]
  528. enc_data_b = binascii.unhexlify(enc_data)
  529. sk = self.__md5(
  530. base64.b64decode(base64.b64decode(GK)) +
  531. self.__md5(
  532. str(video_id).encode('utf-8')
  533. )
  534. )
  535. dec_data = self.__rc4crypt(enc_data_b, sk)
  536. # extracting infos
  537. self.report_extraction(video_id)
  538. video_url = None
  539. mobj = re.search('connectionurl=\'(.*?)\'', dec_data)
  540. if mobj:
  541. video_url = compat_urllib_parse.unquote(mobj.group(1))
  542. if 'myvideo2flash' in video_url:
  543. self._downloader.report_warning(u'forcing RTMPT ...')
  544. video_url = video_url.replace('rtmpe://', 'rtmpt://')
  545. if not video_url:
  546. # extract non rtmp videos
  547. mobj = re.search('path=\'(http.*?)\' source=\'(.*?)\'', dec_data)
  548. if mobj is None:
  549. raise ExtractorError(u'unable to extract url')
  550. video_url = compat_urllib_parse.unquote(mobj.group(1)) + compat_urllib_parse.unquote(mobj.group(2))
  551. video_file = self._search_regex('source=\'(.*?)\'', dec_data, u'video file')
  552. video_file = compat_urllib_parse.unquote(video_file)
  553. if not video_file.endswith('f4m'):
  554. ppath, prefix = video_file.split('.')
  555. video_playpath = '%s:%s' % (prefix, ppath)
  556. video_hls_playlist = ''
  557. else:
  558. video_playpath = ''
  559. video_hls_playlist = (
  560. video_filepath + video_file
  561. ).replace('.f4m', '.m3u8')
  562. video_swfobj = self._search_regex('swfobject.embedSWF\(\'(.+?)\'', webpage, u'swfobj')
  563. video_swfobj = compat_urllib_parse.unquote(video_swfobj)
  564. video_title = self._html_search_regex("<h1(?: class='globalHd')?>(.*?)</h1>",
  565. webpage, u'title')
  566. return [{
  567. 'id': video_id,
  568. 'url': video_url,
  569. 'tc_url': video_url,
  570. 'uploader': None,
  571. 'upload_date': None,
  572. 'title': video_title,
  573. 'ext': u'flv',
  574. 'play_path': video_playpath,
  575. 'video_file': video_file,
  576. 'video_hls_playlist': video_hls_playlist,
  577. 'player_url': video_swfobj,
  578. }]
  579. class ComedyCentralIE(InfoExtractor):
  580. """Information extractor for The Daily Show and Colbert Report """
  581. # urls can be abbreviations like :thedailyshow or :colbert
  582. # urls for episodes like:
  583. # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
  584. # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
  585. # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
  586. _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
  587. |(https?://)?(www\.)?
  588. (?P<showname>thedailyshow|colbertnation)\.com/
  589. (full-episodes/(?P<episode>.*)|
  590. (?P<clip>
  591. (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
  592. |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
  593. $"""
  594. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  595. _video_extensions = {
  596. '3500': 'mp4',
  597. '2200': 'mp4',
  598. '1700': 'mp4',
  599. '1200': 'mp4',
  600. '750': 'mp4',
  601. '400': 'mp4',
  602. }
  603. _video_dimensions = {
  604. '3500': '1280x720',
  605. '2200': '960x540',
  606. '1700': '768x432',
  607. '1200': '640x360',
  608. '750': '512x288',
  609. '400': '384x216',
  610. }
  611. @classmethod
  612. def suitable(cls, url):
  613. """Receives a URL and returns True if suitable for this IE."""
  614. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  615. def _print_formats(self, formats):
  616. print('Available formats:')
  617. for x in formats:
  618. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  619. def _real_extract(self, url):
  620. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  621. if mobj is None:
  622. raise ExtractorError(u'Invalid URL: %s' % url)
  623. if mobj.group('shortname'):
  624. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  625. url = u'http://www.thedailyshow.com/full-episodes/'
  626. else:
  627. url = u'http://www.colbertnation.com/full-episodes/'
  628. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  629. assert mobj is not None
  630. if mobj.group('clip'):
  631. if mobj.group('showname') == 'thedailyshow':
  632. epTitle = mobj.group('tdstitle')
  633. else:
  634. epTitle = mobj.group('cntitle')
  635. dlNewest = False
  636. else:
  637. dlNewest = not mobj.group('episode')
  638. if dlNewest:
  639. epTitle = mobj.group('showname')
  640. else:
  641. epTitle = mobj.group('episode')
  642. self.report_extraction(epTitle)
  643. webpage,htmlHandle = self._download_webpage_handle(url, epTitle)
  644. if dlNewest:
  645. url = htmlHandle.geturl()
  646. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  647. if mobj is None:
  648. raise ExtractorError(u'Invalid redirected URL: ' + url)
  649. if mobj.group('episode') == '':
  650. raise ExtractorError(u'Redirected URL is still not specific: ' + url)
  651. epTitle = mobj.group('episode')
  652. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
  653. if len(mMovieParams) == 0:
  654. # The Colbert Report embeds the information in a without
  655. # a URL prefix; so extract the alternate reference
  656. # and then add the URL prefix manually.
  657. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
  658. if len(altMovieParams) == 0:
  659. raise ExtractorError(u'unable to find Flash URL in webpage ' + url)
  660. else:
  661. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  662. uri = mMovieParams[0][1]
  663. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  664. indexXml = self._download_webpage(indexUrl, epTitle,
  665. u'Downloading show index',
  666. u'unable to download episode index')
  667. results = []
  668. idoc = xml.etree.ElementTree.fromstring(indexXml)
  669. itemEls = idoc.findall('.//item')
  670. for partNum,itemEl in enumerate(itemEls):
  671. mediaId = itemEl.findall('./guid')[0].text
  672. shortMediaId = mediaId.split(':')[-1]
  673. showId = mediaId.split(':')[-2].replace('.com', '')
  674. officialTitle = itemEl.findall('./title')[0].text
  675. officialDate = unified_strdate(itemEl.findall('./pubDate')[0].text)
  676. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  677. compat_urllib_parse.urlencode({'uri': mediaId}))
  678. configXml = self._download_webpage(configUrl, epTitle,
  679. u'Downloading configuration for %s' % shortMediaId)
  680. cdoc = xml.etree.ElementTree.fromstring(configXml)
  681. turls = []
  682. for rendition in cdoc.findall('.//rendition'):
  683. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  684. turls.append(finfo)
  685. if len(turls) == 0:
  686. self._downloader.report_error(u'unable to download ' + mediaId + ': No videos found')
  687. continue
  688. if self._downloader.params.get('listformats', None):
  689. self._print_formats([i[0] for i in turls])
  690. return
  691. # For now, just pick the highest bitrate
  692. format,rtmp_video_url = turls[-1]
  693. # Get the format arg from the arg stream
  694. req_format = self._downloader.params.get('format', None)
  695. # Select format if we can find one
  696. for f,v in turls:
  697. if f == req_format:
  698. format, rtmp_video_url = f, v
  699. break
  700. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
  701. if not m:
  702. raise ExtractorError(u'Cannot transform RTMP url')
  703. base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
  704. video_url = base + m.group('finalid')
  705. effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
  706. info = {
  707. 'id': shortMediaId,
  708. 'url': video_url,
  709. 'uploader': showId,
  710. 'upload_date': officialDate,
  711. 'title': effTitle,
  712. 'ext': 'mp4',
  713. 'format': format,
  714. 'thumbnail': None,
  715. 'description': officialTitle,
  716. }
  717. results.append(info)
  718. return results
  719. class EscapistIE(InfoExtractor):
  720. """Information extractor for The Escapist """
  721. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  722. IE_NAME = u'escapist'
  723. def _real_extract(self, url):
  724. mobj = re.match(self._VALID_URL, url)
  725. if mobj is None:
  726. raise ExtractorError(u'Invalid URL: %s' % url)
  727. showName = mobj.group('showname')
  728. videoId = mobj.group('episode')
  729. self.report_extraction(videoId)
  730. webpage = self._download_webpage(url, videoId)
  731. videoDesc = self._html_search_regex('<meta name="description" content="([^"]*)"',
  732. webpage, u'description', fatal=False)
  733. imgUrl = self._html_search_regex('<meta property="og:image" content="([^"]*)"',
  734. webpage, u'thumbnail', fatal=False)
  735. playerUrl = self._html_search_regex('<meta property="og:video" content="([^"]*)"',
  736. webpage, u'player url')
  737. title = self._html_search_regex('<meta name="title" content="([^"]*)"',
  738. webpage, u'player url').split(' : ')[-1]
  739. configUrl = self._search_regex('config=(.*)$', playerUrl, u'config url')
  740. configUrl = compat_urllib_parse.unquote(configUrl)
  741. configJSON = self._download_webpage(configUrl, videoId,
  742. u'Downloading configuration',
  743. u'unable to download configuration')
  744. # Technically, it's JavaScript, not JSON
  745. configJSON = configJSON.replace("'", '"')
  746. try:
  747. config = json.loads(configJSON)
  748. except (ValueError,) as err:
  749. raise ExtractorError(u'Invalid JSON in configuration file: ' + compat_str(err))
  750. playlist = config['playlist']
  751. videoUrl = playlist[1]['url']
  752. info = {
  753. 'id': videoId,
  754. 'url': videoUrl,
  755. 'uploader': showName,
  756. 'upload_date': None,
  757. 'title': title,
  758. 'ext': 'mp4',
  759. 'thumbnail': imgUrl,
  760. 'description': videoDesc,
  761. 'player_url': playerUrl,
  762. }
  763. return [info]
  764. class CollegeHumorIE(InfoExtractor):
  765. """Information extractor for collegehumor.com"""
  766. _WORKING = False
  767. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  768. IE_NAME = u'collegehumor'
  769. def report_manifest(self, video_id):
  770. """Report information extraction."""
  771. self.to_screen(u'%s: Downloading XML manifest' % video_id)
  772. def _real_extract(self, url):
  773. mobj = re.match(self._VALID_URL, url)
  774. if mobj is None:
  775. raise ExtractorError(u'Invalid URL: %s' % url)
  776. video_id = mobj.group('videoid')
  777. info = {
  778. 'id': video_id,
  779. 'uploader': None,
  780. 'upload_date': None,
  781. }
  782. self.report_extraction(video_id)
  783. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  784. try:
  785. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  786. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  787. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  788. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  789. try:
  790. videoNode = mdoc.findall('./video')[0]
  791. info['description'] = videoNode.findall('./description')[0].text
  792. info['title'] = videoNode.findall('./caption')[0].text
  793. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  794. manifest_url = videoNode.findall('./file')[0].text
  795. except IndexError:
  796. raise ExtractorError(u'Invalid metadata XML file')
  797. manifest_url += '?hdcore=2.10.3'
  798. self.report_manifest(video_id)
  799. try:
  800. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  801. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  802. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  803. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  804. try:
  805. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  806. node_id = media_node.attrib['url']
  807. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  808. except IndexError as err:
  809. raise ExtractorError(u'Invalid manifest file')
  810. url_pr = compat_urllib_parse_urlparse(manifest_url)
  811. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  812. info['url'] = url
  813. info['ext'] = 'f4f'
  814. return [info]
  815. class XVideosIE(InfoExtractor):
  816. """Information extractor for xvideos.com"""
  817. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  818. IE_NAME = u'xvideos'
  819. def _real_extract(self, url):
  820. mobj = re.match(self._VALID_URL, url)
  821. if mobj is None:
  822. raise ExtractorError(u'Invalid URL: %s' % url)
  823. video_id = mobj.group(1)
  824. webpage = self._download_webpage(url, video_id)
  825. self.report_extraction(video_id)
  826. # Extract video URL
  827. video_url = compat_urllib_parse.unquote(self._search_regex(r'flv_url=(.+?)&',
  828. webpage, u'video URL'))
  829. # Extract title
  830. video_title = self._html_search_regex(r'<title>(.*?)\s+-\s+XVID',
  831. webpage, u'title')
  832. # Extract video thumbnail
  833. video_thumbnail = self._search_regex(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)',
  834. webpage, u'thumbnail', fatal=False)
  835. info = {
  836. 'id': video_id,
  837. 'url': video_url,
  838. 'uploader': None,
  839. 'upload_date': None,
  840. 'title': video_title,
  841. 'ext': 'flv',
  842. 'thumbnail': video_thumbnail,
  843. 'description': None,
  844. }
  845. return [info]
  846. class SoundcloudIE(InfoExtractor):
  847. """Information extractor for soundcloud.com
  848. To access the media, the uid of the song and a stream token
  849. must be extracted from the page source and the script must make
  850. a request to media.soundcloud.com/crossdomain.xml. Then
  851. the media can be grabbed by requesting from an url composed
  852. of the stream token and uid
  853. """
  854. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  855. IE_NAME = u'soundcloud'
  856. def report_resolve(self, video_id):
  857. """Report information extraction."""
  858. self.to_screen(u'%s: Resolving id' % video_id)
  859. def _real_extract(self, url):
  860. mobj = re.match(self._VALID_URL, url)
  861. if mobj is None:
  862. raise ExtractorError(u'Invalid URL: %s' % url)
  863. # extract uploader (which is in the url)
  864. uploader = mobj.group(1)
  865. # extract simple title (uploader + slug of song title)
  866. slug_title = mobj.group(2)
  867. simple_title = uploader + u'-' + slug_title
  868. full_title = '%s/%s' % (uploader, slug_title)
  869. self.report_resolve(full_title)
  870. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  871. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  872. info_json = self._download_webpage(resolv_url, full_title, u'Downloading info JSON')
  873. info = json.loads(info_json)
  874. video_id = info['id']
  875. self.report_extraction(full_title)
  876. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  877. stream_json = self._download_webpage(streams_url, full_title,
  878. u'Downloading stream definitions',
  879. u'unable to download stream definitions')
  880. streams = json.loads(stream_json)
  881. mediaURL = streams['http_mp3_128_url']
  882. upload_date = unified_strdate(info['created_at'])
  883. return [{
  884. 'id': info['id'],
  885. 'url': mediaURL,
  886. 'uploader': info['user']['username'],
  887. 'upload_date': upload_date,
  888. 'title': info['title'],
  889. 'ext': u'mp3',
  890. 'description': info['description'],
  891. }]
  892. class SoundcloudSetIE(InfoExtractor):
  893. """Information extractor for soundcloud.com sets
  894. To access the media, the uid of the song and a stream token
  895. must be extracted from the page source and the script must make
  896. a request to media.soundcloud.com/crossdomain.xml. Then
  897. the media can be grabbed by requesting from an url composed
  898. of the stream token and uid
  899. """
  900. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
  901. IE_NAME = u'soundcloud:set'
  902. def report_resolve(self, video_id):
  903. """Report information extraction."""
  904. self.to_screen(u'%s: Resolving id' % video_id)
  905. def _real_extract(self, url):
  906. mobj = re.match(self._VALID_URL, url)
  907. if mobj is None:
  908. raise ExtractorError(u'Invalid URL: %s' % url)
  909. # extract uploader (which is in the url)
  910. uploader = mobj.group(1)
  911. # extract simple title (uploader + slug of song title)
  912. slug_title = mobj.group(2)
  913. simple_title = uploader + u'-' + slug_title
  914. full_title = '%s/sets/%s' % (uploader, slug_title)
  915. self.report_resolve(full_title)
  916. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  917. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  918. info_json = self._download_webpage(resolv_url, full_title)
  919. videos = []
  920. info = json.loads(info_json)
  921. if 'errors' in info:
  922. for err in info['errors']:
  923. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
  924. return
  925. self.report_extraction(full_title)
  926. for track in info['tracks']:
  927. video_id = track['id']
  928. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  929. stream_json = self._download_webpage(streams_url, video_id, u'Downloading track info JSON')
  930. self.report_extraction(video_id)
  931. streams = json.loads(stream_json)
  932. mediaURL = streams['http_mp3_128_url']
  933. videos.append({
  934. 'id': video_id,
  935. 'url': mediaURL,
  936. 'uploader': track['user']['username'],
  937. 'upload_date': unified_strdate(track['created_at']),
  938. 'title': track['title'],
  939. 'ext': u'mp3',
  940. 'description': track['description'],
  941. })
  942. return videos
  943. class InfoQIE(InfoExtractor):
  944. """Information extractor for infoq.com"""
  945. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  946. def _real_extract(self, url):
  947. mobj = re.match(self._VALID_URL, url)
  948. if mobj is None:
  949. raise ExtractorError(u'Invalid URL: %s' % url)
  950. webpage = self._download_webpage(url, video_id=url)
  951. self.report_extraction(url)
  952. # Extract video URL
  953. mobj = re.search(r"jsclassref ?= ?'([^']*)'", webpage)
  954. if mobj is None:
  955. raise ExtractorError(u'Unable to extract video url')
  956. real_id = compat_urllib_parse.unquote(base64.b64decode(mobj.group(1).encode('ascii')).decode('utf-8'))
  957. video_url = 'rtmpe://video.infoq.com/cfx/st/' + real_id
  958. # Extract title
  959. video_title = self._search_regex(r'contentTitle = "(.*?)";',
  960. webpage, u'title')
  961. # Extract description
  962. video_description = self._html_search_regex(r'<meta name="description" content="(.*)"(?:\s*/)?>',
  963. webpage, u'description', fatal=False)
  964. video_filename = video_url.split('/')[-1]
  965. video_id, extension = video_filename.split('.')
  966. info = {
  967. 'id': video_id,
  968. 'url': video_url,
  969. 'uploader': None,
  970. 'upload_date': None,
  971. 'title': video_title,
  972. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  973. 'thumbnail': None,
  974. 'description': video_description,
  975. }
  976. return [info]
  977. class MixcloudIE(InfoExtractor):
  978. """Information extractor for www.mixcloud.com"""
  979. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  980. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  981. IE_NAME = u'mixcloud'
  982. def report_download_json(self, file_id):
  983. """Report JSON download."""
  984. self.to_screen(u'Downloading json')
  985. def get_urls(self, jsonData, fmt, bitrate='best'):
  986. """Get urls from 'audio_formats' section in json"""
  987. file_url = None
  988. try:
  989. bitrate_list = jsonData[fmt]
  990. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  991. bitrate = max(bitrate_list) # select highest
  992. url_list = jsonData[fmt][bitrate]
  993. except TypeError: # we have no bitrate info.
  994. url_list = jsonData[fmt]
  995. return url_list
  996. def check_urls(self, url_list):
  997. """Returns 1st active url from list"""
  998. for url in url_list:
  999. try:
  1000. compat_urllib_request.urlopen(url)
  1001. return url
  1002. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1003. url = None
  1004. return None
  1005. def _print_formats(self, formats):
  1006. print('Available formats:')
  1007. for fmt in formats.keys():
  1008. for b in formats[fmt]:
  1009. try:
  1010. ext = formats[fmt][b][0]
  1011. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  1012. except TypeError: # we have no bitrate info
  1013. ext = formats[fmt][0]
  1014. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  1015. break
  1016. def _real_extract(self, url):
  1017. mobj = re.match(self._VALID_URL, url)
  1018. if mobj is None:
  1019. raise ExtractorError(u'Invalid URL: %s' % url)
  1020. # extract uploader & filename from url
  1021. uploader = mobj.group(1).decode('utf-8')
  1022. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  1023. # construct API request
  1024. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  1025. # retrieve .json file with links to files
  1026. request = compat_urllib_request.Request(file_url)
  1027. try:
  1028. self.report_download_json(file_url)
  1029. jsonData = compat_urllib_request.urlopen(request).read()
  1030. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1031. raise ExtractorError(u'Unable to retrieve file: %s' % compat_str(err))
  1032. # parse JSON
  1033. json_data = json.loads(jsonData)
  1034. player_url = json_data['player_swf_url']
  1035. formats = dict(json_data['audio_formats'])
  1036. req_format = self._downloader.params.get('format', None)
  1037. bitrate = None
  1038. if self._downloader.params.get('listformats', None):
  1039. self._print_formats(formats)
  1040. return
  1041. if req_format is None or req_format == 'best':
  1042. for format_param in formats.keys():
  1043. url_list = self.get_urls(formats, format_param)
  1044. # check urls
  1045. file_url = self.check_urls(url_list)
  1046. if file_url is not None:
  1047. break # got it!
  1048. else:
  1049. if req_format not in formats:
  1050. raise ExtractorError(u'Format is not available')
  1051. url_list = self.get_urls(formats, req_format)
  1052. file_url = self.check_urls(url_list)
  1053. format_param = req_format
  1054. return [{
  1055. 'id': file_id.decode('utf-8'),
  1056. 'url': file_url.decode('utf-8'),
  1057. 'uploader': uploader.decode('utf-8'),
  1058. 'upload_date': None,
  1059. 'title': json_data['name'],
  1060. 'ext': file_url.split('.')[-1].decode('utf-8'),
  1061. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  1062. 'thumbnail': json_data['thumbnail_url'],
  1063. 'description': json_data['description'],
  1064. 'player_url': player_url.decode('utf-8'),
  1065. }]
  1066. class StanfordOpenClassroomIE(InfoExtractor):
  1067. """Information extractor for Stanford's Open ClassRoom"""
  1068. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  1069. IE_NAME = u'stanfordoc'
  1070. def _real_extract(self, url):
  1071. mobj = re.match(self._VALID_URL, url)
  1072. if mobj is None:
  1073. raise ExtractorError(u'Invalid URL: %s' % url)
  1074. if mobj.group('course') and mobj.group('video'): # A specific video
  1075. course = mobj.group('course')
  1076. video = mobj.group('video')
  1077. info = {
  1078. 'id': course + '_' + video,
  1079. 'uploader': None,
  1080. 'upload_date': None,
  1081. }
  1082. self.report_extraction(info['id'])
  1083. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  1084. xmlUrl = baseUrl + video + '.xml'
  1085. try:
  1086. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  1087. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1088. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  1089. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  1090. try:
  1091. info['title'] = mdoc.findall('./title')[0].text
  1092. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  1093. except IndexError:
  1094. raise ExtractorError(u'Invalid metadata XML file')
  1095. info['ext'] = info['url'].rpartition('.')[2]
  1096. return [info]
  1097. elif mobj.group('course'): # A course page
  1098. course = mobj.group('course')
  1099. info = {
  1100. 'id': course,
  1101. 'type': 'playlist',
  1102. 'uploader': None,
  1103. 'upload_date': None,
  1104. }
  1105. coursepage = self._download_webpage(url, info['id'],
  1106. note='Downloading course info page',
  1107. errnote='Unable to download course info page')
  1108. info['title'] = self._html_search_regex('<h1>([^<]+)</h1>', coursepage, 'title', default=info['id'])
  1109. info['description'] = self._html_search_regex('<description>([^<]+)</description>',
  1110. coursepage, u'description', fatal=False)
  1111. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  1112. info['list'] = [
  1113. {
  1114. 'type': 'reference',
  1115. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  1116. }
  1117. for vpage in links]
  1118. results = []
  1119. for entry in info['list']:
  1120. assert entry['type'] == 'reference'
  1121. results += self.extract(entry['url'])
  1122. return results
  1123. else: # Root page
  1124. info = {
  1125. 'id': 'Stanford OpenClassroom',
  1126. 'type': 'playlist',
  1127. 'uploader': None,
  1128. 'upload_date': None,
  1129. }
  1130. self.report_download_webpage(info['id'])
  1131. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  1132. try:
  1133. rootpage = compat_urllib_request.urlopen(rootURL).read()
  1134. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1135. raise ExtractorError(u'Unable to download course info page: ' + compat_str(err))
  1136. info['title'] = info['id']
  1137. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  1138. info['list'] = [
  1139. {
  1140. 'type': 'reference',
  1141. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  1142. }
  1143. for cpage in links]
  1144. results = []
  1145. for entry in info['list']:
  1146. assert entry['type'] == 'reference'
  1147. results += self.extract(entry['url'])
  1148. return results
  1149. class MTVIE(InfoExtractor):
  1150. """Information extractor for MTV.com"""
  1151. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  1152. IE_NAME = u'mtv'
  1153. def _real_extract(self, url):
  1154. mobj = re.match(self._VALID_URL, url)
  1155. if mobj is None:
  1156. raise ExtractorError(u'Invalid URL: %s' % url)
  1157. if not mobj.group('proto'):
  1158. url = 'http://' + url
  1159. video_id = mobj.group('videoid')
  1160. webpage = self._download_webpage(url, video_id)
  1161. song_name = self._html_search_regex(r'<meta name="mtv_vt" content="([^"]+)"/>',
  1162. webpage, u'song name', fatal=False)
  1163. video_title = self._html_search_regex(r'<meta name="mtv_an" content="([^"]+)"/>',
  1164. webpage, u'title')
  1165. mtvn_uri = self._html_search_regex(r'<meta name="mtvn_uri" content="([^"]+)"/>',
  1166. webpage, u'mtvn_uri', fatal=False)
  1167. content_id = self._search_regex(r'MTVN.Player.defaultPlaylistId = ([0-9]+);',
  1168. webpage, u'content id', fatal=False)
  1169. 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
  1170. self.report_extraction(video_id)
  1171. request = compat_urllib_request.Request(videogen_url)
  1172. try:
  1173. metadataXml = compat_urllib_request.urlopen(request).read()
  1174. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1175. raise ExtractorError(u'Unable to download video metadata: %s' % compat_str(err))
  1176. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  1177. renditions = mdoc.findall('.//rendition')
  1178. # For now, always pick the highest quality.
  1179. rendition = renditions[-1]
  1180. try:
  1181. _,_,ext = rendition.attrib['type'].partition('/')
  1182. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  1183. video_url = rendition.find('./src').text
  1184. except KeyError:
  1185. raise ExtractorError('Invalid rendition field.')
  1186. info = {
  1187. 'id': video_id,
  1188. 'url': video_url,
  1189. 'uploader': performer,
  1190. 'upload_date': None,
  1191. 'title': video_title,
  1192. 'ext': ext,
  1193. 'format': format,
  1194. }
  1195. return [info]
  1196. class YoukuIE(InfoExtractor):
  1197. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  1198. def _gen_sid(self):
  1199. nowTime = int(time.time() * 1000)
  1200. random1 = random.randint(1000,1998)
  1201. random2 = random.randint(1000,9999)
  1202. return "%d%d%d" %(nowTime,random1,random2)
  1203. def _get_file_ID_mix_string(self, seed):
  1204. mixed = []
  1205. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  1206. seed = float(seed)
  1207. for i in range(len(source)):
  1208. seed = (seed * 211 + 30031 ) % 65536
  1209. index = math.floor(seed / 65536 * len(source) )
  1210. mixed.append(source[int(index)])
  1211. source.remove(source[int(index)])
  1212. #return ''.join(mixed)
  1213. return mixed
  1214. def _get_file_id(self, fileId, seed):
  1215. mixed = self._get_file_ID_mix_string(seed)
  1216. ids = fileId.split('*')
  1217. realId = []
  1218. for ch in ids:
  1219. if ch:
  1220. realId.append(mixed[int(ch)])
  1221. return ''.join(realId)
  1222. def _real_extract(self, url):
  1223. mobj = re.match(self._VALID_URL, url)
  1224. if mobj is None:
  1225. raise ExtractorError(u'Invalid URL: %s' % url)
  1226. video_id = mobj.group('ID')
  1227. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  1228. jsondata = self._download_webpage(info_url, video_id)
  1229. self.report_extraction(video_id)
  1230. try:
  1231. config = json.loads(jsondata)
  1232. video_title = config['data'][0]['title']
  1233. seed = config['data'][0]['seed']
  1234. format = self._downloader.params.get('format', None)
  1235. supported_format = list(config['data'][0]['streamfileids'].keys())
  1236. if format is None or format == 'best':
  1237. if 'hd2' in supported_format:
  1238. format = 'hd2'
  1239. else:
  1240. format = 'flv'
  1241. ext = u'flv'
  1242. elif format == 'worst':
  1243. format = 'mp4'
  1244. ext = u'mp4'
  1245. else:
  1246. format = 'flv'
  1247. ext = u'flv'
  1248. fileid = config['data'][0]['streamfileids'][format]
  1249. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  1250. except (UnicodeDecodeError, ValueError, KeyError):
  1251. raise ExtractorError(u'Unable to extract info section')
  1252. files_info=[]
  1253. sid = self._gen_sid()
  1254. fileid = self._get_file_id(fileid, seed)
  1255. #column 8,9 of fileid represent the segment number
  1256. #fileid[7:9] should be changed
  1257. for index, key in enumerate(keys):
  1258. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  1259. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  1260. info = {
  1261. 'id': '%s_part%02d' % (video_id, index),
  1262. 'url': download_url,
  1263. 'uploader': None,
  1264. 'upload_date': None,
  1265. 'title': video_title,
  1266. 'ext': ext,
  1267. }
  1268. files_info.append(info)
  1269. return files_info
  1270. class XNXXIE(InfoExtractor):
  1271. """Information extractor for xnxx.com"""
  1272. _VALID_URL = r'^(?:https?://)?video\.xnxx\.com/video([0-9]+)/(.*)'
  1273. IE_NAME = u'xnxx'
  1274. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  1275. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  1276. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  1277. def _real_extract(self, url):
  1278. mobj = re.match(self._VALID_URL, url)
  1279. if mobj is None:
  1280. raise ExtractorError(u'Invalid URL: %s' % url)
  1281. video_id = mobj.group(1)
  1282. # Get webpage content
  1283. webpage = self._download_webpage(url, video_id)
  1284. video_url = self._search_regex(self.VIDEO_URL_RE,
  1285. webpage, u'video URL')
  1286. video_url = compat_urllib_parse.unquote(video_url)
  1287. video_title = self._html_search_regex(self.VIDEO_TITLE_RE,
  1288. webpage, u'title')
  1289. video_thumbnail = self._search_regex(self.VIDEO_THUMB_RE,
  1290. webpage, u'thumbnail', fatal=False)
  1291. return [{
  1292. 'id': video_id,
  1293. 'url': video_url,
  1294. 'uploader': None,
  1295. 'upload_date': None,
  1296. 'title': video_title,
  1297. 'ext': 'flv',
  1298. 'thumbnail': video_thumbnail,
  1299. 'description': None,
  1300. }]
  1301. class GooglePlusIE(InfoExtractor):
  1302. """Information extractor for plus.google.com."""
  1303. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:[^/]+/)*?posts/(\w+)'
  1304. IE_NAME = u'plus.google'
  1305. def _real_extract(self, url):
  1306. # Extract id from URL
  1307. mobj = re.match(self._VALID_URL, url)
  1308. if mobj is None:
  1309. raise ExtractorError(u'Invalid URL: %s' % url)
  1310. post_url = mobj.group(0)
  1311. video_id = mobj.group(1)
  1312. video_extension = 'flv'
  1313. # Step 1, Retrieve post webpage to extract further information
  1314. webpage = self._download_webpage(post_url, video_id, u'Downloading entry webpage')
  1315. self.report_extraction(video_id)
  1316. # Extract update date
  1317. upload_date = self._html_search_regex('title="Timestamp">(.*?)</a>',
  1318. webpage, u'upload date', fatal=False)
  1319. if upload_date:
  1320. # Convert timestring to a format suitable for filename
  1321. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  1322. upload_date = upload_date.strftime('%Y%m%d')
  1323. # Extract uploader
  1324. uploader = self._html_search_regex(r'rel\="author".*?>(.*?)</a>',
  1325. webpage, u'uploader', fatal=False)
  1326. # Extract title
  1327. # Get the first line for title
  1328. video_title = self._html_search_regex(r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]',
  1329. webpage, 'title', default=u'NA')
  1330. # Step 2, Stimulate clicking the image box to launch video
  1331. video_page = self._search_regex('"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]',
  1332. webpage, u'video page URL')
  1333. webpage = self._download_webpage(video_page, video_id, u'Downloading video page')
  1334. # Extract video links on video page
  1335. """Extract video links of all sizes"""
  1336. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  1337. mobj = re.findall(pattern, webpage)
  1338. if len(mobj) == 0:
  1339. raise ExtractorError(u'Unable to extract video links')
  1340. # Sort in resolution
  1341. links = sorted(mobj)
  1342. # Choose the lowest of the sort, i.e. highest resolution
  1343. video_url = links[-1]
  1344. # Only get the url. The resolution part in the tuple has no use anymore
  1345. video_url = video_url[-1]
  1346. # Treat escaped \u0026 style hex
  1347. try:
  1348. video_url = video_url.decode("unicode_escape")
  1349. except AttributeError: # Python 3
  1350. video_url = bytes(video_url, 'ascii').decode('unicode-escape')
  1351. return [{
  1352. 'id': video_id,
  1353. 'url': video_url,
  1354. 'uploader': uploader,
  1355. 'upload_date': upload_date,
  1356. 'title': video_title,
  1357. 'ext': video_extension,
  1358. }]
  1359. class NBAIE(InfoExtractor):
  1360. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*?)(?:/index\.html)?(?:\?.*)?$'
  1361. IE_NAME = u'nba'
  1362. def _real_extract(self, url):
  1363. mobj = re.match(self._VALID_URL, url)
  1364. if mobj is None:
  1365. raise ExtractorError(u'Invalid URL: %s' % url)
  1366. video_id = mobj.group(1)
  1367. webpage = self._download_webpage(url, video_id)
  1368. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  1369. shortened_video_id = video_id.rpartition('/')[2]
  1370. title = self._html_search_regex(r'<meta property="og:title" content="(.*?)"',
  1371. webpage, 'title', default=shortened_video_id).replace('NBA.com: ', '')
  1372. # It isn't there in the HTML it returns to us
  1373. # uploader_date = self._html_search_regex(r'<b>Date:</b> (.*?)</div>', webpage, 'upload_date', fatal=False)
  1374. description = self._html_search_regex(r'<meta name="description" (?:content|value)="(.*?)" />', webpage, 'description', fatal=False)
  1375. info = {
  1376. 'id': shortened_video_id,
  1377. 'url': video_url,
  1378. 'ext': 'mp4',
  1379. 'title': title,
  1380. # 'uploader_date': uploader_date,
  1381. 'description': description,
  1382. }
  1383. return [info]
  1384. class JustinTVIE(InfoExtractor):
  1385. """Information extractor for justin.tv and twitch.tv"""
  1386. # TODO: One broadcast may be split into multiple videos. The key
  1387. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  1388. # starts at 1 and increases. Can we treat all parts as one video?
  1389. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  1390. (?:
  1391. (?P<channelid>[^/]+)|
  1392. (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
  1393. (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
  1394. )
  1395. /?(?:\#.*)?$
  1396. """
  1397. _JUSTIN_PAGE_LIMIT = 100
  1398. IE_NAME = u'justin.tv'
  1399. def report_download_page(self, channel, offset):
  1400. """Report attempt to download a single page of videos."""
  1401. self.to_screen(u'%s: Downloading video information from %d to %d' %
  1402. (channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  1403. # Return count of items, list of *valid* items
  1404. def _parse_page(self, url, video_id):
  1405. webpage = self._download_webpage(url, video_id,
  1406. u'Downloading video info JSON',
  1407. u'unable to download video info JSON')
  1408. response = json.loads(webpage)
  1409. if type(response) != list:
  1410. error_text = response.get('error', 'unknown error')
  1411. raise ExtractorError(u'Justin.tv API: %s' % error_text)
  1412. info = []
  1413. for clip in response:
  1414. video_url = clip['video_file_url']
  1415. if video_url:
  1416. video_extension = os.path.splitext(video_url)[1][1:]
  1417. video_date = re.sub('-', '', clip['start_time'][:10])
  1418. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  1419. video_id = clip['id']
  1420. video_title = clip.get('title', video_id)
  1421. info.append({
  1422. 'id': video_id,
  1423. 'url': video_url,
  1424. 'title': video_title,
  1425. 'uploader': clip.get('channel_name', video_uploader_id),
  1426. 'uploader_id': video_uploader_id,
  1427. 'upload_date': video_date,
  1428. 'ext': video_extension,
  1429. })
  1430. return (len(response), info)
  1431. def _real_extract(self, url):
  1432. mobj = re.match(self._VALID_URL, url)
  1433. if mobj is None:
  1434. raise ExtractorError(u'invalid URL: %s' % url)
  1435. api_base = 'http://api.justin.tv'
  1436. paged = False
  1437. if mobj.group('channelid'):
  1438. paged = True
  1439. video_id = mobj.group('channelid')
  1440. api = api_base + '/channel/archives/%s.json' % video_id
  1441. elif mobj.group('chapterid'):
  1442. chapter_id = mobj.group('chapterid')
  1443. webpage = self._download_webpage(url, chapter_id)
  1444. m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
  1445. if not m:
  1446. raise ExtractorError(u'Cannot find archive of a chapter')
  1447. archive_id = m.group(1)
  1448. api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
  1449. chapter_info_xml = self._download_webpage(api, chapter_id,
  1450. note=u'Downloading chapter information',
  1451. errnote=u'Chapter information download failed')
  1452. doc = xml.etree.ElementTree.fromstring(chapter_info_xml)
  1453. for a in doc.findall('.//archive'):
  1454. if archive_id == a.find('./id').text:
  1455. break
  1456. else:
  1457. raise ExtractorError(u'Could not find chapter in chapter information')
  1458. video_url = a.find('./video_file_url').text
  1459. video_ext = video_url.rpartition('.')[2] or u'flv'
  1460. chapter_api_url = u'https://api.twitch.tv/kraken/videos/c' + chapter_id
  1461. chapter_info_json = self._download_webpage(chapter_api_url, u'c' + chapter_id,
  1462. note='Downloading chapter metadata',
  1463. errnote='Download of chapter metadata failed')
  1464. chapter_info = json.loads(chapter_info_json)
  1465. bracket_start = int(doc.find('.//bracket_start').text)
  1466. bracket_end = int(doc.find('.//bracket_end').text)
  1467. # TODO determine start (and probably fix up file)
  1468. # youtube-dl -v http://www.twitch.tv/firmbelief/c/1757457
  1469. #video_url += u'?start=' + TODO:start_timestamp
  1470. # bracket_start is 13290, but we want 51670615
  1471. self._downloader.report_warning(u'Chapter detected, but we can just download the whole file. '
  1472. u'Chapter starts at %s and ends at %s' % (formatSeconds(bracket_start), formatSeconds(bracket_end)))
  1473. info = {
  1474. 'id': u'c' + chapter_id,
  1475. 'url': video_url,
  1476. 'ext': video_ext,
  1477. 'title': chapter_info['title'],
  1478. 'thumbnail': chapter_info['preview'],
  1479. 'description': chapter_info['description'],
  1480. 'uploader': chapter_info['channel']['display_name'],
  1481. 'uploader_id': chapter_info['channel']['name'],
  1482. }
  1483. return [info]
  1484. else:
  1485. video_id = mobj.group('videoid')
  1486. api = api_base + '/broadcast/by_archive/%s.json' % video_id
  1487. self.report_extraction(video_id)
  1488. info = []
  1489. offset = 0
  1490. limit = self._JUSTIN_PAGE_LIMIT
  1491. while True:
  1492. if paged:
  1493. self.report_download_page(video_id, offset)
  1494. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  1495. page_count, page_info = self._parse_page(page_url, video_id)
  1496. info.extend(page_info)
  1497. if not paged or page_count != limit:
  1498. break
  1499. offset += limit
  1500. return info
  1501. class FunnyOrDieIE(InfoExtractor):
  1502. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  1503. def _real_extract(self, url):
  1504. mobj = re.match(self._VALID_URL, url)
  1505. if mobj is None:
  1506. raise ExtractorError(u'invalid URL: %s' % url)
  1507. video_id = mobj.group('id')
  1508. webpage = self._download_webpage(url, video_id)
  1509. video_url = self._html_search_regex(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"',
  1510. webpage, u'video URL', flags=re.DOTALL)
  1511. title = self._html_search_regex((r"<h1 class='player_page_h1'.*?>(?P<title>.*?)</h1>",
  1512. r'<title>(?P<title>[^<]+?)</title>'), webpage, 'title', flags=re.DOTALL)
  1513. video_description = self._html_search_regex(r'<meta property="og:description" content="(?P<desc>.*?)"',
  1514. webpage, u'description', fatal=False, flags=re.DOTALL)
  1515. info = {
  1516. 'id': video_id,
  1517. 'url': video_url,
  1518. 'ext': 'mp4',
  1519. 'title': title,
  1520. 'description': video_description,
  1521. }
  1522. return [info]
  1523. class SteamIE(InfoExtractor):
  1524. _VALID_URL = r"""http://store\.steampowered\.com/
  1525. (agecheck/)?
  1526. (?P<urltype>video|app)/ #If the page is only for videos or for a game
  1527. (?P<gameID>\d+)/?
  1528. (?P<videoID>\d*)(?P<extra>\??) #For urltype == video we sometimes get the videoID
  1529. """
  1530. _VIDEO_PAGE_TEMPLATE = 'http://store.steampowered.com/video/%s/'
  1531. _AGECHECK_TEMPLATE = 'http://store.steampowered.com/agecheck/video/%s/?snr=1_agecheck_agecheck__age-gate&ageDay=1&ageMonth=January&ageYear=1970'
  1532. @classmethod
  1533. def suitable(cls, url):
  1534. """Receives a URL and returns True if suitable for this IE."""
  1535. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1536. def _real_extract(self, url):
  1537. m = re.match(self._VALID_URL, url, re.VERBOSE)
  1538. gameID = m.group('gameID')
  1539. videourl = self._VIDEO_PAGE_TEMPLATE % gameID
  1540. webpage = self._download_webpage(videourl, gameID)
  1541. if re.search('<h2>Please enter your birth date to continue:</h2>', webpage) is not None:
  1542. videourl = self._AGECHECK_TEMPLATE % gameID
  1543. self.report_age_confirmation()
  1544. webpage = self._download_webpage(videourl, gameID)
  1545. self.report_extraction(gameID)
  1546. game_title = self._html_search_regex(r'<h2 class="pageheader">(.*?)</h2>',
  1547. webpage, 'game title')
  1548. urlRE = r"'movie_(?P<videoID>\d+)': \{\s*FILENAME: \"(?P<videoURL>[\w:/\.\?=]+)\"(,\s*MOVIE_NAME: \"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\},"
  1549. mweb = re.finditer(urlRE, webpage)
  1550. namesRE = r'<span class="title">(?P<videoName>.+?)</span>'
  1551. titles = re.finditer(namesRE, webpage)
  1552. thumbsRE = r'<img class="movie_thumb" src="(?P<thumbnail>.+?)">'
  1553. thumbs = re.finditer(thumbsRE, webpage)
  1554. videos = []
  1555. for vid,vtitle,thumb in zip(mweb,titles,thumbs):
  1556. video_id = vid.group('videoID')
  1557. title = vtitle.group('videoName')
  1558. video_url = vid.group('videoURL')
  1559. video_thumb = thumb.group('thumbnail')
  1560. if not video_url:
  1561. raise ExtractorError(u'Cannot find video url for %s' % video_id)
  1562. info = {
  1563. 'id':video_id,
  1564. 'url':video_url,
  1565. 'ext': 'flv',
  1566. 'title': unescapeHTML(title),
  1567. 'thumbnail': video_thumb
  1568. }
  1569. videos.append(info)
  1570. return [self.playlist_result(videos, gameID, game_title)]
  1571. class UstreamIE(InfoExtractor):
  1572. _VALID_URL = r'https?://www\.ustream\.tv/recorded/(?P<videoID>\d+)'
  1573. IE_NAME = u'ustream'
  1574. def _real_extract(self, url):
  1575. m = re.match(self._VALID_URL, url)
  1576. video_id = m.group('videoID')
  1577. video_url = u'http://tcdn.ustream.tv/video/%s' % video_id
  1578. webpage = self._download_webpage(url, video_id)
  1579. self.report_extraction(video_id)
  1580. video_title = self._html_search_regex(r'data-title="(?P<title>.+)"',
  1581. webpage, u'title')
  1582. uploader = self._html_search_regex(r'data-content-type="channel".*?>(?P<uploader>.*?)</a>',
  1583. webpage, u'uploader', fatal=False, flags=re.DOTALL)
  1584. thumbnail = self._html_search_regex(r'<link rel="image_src" href="(?P<thumb>.*?)"',
  1585. webpage, u'thumbnail', fatal=False)
  1586. info = {
  1587. 'id': video_id,
  1588. 'url': video_url,
  1589. 'ext': 'flv',
  1590. 'title': video_title,
  1591. 'uploader': uploader,
  1592. 'thumbnail': thumbnail,
  1593. }
  1594. return info
  1595. class WorldStarHipHopIE(InfoExtractor):
  1596. _VALID_URL = r'https?://(?:www|m)\.worldstar(?:candy|hiphop)\.com/videos/video\.php\?v=(?P<id>.*)'
  1597. IE_NAME = u'WorldStarHipHop'
  1598. def _real_extract(self, url):
  1599. m = re.match(self._VALID_URL, url)
  1600. video_id = m.group('id')
  1601. webpage_src = self._download_webpage(url, video_id)
  1602. video_url = self._search_regex(r'so\.addVariable\("file","(.*?)"\)',
  1603. webpage_src, u'video URL')
  1604. if 'mp4' in video_url:
  1605. ext = 'mp4'
  1606. else:
  1607. ext = 'flv'
  1608. video_title = self._html_search_regex(r"<title>(.*)</title>",
  1609. webpage_src, u'title')
  1610. # Getting thumbnail and if not thumbnail sets correct title for WSHH candy video.
  1611. thumbnail = self._html_search_regex(r'rel="image_src" href="(.*)" />',
  1612. webpage_src, u'thumbnail', fatal=False)
  1613. if not thumbnail:
  1614. _title = r"""candytitles.*>(.*)</span>"""
  1615. mobj = re.search(_title, webpage_src)
  1616. if mobj is not None:
  1617. video_title = mobj.group(1)
  1618. results = [{
  1619. 'id': video_id,
  1620. 'url' : video_url,
  1621. 'title' : video_title,
  1622. 'thumbnail' : thumbnail,
  1623. 'ext' : ext,
  1624. }]
  1625. return results
  1626. class RBMARadioIE(InfoExtractor):
  1627. _VALID_URL = r'https?://(?:www\.)?rbmaradio\.com/shows/(?P<videoID>[^/]+)$'
  1628. def _real_extract(self, url):
  1629. m = re.match(self._VALID_URL, url)
  1630. video_id = m.group('videoID')
  1631. webpage = self._download_webpage(url, video_id)
  1632. json_data = self._search_regex(r'window\.gon.*?gon\.show=(.+?);$',
  1633. webpage, u'json data', flags=re.MULTILINE)
  1634. try:
  1635. data = json.loads(json_data)
  1636. except ValueError as e:
  1637. raise ExtractorError(u'Invalid JSON: ' + str(e))
  1638. video_url = data['akamai_url'] + '&cbr=256'
  1639. url_parts = compat_urllib_parse_urlparse(video_url)
  1640. video_ext = url_parts.path.rpartition('.')[2]
  1641. info = {
  1642. 'id': video_id,
  1643. 'url': video_url,
  1644. 'ext': video_ext,
  1645. 'title': data['title'],
  1646. 'description': data.get('teaser_text'),
  1647. 'location': data.get('country_of_origin'),
  1648. 'uploader': data.get('host', {}).get('name'),
  1649. 'uploader_id': data.get('host', {}).get('slug'),
  1650. 'thumbnail': data.get('image', {}).get('large_url_2x'),
  1651. 'duration': data.get('duration'),
  1652. }
  1653. return [info]
  1654. class YouPornIE(InfoExtractor):
  1655. """Information extractor for youporn.com."""
  1656. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
  1657. def _print_formats(self, formats):
  1658. """Print all available formats"""
  1659. print(u'Available formats:')
  1660. print(u'ext\t\tformat')
  1661. print(u'---------------------------------')
  1662. for format in formats:
  1663. print(u'%s\t\t%s' % (format['ext'], format['format']))
  1664. def _specific(self, req_format, formats):
  1665. for x in formats:
  1666. if(x["format"]==req_format):
  1667. return x
  1668. return None
  1669. def _real_extract(self, url):
  1670. mobj = re.match(self._VALID_URL, url)
  1671. if mobj is None:
  1672. raise ExtractorError(u'Invalid URL: %s' % url)
  1673. video_id = mobj.group('videoid')
  1674. req = compat_urllib_request.Request(url)
  1675. req.add_header('Cookie', 'age_verified=1')
  1676. webpage = self._download_webpage(req, video_id)
  1677. # Get JSON parameters
  1678. json_params = self._search_regex(r'var currentVideo = new Video\((.*)\);', webpage, u'JSON parameters')
  1679. try:
  1680. params = json.loads(json_params)
  1681. except:
  1682. raise ExtractorError(u'Invalid JSON')
  1683. self.report_extraction(video_id)
  1684. try:
  1685. video_title = params['title']
  1686. upload_date = unified_strdate(params['release_date_f'])
  1687. video_description = params['description']
  1688. video_uploader = params['submitted_by']
  1689. thumbnail = params['thumbnails'][0]['image']
  1690. except KeyError:
  1691. raise ExtractorError('Missing JSON parameter: ' + sys.exc_info()[1])
  1692. # Get all of the formats available
  1693. DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
  1694. download_list_html = self._search_regex(DOWNLOAD_LIST_RE,
  1695. webpage, u'download list').strip()
  1696. # Get all of the links from the page
  1697. LINK_RE = r'(?s)<a href="(?P<url>[^"]+)">'
  1698. links = re.findall(LINK_RE, download_list_html)
  1699. if(len(links) == 0):
  1700. raise ExtractorError(u'ERROR: no known formats available for video')
  1701. self.to_screen(u'Links found: %d' % len(links))
  1702. formats = []
  1703. for link in links:
  1704. # A link looks like this:
  1705. # http://cdn1.download.youporn.phncdn.com/201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4?nvb=20121113051249&nva=20121114051249&ir=1200&sr=1200&hash=014b882080310e95fb6a0
  1706. # A path looks like this:
  1707. # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
  1708. video_url = unescapeHTML( link )
  1709. path = compat_urllib_parse_urlparse( video_url ).path
  1710. extension = os.path.splitext( path )[1][1:]
  1711. format = path.split('/')[4].split('_')[:2]
  1712. size = format[0]
  1713. bitrate = format[1]
  1714. format = "-".join( format )
  1715. # title = u'%s-%s-%s' % (video_title, size, bitrate)
  1716. formats.append({
  1717. 'id': video_id,
  1718. 'url': video_url,
  1719. 'uploader': video_uploader,
  1720. 'upload_date': upload_date,
  1721. 'title': video_title,
  1722. 'ext': extension,
  1723. 'format': format,
  1724. 'thumbnail': thumbnail,
  1725. 'description': video_description
  1726. })
  1727. if self._downloader.params.get('listformats', None):
  1728. self._print_formats(formats)
  1729. return
  1730. req_format = self._downloader.params.get('format', None)
  1731. self.to_screen(u'Format: %s' % req_format)
  1732. if req_format is None or req_format == 'best':
  1733. return [formats[0]]
  1734. elif req_format == 'worst':
  1735. return [formats[-1]]
  1736. elif req_format in ('-1', 'all'):
  1737. return formats
  1738. else:
  1739. format = self._specific( req_format, formats )
  1740. if result is None:
  1741. raise ExtractorError(u'Requested format not available')
  1742. return [format]
  1743. class PornotubeIE(InfoExtractor):
  1744. """Information extractor for pornotube.com."""
  1745. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?pornotube\.com(/c/(?P<channel>[0-9]+))?(/m/(?P<videoid>[0-9]+))(/(?P<title>.+))$'
  1746. def _real_extract(self, url):
  1747. mobj = re.match(self._VALID_URL, url)
  1748. if mobj is None:
  1749. raise ExtractorError(u'Invalid URL: %s' % url)
  1750. video_id = mobj.group('videoid')
  1751. video_title = mobj.group('title')
  1752. # Get webpage content
  1753. webpage = self._download_webpage(url, video_id)
  1754. # Get the video URL
  1755. VIDEO_URL_RE = r'url: "(?P<url>http://video[0-9].pornotube.com/.+\.flv)",'
  1756. video_url = self._search_regex(VIDEO_URL_RE, webpage, u'video url')
  1757. video_url = compat_urllib_parse.unquote(video_url)
  1758. #Get the uploaded date
  1759. VIDEO_UPLOADED_RE = r'<div class="video_added_by">Added (?P<date>[0-9\/]+) by'
  1760. upload_date = self._html_search_regex(VIDEO_UPLOADED_RE, webpage, u'upload date', fatal=False)
  1761. if upload_date: upload_date = unified_strdate(upload_date)
  1762. info = {'id': video_id,
  1763. 'url': video_url,
  1764. 'uploader': None,
  1765. 'upload_date': upload_date,
  1766. 'title': video_title,
  1767. 'ext': 'flv',
  1768. 'format': 'flv'}
  1769. return [info]
  1770. class YouJizzIE(InfoExtractor):
  1771. """Information extractor for youjizz.com."""
  1772. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youjizz\.com/videos/(?P<videoid>[^.]+).html$'
  1773. def _real_extract(self, url):
  1774. mobj = re.match(self._VALID_URL, url)
  1775. if mobj is None:
  1776. raise ExtractorError(u'Invalid URL: %s' % url)
  1777. video_id = mobj.group('videoid')
  1778. # Get webpage content
  1779. webpage = self._download_webpage(url, video_id)
  1780. # Get the video title
  1781. video_title = self._html_search_regex(r'<title>(?P<title>.*)</title>',
  1782. webpage, u'title').strip()
  1783. # Get the embed page
  1784. result = re.search(r'https?://www.youjizz.com/videos/embed/(?P<videoid>[0-9]+)', webpage)
  1785. if result is None:
  1786. raise ExtractorError(u'ERROR: unable to extract embed page')
  1787. embed_page_url = result.group(0).strip()
  1788. video_id = result.group('videoid')
  1789. webpage = self._download_webpage(embed_page_url, video_id)
  1790. # Get the video URL
  1791. video_url = self._search_regex(r'so.addVariable\("file",encodeURIComponent\("(?P<source>[^"]+)"\)\);',
  1792. webpage, u'video URL')
  1793. info = {'id': video_id,
  1794. 'url': video_url,
  1795. 'title': video_title,
  1796. 'ext': 'flv',
  1797. 'format': 'flv',
  1798. 'player_url': embed_page_url}
  1799. return [info]
  1800. class EightTracksIE(InfoExtractor):
  1801. IE_NAME = '8tracks'
  1802. _VALID_URL = r'https?://8tracks.com/(?P<user>[^/]+)/(?P<id>[^/#]+)(?:#.*)?$'
  1803. def _real_extract(self, url):
  1804. mobj = re.match(self._VALID_URL, url)
  1805. if mobj is None:
  1806. raise ExtractorError(u'Invalid URL: %s' % url)
  1807. playlist_id = mobj.group('id')
  1808. webpage = self._download_webpage(url, playlist_id)
  1809. json_like = self._search_regex(r"PAGE.mix = (.*?);\n", webpage, u'trax information', flags=re.DOTALL)
  1810. data = json.loads(json_like)
  1811. session = str(random.randint(0, 1000000000))
  1812. mix_id = data['id']
  1813. track_count = data['tracks_count']
  1814. first_url = 'http://8tracks.com/sets/%s/play?player=sm&mix_id=%s&format=jsonh' % (session, mix_id)
  1815. next_url = first_url
  1816. res = []
  1817. for i in itertools.count():
  1818. api_json = self._download_webpage(next_url, playlist_id,
  1819. note=u'Downloading song information %s/%s' % (str(i+1), track_count),
  1820. errnote=u'Failed to download song information')
  1821. api_data = json.loads(api_json)
  1822. track_data = api_data[u'set']['track']
  1823. info = {
  1824. 'id': track_data['id'],
  1825. 'url': track_data['track_file_stream_url'],
  1826. 'title': track_data['performer'] + u' - ' + track_data['name'],
  1827. 'raw_title': track_data['name'],
  1828. 'uploader_id': data['user']['login'],
  1829. 'ext': 'm4a',
  1830. }
  1831. res.append(info)
  1832. if api_data['set']['at_last_track']:
  1833. break
  1834. next_url = 'http://8tracks.com/sets/%s/next?player=sm&mix_id=%s&format=jsonh&track_id=%s' % (session, mix_id, track_data['id'])
  1835. return res
  1836. class KeekIE(InfoExtractor):
  1837. _VALID_URL = r'http://(?:www\.)?keek\.com/(?:!|\w+/keeks/)(?P<videoID>\w+)'
  1838. IE_NAME = u'keek'
  1839. def _real_extract(self, url):
  1840. m = re.match(self._VALID_URL, url)
  1841. video_id = m.group('videoID')
  1842. video_url = u'http://cdn.keek.com/keek/video/%s' % video_id
  1843. thumbnail = u'http://cdn.keek.com/keek/thumbnail/%s/w100/h75' % video_id
  1844. webpage = self._download_webpage(url, video_id)
  1845. video_title = self._html_search_regex(r'<meta property="og:title" content="(?P<title>.*?)"',
  1846. webpage, u'title')
  1847. uploader = self._html_search_regex(r'<div class="user-name-and-bio">[\S\s]+?<h2>(?P<uploader>.+?)</h2>',
  1848. webpage, u'uploader', fatal=False)
  1849. info = {
  1850. 'id': video_id,
  1851. 'url': video_url,
  1852. 'ext': 'mp4',
  1853. 'title': video_title,
  1854. 'thumbnail': thumbnail,
  1855. 'uploader': uploader
  1856. }
  1857. return [info]
  1858. class TEDIE(InfoExtractor):
  1859. _VALID_URL=r'''http://www\.ted\.com/
  1860. (
  1861. ((?P<type_playlist>playlists)/(?P<playlist_id>\d+)) # We have a playlist
  1862. |
  1863. ((?P<type_talk>talks)) # We have a simple talk
  1864. )
  1865. (/lang/(.*?))? # The url may contain the language
  1866. /(?P<name>\w+) # Here goes the name and then ".html"
  1867. '''
  1868. @classmethod
  1869. def suitable(cls, url):
  1870. """Receives a URL and returns True if suitable for this IE."""
  1871. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1872. def _real_extract(self, url):
  1873. m=re.match(self._VALID_URL, url, re.VERBOSE)
  1874. if m.group('type_talk'):
  1875. return [self._talk_info(url)]
  1876. else :
  1877. playlist_id=m.group('playlist_id')
  1878. name=m.group('name')
  1879. self.to_screen(u'Getting info of playlist %s: "%s"' % (playlist_id,name))
  1880. return [self._playlist_videos_info(url,name,playlist_id)]
  1881. def _playlist_videos_info(self,url,name,playlist_id=0):
  1882. '''Returns the videos of the playlist'''
  1883. video_RE=r'''
  1884. <li\ id="talk_(\d+)"([.\s]*?)data-id="(?P<video_id>\d+)"
  1885. ([.\s]*?)data-playlist_item_id="(\d+)"
  1886. ([.\s]*?)data-mediaslug="(?P<mediaSlug>.+?)"
  1887. '''
  1888. video_name_RE=r'<p\ class="talk-title"><a href="(?P<talk_url>/talks/(.+).html)">(?P<fullname>.+?)</a></p>'
  1889. webpage=self._download_webpage(url, playlist_id, 'Downloading playlist webpage')
  1890. m_videos=re.finditer(video_RE,webpage,re.VERBOSE)
  1891. m_names=re.finditer(video_name_RE,webpage)
  1892. playlist_title = self._html_search_regex(r'div class="headline">\s*?<h1>\s*?<span>(.*?)</span>',
  1893. webpage, 'playlist title')
  1894. playlist_entries = []
  1895. for m_video, m_name in zip(m_videos,m_names):
  1896. video_id=m_video.group('video_id')
  1897. talk_url='http://www.ted.com%s' % m_name.group('talk_url')
  1898. playlist_entries.append(self.url_result(talk_url, 'TED'))
  1899. return self.playlist_result(playlist_entries, playlist_id = playlist_id, playlist_title = playlist_title)
  1900. def _talk_info(self, url, video_id=0):
  1901. """Return the video for the talk in the url"""
  1902. m = re.match(self._VALID_URL, url,re.VERBOSE)
  1903. video_name = m.group('name')
  1904. webpage = self._download_webpage(url, video_id, 'Downloading \"%s\" page' % video_name)
  1905. self.report_extraction(video_name)
  1906. # If the url includes the language we get the title translated
  1907. title = self._html_search_regex(r'<span id="altHeadline" >(?P<title>.*)</span>',
  1908. webpage, 'title')
  1909. json_data = self._search_regex(r'<script.*?>var talkDetails = ({.*?})</script>',
  1910. webpage, 'json data')
  1911. info = json.loads(json_data)
  1912. desc = self._html_search_regex(r'<div class="talk-intro">.*?<p.*?>(.*?)</p>',
  1913. webpage, 'description', flags = re.DOTALL)
  1914. thumbnail = self._search_regex(r'</span>[\s.]*</div>[\s.]*<img src="(.*?)"',
  1915. webpage, 'thumbnail')
  1916. info = {
  1917. 'id': info['id'],
  1918. 'url': info['htmlStreams'][-1]['file'],
  1919. 'ext': 'mp4',
  1920. 'title': title,
  1921. 'thumbnail': thumbnail,
  1922. 'description': desc,
  1923. }
  1924. return info
  1925. class MySpassIE(InfoExtractor):
  1926. _VALID_URL = r'http://www.myspass.de/.*'
  1927. def _real_extract(self, url):
  1928. META_DATA_URL_TEMPLATE = 'http://www.myspass.de/myspass/includes/apps/video/getvideometadataxml.php?id=%s'
  1929. # video id is the last path element of the URL
  1930. # usually there is a trailing slash, so also try the second but last
  1931. url_path = compat_urllib_parse_urlparse(url).path
  1932. url_parent_path, video_id = os.path.split(url_path)
  1933. if not video_id:
  1934. _, video_id = os.path.split(url_parent_path)
  1935. # get metadata
  1936. metadata_url = META_DATA_URL_TEMPLATE % video_id
  1937. metadata_text = self._download_webpage(metadata_url, video_id)
  1938. metadata = xml.etree.ElementTree.fromstring(metadata_text.encode('utf-8'))
  1939. # extract values from metadata
  1940. url_flv_el = metadata.find('url_flv')
  1941. if url_flv_el is None:
  1942. raise ExtractorError(u'Unable to extract download url')
  1943. video_url = url_flv_el.text
  1944. extension = os.path.splitext(video_url)[1][1:]
  1945. title_el = metadata.find('title')
  1946. if title_el is None:
  1947. raise ExtractorError(u'Unable to extract title')
  1948. title = title_el.text
  1949. format_id_el = metadata.find('format_id')
  1950. if format_id_el is None:
  1951. format = ext
  1952. else:
  1953. format = format_id_el.text
  1954. description_el = metadata.find('description')
  1955. if description_el is not None:
  1956. description = description_el.text
  1957. else:
  1958. description = None
  1959. imagePreview_el = metadata.find('imagePreview')
  1960. if imagePreview_el is not None:
  1961. thumbnail = imagePreview_el.text
  1962. else:
  1963. thumbnail = None
  1964. info = {
  1965. 'id': video_id,
  1966. 'url': video_url,
  1967. 'title': title,
  1968. 'ext': extension,
  1969. 'format': format,
  1970. 'thumbnail': thumbnail,
  1971. 'description': description
  1972. }
  1973. return [info]
  1974. class SpiegelIE(InfoExtractor):
  1975. _VALID_URL = r'https?://(?:www\.)?spiegel\.de/video/[^/]*-(?P<videoID>[0-9]+)(?:\.html)?(?:#.*)?$'
  1976. def _real_extract(self, url):
  1977. m = re.match(self._VALID_URL, url)
  1978. video_id = m.group('videoID')
  1979. webpage = self._download_webpage(url, video_id)
  1980. video_title = self._html_search_regex(r'<div class="module-title">(.*?)</div>',
  1981. webpage, u'title')
  1982. xml_url = u'http://video2.spiegel.de/flash/' + video_id + u'.xml'
  1983. xml_code = self._download_webpage(xml_url, video_id,
  1984. note=u'Downloading XML', errnote=u'Failed to download XML')
  1985. idoc = xml.etree.ElementTree.fromstring(xml_code)
  1986. last_type = idoc[-1]
  1987. filename = last_type.findall('./filename')[0].text
  1988. duration = float(last_type.findall('./duration')[0].text)
  1989. video_url = 'http://video2.spiegel.de/flash/' + filename
  1990. video_ext = filename.rpartition('.')[2]
  1991. info = {
  1992. 'id': video_id,
  1993. 'url': video_url,
  1994. 'ext': video_ext,
  1995. 'title': video_title,
  1996. 'duration': duration,
  1997. }
  1998. return [info]
  1999. class LiveLeakIE(InfoExtractor):
  2000. _VALID_URL = r'^(?:http?://)?(?:\w+\.)?liveleak\.com/view\?(?:.*?)i=(?P<video_id>[\w_]+)(?:.*)'
  2001. IE_NAME = u'liveleak'
  2002. def _real_extract(self, url):
  2003. mobj = re.match(self._VALID_URL, url)
  2004. if mobj is None:
  2005. raise ExtractorError(u'Invalid URL: %s' % url)
  2006. video_id = mobj.group('video_id')
  2007. webpage = self._download_webpage(url, video_id)
  2008. video_url = self._search_regex(r'file: "(.*?)",',
  2009. webpage, u'video URL')
  2010. video_title = self._html_search_regex(r'<meta property="og:title" content="(?P<title>.*?)"',
  2011. webpage, u'title').replace('LiveLeak.com -', '').strip()
  2012. video_description = self._html_search_regex(r'<meta property="og:description" content="(?P<desc>.*?)"',
  2013. webpage, u'description', fatal=False)
  2014. video_uploader = self._html_search_regex(r'By:.*?(\w+)</a>',
  2015. webpage, u'uploader', fatal=False)
  2016. info = {
  2017. 'id': video_id,
  2018. 'url': video_url,
  2019. 'ext': 'mp4',
  2020. 'title': video_title,
  2021. 'description': video_description,
  2022. 'uploader': video_uploader
  2023. }
  2024. return [info]
  2025. class TumblrIE(InfoExtractor):
  2026. _VALID_URL = r'http://(?P<blog_name>.*?)\.tumblr\.com/((post)|(video))/(?P<id>\d*)/(.*?)'
  2027. def _real_extract(self, url):
  2028. m_url = re.match(self._VALID_URL, url)
  2029. video_id = m_url.group('id')
  2030. blog = m_url.group('blog_name')
  2031. url = 'http://%s.tumblr.com/post/%s/' % (blog, video_id)
  2032. webpage = self._download_webpage(url, video_id)
  2033. re_video = r'src=\\x22(?P<video_url>http://%s\.tumblr\.com/video_file/%s/(.*?))\\x22 type=\\x22video/(?P<ext>.*?)\\x22' % (blog, video_id)
  2034. video = re.search(re_video, webpage)
  2035. if video is None:
  2036. raise ExtractorError(u'Unable to extract video')
  2037. video_url = video.group('video_url')
  2038. ext = video.group('ext')
  2039. video_thumbnail = self._search_regex(r'posters(.*?)\[\\x22(?P<thumb>.*?)\\x22',
  2040. webpage, u'thumbnail', fatal=False) # We pick the first poster
  2041. if video_thumbnail: video_thumbnail = video_thumbnail.replace('\\', '')
  2042. # The only place where you can get a title, it's not complete,
  2043. # but searching in other places doesn't work for all videos
  2044. video_title = self._html_search_regex(r'<title>(?P<title>.*?)</title>',
  2045. webpage, u'title', flags=re.DOTALL)
  2046. return [{'id': video_id,
  2047. 'url': video_url,
  2048. 'title': video_title,
  2049. 'thumbnail': video_thumbnail,
  2050. 'ext': ext
  2051. }]
  2052. class BandcampIE(InfoExtractor):
  2053. _VALID_URL = r'http://.*?\.bandcamp\.com/track/(?P<title>.*)'
  2054. def _real_extract(self, url):
  2055. mobj = re.match(self._VALID_URL, url)
  2056. title = mobj.group('title')
  2057. webpage = self._download_webpage(url, title)
  2058. # We get the link to the free download page
  2059. m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
  2060. if m_download is None:
  2061. raise ExtractorError(u'No free songs found')
  2062. download_link = m_download.group(1)
  2063. id = re.search(r'var TralbumData = {(.*?)id: (?P<id>\d*?)$',
  2064. webpage, re.MULTILINE|re.DOTALL).group('id')
  2065. download_webpage = self._download_webpage(download_link, id,
  2066. 'Downloading free downloads page')
  2067. # We get the dictionary of the track from some javascrip code
  2068. info = re.search(r'items: (.*?),$',
  2069. download_webpage, re.MULTILINE).group(1)
  2070. info = json.loads(info)[0]
  2071. # We pick mp3-320 for now, until format selection can be easily implemented.
  2072. mp3_info = info[u'downloads'][u'mp3-320']
  2073. # If we try to use this url it says the link has expired
  2074. initial_url = mp3_info[u'url']
  2075. re_url = r'(?P<server>http://(.*?)\.bandcamp\.com)/download/track\?enc=mp3-320&fsig=(?P<fsig>.*?)&id=(?P<id>.*?)&ts=(?P<ts>.*)$'
  2076. m_url = re.match(re_url, initial_url)
  2077. #We build the url we will use to get the final track url
  2078. # This url is build in Bandcamp in the script download_bunde_*.js
  2079. request_url = '%s/statdownload/track?enc=mp3-320&fsig=%s&id=%s&ts=%s&.rand=665028774616&.vrs=1' % (m_url.group('server'), m_url.group('fsig'), id, m_url.group('ts'))
  2080. final_url_webpage = self._download_webpage(request_url, id, 'Requesting download url')
  2081. # If we could correctly generate the .rand field the url would be
  2082. #in the "download_url" key
  2083. final_url = re.search(r'"retry_url":"(.*?)"', final_url_webpage).group(1)
  2084. track_info = {'id':id,
  2085. 'title' : info[u'title'],
  2086. 'ext' : 'mp3',
  2087. 'url' : final_url,
  2088. 'thumbnail' : info[u'thumb_url'],
  2089. 'uploader' : info[u'artist']
  2090. }
  2091. return [track_info]
  2092. class RedTubeIE(InfoExtractor):
  2093. """Information Extractor for redtube"""
  2094. _VALID_URL = r'(?:http://)?(?:www\.)?redtube\.com/(?P<id>[0-9]+)'
  2095. def _real_extract(self,url):
  2096. mobj = re.match(self._VALID_URL, url)
  2097. if mobj is None:
  2098. raise ExtractorError(u'Invalid URL: %s' % url)
  2099. video_id = mobj.group('id')
  2100. video_extension = 'mp4'
  2101. webpage = self._download_webpage(url, video_id)
  2102. self.report_extraction(video_id)
  2103. video_url = self._html_search_regex(r'<source src="(.+?)" type="video/mp4">',
  2104. webpage, u'video URL')
  2105. video_title = self._html_search_regex('<h1 class="videoTitle slidePanelMovable">(.+?)</h1>',
  2106. webpage, u'title')
  2107. return [{
  2108. 'id': video_id,
  2109. 'url': video_url,
  2110. 'ext': video_extension,
  2111. 'title': video_title,
  2112. }]
  2113. class InaIE(InfoExtractor):
  2114. """Information Extractor for Ina.fr"""
  2115. _VALID_URL = r'(?:http://)?(?:www\.)?ina\.fr/video/(?P<id>I[0-9]+)/.*'
  2116. def _real_extract(self,url):
  2117. mobj = re.match(self._VALID_URL, url)
  2118. video_id = mobj.group('id')
  2119. mrss_url='http://player.ina.fr/notices/%s.mrss' % video_id
  2120. video_extension = 'mp4'
  2121. webpage = self._download_webpage(mrss_url, video_id)
  2122. self.report_extraction(video_id)
  2123. video_url = self._html_search_regex(r'<media:player url="(?P<mp4url>http://mp4.ina.fr/[^"]+\.mp4)',
  2124. webpage, u'video URL')
  2125. video_title = self._search_regex(r'<title><!\[CDATA\[(?P<titre>.*?)]]></title>',
  2126. webpage, u'title')
  2127. return [{
  2128. 'id': video_id,
  2129. 'url': video_url,
  2130. 'ext': video_extension,
  2131. 'title': video_title,
  2132. }]
  2133. class HowcastIE(InfoExtractor):
  2134. """Information Extractor for Howcast.com"""
  2135. _VALID_URL = r'(?:https?://)?(?:www\.)?howcast\.com/videos/(?P<id>\d+)'
  2136. def _real_extract(self, url):
  2137. mobj = re.match(self._VALID_URL, url)
  2138. video_id = mobj.group('id')
  2139. webpage_url = 'http://www.howcast.com/videos/' + video_id
  2140. webpage = self._download_webpage(webpage_url, video_id)
  2141. self.report_extraction(video_id)
  2142. video_url = self._search_regex(r'\'?file\'?: "(http://mobile-media\.howcast\.com/[0-9]+\.mp4)',
  2143. webpage, u'video URL')
  2144. video_title = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') property=\'og:title\'',
  2145. webpage, u'title')
  2146. video_description = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') name=\'description\'',
  2147. webpage, u'description', fatal=False)
  2148. thumbnail = self._html_search_regex(r'<meta content=\'(.+?)\' property=\'og:image\'',
  2149. webpage, u'thumbnail', fatal=False)
  2150. return [{
  2151. 'id': video_id,
  2152. 'url': video_url,
  2153. 'ext': 'mp4',
  2154. 'title': video_title,
  2155. 'description': video_description,
  2156. 'thumbnail': thumbnail,
  2157. }]
  2158. class VineIE(InfoExtractor):
  2159. """Information Extractor for Vine.co"""
  2160. _VALID_URL = r'(?:https?://)?(?:www\.)?vine\.co/v/(?P<id>\w+)'
  2161. def _real_extract(self, url):
  2162. mobj = re.match(self._VALID_URL, url)
  2163. video_id = mobj.group('id')
  2164. webpage_url = 'https://vine.co/v/' + video_id
  2165. webpage = self._download_webpage(webpage_url, video_id)
  2166. self.report_extraction(video_id)
  2167. video_url = self._html_search_regex(r'<meta property="twitter:player:stream" content="(.+?)"',
  2168. webpage, u'video URL')
  2169. video_title = self._html_search_regex(r'<meta property="og:title" content="(.+?)"',
  2170. webpage, u'title')
  2171. thumbnail = self._html_search_regex(r'<meta property="og:image" content="(.+?)(\?.*?)?"',
  2172. webpage, u'thumbnail', fatal=False)
  2173. uploader = self._html_search_regex(r'<div class="user">.*?<h2>(.+?)</h2>',
  2174. webpage, u'uploader', fatal=False, flags=re.DOTALL)
  2175. return [{
  2176. 'id': video_id,
  2177. 'url': video_url,
  2178. 'ext': 'mp4',
  2179. 'title': video_title,
  2180. 'thumbnail': thumbnail,
  2181. 'uploader': uploader,
  2182. }]
  2183. class FlickrIE(InfoExtractor):
  2184. """Information Extractor for Flickr videos"""
  2185. _VALID_URL = r'(?:https?://)?(?:www\.)?flickr\.com/photos/(?P<uploader_id>[\w\-_@]+)/(?P<id>\d+).*'
  2186. def _real_extract(self, url):
  2187. mobj = re.match(self._VALID_URL, url)
  2188. video_id = mobj.group('id')
  2189. video_uploader_id = mobj.group('uploader_id')
  2190. webpage_url = 'http://www.flickr.com/photos/' + video_uploader_id + '/' + video_id
  2191. webpage = self._download_webpage(webpage_url, video_id)
  2192. secret = self._search_regex(r"photo_secret: '(\w+)'", webpage, u'secret')
  2193. first_url = 'https://secure.flickr.com/apps/video/video_mtl_xml.gne?v=x&photo_id=' + video_id + '&secret=' + secret + '&bitrate=700&target=_self'
  2194. first_xml = self._download_webpage(first_url, video_id, 'Downloading first data webpage')
  2195. node_id = self._html_search_regex(r'<Item id="id">(\d+-\d+)</Item>',
  2196. first_xml, u'node_id')
  2197. second_url = 'https://secure.flickr.com/video_playlist.gne?node_id=' + node_id + '&tech=flash&mode=playlist&bitrate=700&secret=' + secret + '&rd=video.yahoo.com&noad=1'
  2198. second_xml = self._download_webpage(second_url, video_id, 'Downloading second data webpage')
  2199. self.report_extraction(video_id)
  2200. mobj = re.search(r'<STREAM APP="(.+?)" FULLPATH="(.+?)"', second_xml)
  2201. if mobj is None:
  2202. raise ExtractorError(u'Unable to extract video url')
  2203. video_url = mobj.group(1) + unescapeHTML(mobj.group(2))
  2204. video_title = self._html_search_regex(r'<meta property="og:title" content=(?:"([^"]+)"|\'([^\']+)\')',
  2205. webpage, u'video title')
  2206. video_description = self._html_search_regex(r'<meta property="og:description" content=(?:"([^"]+)"|\'([^\']+)\')',
  2207. webpage, u'description', fatal=False)
  2208. thumbnail = self._html_search_regex(r'<meta property="og:image" content=(?:"([^"]+)"|\'([^\']+)\')',
  2209. webpage, u'thumbnail', fatal=False)
  2210. return [{
  2211. 'id': video_id,
  2212. 'url': video_url,
  2213. 'ext': 'mp4',
  2214. 'title': video_title,
  2215. 'description': video_description,
  2216. 'thumbnail': thumbnail,
  2217. 'uploader_id': video_uploader_id,
  2218. }]
  2219. class TeamcocoIE(InfoExtractor):
  2220. _VALID_URL = r'http://teamcoco\.com/video/(?P<url_title>.*)'
  2221. def _real_extract(self, url):
  2222. mobj = re.match(self._VALID_URL, url)
  2223. if mobj is None:
  2224. raise ExtractorError(u'Invalid URL: %s' % url)
  2225. url_title = mobj.group('url_title')
  2226. webpage = self._download_webpage(url, url_title)
  2227. video_id = self._html_search_regex(r'<article class="video" data-id="(\d+?)"',
  2228. webpage, u'video id')
  2229. self.report_extraction(video_id)
  2230. video_title = self._html_search_regex(r'<meta property="og:title" content="(.+?)"',
  2231. webpage, u'title')
  2232. thumbnail = self._html_search_regex(r'<meta property="og:image" content="(.+?)"',
  2233. webpage, u'thumbnail', fatal=False)
  2234. video_description = self._html_search_regex(r'<meta property="og:description" content="(.*?)"',
  2235. webpage, u'description', fatal=False)
  2236. data_url = 'http://teamcoco.com/cvp/2.0/%s.xml' % video_id
  2237. data = self._download_webpage(data_url, video_id, 'Downloading data webpage')
  2238. video_url = self._html_search_regex(r'<file type="high".*?>(.*?)</file>',
  2239. data, u'video URL')
  2240. return [{
  2241. 'id': video_id,
  2242. 'url': video_url,
  2243. 'ext': 'mp4',
  2244. 'title': video_title,
  2245. 'thumbnail': thumbnail,
  2246. 'description': video_description,
  2247. }]
  2248. class XHamsterIE(InfoExtractor):
  2249. """Information Extractor for xHamster"""
  2250. _VALID_URL = r'(?:http://)?(?:www.)?xhamster\.com/movies/(?P<id>[0-9]+)/.*\.html'
  2251. def _real_extract(self,url):
  2252. mobj = re.match(self._VALID_URL, url)
  2253. video_id = mobj.group('id')
  2254. mrss_url = 'http://xhamster.com/movies/%s/.html' % video_id
  2255. webpage = self._download_webpage(mrss_url, video_id)
  2256. mobj = re.search(r'\'srv\': \'(?P<server>[^\']*)\',\s*\'file\': \'(?P<file>[^\']+)\',', webpage)
  2257. if mobj is None:
  2258. raise ExtractorError(u'Unable to extract media URL')
  2259. if len(mobj.group('server')) == 0:
  2260. video_url = compat_urllib_parse.unquote(mobj.group('file'))
  2261. else:
  2262. video_url = mobj.group('server')+'/key='+mobj.group('file')
  2263. video_extension = video_url.split('.')[-1]
  2264. video_title = self._html_search_regex(r'<title>(?P<title>.+?) - xHamster\.com</title>',
  2265. webpage, u'title')
  2266. # Can't see the description anywhere in the UI
  2267. # video_description = self._html_search_regex(r'<span>Description: </span>(?P<description>[^<]+)',
  2268. # webpage, u'description', fatal=False)
  2269. # if video_description: video_description = unescapeHTML(video_description)
  2270. mobj = re.search(r'hint=\'(?P<upload_date_Y>[0-9]{4})-(?P<upload_date_m>[0-9]{2})-(?P<upload_date_d>[0-9]{2}) [0-9]{2}:[0-9]{2}:[0-9]{2} [A-Z]{3,4}\'', webpage)
  2271. if mobj:
  2272. video_upload_date = mobj.group('upload_date_Y')+mobj.group('upload_date_m')+mobj.group('upload_date_d')
  2273. else:
  2274. video_upload_date = None
  2275. self._downloader.report_warning(u'Unable to extract upload date')
  2276. video_uploader_id = self._html_search_regex(r'<a href=\'/user/[^>]+>(?P<uploader_id>[^<]+)',
  2277. webpage, u'uploader id', default=u'anonymous')
  2278. video_thumbnail = self._search_regex(r'\'image\':\'(?P<thumbnail>[^\']+)\'',
  2279. webpage, u'thumbnail', fatal=False)
  2280. return [{
  2281. 'id': video_id,
  2282. 'url': video_url,
  2283. 'ext': video_extension,
  2284. 'title': video_title,
  2285. # 'description': video_description,
  2286. 'upload_date': video_upload_date,
  2287. 'uploader_id': video_uploader_id,
  2288. 'thumbnail': video_thumbnail
  2289. }]
  2290. class HypemIE(InfoExtractor):
  2291. """Information Extractor for hypem"""
  2292. _VALID_URL = r'(?:http://)?(?:www\.)?hypem\.com/track/([^/]+)/([^/]+)'
  2293. def _real_extract(self, url):
  2294. mobj = re.match(self._VALID_URL, url)
  2295. if mobj is None:
  2296. raise ExtractorError(u'Invalid URL: %s' % url)
  2297. track_id = mobj.group(1)
  2298. data = { 'ax': 1, 'ts': time.time() }
  2299. data_encoded = compat_urllib_parse.urlencode(data)
  2300. complete_url = url + "?" + data_encoded
  2301. request = compat_urllib_request.Request(complete_url)
  2302. response, urlh = self._download_webpage_handle(request, track_id, u'Downloading webpage with the url')
  2303. cookie = urlh.headers.get('Set-Cookie', '')
  2304. self.report_extraction(track_id)
  2305. html_tracks = self._html_search_regex(r'<script type="application/json" id="displayList-data">(.*?)</script>',
  2306. response, u'tracks', flags=re.MULTILINE|re.DOTALL).strip()
  2307. try:
  2308. track_list = json.loads(html_tracks)
  2309. track = track_list[u'tracks'][0]
  2310. except ValueError:
  2311. raise ExtractorError(u'Hypemachine contained invalid JSON.')
  2312. key = track[u"key"]
  2313. track_id = track[u"id"]
  2314. artist = track[u"artist"]
  2315. title = track[u"song"]
  2316. serve_url = "http://hypem.com/serve/source/%s/%s" % (compat_str(track_id), compat_str(key))
  2317. request = compat_urllib_request.Request(serve_url, "" , {'Content-Type': 'application/json'})
  2318. request.add_header('cookie', cookie)
  2319. song_data_json = self._download_webpage(request, track_id, u'Downloading metadata')
  2320. try:
  2321. song_data = json.loads(song_data_json)
  2322. except ValueError:
  2323. raise ExtractorError(u'Hypemachine contained invalid JSON.')
  2324. final_url = song_data[u"url"]
  2325. return [{
  2326. 'id': track_id,
  2327. 'url': final_url,
  2328. 'ext': "mp3",
  2329. 'title': title,
  2330. 'artist': artist,
  2331. }]
  2332. class Vbox7IE(InfoExtractor):
  2333. """Information Extractor for Vbox7"""
  2334. _VALID_URL = r'(?:http://)?(?:www\.)?vbox7\.com/play:([^/]+)'
  2335. def _real_extract(self,url):
  2336. mobj = re.match(self._VALID_URL, url)
  2337. if mobj is None:
  2338. raise ExtractorError(u'Invalid URL: %s' % url)
  2339. video_id = mobj.group(1)
  2340. redirect_page, urlh = self._download_webpage_handle(url, video_id)
  2341. new_location = self._search_regex(r'window\.location = \'(.*)\';', redirect_page, u'redirect location')
  2342. redirect_url = urlh.geturl() + new_location
  2343. webpage = self._download_webpage(redirect_url, video_id, u'Downloading redirect page')
  2344. title = self._html_search_regex(r'<title>(.*)</title>',
  2345. webpage, u'title').split('/')[0].strip()
  2346. ext = "flv"
  2347. info_url = "http://vbox7.com/play/magare.do"
  2348. data = compat_urllib_parse.urlencode({'as3':'1','vid':video_id})
  2349. info_request = compat_urllib_request.Request(info_url, data)
  2350. info_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  2351. info_response = self._download_webpage(info_request, video_id, u'Downloading info webpage')
  2352. if info_response is None:
  2353. raise ExtractorError(u'Unable to extract the media url')
  2354. (final_url, thumbnail_url) = map(lambda x: x.split('=')[1], info_response.split('&'))
  2355. return [{
  2356. 'id': video_id,
  2357. 'url': final_url,
  2358. 'ext': ext,
  2359. 'title': title,
  2360. 'thumbnail': thumbnail_url,
  2361. }]
  2362. def gen_extractors():
  2363. """ Return a list of an instance of every supported extractor.
  2364. The order does matter; the first extractor matched is the one handling the URL.
  2365. """
  2366. return [
  2367. YoutubePlaylistIE(),
  2368. YoutubeChannelIE(),
  2369. YoutubeUserIE(),
  2370. YoutubeSearchIE(),
  2371. YoutubeIE(),
  2372. MetacafeIE(),
  2373. DailymotionIE(),
  2374. GoogleSearchIE(),
  2375. PhotobucketIE(),
  2376. YahooIE(),
  2377. YahooSearchIE(),
  2378. DepositFilesIE(),
  2379. FacebookIE(),
  2380. BlipTVIE(),
  2381. BlipTVUserIE(),
  2382. VimeoIE(),
  2383. MyVideoIE(),
  2384. ComedyCentralIE(),
  2385. EscapistIE(),
  2386. CollegeHumorIE(),
  2387. XVideosIE(),
  2388. SoundcloudSetIE(),
  2389. SoundcloudIE(),
  2390. InfoQIE(),
  2391. MixcloudIE(),
  2392. StanfordOpenClassroomIE(),
  2393. MTVIE(),
  2394. YoukuIE(),
  2395. XNXXIE(),
  2396. YouJizzIE(),
  2397. PornotubeIE(),
  2398. YouPornIE(),
  2399. GooglePlusIE(),
  2400. ArteTvIE(),
  2401. NBAIE(),
  2402. WorldStarHipHopIE(),
  2403. JustinTVIE(),
  2404. FunnyOrDieIE(),
  2405. SteamIE(),
  2406. UstreamIE(),
  2407. RBMARadioIE(),
  2408. EightTracksIE(),
  2409. KeekIE(),
  2410. TEDIE(),
  2411. MySpassIE(),
  2412. SpiegelIE(),
  2413. LiveLeakIE(),
  2414. ARDIE(),
  2415. ZDFIE(),
  2416. TumblrIE(),
  2417. BandcampIE(),
  2418. RedTubeIE(),
  2419. InaIE(),
  2420. HowcastIE(),
  2421. VineIE(),
  2422. FlickrIE(),
  2423. TeamcocoIE(),
  2424. XHamsterIE(),
  2425. HypemIE(),
  2426. Vbox7IE(),
  2427. GametrailersIE(),
  2428. StatigramIE(),
  2429. GenericIE()
  2430. ]
  2431. def get_info_extractor(ie_name):
  2432. """Returns the info extractor class with the given ie_name"""
  2433. return globals()[ie_name+'IE']