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.

2031 lines
76 KiB

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