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.

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