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.

1931 lines
72 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
  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.comedycentral import ComedyCentralIE
  23. from .extractor.dailymotion import DailymotionIE
  24. from .extractor.depositfiles import DepositFilesIE
  25. from .extractor.escapist import EscapistIE
  26. from .extractor.facebook import FacebookIE
  27. from .extractor.gametrailers import GametrailersIE
  28. from .extractor.generic import GenericIE
  29. from .extractor.googleplus import GooglePlusIE
  30. from .extractor.googlesearch import GoogleSearchIE
  31. from .extractor.metacafe import MetacafeIE
  32. from .extractor.myvideo import MyVideoIE
  33. from .extractor.statigram import StatigramIE
  34. from .extractor.photobucket import PhotobucketIE
  35. from .extractor.soundcloud import SoundcloudIE, SoundcloudSetIE
  36. from .extractor.vimeo import VimeoIE
  37. from .extractor.yahoo import YahooIE, YahooSearchIE
  38. from .extractor.youtube import YoutubeIE, YoutubePlaylistIE, YoutubeSearchIE, YoutubeUserIE, YoutubeChannelIE
  39. from .extractor.zdf import ZDFIE
  40. class CollegeHumorIE(InfoExtractor):
  41. """Information extractor for collegehumor.com"""
  42. _WORKING = False
  43. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  44. IE_NAME = u'collegehumor'
  45. def report_manifest(self, video_id):
  46. """Report information extraction."""
  47. self.to_screen(u'%s: Downloading XML manifest' % video_id)
  48. def _real_extract(self, url):
  49. mobj = re.match(self._VALID_URL, url)
  50. if mobj is None:
  51. raise ExtractorError(u'Invalid URL: %s' % url)
  52. video_id = mobj.group('videoid')
  53. info = {
  54. 'id': video_id,
  55. 'uploader': None,
  56. 'upload_date': None,
  57. }
  58. self.report_extraction(video_id)
  59. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  60. try:
  61. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  62. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  63. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  64. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  65. try:
  66. videoNode = mdoc.findall('./video')[0]
  67. info['description'] = videoNode.findall('./description')[0].text
  68. info['title'] = videoNode.findall('./caption')[0].text
  69. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  70. manifest_url = videoNode.findall('./file')[0].text
  71. except IndexError:
  72. raise ExtractorError(u'Invalid metadata XML file')
  73. manifest_url += '?hdcore=2.10.3'
  74. self.report_manifest(video_id)
  75. try:
  76. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  77. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  78. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  79. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  80. try:
  81. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  82. node_id = media_node.attrib['url']
  83. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  84. except IndexError as err:
  85. raise ExtractorError(u'Invalid manifest file')
  86. url_pr = compat_urllib_parse_urlparse(manifest_url)
  87. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  88. info['url'] = url
  89. info['ext'] = 'f4f'
  90. return [info]
  91. class XVideosIE(InfoExtractor):
  92. """Information extractor for xvideos.com"""
  93. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  94. IE_NAME = u'xvideos'
  95. def _real_extract(self, url):
  96. mobj = re.match(self._VALID_URL, url)
  97. if mobj is None:
  98. raise ExtractorError(u'Invalid URL: %s' % url)
  99. video_id = mobj.group(1)
  100. webpage = self._download_webpage(url, video_id)
  101. self.report_extraction(video_id)
  102. # Extract video URL
  103. video_url = compat_urllib_parse.unquote(self._search_regex(r'flv_url=(.+?)&',
  104. webpage, u'video URL'))
  105. # Extract title
  106. video_title = self._html_search_regex(r'<title>(.*?)\s+-\s+XVID',
  107. webpage, u'title')
  108. # Extract video thumbnail
  109. 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)',
  110. webpage, u'thumbnail', fatal=False)
  111. info = {
  112. 'id': video_id,
  113. 'url': video_url,
  114. 'uploader': None,
  115. 'upload_date': None,
  116. 'title': video_title,
  117. 'ext': 'flv',
  118. 'thumbnail': video_thumbnail,
  119. 'description': None,
  120. }
  121. return [info]
  122. class InfoQIE(InfoExtractor):
  123. """Information extractor for infoq.com"""
  124. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  125. def _real_extract(self, url):
  126. mobj = re.match(self._VALID_URL, url)
  127. if mobj is None:
  128. raise ExtractorError(u'Invalid URL: %s' % url)
  129. webpage = self._download_webpage(url, video_id=url)
  130. self.report_extraction(url)
  131. # Extract video URL
  132. mobj = re.search(r"jsclassref ?= ?'([^']*)'", webpage)
  133. if mobj is None:
  134. raise ExtractorError(u'Unable to extract video url')
  135. real_id = compat_urllib_parse.unquote(base64.b64decode(mobj.group(1).encode('ascii')).decode('utf-8'))
  136. video_url = 'rtmpe://video.infoq.com/cfx/st/' + real_id
  137. # Extract title
  138. video_title = self._search_regex(r'contentTitle = "(.*?)";',
  139. webpage, u'title')
  140. # Extract description
  141. video_description = self._html_search_regex(r'<meta name="description" content="(.*)"(?:\s*/)?>',
  142. webpage, u'description', fatal=False)
  143. video_filename = video_url.split('/')[-1]
  144. video_id, extension = video_filename.split('.')
  145. info = {
  146. 'id': video_id,
  147. 'url': video_url,
  148. 'uploader': None,
  149. 'upload_date': None,
  150. 'title': video_title,
  151. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  152. 'thumbnail': None,
  153. 'description': video_description,
  154. }
  155. return [info]
  156. class MixcloudIE(InfoExtractor):
  157. """Information extractor for www.mixcloud.com"""
  158. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  159. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  160. IE_NAME = u'mixcloud'
  161. def report_download_json(self, file_id):
  162. """Report JSON download."""
  163. self.to_screen(u'Downloading json')
  164. def get_urls(self, jsonData, fmt, bitrate='best'):
  165. """Get urls from 'audio_formats' section in json"""
  166. file_url = None
  167. try:
  168. bitrate_list = jsonData[fmt]
  169. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  170. bitrate = max(bitrate_list) # select highest
  171. url_list = jsonData[fmt][bitrate]
  172. except TypeError: # we have no bitrate info.
  173. url_list = jsonData[fmt]
  174. return url_list
  175. def check_urls(self, url_list):
  176. """Returns 1st active url from list"""
  177. for url in url_list:
  178. try:
  179. compat_urllib_request.urlopen(url)
  180. return url
  181. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  182. url = None
  183. return None
  184. def _print_formats(self, formats):
  185. print('Available formats:')
  186. for fmt in formats.keys():
  187. for b in formats[fmt]:
  188. try:
  189. ext = formats[fmt][b][0]
  190. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  191. except TypeError: # we have no bitrate info
  192. ext = formats[fmt][0]
  193. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  194. break
  195. def _real_extract(self, url):
  196. mobj = re.match(self._VALID_URL, url)
  197. if mobj is None:
  198. raise ExtractorError(u'Invalid URL: %s' % url)
  199. # extract uploader & filename from url
  200. uploader = mobj.group(1).decode('utf-8')
  201. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  202. # construct API request
  203. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  204. # retrieve .json file with links to files
  205. request = compat_urllib_request.Request(file_url)
  206. try:
  207. self.report_download_json(file_url)
  208. jsonData = compat_urllib_request.urlopen(request).read()
  209. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  210. raise ExtractorError(u'Unable to retrieve file: %s' % compat_str(err))
  211. # parse JSON
  212. json_data = json.loads(jsonData)
  213. player_url = json_data['player_swf_url']
  214. formats = dict(json_data['audio_formats'])
  215. req_format = self._downloader.params.get('format', None)
  216. bitrate = None
  217. if self._downloader.params.get('listformats', None):
  218. self._print_formats(formats)
  219. return
  220. if req_format is None or req_format == 'best':
  221. for format_param in formats.keys():
  222. url_list = self.get_urls(formats, format_param)
  223. # check urls
  224. file_url = self.check_urls(url_list)
  225. if file_url is not None:
  226. break # got it!
  227. else:
  228. if req_format not in formats:
  229. raise ExtractorError(u'Format is not available')
  230. url_list = self.get_urls(formats, req_format)
  231. file_url = self.check_urls(url_list)
  232. format_param = req_format
  233. return [{
  234. 'id': file_id.decode('utf-8'),
  235. 'url': file_url.decode('utf-8'),
  236. 'uploader': uploader.decode('utf-8'),
  237. 'upload_date': None,
  238. 'title': json_data['name'],
  239. 'ext': file_url.split('.')[-1].decode('utf-8'),
  240. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  241. 'thumbnail': json_data['thumbnail_url'],
  242. 'description': json_data['description'],
  243. 'player_url': player_url.decode('utf-8'),
  244. }]
  245. class StanfordOpenClassroomIE(InfoExtractor):
  246. """Information extractor for Stanford's Open ClassRoom"""
  247. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  248. IE_NAME = u'stanfordoc'
  249. def _real_extract(self, url):
  250. mobj = re.match(self._VALID_URL, url)
  251. if mobj is None:
  252. raise ExtractorError(u'Invalid URL: %s' % url)
  253. if mobj.group('course') and mobj.group('video'): # A specific video
  254. course = mobj.group('course')
  255. video = mobj.group('video')
  256. info = {
  257. 'id': course + '_' + video,
  258. 'uploader': None,
  259. 'upload_date': None,
  260. }
  261. self.report_extraction(info['id'])
  262. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  263. xmlUrl = baseUrl + video + '.xml'
  264. try:
  265. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  266. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  267. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  268. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  269. try:
  270. info['title'] = mdoc.findall('./title')[0].text
  271. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  272. except IndexError:
  273. raise ExtractorError(u'Invalid metadata XML file')
  274. info['ext'] = info['url'].rpartition('.')[2]
  275. return [info]
  276. elif mobj.group('course'): # A course page
  277. course = mobj.group('course')
  278. info = {
  279. 'id': course,
  280. 'type': 'playlist',
  281. 'uploader': None,
  282. 'upload_date': None,
  283. }
  284. coursepage = self._download_webpage(url, info['id'],
  285. note='Downloading course info page',
  286. errnote='Unable to download course info page')
  287. info['title'] = self._html_search_regex('<h1>([^<]+)</h1>', coursepage, 'title', default=info['id'])
  288. info['description'] = self._html_search_regex('<description>([^<]+)</description>',
  289. coursepage, u'description', fatal=False)
  290. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  291. info['list'] = [
  292. {
  293. 'type': 'reference',
  294. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  295. }
  296. for vpage in links]
  297. results = []
  298. for entry in info['list']:
  299. assert entry['type'] == 'reference'
  300. results += self.extract(entry['url'])
  301. return results
  302. else: # Root page
  303. info = {
  304. 'id': 'Stanford OpenClassroom',
  305. 'type': 'playlist',
  306. 'uploader': None,
  307. 'upload_date': None,
  308. }
  309. self.report_download_webpage(info['id'])
  310. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  311. try:
  312. rootpage = compat_urllib_request.urlopen(rootURL).read()
  313. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  314. raise ExtractorError(u'Unable to download course info page: ' + compat_str(err))
  315. info['title'] = info['id']
  316. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  317. info['list'] = [
  318. {
  319. 'type': 'reference',
  320. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  321. }
  322. for cpage in links]
  323. results = []
  324. for entry in info['list']:
  325. assert entry['type'] == 'reference'
  326. results += self.extract(entry['url'])
  327. return results
  328. class MTVIE(InfoExtractor):
  329. """Information extractor for MTV.com"""
  330. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  331. IE_NAME = u'mtv'
  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. if not mobj.group('proto'):
  337. url = 'http://' + url
  338. video_id = mobj.group('videoid')
  339. webpage = self._download_webpage(url, video_id)
  340. song_name = self._html_search_regex(r'<meta name="mtv_vt" content="([^"]+)"/>',
  341. webpage, u'song name', fatal=False)
  342. video_title = self._html_search_regex(r'<meta name="mtv_an" content="([^"]+)"/>',
  343. webpage, u'title')
  344. mtvn_uri = self._html_search_regex(r'<meta name="mtvn_uri" content="([^"]+)"/>',
  345. webpage, u'mtvn_uri', fatal=False)
  346. content_id = self._search_regex(r'MTVN.Player.defaultPlaylistId = ([0-9]+);',
  347. webpage, u'content id', fatal=False)
  348. 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
  349. self.report_extraction(video_id)
  350. request = compat_urllib_request.Request(videogen_url)
  351. try:
  352. metadataXml = compat_urllib_request.urlopen(request).read()
  353. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  354. raise ExtractorError(u'Unable to download video metadata: %s' % compat_str(err))
  355. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  356. renditions = mdoc.findall('.//rendition')
  357. # For now, always pick the highest quality.
  358. rendition = renditions[-1]
  359. try:
  360. _,_,ext = rendition.attrib['type'].partition('/')
  361. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  362. video_url = rendition.find('./src').text
  363. except KeyError:
  364. raise ExtractorError('Invalid rendition field.')
  365. info = {
  366. 'id': video_id,
  367. 'url': video_url,
  368. 'uploader': performer,
  369. 'upload_date': None,
  370. 'title': video_title,
  371. 'ext': ext,
  372. 'format': format,
  373. }
  374. return [info]
  375. class YoukuIE(InfoExtractor):
  376. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  377. def _gen_sid(self):
  378. nowTime = int(time.time() * 1000)
  379. random1 = random.randint(1000,1998)
  380. random2 = random.randint(1000,9999)
  381. return "%d%d%d" %(nowTime,random1,random2)
  382. def _get_file_ID_mix_string(self, seed):
  383. mixed = []
  384. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  385. seed = float(seed)
  386. for i in range(len(source)):
  387. seed = (seed * 211 + 30031 ) % 65536
  388. index = math.floor(seed / 65536 * len(source) )
  389. mixed.append(source[int(index)])
  390. source.remove(source[int(index)])
  391. #return ''.join(mixed)
  392. return mixed
  393. def _get_file_id(self, fileId, seed):
  394. mixed = self._get_file_ID_mix_string(seed)
  395. ids = fileId.split('*')
  396. realId = []
  397. for ch in ids:
  398. if ch:
  399. realId.append(mixed[int(ch)])
  400. return ''.join(realId)
  401. def _real_extract(self, url):
  402. mobj = re.match(self._VALID_URL, url)
  403. if mobj is None:
  404. raise ExtractorError(u'Invalid URL: %s' % url)
  405. video_id = mobj.group('ID')
  406. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  407. jsondata = self._download_webpage(info_url, video_id)
  408. self.report_extraction(video_id)
  409. try:
  410. config = json.loads(jsondata)
  411. video_title = config['data'][0]['title']
  412. seed = config['data'][0]['seed']
  413. format = self._downloader.params.get('format', None)
  414. supported_format = list(config['data'][0]['streamfileids'].keys())
  415. if format is None or format == 'best':
  416. if 'hd2' in supported_format:
  417. format = 'hd2'
  418. else:
  419. format = 'flv'
  420. ext = u'flv'
  421. elif format == 'worst':
  422. format = 'mp4'
  423. ext = u'mp4'
  424. else:
  425. format = 'flv'
  426. ext = u'flv'
  427. fileid = config['data'][0]['streamfileids'][format]
  428. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  429. except (UnicodeDecodeError, ValueError, KeyError):
  430. raise ExtractorError(u'Unable to extract info section')
  431. files_info=[]
  432. sid = self._gen_sid()
  433. fileid = self._get_file_id(fileid, seed)
  434. #column 8,9 of fileid represent the segment number
  435. #fileid[7:9] should be changed
  436. for index, key in enumerate(keys):
  437. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  438. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  439. info = {
  440. 'id': '%s_part%02d' % (video_id, index),
  441. 'url': download_url,
  442. 'uploader': None,
  443. 'upload_date': None,
  444. 'title': video_title,
  445. 'ext': ext,
  446. }
  447. files_info.append(info)
  448. return files_info
  449. class XNXXIE(InfoExtractor):
  450. """Information extractor for xnxx.com"""
  451. _VALID_URL = r'^(?:https?://)?video\.xnxx\.com/video([0-9]+)/(.*)'
  452. IE_NAME = u'xnxx'
  453. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  454. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  455. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  456. def _real_extract(self, url):
  457. mobj = re.match(self._VALID_URL, url)
  458. if mobj is None:
  459. raise ExtractorError(u'Invalid URL: %s' % url)
  460. video_id = mobj.group(1)
  461. # Get webpage content
  462. webpage = self._download_webpage(url, video_id)
  463. video_url = self._search_regex(self.VIDEO_URL_RE,
  464. webpage, u'video URL')
  465. video_url = compat_urllib_parse.unquote(video_url)
  466. video_title = self._html_search_regex(self.VIDEO_TITLE_RE,
  467. webpage, u'title')
  468. video_thumbnail = self._search_regex(self.VIDEO_THUMB_RE,
  469. webpage, u'thumbnail', fatal=False)
  470. return [{
  471. 'id': video_id,
  472. 'url': video_url,
  473. 'uploader': None,
  474. 'upload_date': None,
  475. 'title': video_title,
  476. 'ext': 'flv',
  477. 'thumbnail': video_thumbnail,
  478. 'description': None,
  479. }]
  480. class NBAIE(InfoExtractor):
  481. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*?)(?:/index\.html)?(?:\?.*)?$'
  482. IE_NAME = u'nba'
  483. def _real_extract(self, url):
  484. mobj = re.match(self._VALID_URL, url)
  485. if mobj is None:
  486. raise ExtractorError(u'Invalid URL: %s' % url)
  487. video_id = mobj.group(1)
  488. webpage = self._download_webpage(url, video_id)
  489. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  490. shortened_video_id = video_id.rpartition('/')[2]
  491. title = self._html_search_regex(r'<meta property="og:title" content="(.*?)"',
  492. webpage, 'title', default=shortened_video_id).replace('NBA.com: ', '')
  493. # It isn't there in the HTML it returns to us
  494. # uploader_date = self._html_search_regex(r'<b>Date:</b> (.*?)</div>', webpage, 'upload_date', fatal=False)
  495. description = self._html_search_regex(r'<meta name="description" (?:content|value)="(.*?)" />', webpage, 'description', fatal=False)
  496. info = {
  497. 'id': shortened_video_id,
  498. 'url': video_url,
  499. 'ext': 'mp4',
  500. 'title': title,
  501. # 'uploader_date': uploader_date,
  502. 'description': description,
  503. }
  504. return [info]
  505. class JustinTVIE(InfoExtractor):
  506. """Information extractor for justin.tv and twitch.tv"""
  507. # TODO: One broadcast may be split into multiple videos. The key
  508. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  509. # starts at 1 and increases. Can we treat all parts as one video?
  510. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  511. (?:
  512. (?P<channelid>[^/]+)|
  513. (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
  514. (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
  515. )
  516. /?(?:\#.*)?$
  517. """
  518. _JUSTIN_PAGE_LIMIT = 100
  519. IE_NAME = u'justin.tv'
  520. def report_download_page(self, channel, offset):
  521. """Report attempt to download a single page of videos."""
  522. self.to_screen(u'%s: Downloading video information from %d to %d' %
  523. (channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  524. # Return count of items, list of *valid* items
  525. def _parse_page(self, url, video_id):
  526. webpage = self._download_webpage(url, video_id,
  527. u'Downloading video info JSON',
  528. u'unable to download video info JSON')
  529. response = json.loads(webpage)
  530. if type(response) != list:
  531. error_text = response.get('error', 'unknown error')
  532. raise ExtractorError(u'Justin.tv API: %s' % error_text)
  533. info = []
  534. for clip in response:
  535. video_url = clip['video_file_url']
  536. if video_url:
  537. video_extension = os.path.splitext(video_url)[1][1:]
  538. video_date = re.sub('-', '', clip['start_time'][:10])
  539. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  540. video_id = clip['id']
  541. video_title = clip.get('title', video_id)
  542. info.append({
  543. 'id': video_id,
  544. 'url': video_url,
  545. 'title': video_title,
  546. 'uploader': clip.get('channel_name', video_uploader_id),
  547. 'uploader_id': video_uploader_id,
  548. 'upload_date': video_date,
  549. 'ext': video_extension,
  550. })
  551. return (len(response), info)
  552. def _real_extract(self, url):
  553. mobj = re.match(self._VALID_URL, url)
  554. if mobj is None:
  555. raise ExtractorError(u'invalid URL: %s' % url)
  556. api_base = 'http://api.justin.tv'
  557. paged = False
  558. if mobj.group('channelid'):
  559. paged = True
  560. video_id = mobj.group('channelid')
  561. api = api_base + '/channel/archives/%s.json' % video_id
  562. elif mobj.group('chapterid'):
  563. chapter_id = mobj.group('chapterid')
  564. webpage = self._download_webpage(url, chapter_id)
  565. m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
  566. if not m:
  567. raise ExtractorError(u'Cannot find archive of a chapter')
  568. archive_id = m.group(1)
  569. api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
  570. chapter_info_xml = self._download_webpage(api, chapter_id,
  571. note=u'Downloading chapter information',
  572. errnote=u'Chapter information download failed')
  573. doc = xml.etree.ElementTree.fromstring(chapter_info_xml)
  574. for a in doc.findall('.//archive'):
  575. if archive_id == a.find('./id').text:
  576. break
  577. else:
  578. raise ExtractorError(u'Could not find chapter in chapter information')
  579. video_url = a.find('./video_file_url').text
  580. video_ext = video_url.rpartition('.')[2] or u'flv'
  581. chapter_api_url = u'https://api.twitch.tv/kraken/videos/c' + chapter_id
  582. chapter_info_json = self._download_webpage(chapter_api_url, u'c' + chapter_id,
  583. note='Downloading chapter metadata',
  584. errnote='Download of chapter metadata failed')
  585. chapter_info = json.loads(chapter_info_json)
  586. bracket_start = int(doc.find('.//bracket_start').text)
  587. bracket_end = int(doc.find('.//bracket_end').text)
  588. # TODO determine start (and probably fix up file)
  589. # youtube-dl -v http://www.twitch.tv/firmbelief/c/1757457
  590. #video_url += u'?start=' + TODO:start_timestamp
  591. # bracket_start is 13290, but we want 51670615
  592. self._downloader.report_warning(u'Chapter detected, but we can just download the whole file. '
  593. u'Chapter starts at %s and ends at %s' % (formatSeconds(bracket_start), formatSeconds(bracket_end)))
  594. info = {
  595. 'id': u'c' + chapter_id,
  596. 'url': video_url,
  597. 'ext': video_ext,
  598. 'title': chapter_info['title'],
  599. 'thumbnail': chapter_info['preview'],
  600. 'description': chapter_info['description'],
  601. 'uploader': chapter_info['channel']['display_name'],
  602. 'uploader_id': chapter_info['channel']['name'],
  603. }
  604. return [info]
  605. else:
  606. video_id = mobj.group('videoid')
  607. api = api_base + '/broadcast/by_archive/%s.json' % video_id
  608. self.report_extraction(video_id)
  609. info = []
  610. offset = 0
  611. limit = self._JUSTIN_PAGE_LIMIT
  612. while True:
  613. if paged:
  614. self.report_download_page(video_id, offset)
  615. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  616. page_count, page_info = self._parse_page(page_url, video_id)
  617. info.extend(page_info)
  618. if not paged or page_count != limit:
  619. break
  620. offset += limit
  621. return info
  622. class FunnyOrDieIE(InfoExtractor):
  623. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  624. def _real_extract(self, url):
  625. mobj = re.match(self._VALID_URL, url)
  626. if mobj is None:
  627. raise ExtractorError(u'invalid URL: %s' % url)
  628. video_id = mobj.group('id')
  629. webpage = self._download_webpage(url, video_id)
  630. video_url = self._html_search_regex(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"',
  631. webpage, u'video URL', flags=re.DOTALL)
  632. title = self._html_search_regex((r"<h1 class='player_page_h1'.*?>(?P<title>.*?)</h1>",
  633. r'<title>(?P<title>[^<]+?)</title>'), webpage, 'title', flags=re.DOTALL)
  634. video_description = self._html_search_regex(r'<meta property="og:description" content="(?P<desc>.*?)"',
  635. webpage, u'description', fatal=False, flags=re.DOTALL)
  636. info = {
  637. 'id': video_id,
  638. 'url': video_url,
  639. 'ext': 'mp4',
  640. 'title': title,
  641. 'description': video_description,
  642. }
  643. return [info]
  644. class SteamIE(InfoExtractor):
  645. _VALID_URL = r"""http://store\.steampowered\.com/
  646. (agecheck/)?
  647. (?P<urltype>video|app)/ #If the page is only for videos or for a game
  648. (?P<gameID>\d+)/?
  649. (?P<videoID>\d*)(?P<extra>\??) #For urltype == video we sometimes get the videoID
  650. """
  651. _VIDEO_PAGE_TEMPLATE = 'http://store.steampowered.com/video/%s/'
  652. _AGECHECK_TEMPLATE = 'http://store.steampowered.com/agecheck/video/%s/?snr=1_agecheck_agecheck__age-gate&ageDay=1&ageMonth=January&ageYear=1970'
  653. @classmethod
  654. def suitable(cls, url):
  655. """Receives a URL and returns True if suitable for this IE."""
  656. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  657. def _real_extract(self, url):
  658. m = re.match(self._VALID_URL, url, re.VERBOSE)
  659. gameID = m.group('gameID')
  660. videourl = self._VIDEO_PAGE_TEMPLATE % gameID
  661. webpage = self._download_webpage(videourl, gameID)
  662. if re.search('<h2>Please enter your birth date to continue:</h2>', webpage) is not None:
  663. videourl = self._AGECHECK_TEMPLATE % gameID
  664. self.report_age_confirmation()
  665. webpage = self._download_webpage(videourl, gameID)
  666. self.report_extraction(gameID)
  667. game_title = self._html_search_regex(r'<h2 class="pageheader">(.*?)</h2>',
  668. webpage, 'game title')
  669. urlRE = r"'movie_(?P<videoID>\d+)': \{\s*FILENAME: \"(?P<videoURL>[\w:/\.\?=]+)\"(,\s*MOVIE_NAME: \"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\},"
  670. mweb = re.finditer(urlRE, webpage)
  671. namesRE = r'<span class="title">(?P<videoName>.+?)</span>'
  672. titles = re.finditer(namesRE, webpage)
  673. thumbsRE = r'<img class="movie_thumb" src="(?P<thumbnail>.+?)">'
  674. thumbs = re.finditer(thumbsRE, webpage)
  675. videos = []
  676. for vid,vtitle,thumb in zip(mweb,titles,thumbs):
  677. video_id = vid.group('videoID')
  678. title = vtitle.group('videoName')
  679. video_url = vid.group('videoURL')
  680. video_thumb = thumb.group('thumbnail')
  681. if not video_url:
  682. raise ExtractorError(u'Cannot find video url for %s' % video_id)
  683. info = {
  684. 'id':video_id,
  685. 'url':video_url,
  686. 'ext': 'flv',
  687. 'title': unescapeHTML(title),
  688. 'thumbnail': video_thumb
  689. }
  690. videos.append(info)
  691. return [self.playlist_result(videos, gameID, game_title)]
  692. class UstreamIE(InfoExtractor):
  693. _VALID_URL = r'https?://www\.ustream\.tv/recorded/(?P<videoID>\d+)'
  694. IE_NAME = u'ustream'
  695. def _real_extract(self, url):
  696. m = re.match(self._VALID_URL, url)
  697. video_id = m.group('videoID')
  698. video_url = u'http://tcdn.ustream.tv/video/%s' % video_id
  699. webpage = self._download_webpage(url, video_id)
  700. self.report_extraction(video_id)
  701. video_title = self._html_search_regex(r'data-title="(?P<title>.+)"',
  702. webpage, u'title')
  703. uploader = self._html_search_regex(r'data-content-type="channel".*?>(?P<uploader>.*?)</a>',
  704. webpage, u'uploader', fatal=False, flags=re.DOTALL)
  705. thumbnail = self._html_search_regex(r'<link rel="image_src" href="(?P<thumb>.*?)"',
  706. webpage, u'thumbnail', fatal=False)
  707. info = {
  708. 'id': video_id,
  709. 'url': video_url,
  710. 'ext': 'flv',
  711. 'title': video_title,
  712. 'uploader': uploader,
  713. 'thumbnail': thumbnail,
  714. }
  715. return info
  716. class WorldStarHipHopIE(InfoExtractor):
  717. _VALID_URL = r'https?://(?:www|m)\.worldstar(?:candy|hiphop)\.com/videos/video\.php\?v=(?P<id>.*)'
  718. IE_NAME = u'WorldStarHipHop'
  719. def _real_extract(self, url):
  720. m = re.match(self._VALID_URL, url)
  721. video_id = m.group('id')
  722. webpage_src = self._download_webpage(url, video_id)
  723. video_url = self._search_regex(r'so\.addVariable\("file","(.*?)"\)',
  724. webpage_src, u'video URL')
  725. if 'mp4' in video_url:
  726. ext = 'mp4'
  727. else:
  728. ext = 'flv'
  729. video_title = self._html_search_regex(r"<title>(.*)</title>",
  730. webpage_src, u'title')
  731. # Getting thumbnail and if not thumbnail sets correct title for WSHH candy video.
  732. thumbnail = self._html_search_regex(r'rel="image_src" href="(.*)" />',
  733. webpage_src, u'thumbnail', fatal=False)
  734. if not thumbnail:
  735. _title = r"""candytitles.*>(.*)</span>"""
  736. mobj = re.search(_title, webpage_src)
  737. if mobj is not None:
  738. video_title = mobj.group(1)
  739. results = [{
  740. 'id': video_id,
  741. 'url' : video_url,
  742. 'title' : video_title,
  743. 'thumbnail' : thumbnail,
  744. 'ext' : ext,
  745. }]
  746. return results
  747. class RBMARadioIE(InfoExtractor):
  748. _VALID_URL = r'https?://(?:www\.)?rbmaradio\.com/shows/(?P<videoID>[^/]+)$'
  749. def _real_extract(self, url):
  750. m = re.match(self._VALID_URL, url)
  751. video_id = m.group('videoID')
  752. webpage = self._download_webpage(url, video_id)
  753. json_data = self._search_regex(r'window\.gon.*?gon\.show=(.+?);$',
  754. webpage, u'json data', flags=re.MULTILINE)
  755. try:
  756. data = json.loads(json_data)
  757. except ValueError as e:
  758. raise ExtractorError(u'Invalid JSON: ' + str(e))
  759. video_url = data['akamai_url'] + '&cbr=256'
  760. url_parts = compat_urllib_parse_urlparse(video_url)
  761. video_ext = url_parts.path.rpartition('.')[2]
  762. info = {
  763. 'id': video_id,
  764. 'url': video_url,
  765. 'ext': video_ext,
  766. 'title': data['title'],
  767. 'description': data.get('teaser_text'),
  768. 'location': data.get('country_of_origin'),
  769. 'uploader': data.get('host', {}).get('name'),
  770. 'uploader_id': data.get('host', {}).get('slug'),
  771. 'thumbnail': data.get('image', {}).get('large_url_2x'),
  772. 'duration': data.get('duration'),
  773. }
  774. return [info]
  775. class YouPornIE(InfoExtractor):
  776. """Information extractor for youporn.com."""
  777. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
  778. def _print_formats(self, formats):
  779. """Print all available formats"""
  780. print(u'Available formats:')
  781. print(u'ext\t\tformat')
  782. print(u'---------------------------------')
  783. for format in formats:
  784. print(u'%s\t\t%s' % (format['ext'], format['format']))
  785. def _specific(self, req_format, formats):
  786. for x in formats:
  787. if(x["format"]==req_format):
  788. return x
  789. return None
  790. def _real_extract(self, url):
  791. mobj = re.match(self._VALID_URL, url)
  792. if mobj is None:
  793. raise ExtractorError(u'Invalid URL: %s' % url)
  794. video_id = mobj.group('videoid')
  795. req = compat_urllib_request.Request(url)
  796. req.add_header('Cookie', 'age_verified=1')
  797. webpage = self._download_webpage(req, video_id)
  798. # Get JSON parameters
  799. json_params = self._search_regex(r'var currentVideo = new Video\((.*)\);', webpage, u'JSON parameters')
  800. try:
  801. params = json.loads(json_params)
  802. except:
  803. raise ExtractorError(u'Invalid JSON')
  804. self.report_extraction(video_id)
  805. try:
  806. video_title = params['title']
  807. upload_date = unified_strdate(params['release_date_f'])
  808. video_description = params['description']
  809. video_uploader = params['submitted_by']
  810. thumbnail = params['thumbnails'][0]['image']
  811. except KeyError:
  812. raise ExtractorError('Missing JSON parameter: ' + sys.exc_info()[1])
  813. # Get all of the formats available
  814. DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
  815. download_list_html = self._search_regex(DOWNLOAD_LIST_RE,
  816. webpage, u'download list').strip()
  817. # Get all of the links from the page
  818. LINK_RE = r'(?s)<a href="(?P<url>[^"]+)">'
  819. links = re.findall(LINK_RE, download_list_html)
  820. if(len(links) == 0):
  821. raise ExtractorError(u'ERROR: no known formats available for video')
  822. self.to_screen(u'Links found: %d' % len(links))
  823. formats = []
  824. for link in links:
  825. # A link looks like this:
  826. # 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
  827. # A path looks like this:
  828. # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
  829. video_url = unescapeHTML( link )
  830. path = compat_urllib_parse_urlparse( video_url ).path
  831. extension = os.path.splitext( path )[1][1:]
  832. format = path.split('/')[4].split('_')[:2]
  833. size = format[0]
  834. bitrate = format[1]
  835. format = "-".join( format )
  836. # title = u'%s-%s-%s' % (video_title, size, bitrate)
  837. formats.append({
  838. 'id': video_id,
  839. 'url': video_url,
  840. 'uploader': video_uploader,
  841. 'upload_date': upload_date,
  842. 'title': video_title,
  843. 'ext': extension,
  844. 'format': format,
  845. 'thumbnail': thumbnail,
  846. 'description': video_description
  847. })
  848. if self._downloader.params.get('listformats', None):
  849. self._print_formats(formats)
  850. return
  851. req_format = self._downloader.params.get('format', None)
  852. self.to_screen(u'Format: %s' % req_format)
  853. if req_format is None or req_format == 'best':
  854. return [formats[0]]
  855. elif req_format == 'worst':
  856. return [formats[-1]]
  857. elif req_format in ('-1', 'all'):
  858. return formats
  859. else:
  860. format = self._specific( req_format, formats )
  861. if result is None:
  862. raise ExtractorError(u'Requested format not available')
  863. return [format]
  864. class PornotubeIE(InfoExtractor):
  865. """Information extractor for pornotube.com."""
  866. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?pornotube\.com(/c/(?P<channel>[0-9]+))?(/m/(?P<videoid>[0-9]+))(/(?P<title>.+))$'
  867. def _real_extract(self, url):
  868. mobj = re.match(self._VALID_URL, url)
  869. if mobj is None:
  870. raise ExtractorError(u'Invalid URL: %s' % url)
  871. video_id = mobj.group('videoid')
  872. video_title = mobj.group('title')
  873. # Get webpage content
  874. webpage = self._download_webpage(url, video_id)
  875. # Get the video URL
  876. VIDEO_URL_RE = r'url: "(?P<url>http://video[0-9].pornotube.com/.+\.flv)",'
  877. video_url = self._search_regex(VIDEO_URL_RE, webpage, u'video url')
  878. video_url = compat_urllib_parse.unquote(video_url)
  879. #Get the uploaded date
  880. VIDEO_UPLOADED_RE = r'<div class="video_added_by">Added (?P<date>[0-9\/]+) by'
  881. upload_date = self._html_search_regex(VIDEO_UPLOADED_RE, webpage, u'upload date', fatal=False)
  882. if upload_date: upload_date = unified_strdate(upload_date)
  883. info = {'id': video_id,
  884. 'url': video_url,
  885. 'uploader': None,
  886. 'upload_date': upload_date,
  887. 'title': video_title,
  888. 'ext': 'flv',
  889. 'format': 'flv'}
  890. return [info]
  891. class YouJizzIE(InfoExtractor):
  892. """Information extractor for youjizz.com."""
  893. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youjizz\.com/videos/(?P<videoid>[^.]+).html$'
  894. def _real_extract(self, url):
  895. mobj = re.match(self._VALID_URL, url)
  896. if mobj is None:
  897. raise ExtractorError(u'Invalid URL: %s' % url)
  898. video_id = mobj.group('videoid')
  899. # Get webpage content
  900. webpage = self._download_webpage(url, video_id)
  901. # Get the video title
  902. video_title = self._html_search_regex(r'<title>(?P<title>.*)</title>',
  903. webpage, u'title').strip()
  904. # Get the embed page
  905. result = re.search(r'https?://www.youjizz.com/videos/embed/(?P<videoid>[0-9]+)', webpage)
  906. if result is None:
  907. raise ExtractorError(u'ERROR: unable to extract embed page')
  908. embed_page_url = result.group(0).strip()
  909. video_id = result.group('videoid')
  910. webpage = self._download_webpage(embed_page_url, video_id)
  911. # Get the video URL
  912. video_url = self._search_regex(r'so.addVariable\("file",encodeURIComponent\("(?P<source>[^"]+)"\)\);',
  913. webpage, u'video URL')
  914. info = {'id': video_id,
  915. 'url': video_url,
  916. 'title': video_title,
  917. 'ext': 'flv',
  918. 'format': 'flv',
  919. 'player_url': embed_page_url}
  920. return [info]
  921. class EightTracksIE(InfoExtractor):
  922. IE_NAME = '8tracks'
  923. _VALID_URL = r'https?://8tracks.com/(?P<user>[^/]+)/(?P<id>[^/#]+)(?:#.*)?$'
  924. def _real_extract(self, url):
  925. mobj = re.match(self._VALID_URL, url)
  926. if mobj is None:
  927. raise ExtractorError(u'Invalid URL: %s' % url)
  928. playlist_id = mobj.group('id')
  929. webpage = self._download_webpage(url, playlist_id)
  930. json_like = self._search_regex(r"PAGE.mix = (.*?);\n", webpage, u'trax information', flags=re.DOTALL)
  931. data = json.loads(json_like)
  932. session = str(random.randint(0, 1000000000))
  933. mix_id = data['id']
  934. track_count = data['tracks_count']
  935. first_url = 'http://8tracks.com/sets/%s/play?player=sm&mix_id=%s&format=jsonh' % (session, mix_id)
  936. next_url = first_url
  937. res = []
  938. for i in itertools.count():
  939. api_json = self._download_webpage(next_url, playlist_id,
  940. note=u'Downloading song information %s/%s' % (str(i+1), track_count),
  941. errnote=u'Failed to download song information')
  942. api_data = json.loads(api_json)
  943. track_data = api_data[u'set']['track']
  944. info = {
  945. 'id': track_data['id'],
  946. 'url': track_data['track_file_stream_url'],
  947. 'title': track_data['performer'] + u' - ' + track_data['name'],
  948. 'raw_title': track_data['name'],
  949. 'uploader_id': data['user']['login'],
  950. 'ext': 'm4a',
  951. }
  952. res.append(info)
  953. if api_data['set']['at_last_track']:
  954. break
  955. next_url = 'http://8tracks.com/sets/%s/next?player=sm&mix_id=%s&format=jsonh&track_id=%s' % (session, mix_id, track_data['id'])
  956. return res
  957. class KeekIE(InfoExtractor):
  958. _VALID_URL = r'http://(?:www\.)?keek\.com/(?:!|\w+/keeks/)(?P<videoID>\w+)'
  959. IE_NAME = u'keek'
  960. def _real_extract(self, url):
  961. m = re.match(self._VALID_URL, url)
  962. video_id = m.group('videoID')
  963. video_url = u'http://cdn.keek.com/keek/video/%s' % video_id
  964. thumbnail = u'http://cdn.keek.com/keek/thumbnail/%s/w100/h75' % video_id
  965. webpage = self._download_webpage(url, video_id)
  966. video_title = self._html_search_regex(r'<meta property="og:title" content="(?P<title>.*?)"',
  967. webpage, u'title')
  968. uploader = self._html_search_regex(r'<div class="user-name-and-bio">[\S\s]+?<h2>(?P<uploader>.+?)</h2>',
  969. webpage, u'uploader', fatal=False)
  970. info = {
  971. 'id': video_id,
  972. 'url': video_url,
  973. 'ext': 'mp4',
  974. 'title': video_title,
  975. 'thumbnail': thumbnail,
  976. 'uploader': uploader
  977. }
  978. return [info]
  979. class TEDIE(InfoExtractor):
  980. _VALID_URL=r'''http://www\.ted\.com/
  981. (
  982. ((?P<type_playlist>playlists)/(?P<playlist_id>\d+)) # We have a playlist
  983. |
  984. ((?P<type_talk>talks)) # We have a simple talk
  985. )
  986. (/lang/(.*?))? # The url may contain the language
  987. /(?P<name>\w+) # Here goes the name and then ".html"
  988. '''
  989. @classmethod
  990. def suitable(cls, url):
  991. """Receives a URL and returns True if suitable for this IE."""
  992. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  993. def _real_extract(self, url):
  994. m=re.match(self._VALID_URL, url, re.VERBOSE)
  995. if m.group('type_talk'):
  996. return [self._talk_info(url)]
  997. else :
  998. playlist_id=m.group('playlist_id')
  999. name=m.group('name')
  1000. self.to_screen(u'Getting info of playlist %s: "%s"' % (playlist_id,name))
  1001. return [self._playlist_videos_info(url,name,playlist_id)]
  1002. def _playlist_videos_info(self,url,name,playlist_id=0):
  1003. '''Returns the videos of the playlist'''
  1004. video_RE=r'''
  1005. <li\ id="talk_(\d+)"([.\s]*?)data-id="(?P<video_id>\d+)"
  1006. ([.\s]*?)data-playlist_item_id="(\d+)"
  1007. ([.\s]*?)data-mediaslug="(?P<mediaSlug>.+?)"
  1008. '''
  1009. video_name_RE=r'<p\ class="talk-title"><a href="(?P<talk_url>/talks/(.+).html)">(?P<fullname>.+?)</a></p>'
  1010. webpage=self._download_webpage(url, playlist_id, 'Downloading playlist webpage')
  1011. m_videos=re.finditer(video_RE,webpage,re.VERBOSE)
  1012. m_names=re.finditer(video_name_RE,webpage)
  1013. playlist_title = self._html_search_regex(r'div class="headline">\s*?<h1>\s*?<span>(.*?)</span>',
  1014. webpage, 'playlist title')
  1015. playlist_entries = []
  1016. for m_video, m_name in zip(m_videos,m_names):
  1017. video_id=m_video.group('video_id')
  1018. talk_url='http://www.ted.com%s' % m_name.group('talk_url')
  1019. playlist_entries.append(self.url_result(talk_url, 'TED'))
  1020. return self.playlist_result(playlist_entries, playlist_id = playlist_id, playlist_title = playlist_title)
  1021. def _talk_info(self, url, video_id=0):
  1022. """Return the video for the talk in the url"""
  1023. m = re.match(self._VALID_URL, url,re.VERBOSE)
  1024. video_name = m.group('name')
  1025. webpage = self._download_webpage(url, video_id, 'Downloading \"%s\" page' % video_name)
  1026. self.report_extraction(video_name)
  1027. # If the url includes the language we get the title translated
  1028. title = self._html_search_regex(r'<span id="altHeadline" >(?P<title>.*)</span>',
  1029. webpage, 'title')
  1030. json_data = self._search_regex(r'<script.*?>var talkDetails = ({.*?})</script>',
  1031. webpage, 'json data')
  1032. info = json.loads(json_data)
  1033. desc = self._html_search_regex(r'<div class="talk-intro">.*?<p.*?>(.*?)</p>',
  1034. webpage, 'description', flags = re.DOTALL)
  1035. thumbnail = self._search_regex(r'</span>[\s.]*</div>[\s.]*<img src="(.*?)"',
  1036. webpage, 'thumbnail')
  1037. info = {
  1038. 'id': info['id'],
  1039. 'url': info['htmlStreams'][-1]['file'],
  1040. 'ext': 'mp4',
  1041. 'title': title,
  1042. 'thumbnail': thumbnail,
  1043. 'description': desc,
  1044. }
  1045. return info
  1046. class MySpassIE(InfoExtractor):
  1047. _VALID_URL = r'http://www.myspass.de/.*'
  1048. def _real_extract(self, url):
  1049. META_DATA_URL_TEMPLATE = 'http://www.myspass.de/myspass/includes/apps/video/getvideometadataxml.php?id=%s'
  1050. # video id is the last path element of the URL
  1051. # usually there is a trailing slash, so also try the second but last
  1052. url_path = compat_urllib_parse_urlparse(url).path
  1053. url_parent_path, video_id = os.path.split(url_path)
  1054. if not video_id:
  1055. _, video_id = os.path.split(url_parent_path)
  1056. # get metadata
  1057. metadata_url = META_DATA_URL_TEMPLATE % video_id
  1058. metadata_text = self._download_webpage(metadata_url, video_id)
  1059. metadata = xml.etree.ElementTree.fromstring(metadata_text.encode('utf-8'))
  1060. # extract values from metadata
  1061. url_flv_el = metadata.find('url_flv')
  1062. if url_flv_el is None:
  1063. raise ExtractorError(u'Unable to extract download url')
  1064. video_url = url_flv_el.text
  1065. extension = os.path.splitext(video_url)[1][1:]
  1066. title_el = metadata.find('title')
  1067. if title_el is None:
  1068. raise ExtractorError(u'Unable to extract title')
  1069. title = title_el.text
  1070. format_id_el = metadata.find('format_id')
  1071. if format_id_el is None:
  1072. format = ext
  1073. else:
  1074. format = format_id_el.text
  1075. description_el = metadata.find('description')
  1076. if description_el is not None:
  1077. description = description_el.text
  1078. else:
  1079. description = None
  1080. imagePreview_el = metadata.find('imagePreview')
  1081. if imagePreview_el is not None:
  1082. thumbnail = imagePreview_el.text
  1083. else:
  1084. thumbnail = None
  1085. info = {
  1086. 'id': video_id,
  1087. 'url': video_url,
  1088. 'title': title,
  1089. 'ext': extension,
  1090. 'format': format,
  1091. 'thumbnail': thumbnail,
  1092. 'description': description
  1093. }
  1094. return [info]
  1095. class SpiegelIE(InfoExtractor):
  1096. _VALID_URL = r'https?://(?:www\.)?spiegel\.de/video/[^/]*-(?P<videoID>[0-9]+)(?:\.html)?(?:#.*)?$'
  1097. def _real_extract(self, url):
  1098. m = re.match(self._VALID_URL, url)
  1099. video_id = m.group('videoID')
  1100. webpage = self._download_webpage(url, video_id)
  1101. video_title = self._html_search_regex(r'<div class="module-title">(.*?)</div>',
  1102. webpage, u'title')
  1103. xml_url = u'http://video2.spiegel.de/flash/' + video_id + u'.xml'
  1104. xml_code = self._download_webpage(xml_url, video_id,
  1105. note=u'Downloading XML', errnote=u'Failed to download XML')
  1106. idoc = xml.etree.ElementTree.fromstring(xml_code)
  1107. last_type = idoc[-1]
  1108. filename = last_type.findall('./filename')[0].text
  1109. duration = float(last_type.findall('./duration')[0].text)
  1110. video_url = 'http://video2.spiegel.de/flash/' + filename
  1111. video_ext = filename.rpartition('.')[2]
  1112. info = {
  1113. 'id': video_id,
  1114. 'url': video_url,
  1115. 'ext': video_ext,
  1116. 'title': video_title,
  1117. 'duration': duration,
  1118. }
  1119. return [info]
  1120. class LiveLeakIE(InfoExtractor):
  1121. _VALID_URL = r'^(?:http?://)?(?:\w+\.)?liveleak\.com/view\?(?:.*?)i=(?P<video_id>[\w_]+)(?:.*)'
  1122. IE_NAME = u'liveleak'
  1123. def _real_extract(self, url):
  1124. mobj = re.match(self._VALID_URL, url)
  1125. if mobj is None:
  1126. raise ExtractorError(u'Invalid URL: %s' % url)
  1127. video_id = mobj.group('video_id')
  1128. webpage = self._download_webpage(url, video_id)
  1129. video_url = self._search_regex(r'file: "(.*?)",',
  1130. webpage, u'video URL')
  1131. video_title = self._html_search_regex(r'<meta property="og:title" content="(?P<title>.*?)"',
  1132. webpage, u'title').replace('LiveLeak.com -', '').strip()
  1133. video_description = self._html_search_regex(r'<meta property="og:description" content="(?P<desc>.*?)"',
  1134. webpage, u'description', fatal=False)
  1135. video_uploader = self._html_search_regex(r'By:.*?(\w+)</a>',
  1136. webpage, u'uploader', fatal=False)
  1137. info = {
  1138. 'id': video_id,
  1139. 'url': video_url,
  1140. 'ext': 'mp4',
  1141. 'title': video_title,
  1142. 'description': video_description,
  1143. 'uploader': video_uploader
  1144. }
  1145. return [info]
  1146. class TumblrIE(InfoExtractor):
  1147. _VALID_URL = r'http://(?P<blog_name>.*?)\.tumblr\.com/((post)|(video))/(?P<id>\d*)/(.*?)'
  1148. def _real_extract(self, url):
  1149. m_url = re.match(self._VALID_URL, url)
  1150. video_id = m_url.group('id')
  1151. blog = m_url.group('blog_name')
  1152. url = 'http://%s.tumblr.com/post/%s/' % (blog, video_id)
  1153. webpage = self._download_webpage(url, video_id)
  1154. re_video = r'src=\\x22(?P<video_url>http://%s\.tumblr\.com/video_file/%s/(.*?))\\x22 type=\\x22video/(?P<ext>.*?)\\x22' % (blog, video_id)
  1155. video = re.search(re_video, webpage)
  1156. if video is None:
  1157. raise ExtractorError(u'Unable to extract video')
  1158. video_url = video.group('video_url')
  1159. ext = video.group('ext')
  1160. video_thumbnail = self._search_regex(r'posters(.*?)\[\\x22(?P<thumb>.*?)\\x22',
  1161. webpage, u'thumbnail', fatal=False) # We pick the first poster
  1162. if video_thumbnail: video_thumbnail = video_thumbnail.replace('\\', '')
  1163. # The only place where you can get a title, it's not complete,
  1164. # but searching in other places doesn't work for all videos
  1165. video_title = self._html_search_regex(r'<title>(?P<title>.*?)</title>',
  1166. webpage, u'title', flags=re.DOTALL)
  1167. return [{'id': video_id,
  1168. 'url': video_url,
  1169. 'title': video_title,
  1170. 'thumbnail': video_thumbnail,
  1171. 'ext': ext
  1172. }]
  1173. class BandcampIE(InfoExtractor):
  1174. _VALID_URL = r'http://.*?\.bandcamp\.com/track/(?P<title>.*)'
  1175. def _real_extract(self, url):
  1176. mobj = re.match(self._VALID_URL, url)
  1177. title = mobj.group('title')
  1178. webpage = self._download_webpage(url, title)
  1179. # We get the link to the free download page
  1180. m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
  1181. if m_download is None:
  1182. raise ExtractorError(u'No free songs found')
  1183. download_link = m_download.group(1)
  1184. id = re.search(r'var TralbumData = {(.*?)id: (?P<id>\d*?)$',
  1185. webpage, re.MULTILINE|re.DOTALL).group('id')
  1186. download_webpage = self._download_webpage(download_link, id,
  1187. 'Downloading free downloads page')
  1188. # We get the dictionary of the track from some javascrip code
  1189. info = re.search(r'items: (.*?),$',
  1190. download_webpage, re.MULTILINE).group(1)
  1191. info = json.loads(info)[0]
  1192. # We pick mp3-320 for now, until format selection can be easily implemented.
  1193. mp3_info = info[u'downloads'][u'mp3-320']
  1194. # If we try to use this url it says the link has expired
  1195. initial_url = mp3_info[u'url']
  1196. re_url = r'(?P<server>http://(.*?)\.bandcamp\.com)/download/track\?enc=mp3-320&fsig=(?P<fsig>.*?)&id=(?P<id>.*?)&ts=(?P<ts>.*)$'
  1197. m_url = re.match(re_url, initial_url)
  1198. #We build the url we will use to get the final track url
  1199. # This url is build in Bandcamp in the script download_bunde_*.js
  1200. 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'))
  1201. final_url_webpage = self._download_webpage(request_url, id, 'Requesting download url')
  1202. # If we could correctly generate the .rand field the url would be
  1203. #in the "download_url" key
  1204. final_url = re.search(r'"retry_url":"(.*?)"', final_url_webpage).group(1)
  1205. track_info = {'id':id,
  1206. 'title' : info[u'title'],
  1207. 'ext' : 'mp3',
  1208. 'url' : final_url,
  1209. 'thumbnail' : info[u'thumb_url'],
  1210. 'uploader' : info[u'artist']
  1211. }
  1212. return [track_info]
  1213. class RedTubeIE(InfoExtractor):
  1214. """Information Extractor for redtube"""
  1215. _VALID_URL = r'(?:http://)?(?:www\.)?redtube\.com/(?P<id>[0-9]+)'
  1216. def _real_extract(self,url):
  1217. mobj = re.match(self._VALID_URL, url)
  1218. if mobj is None:
  1219. raise ExtractorError(u'Invalid URL: %s' % url)
  1220. video_id = mobj.group('id')
  1221. video_extension = 'mp4'
  1222. webpage = self._download_webpage(url, video_id)
  1223. self.report_extraction(video_id)
  1224. video_url = self._html_search_regex(r'<source src="(.+?)" type="video/mp4">',
  1225. webpage, u'video URL')
  1226. video_title = self._html_search_regex('<h1 class="videoTitle slidePanelMovable">(.+?)</h1>',
  1227. webpage, u'title')
  1228. return [{
  1229. 'id': video_id,
  1230. 'url': video_url,
  1231. 'ext': video_extension,
  1232. 'title': video_title,
  1233. }]
  1234. class InaIE(InfoExtractor):
  1235. """Information Extractor for Ina.fr"""
  1236. _VALID_URL = r'(?:http://)?(?:www\.)?ina\.fr/video/(?P<id>I[0-9]+)/.*'
  1237. def _real_extract(self,url):
  1238. mobj = re.match(self._VALID_URL, url)
  1239. video_id = mobj.group('id')
  1240. mrss_url='http://player.ina.fr/notices/%s.mrss' % video_id
  1241. video_extension = 'mp4'
  1242. webpage = self._download_webpage(mrss_url, video_id)
  1243. self.report_extraction(video_id)
  1244. video_url = self._html_search_regex(r'<media:player url="(?P<mp4url>http://mp4.ina.fr/[^"]+\.mp4)',
  1245. webpage, u'video URL')
  1246. video_title = self._search_regex(r'<title><!\[CDATA\[(?P<titre>.*?)]]></title>',
  1247. webpage, u'title')
  1248. return [{
  1249. 'id': video_id,
  1250. 'url': video_url,
  1251. 'ext': video_extension,
  1252. 'title': video_title,
  1253. }]
  1254. class HowcastIE(InfoExtractor):
  1255. """Information Extractor for Howcast.com"""
  1256. _VALID_URL = r'(?:https?://)?(?:www\.)?howcast\.com/videos/(?P<id>\d+)'
  1257. def _real_extract(self, url):
  1258. mobj = re.match(self._VALID_URL, url)
  1259. video_id = mobj.group('id')
  1260. webpage_url = 'http://www.howcast.com/videos/' + video_id
  1261. webpage = self._download_webpage(webpage_url, video_id)
  1262. self.report_extraction(video_id)
  1263. video_url = self._search_regex(r'\'?file\'?: "(http://mobile-media\.howcast\.com/[0-9]+\.mp4)',
  1264. webpage, u'video URL')
  1265. video_title = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') property=\'og:title\'',
  1266. webpage, u'title')
  1267. video_description = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') name=\'description\'',
  1268. webpage, u'description', fatal=False)
  1269. thumbnail = self._html_search_regex(r'<meta content=\'(.+?)\' property=\'og:image\'',
  1270. webpage, u'thumbnail', fatal=False)
  1271. return [{
  1272. 'id': video_id,
  1273. 'url': video_url,
  1274. 'ext': 'mp4',
  1275. 'title': video_title,
  1276. 'description': video_description,
  1277. 'thumbnail': thumbnail,
  1278. }]
  1279. class VineIE(InfoExtractor):
  1280. """Information Extractor for Vine.co"""
  1281. _VALID_URL = r'(?:https?://)?(?:www\.)?vine\.co/v/(?P<id>\w+)'
  1282. def _real_extract(self, url):
  1283. mobj = re.match(self._VALID_URL, url)
  1284. video_id = mobj.group('id')
  1285. webpage_url = 'https://vine.co/v/' + video_id
  1286. webpage = self._download_webpage(webpage_url, video_id)
  1287. self.report_extraction(video_id)
  1288. video_url = self._html_search_regex(r'<meta property="twitter:player:stream" content="(.+?)"',
  1289. webpage, u'video URL')
  1290. video_title = self._html_search_regex(r'<meta property="og:title" content="(.+?)"',
  1291. webpage, u'title')
  1292. thumbnail = self._html_search_regex(r'<meta property="og:image" content="(.+?)(\?.*?)?"',
  1293. webpage, u'thumbnail', fatal=False)
  1294. uploader = self._html_search_regex(r'<div class="user">.*?<h2>(.+?)</h2>',
  1295. webpage, u'uploader', fatal=False, flags=re.DOTALL)
  1296. return [{
  1297. 'id': video_id,
  1298. 'url': video_url,
  1299. 'ext': 'mp4',
  1300. 'title': video_title,
  1301. 'thumbnail': thumbnail,
  1302. 'uploader': uploader,
  1303. }]
  1304. class FlickrIE(InfoExtractor):
  1305. """Information Extractor for Flickr videos"""
  1306. _VALID_URL = r'(?:https?://)?(?:www\.)?flickr\.com/photos/(?P<uploader_id>[\w\-_@]+)/(?P<id>\d+).*'
  1307. def _real_extract(self, url):
  1308. mobj = re.match(self._VALID_URL, url)
  1309. video_id = mobj.group('id')
  1310. video_uploader_id = mobj.group('uploader_id')
  1311. webpage_url = 'http://www.flickr.com/photos/' + video_uploader_id + '/' + video_id
  1312. webpage = self._download_webpage(webpage_url, video_id)
  1313. secret = self._search_regex(r"photo_secret: '(\w+)'", webpage, u'secret')
  1314. first_url = 'https://secure.flickr.com/apps/video/video_mtl_xml.gne?v=x&photo_id=' + video_id + '&secret=' + secret + '&bitrate=700&target=_self'
  1315. first_xml = self._download_webpage(first_url, video_id, 'Downloading first data webpage')
  1316. node_id = self._html_search_regex(r'<Item id="id">(\d+-\d+)</Item>',
  1317. first_xml, u'node_id')
  1318. 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'
  1319. second_xml = self._download_webpage(second_url, video_id, 'Downloading second data webpage')
  1320. self.report_extraction(video_id)
  1321. mobj = re.search(r'<STREAM APP="(.+?)" FULLPATH="(.+?)"', second_xml)
  1322. if mobj is None:
  1323. raise ExtractorError(u'Unable to extract video url')
  1324. video_url = mobj.group(1) + unescapeHTML(mobj.group(2))
  1325. video_title = self._html_search_regex(r'<meta property="og:title" content=(?:"([^"]+)"|\'([^\']+)\')',
  1326. webpage, u'video title')
  1327. video_description = self._html_search_regex(r'<meta property="og:description" content=(?:"([^"]+)"|\'([^\']+)\')',
  1328. webpage, u'description', fatal=False)
  1329. thumbnail = self._html_search_regex(r'<meta property="og:image" content=(?:"([^"]+)"|\'([^\']+)\')',
  1330. webpage, u'thumbnail', fatal=False)
  1331. return [{
  1332. 'id': video_id,
  1333. 'url': video_url,
  1334. 'ext': 'mp4',
  1335. 'title': video_title,
  1336. 'description': video_description,
  1337. 'thumbnail': thumbnail,
  1338. 'uploader_id': video_uploader_id,
  1339. }]
  1340. class TeamcocoIE(InfoExtractor):
  1341. _VALID_URL = r'http://teamcoco\.com/video/(?P<url_title>.*)'
  1342. def _real_extract(self, url):
  1343. mobj = re.match(self._VALID_URL, url)
  1344. if mobj is None:
  1345. raise ExtractorError(u'Invalid URL: %s' % url)
  1346. url_title = mobj.group('url_title')
  1347. webpage = self._download_webpage(url, url_title)
  1348. video_id = self._html_search_regex(r'<article class="video" data-id="(\d+?)"',
  1349. webpage, u'video id')
  1350. self.report_extraction(video_id)
  1351. video_title = self._html_search_regex(r'<meta property="og:title" content="(.+?)"',
  1352. webpage, u'title')
  1353. thumbnail = self._html_search_regex(r'<meta property="og:image" content="(.+?)"',
  1354. webpage, u'thumbnail', fatal=False)
  1355. video_description = self._html_search_regex(r'<meta property="og:description" content="(.*?)"',
  1356. webpage, u'description', fatal=False)
  1357. data_url = 'http://teamcoco.com/cvp/2.0/%s.xml' % video_id
  1358. data = self._download_webpage(data_url, video_id, 'Downloading data webpage')
  1359. video_url = self._html_search_regex(r'<file type="high".*?>(.*?)</file>',
  1360. data, u'video URL')
  1361. return [{
  1362. 'id': video_id,
  1363. 'url': video_url,
  1364. 'ext': 'mp4',
  1365. 'title': video_title,
  1366. 'thumbnail': thumbnail,
  1367. 'description': video_description,
  1368. }]
  1369. class XHamsterIE(InfoExtractor):
  1370. """Information Extractor for xHamster"""
  1371. _VALID_URL = r'(?:http://)?(?:www.)?xhamster\.com/movies/(?P<id>[0-9]+)/.*\.html'
  1372. def _real_extract(self,url):
  1373. mobj = re.match(self._VALID_URL, url)
  1374. video_id = mobj.group('id')
  1375. mrss_url = 'http://xhamster.com/movies/%s/.html' % video_id
  1376. webpage = self._download_webpage(mrss_url, video_id)
  1377. mobj = re.search(r'\'srv\': \'(?P<server>[^\']*)\',\s*\'file\': \'(?P<file>[^\']+)\',', webpage)
  1378. if mobj is None:
  1379. raise ExtractorError(u'Unable to extract media URL')
  1380. if len(mobj.group('server')) == 0:
  1381. video_url = compat_urllib_parse.unquote(mobj.group('file'))
  1382. else:
  1383. video_url = mobj.group('server')+'/key='+mobj.group('file')
  1384. video_extension = video_url.split('.')[-1]
  1385. video_title = self._html_search_regex(r'<title>(?P<title>.+?) - xHamster\.com</title>',
  1386. webpage, u'title')
  1387. # Can't see the description anywhere in the UI
  1388. # video_description = self._html_search_regex(r'<span>Description: </span>(?P<description>[^<]+)',
  1389. # webpage, u'description', fatal=False)
  1390. # if video_description: video_description = unescapeHTML(video_description)
  1391. 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)
  1392. if mobj:
  1393. video_upload_date = mobj.group('upload_date_Y')+mobj.group('upload_date_m')+mobj.group('upload_date_d')
  1394. else:
  1395. video_upload_date = None
  1396. self._downloader.report_warning(u'Unable to extract upload date')
  1397. video_uploader_id = self._html_search_regex(r'<a href=\'/user/[^>]+>(?P<uploader_id>[^<]+)',
  1398. webpage, u'uploader id', default=u'anonymous')
  1399. video_thumbnail = self._search_regex(r'\'image\':\'(?P<thumbnail>[^\']+)\'',
  1400. webpage, u'thumbnail', fatal=False)
  1401. return [{
  1402. 'id': video_id,
  1403. 'url': video_url,
  1404. 'ext': video_extension,
  1405. 'title': video_title,
  1406. # 'description': video_description,
  1407. 'upload_date': video_upload_date,
  1408. 'uploader_id': video_uploader_id,
  1409. 'thumbnail': video_thumbnail
  1410. }]
  1411. class HypemIE(InfoExtractor):
  1412. """Information Extractor for hypem"""
  1413. _VALID_URL = r'(?:http://)?(?:www\.)?hypem\.com/track/([^/]+)/([^/]+)'
  1414. def _real_extract(self, url):
  1415. mobj = re.match(self._VALID_URL, url)
  1416. if mobj is None:
  1417. raise ExtractorError(u'Invalid URL: %s' % url)
  1418. track_id = mobj.group(1)
  1419. data = { 'ax': 1, 'ts': time.time() }
  1420. data_encoded = compat_urllib_parse.urlencode(data)
  1421. complete_url = url + "?" + data_encoded
  1422. request = compat_urllib_request.Request(complete_url)
  1423. response, urlh = self._download_webpage_handle(request, track_id, u'Downloading webpage with the url')
  1424. cookie = urlh.headers.get('Set-Cookie', '')
  1425. self.report_extraction(track_id)
  1426. html_tracks = self._html_search_regex(r'<script type="application/json" id="displayList-data">(.*?)</script>',
  1427. response, u'tracks', flags=re.MULTILINE|re.DOTALL).strip()
  1428. try:
  1429. track_list = json.loads(html_tracks)
  1430. track = track_list[u'tracks'][0]
  1431. except ValueError:
  1432. raise ExtractorError(u'Hypemachine contained invalid JSON.')
  1433. key = track[u"key"]
  1434. track_id = track[u"id"]
  1435. artist = track[u"artist"]
  1436. title = track[u"song"]
  1437. serve_url = "http://hypem.com/serve/source/%s/%s" % (compat_str(track_id), compat_str(key))
  1438. request = compat_urllib_request.Request(serve_url, "" , {'Content-Type': 'application/json'})
  1439. request.add_header('cookie', cookie)
  1440. song_data_json = self._download_webpage(request, track_id, u'Downloading metadata')
  1441. try:
  1442. song_data = json.loads(song_data_json)
  1443. except ValueError:
  1444. raise ExtractorError(u'Hypemachine contained invalid JSON.')
  1445. final_url = song_data[u"url"]
  1446. return [{
  1447. 'id': track_id,
  1448. 'url': final_url,
  1449. 'ext': "mp3",
  1450. 'title': title,
  1451. 'artist': artist,
  1452. }]
  1453. class Vbox7IE(InfoExtractor):
  1454. """Information Extractor for Vbox7"""
  1455. _VALID_URL = r'(?:http://)?(?:www\.)?vbox7\.com/play:([^/]+)'
  1456. def _real_extract(self,url):
  1457. mobj = re.match(self._VALID_URL, url)
  1458. if mobj is None:
  1459. raise ExtractorError(u'Invalid URL: %s' % url)
  1460. video_id = mobj.group(1)
  1461. redirect_page, urlh = self._download_webpage_handle(url, video_id)
  1462. new_location = self._search_regex(r'window\.location = \'(.*)\';', redirect_page, u'redirect location')
  1463. redirect_url = urlh.geturl() + new_location
  1464. webpage = self._download_webpage(redirect_url, video_id, u'Downloading redirect page')
  1465. title = self._html_search_regex(r'<title>(.*)</title>',
  1466. webpage, u'title').split('/')[0].strip()
  1467. ext = "flv"
  1468. info_url = "http://vbox7.com/play/magare.do"
  1469. data = compat_urllib_parse.urlencode({'as3':'1','vid':video_id})
  1470. info_request = compat_urllib_request.Request(info_url, data)
  1471. info_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  1472. info_response = self._download_webpage(info_request, video_id, u'Downloading info webpage')
  1473. if info_response is None:
  1474. raise ExtractorError(u'Unable to extract the media url')
  1475. (final_url, thumbnail_url) = map(lambda x: x.split('=')[1], info_response.split('&'))
  1476. return [{
  1477. 'id': video_id,
  1478. 'url': final_url,
  1479. 'ext': ext,
  1480. 'title': title,
  1481. 'thumbnail': thumbnail_url,
  1482. }]
  1483. def gen_extractors():
  1484. """ Return a list of an instance of every supported extractor.
  1485. The order does matter; the first extractor matched is the one handling the URL.
  1486. """
  1487. return [
  1488. YoutubePlaylistIE(),
  1489. YoutubeChannelIE(),
  1490. YoutubeUserIE(),
  1491. YoutubeSearchIE(),
  1492. YoutubeIE(),
  1493. MetacafeIE(),
  1494. DailymotionIE(),
  1495. GoogleSearchIE(),
  1496. PhotobucketIE(),
  1497. YahooIE(),
  1498. YahooSearchIE(),
  1499. DepositFilesIE(),
  1500. FacebookIE(),
  1501. BlipTVIE(),
  1502. BlipTVUserIE(),
  1503. VimeoIE(),
  1504. MyVideoIE(),
  1505. ComedyCentralIE(),
  1506. EscapistIE(),
  1507. CollegeHumorIE(),
  1508. XVideosIE(),
  1509. SoundcloudSetIE(),
  1510. SoundcloudIE(),
  1511. InfoQIE(),
  1512. MixcloudIE(),
  1513. StanfordOpenClassroomIE(),
  1514. MTVIE(),
  1515. YoukuIE(),
  1516. XNXXIE(),
  1517. YouJizzIE(),
  1518. PornotubeIE(),
  1519. YouPornIE(),
  1520. GooglePlusIE(),
  1521. ArteTvIE(),
  1522. NBAIE(),
  1523. WorldStarHipHopIE(),
  1524. JustinTVIE(),
  1525. FunnyOrDieIE(),
  1526. SteamIE(),
  1527. UstreamIE(),
  1528. RBMARadioIE(),
  1529. EightTracksIE(),
  1530. KeekIE(),
  1531. TEDIE(),
  1532. MySpassIE(),
  1533. SpiegelIE(),
  1534. LiveLeakIE(),
  1535. ARDIE(),
  1536. ZDFIE(),
  1537. TumblrIE(),
  1538. BandcampIE(),
  1539. RedTubeIE(),
  1540. InaIE(),
  1541. HowcastIE(),
  1542. VineIE(),
  1543. FlickrIE(),
  1544. TeamcocoIE(),
  1545. XHamsterIE(),
  1546. HypemIE(),
  1547. Vbox7IE(),
  1548. GametrailersIE(),
  1549. StatigramIE(),
  1550. GenericIE()
  1551. ]
  1552. def get_info_extractor(ie_name):
  1553. """Returns the info extractor class with the given ie_name"""
  1554. return globals()[ie_name+'IE']