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.

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