InfoExtractors.py 70 KB

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