InfoExtractors.py 133 KB

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