InfoExtractors.py 69 KB

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