InfoExtractors.py 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import base64
  5. import datetime
  6. import itertools
  7. import netrc
  8. import os
  9. import re
  10. import socket
  11. import time
  12. import email.utils
  13. import xml.etree.ElementTree
  14. import random
  15. import math
  16. import operator
  17. import hashlib
  18. import binascii
  19. import urllib
  20. from .utils import *
  21. from .extractor.common import InfoExtractor, SearchInfoExtractor
  22. from .extractor.ard import ARDIE
  23. from .extractor.arte import ArteTvIE
  24. from .extractor.dailymotion import DailymotionIE
  25. from .extractor.gametrailers import GametrailersIE
  26. from .extractor.generic import GenericIE
  27. from .extractor.metacafe import MetacafeIE
  28. from .extractor.statigram import StatigramIE
  29. from .extractor.photobucket import PhotobucketIE
  30. from .extractor.vimeo import VimeoIE
  31. from .extractor.yahoo import YahooIE
  32. from .extractor.youtube import YoutubeIE, YoutubePlaylistIE, YoutubeSearchIE, YoutubeUserIE, YoutubeChannelIE
  33. from .extractor.zdf import ZDFIE
  34. class GoogleSearchIE(SearchInfoExtractor):
  35. """Information Extractor for Google Video search queries."""
  36. _MORE_PAGES_INDICATOR = r'id="pnnext" class="pn"'
  37. _MAX_RESULTS = 1000
  38. IE_NAME = u'video.google:search'
  39. _SEARCH_KEY = 'gvsearch'
  40. def _get_n_results(self, query, n):
  41. """Get a specified number of results for a query"""
  42. res = {
  43. '_type': 'playlist',
  44. 'id': query,
  45. 'entries': []
  46. }
  47. for pagenum in itertools.count(1):
  48. result_url = u'http://www.google.com/search?tbm=vid&q=%s&start=%s&hl=en' % (compat_urllib_parse.quote_plus(query), pagenum*10)
  49. webpage = self._download_webpage(result_url, u'gvsearch:' + query,
  50. note='Downloading result page ' + str(pagenum))
  51. for mobj in re.finditer(r'<h3 class="r"><a href="([^"]+)"', webpage):
  52. e = {
  53. '_type': 'url',
  54. 'url': mobj.group(1)
  55. }
  56. res['entries'].append(e)
  57. if (pagenum * 10 > n) or not re.search(self._MORE_PAGES_INDICATOR, webpage):
  58. return res
  59. class YahooSearchIE(SearchInfoExtractor):
  60. """Information Extractor for Yahoo! Video search queries."""
  61. _MAX_RESULTS = 1000
  62. IE_NAME = u'screen.yahoo:search'
  63. _SEARCH_KEY = 'yvsearch'
  64. def _get_n_results(self, query, n):
  65. """Get a specified number of results for a query"""
  66. res = {
  67. '_type': 'playlist',
  68. 'id': query,
  69. 'entries': []
  70. }
  71. for pagenum in itertools.count(0):
  72. result_url = u'http://video.search.yahoo.com/search/?p=%s&fr=screen&o=js&gs=0&b=%d' % (compat_urllib_parse.quote_plus(query), pagenum * 30)
  73. webpage = self._download_webpage(result_url, query,
  74. note='Downloading results page '+str(pagenum+1))
  75. info = json.loads(webpage)
  76. m = info[u'm']
  77. results = info[u'results']
  78. for (i, r) in enumerate(results):
  79. if (pagenum * 30) +i >= n:
  80. break
  81. mobj = re.search(r'(?P<url>screen\.yahoo\.com/.*?-\d*?\.html)"', r)
  82. e = self.url_result('http://' + mobj.group('url'), 'Yahoo')
  83. res['entries'].append(e)
  84. if (pagenum * 30 +i >= n) or (m[u'last'] >= (m[u'total'] -1 )):
  85. break
  86. return res
  87. class BlipTVUserIE(InfoExtractor):
  88. """Information Extractor for blip.tv users."""
  89. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  90. _PAGE_SIZE = 12
  91. IE_NAME = u'blip.tv:user'
  92. def _real_extract(self, url):
  93. # Extract username
  94. mobj = re.match(self._VALID_URL, url)
  95. if mobj is None:
  96. raise ExtractorError(u'Invalid URL: %s' % url)
  97. username = mobj.group(1)
  98. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  99. page = self._download_webpage(url, username, u'Downloading user page')
  100. mobj = re.search(r'data-users-id="([^"]+)"', page)
  101. page_base = page_base % mobj.group(1)
  102. # Download video ids using BlipTV Ajax calls. Result size per
  103. # query is limited (currently to 12 videos) so we need to query
  104. # page by page until there are no video ids - it means we got
  105. # all of them.
  106. video_ids = []
  107. pagenum = 1
  108. while True:
  109. url = page_base + "&page=" + str(pagenum)
  110. page = self._download_webpage(url, username,
  111. u'Downloading video ids from page %d' % pagenum)
  112. # Extract video identifiers
  113. ids_in_page = []
  114. for mobj in re.finditer(r'href="/([^"]+)"', page):
  115. if mobj.group(1) not in ids_in_page:
  116. ids_in_page.append(unescapeHTML(mobj.group(1)))
  117. video_ids.extend(ids_in_page)
  118. # A little optimization - if current page is not
  119. # "full", ie. does not contain PAGE_SIZE video ids then
  120. # we can assume that this page is the last one - there
  121. # are no more ids on further pages - no need to query
  122. # again.
  123. if len(ids_in_page) < self._PAGE_SIZE:
  124. break
  125. pagenum += 1
  126. urls = [u'http://blip.tv/%s' % video_id for video_id in video_ids]
  127. url_entries = [self.url_result(url, 'BlipTV') for url in urls]
  128. return [self.playlist_result(url_entries, playlist_title = username)]
  129. class DepositFilesIE(InfoExtractor):
  130. """Information extractor for depositfiles.com"""
  131. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  132. def _real_extract(self, url):
  133. file_id = url.split('/')[-1]
  134. # Rebuild url in english locale
  135. url = 'http://depositfiles.com/en/files/' + file_id
  136. # Retrieve file webpage with 'Free download' button pressed
  137. free_download_indication = { 'gateway_result' : '1' }
  138. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  139. try:
  140. self.report_download_webpage(file_id)
  141. webpage = compat_urllib_request.urlopen(request).read()
  142. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  143. raise ExtractorError(u'Unable to retrieve file webpage: %s' % compat_str(err))
  144. # Search for the real file URL
  145. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  146. if (mobj is None) or (mobj.group(1) is None):
  147. # Try to figure out reason of the error.
  148. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  149. if (mobj is not None) and (mobj.group(1) is not None):
  150. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  151. raise ExtractorError(u'%s' % restriction_message)
  152. else:
  153. raise ExtractorError(u'Unable to extract download URL from: %s' % url)
  154. file_url = mobj.group(1)
  155. file_extension = os.path.splitext(file_url)[1][1:]
  156. # Search for file title
  157. file_title = self._search_regex(r'<b title="(.*?)">', webpage, u'title')
  158. return [{
  159. 'id': file_id.decode('utf-8'),
  160. 'url': file_url.decode('utf-8'),
  161. 'uploader': None,
  162. 'upload_date': None,
  163. 'title': file_title,
  164. 'ext': file_extension.decode('utf-8'),
  165. }]
  166. class FacebookIE(InfoExtractor):
  167. """Information Extractor for Facebook"""
  168. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  169. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  170. _NETRC_MACHINE = 'facebook'
  171. IE_NAME = u'facebook'
  172. def report_login(self):
  173. """Report attempt to log in."""
  174. self.to_screen(u'Logging in')
  175. def _real_initialize(self):
  176. if self._downloader is None:
  177. return
  178. useremail = None
  179. password = None
  180. downloader_params = self._downloader.params
  181. # Attempt to use provided username and password or .netrc data
  182. if downloader_params.get('username', None) is not None:
  183. useremail = downloader_params['username']
  184. password = downloader_params['password']
  185. elif downloader_params.get('usenetrc', False):
  186. try:
  187. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  188. if info is not None:
  189. useremail = info[0]
  190. password = info[2]
  191. else:
  192. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  193. except (IOError, netrc.NetrcParseError) as err:
  194. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  195. return
  196. if useremail is None:
  197. return
  198. # Log in
  199. login_form = {
  200. 'email': useremail,
  201. 'pass': password,
  202. 'login': 'Log+In'
  203. }
  204. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  205. try:
  206. self.report_login()
  207. login_results = compat_urllib_request.urlopen(request).read()
  208. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  209. self._downloader.report_warning(u'unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  210. return
  211. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  212. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  213. return
  214. def _real_extract(self, url):
  215. mobj = re.match(self._VALID_URL, url)
  216. if mobj is None:
  217. raise ExtractorError(u'Invalid URL: %s' % url)
  218. video_id = mobj.group('ID')
  219. url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
  220. webpage = self._download_webpage(url, video_id)
  221. BEFORE = '{swf.addParam(param[0], param[1]);});\n'
  222. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  223. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  224. if not m:
  225. raise ExtractorError(u'Cannot parse data')
  226. data = dict(json.loads(m.group(1)))
  227. params_raw = compat_urllib_parse.unquote(data['params'])
  228. params = json.loads(params_raw)
  229. video_data = params['video_data'][0]
  230. video_url = video_data.get('hd_src')
  231. if not video_url:
  232. video_url = video_data['sd_src']
  233. if not video_url:
  234. raise ExtractorError(u'Cannot find video URL')
  235. video_duration = int(video_data['video_duration'])
  236. thumbnail = video_data['thumbnail_src']
  237. video_title = self._html_search_regex('<h2 class="uiHeaderTitle">([^<]+)</h2>',
  238. webpage, u'title')
  239. info = {
  240. 'id': video_id,
  241. 'title': video_title,
  242. 'url': video_url,
  243. 'ext': 'mp4',
  244. 'duration': video_duration,
  245. 'thumbnail': thumbnail,
  246. }
  247. return [info]
  248. class BlipTVIE(InfoExtractor):
  249. """Information extractor for blip.tv"""
  250. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(.+)$'
  251. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  252. IE_NAME = u'blip.tv'
  253. def report_direct_download(self, title):
  254. """Report information extraction."""
  255. self.to_screen(u'%s: Direct download detected' % title)
  256. def _real_extract(self, url):
  257. mobj = re.match(self._VALID_URL, url)
  258. if mobj is None:
  259. raise ExtractorError(u'Invalid URL: %s' % url)
  260. # See https://github.com/rg3/youtube-dl/issues/857
  261. api_mobj = re.match(r'http://a\.blip\.tv/api\.swf#(?P<video_id>[\d\w]+)', url)
  262. if api_mobj is not None:
  263. url = 'http://blip.tv/play/g_%s' % api_mobj.group('video_id')
  264. urlp = compat_urllib_parse_urlparse(url)
  265. if urlp.path.startswith('/play/'):
  266. request = compat_urllib_request.Request(url)
  267. response = compat_urllib_request.urlopen(request)
  268. redirecturl = response.geturl()
  269. rurlp = compat_urllib_parse_urlparse(redirecturl)
  270. file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
  271. url = 'http://blip.tv/a/a-' + file_id
  272. return self._real_extract(url)
  273. if '?' in url:
  274. cchar = '&'
  275. else:
  276. cchar = '?'
  277. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  278. request = compat_urllib_request.Request(json_url)
  279. request.add_header('User-Agent', 'iTunes/10.6.1')
  280. self.report_extraction(mobj.group(1))
  281. info = None
  282. try:
  283. urlh = compat_urllib_request.urlopen(request)
  284. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  285. basename = url.split('/')[-1]
  286. title,ext = os.path.splitext(basename)
  287. title = title.decode('UTF-8')
  288. ext = ext.replace('.', '')
  289. self.report_direct_download(title)
  290. info = {
  291. 'id': title,
  292. 'url': url,
  293. 'uploader': None,
  294. 'upload_date': None,
  295. 'title': title,
  296. 'ext': ext,
  297. 'urlhandle': urlh
  298. }
  299. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  300. raise ExtractorError(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  301. if info is None: # Regular URL
  302. try:
  303. json_code_bytes = urlh.read()
  304. json_code = json_code_bytes.decode('utf-8')
  305. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  306. raise ExtractorError(u'Unable to read video info webpage: %s' % compat_str(err))
  307. try:
  308. json_data = json.loads(json_code)
  309. if 'Post' in json_data:
  310. data = json_data['Post']
  311. else:
  312. data = json_data
  313. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  314. video_url = data['media']['url']
  315. umobj = re.match(self._URL_EXT, video_url)
  316. if umobj is None:
  317. raise ValueError('Can not determine filename extension')
  318. ext = umobj.group(1)
  319. info = {
  320. 'id': data['item_id'],
  321. 'url': video_url,
  322. 'uploader': data['display_name'],
  323. 'upload_date': upload_date,
  324. 'title': data['title'],
  325. 'ext': ext,
  326. 'format': data['media']['mimeType'],
  327. 'thumbnail': data['thumbnailUrl'],
  328. 'description': data['description'],
  329. 'player_url': data['embedUrl'],
  330. 'user_agent': 'iTunes/10.6.1',
  331. }
  332. except (ValueError,KeyError) as err:
  333. raise ExtractorError(u'Unable to parse video information: %s' % repr(err))
  334. return [info]
  335. class MyVideoIE(InfoExtractor):
  336. """Information Extractor for myvideo.de."""
  337. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  338. IE_NAME = u'myvideo'
  339. # Original Code from: https://github.com/dersphere/plugin.video.myvideo_de.git
  340. # Released into the Public Domain by Tristan Fischer on 2013-05-19
  341. # https://github.com/rg3/youtube-dl/pull/842
  342. def __rc4crypt(self,data, key):
  343. x = 0
  344. box = list(range(256))
  345. for i in list(range(256)):
  346. x = (x + box[i] + compat_ord(key[i % len(key)])) % 256
  347. box[i], box[x] = box[x], box[i]
  348. x = 0
  349. y = 0
  350. out = ''
  351. for char in data:
  352. x = (x + 1) % 256
  353. y = (y + box[x]) % 256
  354. box[x], box[y] = box[y], box[x]
  355. out += chr(compat_ord(char) ^ box[(box[x] + box[y]) % 256])
  356. return out
  357. def __md5(self,s):
  358. return hashlib.md5(s).hexdigest().encode()
  359. def _real_extract(self,url):
  360. mobj = re.match(self._VALID_URL, url)
  361. if mobj is None:
  362. raise ExtractorError(u'invalid URL: %s' % url)
  363. video_id = mobj.group(1)
  364. GK = (
  365. b'WXpnME1EZGhNRGhpTTJNM01XVmhOREU0WldNNVpHTTJOakpt'
  366. b'TW1FMU5tVTBNR05pWkRaa05XRXhNVFJoWVRVd1ptSXhaVEV3'
  367. b'TnpsbA0KTVRkbU1tSTRNdz09'
  368. )
  369. # Get video webpage
  370. webpage_url = 'http://www.myvideo.de/watch/%s' % video_id
  371. webpage = self._download_webpage(webpage_url, video_id)
  372. mobj = re.search('source src=\'(.+?)[.]([^.]+)\'', webpage)
  373. if mobj is not None:
  374. self.report_extraction(video_id)
  375. video_url = mobj.group(1) + '.flv'
  376. video_title = self._html_search_regex('<title>([^<]+)</title>',
  377. webpage, u'title')
  378. video_ext = self._search_regex('[.](.+?)$', video_url, u'extension')
  379. return [{
  380. 'id': video_id,
  381. 'url': video_url,
  382. 'uploader': None,
  383. 'upload_date': None,
  384. 'title': video_title,
  385. 'ext': u'flv',
  386. }]
  387. # try encxml
  388. mobj = re.search('var flashvars={(.+?)}', webpage)
  389. if mobj is None:
  390. raise ExtractorError(u'Unable to extract video')
  391. params = {}
  392. encxml = ''
  393. sec = mobj.group(1)
  394. for (a, b) in re.findall('(.+?):\'(.+?)\',?', sec):
  395. if not a == '_encxml':
  396. params[a] = b
  397. else:
  398. encxml = compat_urllib_parse.unquote(b)
  399. if not params.get('domain'):
  400. params['domain'] = 'www.myvideo.de'
  401. xmldata_url = '%s?%s' % (encxml, compat_urllib_parse.urlencode(params))
  402. if 'flash_playertype=MTV' in xmldata_url:
  403. self._downloader.report_warning(u'avoiding MTV player')
  404. xmldata_url = (
  405. 'http://www.myvideo.de/dynamic/get_player_video_xml.php'
  406. '?flash_playertype=D&ID=%s&_countlimit=4&autorun=yes'
  407. ) % video_id
  408. # get enc data
  409. enc_data = self._download_webpage(xmldata_url, video_id).split('=')[1]
  410. enc_data_b = binascii.unhexlify(enc_data)
  411. sk = self.__md5(
  412. base64.b64decode(base64.b64decode(GK)) +
  413. self.__md5(
  414. str(video_id).encode('utf-8')
  415. )
  416. )
  417. dec_data = self.__rc4crypt(enc_data_b, sk)
  418. # extracting infos
  419. self.report_extraction(video_id)
  420. video_url = None
  421. mobj = re.search('connectionurl=\'(.*?)\'', dec_data)
  422. if mobj:
  423. video_url = compat_urllib_parse.unquote(mobj.group(1))
  424. if 'myvideo2flash' in video_url:
  425. self._downloader.report_warning(u'forcing RTMPT ...')
  426. video_url = video_url.replace('rtmpe://', 'rtmpt://')
  427. if not video_url:
  428. # extract non rtmp videos
  429. mobj = re.search('path=\'(http.*?)\' source=\'(.*?)\'', dec_data)
  430. if mobj is None:
  431. raise ExtractorError(u'unable to extract url')
  432. video_url = compat_urllib_parse.unquote(mobj.group(1)) + compat_urllib_parse.unquote(mobj.group(2))
  433. video_file = self._search_regex('source=\'(.*?)\'', dec_data, u'video file')
  434. video_file = compat_urllib_parse.unquote(video_file)
  435. if not video_file.endswith('f4m'):
  436. ppath, prefix = video_file.split('.')
  437. video_playpath = '%s:%s' % (prefix, ppath)
  438. video_hls_playlist = ''
  439. else:
  440. video_playpath = ''
  441. video_hls_playlist = (
  442. video_filepath + video_file
  443. ).replace('.f4m', '.m3u8')
  444. video_swfobj = self._search_regex('swfobject.embedSWF\(\'(.+?)\'', webpage, u'swfobj')
  445. video_swfobj = compat_urllib_parse.unquote(video_swfobj)
  446. video_title = self._html_search_regex("<h1(?: class='globalHd')?>(.*?)</h1>",
  447. webpage, u'title')
  448. return [{
  449. 'id': video_id,
  450. 'url': video_url,
  451. 'tc_url': video_url,
  452. 'uploader': None,
  453. 'upload_date': None,
  454. 'title': video_title,
  455. 'ext': u'flv',
  456. 'play_path': video_playpath,
  457. 'video_file': video_file,
  458. 'video_hls_playlist': video_hls_playlist,
  459. 'player_url': video_swfobj,
  460. }]
  461. class ComedyCentralIE(InfoExtractor):
  462. """Information extractor for The Daily Show and Colbert Report """
  463. # urls can be abbreviations like :thedailyshow or :colbert
  464. # urls for episodes like:
  465. # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
  466. # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
  467. # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
  468. _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
  469. |(https?://)?(www\.)?
  470. (?P<showname>thedailyshow|colbertnation)\.com/
  471. (full-episodes/(?P<episode>.*)|
  472. (?P<clip>
  473. (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
  474. |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
  475. $"""
  476. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  477. _video_extensions = {
  478. '3500': 'mp4',
  479. '2200': 'mp4',
  480. '1700': 'mp4',
  481. '1200': 'mp4',
  482. '750': 'mp4',
  483. '400': 'mp4',
  484. }
  485. _video_dimensions = {
  486. '3500': '1280x720',
  487. '2200': '960x540',
  488. '1700': '768x432',
  489. '1200': '640x360',
  490. '750': '512x288',
  491. '400': '384x216',
  492. }
  493. @classmethod
  494. def suitable(cls, url):
  495. """Receives a URL and returns True if suitable for this IE."""
  496. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  497. def _print_formats(self, formats):
  498. print('Available formats:')
  499. for x in formats:
  500. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  501. def _real_extract(self, url):
  502. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  503. if mobj is None:
  504. raise ExtractorError(u'Invalid URL: %s' % url)
  505. if mobj.group('shortname'):
  506. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  507. url = u'http://www.thedailyshow.com/full-episodes/'
  508. else:
  509. url = u'http://www.colbertnation.com/full-episodes/'
  510. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  511. assert mobj is not None
  512. if mobj.group('clip'):
  513. if mobj.group('showname') == 'thedailyshow':
  514. epTitle = mobj.group('tdstitle')
  515. else:
  516. epTitle = mobj.group('cntitle')
  517. dlNewest = False
  518. else:
  519. dlNewest = not mobj.group('episode')
  520. if dlNewest:
  521. epTitle = mobj.group('showname')
  522. else:
  523. epTitle = mobj.group('episode')
  524. self.report_extraction(epTitle)
  525. webpage,htmlHandle = self._download_webpage_handle(url, epTitle)
  526. if dlNewest:
  527. url = htmlHandle.geturl()
  528. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  529. if mobj is None:
  530. raise ExtractorError(u'Invalid redirected URL: ' + url)
  531. if mobj.group('episode') == '':
  532. raise ExtractorError(u'Redirected URL is still not specific: ' + url)
  533. epTitle = mobj.group('episode')
  534. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
  535. if len(mMovieParams) == 0:
  536. # The Colbert Report embeds the information in a without
  537. # a URL prefix; so extract the alternate reference
  538. # and then add the URL prefix manually.
  539. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
  540. if len(altMovieParams) == 0:
  541. raise ExtractorError(u'unable to find Flash URL in webpage ' + url)
  542. else:
  543. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  544. uri = mMovieParams[0][1]
  545. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  546. indexXml = self._download_webpage(indexUrl, epTitle,
  547. u'Downloading show index',
  548. u'unable to download episode index')
  549. results = []
  550. idoc = xml.etree.ElementTree.fromstring(indexXml)
  551. itemEls = idoc.findall('.//item')
  552. for partNum,itemEl in enumerate(itemEls):
  553. mediaId = itemEl.findall('./guid')[0].text
  554. shortMediaId = mediaId.split(':')[-1]
  555. showId = mediaId.split(':')[-2].replace('.com', '')
  556. officialTitle = itemEl.findall('./title')[0].text
  557. officialDate = unified_strdate(itemEl.findall('./pubDate')[0].text)
  558. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  559. compat_urllib_parse.urlencode({'uri': mediaId}))
  560. configXml = self._download_webpage(configUrl, epTitle,
  561. u'Downloading configuration for %s' % shortMediaId)
  562. cdoc = xml.etree.ElementTree.fromstring(configXml)
  563. turls = []
  564. for rendition in cdoc.findall('.//rendition'):
  565. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  566. turls.append(finfo)
  567. if len(turls) == 0:
  568. self._downloader.report_error(u'unable to download ' + mediaId + ': No videos found')
  569. continue
  570. if self._downloader.params.get('listformats', None):
  571. self._print_formats([i[0] for i in turls])
  572. return
  573. # For now, just pick the highest bitrate
  574. format,rtmp_video_url = turls[-1]
  575. # Get the format arg from the arg stream
  576. req_format = self._downloader.params.get('format', None)
  577. # Select format if we can find one
  578. for f,v in turls:
  579. if f == req_format:
  580. format, rtmp_video_url = f, v
  581. break
  582. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
  583. if not m:
  584. raise ExtractorError(u'Cannot transform RTMP url')
  585. base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
  586. video_url = base + m.group('finalid')
  587. effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
  588. info = {
  589. 'id': shortMediaId,
  590. 'url': video_url,
  591. 'uploader': showId,
  592. 'upload_date': officialDate,
  593. 'title': effTitle,
  594. 'ext': 'mp4',
  595. 'format': format,
  596. 'thumbnail': None,
  597. 'description': officialTitle,
  598. }
  599. results.append(info)
  600. return results
  601. class EscapistIE(InfoExtractor):
  602. """Information extractor for The Escapist """
  603. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  604. IE_NAME = u'escapist'
  605. def _real_extract(self, url):
  606. mobj = re.match(self._VALID_URL, url)
  607. if mobj is None:
  608. raise ExtractorError(u'Invalid URL: %s' % url)
  609. showName = mobj.group('showname')
  610. videoId = mobj.group('episode')
  611. self.report_extraction(videoId)
  612. webpage = self._download_webpage(url, videoId)
  613. videoDesc = self._html_search_regex('<meta name="description" content="([^"]*)"',
  614. webpage, u'description', fatal=False)
  615. imgUrl = self._html_search_regex('<meta property="og:image" content="([^"]*)"',
  616. webpage, u'thumbnail', fatal=False)
  617. playerUrl = self._html_search_regex('<meta property="og:video" content="([^"]*)"',
  618. webpage, u'player url')
  619. title = self._html_search_regex('<meta name="title" content="([^"]*)"',
  620. webpage, u'player url').split(' : ')[-1]
  621. configUrl = self._search_regex('config=(.*)$', playerUrl, u'config url')
  622. configUrl = compat_urllib_parse.unquote(configUrl)
  623. configJSON = self._download_webpage(configUrl, videoId,
  624. u'Downloading configuration',
  625. u'unable to download configuration')
  626. # Technically, it's JavaScript, not JSON
  627. configJSON = configJSON.replace("'", '"')
  628. try:
  629. config = json.loads(configJSON)
  630. except (ValueError,) as err:
  631. raise ExtractorError(u'Invalid JSON in configuration file: ' + compat_str(err))
  632. playlist = config['playlist']
  633. videoUrl = playlist[1]['url']
  634. info = {
  635. 'id': videoId,
  636. 'url': videoUrl,
  637. 'uploader': showName,
  638. 'upload_date': None,
  639. 'title': title,
  640. 'ext': 'mp4',
  641. 'thumbnail': imgUrl,
  642. 'description': videoDesc,
  643. 'player_url': playerUrl,
  644. }
  645. return [info]
  646. class CollegeHumorIE(InfoExtractor):
  647. """Information extractor for collegehumor.com"""
  648. _WORKING = False
  649. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  650. IE_NAME = u'collegehumor'
  651. def report_manifest(self, video_id):
  652. """Report information extraction."""
  653. self.to_screen(u'%s: Downloading XML manifest' % video_id)
  654. def _real_extract(self, url):
  655. mobj = re.match(self._VALID_URL, url)
  656. if mobj is None:
  657. raise ExtractorError(u'Invalid URL: %s' % url)
  658. video_id = mobj.group('videoid')
  659. info = {
  660. 'id': video_id,
  661. 'uploader': None,
  662. 'upload_date': None,
  663. }
  664. self.report_extraction(video_id)
  665. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  666. try:
  667. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  668. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  669. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  670. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  671. try:
  672. videoNode = mdoc.findall('./video')[0]
  673. info['description'] = videoNode.findall('./description')[0].text
  674. info['title'] = videoNode.findall('./caption')[0].text
  675. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  676. manifest_url = videoNode.findall('./file')[0].text
  677. except IndexError:
  678. raise ExtractorError(u'Invalid metadata XML file')
  679. manifest_url += '?hdcore=2.10.3'
  680. self.report_manifest(video_id)
  681. try:
  682. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  683. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  684. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  685. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  686. try:
  687. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  688. node_id = media_node.attrib['url']
  689. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  690. except IndexError as err:
  691. raise ExtractorError(u'Invalid manifest file')
  692. url_pr = compat_urllib_parse_urlparse(manifest_url)
  693. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  694. info['url'] = url
  695. info['ext'] = 'f4f'
  696. return [info]
  697. class XVideosIE(InfoExtractor):
  698. """Information extractor for xvideos.com"""
  699. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  700. IE_NAME = u'xvideos'
  701. def _real_extract(self, url):
  702. mobj = re.match(self._VALID_URL, url)
  703. if mobj is None:
  704. raise ExtractorError(u'Invalid URL: %s' % url)
  705. video_id = mobj.group(1)
  706. webpage = self._download_webpage(url, video_id)
  707. self.report_extraction(video_id)
  708. # Extract video URL
  709. video_url = compat_urllib_parse.unquote(self._search_regex(r'flv_url=(.+?)&',
  710. webpage, u'video URL'))
  711. # Extract title
  712. video_title = self._html_search_regex(r'<title>(.*?)\s+-\s+XVID',
  713. webpage, u'title')
  714. # Extract video thumbnail
  715. 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)',
  716. webpage, u'thumbnail', fatal=False)
  717. info = {
  718. 'id': video_id,
  719. 'url': video_url,
  720. 'uploader': None,
  721. 'upload_date': None,
  722. 'title': video_title,
  723. 'ext': 'flv',
  724. 'thumbnail': video_thumbnail,
  725. 'description': None,
  726. }
  727. return [info]
  728. class SoundcloudIE(InfoExtractor):
  729. """Information extractor for soundcloud.com
  730. To access the media, the uid of the song and a stream token
  731. must be extracted from the page source and the script must make
  732. a request to media.soundcloud.com/crossdomain.xml. Then
  733. the media can be grabbed by requesting from an url composed
  734. of the stream token and uid
  735. """
  736. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  737. IE_NAME = u'soundcloud'
  738. def report_resolve(self, video_id):
  739. """Report information extraction."""
  740. self.to_screen(u'%s: Resolving id' % video_id)
  741. def _real_extract(self, url):
  742. mobj = re.match(self._VALID_URL, url)
  743. if mobj is None:
  744. raise ExtractorError(u'Invalid URL: %s' % url)
  745. # extract uploader (which is in the url)
  746. uploader = mobj.group(1)
  747. # extract simple title (uploader + slug of song title)
  748. slug_title = mobj.group(2)
  749. simple_title = uploader + u'-' + slug_title
  750. full_title = '%s/%s' % (uploader, slug_title)
  751. self.report_resolve(full_title)
  752. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  753. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  754. info_json = self._download_webpage(resolv_url, full_title, u'Downloading info JSON')
  755. info = json.loads(info_json)
  756. video_id = info['id']
  757. self.report_extraction(full_title)
  758. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  759. stream_json = self._download_webpage(streams_url, full_title,
  760. u'Downloading stream definitions',
  761. u'unable to download stream definitions')
  762. streams = json.loads(stream_json)
  763. mediaURL = streams['http_mp3_128_url']
  764. upload_date = unified_strdate(info['created_at'])
  765. return [{
  766. 'id': info['id'],
  767. 'url': mediaURL,
  768. 'uploader': info['user']['username'],
  769. 'upload_date': upload_date,
  770. 'title': info['title'],
  771. 'ext': u'mp3',
  772. 'description': info['description'],
  773. }]
  774. class SoundcloudSetIE(InfoExtractor):
  775. """Information extractor for soundcloud.com sets
  776. To access the media, the uid of the song and a stream token
  777. must be extracted from the page source and the script must make
  778. a request to media.soundcloud.com/crossdomain.xml. Then
  779. the media can be grabbed by requesting from an url composed
  780. of the stream token and uid
  781. """
  782. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
  783. IE_NAME = u'soundcloud:set'
  784. def report_resolve(self, video_id):
  785. """Report information extraction."""
  786. self.to_screen(u'%s: Resolving id' % video_id)
  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. # extract uploader (which is in the url)
  792. uploader = mobj.group(1)
  793. # extract simple title (uploader + slug of song title)
  794. slug_title = mobj.group(2)
  795. simple_title = uploader + u'-' + slug_title
  796. full_title = '%s/sets/%s' % (uploader, slug_title)
  797. self.report_resolve(full_title)
  798. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  799. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  800. info_json = self._download_webpage(resolv_url, full_title)
  801. videos = []
  802. info = json.loads(info_json)
  803. if 'errors' in info:
  804. for err in info['errors']:
  805. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
  806. return
  807. self.report_extraction(full_title)
  808. for track in info['tracks']:
  809. video_id = track['id']
  810. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  811. stream_json = self._download_webpage(streams_url, video_id, u'Downloading track info JSON')
  812. self.report_extraction(video_id)
  813. streams = json.loads(stream_json)
  814. mediaURL = streams['http_mp3_128_url']
  815. videos.append({
  816. 'id': video_id,
  817. 'url': mediaURL,
  818. 'uploader': track['user']['username'],
  819. 'upload_date': unified_strdate(track['created_at']),
  820. 'title': track['title'],
  821. 'ext': u'mp3',
  822. 'description': track['description'],
  823. })
  824. return videos
  825. class InfoQIE(InfoExtractor):
  826. """Information extractor for infoq.com"""
  827. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  828. def _real_extract(self, url):
  829. mobj = re.match(self._VALID_URL, url)
  830. if mobj is None:
  831. raise ExtractorError(u'Invalid URL: %s' % url)
  832. webpage = self._download_webpage(url, video_id=url)
  833. self.report_extraction(url)
  834. # Extract video URL
  835. mobj = re.search(r"jsclassref ?= ?'([^']*)'", webpage)
  836. if mobj is None:
  837. raise ExtractorError(u'Unable to extract video url')
  838. real_id = compat_urllib_parse.unquote(base64.b64decode(mobj.group(1).encode('ascii')).decode('utf-8'))
  839. video_url = 'rtmpe://video.infoq.com/cfx/st/' + real_id
  840. # Extract title
  841. video_title = self._search_regex(r'contentTitle = "(.*?)";',
  842. webpage, u'title')
  843. # Extract description
  844. video_description = self._html_search_regex(r'<meta name="description" content="(.*)"(?:\s*/)?>',
  845. webpage, u'description', fatal=False)
  846. video_filename = video_url.split('/')[-1]
  847. video_id, extension = video_filename.split('.')
  848. info = {
  849. 'id': video_id,
  850. 'url': video_url,
  851. 'uploader': None,
  852. 'upload_date': None,
  853. 'title': video_title,
  854. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  855. 'thumbnail': None,
  856. 'description': video_description,
  857. }
  858. return [info]
  859. class MixcloudIE(InfoExtractor):
  860. """Information extractor for www.mixcloud.com"""
  861. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  862. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  863. IE_NAME = u'mixcloud'
  864. def report_download_json(self, file_id):
  865. """Report JSON download."""
  866. self.to_screen(u'Downloading json')
  867. def get_urls(self, jsonData, fmt, bitrate='best'):
  868. """Get urls from 'audio_formats' section in json"""
  869. file_url = None
  870. try:
  871. bitrate_list = jsonData[fmt]
  872. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  873. bitrate = max(bitrate_list) # select highest
  874. url_list = jsonData[fmt][bitrate]
  875. except TypeError: # we have no bitrate info.
  876. url_list = jsonData[fmt]
  877. return url_list
  878. def check_urls(self, url_list):
  879. """Returns 1st active url from list"""
  880. for url in url_list:
  881. try:
  882. compat_urllib_request.urlopen(url)
  883. return url
  884. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  885. url = None
  886. return None
  887. def _print_formats(self, formats):
  888. print('Available formats:')
  889. for fmt in formats.keys():
  890. for b in formats[fmt]:
  891. try:
  892. ext = formats[fmt][b][0]
  893. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  894. except TypeError: # we have no bitrate info
  895. ext = formats[fmt][0]
  896. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  897. break
  898. def _real_extract(self, url):
  899. mobj = re.match(self._VALID_URL, url)
  900. if mobj is None:
  901. raise ExtractorError(u'Invalid URL: %s' % url)
  902. # extract uploader & filename from url
  903. uploader = mobj.group(1).decode('utf-8')
  904. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  905. # construct API request
  906. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  907. # retrieve .json file with links to files
  908. request = compat_urllib_request.Request(file_url)
  909. try:
  910. self.report_download_json(file_url)
  911. jsonData = compat_urllib_request.urlopen(request).read()
  912. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  913. raise ExtractorError(u'Unable to retrieve file: %s' % compat_str(err))
  914. # parse JSON
  915. json_data = json.loads(jsonData)
  916. player_url = json_data['player_swf_url']
  917. formats = dict(json_data['audio_formats'])
  918. req_format = self._downloader.params.get('format', None)
  919. bitrate = None
  920. if self._downloader.params.get('listformats', None):
  921. self._print_formats(formats)
  922. return
  923. if req_format is None or req_format == 'best':
  924. for format_param in formats.keys():
  925. url_list = self.get_urls(formats, format_param)
  926. # check urls
  927. file_url = self.check_urls(url_list)
  928. if file_url is not None:
  929. break # got it!
  930. else:
  931. if req_format not in formats:
  932. raise ExtractorError(u'Format is not available')
  933. url_list = self.get_urls(formats, req_format)
  934. file_url = self.check_urls(url_list)
  935. format_param = req_format
  936. return [{
  937. 'id': file_id.decode('utf-8'),
  938. 'url': file_url.decode('utf-8'),
  939. 'uploader': uploader.decode('utf-8'),
  940. 'upload_date': None,
  941. 'title': json_data['name'],
  942. 'ext': file_url.split('.')[-1].decode('utf-8'),
  943. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  944. 'thumbnail': json_data['thumbnail_url'],
  945. 'description': json_data['description'],
  946. 'player_url': player_url.decode('utf-8'),
  947. }]
  948. class StanfordOpenClassroomIE(InfoExtractor):
  949. """Information extractor for Stanford's Open ClassRoom"""
  950. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  951. IE_NAME = u'stanfordoc'
  952. def _real_extract(self, url):
  953. mobj = re.match(self._VALID_URL, url)
  954. if mobj is None:
  955. raise ExtractorError(u'Invalid URL: %s' % url)
  956. if mobj.group('course') and mobj.group('video'): # A specific video
  957. course = mobj.group('course')
  958. video = mobj.group('video')
  959. info = {
  960. 'id': course + '_' + video,
  961. 'uploader': None,
  962. 'upload_date': None,
  963. }
  964. self.report_extraction(info['id'])
  965. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  966. xmlUrl = baseUrl + video + '.xml'
  967. try:
  968. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  969. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  970. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  971. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  972. try:
  973. info['title'] = mdoc.findall('./title')[0].text
  974. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  975. except IndexError:
  976. raise ExtractorError(u'Invalid metadata XML file')
  977. info['ext'] = info['url'].rpartition('.')[2]
  978. return [info]
  979. elif mobj.group('course'): # A course page
  980. course = mobj.group('course')
  981. info = {
  982. 'id': course,
  983. 'type': 'playlist',
  984. 'uploader': None,
  985. 'upload_date': None,
  986. }
  987. coursepage = self._download_webpage(url, info['id'],
  988. note='Downloading course info page',
  989. errnote='Unable to download course info page')
  990. info['title'] = self._html_search_regex('<h1>([^<]+)</h1>', coursepage, 'title', default=info['id'])
  991. info['description'] = self._html_search_regex('<description>([^<]+)</description>',
  992. coursepage, u'description', fatal=False)
  993. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  994. info['list'] = [
  995. {
  996. 'type': 'reference',
  997. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  998. }
  999. for vpage in links]
  1000. results = []
  1001. for entry in info['list']:
  1002. assert entry['type'] == 'reference'
  1003. results += self.extract(entry['url'])
  1004. return results
  1005. else: # Root page
  1006. info = {
  1007. 'id': 'Stanford OpenClassroom',
  1008. 'type': 'playlist',
  1009. 'uploader': None,
  1010. 'upload_date': None,
  1011. }
  1012. self.report_download_webpage(info['id'])
  1013. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  1014. try:
  1015. rootpage = compat_urllib_request.urlopen(rootURL).read()
  1016. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1017. raise ExtractorError(u'Unable to download course info page: ' + compat_str(err))
  1018. info['title'] = info['id']
  1019. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  1020. info['list'] = [
  1021. {
  1022. 'type': 'reference',
  1023. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  1024. }
  1025. for cpage in links]
  1026. results = []
  1027. for entry in info['list']:
  1028. assert entry['type'] == 'reference'
  1029. results += self.extract(entry['url'])
  1030. return results
  1031. class MTVIE(InfoExtractor):
  1032. """Information extractor for MTV.com"""
  1033. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  1034. IE_NAME = u'mtv'
  1035. def _real_extract(self, url):
  1036. mobj = re.match(self._VALID_URL, url)
  1037. if mobj is None:
  1038. raise ExtractorError(u'Invalid URL: %s' % url)
  1039. if not mobj.group('proto'):
  1040. url = 'http://' + url
  1041. video_id = mobj.group('videoid')
  1042. webpage = self._download_webpage(url, video_id)
  1043. song_name = self._html_search_regex(r'<meta name="mtv_vt" content="([^"]+)"/>',
  1044. webpage, u'song name', fatal=False)
  1045. video_title = self._html_search_regex(r'<meta name="mtv_an" content="([^"]+)"/>',
  1046. webpage, u'title')
  1047. mtvn_uri = self._html_search_regex(r'<meta name="mtvn_uri" content="([^"]+)"/>',
  1048. webpage, u'mtvn_uri', fatal=False)
  1049. content_id = self._search_regex(r'MTVN.Player.defaultPlaylistId = ([0-9]+);',
  1050. webpage, u'content id', fatal=False)
  1051. 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
  1052. self.report_extraction(video_id)
  1053. request = compat_urllib_request.Request(videogen_url)
  1054. try:
  1055. metadataXml = compat_urllib_request.urlopen(request).read()
  1056. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1057. raise ExtractorError(u'Unable to download video metadata: %s' % compat_str(err))
  1058. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  1059. renditions = mdoc.findall('.//rendition')
  1060. # For now, always pick the highest quality.
  1061. rendition = renditions[-1]
  1062. try:
  1063. _,_,ext = rendition.attrib['type'].partition('/')
  1064. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  1065. video_url = rendition.find('./src').text
  1066. except KeyError:
  1067. raise ExtractorError('Invalid rendition field.')
  1068. info = {
  1069. 'id': video_id,
  1070. 'url': video_url,
  1071. 'uploader': performer,
  1072. 'upload_date': None,
  1073. 'title': video_title,
  1074. 'ext': ext,
  1075. 'format': format,
  1076. }
  1077. return [info]
  1078. class YoukuIE(InfoExtractor):
  1079. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  1080. def _gen_sid(self):
  1081. nowTime = int(time.time() * 1000)
  1082. random1 = random.randint(1000,1998)
  1083. random2 = random.randint(1000,9999)
  1084. return "%d%d%d" %(nowTime,random1,random2)
  1085. def _get_file_ID_mix_string(self, seed):
  1086. mixed = []
  1087. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  1088. seed = float(seed)
  1089. for i in range(len(source)):
  1090. seed = (seed * 211 + 30031 ) % 65536
  1091. index = math.floor(seed / 65536 * len(source) )
  1092. mixed.append(source[int(index)])
  1093. source.remove(source[int(index)])
  1094. #return ''.join(mixed)
  1095. return mixed
  1096. def _get_file_id(self, fileId, seed):
  1097. mixed = self._get_file_ID_mix_string(seed)
  1098. ids = fileId.split('*')
  1099. realId = []
  1100. for ch in ids:
  1101. if ch:
  1102. realId.append(mixed[int(ch)])
  1103. return ''.join(realId)
  1104. def _real_extract(self, url):
  1105. mobj = re.match(self._VALID_URL, url)
  1106. if mobj is None:
  1107. raise ExtractorError(u'Invalid URL: %s' % url)
  1108. video_id = mobj.group('ID')
  1109. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  1110. jsondata = self._download_webpage(info_url, video_id)
  1111. self.report_extraction(video_id)
  1112. try:
  1113. config = json.loads(jsondata)
  1114. video_title = config['data'][0]['title']
  1115. seed = config['data'][0]['seed']
  1116. format = self._downloader.params.get('format', None)
  1117. supported_format = list(config['data'][0]['streamfileids'].keys())
  1118. if format is None or format == 'best':
  1119. if 'hd2' in supported_format:
  1120. format = 'hd2'
  1121. else:
  1122. format = 'flv'
  1123. ext = u'flv'
  1124. elif format == 'worst':
  1125. format = 'mp4'
  1126. ext = u'mp4'
  1127. else:
  1128. format = 'flv'
  1129. ext = u'flv'
  1130. fileid = config['data'][0]['streamfileids'][format]
  1131. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  1132. except (UnicodeDecodeError, ValueError, KeyError):
  1133. raise ExtractorError(u'Unable to extract info section')
  1134. files_info=[]
  1135. sid = self._gen_sid()
  1136. fileid = self._get_file_id(fileid, seed)
  1137. #column 8,9 of fileid represent the segment number
  1138. #fileid[7:9] should be changed
  1139. for index, key in enumerate(keys):
  1140. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  1141. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  1142. info = {
  1143. 'id': '%s_part%02d' % (video_id, index),
  1144. 'url': download_url,
  1145. 'uploader': None,
  1146. 'upload_date': None,
  1147. 'title': video_title,
  1148. 'ext': ext,
  1149. }
  1150. files_info.append(info)
  1151. return files_info
  1152. class XNXXIE(InfoExtractor):
  1153. """Information extractor for xnxx.com"""
  1154. _VALID_URL = r'^(?:https?://)?video\.xnxx\.com/video([0-9]+)/(.*)'
  1155. IE_NAME = u'xnxx'
  1156. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  1157. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  1158. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  1159. def _real_extract(self, url):
  1160. mobj = re.match(self._VALID_URL, url)
  1161. if mobj is None:
  1162. raise ExtractorError(u'Invalid URL: %s' % url)
  1163. video_id = mobj.group(1)
  1164. # Get webpage content
  1165. webpage = self._download_webpage(url, video_id)
  1166. video_url = self._search_regex(self.VIDEO_URL_RE,
  1167. webpage, u'video URL')
  1168. video_url = compat_urllib_parse.unquote(video_url)
  1169. video_title = self._html_search_regex(self.VIDEO_TITLE_RE,
  1170. webpage, u'title')
  1171. video_thumbnail = self._search_regex(self.VIDEO_THUMB_RE,
  1172. webpage, u'thumbnail', fatal=False)
  1173. return [{
  1174. 'id': video_id,
  1175. 'url': video_url,
  1176. 'uploader': None,
  1177. 'upload_date': None,
  1178. 'title': video_title,
  1179. 'ext': 'flv',
  1180. 'thumbnail': video_thumbnail,
  1181. 'description': None,
  1182. }]
  1183. class GooglePlusIE(InfoExtractor):
  1184. """Information extractor for plus.google.com."""
  1185. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:[^/]+/)*?posts/(\w+)'
  1186. IE_NAME = u'plus.google'
  1187. def _real_extract(self, url):
  1188. # Extract id from URL
  1189. mobj = re.match(self._VALID_URL, url)
  1190. if mobj is None:
  1191. raise ExtractorError(u'Invalid URL: %s' % url)
  1192. post_url = mobj.group(0)
  1193. video_id = mobj.group(1)
  1194. video_extension = 'flv'
  1195. # Step 1, Retrieve post webpage to extract further information
  1196. webpage = self._download_webpage(post_url, video_id, u'Downloading entry webpage')
  1197. self.report_extraction(video_id)
  1198. # Extract update date
  1199. upload_date = self._html_search_regex('title="Timestamp">(.*?)</a>',
  1200. webpage, u'upload date', fatal=False)
  1201. if upload_date:
  1202. # Convert timestring to a format suitable for filename
  1203. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  1204. upload_date = upload_date.strftime('%Y%m%d')
  1205. # Extract uploader
  1206. uploader = self._html_search_regex(r'rel\="author".*?>(.*?)</a>',
  1207. webpage, u'uploader', fatal=False)
  1208. # Extract title
  1209. # Get the first line for title
  1210. video_title = self._html_search_regex(r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]',
  1211. webpage, 'title', default=u'NA')
  1212. # Step 2, Stimulate clicking the image box to launch video
  1213. video_page = self._search_regex('"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]',
  1214. webpage, u'video page URL')
  1215. webpage = self._download_webpage(video_page, video_id, u'Downloading video page')
  1216. # Extract video links on video page
  1217. """Extract video links of all sizes"""
  1218. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  1219. mobj = re.findall(pattern, webpage)
  1220. if len(mobj) == 0:
  1221. raise ExtractorError(u'Unable to extract video links')
  1222. # Sort in resolution
  1223. links = sorted(mobj)
  1224. # Choose the lowest of the sort, i.e. highest resolution
  1225. video_url = links[-1]
  1226. # Only get the url. The resolution part in the tuple has no use anymore
  1227. video_url = video_url[-1]
  1228. # Treat escaped \u0026 style hex
  1229. try:
  1230. video_url = video_url.decode("unicode_escape")
  1231. except AttributeError: # Python 3
  1232. video_url = bytes(video_url, 'ascii').decode('unicode-escape')
  1233. return [{
  1234. 'id': video_id,
  1235. 'url': video_url,
  1236. 'uploader': uploader,
  1237. 'upload_date': upload_date,
  1238. 'title': video_title,
  1239. 'ext': video_extension,
  1240. }]
  1241. class NBAIE(InfoExtractor):
  1242. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*?)(?:/index\.html)?(?:\?.*)?$'
  1243. IE_NAME = u'nba'
  1244. def _real_extract(self, url):
  1245. mobj = re.match(self._VALID_URL, url)
  1246. if mobj is None:
  1247. raise ExtractorError(u'Invalid URL: %s' % url)
  1248. video_id = mobj.group(1)
  1249. webpage = self._download_webpage(url, video_id)
  1250. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  1251. shortened_video_id = video_id.rpartition('/')[2]
  1252. title = self._html_search_regex(r'<meta property="og:title" content="(.*?)"',
  1253. webpage, 'title', default=shortened_video_id).replace('NBA.com: ', '')
  1254. # It isn't there in the HTML it returns to us
  1255. # uploader_date = self._html_search_regex(r'<b>Date:</b> (.*?)</div>', webpage, 'upload_date', fatal=False)
  1256. description = self._html_search_regex(r'<meta name="description" (?:content|value)="(.*?)" />', webpage, 'description', fatal=False)
  1257. info = {
  1258. 'id': shortened_video_id,
  1259. 'url': video_url,
  1260. 'ext': 'mp4',
  1261. 'title': title,
  1262. # 'uploader_date': uploader_date,
  1263. 'description': description,
  1264. }
  1265. return [info]
  1266. class JustinTVIE(InfoExtractor):
  1267. """Information extractor for justin.tv and twitch.tv"""
  1268. # TODO: One broadcast may be split into multiple videos. The key
  1269. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  1270. # starts at 1 and increases. Can we treat all parts as one video?
  1271. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  1272. (?:
  1273. (?P<channelid>[^/]+)|
  1274. (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
  1275. (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
  1276. )
  1277. /?(?:\#.*)?$
  1278. """
  1279. _JUSTIN_PAGE_LIMIT = 100
  1280. IE_NAME = u'justin.tv'
  1281. def report_download_page(self, channel, offset):
  1282. """Report attempt to download a single page of videos."""
  1283. self.to_screen(u'%s: Downloading video information from %d to %d' %
  1284. (channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  1285. # Return count of items, list of *valid* items
  1286. def _parse_page(self, url, video_id):
  1287. webpage = self._download_webpage(url, video_id,
  1288. u'Downloading video info JSON',
  1289. u'unable to download video info JSON')
  1290. response = json.loads(webpage)
  1291. if type(response) != list:
  1292. error_text = response.get('error', 'unknown error')
  1293. raise ExtractorError(u'Justin.tv API: %s' % error_text)
  1294. info = []
  1295. for clip in response:
  1296. video_url = clip['video_file_url']
  1297. if video_url:
  1298. video_extension = os.path.splitext(video_url)[1][1:]
  1299. video_date = re.sub('-', '', clip['start_time'][:10])
  1300. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  1301. video_id = clip['id']
  1302. video_title = clip.get('title', video_id)
  1303. info.append({
  1304. 'id': video_id,
  1305. 'url': video_url,
  1306. 'title': video_title,
  1307. 'uploader': clip.get('channel_name', video_uploader_id),
  1308. 'uploader_id': video_uploader_id,
  1309. 'upload_date': video_date,
  1310. 'ext': video_extension,
  1311. })
  1312. return (len(response), info)
  1313. def _real_extract(self, url):
  1314. mobj = re.match(self._VALID_URL, url)
  1315. if mobj is None:
  1316. raise ExtractorError(u'invalid URL: %s' % url)
  1317. api_base = 'http://api.justin.tv'
  1318. paged = False
  1319. if mobj.group('channelid'):
  1320. paged = True
  1321. video_id = mobj.group('channelid')
  1322. api = api_base + '/channel/archives/%s.json' % video_id
  1323. elif mobj.group('chapterid'):
  1324. chapter_id = mobj.group('chapterid')
  1325. webpage = self._download_webpage(url, chapter_id)
  1326. m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
  1327. if not m:
  1328. raise ExtractorError(u'Cannot find archive of a chapter')
  1329. archive_id = m.group(1)
  1330. api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
  1331. chapter_info_xml = self._download_webpage(api, chapter_id,
  1332. note=u'Downloading chapter information',
  1333. errnote=u'Chapter information download failed')
  1334. doc = xml.etree.ElementTree.fromstring(chapter_info_xml)
  1335. for a in doc.findall('.//archive'):
  1336. if archive_id == a.find('./id').text:
  1337. break
  1338. else:
  1339. raise ExtractorError(u'Could not find chapter in chapter information')
  1340. video_url = a.find('./video_file_url').text
  1341. video_ext = video_url.rpartition('.')[2] or u'flv'
  1342. chapter_api_url = u'https://api.twitch.tv/kraken/videos/c' + chapter_id
  1343. chapter_info_json = self._download_webpage(chapter_api_url, u'c' + chapter_id,
  1344. note='Downloading chapter metadata',
  1345. errnote='Download of chapter metadata failed')
  1346. chapter_info = json.loads(chapter_info_json)
  1347. bracket_start = int(doc.find('.//bracket_start').text)
  1348. bracket_end = int(doc.find('.//bracket_end').text)
  1349. # TODO determine start (and probably fix up file)
  1350. # youtube-dl -v http://www.twitch.tv/firmbelief/c/1757457
  1351. #video_url += u'?start=' + TODO:start_timestamp
  1352. # bracket_start is 13290, but we want 51670615
  1353. self._downloader.report_warning(u'Chapter detected, but we can just download the whole file. '
  1354. u'Chapter starts at %s and ends at %s' % (formatSeconds(bracket_start), formatSeconds(bracket_end)))
  1355. info = {
  1356. 'id': u'c' + chapter_id,
  1357. 'url': video_url,
  1358. 'ext': video_ext,
  1359. 'title': chapter_info['title'],
  1360. 'thumbnail': chapter_info['preview'],
  1361. 'description': chapter_info['description'],
  1362. 'uploader': chapter_info['channel']['display_name'],
  1363. 'uploader_id': chapter_info['channel']['name'],
  1364. }
  1365. return [info]
  1366. else:
  1367. video_id = mobj.group('videoid')
  1368. api = api_base + '/broadcast/by_archive/%s.json' % video_id
  1369. self.report_extraction(video_id)
  1370. info = []
  1371. offset = 0
  1372. limit = self._JUSTIN_PAGE_LIMIT
  1373. while True:
  1374. if paged:
  1375. self.report_download_page(video_id, offset)
  1376. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  1377. page_count, page_info = self._parse_page(page_url, video_id)
  1378. info.extend(page_info)
  1379. if not paged or page_count != limit:
  1380. break
  1381. offset += limit
  1382. return info
  1383. class FunnyOrDieIE(InfoExtractor):
  1384. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  1385. def _real_extract(self, url):
  1386. mobj = re.match(self._VALID_URL, url)
  1387. if mobj is None:
  1388. raise ExtractorError(u'invalid URL: %s' % url)
  1389. video_id = mobj.group('id')
  1390. webpage = self._download_webpage(url, video_id)
  1391. video_url = self._html_search_regex(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"',
  1392. webpage, u'video URL', flags=re.DOTALL)
  1393. title = self._html_search_regex((r"<h1 class='player_page_h1'.*?>(?P<title>.*?)</h1>",
  1394. r'<title>(?P<title>[^<]+?)</title>'), webpage, 'title', flags=re.DOTALL)
  1395. video_description = self._html_search_regex(r'<meta property="og:description" content="(?P<desc>.*?)"',
  1396. webpage, u'description', fatal=False, flags=re.DOTALL)
  1397. info = {
  1398. 'id': video_id,
  1399. 'url': video_url,
  1400. 'ext': 'mp4',
  1401. 'title': title,
  1402. 'description': video_description,
  1403. }
  1404. return [info]
  1405. class SteamIE(InfoExtractor):
  1406. _VALID_URL = r"""http://store\.steampowered\.com/
  1407. (agecheck/)?
  1408. (?P<urltype>video|app)/ #If the page is only for videos or for a game
  1409. (?P<gameID>\d+)/?
  1410. (?P<videoID>\d*)(?P<extra>\??) #For urltype == video we sometimes get the videoID
  1411. """
  1412. _VIDEO_PAGE_TEMPLATE = 'http://store.steampowered.com/video/%s/'
  1413. _AGECHECK_TEMPLATE = 'http://store.steampowered.com/agecheck/video/%s/?snr=1_agecheck_agecheck__age-gate&ageDay=1&ageMonth=January&ageYear=1970'
  1414. @classmethod
  1415. def suitable(cls, url):
  1416. """Receives a URL and returns True if suitable for this IE."""
  1417. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1418. def _real_extract(self, url):
  1419. m = re.match(self._VALID_URL, url, re.VERBOSE)
  1420. gameID = m.group('gameID')
  1421. videourl = self._VIDEO_PAGE_TEMPLATE % gameID
  1422. webpage = self._download_webpage(videourl, gameID)
  1423. if re.search('<h2>Please enter your birth date to continue:</h2>', webpage) is not None:
  1424. videourl = self._AGECHECK_TEMPLATE % gameID
  1425. self.report_age_confirmation()
  1426. webpage = self._download_webpage(videourl, gameID)
  1427. self.report_extraction(gameID)
  1428. game_title = self._html_search_regex(r'<h2 class="pageheader">(.*?)</h2>',
  1429. webpage, 'game title')
  1430. urlRE = r"'movie_(?P<videoID>\d+)': \{\s*FILENAME: \"(?P<videoURL>[\w:/\.\?=]+)\"(,\s*MOVIE_NAME: \"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\},"
  1431. mweb = re.finditer(urlRE, webpage)
  1432. namesRE = r'<span class="title">(?P<videoName>.+?)</span>'
  1433. titles = re.finditer(namesRE, webpage)
  1434. thumbsRE = r'<img class="movie_thumb" src="(?P<thumbnail>.+?)">'
  1435. thumbs = re.finditer(thumbsRE, webpage)
  1436. videos = []
  1437. for vid,vtitle,thumb in zip(mweb,titles,thumbs):
  1438. video_id = vid.group('videoID')
  1439. title = vtitle.group('videoName')
  1440. video_url = vid.group('videoURL')
  1441. video_thumb = thumb.group('thumbnail')
  1442. if not video_url:
  1443. raise ExtractorError(u'Cannot find video url for %s' % video_id)
  1444. info = {
  1445. 'id':video_id,
  1446. 'url':video_url,
  1447. 'ext': 'flv',
  1448. 'title': unescapeHTML(title),
  1449. 'thumbnail': video_thumb
  1450. }
  1451. videos.append(info)
  1452. return [self.playlist_result(videos, gameID, game_title)]
  1453. class UstreamIE(InfoExtractor):
  1454. _VALID_URL = r'https?://www\.ustream\.tv/recorded/(?P<videoID>\d+)'
  1455. IE_NAME = u'ustream'
  1456. def _real_extract(self, url):
  1457. m = re.match(self._VALID_URL, url)
  1458. video_id = m.group('videoID')
  1459. video_url = u'http://tcdn.ustream.tv/video/%s' % video_id
  1460. webpage = self._download_webpage(url, video_id)
  1461. self.report_extraction(video_id)
  1462. video_title = self._html_search_regex(r'data-title="(?P<title>.+)"',
  1463. webpage, u'title')
  1464. uploader = self._html_search_regex(r'data-content-type="channel".*?>(?P<uploader>.*?)</a>',
  1465. webpage, u'uploader', fatal=False, flags=re.DOTALL)
  1466. thumbnail = self._html_search_regex(r'<link rel="image_src" href="(?P<thumb>.*?)"',
  1467. webpage, u'thumbnail', fatal=False)
  1468. info = {
  1469. 'id': video_id,
  1470. 'url': video_url,
  1471. 'ext': 'flv',
  1472. 'title': video_title,
  1473. 'uploader': uploader,
  1474. 'thumbnail': thumbnail,
  1475. }
  1476. return info
  1477. class WorldStarHipHopIE(InfoExtractor):
  1478. _VALID_URL = r'https?://(?:www|m)\.worldstar(?:candy|hiphop)\.com/videos/video\.php\?v=(?P<id>.*)'
  1479. IE_NAME = u'WorldStarHipHop'
  1480. def _real_extract(self, url):
  1481. m = re.match(self._VALID_URL, url)
  1482. video_id = m.group('id')
  1483. webpage_src = self._download_webpage(url, video_id)
  1484. video_url = self._search_regex(r'so\.addVariable\("file","(.*?)"\)',
  1485. webpage_src, u'video URL')
  1486. if 'mp4' in video_url:
  1487. ext = 'mp4'
  1488. else:
  1489. ext = 'flv'
  1490. video_title = self._html_search_regex(r"<title>(.*)</title>",
  1491. webpage_src, u'title')
  1492. # Getting thumbnail and if not thumbnail sets correct title for WSHH candy video.
  1493. thumbnail = self._html_search_regex(r'rel="image_src" href="(.*)" />',
  1494. webpage_src, u'thumbnail', fatal=False)
  1495. if not thumbnail:
  1496. _title = r"""candytitles.*>(.*)</span>"""
  1497. mobj = re.search(_title, webpage_src)
  1498. if mobj is not None:
  1499. video_title = mobj.group(1)
  1500. results = [{
  1501. 'id': video_id,
  1502. 'url' : video_url,
  1503. 'title' : video_title,
  1504. 'thumbnail' : thumbnail,
  1505. 'ext' : ext,
  1506. }]
  1507. return results
  1508. class RBMARadioIE(InfoExtractor):
  1509. _VALID_URL = r'https?://(?:www\.)?rbmaradio\.com/shows/(?P<videoID>[^/]+)$'
  1510. def _real_extract(self, url):
  1511. m = re.match(self._VALID_URL, url)
  1512. video_id = m.group('videoID')
  1513. webpage = self._download_webpage(url, video_id)
  1514. json_data = self._search_regex(r'window\.gon.*?gon\.show=(.+?);$',
  1515. webpage, u'json data', flags=re.MULTILINE)
  1516. try:
  1517. data = json.loads(json_data)
  1518. except ValueError as e:
  1519. raise ExtractorError(u'Invalid JSON: ' + str(e))
  1520. video_url = data['akamai_url'] + '&cbr=256'
  1521. url_parts = compat_urllib_parse_urlparse(video_url)
  1522. video_ext = url_parts.path.rpartition('.')[2]
  1523. info = {
  1524. 'id': video_id,
  1525. 'url': video_url,
  1526. 'ext': video_ext,
  1527. 'title': data['title'],
  1528. 'description': data.get('teaser_text'),
  1529. 'location': data.get('country_of_origin'),
  1530. 'uploader': data.get('host', {}).get('name'),
  1531. 'uploader_id': data.get('host', {}).get('slug'),
  1532. 'thumbnail': data.get('image', {}).get('large_url_2x'),
  1533. 'duration': data.get('duration'),
  1534. }
  1535. return [info]
  1536. class YouPornIE(InfoExtractor):
  1537. """Information extractor for youporn.com."""
  1538. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
  1539. def _print_formats(self, formats):
  1540. """Print all available formats"""
  1541. print(u'Available formats:')
  1542. print(u'ext\t\tformat')
  1543. print(u'---------------------------------')
  1544. for format in formats:
  1545. print(u'%s\t\t%s' % (format['ext'], format['format']))
  1546. def _specific(self, req_format, formats):
  1547. for x in formats:
  1548. if(x["format"]==req_format):
  1549. return x
  1550. return None
  1551. def _real_extract(self, url):
  1552. mobj = re.match(self._VALID_URL, url)
  1553. if mobj is None:
  1554. raise ExtractorError(u'Invalid URL: %s' % url)
  1555. video_id = mobj.group('videoid')
  1556. req = compat_urllib_request.Request(url)
  1557. req.add_header('Cookie', 'age_verified=1')
  1558. webpage = self._download_webpage(req, video_id)
  1559. # Get JSON parameters
  1560. json_params = self._search_regex(r'var currentVideo = new Video\((.*)\);', webpage, u'JSON parameters')
  1561. try:
  1562. params = json.loads(json_params)
  1563. except:
  1564. raise ExtractorError(u'Invalid JSON')
  1565. self.report_extraction(video_id)
  1566. try:
  1567. video_title = params['title']
  1568. upload_date = unified_strdate(params['release_date_f'])
  1569. video_description = params['description']
  1570. video_uploader = params['submitted_by']
  1571. thumbnail = params['thumbnails'][0]['image']
  1572. except KeyError:
  1573. raise ExtractorError('Missing JSON parameter: ' + sys.exc_info()[1])
  1574. # Get all of the formats available
  1575. DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
  1576. download_list_html = self._search_regex(DOWNLOAD_LIST_RE,
  1577. webpage, u'download list').strip()
  1578. # Get all of the links from the page
  1579. LINK_RE = r'(?s)<a href="(?P<url>[^"]+)">'
  1580. links = re.findall(LINK_RE, download_list_html)
  1581. if(len(links) == 0):
  1582. raise ExtractorError(u'ERROR: no known formats available for video')
  1583. self.to_screen(u'Links found: %d' % len(links))
  1584. formats = []
  1585. for link in links:
  1586. # A link looks like this:
  1587. # 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
  1588. # A path looks like this:
  1589. # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
  1590. video_url = unescapeHTML( link )
  1591. path = compat_urllib_parse_urlparse( video_url ).path
  1592. extension = os.path.splitext( path )[1][1:]
  1593. format = path.split('/')[4].split('_')[:2]
  1594. size = format[0]
  1595. bitrate = format[1]
  1596. format = "-".join( format )
  1597. # title = u'%s-%s-%s' % (video_title, size, bitrate)
  1598. formats.append({
  1599. 'id': video_id,
  1600. 'url': video_url,
  1601. 'uploader': video_uploader,
  1602. 'upload_date': upload_date,
  1603. 'title': video_title,
  1604. 'ext': extension,
  1605. 'format': format,
  1606. 'thumbnail': thumbnail,
  1607. 'description': video_description
  1608. })
  1609. if self._downloader.params.get('listformats', None):
  1610. self._print_formats(formats)
  1611. return
  1612. req_format = self._downloader.params.get('format', None)
  1613. self.to_screen(u'Format: %s' % req_format)
  1614. if req_format is None or req_format == 'best':
  1615. return [formats[0]]
  1616. elif req_format == 'worst':
  1617. return [formats[-1]]
  1618. elif req_format in ('-1', 'all'):
  1619. return formats
  1620. else:
  1621. format = self._specific( req_format, formats )
  1622. if result is None:
  1623. raise ExtractorError(u'Requested format not available')
  1624. return [format]
  1625. class PornotubeIE(InfoExtractor):
  1626. """Information extractor for pornotube.com."""
  1627. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?pornotube\.com(/c/(?P<channel>[0-9]+))?(/m/(?P<videoid>[0-9]+))(/(?P<title>.+))$'
  1628. def _real_extract(self, url):
  1629. mobj = re.match(self._VALID_URL, url)
  1630. if mobj is None:
  1631. raise ExtractorError(u'Invalid URL: %s' % url)
  1632. video_id = mobj.group('videoid')
  1633. video_title = mobj.group('title')
  1634. # Get webpage content
  1635. webpage = self._download_webpage(url, video_id)
  1636. # Get the video URL
  1637. VIDEO_URL_RE = r'url: "(?P<url>http://video[0-9].pornotube.com/.+\.flv)",'
  1638. video_url = self._search_regex(VIDEO_URL_RE, webpage, u'video url')
  1639. video_url = compat_urllib_parse.unquote(video_url)
  1640. #Get the uploaded date
  1641. VIDEO_UPLOADED_RE = r'<div class="video_added_by">Added (?P<date>[0-9\/]+) by'
  1642. upload_date = self._html_search_regex(VIDEO_UPLOADED_RE, webpage, u'upload date', fatal=False)
  1643. if upload_date: upload_date = unified_strdate(upload_date)
  1644. info = {'id': video_id,
  1645. 'url': video_url,
  1646. 'uploader': None,
  1647. 'upload_date': upload_date,
  1648. 'title': video_title,
  1649. 'ext': 'flv',
  1650. 'format': 'flv'}
  1651. return [info]
  1652. class YouJizzIE(InfoExtractor):
  1653. """Information extractor for youjizz.com."""
  1654. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youjizz\.com/videos/(?P<videoid>[^.]+).html$'
  1655. def _real_extract(self, url):
  1656. mobj = re.match(self._VALID_URL, url)
  1657. if mobj is None:
  1658. raise ExtractorError(u'Invalid URL: %s' % url)
  1659. video_id = mobj.group('videoid')
  1660. # Get webpage content
  1661. webpage = self._download_webpage(url, video_id)
  1662. # Get the video title
  1663. video_title = self._html_search_regex(r'<title>(?P<title>.*)</title>',
  1664. webpage, u'title').strip()
  1665. # Get the embed page
  1666. result = re.search(r'https?://www.youjizz.com/videos/embed/(?P<videoid>[0-9]+)', webpage)
  1667. if result is None:
  1668. raise ExtractorError(u'ERROR: unable to extract embed page')
  1669. embed_page_url = result.group(0).strip()
  1670. video_id = result.group('videoid')
  1671. webpage = self._download_webpage(embed_page_url, video_id)
  1672. # Get the video URL
  1673. video_url = self._search_regex(r'so.addVariable\("file",encodeURIComponent\("(?P<source>[^"]+)"\)\);',
  1674. webpage, u'video URL')
  1675. info = {'id': video_id,
  1676. 'url': video_url,
  1677. 'title': video_title,
  1678. 'ext': 'flv',
  1679. 'format': 'flv',
  1680. 'player_url': embed_page_url}
  1681. return [info]
  1682. class EightTracksIE(InfoExtractor):
  1683. IE_NAME = '8tracks'
  1684. _VALID_URL = r'https?://8tracks.com/(?P<user>[^/]+)/(?P<id>[^/#]+)(?:#.*)?$'
  1685. def _real_extract(self, url):
  1686. mobj = re.match(self._VALID_URL, url)
  1687. if mobj is None:
  1688. raise ExtractorError(u'Invalid URL: %s' % url)
  1689. playlist_id = mobj.group('id')
  1690. webpage = self._download_webpage(url, playlist_id)
  1691. json_like = self._search_regex(r"PAGE.mix = (.*?);\n", webpage, u'trax information', flags=re.DOTALL)
  1692. data = json.loads(json_like)
  1693. session = str(random.randint(0, 1000000000))
  1694. mix_id = data['id']
  1695. track_count = data['tracks_count']
  1696. first_url = 'http://8tracks.com/sets/%s/play?player=sm&mix_id=%s&format=jsonh' % (session, mix_id)
  1697. next_url = first_url
  1698. res = []
  1699. for i in itertools.count():
  1700. api_json = self._download_webpage(next_url, playlist_id,
  1701. note=u'Downloading song information %s/%s' % (str(i+1), track_count),
  1702. errnote=u'Failed to download song information')
  1703. api_data = json.loads(api_json)
  1704. track_data = api_data[u'set']['track']
  1705. info = {
  1706. 'id': track_data['id'],
  1707. 'url': track_data['track_file_stream_url'],
  1708. 'title': track_data['performer'] + u' - ' + track_data['name'],
  1709. 'raw_title': track_data['name'],
  1710. 'uploader_id': data['user']['login'],
  1711. 'ext': 'm4a',
  1712. }
  1713. res.append(info)
  1714. if api_data['set']['at_last_track']:
  1715. break
  1716. next_url = 'http://8tracks.com/sets/%s/next?player=sm&mix_id=%s&format=jsonh&track_id=%s' % (session, mix_id, track_data['id'])
  1717. return res
  1718. class KeekIE(InfoExtractor):
  1719. _VALID_URL = r'http://(?:www\.)?keek\.com/(?:!|\w+/keeks/)(?P<videoID>\w+)'
  1720. IE_NAME = u'keek'
  1721. def _real_extract(self, url):
  1722. m = re.match(self._VALID_URL, url)
  1723. video_id = m.group('videoID')
  1724. video_url = u'http://cdn.keek.com/keek/video/%s' % video_id
  1725. thumbnail = u'http://cdn.keek.com/keek/thumbnail/%s/w100/h75' % video_id
  1726. webpage = self._download_webpage(url, video_id)
  1727. video_title = self._html_search_regex(r'<meta property="og:title" content="(?P<title>.*?)"',
  1728. webpage, u'title')
  1729. uploader = self._html_search_regex(r'<div class="user-name-and-bio">[\S\s]+?<h2>(?P<uploader>.+?)</h2>',
  1730. webpage, u'uploader', fatal=False)
  1731. info = {
  1732. 'id': video_id,
  1733. 'url': video_url,
  1734. 'ext': 'mp4',
  1735. 'title': video_title,
  1736. 'thumbnail': thumbnail,
  1737. 'uploader': uploader
  1738. }
  1739. return [info]
  1740. class TEDIE(InfoExtractor):
  1741. _VALID_URL=r'''http://www\.ted\.com/
  1742. (
  1743. ((?P<type_playlist>playlists)/(?P<playlist_id>\d+)) # We have a playlist
  1744. |
  1745. ((?P<type_talk>talks)) # We have a simple talk
  1746. )
  1747. (/lang/(.*?))? # The url may contain the language
  1748. /(?P<name>\w+) # Here goes the name and then ".html"
  1749. '''
  1750. @classmethod
  1751. def suitable(cls, url):
  1752. """Receives a URL and returns True if suitable for this IE."""
  1753. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1754. def _real_extract(self, url):
  1755. m=re.match(self._VALID_URL, url, re.VERBOSE)
  1756. if m.group('type_talk'):
  1757. return [self._talk_info(url)]
  1758. else :
  1759. playlist_id=m.group('playlist_id')
  1760. name=m.group('name')
  1761. self.to_screen(u'Getting info of playlist %s: "%s"' % (playlist_id,name))
  1762. return [self._playlist_videos_info(url,name,playlist_id)]
  1763. def _playlist_videos_info(self,url,name,playlist_id=0):
  1764. '''Returns the videos of the playlist'''
  1765. video_RE=r'''
  1766. <li\ id="talk_(\d+)"([.\s]*?)data-id="(?P<video_id>\d+)"
  1767. ([.\s]*?)data-playlist_item_id="(\d+)"
  1768. ([.\s]*?)data-mediaslug="(?P<mediaSlug>.+?)"
  1769. '''
  1770. video_name_RE=r'<p\ class="talk-title"><a href="(?P<talk_url>/talks/(.+).html)">(?P<fullname>.+?)</a></p>'
  1771. webpage=self._download_webpage(url, playlist_id, 'Downloading playlist webpage')
  1772. m_videos=re.finditer(video_RE,webpage,re.VERBOSE)
  1773. m_names=re.finditer(video_name_RE,webpage)
  1774. playlist_title = self._html_search_regex(r'div class="headline">\s*?<h1>\s*?<span>(.*?)</span>',
  1775. webpage, 'playlist title')
  1776. playlist_entries = []
  1777. for m_video, m_name in zip(m_videos,m_names):
  1778. video_id=m_video.group('video_id')
  1779. talk_url='http://www.ted.com%s' % m_name.group('talk_url')
  1780. playlist_entries.append(self.url_result(talk_url, 'TED'))
  1781. return self.playlist_result(playlist_entries, playlist_id = playlist_id, playlist_title = playlist_title)
  1782. def _talk_info(self, url, video_id=0):
  1783. """Return the video for the talk in the url"""
  1784. m = re.match(self._VALID_URL, url,re.VERBOSE)
  1785. video_name = m.group('name')
  1786. webpage = self._download_webpage(url, video_id, 'Downloading \"%s\" page' % video_name)
  1787. self.report_extraction(video_name)
  1788. # If the url includes the language we get the title translated
  1789. title = self._html_search_regex(r'<span id="altHeadline" >(?P<title>.*)</span>',
  1790. webpage, 'title')
  1791. json_data = self._search_regex(r'<script.*?>var talkDetails = ({.*?})</script>',
  1792. webpage, 'json data')
  1793. info = json.loads(json_data)
  1794. desc = self._html_search_regex(r'<div class="talk-intro">.*?<p.*?>(.*?)</p>',
  1795. webpage, 'description', flags = re.DOTALL)
  1796. thumbnail = self._search_regex(r'</span>[\s.]*</div>[\s.]*<img src="(.*?)"',
  1797. webpage, 'thumbnail')
  1798. info = {
  1799. 'id': info['id'],
  1800. 'url': info['htmlStreams'][-1]['file'],
  1801. 'ext': 'mp4',
  1802. 'title': title,
  1803. 'thumbnail': thumbnail,
  1804. 'description': desc,
  1805. }
  1806. return info
  1807. class MySpassIE(InfoExtractor):
  1808. _VALID_URL = r'http://www.myspass.de/.*'
  1809. def _real_extract(self, url):
  1810. META_DATA_URL_TEMPLATE = 'http://www.myspass.de/myspass/includes/apps/video/getvideometadataxml.php?id=%s'
  1811. # video id is the last path element of the URL
  1812. # usually there is a trailing slash, so also try the second but last
  1813. url_path = compat_urllib_parse_urlparse(url).path
  1814. url_parent_path, video_id = os.path.split(url_path)
  1815. if not video_id:
  1816. _, video_id = os.path.split(url_parent_path)
  1817. # get metadata
  1818. metadata_url = META_DATA_URL_TEMPLATE % video_id
  1819. metadata_text = self._download_webpage(metadata_url, video_id)
  1820. metadata = xml.etree.ElementTree.fromstring(metadata_text.encode('utf-8'))
  1821. # extract values from metadata
  1822. url_flv_el = metadata.find('url_flv')
  1823. if url_flv_el is None:
  1824. raise ExtractorError(u'Unable to extract download url')
  1825. video_url = url_flv_el.text
  1826. extension = os.path.splitext(video_url)[1][1:]
  1827. title_el = metadata.find('title')
  1828. if title_el is None:
  1829. raise ExtractorError(u'Unable to extract title')
  1830. title = title_el.text
  1831. format_id_el = metadata.find('format_id')
  1832. if format_id_el is None:
  1833. format = ext
  1834. else:
  1835. format = format_id_el.text
  1836. description_el = metadata.find('description')
  1837. if description_el is not None:
  1838. description = description_el.text
  1839. else:
  1840. description = None
  1841. imagePreview_el = metadata.find('imagePreview')
  1842. if imagePreview_el is not None:
  1843. thumbnail = imagePreview_el.text
  1844. else:
  1845. thumbnail = None
  1846. info = {
  1847. 'id': video_id,
  1848. 'url': video_url,
  1849. 'title': title,
  1850. 'ext': extension,
  1851. 'format': format,
  1852. 'thumbnail': thumbnail,
  1853. 'description': description
  1854. }
  1855. return [info]
  1856. class SpiegelIE(InfoExtractor):
  1857. _VALID_URL = r'https?://(?:www\.)?spiegel\.de/video/[^/]*-(?P<videoID>[0-9]+)(?:\.html)?(?:#.*)?$'
  1858. def _real_extract(self, url):
  1859. m = re.match(self._VALID_URL, url)
  1860. video_id = m.group('videoID')
  1861. webpage = self._download_webpage(url, video_id)
  1862. video_title = self._html_search_regex(r'<div class="module-title">(.*?)</div>',
  1863. webpage, u'title')
  1864. xml_url = u'http://video2.spiegel.de/flash/' + video_id + u'.xml'
  1865. xml_code = self._download_webpage(xml_url, video_id,
  1866. note=u'Downloading XML', errnote=u'Failed to download XML')
  1867. idoc = xml.etree.ElementTree.fromstring(xml_code)
  1868. last_type = idoc[-1]
  1869. filename = last_type.findall('./filename')[0].text
  1870. duration = float(last_type.findall('./duration')[0].text)
  1871. video_url = 'http://video2.spiegel.de/flash/' + filename
  1872. video_ext = filename.rpartition('.')[2]
  1873. info = {
  1874. 'id': video_id,
  1875. 'url': video_url,
  1876. 'ext': video_ext,
  1877. 'title': video_title,
  1878. 'duration': duration,
  1879. }
  1880. return [info]
  1881. class LiveLeakIE(InfoExtractor):
  1882. _VALID_URL = r'^(?:http?://)?(?:\w+\.)?liveleak\.com/view\?(?:.*?)i=(?P<video_id>[\w_]+)(?:.*)'
  1883. IE_NAME = u'liveleak'
  1884. def _real_extract(self, url):
  1885. mobj = re.match(self._VALID_URL, url)
  1886. if mobj is None:
  1887. raise ExtractorError(u'Invalid URL: %s' % url)
  1888. video_id = mobj.group('video_id')
  1889. webpage = self._download_webpage(url, video_id)
  1890. video_url = self._search_regex(r'file: "(.*?)",',
  1891. webpage, u'video URL')
  1892. video_title = self._html_search_regex(r'<meta property="og:title" content="(?P<title>.*?)"',
  1893. webpage, u'title').replace('LiveLeak.com -', '').strip()
  1894. video_description = self._html_search_regex(r'<meta property="og:description" content="(?P<desc>.*?)"',
  1895. webpage, u'description', fatal=False)
  1896. video_uploader = self._html_search_regex(r'By:.*?(\w+)</a>',
  1897. webpage, u'uploader', fatal=False)
  1898. info = {
  1899. 'id': video_id,
  1900. 'url': video_url,
  1901. 'ext': 'mp4',
  1902. 'title': video_title,
  1903. 'description': video_description,
  1904. 'uploader': video_uploader
  1905. }
  1906. return [info]
  1907. class TumblrIE(InfoExtractor):
  1908. _VALID_URL = r'http://(?P<blog_name>.*?)\.tumblr\.com/((post)|(video))/(?P<id>\d*)/(.*?)'
  1909. def _real_extract(self, url):
  1910. m_url = re.match(self._VALID_URL, url)
  1911. video_id = m_url.group('id')
  1912. blog = m_url.group('blog_name')
  1913. url = 'http://%s.tumblr.com/post/%s/' % (blog, video_id)
  1914. webpage = self._download_webpage(url, video_id)
  1915. re_video = r'src=\\x22(?P<video_url>http://%s\.tumblr\.com/video_file/%s/(.*?))\\x22 type=\\x22video/(?P<ext>.*?)\\x22' % (blog, video_id)
  1916. video = re.search(re_video, webpage)
  1917. if video is None:
  1918. raise ExtractorError(u'Unable to extract video')
  1919. video_url = video.group('video_url')
  1920. ext = video.group('ext')
  1921. video_thumbnail = self._search_regex(r'posters(.*?)\[\\x22(?P<thumb>.*?)\\x22',
  1922. webpage, u'thumbnail', fatal=False) # We pick the first poster
  1923. if video_thumbnail: video_thumbnail = video_thumbnail.replace('\\', '')
  1924. # The only place where you can get a title, it's not complete,
  1925. # but searching in other places doesn't work for all videos
  1926. video_title = self._html_search_regex(r'<title>(?P<title>.*?)</title>',
  1927. webpage, u'title', flags=re.DOTALL)
  1928. return [{'id': video_id,
  1929. 'url': video_url,
  1930. 'title': video_title,
  1931. 'thumbnail': video_thumbnail,
  1932. 'ext': ext
  1933. }]
  1934. class BandcampIE(InfoExtractor):
  1935. _VALID_URL = r'http://.*?\.bandcamp\.com/track/(?P<title>.*)'
  1936. def _real_extract(self, url):
  1937. mobj = re.match(self._VALID_URL, url)
  1938. title = mobj.group('title')
  1939. webpage = self._download_webpage(url, title)
  1940. # We get the link to the free download page
  1941. m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
  1942. if m_download is None:
  1943. raise ExtractorError(u'No free songs found')
  1944. download_link = m_download.group(1)
  1945. id = re.search(r'var TralbumData = {(.*?)id: (?P<id>\d*?)$',
  1946. webpage, re.MULTILINE|re.DOTALL).group('id')
  1947. download_webpage = self._download_webpage(download_link, id,
  1948. 'Downloading free downloads page')
  1949. # We get the dictionary of the track from some javascrip code
  1950. info = re.search(r'items: (.*?),$',
  1951. download_webpage, re.MULTILINE).group(1)
  1952. info = json.loads(info)[0]
  1953. # We pick mp3-320 for now, until format selection can be easily implemented.
  1954. mp3_info = info[u'downloads'][u'mp3-320']
  1955. # If we try to use this url it says the link has expired
  1956. initial_url = mp3_info[u'url']
  1957. re_url = r'(?P<server>http://(.*?)\.bandcamp\.com)/download/track\?enc=mp3-320&fsig=(?P<fsig>.*?)&id=(?P<id>.*?)&ts=(?P<ts>.*)$'
  1958. m_url = re.match(re_url, initial_url)
  1959. #We build the url we will use to get the final track url
  1960. # This url is build in Bandcamp in the script download_bunde_*.js
  1961. 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'))
  1962. final_url_webpage = self._download_webpage(request_url, id, 'Requesting download url')
  1963. # If we could correctly generate the .rand field the url would be
  1964. #in the "download_url" key
  1965. final_url = re.search(r'"retry_url":"(.*?)"', final_url_webpage).group(1)
  1966. track_info = {'id':id,
  1967. 'title' : info[u'title'],
  1968. 'ext' : 'mp3',
  1969. 'url' : final_url,
  1970. 'thumbnail' : info[u'thumb_url'],
  1971. 'uploader' : info[u'artist']
  1972. }
  1973. return [track_info]
  1974. class RedTubeIE(InfoExtractor):
  1975. """Information Extractor for redtube"""
  1976. _VALID_URL = r'(?:http://)?(?:www\.)?redtube\.com/(?P<id>[0-9]+)'
  1977. def _real_extract(self,url):
  1978. mobj = re.match(self._VALID_URL, url)
  1979. if mobj is None:
  1980. raise ExtractorError(u'Invalid URL: %s' % url)
  1981. video_id = mobj.group('id')
  1982. video_extension = 'mp4'
  1983. webpage = self._download_webpage(url, video_id)
  1984. self.report_extraction(video_id)
  1985. video_url = self._html_search_regex(r'<source src="(.+?)" type="video/mp4">',
  1986. webpage, u'video URL')
  1987. video_title = self._html_search_regex('<h1 class="videoTitle slidePanelMovable">(.+?)</h1>',
  1988. webpage, u'title')
  1989. return [{
  1990. 'id': video_id,
  1991. 'url': video_url,
  1992. 'ext': video_extension,
  1993. 'title': video_title,
  1994. }]
  1995. class InaIE(InfoExtractor):
  1996. """Information Extractor for Ina.fr"""
  1997. _VALID_URL = r'(?:http://)?(?:www\.)?ina\.fr/video/(?P<id>I[0-9]+)/.*'
  1998. def _real_extract(self,url):
  1999. mobj = re.match(self._VALID_URL, url)
  2000. video_id = mobj.group('id')
  2001. mrss_url='http://player.ina.fr/notices/%s.mrss' % video_id
  2002. video_extension = 'mp4'
  2003. webpage = self._download_webpage(mrss_url, video_id)
  2004. self.report_extraction(video_id)
  2005. video_url = self._html_search_regex(r'<media:player url="(?P<mp4url>http://mp4.ina.fr/[^"]+\.mp4)',
  2006. webpage, u'video URL')
  2007. video_title = self._search_regex(r'<title><!\[CDATA\[(?P<titre>.*?)]]></title>',
  2008. webpage, u'title')
  2009. return [{
  2010. 'id': video_id,
  2011. 'url': video_url,
  2012. 'ext': video_extension,
  2013. 'title': video_title,
  2014. }]
  2015. class HowcastIE(InfoExtractor):
  2016. """Information Extractor for Howcast.com"""
  2017. _VALID_URL = r'(?:https?://)?(?:www\.)?howcast\.com/videos/(?P<id>\d+)'
  2018. def _real_extract(self, url):
  2019. mobj = re.match(self._VALID_URL, url)
  2020. video_id = mobj.group('id')
  2021. webpage_url = 'http://www.howcast.com/videos/' + video_id
  2022. webpage = self._download_webpage(webpage_url, video_id)
  2023. self.report_extraction(video_id)
  2024. video_url = self._search_regex(r'\'?file\'?: "(http://mobile-media\.howcast\.com/[0-9]+\.mp4)',
  2025. webpage, u'video URL')
  2026. video_title = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') property=\'og:title\'',
  2027. webpage, u'title')
  2028. video_description = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') name=\'description\'',
  2029. webpage, u'description', fatal=False)
  2030. thumbnail = self._html_search_regex(r'<meta content=\'(.+?)\' property=\'og:image\'',
  2031. webpage, u'thumbnail', fatal=False)
  2032. return [{
  2033. 'id': video_id,
  2034. 'url': video_url,
  2035. 'ext': 'mp4',
  2036. 'title': video_title,
  2037. 'description': video_description,
  2038. 'thumbnail': thumbnail,
  2039. }]
  2040. class VineIE(InfoExtractor):
  2041. """Information Extractor for Vine.co"""
  2042. _VALID_URL = r'(?:https?://)?(?:www\.)?vine\.co/v/(?P<id>\w+)'
  2043. def _real_extract(self, url):
  2044. mobj = re.match(self._VALID_URL, url)
  2045. video_id = mobj.group('id')
  2046. webpage_url = 'https://vine.co/v/' + video_id
  2047. webpage = self._download_webpage(webpage_url, video_id)
  2048. self.report_extraction(video_id)
  2049. video_url = self._html_search_regex(r'<meta property="twitter:player:stream" content="(.+?)"',
  2050. webpage, u'video URL')
  2051. video_title = self._html_search_regex(r'<meta property="og:title" content="(.+?)"',
  2052. webpage, u'title')
  2053. thumbnail = self._html_search_regex(r'<meta property="og:image" content="(.+?)(\?.*?)?"',
  2054. webpage, u'thumbnail', fatal=False)
  2055. uploader = self._html_search_regex(r'<div class="user">.*?<h2>(.+?)</h2>',
  2056. webpage, u'uploader', fatal=False, flags=re.DOTALL)
  2057. return [{
  2058. 'id': video_id,
  2059. 'url': video_url,
  2060. 'ext': 'mp4',
  2061. 'title': video_title,
  2062. 'thumbnail': thumbnail,
  2063. 'uploader': uploader,
  2064. }]
  2065. class FlickrIE(InfoExtractor):
  2066. """Information Extractor for Flickr videos"""
  2067. _VALID_URL = r'(?:https?://)?(?:www\.)?flickr\.com/photos/(?P<uploader_id>[\w\-_@]+)/(?P<id>\d+).*'
  2068. def _real_extract(self, url):
  2069. mobj = re.match(self._VALID_URL, url)
  2070. video_id = mobj.group('id')
  2071. video_uploader_id = mobj.group('uploader_id')
  2072. webpage_url = 'http://www.flickr.com/photos/' + video_uploader_id + '/' + video_id
  2073. webpage = self._download_webpage(webpage_url, video_id)
  2074. secret = self._search_regex(r"photo_secret: '(\w+)'", webpage, u'secret')
  2075. first_url = 'https://secure.flickr.com/apps/video/video_mtl_xml.gne?v=x&photo_id=' + video_id + '&secret=' + secret + '&bitrate=700&target=_self'
  2076. first_xml = self._download_webpage(first_url, video_id, 'Downloading first data webpage')
  2077. node_id = self._html_search_regex(r'<Item id="id">(\d+-\d+)</Item>',
  2078. first_xml, u'node_id')
  2079. 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'
  2080. second_xml = self._download_webpage(second_url, video_id, 'Downloading second data webpage')
  2081. self.report_extraction(video_id)
  2082. mobj = re.search(r'<STREAM APP="(.+?)" FULLPATH="(.+?)"', second_xml)
  2083. if mobj is None:
  2084. raise ExtractorError(u'Unable to extract video url')
  2085. video_url = mobj.group(1) + unescapeHTML(mobj.group(2))
  2086. video_title = self._html_search_regex(r'<meta property="og:title" content=(?:"([^"]+)"|\'([^\']+)\')',
  2087. webpage, u'video title')
  2088. video_description = self._html_search_regex(r'<meta property="og:description" content=(?:"([^"]+)"|\'([^\']+)\')',
  2089. webpage, u'description', fatal=False)
  2090. thumbnail = self._html_search_regex(r'<meta property="og:image" content=(?:"([^"]+)"|\'([^\']+)\')',
  2091. webpage, u'thumbnail', fatal=False)
  2092. return [{
  2093. 'id': video_id,
  2094. 'url': video_url,
  2095. 'ext': 'mp4',
  2096. 'title': video_title,
  2097. 'description': video_description,
  2098. 'thumbnail': thumbnail,
  2099. 'uploader_id': video_uploader_id,
  2100. }]
  2101. class TeamcocoIE(InfoExtractor):
  2102. _VALID_URL = r'http://teamcoco\.com/video/(?P<url_title>.*)'
  2103. def _real_extract(self, url):
  2104. mobj = re.match(self._VALID_URL, url)
  2105. if mobj is None:
  2106. raise ExtractorError(u'Invalid URL: %s' % url)
  2107. url_title = mobj.group('url_title')
  2108. webpage = self._download_webpage(url, url_title)
  2109. video_id = self._html_search_regex(r'<article class="video" data-id="(\d+?)"',
  2110. webpage, u'video id')
  2111. self.report_extraction(video_id)
  2112. video_title = self._html_search_regex(r'<meta property="og:title" content="(.+?)"',
  2113. webpage, u'title')
  2114. thumbnail = self._html_search_regex(r'<meta property="og:image" content="(.+?)"',
  2115. webpage, u'thumbnail', fatal=False)
  2116. video_description = self._html_search_regex(r'<meta property="og:description" content="(.*?)"',
  2117. webpage, u'description', fatal=False)
  2118. data_url = 'http://teamcoco.com/cvp/2.0/%s.xml' % video_id
  2119. data = self._download_webpage(data_url, video_id, 'Downloading data webpage')
  2120. video_url = self._html_search_regex(r'<file type="high".*?>(.*?)</file>',
  2121. data, u'video URL')
  2122. return [{
  2123. 'id': video_id,
  2124. 'url': video_url,
  2125. 'ext': 'mp4',
  2126. 'title': video_title,
  2127. 'thumbnail': thumbnail,
  2128. 'description': video_description,
  2129. }]
  2130. class XHamsterIE(InfoExtractor):
  2131. """Information Extractor for xHamster"""
  2132. _VALID_URL = r'(?:http://)?(?:www.)?xhamster\.com/movies/(?P<id>[0-9]+)/.*\.html'
  2133. def _real_extract(self,url):
  2134. mobj = re.match(self._VALID_URL, url)
  2135. video_id = mobj.group('id')
  2136. mrss_url = 'http://xhamster.com/movies/%s/.html' % video_id
  2137. webpage = self._download_webpage(mrss_url, video_id)
  2138. mobj = re.search(r'\'srv\': \'(?P<server>[^\']*)\',\s*\'file\': \'(?P<file>[^\']+)\',', webpage)
  2139. if mobj is None:
  2140. raise ExtractorError(u'Unable to extract media URL')
  2141. if len(mobj.group('server')) == 0:
  2142. video_url = compat_urllib_parse.unquote(mobj.group('file'))
  2143. else:
  2144. video_url = mobj.group('server')+'/key='+mobj.group('file')
  2145. video_extension = video_url.split('.')[-1]
  2146. video_title = self._html_search_regex(r'<title>(?P<title>.+?) - xHamster\.com</title>',
  2147. webpage, u'title')
  2148. # Can't see the description anywhere in the UI
  2149. # video_description = self._html_search_regex(r'<span>Description: </span>(?P<description>[^<]+)',
  2150. # webpage, u'description', fatal=False)
  2151. # if video_description: video_description = unescapeHTML(video_description)
  2152. 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)
  2153. if mobj:
  2154. video_upload_date = mobj.group('upload_date_Y')+mobj.group('upload_date_m')+mobj.group('upload_date_d')
  2155. else:
  2156. video_upload_date = None
  2157. self._downloader.report_warning(u'Unable to extract upload date')
  2158. video_uploader_id = self._html_search_regex(r'<a href=\'/user/[^>]+>(?P<uploader_id>[^<]+)',
  2159. webpage, u'uploader id', default=u'anonymous')
  2160. video_thumbnail = self._search_regex(r'\'image\':\'(?P<thumbnail>[^\']+)\'',
  2161. webpage, u'thumbnail', fatal=False)
  2162. return [{
  2163. 'id': video_id,
  2164. 'url': video_url,
  2165. 'ext': video_extension,
  2166. 'title': video_title,
  2167. # 'description': video_description,
  2168. 'upload_date': video_upload_date,
  2169. 'uploader_id': video_uploader_id,
  2170. 'thumbnail': video_thumbnail
  2171. }]
  2172. class HypemIE(InfoExtractor):
  2173. """Information Extractor for hypem"""
  2174. _VALID_URL = r'(?:http://)?(?:www\.)?hypem\.com/track/([^/]+)/([^/]+)'
  2175. def _real_extract(self, url):
  2176. mobj = re.match(self._VALID_URL, url)
  2177. if mobj is None:
  2178. raise ExtractorError(u'Invalid URL: %s' % url)
  2179. track_id = mobj.group(1)
  2180. data = { 'ax': 1, 'ts': time.time() }
  2181. data_encoded = compat_urllib_parse.urlencode(data)
  2182. complete_url = url + "?" + data_encoded
  2183. request = compat_urllib_request.Request(complete_url)
  2184. response, urlh = self._download_webpage_handle(request, track_id, u'Downloading webpage with the url')
  2185. cookie = urlh.headers.get('Set-Cookie', '')
  2186. self.report_extraction(track_id)
  2187. html_tracks = self._html_search_regex(r'<script type="application/json" id="displayList-data">(.*?)</script>',
  2188. response, u'tracks', flags=re.MULTILINE|re.DOTALL).strip()
  2189. try:
  2190. track_list = json.loads(html_tracks)
  2191. track = track_list[u'tracks'][0]
  2192. except ValueError:
  2193. raise ExtractorError(u'Hypemachine contained invalid JSON.')
  2194. key = track[u"key"]
  2195. track_id = track[u"id"]
  2196. artist = track[u"artist"]
  2197. title = track[u"song"]
  2198. serve_url = "http://hypem.com/serve/source/%s/%s" % (compat_str(track_id), compat_str(key))
  2199. request = compat_urllib_request.Request(serve_url, "" , {'Content-Type': 'application/json'})
  2200. request.add_header('cookie', cookie)
  2201. song_data_json = self._download_webpage(request, track_id, u'Downloading metadata')
  2202. try:
  2203. song_data = json.loads(song_data_json)
  2204. except ValueError:
  2205. raise ExtractorError(u'Hypemachine contained invalid JSON.')
  2206. final_url = song_data[u"url"]
  2207. return [{
  2208. 'id': track_id,
  2209. 'url': final_url,
  2210. 'ext': "mp3",
  2211. 'title': title,
  2212. 'artist': artist,
  2213. }]
  2214. class Vbox7IE(InfoExtractor):
  2215. """Information Extractor for Vbox7"""
  2216. _VALID_URL = r'(?:http://)?(?:www\.)?vbox7\.com/play:([^/]+)'
  2217. def _real_extract(self,url):
  2218. mobj = re.match(self._VALID_URL, url)
  2219. if mobj is None:
  2220. raise ExtractorError(u'Invalid URL: %s' % url)
  2221. video_id = mobj.group(1)
  2222. redirect_page, urlh = self._download_webpage_handle(url, video_id)
  2223. new_location = self._search_regex(r'window\.location = \'(.*)\';', redirect_page, u'redirect location')
  2224. redirect_url = urlh.geturl() + new_location
  2225. webpage = self._download_webpage(redirect_url, video_id, u'Downloading redirect page')
  2226. title = self._html_search_regex(r'<title>(.*)</title>',
  2227. webpage, u'title').split('/')[0].strip()
  2228. ext = "flv"
  2229. info_url = "http://vbox7.com/play/magare.do"
  2230. data = compat_urllib_parse.urlencode({'as3':'1','vid':video_id})
  2231. info_request = compat_urllib_request.Request(info_url, data)
  2232. info_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  2233. info_response = self._download_webpage(info_request, video_id, u'Downloading info webpage')
  2234. if info_response is None:
  2235. raise ExtractorError(u'Unable to extract the media url')
  2236. (final_url, thumbnail_url) = map(lambda x: x.split('=')[1], info_response.split('&'))
  2237. return [{
  2238. 'id': video_id,
  2239. 'url': final_url,
  2240. 'ext': ext,
  2241. 'title': title,
  2242. 'thumbnail': thumbnail_url,
  2243. }]
  2244. def gen_extractors():
  2245. """ Return a list of an instance of every supported extractor.
  2246. The order does matter; the first extractor matched is the one handling the URL.
  2247. """
  2248. return [
  2249. YoutubePlaylistIE(),
  2250. YoutubeChannelIE(),
  2251. YoutubeUserIE(),
  2252. YoutubeSearchIE(),
  2253. YoutubeIE(),
  2254. MetacafeIE(),
  2255. DailymotionIE(),
  2256. GoogleSearchIE(),
  2257. PhotobucketIE(),
  2258. YahooIE(),
  2259. YahooSearchIE(),
  2260. DepositFilesIE(),
  2261. FacebookIE(),
  2262. BlipTVIE(),
  2263. BlipTVUserIE(),
  2264. VimeoIE(),
  2265. MyVideoIE(),
  2266. ComedyCentralIE(),
  2267. EscapistIE(),
  2268. CollegeHumorIE(),
  2269. XVideosIE(),
  2270. SoundcloudSetIE(),
  2271. SoundcloudIE(),
  2272. InfoQIE(),
  2273. MixcloudIE(),
  2274. StanfordOpenClassroomIE(),
  2275. MTVIE(),
  2276. YoukuIE(),
  2277. XNXXIE(),
  2278. YouJizzIE(),
  2279. PornotubeIE(),
  2280. YouPornIE(),
  2281. GooglePlusIE(),
  2282. ArteTvIE(),
  2283. NBAIE(),
  2284. WorldStarHipHopIE(),
  2285. JustinTVIE(),
  2286. FunnyOrDieIE(),
  2287. SteamIE(),
  2288. UstreamIE(),
  2289. RBMARadioIE(),
  2290. EightTracksIE(),
  2291. KeekIE(),
  2292. TEDIE(),
  2293. MySpassIE(),
  2294. SpiegelIE(),
  2295. LiveLeakIE(),
  2296. ARDIE(),
  2297. ZDFIE(),
  2298. TumblrIE(),
  2299. BandcampIE(),
  2300. RedTubeIE(),
  2301. InaIE(),
  2302. HowcastIE(),
  2303. VineIE(),
  2304. FlickrIE(),
  2305. TeamcocoIE(),
  2306. XHamsterIE(),
  2307. HypemIE(),
  2308. Vbox7IE(),
  2309. GametrailersIE(),
  2310. StatigramIE(),
  2311. GenericIE()
  2312. ]
  2313. def get_info_extractor(ie_name):
  2314. """Returns the info extractor class with the given ie_name"""
  2315. return globals()[ie_name+'IE']