InfoExtractors.py 179 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460
  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. class YoutubeIE(InfoExtractor):
  23. """Information extractor for youtube.com."""
  24. _VALID_URL = r"""^
  25. (
  26. (?:https?://)? # http(s):// (optional)
  27. (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  28. tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
  29. (?:.*?\#/)? # handle anchor (#/) redirect urls
  30. (?: # the various things that can precede the ID:
  31. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  32. |(?: # or the v= param in all its forms
  33. (?:watch(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  34. (?:\?|\#!?) # the params delimiter ? or # or #!
  35. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  36. v=
  37. )
  38. )? # optional -> youtube.com/xxxx is OK
  39. )? # all until now is optional -> you can pass the naked ID
  40. ([0-9A-Za-z_-]+) # here is it! the YouTube video ID
  41. (?(1).+)? # if we found the ID, everything can follow
  42. $"""
  43. _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  44. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  45. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  46. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  47. _NETRC_MACHINE = 'youtube'
  48. # Listed in order of quality
  49. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  50. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
  51. _video_extensions = {
  52. '13': '3gp',
  53. '17': 'mp4',
  54. '18': 'mp4',
  55. '22': 'mp4',
  56. '37': 'mp4',
  57. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  58. '43': 'webm',
  59. '44': 'webm',
  60. '45': 'webm',
  61. '46': 'webm',
  62. }
  63. _video_dimensions = {
  64. '5': '240x400',
  65. '6': '???',
  66. '13': '???',
  67. '17': '144x176',
  68. '18': '360x640',
  69. '22': '720x1280',
  70. '34': '360x640',
  71. '35': '480x854',
  72. '37': '1080x1920',
  73. '38': '3072x4096',
  74. '43': '360x640',
  75. '44': '480x854',
  76. '45': '720x1280',
  77. '46': '1080x1920',
  78. }
  79. IE_NAME = u'youtube'
  80. @classmethod
  81. def suitable(cls, url):
  82. """Receives a URL and returns True if suitable for this IE."""
  83. if YoutubePlaylistIE.suitable(url): return False
  84. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  85. def report_lang(self):
  86. """Report attempt to set language."""
  87. self.to_screen(u'Setting language')
  88. def report_login(self):
  89. """Report attempt to log in."""
  90. self.to_screen(u'Logging in')
  91. def report_video_webpage_download(self, video_id):
  92. """Report attempt to download video webpage."""
  93. self.to_screen(u'%s: Downloading video webpage' % video_id)
  94. def report_video_info_webpage_download(self, video_id):
  95. """Report attempt to download video info webpage."""
  96. self.to_screen(u'%s: Downloading video info webpage' % video_id)
  97. def report_video_subtitles_download(self, video_id):
  98. """Report attempt to download video info webpage."""
  99. self.to_screen(u'%s: Checking available subtitles' % video_id)
  100. def report_video_subtitles_request(self, video_id, sub_lang, format):
  101. """Report attempt to download video info webpage."""
  102. self.to_screen(u'%s: Downloading video subtitles for %s.%s' % (video_id, sub_lang, format))
  103. def report_video_subtitles_available(self, video_id, sub_lang_list):
  104. """Report available subtitles."""
  105. sub_lang = ",".join(list(sub_lang_list.keys()))
  106. self.to_screen(u'%s: Available subtitles for video: %s' % (video_id, sub_lang))
  107. def report_information_extraction(self, video_id):
  108. """Report attempt to extract video information."""
  109. self.to_screen(u'%s: Extracting video information' % video_id)
  110. def report_unavailable_format(self, video_id, format):
  111. """Report extracted video URL."""
  112. self.to_screen(u'%s: Format %s not available' % (video_id, format))
  113. def report_rtmp_download(self):
  114. """Indicate the download will use the RTMP protocol."""
  115. self.to_screen(u'RTMP download detected')
  116. @staticmethod
  117. def _decrypt_signature(s):
  118. """Decrypt the key the two subkeys must have a length of 43"""
  119. (a,b) = s.split('.')
  120. if len(a) != 43 or len(b) != 43:
  121. raise ExtractorError(u'Unable to decrypt signature, subkeys lengths not valid')
  122. b = ''.join([b[:8],a[0],b[9:18],b[-4],b[19:39], b[18]])[0:40]
  123. a = a[-40:]
  124. s_dec = '.'.join((a,b))[::-1]
  125. return s_dec
  126. def _get_available_subtitles(self, video_id):
  127. self.report_video_subtitles_download(video_id)
  128. request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  129. try:
  130. sub_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
  131. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  132. return (u'unable to download video subtitles: %s' % compat_str(err), None)
  133. sub_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  134. sub_lang_list = dict((l[1], l[0]) for l in sub_lang_list)
  135. if not sub_lang_list:
  136. return (u'video doesn\'t have subtitles', None)
  137. return sub_lang_list
  138. def _list_available_subtitles(self, video_id):
  139. sub_lang_list = self._get_available_subtitles(video_id)
  140. self.report_video_subtitles_available(video_id, sub_lang_list)
  141. def _request_subtitle(self, sub_lang, sub_name, video_id, format):
  142. """
  143. Return tuple:
  144. (error_message, sub_lang, sub)
  145. """
  146. self.report_video_subtitles_request(video_id, sub_lang, format)
  147. params = compat_urllib_parse.urlencode({
  148. 'lang': sub_lang,
  149. 'name': sub_name,
  150. 'v': video_id,
  151. 'fmt': format,
  152. })
  153. url = 'http://www.youtube.com/api/timedtext?' + params
  154. try:
  155. sub = compat_urllib_request.urlopen(url).read().decode('utf-8')
  156. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  157. return (u'unable to download video subtitles: %s' % compat_str(err), None, None)
  158. if not sub:
  159. return (u'Did not fetch video subtitles', None, None)
  160. return (None, sub_lang, sub)
  161. def _request_automatic_caption(self, video_id, webpage):
  162. """We need the webpage for getting the captions url, pass it as an
  163. argument to speed up the process."""
  164. sub_lang = self._downloader.params.get('subtitleslang') or 'en'
  165. sub_format = self._downloader.params.get('subtitlesformat')
  166. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  167. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  168. err_msg = u'Couldn\'t find automatic captions for "%s"' % sub_lang
  169. if mobj is None:
  170. return [(err_msg, None, None)]
  171. player_config = json.loads(mobj.group(1))
  172. try:
  173. args = player_config[u'args']
  174. caption_url = args[u'ttsurl']
  175. timestamp = args[u'timestamp']
  176. params = compat_urllib_parse.urlencode({
  177. 'lang': 'en',
  178. 'tlang': sub_lang,
  179. 'fmt': sub_format,
  180. 'ts': timestamp,
  181. 'kind': 'asr',
  182. })
  183. subtitles_url = caption_url + '&' + params
  184. sub = self._download_webpage(subtitles_url, video_id, u'Downloading automatic captions')
  185. return [(None, sub_lang, sub)]
  186. except KeyError:
  187. return [(err_msg, None, None)]
  188. def _extract_subtitle(self, video_id):
  189. """
  190. Return a list with a tuple:
  191. [(error_message, sub_lang, sub)]
  192. """
  193. sub_lang_list = self._get_available_subtitles(video_id)
  194. sub_format = self._downloader.params.get('subtitlesformat')
  195. if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
  196. return [(sub_lang_list[0], None, None)]
  197. if self._downloader.params.get('subtitleslang', False):
  198. sub_lang = self._downloader.params.get('subtitleslang')
  199. elif 'en' in sub_lang_list:
  200. sub_lang = 'en'
  201. else:
  202. sub_lang = list(sub_lang_list.keys())[0]
  203. if not sub_lang in sub_lang_list:
  204. return [(u'no closed captions found in the specified language "%s"' % sub_lang, None, None)]
  205. subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
  206. return [subtitle]
  207. def _extract_all_subtitles(self, video_id):
  208. sub_lang_list = self._get_available_subtitles(video_id)
  209. sub_format = self._downloader.params.get('subtitlesformat')
  210. if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
  211. return [(sub_lang_list[0], None, None)]
  212. subtitles = []
  213. for sub_lang in sub_lang_list:
  214. subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
  215. subtitles.append(subtitle)
  216. return subtitles
  217. def _print_formats(self, formats):
  218. print('Available formats:')
  219. for x in formats:
  220. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
  221. def _real_initialize(self):
  222. if self._downloader is None:
  223. return
  224. username = None
  225. password = None
  226. downloader_params = self._downloader.params
  227. # Attempt to use provided username and password or .netrc data
  228. if downloader_params.get('username', None) is not None:
  229. username = downloader_params['username']
  230. password = downloader_params['password']
  231. elif downloader_params.get('usenetrc', False):
  232. try:
  233. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  234. if info is not None:
  235. username = info[0]
  236. password = info[2]
  237. else:
  238. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  239. except (IOError, netrc.NetrcParseError) as err:
  240. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  241. return
  242. # Set language
  243. request = compat_urllib_request.Request(self._LANG_URL)
  244. try:
  245. self.report_lang()
  246. compat_urllib_request.urlopen(request).read()
  247. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  248. self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
  249. return
  250. # No authentication to be performed
  251. if username is None:
  252. return
  253. request = compat_urllib_request.Request(self._LOGIN_URL)
  254. try:
  255. login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  256. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  257. self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
  258. return
  259. galx = None
  260. dsh = None
  261. match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
  262. if match:
  263. galx = match.group(1)
  264. match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
  265. if match:
  266. dsh = match.group(1)
  267. # Log in
  268. login_form_strs = {
  269. u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  270. u'Email': username,
  271. u'GALX': galx,
  272. u'Passwd': password,
  273. u'PersistentCookie': u'yes',
  274. u'_utf8': u'霱',
  275. u'bgresponse': u'js_disabled',
  276. u'checkConnection': u'',
  277. u'checkedDomains': u'youtube',
  278. u'dnConn': u'',
  279. u'dsh': dsh,
  280. u'pstMsg': u'0',
  281. u'rmShown': u'1',
  282. u'secTok': u'',
  283. u'signIn': u'Sign in',
  284. u'timeStmp': u'',
  285. u'service': u'youtube',
  286. u'uilel': u'3',
  287. u'hl': u'en_US',
  288. }
  289. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  290. # chokes on unicode
  291. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  292. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  293. request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  294. try:
  295. self.report_login()
  296. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  297. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  298. self._downloader.report_warning(u'unable to log in: bad username or password')
  299. return
  300. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  301. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  302. return
  303. # Confirm age
  304. age_form = {
  305. 'next_url': '/',
  306. 'action_confirm': 'Confirm',
  307. }
  308. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  309. try:
  310. self.report_age_confirmation()
  311. age_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  312. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  313. raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err))
  314. def _extract_id(self, url):
  315. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  316. if mobj is None:
  317. raise ExtractorError(u'Invalid URL: %s' % url)
  318. video_id = mobj.group(2)
  319. return video_id
  320. def _real_extract(self, url):
  321. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  322. mobj = re.search(self._NEXT_URL_RE, url)
  323. if mobj:
  324. url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  325. video_id = self._extract_id(url)
  326. # Get video webpage
  327. self.report_video_webpage_download(video_id)
  328. url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  329. request = compat_urllib_request.Request(url)
  330. try:
  331. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  332. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  333. raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
  334. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  335. # Attempt to extract SWF player URL
  336. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  337. if mobj is not None:
  338. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  339. else:
  340. player_url = None
  341. # Get video info
  342. self.report_video_info_webpage_download(video_id)
  343. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  344. video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  345. % (video_id, el_type))
  346. video_info_webpage = self._download_webpage(video_info_url, video_id,
  347. note=False,
  348. errnote='unable to download video info webpage')
  349. video_info = compat_parse_qs(video_info_webpage)
  350. if 'token' in video_info:
  351. break
  352. if 'token' not in video_info:
  353. if 'reason' in video_info:
  354. raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0])
  355. else:
  356. raise ExtractorError(u'"token" parameter not in video info for unknown reason')
  357. # Check for "rental" videos
  358. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  359. raise ExtractorError(u'"rental" videos not supported')
  360. # Start extracting information
  361. self.report_information_extraction(video_id)
  362. # uploader
  363. if 'author' not in video_info:
  364. raise ExtractorError(u'Unable to extract uploader name')
  365. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  366. # uploader_id
  367. video_uploader_id = None
  368. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  369. if mobj is not None:
  370. video_uploader_id = mobj.group(1)
  371. else:
  372. self._downloader.report_warning(u'unable to extract uploader nickname')
  373. # title
  374. if 'title' not in video_info:
  375. raise ExtractorError(u'Unable to extract video title')
  376. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  377. # thumbnail image
  378. if 'thumbnail_url' not in video_info:
  379. self._downloader.report_warning(u'unable to extract video thumbnail')
  380. video_thumbnail = ''
  381. else: # don't panic if we can't find it
  382. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  383. # upload date
  384. upload_date = None
  385. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  386. if mobj is not None:
  387. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  388. upload_date = unified_strdate(upload_date)
  389. # description
  390. video_description = get_element_by_id("eow-description", video_webpage)
  391. if video_description:
  392. video_description = clean_html(video_description)
  393. else:
  394. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  395. if fd_mobj:
  396. video_description = unescapeHTML(fd_mobj.group(1))
  397. else:
  398. video_description = u''
  399. # subtitles
  400. video_subtitles = None
  401. if self._downloader.params.get('writesubtitles', False):
  402. video_subtitles = self._extract_subtitle(video_id)
  403. if video_subtitles:
  404. (sub_error, sub_lang, sub) = video_subtitles[0]
  405. if sub_error:
  406. # We try with the automatic captions
  407. video_subtitles = self._request_automatic_caption(video_id, video_webpage)
  408. (sub_error_auto, sub_lang, sub) = video_subtitles[0]
  409. if sub is not None:
  410. pass
  411. else:
  412. # We report the original error
  413. self._downloader.report_warning(sub_error)
  414. if self._downloader.params.get('allsubtitles', False):
  415. video_subtitles = self._extract_all_subtitles(video_id)
  416. for video_subtitle in video_subtitles:
  417. (sub_error, sub_lang, sub) = video_subtitle
  418. if sub_error:
  419. self._downloader.report_warning(sub_error)
  420. if self._downloader.params.get('listsubtitles', False):
  421. sub_lang_list = self._list_available_subtitles(video_id)
  422. return
  423. if 'length_seconds' not in video_info:
  424. self._downloader.report_warning(u'unable to extract video duration')
  425. video_duration = ''
  426. else:
  427. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  428. # token
  429. video_token = compat_urllib_parse.unquote_plus(video_info['token'][0])
  430. # Decide which formats to download
  431. req_format = self._downloader.params.get('format', None)
  432. try:
  433. mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
  434. info = json.loads(mobj.group(1))
  435. args = info['args']
  436. if args.get('ptk','') == 'vevo' or 'dashmpd':
  437. # Vevo videos with encrypted signatures
  438. self.to_screen(u'%s: Vevo video detected.' % video_id)
  439. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  440. except ValueError:
  441. pass
  442. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  443. self.report_rtmp_download()
  444. video_url_list = [(None, video_info['conn'][0])]
  445. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  446. url_map = {}
  447. for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','):
  448. url_data = compat_parse_qs(url_data_str)
  449. if 'itag' in url_data and 'url' in url_data:
  450. url = url_data['url'][0]
  451. if 'sig' in url_data:
  452. url += '&signature=' + url_data['sig'][0]
  453. elif 's' in url_data:
  454. signature = self._decrypt_signature(url_data['s'][0])
  455. url += '&signature=' + signature
  456. if 'ratebypass' not in url:
  457. url += '&ratebypass=yes'
  458. url_map[url_data['itag'][0]] = url
  459. format_limit = self._downloader.params.get('format_limit', None)
  460. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  461. if format_limit is not None and format_limit in available_formats:
  462. format_list = available_formats[available_formats.index(format_limit):]
  463. else:
  464. format_list = available_formats
  465. existing_formats = [x for x in format_list if x in url_map]
  466. if len(existing_formats) == 0:
  467. raise ExtractorError(u'no known formats available for video')
  468. if self._downloader.params.get('listformats', None):
  469. self._print_formats(existing_formats)
  470. return
  471. if req_format is None or req_format == 'best':
  472. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  473. elif req_format == 'worst':
  474. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  475. elif req_format in ('-1', 'all'):
  476. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  477. else:
  478. # Specific formats. We pick the first in a slash-delimeted sequence.
  479. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  480. req_formats = req_format.split('/')
  481. video_url_list = None
  482. for rf in req_formats:
  483. if rf in url_map:
  484. video_url_list = [(rf, url_map[rf])]
  485. break
  486. if video_url_list is None:
  487. raise ExtractorError(u'requested format not available')
  488. else:
  489. raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info')
  490. results = []
  491. for format_param, video_real_url in video_url_list:
  492. # Extension
  493. video_extension = self._video_extensions.get(format_param, 'flv')
  494. video_format = '{0} - {1}'.format(format_param if format_param else video_extension,
  495. self._video_dimensions.get(format_param, '???'))
  496. results.append({
  497. 'id': video_id,
  498. 'url': video_real_url,
  499. 'uploader': video_uploader,
  500. 'uploader_id': video_uploader_id,
  501. 'upload_date': upload_date,
  502. 'title': video_title,
  503. 'ext': video_extension,
  504. 'format': video_format,
  505. 'thumbnail': video_thumbnail,
  506. 'description': video_description,
  507. 'player_url': player_url,
  508. 'subtitles': video_subtitles,
  509. 'duration': video_duration
  510. })
  511. return results
  512. class MetacafeIE(InfoExtractor):
  513. """Information Extractor for metacafe.com."""
  514. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  515. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  516. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  517. IE_NAME = u'metacafe'
  518. def report_disclaimer(self):
  519. """Report disclaimer retrieval."""
  520. self.to_screen(u'Retrieving disclaimer')
  521. def _real_initialize(self):
  522. # Retrieve disclaimer
  523. request = compat_urllib_request.Request(self._DISCLAIMER)
  524. try:
  525. self.report_disclaimer()
  526. disclaimer = compat_urllib_request.urlopen(request).read()
  527. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  528. raise ExtractorError(u'Unable to retrieve disclaimer: %s' % compat_str(err))
  529. # Confirm age
  530. disclaimer_form = {
  531. 'filters': '0',
  532. 'submit': "Continue - I'm over 18",
  533. }
  534. request = compat_urllib_request.Request(self._FILTER_POST, compat_urllib_parse.urlencode(disclaimer_form))
  535. try:
  536. self.report_age_confirmation()
  537. disclaimer = compat_urllib_request.urlopen(request).read()
  538. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  539. raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err))
  540. def _real_extract(self, url):
  541. # Extract id and simplified title from URL
  542. mobj = re.match(self._VALID_URL, url)
  543. if mobj is None:
  544. raise ExtractorError(u'Invalid URL: %s' % url)
  545. video_id = mobj.group(1)
  546. # Check if video comes from YouTube
  547. mobj2 = re.match(r'^yt-(.*)$', video_id)
  548. if mobj2 is not None:
  549. return [self.url_result('http://www.youtube.com/watch?v=%s' % mobj2.group(1), 'Youtube')]
  550. # Retrieve video webpage to extract further information
  551. webpage = self._download_webpage('http://www.metacafe.com/watch/%s/' % video_id, video_id)
  552. # Extract URL, uploader and title from webpage
  553. self.report_extraction(video_id)
  554. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  555. if mobj is not None:
  556. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  557. video_extension = mediaURL[-3:]
  558. # Extract gdaKey if available
  559. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  560. if mobj is None:
  561. video_url = mediaURL
  562. else:
  563. gdaKey = mobj.group(1)
  564. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  565. else:
  566. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  567. if mobj is None:
  568. raise ExtractorError(u'Unable to extract media URL')
  569. vardict = compat_parse_qs(mobj.group(1))
  570. if 'mediaData' not in vardict:
  571. raise ExtractorError(u'Unable to extract media URL')
  572. mobj = re.search(r'"mediaURL":"(?P<mediaURL>http.*?)",(.*?)"key":"(?P<key>.*?)"', vardict['mediaData'][0])
  573. if mobj is None:
  574. raise ExtractorError(u'Unable to extract media URL')
  575. mediaURL = mobj.group('mediaURL').replace('\\/', '/')
  576. video_extension = mediaURL[-3:]
  577. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group('key'))
  578. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  579. if mobj is None:
  580. raise ExtractorError(u'Unable to extract title')
  581. video_title = mobj.group(1).decode('utf-8')
  582. mobj = re.search(r'submitter=(.*?);', webpage)
  583. if mobj is None:
  584. raise ExtractorError(u'Unable to extract uploader nickname')
  585. video_uploader = mobj.group(1)
  586. return [{
  587. 'id': video_id.decode('utf-8'),
  588. 'url': video_url.decode('utf-8'),
  589. 'uploader': video_uploader.decode('utf-8'),
  590. 'upload_date': None,
  591. 'title': video_title,
  592. 'ext': video_extension.decode('utf-8'),
  593. }]
  594. class DailymotionIE(InfoExtractor):
  595. """Information Extractor for Dailymotion"""
  596. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^/]+)'
  597. IE_NAME = u'dailymotion'
  598. def _real_extract(self, url):
  599. # Extract id and simplified title from URL
  600. mobj = re.match(self._VALID_URL, url)
  601. if mobj is None:
  602. raise ExtractorError(u'Invalid URL: %s' % url)
  603. video_id = mobj.group(1).split('_')[0].split('?')[0]
  604. video_extension = 'mp4'
  605. # Retrieve video webpage to extract further information
  606. request = compat_urllib_request.Request(url)
  607. request.add_header('Cookie', 'family_filter=off')
  608. webpage = self._download_webpage(request, video_id)
  609. # Extract URL, uploader and title from webpage
  610. self.report_extraction(video_id)
  611. mobj = re.search(r'\s*var flashvars = (.*)', webpage)
  612. if mobj is None:
  613. raise ExtractorError(u'Unable to extract media URL')
  614. flashvars = compat_urllib_parse.unquote(mobj.group(1))
  615. for key in ['hd1080URL', 'hd720URL', 'hqURL', 'sdURL', 'ldURL', 'video_url']:
  616. if key in flashvars:
  617. max_quality = key
  618. self.to_screen(u'Using %s' % key)
  619. break
  620. else:
  621. raise ExtractorError(u'Unable to extract video URL')
  622. mobj = re.search(r'"' + max_quality + r'":"(.+?)"', flashvars)
  623. if mobj is None:
  624. raise ExtractorError(u'Unable to extract video URL')
  625. video_url = compat_urllib_parse.unquote(mobj.group(1)).replace('\\/', '/')
  626. # TODO: support choosing qualities
  627. mobj = re.search(r'<meta property="og:title" content="(?P<title>[^"]*)" />', webpage)
  628. if mobj is None:
  629. raise ExtractorError(u'Unable to extract title')
  630. video_title = unescapeHTML(mobj.group('title'))
  631. video_uploader = None
  632. video_uploader = self._search_regex([r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>',
  633. # Looking for official user
  634. r'<(?:span|a) .*?rel="author".*?>([^<]+?)</'],
  635. webpage, 'video uploader')
  636. video_upload_date = None
  637. mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
  638. if mobj is not None:
  639. video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
  640. return [{
  641. 'id': video_id,
  642. 'url': video_url,
  643. 'uploader': video_uploader,
  644. 'upload_date': video_upload_date,
  645. 'title': video_title,
  646. 'ext': video_extension,
  647. }]
  648. class PhotobucketIE(InfoExtractor):
  649. """Information extractor for photobucket.com."""
  650. # TODO: the original _VALID_URL was:
  651. # r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  652. # Check if it's necessary to keep the old extracion process
  653. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*(([\?\&]current=)|_)(?P<id>.*)\.(?P<ext>(flv)|(mp4))'
  654. IE_NAME = u'photobucket'
  655. def _real_extract(self, url):
  656. # Extract id from URL
  657. mobj = re.match(self._VALID_URL, url)
  658. if mobj is None:
  659. raise ExtractorError(u'Invalid URL: %s' % url)
  660. video_id = mobj.group('id')
  661. video_extension = mobj.group('ext')
  662. # Retrieve video webpage to extract further information
  663. webpage = self._download_webpage(url, video_id)
  664. # Extract URL, uploader, and title from webpage
  665. self.report_extraction(video_id)
  666. # We try first by looking the javascript code:
  667. mobj = re.search(r'Pb\.Data\.Shared\.put\(Pb\.Data\.Shared\.MEDIA, (?P<json>.*?)\);', webpage)
  668. if mobj is not None:
  669. info = json.loads(mobj.group('json'))
  670. return [{
  671. 'id': video_id,
  672. 'url': info[u'downloadUrl'],
  673. 'uploader': info[u'username'],
  674. 'upload_date': datetime.date.fromtimestamp(info[u'creationDate']).strftime('%Y%m%d'),
  675. 'title': info[u'title'],
  676. 'ext': video_extension,
  677. 'thumbnail': info[u'thumbUrl'],
  678. }]
  679. # We try looking in other parts of the webpage
  680. video_url = self._search_regex(r'<link rel="video_src" href=".*\?file=([^"]+)" />',
  681. webpage, u'video URL')
  682. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  683. if mobj is None:
  684. raise ExtractorError(u'Unable to extract title')
  685. video_title = mobj.group(1).decode('utf-8')
  686. video_uploader = mobj.group(2).decode('utf-8')
  687. return [{
  688. 'id': video_id.decode('utf-8'),
  689. 'url': video_url.decode('utf-8'),
  690. 'uploader': video_uploader,
  691. 'upload_date': None,
  692. 'title': video_title,
  693. 'ext': video_extension.decode('utf-8'),
  694. }]
  695. class YahooIE(InfoExtractor):
  696. """Information extractor for screen.yahoo.com."""
  697. _VALID_URL = r'http://screen\.yahoo\.com/.*?-(?P<id>\d*?)\.html'
  698. def _real_extract(self, url):
  699. mobj = re.match(self._VALID_URL, url)
  700. if mobj is None:
  701. raise ExtractorError(u'Invalid URL: %s' % url)
  702. video_id = mobj.group('id')
  703. webpage = self._download_webpage(url, video_id)
  704. m_id = re.search(r'YUI\.namespace\("Media"\)\.CONTENT_ID = "(?P<new_id>.+?)";', webpage)
  705. if m_id is None:
  706. # TODO: Check which url parameters are required
  707. info_url = 'http://cosmos.bcst.yahoo.com/rest/v2/pops;lmsoverride=1;outputformat=mrss;cb=974419660;id=%s;rd=news.yahoo.com;datacontext=mdb;lg=KCa2IihxG3qE60vQ7HtyUy' % video_id
  708. webpage = self._download_webpage(info_url, video_id, u'Downloading info webpage')
  709. info_re = r'''<title><!\[CDATA\[(?P<title>.*?)\]\]></title>.*
  710. <description><!\[CDATA\[(?P<description>.*?)\]\]></description>.*
  711. <media:pubStart><!\[CDATA\[(?P<date>.*?)\ .*\]\]></media:pubStart>.*
  712. <media:content\ medium="image"\ url="(?P<thumb>.*?)"\ name="LARGETHUMB"
  713. '''
  714. self.report_extraction(video_id)
  715. m_info = re.search(info_re, webpage, re.VERBOSE|re.DOTALL)
  716. if m_info is None:
  717. raise ExtractorError(u'Unable to extract video info')
  718. video_title = m_info.group('title')
  719. video_description = m_info.group('description')
  720. video_thumb = m_info.group('thumb')
  721. video_date = m_info.group('date')
  722. video_date = datetime.datetime.strptime(video_date, '%m/%d/%Y').strftime('%Y%m%d')
  723. # TODO: Find a way to get mp4 videos
  724. rest_url = 'http://cosmos.bcst.yahoo.com/rest/v2/pops;element=stream;outputformat=mrss;id=%s;lmsoverride=1;bw=375;dynamicstream=1;cb=83521105;tech=flv,mp4;rd=news.yahoo.com;datacontext=mdb;lg=KCa2IihxG3qE60vQ7HtyUy' % video_id
  725. webpage = self._download_webpage(rest_url, video_id, u'Downloading video url webpage')
  726. m_rest = re.search(r'<media:content url="(?P<url>.*?)" path="(?P<path>.*?)"', webpage)
  727. video_url = m_rest.group('url')
  728. video_path = m_rest.group('path')
  729. if m_rest is None:
  730. raise ExtractorError(u'Unable to extract video url')
  731. else: # We have to use a different method if another id is defined
  732. long_id = m_id.group('new_id')
  733. info_url = 'http://video.query.yahoo.com/v1/public/yql?q=SELECT%20*%20FROM%20yahoo.media.video.streams%20WHERE%20id%3D%22' + long_id + '%22%20AND%20format%3D%22mp4%2Cflv%22%20AND%20protocol%3D%22rtmp%2Chttp%22%20AND%20plrs%3D%2286Gj0vCaSzV_Iuf6hNylf2%22%20AND%20acctid%3D%22389%22%20AND%20plidl%3D%22%22%20AND%20pspid%3D%22792700001%22%20AND%20offnetwork%3D%22false%22%20AND%20site%3D%22ivy%22%20AND%20lang%3D%22en-US%22%20AND%20region%3D%22US%22%20AND%20override%3D%22none%22%3B&env=prod&format=json&callback=YUI.Env.JSONP.yui_3_8_1_1_1368368376830_335'
  734. webpage = self._download_webpage(info_url, video_id, u'Downloading info json')
  735. json_str = re.search(r'YUI.Env.JSONP.yui.*?\((.*?)\);', webpage).group(1)
  736. info = json.loads(json_str)
  737. res = info[u'query'][u'results'][u'mediaObj'][0]
  738. stream = res[u'streams'][0]
  739. video_path = stream[u'path']
  740. video_url = stream[u'host']
  741. meta = res[u'meta']
  742. video_title = meta[u'title']
  743. video_description = meta[u'description']
  744. video_thumb = meta[u'thumbnail']
  745. video_date = None # I can't find it
  746. info_dict = {
  747. 'id': video_id,
  748. 'url': video_url,
  749. 'play_path': video_path,
  750. 'title':video_title,
  751. 'description': video_description,
  752. 'thumbnail': video_thumb,
  753. 'upload_date': video_date,
  754. 'ext': 'flv',
  755. }
  756. return info_dict
  757. class VimeoIE(InfoExtractor):
  758. """Information extractor for vimeo.com."""
  759. # _VALID_URL matches Vimeo URLs
  760. _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]+)'
  761. IE_NAME = u'vimeo'
  762. def _verify_video_password(self, url, video_id, webpage):
  763. password = self._downloader.params.get('password', None)
  764. if password is None:
  765. raise ExtractorError(u'This video is protected by a password, use the --password option')
  766. token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
  767. data = compat_urllib_parse.urlencode({'password': password,
  768. 'token': token})
  769. # I didn't manage to use the password with https
  770. if url.startswith('https'):
  771. pass_url = url.replace('https','http')
  772. else:
  773. pass_url = url
  774. password_request = compat_urllib_request.Request(pass_url+'/password', data)
  775. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  776. password_request.add_header('Cookie', 'xsrft=%s' % token)
  777. pass_web = self._download_webpage(password_request, video_id,
  778. u'Verifying the password',
  779. u'Wrong password')
  780. def _real_extract(self, url, new_video=True):
  781. # Extract ID from URL
  782. mobj = re.match(self._VALID_URL, url)
  783. if mobj is None:
  784. raise ExtractorError(u'Invalid URL: %s' % url)
  785. video_id = mobj.group('id')
  786. if not mobj.group('proto'):
  787. url = 'https://' + url
  788. if mobj.group('direct_link') or mobj.group('pro'):
  789. url = 'https://vimeo.com/' + video_id
  790. # Retrieve video webpage to extract further information
  791. request = compat_urllib_request.Request(url, None, std_headers)
  792. webpage = self._download_webpage(request, video_id)
  793. # Now we begin extracting as much information as we can from what we
  794. # retrieved. First we extract the information common to all extractors,
  795. # and latter we extract those that are Vimeo specific.
  796. self.report_extraction(video_id)
  797. # Extract the config JSON
  798. try:
  799. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  800. config = json.loads(config)
  801. except:
  802. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  803. raise ExtractorError(u'The author has restricted the access to this video, try with the "--referer" option')
  804. if re.search('If so please provide the correct password.', webpage):
  805. self._verify_video_password(url, video_id, webpage)
  806. return self._real_extract(url)
  807. else:
  808. raise ExtractorError(u'Unable to extract info section')
  809. # Extract title
  810. video_title = config["video"]["title"]
  811. # Extract uploader and uploader_id
  812. video_uploader = config["video"]["owner"]["name"]
  813. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  814. # Extract video thumbnail
  815. video_thumbnail = config["video"]["thumbnail"]
  816. # Extract video description
  817. video_description = get_element_by_attribute("itemprop", "description", webpage)
  818. if video_description: video_description = clean_html(video_description)
  819. else: video_description = u''
  820. # Extract upload date
  821. video_upload_date = None
  822. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  823. if mobj is not None:
  824. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  825. # Vimeo specific: extract request signature and timestamp
  826. sig = config['request']['signature']
  827. timestamp = config['request']['timestamp']
  828. # Vimeo specific: extract video codec and quality information
  829. # First consider quality, then codecs, then take everything
  830. # TODO bind to format param
  831. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  832. files = { 'hd': [], 'sd': [], 'other': []}
  833. for codec_name, codec_extension in codecs:
  834. if codec_name in config["video"]["files"]:
  835. if 'hd' in config["video"]["files"][codec_name]:
  836. files['hd'].append((codec_name, codec_extension, 'hd'))
  837. elif 'sd' in config["video"]["files"][codec_name]:
  838. files['sd'].append((codec_name, codec_extension, 'sd'))
  839. else:
  840. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  841. for quality in ('hd', 'sd', 'other'):
  842. if len(files[quality]) > 0:
  843. video_quality = files[quality][0][2]
  844. video_codec = files[quality][0][0]
  845. video_extension = files[quality][0][1]
  846. self.to_screen(u'%s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  847. break
  848. else:
  849. raise ExtractorError(u'No known codec found')
  850. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  851. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  852. return [{
  853. 'id': video_id,
  854. 'url': video_url,
  855. 'uploader': video_uploader,
  856. 'uploader_id': video_uploader_id,
  857. 'upload_date': video_upload_date,
  858. 'title': video_title,
  859. 'ext': video_extension,
  860. 'thumbnail': video_thumbnail,
  861. 'description': video_description,
  862. }]
  863. class ArteTvIE(InfoExtractor):
  864. """arte.tv information extractor."""
  865. _VALID_URL = r'(?:http://)?videos\.arte\.tv/(?:fr|de)/videos/.*'
  866. _LIVE_URL = r'index-[0-9]+\.html$'
  867. IE_NAME = u'arte.tv'
  868. def fetch_webpage(self, url):
  869. request = compat_urllib_request.Request(url)
  870. try:
  871. self.report_download_webpage(url)
  872. webpage = compat_urllib_request.urlopen(request).read()
  873. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  874. raise ExtractorError(u'Unable to retrieve video webpage: %s' % compat_str(err))
  875. except ValueError as err:
  876. raise ExtractorError(u'Invalid URL: %s' % url)
  877. return webpage
  878. def grep_webpage(self, url, regex, regexFlags, matchTuples):
  879. page = self.fetch_webpage(url)
  880. mobj = re.search(regex, page, regexFlags)
  881. info = {}
  882. if mobj is None:
  883. raise ExtractorError(u'Invalid URL: %s' % url)
  884. for (i, key, err) in matchTuples:
  885. if mobj.group(i) is None:
  886. raise ExtractorError(err)
  887. else:
  888. info[key] = mobj.group(i)
  889. return info
  890. def extractLiveStream(self, url):
  891. video_lang = url.split('/')[-4]
  892. info = self.grep_webpage(
  893. url,
  894. r'src="(.*?/videothek_js.*?\.js)',
  895. 0,
  896. [
  897. (1, 'url', u'Invalid URL: %s' % url)
  898. ]
  899. )
  900. http_host = url.split('/')[2]
  901. next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
  902. info = self.grep_webpage(
  903. next_url,
  904. r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
  905. '(http://.*?\.swf).*?' +
  906. '(rtmp://.*?)\'',
  907. re.DOTALL,
  908. [
  909. (1, 'path', u'could not extract video path: %s' % url),
  910. (2, 'player', u'could not extract video player: %s' % url),
  911. (3, 'url', u'could not extract video url: %s' % url)
  912. ]
  913. )
  914. video_url = u'%s/%s' % (info.get('url'), info.get('path'))
  915. def extractPlus7Stream(self, url):
  916. video_lang = url.split('/')[-3]
  917. info = self.grep_webpage(
  918. url,
  919. r'param name="movie".*?videorefFileUrl=(http[^\'"&]*)',
  920. 0,
  921. [
  922. (1, 'url', u'Invalid URL: %s' % url)
  923. ]
  924. )
  925. next_url = compat_urllib_parse.unquote(info.get('url'))
  926. info = self.grep_webpage(
  927. next_url,
  928. r'<video lang="%s" ref="(http[^\'"&]*)' % video_lang,
  929. 0,
  930. [
  931. (1, 'url', u'Could not find <video> tag: %s' % url)
  932. ]
  933. )
  934. next_url = compat_urllib_parse.unquote(info.get('url'))
  935. info = self.grep_webpage(
  936. next_url,
  937. r'<video id="(.*?)".*?>.*?' +
  938. '<name>(.*?)</name>.*?' +
  939. '<dateVideo>(.*?)</dateVideo>.*?' +
  940. '<url quality="hd">(.*?)</url>',
  941. re.DOTALL,
  942. [
  943. (1, 'id', u'could not extract video id: %s' % url),
  944. (2, 'title', u'could not extract video title: %s' % url),
  945. (3, 'date', u'could not extract video date: %s' % url),
  946. (4, 'url', u'could not extract video url: %s' % url)
  947. ]
  948. )
  949. return {
  950. 'id': info.get('id'),
  951. 'url': compat_urllib_parse.unquote(info.get('url')),
  952. 'uploader': u'arte.tv',
  953. 'upload_date': unified_strdate(info.get('date')),
  954. 'title': info.get('title').decode('utf-8'),
  955. 'ext': u'mp4',
  956. 'format': u'NA',
  957. 'player_url': None,
  958. }
  959. def _real_extract(self, url):
  960. video_id = url.split('/')[-1]
  961. self.report_extraction(video_id)
  962. if re.search(self._LIVE_URL, video_id) is not None:
  963. self.extractLiveStream(url)
  964. return
  965. else:
  966. info = self.extractPlus7Stream(url)
  967. return [info]
  968. class GenericIE(InfoExtractor):
  969. """Generic last-resort information extractor."""
  970. _VALID_URL = r'.*'
  971. IE_NAME = u'generic'
  972. def report_download_webpage(self, video_id):
  973. """Report webpage download."""
  974. if not self._downloader.params.get('test', False):
  975. self._downloader.report_warning(u'Falling back on generic information extractor.')
  976. super(GenericIE, self).report_download_webpage(video_id)
  977. def report_following_redirect(self, new_url):
  978. """Report information extraction."""
  979. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  980. def _test_redirect(self, url):
  981. """Check if it is a redirect, like url shorteners, in case return the new url."""
  982. class HeadRequest(compat_urllib_request.Request):
  983. def get_method(self):
  984. return "HEAD"
  985. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  986. """
  987. Subclass the HTTPRedirectHandler to make it use our
  988. HeadRequest also on the redirected URL
  989. """
  990. def redirect_request(self, req, fp, code, msg, headers, newurl):
  991. if code in (301, 302, 303, 307):
  992. newurl = newurl.replace(' ', '%20')
  993. newheaders = dict((k,v) for k,v in req.headers.items()
  994. if k.lower() not in ("content-length", "content-type"))
  995. return HeadRequest(newurl,
  996. headers=newheaders,
  997. origin_req_host=req.get_origin_req_host(),
  998. unverifiable=True)
  999. else:
  1000. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  1001. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  1002. """
  1003. Fallback to GET if HEAD is not allowed (405 HTTP error)
  1004. """
  1005. def http_error_405(self, req, fp, code, msg, headers):
  1006. fp.read()
  1007. fp.close()
  1008. newheaders = dict((k,v) for k,v in req.headers.items()
  1009. if k.lower() not in ("content-length", "content-type"))
  1010. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  1011. headers=newheaders,
  1012. origin_req_host=req.get_origin_req_host(),
  1013. unverifiable=True))
  1014. # Build our opener
  1015. opener = compat_urllib_request.OpenerDirector()
  1016. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  1017. HTTPMethodFallback, HEADRedirectHandler,
  1018. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  1019. opener.add_handler(handler())
  1020. response = opener.open(HeadRequest(url))
  1021. if response is None:
  1022. raise ExtractorError(u'Invalid URL protocol')
  1023. new_url = response.geturl()
  1024. if url == new_url:
  1025. return False
  1026. self.report_following_redirect(new_url)
  1027. return new_url
  1028. def _real_extract(self, url):
  1029. new_url = self._test_redirect(url)
  1030. if new_url: return [self.url_result(new_url)]
  1031. video_id = url.split('/')[-1]
  1032. try:
  1033. webpage = self._download_webpage(url, video_id)
  1034. except ValueError as err:
  1035. # since this is the last-resort InfoExtractor, if
  1036. # this error is thrown, it'll be thrown here
  1037. raise ExtractorError(u'Invalid URL: %s' % url)
  1038. self.report_extraction(video_id)
  1039. # Start with something easy: JW Player in SWFObject
  1040. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1041. if mobj is None:
  1042. # Broaden the search a little bit
  1043. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1044. if mobj is None:
  1045. # Broaden the search a little bit: JWPlayer JS loader
  1046. mobj = re.search(r'[^A-Za-z0-9]?file:\s*["\'](http[^\'"&]*)', webpage)
  1047. if mobj is None:
  1048. # Try to find twitter cards info
  1049. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  1050. if mobj is None:
  1051. # We look for Open Graph info:
  1052. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  1053. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  1054. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  1055. if m_video_type is not None:
  1056. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  1057. if mobj is None:
  1058. raise ExtractorError(u'Invalid URL: %s' % url)
  1059. # It's possible that one of the regexes
  1060. # matched, but returned an empty group:
  1061. if mobj.group(1) is None:
  1062. raise ExtractorError(u'Invalid URL: %s' % url)
  1063. video_url = compat_urllib_parse.unquote(mobj.group(1))
  1064. video_id = os.path.basename(video_url)
  1065. # here's a fun little line of code for you:
  1066. video_extension = os.path.splitext(video_id)[1][1:]
  1067. video_id = os.path.splitext(video_id)[0]
  1068. # it's tempting to parse this further, but you would
  1069. # have to take into account all the variations like
  1070. # Video Title - Site Name
  1071. # Site Name | Video Title
  1072. # Video Title - Tagline | Site Name
  1073. # and so on and so forth; it's just not practical
  1074. video_title = self._html_search_regex(r'<title>(.*)</title>',
  1075. webpage, u'video title')
  1076. # video uploader is domain name
  1077. video_uploader = self._search_regex(r'(?:https?://)?([^/]*)/.*',
  1078. url, u'video uploader')
  1079. return [{
  1080. 'id': video_id,
  1081. 'url': video_url,
  1082. 'uploader': video_uploader,
  1083. 'upload_date': None,
  1084. 'title': video_title,
  1085. 'ext': video_extension,
  1086. }]
  1087. class YoutubeSearchIE(SearchInfoExtractor):
  1088. """Information Extractor for YouTube search queries."""
  1089. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1090. _MAX_RESULTS = 1000
  1091. IE_NAME = u'youtube:search'
  1092. _SEARCH_KEY = 'ytsearch'
  1093. def report_download_page(self, query, pagenum):
  1094. """Report attempt to download search page with given number."""
  1095. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1096. def _get_n_results(self, query, n):
  1097. """Get a specified number of results for a query"""
  1098. video_ids = []
  1099. pagenum = 0
  1100. limit = n
  1101. while (50 * pagenum) < limit:
  1102. self.report_download_page(query, pagenum+1)
  1103. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1104. request = compat_urllib_request.Request(result_url)
  1105. try:
  1106. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1107. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1108. raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
  1109. api_response = json.loads(data)['data']
  1110. if not 'items' in api_response:
  1111. raise ExtractorError(u'[youtube] No video results')
  1112. new_ids = list(video['id'] for video in api_response['items'])
  1113. video_ids += new_ids
  1114. limit = min(n, api_response['totalItems'])
  1115. pagenum += 1
  1116. if len(video_ids) > n:
  1117. video_ids = video_ids[:n]
  1118. videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
  1119. return self.playlist_result(videos, query)
  1120. class GoogleSearchIE(SearchInfoExtractor):
  1121. """Information Extractor for Google Video search queries."""
  1122. _MORE_PAGES_INDICATOR = r'id="pnnext" class="pn"'
  1123. _MAX_RESULTS = 1000
  1124. IE_NAME = u'video.google:search'
  1125. _SEARCH_KEY = 'gvsearch'
  1126. def _get_n_results(self, query, n):
  1127. """Get a specified number of results for a query"""
  1128. res = {
  1129. '_type': 'playlist',
  1130. 'id': query,
  1131. 'entries': []
  1132. }
  1133. for pagenum in itertools.count(1):
  1134. result_url = u'http://www.google.com/search?tbm=vid&q=%s&start=%s&hl=en' % (compat_urllib_parse.quote_plus(query), pagenum*10)
  1135. webpage = self._download_webpage(result_url, u'gvsearch:' + query,
  1136. note='Downloading result page ' + str(pagenum))
  1137. for mobj in re.finditer(r'<h3 class="r"><a href="([^"]+)"', webpage):
  1138. e = {
  1139. '_type': 'url',
  1140. 'url': mobj.group(1)
  1141. }
  1142. res['entries'].append(e)
  1143. if (pagenum * 10 > n) or not re.search(self._MORE_PAGES_INDICATOR, webpage):
  1144. return res
  1145. class YahooSearchIE(SearchInfoExtractor):
  1146. """Information Extractor for Yahoo! Video search queries."""
  1147. _MAX_RESULTS = 1000
  1148. IE_NAME = u'screen.yahoo:search'
  1149. _SEARCH_KEY = 'yvsearch'
  1150. def _get_n_results(self, query, n):
  1151. """Get a specified number of results for a query"""
  1152. res = {
  1153. '_type': 'playlist',
  1154. 'id': query,
  1155. 'entries': []
  1156. }
  1157. for pagenum in itertools.count(0):
  1158. 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)
  1159. webpage = self._download_webpage(result_url, query,
  1160. note='Downloading results page '+str(pagenum+1))
  1161. info = json.loads(webpage)
  1162. m = info[u'm']
  1163. results = info[u'results']
  1164. for (i, r) in enumerate(results):
  1165. if (pagenum * 30) +i >= n:
  1166. break
  1167. mobj = re.search(r'(?P<url>screen\.yahoo\.com/.*?-\d*?\.html)"', r)
  1168. e = self.url_result('http://' + mobj.group('url'), 'Yahoo')
  1169. res['entries'].append(e)
  1170. if (pagenum * 30 +i >= n) or (m[u'last'] >= (m[u'total'] -1 )):
  1171. break
  1172. return res
  1173. class YoutubePlaylistIE(InfoExtractor):
  1174. """Information Extractor for YouTube playlists."""
  1175. _VALID_URL = r"""(?:
  1176. (?:https?://)?
  1177. (?:\w+\.)?
  1178. youtube\.com/
  1179. (?:
  1180. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1181. \? (?:.*?&)*? (?:p|a|list)=
  1182. | p/
  1183. )
  1184. ((?:PL|EC|UU)?[0-9A-Za-z-_]{10,})
  1185. .*
  1186. |
  1187. ((?:PL|EC|UU)[0-9A-Za-z-_]{10,})
  1188. )"""
  1189. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none'
  1190. _MAX_RESULTS = 50
  1191. IE_NAME = u'youtube:playlist'
  1192. @classmethod
  1193. def suitable(cls, url):
  1194. """Receives a URL and returns True if suitable for this IE."""
  1195. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1196. def _real_extract(self, url):
  1197. # Extract playlist id
  1198. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1199. if mobj is None:
  1200. raise ExtractorError(u'Invalid URL: %s' % url)
  1201. # Download playlist videos from API
  1202. playlist_id = mobj.group(1) or mobj.group(2)
  1203. page_num = 1
  1204. videos = []
  1205. while True:
  1206. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, self._MAX_RESULTS * (page_num - 1) + 1)
  1207. page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
  1208. try:
  1209. response = json.loads(page)
  1210. except ValueError as err:
  1211. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1212. if 'feed' not in response:
  1213. raise ExtractorError(u'Got a malformed response from YouTube API')
  1214. playlist_title = response['feed']['title']['$t']
  1215. if 'entry' not in response['feed']:
  1216. # Number of videos is a multiple of self._MAX_RESULTS
  1217. break
  1218. for entry in response['feed']['entry']:
  1219. index = entry['yt$position']['$t']
  1220. if 'media$group' in entry and 'media$player' in entry['media$group']:
  1221. videos.append((index, entry['media$group']['media$player']['url']))
  1222. if len(response['feed']['entry']) < self._MAX_RESULTS:
  1223. break
  1224. page_num += 1
  1225. videos = [v[1] for v in sorted(videos)]
  1226. url_results = [self.url_result(url, 'Youtube') for url in videos]
  1227. return [self.playlist_result(url_results, playlist_id, playlist_title)]
  1228. class YoutubeChannelIE(InfoExtractor):
  1229. """Information Extractor for YouTube channels."""
  1230. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  1231. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1232. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  1233. _MORE_PAGES_URL = 'http://www.youtube.com/channel_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
  1234. IE_NAME = u'youtube:channel'
  1235. def extract_videos_from_page(self, page):
  1236. ids_in_page = []
  1237. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1238. if mobj.group(1) not in ids_in_page:
  1239. ids_in_page.append(mobj.group(1))
  1240. return ids_in_page
  1241. def _real_extract(self, url):
  1242. # Extract channel id
  1243. mobj = re.match(self._VALID_URL, url)
  1244. if mobj is None:
  1245. raise ExtractorError(u'Invalid URL: %s' % url)
  1246. # Download channel page
  1247. channel_id = mobj.group(1)
  1248. video_ids = []
  1249. pagenum = 1
  1250. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1251. page = self._download_webpage(url, channel_id,
  1252. u'Downloading page #%s' % pagenum)
  1253. # Extract video identifiers
  1254. ids_in_page = self.extract_videos_from_page(page)
  1255. video_ids.extend(ids_in_page)
  1256. # Download any subsequent channel pages using the json-based channel_ajax query
  1257. if self._MORE_PAGES_INDICATOR in page:
  1258. while True:
  1259. pagenum = pagenum + 1
  1260. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1261. page = self._download_webpage(url, channel_id,
  1262. u'Downloading page #%s' % pagenum)
  1263. page = json.loads(page)
  1264. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1265. video_ids.extend(ids_in_page)
  1266. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1267. break
  1268. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1269. urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
  1270. url_entries = [self.url_result(url, 'Youtube') for url in urls]
  1271. return [self.playlist_result(url_entries, channel_id)]
  1272. class YoutubeUserIE(InfoExtractor):
  1273. """Information Extractor for YouTube users."""
  1274. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1275. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1276. _GDATA_PAGE_SIZE = 50
  1277. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1278. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1279. IE_NAME = u'youtube:user'
  1280. def _real_extract(self, url):
  1281. # Extract username
  1282. mobj = re.match(self._VALID_URL, url)
  1283. if mobj is None:
  1284. raise ExtractorError(u'Invalid URL: %s' % url)
  1285. username = mobj.group(1)
  1286. # Download video ids using YouTube Data API. Result size per
  1287. # query is limited (currently to 50 videos) so we need to query
  1288. # page by page until there are no video ids - it means we got
  1289. # all of them.
  1290. video_ids = []
  1291. pagenum = 0
  1292. while True:
  1293. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1294. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1295. page = self._download_webpage(gdata_url, username,
  1296. u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
  1297. # Extract video identifiers
  1298. ids_in_page = []
  1299. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1300. if mobj.group(1) not in ids_in_page:
  1301. ids_in_page.append(mobj.group(1))
  1302. video_ids.extend(ids_in_page)
  1303. # A little optimization - if current page is not
  1304. # "full", ie. does not contain PAGE_SIZE video ids then
  1305. # we can assume that this page is the last one - there
  1306. # are no more ids on further pages - no need to query
  1307. # again.
  1308. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1309. break
  1310. pagenum += 1
  1311. urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
  1312. url_results = [self.url_result(url, 'Youtube') for url in urls]
  1313. return [self.playlist_result(url_results, playlist_title = username)]
  1314. class BlipTVUserIE(InfoExtractor):
  1315. """Information Extractor for blip.tv users."""
  1316. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1317. _PAGE_SIZE = 12
  1318. IE_NAME = u'blip.tv:user'
  1319. def _real_extract(self, url):
  1320. # Extract username
  1321. mobj = re.match(self._VALID_URL, url)
  1322. if mobj is None:
  1323. raise ExtractorError(u'Invalid URL: %s' % url)
  1324. username = mobj.group(1)
  1325. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1326. page = self._download_webpage(url, username, u'Downloading user page')
  1327. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1328. page_base = page_base % mobj.group(1)
  1329. # Download video ids using BlipTV Ajax calls. Result size per
  1330. # query is limited (currently to 12 videos) so we need to query
  1331. # page by page until there are no video ids - it means we got
  1332. # all of them.
  1333. video_ids = []
  1334. pagenum = 1
  1335. while True:
  1336. url = page_base + "&page=" + str(pagenum)
  1337. page = self._download_webpage(url, username,
  1338. u'Downloading video ids from page %d' % pagenum)
  1339. # Extract video identifiers
  1340. ids_in_page = []
  1341. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1342. if mobj.group(1) not in ids_in_page:
  1343. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1344. video_ids.extend(ids_in_page)
  1345. # A little optimization - if current page is not
  1346. # "full", ie. does not contain PAGE_SIZE video ids then
  1347. # we can assume that this page is the last one - there
  1348. # are no more ids on further pages - no need to query
  1349. # again.
  1350. if len(ids_in_page) < self._PAGE_SIZE:
  1351. break
  1352. pagenum += 1
  1353. urls = [u'http://blip.tv/%s' % video_id for video_id in video_ids]
  1354. url_entries = [self.url_result(url, 'BlipTV') for url in urls]
  1355. return [self.playlist_result(url_entries, playlist_title = username)]
  1356. class DepositFilesIE(InfoExtractor):
  1357. """Information extractor for depositfiles.com"""
  1358. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1359. def _real_extract(self, url):
  1360. file_id = url.split('/')[-1]
  1361. # Rebuild url in english locale
  1362. url = 'http://depositfiles.com/en/files/' + file_id
  1363. # Retrieve file webpage with 'Free download' button pressed
  1364. free_download_indication = { 'gateway_result' : '1' }
  1365. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  1366. try:
  1367. self.report_download_webpage(file_id)
  1368. webpage = compat_urllib_request.urlopen(request).read()
  1369. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1370. raise ExtractorError(u'Unable to retrieve file webpage: %s' % compat_str(err))
  1371. # Search for the real file URL
  1372. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1373. if (mobj is None) or (mobj.group(1) is None):
  1374. # Try to figure out reason of the error.
  1375. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1376. if (mobj is not None) and (mobj.group(1) is not None):
  1377. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1378. raise ExtractorError(u'%s' % restriction_message)
  1379. else:
  1380. raise ExtractorError(u'Unable to extract download URL from: %s' % url)
  1381. file_url = mobj.group(1)
  1382. file_extension = os.path.splitext(file_url)[1][1:]
  1383. # Search for file title
  1384. file_title = self._search_regex(r'<b title="(.*?)">', webpage, u'title')
  1385. return [{
  1386. 'id': file_id.decode('utf-8'),
  1387. 'url': file_url.decode('utf-8'),
  1388. 'uploader': None,
  1389. 'upload_date': None,
  1390. 'title': file_title,
  1391. 'ext': file_extension.decode('utf-8'),
  1392. }]
  1393. class FacebookIE(InfoExtractor):
  1394. """Information Extractor for Facebook"""
  1395. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1396. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1397. _NETRC_MACHINE = 'facebook'
  1398. IE_NAME = u'facebook'
  1399. def report_login(self):
  1400. """Report attempt to log in."""
  1401. self.to_screen(u'Logging in')
  1402. def _real_initialize(self):
  1403. if self._downloader is None:
  1404. return
  1405. useremail = None
  1406. password = None
  1407. downloader_params = self._downloader.params
  1408. # Attempt to use provided username and password or .netrc data
  1409. if downloader_params.get('username', None) is not None:
  1410. useremail = downloader_params['username']
  1411. password = downloader_params['password']
  1412. elif downloader_params.get('usenetrc', False):
  1413. try:
  1414. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1415. if info is not None:
  1416. useremail = info[0]
  1417. password = info[2]
  1418. else:
  1419. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1420. except (IOError, netrc.NetrcParseError) as err:
  1421. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  1422. return
  1423. if useremail is None:
  1424. return
  1425. # Log in
  1426. login_form = {
  1427. 'email': useremail,
  1428. 'pass': password,
  1429. 'login': 'Log+In'
  1430. }
  1431. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  1432. try:
  1433. self.report_login()
  1434. login_results = compat_urllib_request.urlopen(request).read()
  1435. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1436. self._downloader.report_warning(u'unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1437. return
  1438. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1439. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  1440. return
  1441. def _real_extract(self, url):
  1442. mobj = re.match(self._VALID_URL, url)
  1443. if mobj is None:
  1444. raise ExtractorError(u'Invalid URL: %s' % url)
  1445. video_id = mobj.group('ID')
  1446. url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
  1447. webpage = self._download_webpage(url, video_id)
  1448. BEFORE = '{swf.addParam(param[0], param[1]);});\n'
  1449. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  1450. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  1451. if not m:
  1452. raise ExtractorError(u'Cannot parse data')
  1453. data = dict(json.loads(m.group(1)))
  1454. params_raw = compat_urllib_parse.unquote(data['params'])
  1455. params = json.loads(params_raw)
  1456. video_data = params['video_data'][0]
  1457. video_url = video_data.get('hd_src')
  1458. if not video_url:
  1459. video_url = video_data['sd_src']
  1460. if not video_url:
  1461. raise ExtractorError(u'Cannot find video URL')
  1462. video_duration = int(video_data['video_duration'])
  1463. thumbnail = video_data['thumbnail_src']
  1464. video_title = self._html_search_regex('<h2 class="uiHeaderTitle">([^<]+)</h2>',
  1465. webpage, u'title')
  1466. info = {
  1467. 'id': video_id,
  1468. 'title': video_title,
  1469. 'url': video_url,
  1470. 'ext': 'mp4',
  1471. 'duration': video_duration,
  1472. 'thumbnail': thumbnail,
  1473. }
  1474. return [info]
  1475. class BlipTVIE(InfoExtractor):
  1476. """Information extractor for blip.tv"""
  1477. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(.+)$'
  1478. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1479. IE_NAME = u'blip.tv'
  1480. def report_direct_download(self, title):
  1481. """Report information extraction."""
  1482. self.to_screen(u'%s: Direct download detected' % title)
  1483. def _real_extract(self, url):
  1484. mobj = re.match(self._VALID_URL, url)
  1485. if mobj is None:
  1486. raise ExtractorError(u'Invalid URL: %s' % url)
  1487. # See https://github.com/rg3/youtube-dl/issues/857
  1488. api_mobj = re.match(r'http://a\.blip\.tv/api\.swf#(?P<video_id>[\d\w]+)', url)
  1489. if api_mobj is not None:
  1490. url = 'http://blip.tv/play/g_%s' % api_mobj.group('video_id')
  1491. urlp = compat_urllib_parse_urlparse(url)
  1492. if urlp.path.startswith('/play/'):
  1493. request = compat_urllib_request.Request(url)
  1494. response = compat_urllib_request.urlopen(request)
  1495. redirecturl = response.geturl()
  1496. rurlp = compat_urllib_parse_urlparse(redirecturl)
  1497. file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
  1498. url = 'http://blip.tv/a/a-' + file_id
  1499. return self._real_extract(url)
  1500. if '?' in url:
  1501. cchar = '&'
  1502. else:
  1503. cchar = '?'
  1504. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1505. request = compat_urllib_request.Request(json_url)
  1506. request.add_header('User-Agent', 'iTunes/10.6.1')
  1507. self.report_extraction(mobj.group(1))
  1508. info = None
  1509. try:
  1510. urlh = compat_urllib_request.urlopen(request)
  1511. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1512. basename = url.split('/')[-1]
  1513. title,ext = os.path.splitext(basename)
  1514. title = title.decode('UTF-8')
  1515. ext = ext.replace('.', '')
  1516. self.report_direct_download(title)
  1517. info = {
  1518. 'id': title,
  1519. 'url': url,
  1520. 'uploader': None,
  1521. 'upload_date': None,
  1522. 'title': title,
  1523. 'ext': ext,
  1524. 'urlhandle': urlh
  1525. }
  1526. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1527. raise ExtractorError(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  1528. if info is None: # Regular URL
  1529. try:
  1530. json_code_bytes = urlh.read()
  1531. json_code = json_code_bytes.decode('utf-8')
  1532. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1533. raise ExtractorError(u'Unable to read video info webpage: %s' % compat_str(err))
  1534. try:
  1535. json_data = json.loads(json_code)
  1536. if 'Post' in json_data:
  1537. data = json_data['Post']
  1538. else:
  1539. data = json_data
  1540. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1541. video_url = data['media']['url']
  1542. umobj = re.match(self._URL_EXT, video_url)
  1543. if umobj is None:
  1544. raise ValueError('Can not determine filename extension')
  1545. ext = umobj.group(1)
  1546. info = {
  1547. 'id': data['item_id'],
  1548. 'url': video_url,
  1549. 'uploader': data['display_name'],
  1550. 'upload_date': upload_date,
  1551. 'title': data['title'],
  1552. 'ext': ext,
  1553. 'format': data['media']['mimeType'],
  1554. 'thumbnail': data['thumbnailUrl'],
  1555. 'description': data['description'],
  1556. 'player_url': data['embedUrl'],
  1557. 'user_agent': 'iTunes/10.6.1',
  1558. }
  1559. except (ValueError,KeyError) as err:
  1560. raise ExtractorError(u'Unable to parse video information: %s' % repr(err))
  1561. return [info]
  1562. class MyVideoIE(InfoExtractor):
  1563. """Information Extractor for myvideo.de."""
  1564. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1565. IE_NAME = u'myvideo'
  1566. # Original Code from: https://github.com/dersphere/plugin.video.myvideo_de.git
  1567. # Released into the Public Domain by Tristan Fischer on 2013-05-19
  1568. # https://github.com/rg3/youtube-dl/pull/842
  1569. def __rc4crypt(self,data, key):
  1570. x = 0
  1571. box = list(range(256))
  1572. for i in list(range(256)):
  1573. x = (x + box[i] + compat_ord(key[i % len(key)])) % 256
  1574. box[i], box[x] = box[x], box[i]
  1575. x = 0
  1576. y = 0
  1577. out = ''
  1578. for char in data:
  1579. x = (x + 1) % 256
  1580. y = (y + box[x]) % 256
  1581. box[x], box[y] = box[y], box[x]
  1582. out += chr(compat_ord(char) ^ box[(box[x] + box[y]) % 256])
  1583. return out
  1584. def __md5(self,s):
  1585. return hashlib.md5(s).hexdigest().encode()
  1586. def _real_extract(self,url):
  1587. mobj = re.match(self._VALID_URL, url)
  1588. if mobj is None:
  1589. raise ExtractorError(u'invalid URL: %s' % url)
  1590. video_id = mobj.group(1)
  1591. GK = (
  1592. b'WXpnME1EZGhNRGhpTTJNM01XVmhOREU0WldNNVpHTTJOakpt'
  1593. b'TW1FMU5tVTBNR05pWkRaa05XRXhNVFJoWVRVd1ptSXhaVEV3'
  1594. b'TnpsbA0KTVRkbU1tSTRNdz09'
  1595. )
  1596. # Get video webpage
  1597. webpage_url = 'http://www.myvideo.de/watch/%s' % video_id
  1598. webpage = self._download_webpage(webpage_url, video_id)
  1599. mobj = re.search('source src=\'(.+?)[.]([^.]+)\'', webpage)
  1600. if mobj is not None:
  1601. self.report_extraction(video_id)
  1602. video_url = mobj.group(1) + '.flv'
  1603. video_title = self._html_search_regex('<title>([^<]+)</title>',
  1604. webpage, u'title')
  1605. video_ext = self._search_regex('[.](.+?)$', video_url, u'extension')
  1606. return [{
  1607. 'id': video_id,
  1608. 'url': video_url,
  1609. 'uploader': None,
  1610. 'upload_date': None,
  1611. 'title': video_title,
  1612. 'ext': u'flv',
  1613. }]
  1614. # try encxml
  1615. mobj = re.search('var flashvars={(.+?)}', webpage)
  1616. if mobj is None:
  1617. raise ExtractorError(u'Unable to extract video')
  1618. params = {}
  1619. encxml = ''
  1620. sec = mobj.group(1)
  1621. for (a, b) in re.findall('(.+?):\'(.+?)\',?', sec):
  1622. if not a == '_encxml':
  1623. params[a] = b
  1624. else:
  1625. encxml = compat_urllib_parse.unquote(b)
  1626. if not params.get('domain'):
  1627. params['domain'] = 'www.myvideo.de'
  1628. xmldata_url = '%s?%s' % (encxml, compat_urllib_parse.urlencode(params))
  1629. if 'flash_playertype=MTV' in xmldata_url:
  1630. self._downloader.report_warning(u'avoiding MTV player')
  1631. xmldata_url = (
  1632. 'http://www.myvideo.de/dynamic/get_player_video_xml.php'
  1633. '?flash_playertype=D&ID=%s&_countlimit=4&autorun=yes'
  1634. ) % video_id
  1635. # get enc data
  1636. enc_data = self._download_webpage(xmldata_url, video_id).split('=')[1]
  1637. enc_data_b = binascii.unhexlify(enc_data)
  1638. sk = self.__md5(
  1639. base64.b64decode(base64.b64decode(GK)) +
  1640. self.__md5(
  1641. str(video_id).encode('utf-8')
  1642. )
  1643. )
  1644. dec_data = self.__rc4crypt(enc_data_b, sk)
  1645. # extracting infos
  1646. self.report_extraction(video_id)
  1647. video_url = None
  1648. mobj = re.search('connectionurl=\'(.*?)\'', dec_data)
  1649. if mobj:
  1650. video_url = compat_urllib_parse.unquote(mobj.group(1))
  1651. if 'myvideo2flash' in video_url:
  1652. self._downloader.report_warning(u'forcing RTMPT ...')
  1653. video_url = video_url.replace('rtmpe://', 'rtmpt://')
  1654. if not video_url:
  1655. # extract non rtmp videos
  1656. mobj = re.search('path=\'(http.*?)\' source=\'(.*?)\'', dec_data)
  1657. if mobj is None:
  1658. raise ExtractorError(u'unable to extract url')
  1659. video_url = compat_urllib_parse.unquote(mobj.group(1)) + compat_urllib_parse.unquote(mobj.group(2))
  1660. video_file = self._search_regex('source=\'(.*?)\'', dec_data, u'video file')
  1661. video_file = compat_urllib_parse.unquote(video_file)
  1662. if not video_file.endswith('f4m'):
  1663. ppath, prefix = video_file.split('.')
  1664. video_playpath = '%s:%s' % (prefix, ppath)
  1665. video_hls_playlist = ''
  1666. else:
  1667. video_playpath = ''
  1668. video_hls_playlist = (
  1669. video_filepath + video_file
  1670. ).replace('.f4m', '.m3u8')
  1671. video_swfobj = self._search_regex('swfobject.embedSWF\(\'(.+?)\'', webpage, u'swfobj')
  1672. video_swfobj = compat_urllib_parse.unquote(video_swfobj)
  1673. video_title = self._html_search_regex("<h1(?: class='globalHd')?>(.*?)</h1>",
  1674. webpage, u'title')
  1675. return [{
  1676. 'id': video_id,
  1677. 'url': video_url,
  1678. 'tc_url': video_url,
  1679. 'uploader': None,
  1680. 'upload_date': None,
  1681. 'title': video_title,
  1682. 'ext': u'flv',
  1683. 'play_path': video_playpath,
  1684. 'video_file': video_file,
  1685. 'video_hls_playlist': video_hls_playlist,
  1686. 'player_url': video_swfobj,
  1687. }]
  1688. class ComedyCentralIE(InfoExtractor):
  1689. """Information extractor for The Daily Show and Colbert Report """
  1690. # urls can be abbreviations like :thedailyshow or :colbert
  1691. # urls for episodes like:
  1692. # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
  1693. # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
  1694. # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
  1695. _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
  1696. |(https?://)?(www\.)?
  1697. (?P<showname>thedailyshow|colbertnation)\.com/
  1698. (full-episodes/(?P<episode>.*)|
  1699. (?P<clip>
  1700. (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
  1701. |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
  1702. $"""
  1703. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  1704. _video_extensions = {
  1705. '3500': 'mp4',
  1706. '2200': 'mp4',
  1707. '1700': 'mp4',
  1708. '1200': 'mp4',
  1709. '750': 'mp4',
  1710. '400': 'mp4',
  1711. }
  1712. _video_dimensions = {
  1713. '3500': '1280x720',
  1714. '2200': '960x540',
  1715. '1700': '768x432',
  1716. '1200': '640x360',
  1717. '750': '512x288',
  1718. '400': '384x216',
  1719. }
  1720. @classmethod
  1721. def suitable(cls, url):
  1722. """Receives a URL and returns True if suitable for this IE."""
  1723. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1724. def _print_formats(self, formats):
  1725. print('Available formats:')
  1726. for x in formats:
  1727. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  1728. def _real_extract(self, url):
  1729. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1730. if mobj is None:
  1731. raise ExtractorError(u'Invalid URL: %s' % url)
  1732. if mobj.group('shortname'):
  1733. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  1734. url = u'http://www.thedailyshow.com/full-episodes/'
  1735. else:
  1736. url = u'http://www.colbertnation.com/full-episodes/'
  1737. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1738. assert mobj is not None
  1739. if mobj.group('clip'):
  1740. if mobj.group('showname') == 'thedailyshow':
  1741. epTitle = mobj.group('tdstitle')
  1742. else:
  1743. epTitle = mobj.group('cntitle')
  1744. dlNewest = False
  1745. else:
  1746. dlNewest = not mobj.group('episode')
  1747. if dlNewest:
  1748. epTitle = mobj.group('showname')
  1749. else:
  1750. epTitle = mobj.group('episode')
  1751. self.report_extraction(epTitle)
  1752. webpage,htmlHandle = self._download_webpage_handle(url, epTitle)
  1753. if dlNewest:
  1754. url = htmlHandle.geturl()
  1755. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1756. if mobj is None:
  1757. raise ExtractorError(u'Invalid redirected URL: ' + url)
  1758. if mobj.group('episode') == '':
  1759. raise ExtractorError(u'Redirected URL is still not specific: ' + url)
  1760. epTitle = mobj.group('episode')
  1761. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
  1762. if len(mMovieParams) == 0:
  1763. # The Colbert Report embeds the information in a without
  1764. # a URL prefix; so extract the alternate reference
  1765. # and then add the URL prefix manually.
  1766. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
  1767. if len(altMovieParams) == 0:
  1768. raise ExtractorError(u'unable to find Flash URL in webpage ' + url)
  1769. else:
  1770. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  1771. uri = mMovieParams[0][1]
  1772. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  1773. indexXml = self._download_webpage(indexUrl, epTitle,
  1774. u'Downloading show index',
  1775. u'unable to download episode index')
  1776. results = []
  1777. idoc = xml.etree.ElementTree.fromstring(indexXml)
  1778. itemEls = idoc.findall('.//item')
  1779. for partNum,itemEl in enumerate(itemEls):
  1780. mediaId = itemEl.findall('./guid')[0].text
  1781. shortMediaId = mediaId.split(':')[-1]
  1782. showId = mediaId.split(':')[-2].replace('.com', '')
  1783. officialTitle = itemEl.findall('./title')[0].text
  1784. officialDate = unified_strdate(itemEl.findall('./pubDate')[0].text)
  1785. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  1786. compat_urllib_parse.urlencode({'uri': mediaId}))
  1787. configXml = self._download_webpage(configUrl, epTitle,
  1788. u'Downloading configuration for %s' % shortMediaId)
  1789. cdoc = xml.etree.ElementTree.fromstring(configXml)
  1790. turls = []
  1791. for rendition in cdoc.findall('.//rendition'):
  1792. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  1793. turls.append(finfo)
  1794. if len(turls) == 0:
  1795. self._downloader.report_error(u'unable to download ' + mediaId + ': No videos found')
  1796. continue
  1797. if self._downloader.params.get('listformats', None):
  1798. self._print_formats([i[0] for i in turls])
  1799. return
  1800. # For now, just pick the highest bitrate
  1801. format,rtmp_video_url = turls[-1]
  1802. # Get the format arg from the arg stream
  1803. req_format = self._downloader.params.get('format', None)
  1804. # Select format if we can find one
  1805. for f,v in turls:
  1806. if f == req_format:
  1807. format, rtmp_video_url = f, v
  1808. break
  1809. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
  1810. if not m:
  1811. raise ExtractorError(u'Cannot transform RTMP url')
  1812. base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
  1813. video_url = base + m.group('finalid')
  1814. effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
  1815. info = {
  1816. 'id': shortMediaId,
  1817. 'url': video_url,
  1818. 'uploader': showId,
  1819. 'upload_date': officialDate,
  1820. 'title': effTitle,
  1821. 'ext': 'mp4',
  1822. 'format': format,
  1823. 'thumbnail': None,
  1824. 'description': officialTitle,
  1825. }
  1826. results.append(info)
  1827. return results
  1828. class EscapistIE(InfoExtractor):
  1829. """Information extractor for The Escapist """
  1830. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  1831. IE_NAME = u'escapist'
  1832. def _real_extract(self, url):
  1833. mobj = re.match(self._VALID_URL, url)
  1834. if mobj is None:
  1835. raise ExtractorError(u'Invalid URL: %s' % url)
  1836. showName = mobj.group('showname')
  1837. videoId = mobj.group('episode')
  1838. self.report_extraction(videoId)
  1839. webpage = self._download_webpage(url, videoId)
  1840. videoDesc = self._html_search_regex('<meta name="description" content="([^"]*)"',
  1841. webpage, u'description', fatal=False)
  1842. imgUrl = self._html_search_regex('<meta property="og:image" content="([^"]*)"',
  1843. webpage, u'thumbnail', fatal=False)
  1844. playerUrl = self._html_search_regex('<meta property="og:video" content="([^"]*)"',
  1845. webpage, u'player url')
  1846. title = self._html_search_regex('<meta name="title" content="([^"]*)"',
  1847. webpage, u'player url').split(' : ')[-1]
  1848. configUrl = self._search_regex('config=(.*)$', playerUrl, u'config url')
  1849. configUrl = compat_urllib_parse.unquote(configUrl)
  1850. configJSON = self._download_webpage(configUrl, videoId,
  1851. u'Downloading configuration',
  1852. u'unable to download configuration')
  1853. # Technically, it's JavaScript, not JSON
  1854. configJSON = configJSON.replace("'", '"')
  1855. try:
  1856. config = json.loads(configJSON)
  1857. except (ValueError,) as err:
  1858. raise ExtractorError(u'Invalid JSON in configuration file: ' + compat_str(err))
  1859. playlist = config['playlist']
  1860. videoUrl = playlist[1]['url']
  1861. info = {
  1862. 'id': videoId,
  1863. 'url': videoUrl,
  1864. 'uploader': showName,
  1865. 'upload_date': None,
  1866. 'title': title,
  1867. 'ext': 'mp4',
  1868. 'thumbnail': imgUrl,
  1869. 'description': videoDesc,
  1870. 'player_url': playerUrl,
  1871. }
  1872. return [info]
  1873. class CollegeHumorIE(InfoExtractor):
  1874. """Information extractor for collegehumor.com"""
  1875. _WORKING = False
  1876. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  1877. IE_NAME = u'collegehumor'
  1878. def report_manifest(self, video_id):
  1879. """Report information extraction."""
  1880. self.to_screen(u'%s: Downloading XML manifest' % video_id)
  1881. def _real_extract(self, url):
  1882. mobj = re.match(self._VALID_URL, url)
  1883. if mobj is None:
  1884. raise ExtractorError(u'Invalid URL: %s' % url)
  1885. video_id = mobj.group('videoid')
  1886. info = {
  1887. 'id': video_id,
  1888. 'uploader': None,
  1889. 'upload_date': None,
  1890. }
  1891. self.report_extraction(video_id)
  1892. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  1893. try:
  1894. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  1895. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1896. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  1897. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  1898. try:
  1899. videoNode = mdoc.findall('./video')[0]
  1900. info['description'] = videoNode.findall('./description')[0].text
  1901. info['title'] = videoNode.findall('./caption')[0].text
  1902. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  1903. manifest_url = videoNode.findall('./file')[0].text
  1904. except IndexError:
  1905. raise ExtractorError(u'Invalid metadata XML file')
  1906. manifest_url += '?hdcore=2.10.3'
  1907. self.report_manifest(video_id)
  1908. try:
  1909. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  1910. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1911. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  1912. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  1913. try:
  1914. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  1915. node_id = media_node.attrib['url']
  1916. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  1917. except IndexError as err:
  1918. raise ExtractorError(u'Invalid manifest file')
  1919. url_pr = compat_urllib_parse_urlparse(manifest_url)
  1920. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  1921. info['url'] = url
  1922. info['ext'] = 'f4f'
  1923. return [info]
  1924. class XVideosIE(InfoExtractor):
  1925. """Information extractor for xvideos.com"""
  1926. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  1927. IE_NAME = u'xvideos'
  1928. def _real_extract(self, url):
  1929. mobj = re.match(self._VALID_URL, url)
  1930. if mobj is None:
  1931. raise ExtractorError(u'Invalid URL: %s' % url)
  1932. video_id = mobj.group(1)
  1933. webpage = self._download_webpage(url, video_id)
  1934. self.report_extraction(video_id)
  1935. # Extract video URL
  1936. video_url = compat_urllib_parse.unquote(self._search_regex(r'flv_url=(.+?)&',
  1937. webpage, u'video URL'))
  1938. # Extract title
  1939. video_title = self._html_search_regex(r'<title>(.*?)\s+-\s+XVID',
  1940. webpage, u'title')
  1941. # Extract video thumbnail
  1942. 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)',
  1943. webpage, u'thumbnail', fatal=False)
  1944. info = {
  1945. 'id': video_id,
  1946. 'url': video_url,
  1947. 'uploader': None,
  1948. 'upload_date': None,
  1949. 'title': video_title,
  1950. 'ext': 'flv',
  1951. 'thumbnail': video_thumbnail,
  1952. 'description': None,
  1953. }
  1954. return [info]
  1955. class SoundcloudIE(InfoExtractor):
  1956. """Information extractor for soundcloud.com
  1957. To access the media, the uid of the song and a stream token
  1958. must be extracted from the page source and the script must make
  1959. a request to media.soundcloud.com/crossdomain.xml. Then
  1960. the media can be grabbed by requesting from an url composed
  1961. of the stream token and uid
  1962. """
  1963. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  1964. IE_NAME = u'soundcloud'
  1965. def report_resolve(self, video_id):
  1966. """Report information extraction."""
  1967. self.to_screen(u'%s: Resolving id' % video_id)
  1968. def _real_extract(self, url):
  1969. mobj = re.match(self._VALID_URL, url)
  1970. if mobj is None:
  1971. raise ExtractorError(u'Invalid URL: %s' % url)
  1972. # extract uploader (which is in the url)
  1973. uploader = mobj.group(1)
  1974. # extract simple title (uploader + slug of song title)
  1975. slug_title = mobj.group(2)
  1976. simple_title = uploader + u'-' + slug_title
  1977. full_title = '%s/%s' % (uploader, slug_title)
  1978. self.report_resolve(full_title)
  1979. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  1980. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  1981. info_json = self._download_webpage(resolv_url, full_title, u'Downloading info JSON')
  1982. info = json.loads(info_json)
  1983. video_id = info['id']
  1984. self.report_extraction(full_title)
  1985. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  1986. stream_json = self._download_webpage(streams_url, full_title,
  1987. u'Downloading stream definitions',
  1988. u'unable to download stream definitions')
  1989. streams = json.loads(stream_json)
  1990. mediaURL = streams['http_mp3_128_url']
  1991. upload_date = unified_strdate(info['created_at'])
  1992. return [{
  1993. 'id': info['id'],
  1994. 'url': mediaURL,
  1995. 'uploader': info['user']['username'],
  1996. 'upload_date': upload_date,
  1997. 'title': info['title'],
  1998. 'ext': u'mp3',
  1999. 'description': info['description'],
  2000. }]
  2001. class SoundcloudSetIE(InfoExtractor):
  2002. """Information extractor for soundcloud.com sets
  2003. To access the media, the uid of the song and a stream token
  2004. must be extracted from the page source and the script must make
  2005. a request to media.soundcloud.com/crossdomain.xml. Then
  2006. the media can be grabbed by requesting from an url composed
  2007. of the stream token and uid
  2008. """
  2009. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
  2010. IE_NAME = u'soundcloud:set'
  2011. def report_resolve(self, video_id):
  2012. """Report information extraction."""
  2013. self.to_screen(u'%s: Resolving id' % video_id)
  2014. def _real_extract(self, url):
  2015. mobj = re.match(self._VALID_URL, url)
  2016. if mobj is None:
  2017. raise ExtractorError(u'Invalid URL: %s' % url)
  2018. # extract uploader (which is in the url)
  2019. uploader = mobj.group(1)
  2020. # extract simple title (uploader + slug of song title)
  2021. slug_title = mobj.group(2)
  2022. simple_title = uploader + u'-' + slug_title
  2023. full_title = '%s/sets/%s' % (uploader, slug_title)
  2024. self.report_resolve(full_title)
  2025. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  2026. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2027. info_json = self._download_webpage(resolv_url, full_title)
  2028. videos = []
  2029. info = json.loads(info_json)
  2030. if 'errors' in info:
  2031. for err in info['errors']:
  2032. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
  2033. return
  2034. self.report_extraction(full_title)
  2035. for track in info['tracks']:
  2036. video_id = track['id']
  2037. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2038. stream_json = self._download_webpage(streams_url, video_id, u'Downloading track info JSON')
  2039. self.report_extraction(video_id)
  2040. streams = json.loads(stream_json)
  2041. mediaURL = streams['http_mp3_128_url']
  2042. videos.append({
  2043. 'id': video_id,
  2044. 'url': mediaURL,
  2045. 'uploader': track['user']['username'],
  2046. 'upload_date': unified_strdate(track['created_at']),
  2047. 'title': track['title'],
  2048. 'ext': u'mp3',
  2049. 'description': track['description'],
  2050. })
  2051. return videos
  2052. class InfoQIE(InfoExtractor):
  2053. """Information extractor for infoq.com"""
  2054. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2055. def _real_extract(self, url):
  2056. mobj = re.match(self._VALID_URL, url)
  2057. if mobj is None:
  2058. raise ExtractorError(u'Invalid URL: %s' % url)
  2059. webpage = self._download_webpage(url, video_id=url)
  2060. self.report_extraction(url)
  2061. # Extract video URL
  2062. mobj = re.search(r"jsclassref ?= ?'([^']*)'", webpage)
  2063. if mobj is None:
  2064. raise ExtractorError(u'Unable to extract video url')
  2065. real_id = compat_urllib_parse.unquote(base64.b64decode(mobj.group(1).encode('ascii')).decode('utf-8'))
  2066. video_url = 'rtmpe://video.infoq.com/cfx/st/' + real_id
  2067. # Extract title
  2068. video_title = self._search_regex(r'contentTitle = "(.*?)";',
  2069. webpage, u'title')
  2070. # Extract description
  2071. video_description = self._html_search_regex(r'<meta name="description" content="(.*)"(?:\s*/)?>',
  2072. webpage, u'description', fatal=False)
  2073. video_filename = video_url.split('/')[-1]
  2074. video_id, extension = video_filename.split('.')
  2075. info = {
  2076. 'id': video_id,
  2077. 'url': video_url,
  2078. 'uploader': None,
  2079. 'upload_date': None,
  2080. 'title': video_title,
  2081. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  2082. 'thumbnail': None,
  2083. 'description': video_description,
  2084. }
  2085. return [info]
  2086. class MixcloudIE(InfoExtractor):
  2087. """Information extractor for www.mixcloud.com"""
  2088. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  2089. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2090. IE_NAME = u'mixcloud'
  2091. def report_download_json(self, file_id):
  2092. """Report JSON download."""
  2093. self.to_screen(u'Downloading json')
  2094. def get_urls(self, jsonData, fmt, bitrate='best'):
  2095. """Get urls from 'audio_formats' section in json"""
  2096. file_url = None
  2097. try:
  2098. bitrate_list = jsonData[fmt]
  2099. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2100. bitrate = max(bitrate_list) # select highest
  2101. url_list = jsonData[fmt][bitrate]
  2102. except TypeError: # we have no bitrate info.
  2103. url_list = jsonData[fmt]
  2104. return url_list
  2105. def check_urls(self, url_list):
  2106. """Returns 1st active url from list"""
  2107. for url in url_list:
  2108. try:
  2109. compat_urllib_request.urlopen(url)
  2110. return url
  2111. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2112. url = None
  2113. return None
  2114. def _print_formats(self, formats):
  2115. print('Available formats:')
  2116. for fmt in formats.keys():
  2117. for b in formats[fmt]:
  2118. try:
  2119. ext = formats[fmt][b][0]
  2120. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  2121. except TypeError: # we have no bitrate info
  2122. ext = formats[fmt][0]
  2123. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  2124. break
  2125. def _real_extract(self, url):
  2126. mobj = re.match(self._VALID_URL, url)
  2127. if mobj is None:
  2128. raise ExtractorError(u'Invalid URL: %s' % url)
  2129. # extract uploader & filename from url
  2130. uploader = mobj.group(1).decode('utf-8')
  2131. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2132. # construct API request
  2133. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2134. # retrieve .json file with links to files
  2135. request = compat_urllib_request.Request(file_url)
  2136. try:
  2137. self.report_download_json(file_url)
  2138. jsonData = compat_urllib_request.urlopen(request).read()
  2139. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2140. raise ExtractorError(u'Unable to retrieve file: %s' % compat_str(err))
  2141. # parse JSON
  2142. json_data = json.loads(jsonData)
  2143. player_url = json_data['player_swf_url']
  2144. formats = dict(json_data['audio_formats'])
  2145. req_format = self._downloader.params.get('format', None)
  2146. bitrate = None
  2147. if self._downloader.params.get('listformats', None):
  2148. self._print_formats(formats)
  2149. return
  2150. if req_format is None or req_format == 'best':
  2151. for format_param in formats.keys():
  2152. url_list = self.get_urls(formats, format_param)
  2153. # check urls
  2154. file_url = self.check_urls(url_list)
  2155. if file_url is not None:
  2156. break # got it!
  2157. else:
  2158. if req_format not in formats:
  2159. raise ExtractorError(u'Format is not available')
  2160. url_list = self.get_urls(formats, req_format)
  2161. file_url = self.check_urls(url_list)
  2162. format_param = req_format
  2163. return [{
  2164. 'id': file_id.decode('utf-8'),
  2165. 'url': file_url.decode('utf-8'),
  2166. 'uploader': uploader.decode('utf-8'),
  2167. 'upload_date': None,
  2168. 'title': json_data['name'],
  2169. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2170. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2171. 'thumbnail': json_data['thumbnail_url'],
  2172. 'description': json_data['description'],
  2173. 'player_url': player_url.decode('utf-8'),
  2174. }]
  2175. class StanfordOpenClassroomIE(InfoExtractor):
  2176. """Information extractor for Stanford's Open ClassRoom"""
  2177. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2178. IE_NAME = u'stanfordoc'
  2179. def _real_extract(self, url):
  2180. mobj = re.match(self._VALID_URL, url)
  2181. if mobj is None:
  2182. raise ExtractorError(u'Invalid URL: %s' % url)
  2183. if mobj.group('course') and mobj.group('video'): # A specific video
  2184. course = mobj.group('course')
  2185. video = mobj.group('video')
  2186. info = {
  2187. 'id': course + '_' + video,
  2188. 'uploader': None,
  2189. 'upload_date': None,
  2190. }
  2191. self.report_extraction(info['id'])
  2192. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2193. xmlUrl = baseUrl + video + '.xml'
  2194. try:
  2195. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2196. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2197. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  2198. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2199. try:
  2200. info['title'] = mdoc.findall('./title')[0].text
  2201. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2202. except IndexError:
  2203. raise ExtractorError(u'Invalid metadata XML file')
  2204. info['ext'] = info['url'].rpartition('.')[2]
  2205. return [info]
  2206. elif mobj.group('course'): # A course page
  2207. course = mobj.group('course')
  2208. info = {
  2209. 'id': course,
  2210. 'type': 'playlist',
  2211. 'uploader': None,
  2212. 'upload_date': None,
  2213. }
  2214. coursepage = self._download_webpage(url, info['id'],
  2215. note='Downloading course info page',
  2216. errnote='Unable to download course info page')
  2217. info['title'] = self._html_search_regex('<h1>([^<]+)</h1>', coursepage, 'title', default=info['id'])
  2218. info['description'] = self._html_search_regex('<description>([^<]+)</description>',
  2219. coursepage, u'description', fatal=False)
  2220. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2221. info['list'] = [
  2222. {
  2223. 'type': 'reference',
  2224. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2225. }
  2226. for vpage in links]
  2227. results = []
  2228. for entry in info['list']:
  2229. assert entry['type'] == 'reference'
  2230. results += self.extract(entry['url'])
  2231. return results
  2232. else: # Root page
  2233. info = {
  2234. 'id': 'Stanford OpenClassroom',
  2235. 'type': 'playlist',
  2236. 'uploader': None,
  2237. 'upload_date': None,
  2238. }
  2239. self.report_download_webpage(info['id'])
  2240. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2241. try:
  2242. rootpage = compat_urllib_request.urlopen(rootURL).read()
  2243. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2244. raise ExtractorError(u'Unable to download course info page: ' + compat_str(err))
  2245. info['title'] = info['id']
  2246. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2247. info['list'] = [
  2248. {
  2249. 'type': 'reference',
  2250. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2251. }
  2252. for cpage in links]
  2253. results = []
  2254. for entry in info['list']:
  2255. assert entry['type'] == 'reference'
  2256. results += self.extract(entry['url'])
  2257. return results
  2258. class MTVIE(InfoExtractor):
  2259. """Information extractor for MTV.com"""
  2260. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2261. IE_NAME = u'mtv'
  2262. def _real_extract(self, url):
  2263. mobj = re.match(self._VALID_URL, url)
  2264. if mobj is None:
  2265. raise ExtractorError(u'Invalid URL: %s' % url)
  2266. if not mobj.group('proto'):
  2267. url = 'http://' + url
  2268. video_id = mobj.group('videoid')
  2269. webpage = self._download_webpage(url, video_id)
  2270. song_name = self._html_search_regex(r'<meta name="mtv_vt" content="([^"]+)"/>',
  2271. webpage, u'song name', fatal=False)
  2272. video_title = self._html_search_regex(r'<meta name="mtv_an" content="([^"]+)"/>',
  2273. webpage, u'title')
  2274. mtvn_uri = self._html_search_regex(r'<meta name="mtvn_uri" content="([^"]+)"/>',
  2275. webpage, u'mtvn_uri', fatal=False)
  2276. content_id = self._search_regex(r'MTVN.Player.defaultPlaylistId = ([0-9]+);',
  2277. webpage, u'content id', fatal=False)
  2278. 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
  2279. self.report_extraction(video_id)
  2280. request = compat_urllib_request.Request(videogen_url)
  2281. try:
  2282. metadataXml = compat_urllib_request.urlopen(request).read()
  2283. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2284. raise ExtractorError(u'Unable to download video metadata: %s' % compat_str(err))
  2285. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2286. renditions = mdoc.findall('.//rendition')
  2287. # For now, always pick the highest quality.
  2288. rendition = renditions[-1]
  2289. try:
  2290. _,_,ext = rendition.attrib['type'].partition('/')
  2291. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2292. video_url = rendition.find('./src').text
  2293. except KeyError:
  2294. raise ExtractorError('Invalid rendition field.')
  2295. info = {
  2296. 'id': video_id,
  2297. 'url': video_url,
  2298. 'uploader': performer,
  2299. 'upload_date': None,
  2300. 'title': video_title,
  2301. 'ext': ext,
  2302. 'format': format,
  2303. }
  2304. return [info]
  2305. class YoukuIE(InfoExtractor):
  2306. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  2307. def _gen_sid(self):
  2308. nowTime = int(time.time() * 1000)
  2309. random1 = random.randint(1000,1998)
  2310. random2 = random.randint(1000,9999)
  2311. return "%d%d%d" %(nowTime,random1,random2)
  2312. def _get_file_ID_mix_string(self, seed):
  2313. mixed = []
  2314. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  2315. seed = float(seed)
  2316. for i in range(len(source)):
  2317. seed = (seed * 211 + 30031 ) % 65536
  2318. index = math.floor(seed / 65536 * len(source) )
  2319. mixed.append(source[int(index)])
  2320. source.remove(source[int(index)])
  2321. #return ''.join(mixed)
  2322. return mixed
  2323. def _get_file_id(self, fileId, seed):
  2324. mixed = self._get_file_ID_mix_string(seed)
  2325. ids = fileId.split('*')
  2326. realId = []
  2327. for ch in ids:
  2328. if ch:
  2329. realId.append(mixed[int(ch)])
  2330. return ''.join(realId)
  2331. def _real_extract(self, url):
  2332. mobj = re.match(self._VALID_URL, url)
  2333. if mobj is None:
  2334. raise ExtractorError(u'Invalid URL: %s' % url)
  2335. video_id = mobj.group('ID')
  2336. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  2337. jsondata = self._download_webpage(info_url, video_id)
  2338. self.report_extraction(video_id)
  2339. try:
  2340. config = json.loads(jsondata)
  2341. video_title = config['data'][0]['title']
  2342. seed = config['data'][0]['seed']
  2343. format = self._downloader.params.get('format', None)
  2344. supported_format = list(config['data'][0]['streamfileids'].keys())
  2345. if format is None or format == 'best':
  2346. if 'hd2' in supported_format:
  2347. format = 'hd2'
  2348. else:
  2349. format = 'flv'
  2350. ext = u'flv'
  2351. elif format == 'worst':
  2352. format = 'mp4'
  2353. ext = u'mp4'
  2354. else:
  2355. format = 'flv'
  2356. ext = u'flv'
  2357. fileid = config['data'][0]['streamfileids'][format]
  2358. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  2359. except (UnicodeDecodeError, ValueError, KeyError):
  2360. raise ExtractorError(u'Unable to extract info section')
  2361. files_info=[]
  2362. sid = self._gen_sid()
  2363. fileid = self._get_file_id(fileid, seed)
  2364. #column 8,9 of fileid represent the segment number
  2365. #fileid[7:9] should be changed
  2366. for index, key in enumerate(keys):
  2367. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  2368. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  2369. info = {
  2370. 'id': '%s_part%02d' % (video_id, index),
  2371. 'url': download_url,
  2372. 'uploader': None,
  2373. 'upload_date': None,
  2374. 'title': video_title,
  2375. 'ext': ext,
  2376. }
  2377. files_info.append(info)
  2378. return files_info
  2379. class XNXXIE(InfoExtractor):
  2380. """Information extractor for xnxx.com"""
  2381. _VALID_URL = r'^(?:https?://)?video\.xnxx\.com/video([0-9]+)/(.*)'
  2382. IE_NAME = u'xnxx'
  2383. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  2384. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  2385. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  2386. def _real_extract(self, url):
  2387. mobj = re.match(self._VALID_URL, url)
  2388. if mobj is None:
  2389. raise ExtractorError(u'Invalid URL: %s' % url)
  2390. video_id = mobj.group(1)
  2391. # Get webpage content
  2392. webpage = self._download_webpage(url, video_id)
  2393. video_url = self._search_regex(self.VIDEO_URL_RE,
  2394. webpage, u'video URL')
  2395. video_url = compat_urllib_parse.unquote(video_url)
  2396. video_title = self._html_search_regex(self.VIDEO_TITLE_RE,
  2397. webpage, u'title')
  2398. video_thumbnail = self._search_regex(self.VIDEO_THUMB_RE,
  2399. webpage, u'thumbnail', fatal=False)
  2400. return [{
  2401. 'id': video_id,
  2402. 'url': video_url,
  2403. 'uploader': None,
  2404. 'upload_date': None,
  2405. 'title': video_title,
  2406. 'ext': 'flv',
  2407. 'thumbnail': video_thumbnail,
  2408. 'description': None,
  2409. }]
  2410. class GooglePlusIE(InfoExtractor):
  2411. """Information extractor for plus.google.com."""
  2412. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:[^/]+/)*?posts/(\w+)'
  2413. IE_NAME = u'plus.google'
  2414. def _real_extract(self, url):
  2415. # Extract id from URL
  2416. mobj = re.match(self._VALID_URL, url)
  2417. if mobj is None:
  2418. raise ExtractorError(u'Invalid URL: %s' % url)
  2419. post_url = mobj.group(0)
  2420. video_id = mobj.group(1)
  2421. video_extension = 'flv'
  2422. # Step 1, Retrieve post webpage to extract further information
  2423. webpage = self._download_webpage(post_url, video_id, u'Downloading entry webpage')
  2424. self.report_extraction(video_id)
  2425. # Extract update date
  2426. upload_date = self._html_search_regex('title="Timestamp">(.*?)</a>',
  2427. webpage, u'upload date', fatal=False)
  2428. if upload_date:
  2429. # Convert timestring to a format suitable for filename
  2430. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  2431. upload_date = upload_date.strftime('%Y%m%d')
  2432. # Extract uploader
  2433. uploader = self._html_search_regex(r'rel\="author".*?>(.*?)</a>',
  2434. webpage, u'uploader', fatal=False)
  2435. # Extract title
  2436. # Get the first line for title
  2437. video_title = self._html_search_regex(r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]',
  2438. webpage, 'title', default=u'NA')
  2439. # Step 2, Stimulate clicking the image box to launch video
  2440. video_page = self._search_regex('"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]',
  2441. webpage, u'video page URL')
  2442. webpage = self._download_webpage(video_page, video_id, u'Downloading video page')
  2443. # Extract video links on video page
  2444. """Extract video links of all sizes"""
  2445. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  2446. mobj = re.findall(pattern, webpage)
  2447. if len(mobj) == 0:
  2448. raise ExtractorError(u'Unable to extract video links')
  2449. # Sort in resolution
  2450. links = sorted(mobj)
  2451. # Choose the lowest of the sort, i.e. highest resolution
  2452. video_url = links[-1]
  2453. # Only get the url. The resolution part in the tuple has no use anymore
  2454. video_url = video_url[-1]
  2455. # Treat escaped \u0026 style hex
  2456. try:
  2457. video_url = video_url.decode("unicode_escape")
  2458. except AttributeError: # Python 3
  2459. video_url = bytes(video_url, 'ascii').decode('unicode-escape')
  2460. return [{
  2461. 'id': video_id,
  2462. 'url': video_url,
  2463. 'uploader': uploader,
  2464. 'upload_date': upload_date,
  2465. 'title': video_title,
  2466. 'ext': video_extension,
  2467. }]
  2468. class NBAIE(InfoExtractor):
  2469. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*?)(?:/index\.html)?(?:\?.*)?$'
  2470. IE_NAME = u'nba'
  2471. def _real_extract(self, url):
  2472. mobj = re.match(self._VALID_URL, url)
  2473. if mobj is None:
  2474. raise ExtractorError(u'Invalid URL: %s' % url)
  2475. video_id = mobj.group(1)
  2476. webpage = self._download_webpage(url, video_id)
  2477. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  2478. shortened_video_id = video_id.rpartition('/')[2]
  2479. title = self._html_search_regex(r'<meta property="og:title" content="(.*?)"',
  2480. webpage, 'title', default=shortened_video_id).replace('NBA.com: ', '')
  2481. # It isn't there in the HTML it returns to us
  2482. # uploader_date = self._html_search_regex(r'<b>Date:</b> (.*?)</div>', webpage, 'upload_date', fatal=False)
  2483. description = self._html_search_regex(r'<meta name="description" (?:content|value)="(.*?)" />', webpage, 'description', fatal=False)
  2484. info = {
  2485. 'id': shortened_video_id,
  2486. 'url': video_url,
  2487. 'ext': 'mp4',
  2488. 'title': title,
  2489. # 'uploader_date': uploader_date,
  2490. 'description': description,
  2491. }
  2492. return [info]
  2493. class JustinTVIE(InfoExtractor):
  2494. """Information extractor for justin.tv and twitch.tv"""
  2495. # TODO: One broadcast may be split into multiple videos. The key
  2496. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  2497. # starts at 1 and increases. Can we treat all parts as one video?
  2498. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  2499. (?:
  2500. (?P<channelid>[^/]+)|
  2501. (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
  2502. (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
  2503. )
  2504. /?(?:\#.*)?$
  2505. """
  2506. _JUSTIN_PAGE_LIMIT = 100
  2507. IE_NAME = u'justin.tv'
  2508. def report_download_page(self, channel, offset):
  2509. """Report attempt to download a single page of videos."""
  2510. self.to_screen(u'%s: Downloading video information from %d to %d' %
  2511. (channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  2512. # Return count of items, list of *valid* items
  2513. def _parse_page(self, url, video_id):
  2514. webpage = self._download_webpage(url, video_id,
  2515. u'Downloading video info JSON',
  2516. u'unable to download video info JSON')
  2517. response = json.loads(webpage)
  2518. if type(response) != list:
  2519. error_text = response.get('error', 'unknown error')
  2520. raise ExtractorError(u'Justin.tv API: %s' % error_text)
  2521. info = []
  2522. for clip in response:
  2523. video_url = clip['video_file_url']
  2524. if video_url:
  2525. video_extension = os.path.splitext(video_url)[1][1:]
  2526. video_date = re.sub('-', '', clip['start_time'][:10])
  2527. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  2528. video_id = clip['id']
  2529. video_title = clip.get('title', video_id)
  2530. info.append({
  2531. 'id': video_id,
  2532. 'url': video_url,
  2533. 'title': video_title,
  2534. 'uploader': clip.get('channel_name', video_uploader_id),
  2535. 'uploader_id': video_uploader_id,
  2536. 'upload_date': video_date,
  2537. 'ext': video_extension,
  2538. })
  2539. return (len(response), info)
  2540. def _real_extract(self, url):
  2541. mobj = re.match(self._VALID_URL, url)
  2542. if mobj is None:
  2543. raise ExtractorError(u'invalid URL: %s' % url)
  2544. api_base = 'http://api.justin.tv'
  2545. paged = False
  2546. if mobj.group('channelid'):
  2547. paged = True
  2548. video_id = mobj.group('channelid')
  2549. api = api_base + '/channel/archives/%s.json' % video_id
  2550. elif mobj.group('chapterid'):
  2551. chapter_id = mobj.group('chapterid')
  2552. webpage = self._download_webpage(url, chapter_id)
  2553. m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
  2554. if not m:
  2555. raise ExtractorError(u'Cannot find archive of a chapter')
  2556. archive_id = m.group(1)
  2557. api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
  2558. chapter_info_xml = self._download_webpage(api, chapter_id,
  2559. note=u'Downloading chapter information',
  2560. errnote=u'Chapter information download failed')
  2561. doc = xml.etree.ElementTree.fromstring(chapter_info_xml)
  2562. for a in doc.findall('.//archive'):
  2563. if archive_id == a.find('./id').text:
  2564. break
  2565. else:
  2566. raise ExtractorError(u'Could not find chapter in chapter information')
  2567. video_url = a.find('./video_file_url').text
  2568. video_ext = video_url.rpartition('.')[2] or u'flv'
  2569. chapter_api_url = u'https://api.twitch.tv/kraken/videos/c' + chapter_id
  2570. chapter_info_json = self._download_webpage(chapter_api_url, u'c' + chapter_id,
  2571. note='Downloading chapter metadata',
  2572. errnote='Download of chapter metadata failed')
  2573. chapter_info = json.loads(chapter_info_json)
  2574. bracket_start = int(doc.find('.//bracket_start').text)
  2575. bracket_end = int(doc.find('.//bracket_end').text)
  2576. # TODO determine start (and probably fix up file)
  2577. # youtube-dl -v http://www.twitch.tv/firmbelief/c/1757457
  2578. #video_url += u'?start=' + TODO:start_timestamp
  2579. # bracket_start is 13290, but we want 51670615
  2580. self._downloader.report_warning(u'Chapter detected, but we can just download the whole file. '
  2581. u'Chapter starts at %s and ends at %s' % (formatSeconds(bracket_start), formatSeconds(bracket_end)))
  2582. info = {
  2583. 'id': u'c' + chapter_id,
  2584. 'url': video_url,
  2585. 'ext': video_ext,
  2586. 'title': chapter_info['title'],
  2587. 'thumbnail': chapter_info['preview'],
  2588. 'description': chapter_info['description'],
  2589. 'uploader': chapter_info['channel']['display_name'],
  2590. 'uploader_id': chapter_info['channel']['name'],
  2591. }
  2592. return [info]
  2593. else:
  2594. video_id = mobj.group('videoid')
  2595. api = api_base + '/broadcast/by_archive/%s.json' % video_id
  2596. self.report_extraction(video_id)
  2597. info = []
  2598. offset = 0
  2599. limit = self._JUSTIN_PAGE_LIMIT
  2600. while True:
  2601. if paged:
  2602. self.report_download_page(video_id, offset)
  2603. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  2604. page_count, page_info = self._parse_page(page_url, video_id)
  2605. info.extend(page_info)
  2606. if not paged or page_count != limit:
  2607. break
  2608. offset += limit
  2609. return info
  2610. class FunnyOrDieIE(InfoExtractor):
  2611. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  2612. def _real_extract(self, url):
  2613. mobj = re.match(self._VALID_URL, url)
  2614. if mobj is None:
  2615. raise ExtractorError(u'invalid URL: %s' % url)
  2616. video_id = mobj.group('id')
  2617. webpage = self._download_webpage(url, video_id)
  2618. video_url = self._html_search_regex(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"',
  2619. webpage, u'video URL', flags=re.DOTALL)
  2620. title = self._html_search_regex((r"<h1 class='player_page_h1'.*?>(?P<title>.*?)</h1>",
  2621. r'<title>(?P<title>[^<]+?)</title>'), webpage, 'title', flags=re.DOTALL)
  2622. video_description = self._html_search_regex(r'<meta property="og:description" content="(?P<desc>.*?)"',
  2623. webpage, u'description', fatal=False, flags=re.DOTALL)
  2624. info = {
  2625. 'id': video_id,
  2626. 'url': video_url,
  2627. 'ext': 'mp4',
  2628. 'title': title,
  2629. 'description': video_description,
  2630. }
  2631. return [info]
  2632. class SteamIE(InfoExtractor):
  2633. _VALID_URL = r"""http://store\.steampowered\.com/
  2634. (agecheck/)?
  2635. (?P<urltype>video|app)/ #If the page is only for videos or for a game
  2636. (?P<gameID>\d+)/?
  2637. (?P<videoID>\d*)(?P<extra>\??) #For urltype == video we sometimes get the videoID
  2638. """
  2639. _VIDEO_PAGE_TEMPLATE = 'http://store.steampowered.com/video/%s/'
  2640. _AGECHECK_TEMPLATE = 'http://store.steampowered.com/agecheck/video/%s/?snr=1_agecheck_agecheck__age-gate&ageDay=1&ageMonth=January&ageYear=1970'
  2641. @classmethod
  2642. def suitable(cls, url):
  2643. """Receives a URL and returns True if suitable for this IE."""
  2644. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  2645. def _real_extract(self, url):
  2646. m = re.match(self._VALID_URL, url, re.VERBOSE)
  2647. gameID = m.group('gameID')
  2648. videourl = self._VIDEO_PAGE_TEMPLATE % gameID
  2649. webpage = self._download_webpage(videourl, gameID)
  2650. if re.search('<h2>Please enter your birth date to continue:</h2>', webpage) is not None:
  2651. videourl = self._AGECHECK_TEMPLATE % gameID
  2652. self.report_age_confirmation()
  2653. webpage = self._download_webpage(videourl, gameID)
  2654. self.report_extraction(gameID)
  2655. game_title = self._html_search_regex(r'<h2 class="pageheader">(.*?)</h2>',
  2656. webpage, 'game title')
  2657. urlRE = r"'movie_(?P<videoID>\d+)': \{\s*FILENAME: \"(?P<videoURL>[\w:/\.\?=]+)\"(,\s*MOVIE_NAME: \"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\},"
  2658. mweb = re.finditer(urlRE, webpage)
  2659. namesRE = r'<span class="title">(?P<videoName>.+?)</span>'
  2660. titles = re.finditer(namesRE, webpage)
  2661. thumbsRE = r'<img class="movie_thumb" src="(?P<thumbnail>.+?)">'
  2662. thumbs = re.finditer(thumbsRE, webpage)
  2663. videos = []
  2664. for vid,vtitle,thumb in zip(mweb,titles,thumbs):
  2665. video_id = vid.group('videoID')
  2666. title = vtitle.group('videoName')
  2667. video_url = vid.group('videoURL')
  2668. video_thumb = thumb.group('thumbnail')
  2669. if not video_url:
  2670. raise ExtractorError(u'Cannot find video url for %s' % video_id)
  2671. info = {
  2672. 'id':video_id,
  2673. 'url':video_url,
  2674. 'ext': 'flv',
  2675. 'title': unescapeHTML(title),
  2676. 'thumbnail': video_thumb
  2677. }
  2678. videos.append(info)
  2679. return [self.playlist_result(videos, gameID, game_title)]
  2680. class UstreamIE(InfoExtractor):
  2681. _VALID_URL = r'https?://www\.ustream\.tv/recorded/(?P<videoID>\d+)'
  2682. IE_NAME = u'ustream'
  2683. def _real_extract(self, url):
  2684. m = re.match(self._VALID_URL, url)
  2685. video_id = m.group('videoID')
  2686. video_url = u'http://tcdn.ustream.tv/video/%s' % video_id
  2687. webpage = self._download_webpage(url, video_id)
  2688. self.report_extraction(video_id)
  2689. video_title = self._html_search_regex(r'data-title="(?P<title>.+)"',
  2690. webpage, u'title')
  2691. uploader = self._html_search_regex(r'data-content-type="channel".*?>(?P<uploader>.*?)</a>',
  2692. webpage, u'uploader', fatal=False, flags=re.DOTALL)
  2693. thumbnail = self._html_search_regex(r'<link rel="image_src" href="(?P<thumb>.*?)"',
  2694. webpage, u'thumbnail', fatal=False)
  2695. info = {
  2696. 'id': video_id,
  2697. 'url': video_url,
  2698. 'ext': 'flv',
  2699. 'title': video_title,
  2700. 'uploader': uploader,
  2701. 'thumbnail': thumbnail,
  2702. }
  2703. return info
  2704. class WorldStarHipHopIE(InfoExtractor):
  2705. _VALID_URL = r'https?://(?:www|m)\.worldstar(?:candy|hiphop)\.com/videos/video\.php\?v=(?P<id>.*)'
  2706. IE_NAME = u'WorldStarHipHop'
  2707. def _real_extract(self, url):
  2708. m = re.match(self._VALID_URL, url)
  2709. video_id = m.group('id')
  2710. webpage_src = self._download_webpage(url, video_id)
  2711. video_url = self._search_regex(r'so\.addVariable\("file","(.*?)"\)',
  2712. webpage_src, u'video URL')
  2713. if 'mp4' in video_url:
  2714. ext = 'mp4'
  2715. else:
  2716. ext = 'flv'
  2717. video_title = self._html_search_regex(r"<title>(.*)</title>",
  2718. webpage_src, u'title')
  2719. # Getting thumbnail and if not thumbnail sets correct title for WSHH candy video.
  2720. thumbnail = self._html_search_regex(r'rel="image_src" href="(.*)" />',
  2721. webpage_src, u'thumbnail', fatal=False)
  2722. if not thumbnail:
  2723. _title = r"""candytitles.*>(.*)</span>"""
  2724. mobj = re.search(_title, webpage_src)
  2725. if mobj is not None:
  2726. video_title = mobj.group(1)
  2727. results = [{
  2728. 'id': video_id,
  2729. 'url' : video_url,
  2730. 'title' : video_title,
  2731. 'thumbnail' : thumbnail,
  2732. 'ext' : ext,
  2733. }]
  2734. return results
  2735. class RBMARadioIE(InfoExtractor):
  2736. _VALID_URL = r'https?://(?:www\.)?rbmaradio\.com/shows/(?P<videoID>[^/]+)$'
  2737. def _real_extract(self, url):
  2738. m = re.match(self._VALID_URL, url)
  2739. video_id = m.group('videoID')
  2740. webpage = self._download_webpage(url, video_id)
  2741. json_data = self._search_regex(r'window\.gon.*?gon\.show=(.+?);$',
  2742. webpage, u'json data', flags=re.MULTILINE)
  2743. try:
  2744. data = json.loads(json_data)
  2745. except ValueError as e:
  2746. raise ExtractorError(u'Invalid JSON: ' + str(e))
  2747. video_url = data['akamai_url'] + '&cbr=256'
  2748. url_parts = compat_urllib_parse_urlparse(video_url)
  2749. video_ext = url_parts.path.rpartition('.')[2]
  2750. info = {
  2751. 'id': video_id,
  2752. 'url': video_url,
  2753. 'ext': video_ext,
  2754. 'title': data['title'],
  2755. 'description': data.get('teaser_text'),
  2756. 'location': data.get('country_of_origin'),
  2757. 'uploader': data.get('host', {}).get('name'),
  2758. 'uploader_id': data.get('host', {}).get('slug'),
  2759. 'thumbnail': data.get('image', {}).get('large_url_2x'),
  2760. 'duration': data.get('duration'),
  2761. }
  2762. return [info]
  2763. class YouPornIE(InfoExtractor):
  2764. """Information extractor for youporn.com."""
  2765. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
  2766. def _print_formats(self, formats):
  2767. """Print all available formats"""
  2768. print(u'Available formats:')
  2769. print(u'ext\t\tformat')
  2770. print(u'---------------------------------')
  2771. for format in formats:
  2772. print(u'%s\t\t%s' % (format['ext'], format['format']))
  2773. def _specific(self, req_format, formats):
  2774. for x in formats:
  2775. if(x["format"]==req_format):
  2776. return x
  2777. return None
  2778. def _real_extract(self, url):
  2779. mobj = re.match(self._VALID_URL, url)
  2780. if mobj is None:
  2781. raise ExtractorError(u'Invalid URL: %s' % url)
  2782. video_id = mobj.group('videoid')
  2783. req = compat_urllib_request.Request(url)
  2784. req.add_header('Cookie', 'age_verified=1')
  2785. webpage = self._download_webpage(req, video_id)
  2786. # Get JSON parameters
  2787. json_params = self._search_regex(r'var currentVideo = new Video\((.*)\);', webpage, u'JSON parameters')
  2788. try:
  2789. params = json.loads(json_params)
  2790. except:
  2791. raise ExtractorError(u'Invalid JSON')
  2792. self.report_extraction(video_id)
  2793. try:
  2794. video_title = params['title']
  2795. upload_date = unified_strdate(params['release_date_f'])
  2796. video_description = params['description']
  2797. video_uploader = params['submitted_by']
  2798. thumbnail = params['thumbnails'][0]['image']
  2799. except KeyError:
  2800. raise ExtractorError('Missing JSON parameter: ' + sys.exc_info()[1])
  2801. # Get all of the formats available
  2802. DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
  2803. download_list_html = self._search_regex(DOWNLOAD_LIST_RE,
  2804. webpage, u'download list').strip()
  2805. # Get all of the links from the page
  2806. LINK_RE = r'(?s)<a href="(?P<url>[^"]+)">'
  2807. links = re.findall(LINK_RE, download_list_html)
  2808. if(len(links) == 0):
  2809. raise ExtractorError(u'ERROR: no known formats available for video')
  2810. self.to_screen(u'Links found: %d' % len(links))
  2811. formats = []
  2812. for link in links:
  2813. # A link looks like this:
  2814. # 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
  2815. # A path looks like this:
  2816. # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
  2817. video_url = unescapeHTML( link )
  2818. path = compat_urllib_parse_urlparse( video_url ).path
  2819. extension = os.path.splitext( path )[1][1:]
  2820. format = path.split('/')[4].split('_')[:2]
  2821. size = format[0]
  2822. bitrate = format[1]
  2823. format = "-".join( format )
  2824. # title = u'%s-%s-%s' % (video_title, size, bitrate)
  2825. formats.append({
  2826. 'id': video_id,
  2827. 'url': video_url,
  2828. 'uploader': video_uploader,
  2829. 'upload_date': upload_date,
  2830. 'title': video_title,
  2831. 'ext': extension,
  2832. 'format': format,
  2833. 'thumbnail': thumbnail,
  2834. 'description': video_description
  2835. })
  2836. if self._downloader.params.get('listformats', None):
  2837. self._print_formats(formats)
  2838. return
  2839. req_format = self._downloader.params.get('format', None)
  2840. self.to_screen(u'Format: %s' % req_format)
  2841. if req_format is None or req_format == 'best':
  2842. return [formats[0]]
  2843. elif req_format == 'worst':
  2844. return [formats[-1]]
  2845. elif req_format in ('-1', 'all'):
  2846. return formats
  2847. else:
  2848. format = self._specific( req_format, formats )
  2849. if result is None:
  2850. raise ExtractorError(u'Requested format not available')
  2851. return [format]
  2852. class PornotubeIE(InfoExtractor):
  2853. """Information extractor for pornotube.com."""
  2854. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?pornotube\.com(/c/(?P<channel>[0-9]+))?(/m/(?P<videoid>[0-9]+))(/(?P<title>.+))$'
  2855. def _real_extract(self, url):
  2856. mobj = re.match(self._VALID_URL, url)
  2857. if mobj is None:
  2858. raise ExtractorError(u'Invalid URL: %s' % url)
  2859. video_id = mobj.group('videoid')
  2860. video_title = mobj.group('title')
  2861. # Get webpage content
  2862. webpage = self._download_webpage(url, video_id)
  2863. # Get the video URL
  2864. VIDEO_URL_RE = r'url: "(?P<url>http://video[0-9].pornotube.com/.+\.flv)",'
  2865. video_url = self._search_regex(VIDEO_URL_RE, webpage, u'video url')
  2866. video_url = compat_urllib_parse.unquote(video_url)
  2867. #Get the uploaded date
  2868. VIDEO_UPLOADED_RE = r'<div class="video_added_by">Added (?P<date>[0-9\/]+) by'
  2869. upload_date = self._html_search_regex(VIDEO_UPLOADED_RE, webpage, u'upload date', fatal=False)
  2870. if upload_date: upload_date = unified_strdate(upload_date)
  2871. info = {'id': video_id,
  2872. 'url': video_url,
  2873. 'uploader': None,
  2874. 'upload_date': upload_date,
  2875. 'title': video_title,
  2876. 'ext': 'flv',
  2877. 'format': 'flv'}
  2878. return [info]
  2879. class YouJizzIE(InfoExtractor):
  2880. """Information extractor for youjizz.com."""
  2881. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youjizz\.com/videos/(?P<videoid>[^.]+).html$'
  2882. def _real_extract(self, url):
  2883. mobj = re.match(self._VALID_URL, url)
  2884. if mobj is None:
  2885. raise ExtractorError(u'Invalid URL: %s' % url)
  2886. video_id = mobj.group('videoid')
  2887. # Get webpage content
  2888. webpage = self._download_webpage(url, video_id)
  2889. # Get the video title
  2890. video_title = self._html_search_regex(r'<title>(?P<title>.*)</title>',
  2891. webpage, u'title').strip()
  2892. # Get the embed page
  2893. result = re.search(r'https?://www.youjizz.com/videos/embed/(?P<videoid>[0-9]+)', webpage)
  2894. if result is None:
  2895. raise ExtractorError(u'ERROR: unable to extract embed page')
  2896. embed_page_url = result.group(0).strip()
  2897. video_id = result.group('videoid')
  2898. webpage = self._download_webpage(embed_page_url, video_id)
  2899. # Get the video URL
  2900. video_url = self._search_regex(r'so.addVariable\("file",encodeURIComponent\("(?P<source>[^"]+)"\)\);',
  2901. webpage, u'video URL')
  2902. info = {'id': video_id,
  2903. 'url': video_url,
  2904. 'title': video_title,
  2905. 'ext': 'flv',
  2906. 'format': 'flv',
  2907. 'player_url': embed_page_url}
  2908. return [info]
  2909. class EightTracksIE(InfoExtractor):
  2910. IE_NAME = '8tracks'
  2911. _VALID_URL = r'https?://8tracks.com/(?P<user>[^/]+)/(?P<id>[^/#]+)(?:#.*)?$'
  2912. def _real_extract(self, url):
  2913. mobj = re.match(self._VALID_URL, url)
  2914. if mobj is None:
  2915. raise ExtractorError(u'Invalid URL: %s' % url)
  2916. playlist_id = mobj.group('id')
  2917. webpage = self._download_webpage(url, playlist_id)
  2918. json_like = self._search_regex(r"PAGE.mix = (.*?);\n", webpage, u'trax information', flags=re.DOTALL)
  2919. data = json.loads(json_like)
  2920. session = str(random.randint(0, 1000000000))
  2921. mix_id = data['id']
  2922. track_count = data['tracks_count']
  2923. first_url = 'http://8tracks.com/sets/%s/play?player=sm&mix_id=%s&format=jsonh' % (session, mix_id)
  2924. next_url = first_url
  2925. res = []
  2926. for i in itertools.count():
  2927. api_json = self._download_webpage(next_url, playlist_id,
  2928. note=u'Downloading song information %s/%s' % (str(i+1), track_count),
  2929. errnote=u'Failed to download song information')
  2930. api_data = json.loads(api_json)
  2931. track_data = api_data[u'set']['track']
  2932. info = {
  2933. 'id': track_data['id'],
  2934. 'url': track_data['track_file_stream_url'],
  2935. 'title': track_data['performer'] + u' - ' + track_data['name'],
  2936. 'raw_title': track_data['name'],
  2937. 'uploader_id': data['user']['login'],
  2938. 'ext': 'm4a',
  2939. }
  2940. res.append(info)
  2941. if api_data['set']['at_last_track']:
  2942. break
  2943. next_url = 'http://8tracks.com/sets/%s/next?player=sm&mix_id=%s&format=jsonh&track_id=%s' % (session, mix_id, track_data['id'])
  2944. return res
  2945. class KeekIE(InfoExtractor):
  2946. _VALID_URL = r'http://(?:www\.)?keek\.com/(?:!|\w+/keeks/)(?P<videoID>\w+)'
  2947. IE_NAME = u'keek'
  2948. def _real_extract(self, url):
  2949. m = re.match(self._VALID_URL, url)
  2950. video_id = m.group('videoID')
  2951. video_url = u'http://cdn.keek.com/keek/video/%s' % video_id
  2952. thumbnail = u'http://cdn.keek.com/keek/thumbnail/%s/w100/h75' % video_id
  2953. webpage = self._download_webpage(url, video_id)
  2954. video_title = self._html_search_regex(r'<meta property="og:title" content="(?P<title>.*?)"',
  2955. webpage, u'title')
  2956. uploader = self._html_search_regex(r'<div class="user-name-and-bio">[\S\s]+?<h2>(?P<uploader>.+?)</h2>',
  2957. webpage, u'uploader', fatal=False)
  2958. info = {
  2959. 'id': video_id,
  2960. 'url': video_url,
  2961. 'ext': 'mp4',
  2962. 'title': video_title,
  2963. 'thumbnail': thumbnail,
  2964. 'uploader': uploader
  2965. }
  2966. return [info]
  2967. class TEDIE(InfoExtractor):
  2968. _VALID_URL=r'''http://www\.ted\.com/
  2969. (
  2970. ((?P<type_playlist>playlists)/(?P<playlist_id>\d+)) # We have a playlist
  2971. |
  2972. ((?P<type_talk>talks)) # We have a simple talk
  2973. )
  2974. (/lang/(.*?))? # The url may contain the language
  2975. /(?P<name>\w+) # Here goes the name and then ".html"
  2976. '''
  2977. @classmethod
  2978. def suitable(cls, url):
  2979. """Receives a URL and returns True if suitable for this IE."""
  2980. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  2981. def _real_extract(self, url):
  2982. m=re.match(self._VALID_URL, url, re.VERBOSE)
  2983. if m.group('type_talk'):
  2984. return [self._talk_info(url)]
  2985. else :
  2986. playlist_id=m.group('playlist_id')
  2987. name=m.group('name')
  2988. self.to_screen(u'Getting info of playlist %s: "%s"' % (playlist_id,name))
  2989. return [self._playlist_videos_info(url,name,playlist_id)]
  2990. def _playlist_videos_info(self,url,name,playlist_id=0):
  2991. '''Returns the videos of the playlist'''
  2992. video_RE=r'''
  2993. <li\ id="talk_(\d+)"([.\s]*?)data-id="(?P<video_id>\d+)"
  2994. ([.\s]*?)data-playlist_item_id="(\d+)"
  2995. ([.\s]*?)data-mediaslug="(?P<mediaSlug>.+?)"
  2996. '''
  2997. video_name_RE=r'<p\ class="talk-title"><a href="(?P<talk_url>/talks/(.+).html)">(?P<fullname>.+?)</a></p>'
  2998. webpage=self._download_webpage(url, playlist_id, 'Downloading playlist webpage')
  2999. m_videos=re.finditer(video_RE,webpage,re.VERBOSE)
  3000. m_names=re.finditer(video_name_RE,webpage)
  3001. playlist_title = self._html_search_regex(r'div class="headline">\s*?<h1>\s*?<span>(.*?)</span>',
  3002. webpage, 'playlist title')
  3003. playlist_entries = []
  3004. for m_video, m_name in zip(m_videos,m_names):
  3005. video_id=m_video.group('video_id')
  3006. talk_url='http://www.ted.com%s' % m_name.group('talk_url')
  3007. playlist_entries.append(self.url_result(talk_url, 'TED'))
  3008. return self.playlist_result(playlist_entries, playlist_id = playlist_id, playlist_title = playlist_title)
  3009. def _talk_info(self, url, video_id=0):
  3010. """Return the video for the talk in the url"""
  3011. m = re.match(self._VALID_URL, url,re.VERBOSE)
  3012. video_name = m.group('name')
  3013. webpage = self._download_webpage(url, video_id, 'Downloading \"%s\" page' % video_name)
  3014. self.report_extraction(video_name)
  3015. # If the url includes the language we get the title translated
  3016. title = self._html_search_regex(r'<span id="altHeadline" >(?P<title>.*)</span>',
  3017. webpage, 'title')
  3018. json_data = self._search_regex(r'<script.*?>var talkDetails = ({.*?})</script>',
  3019. webpage, 'json data')
  3020. info = json.loads(json_data)
  3021. desc = self._html_search_regex(r'<div class="talk-intro">.*?<p.*?>(.*?)</p>',
  3022. webpage, 'description', flags = re.DOTALL)
  3023. thumbnail = self._search_regex(r'</span>[\s.]*</div>[\s.]*<img src="(.*?)"',
  3024. webpage, 'thumbnail')
  3025. info = {
  3026. 'id': info['id'],
  3027. 'url': info['htmlStreams'][-1]['file'],
  3028. 'ext': 'mp4',
  3029. 'title': title,
  3030. 'thumbnail': thumbnail,
  3031. 'description': desc,
  3032. }
  3033. return info
  3034. class MySpassIE(InfoExtractor):
  3035. _VALID_URL = r'http://www.myspass.de/.*'
  3036. def _real_extract(self, url):
  3037. META_DATA_URL_TEMPLATE = 'http://www.myspass.de/myspass/includes/apps/video/getvideometadataxml.php?id=%s'
  3038. # video id is the last path element of the URL
  3039. # usually there is a trailing slash, so also try the second but last
  3040. url_path = compat_urllib_parse_urlparse(url).path
  3041. url_parent_path, video_id = os.path.split(url_path)
  3042. if not video_id:
  3043. _, video_id = os.path.split(url_parent_path)
  3044. # get metadata
  3045. metadata_url = META_DATA_URL_TEMPLATE % video_id
  3046. metadata_text = self._download_webpage(metadata_url, video_id)
  3047. metadata = xml.etree.ElementTree.fromstring(metadata_text.encode('utf-8'))
  3048. # extract values from metadata
  3049. url_flv_el = metadata.find('url_flv')
  3050. if url_flv_el is None:
  3051. raise ExtractorError(u'Unable to extract download url')
  3052. video_url = url_flv_el.text
  3053. extension = os.path.splitext(video_url)[1][1:]
  3054. title_el = metadata.find('title')
  3055. if title_el is None:
  3056. raise ExtractorError(u'Unable to extract title')
  3057. title = title_el.text
  3058. format_id_el = metadata.find('format_id')
  3059. if format_id_el is None:
  3060. format = ext
  3061. else:
  3062. format = format_id_el.text
  3063. description_el = metadata.find('description')
  3064. if description_el is not None:
  3065. description = description_el.text
  3066. else:
  3067. description = None
  3068. imagePreview_el = metadata.find('imagePreview')
  3069. if imagePreview_el is not None:
  3070. thumbnail = imagePreview_el.text
  3071. else:
  3072. thumbnail = None
  3073. info = {
  3074. 'id': video_id,
  3075. 'url': video_url,
  3076. 'title': title,
  3077. 'ext': extension,
  3078. 'format': format,
  3079. 'thumbnail': thumbnail,
  3080. 'description': description
  3081. }
  3082. return [info]
  3083. class SpiegelIE(InfoExtractor):
  3084. _VALID_URL = r'https?://(?:www\.)?spiegel\.de/video/[^/]*-(?P<videoID>[0-9]+)(?:\.html)?(?:#.*)?$'
  3085. def _real_extract(self, url):
  3086. m = re.match(self._VALID_URL, url)
  3087. video_id = m.group('videoID')
  3088. webpage = self._download_webpage(url, video_id)
  3089. video_title = self._html_search_regex(r'<div class="module-title">(.*?)</div>',
  3090. webpage, u'title')
  3091. xml_url = u'http://video2.spiegel.de/flash/' + video_id + u'.xml'
  3092. xml_code = self._download_webpage(xml_url, video_id,
  3093. note=u'Downloading XML', errnote=u'Failed to download XML')
  3094. idoc = xml.etree.ElementTree.fromstring(xml_code)
  3095. last_type = idoc[-1]
  3096. filename = last_type.findall('./filename')[0].text
  3097. duration = float(last_type.findall('./duration')[0].text)
  3098. video_url = 'http://video2.spiegel.de/flash/' + filename
  3099. video_ext = filename.rpartition('.')[2]
  3100. info = {
  3101. 'id': video_id,
  3102. 'url': video_url,
  3103. 'ext': video_ext,
  3104. 'title': video_title,
  3105. 'duration': duration,
  3106. }
  3107. return [info]
  3108. class LiveLeakIE(InfoExtractor):
  3109. _VALID_URL = r'^(?:http?://)?(?:\w+\.)?liveleak\.com/view\?(?:.*?)i=(?P<video_id>[\w_]+)(?:.*)'
  3110. IE_NAME = u'liveleak'
  3111. def _real_extract(self, url):
  3112. mobj = re.match(self._VALID_URL, url)
  3113. if mobj is None:
  3114. raise ExtractorError(u'Invalid URL: %s' % url)
  3115. video_id = mobj.group('video_id')
  3116. webpage = self._download_webpage(url, video_id)
  3117. video_url = self._search_regex(r'file: "(.*?)",',
  3118. webpage, u'video URL')
  3119. video_title = self._html_search_regex(r'<meta property="og:title" content="(?P<title>.*?)"',
  3120. webpage, u'title').replace('LiveLeak.com -', '').strip()
  3121. video_description = self._html_search_regex(r'<meta property="og:description" content="(?P<desc>.*?)"',
  3122. webpage, u'description', fatal=False)
  3123. video_uploader = self._html_search_regex(r'By:.*?(\w+)</a>',
  3124. webpage, u'uploader', fatal=False)
  3125. info = {
  3126. 'id': video_id,
  3127. 'url': video_url,
  3128. 'ext': 'mp4',
  3129. 'title': video_title,
  3130. 'description': video_description,
  3131. 'uploader': video_uploader
  3132. }
  3133. return [info]
  3134. class ARDIE(InfoExtractor):
  3135. _VALID_URL = r'^(?:https?://)?(?:(?:www\.)?ardmediathek\.de|mediathek\.daserste\.de)/(?:.*/)(?P<video_id>[^/\?]+)(?:\?.*)?'
  3136. _TITLE = r'<h1(?: class="boxTopHeadline")?>(?P<title>.*)</h1>'
  3137. _MEDIA_STREAM = r'mediaCollection\.addMediaStream\((?P<media_type>\d+), (?P<quality>\d+), "(?P<rtmp_url>[^"]*)", "(?P<video_url>[^"]*)", "[^"]*"\)'
  3138. def _real_extract(self, url):
  3139. # determine video id from url
  3140. m = re.match(self._VALID_URL, url)
  3141. numid = re.search(r'documentId=([0-9]+)', url)
  3142. if numid:
  3143. video_id = numid.group(1)
  3144. else:
  3145. video_id = m.group('video_id')
  3146. # determine title and media streams from webpage
  3147. html = self._download_webpage(url, video_id)
  3148. title = re.search(self._TITLE, html).group('title')
  3149. streams = [m.groupdict() for m in re.finditer(self._MEDIA_STREAM, html)]
  3150. if not streams:
  3151. assert '"fsk"' in html
  3152. raise ExtractorError(u'This video is only available after 8:00 pm')
  3153. # choose default media type and highest quality for now
  3154. stream = max([s for s in streams if int(s["media_type"]) == 0],
  3155. key=lambda s: int(s["quality"]))
  3156. # there's two possibilities: RTMP stream or HTTP download
  3157. info = {'id': video_id, 'title': title, 'ext': 'mp4'}
  3158. if stream['rtmp_url']:
  3159. self.to_screen(u'RTMP download detected')
  3160. assert stream['video_url'].startswith('mp4:')
  3161. info["url"] = stream["rtmp_url"]
  3162. info["play_path"] = stream['video_url']
  3163. else:
  3164. assert stream["video_url"].endswith('.mp4')
  3165. info["url"] = stream["video_url"]
  3166. return [info]
  3167. class ZDFIE(InfoExtractor):
  3168. _VALID_URL = r'^http://www\.zdf\.de\/ZDFmediathek\/(.*beitrag\/video\/)(?P<video_id>[^/\?]+)(?:\?.*)?'
  3169. _TITLE = r'<h1(?: class="beitragHeadline")?>(?P<title>.*)</h1>'
  3170. _MEDIA_STREAM = r'<a href="(?P<video_url>.+(?P<media_type>.streaming).+/zdf/(?P<quality>[^\/]+)/[^"]*)".+class="play".+>'
  3171. _MMS_STREAM = r'href="(?P<video_url>mms://[^"]*)"'
  3172. _RTSP_STREAM = r'(?P<video_url>rtsp://[^"]*.mp4)'
  3173. def _real_extract(self, url):
  3174. mobj = re.match(self._VALID_URL, url)
  3175. if mobj is None:
  3176. raise ExtractorError(u'Invalid URL: %s' % url)
  3177. video_id = mobj.group('video_id')
  3178. html = self._download_webpage(url, video_id)
  3179. streams = [m.groupdict() for m in re.finditer(self._MEDIA_STREAM, html)]
  3180. if streams is None:
  3181. raise ExtractorError(u'No media url found.')
  3182. # s['media_type'] == 'wstreaming' -> use 'Windows Media Player' and mms url
  3183. # s['media_type'] == 'hstreaming' -> use 'Quicktime' and rtsp url
  3184. # choose first/default media type and highest quality for now
  3185. for s in streams: #find 300 - dsl1000mbit
  3186. if s['quality'] == '300' and s['media_type'] == 'wstreaming':
  3187. stream_=s
  3188. break
  3189. for s in streams: #find veryhigh - dsl2000mbit
  3190. if s['quality'] == 'veryhigh' and s['media_type'] == 'wstreaming': # 'hstreaming' - rtsp is not working
  3191. stream_=s
  3192. break
  3193. if stream_ is None:
  3194. raise ExtractorError(u'No stream found.')
  3195. media_link = self._download_webpage(stream_['video_url'], video_id,'Get stream URL')
  3196. self.report_extraction(video_id)
  3197. mobj = re.search(self._TITLE, html)
  3198. if mobj is None:
  3199. raise ExtractorError(u'Cannot extract title')
  3200. title = unescapeHTML(mobj.group('title'))
  3201. mobj = re.search(self._MMS_STREAM, media_link)
  3202. if mobj is None:
  3203. mobj = re.search(self._RTSP_STREAM, media_link)
  3204. if mobj is None:
  3205. raise ExtractorError(u'Cannot extract mms:// or rtsp:// URL')
  3206. mms_url = mobj.group('video_url')
  3207. mobj = re.search('(.*)[.](?P<ext>[^.]+)', mms_url)
  3208. if mobj is None:
  3209. raise ExtractorError(u'Cannot extract extention')
  3210. ext = mobj.group('ext')
  3211. return [{'id': video_id,
  3212. 'url': mms_url,
  3213. 'title': title,
  3214. 'ext': ext
  3215. }]
  3216. class TumblrIE(InfoExtractor):
  3217. _VALID_URL = r'http://(?P<blog_name>.*?)\.tumblr\.com/((post)|(video))/(?P<id>\d*)/(.*?)'
  3218. def _real_extract(self, url):
  3219. m_url = re.match(self._VALID_URL, url)
  3220. video_id = m_url.group('id')
  3221. blog = m_url.group('blog_name')
  3222. url = 'http://%s.tumblr.com/post/%s/' % (blog, video_id)
  3223. webpage = self._download_webpage(url, video_id)
  3224. re_video = r'src=\\x22(?P<video_url>http://%s\.tumblr\.com/video_file/%s/(.*?))\\x22 type=\\x22video/(?P<ext>.*?)\\x22' % (blog, video_id)
  3225. video = re.search(re_video, webpage)
  3226. if video is None:
  3227. raise ExtractorError(u'Unable to extract video')
  3228. video_url = video.group('video_url')
  3229. ext = video.group('ext')
  3230. video_thumbnail = self._search_regex(r'posters(.*?)\[\\x22(?P<thumb>.*?)\\x22',
  3231. webpage, u'thumbnail', fatal=False) # We pick the first poster
  3232. if video_thumbnail: video_thumbnail = video_thumbnail.replace('\\', '')
  3233. # The only place where you can get a title, it's not complete,
  3234. # but searching in other places doesn't work for all videos
  3235. video_title = self._html_search_regex(r'<title>(?P<title>.*?)</title>',
  3236. webpage, u'title', flags=re.DOTALL)
  3237. return [{'id': video_id,
  3238. 'url': video_url,
  3239. 'title': video_title,
  3240. 'thumbnail': video_thumbnail,
  3241. 'ext': ext
  3242. }]
  3243. class BandcampIE(InfoExtractor):
  3244. _VALID_URL = r'http://.*?\.bandcamp\.com/track/(?P<title>.*)'
  3245. def _real_extract(self, url):
  3246. mobj = re.match(self._VALID_URL, url)
  3247. title = mobj.group('title')
  3248. webpage = self._download_webpage(url, title)
  3249. # We get the link to the free download page
  3250. m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
  3251. if m_download is None:
  3252. raise ExtractorError(u'No free songs found')
  3253. download_link = m_download.group(1)
  3254. id = re.search(r'var TralbumData = {(.*?)id: (?P<id>\d*?)$',
  3255. webpage, re.MULTILINE|re.DOTALL).group('id')
  3256. download_webpage = self._download_webpage(download_link, id,
  3257. 'Downloading free downloads page')
  3258. # We get the dictionary of the track from some javascrip code
  3259. info = re.search(r'items: (.*?),$',
  3260. download_webpage, re.MULTILINE).group(1)
  3261. info = json.loads(info)[0]
  3262. # We pick mp3-320 for now, until format selection can be easily implemented.
  3263. mp3_info = info[u'downloads'][u'mp3-320']
  3264. # If we try to use this url it says the link has expired
  3265. initial_url = mp3_info[u'url']
  3266. re_url = r'(?P<server>http://(.*?)\.bandcamp\.com)/download/track\?enc=mp3-320&fsig=(?P<fsig>.*?)&id=(?P<id>.*?)&ts=(?P<ts>.*)$'
  3267. m_url = re.match(re_url, initial_url)
  3268. #We build the url we will use to get the final track url
  3269. # This url is build in Bandcamp in the script download_bunde_*.js
  3270. 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'))
  3271. final_url_webpage = self._download_webpage(request_url, id, 'Requesting download url')
  3272. # If we could correctly generate the .rand field the url would be
  3273. #in the "download_url" key
  3274. final_url = re.search(r'"retry_url":"(.*?)"', final_url_webpage).group(1)
  3275. track_info = {'id':id,
  3276. 'title' : info[u'title'],
  3277. 'ext' : 'mp3',
  3278. 'url' : final_url,
  3279. 'thumbnail' : info[u'thumb_url'],
  3280. 'uploader' : info[u'artist']
  3281. }
  3282. return [track_info]
  3283. class RedTubeIE(InfoExtractor):
  3284. """Information Extractor for redtube"""
  3285. _VALID_URL = r'(?:http://)?(?:www\.)?redtube\.com/(?P<id>[0-9]+)'
  3286. def _real_extract(self,url):
  3287. mobj = re.match(self._VALID_URL, url)
  3288. if mobj is None:
  3289. raise ExtractorError(u'Invalid URL: %s' % url)
  3290. video_id = mobj.group('id')
  3291. video_extension = 'mp4'
  3292. webpage = self._download_webpage(url, video_id)
  3293. self.report_extraction(video_id)
  3294. video_url = self._html_search_regex(r'<source src="(.+?)" type="video/mp4">',
  3295. webpage, u'video URL')
  3296. video_title = self._html_search_regex('<h1 class="videoTitle slidePanelMovable">(.+?)</h1>',
  3297. webpage, u'title')
  3298. return [{
  3299. 'id': video_id,
  3300. 'url': video_url,
  3301. 'ext': video_extension,
  3302. 'title': video_title,
  3303. }]
  3304. class InaIE(InfoExtractor):
  3305. """Information Extractor for Ina.fr"""
  3306. _VALID_URL = r'(?:http://)?(?:www\.)?ina\.fr/video/(?P<id>I[0-9]+)/.*'
  3307. def _real_extract(self,url):
  3308. mobj = re.match(self._VALID_URL, url)
  3309. video_id = mobj.group('id')
  3310. mrss_url='http://player.ina.fr/notices/%s.mrss' % video_id
  3311. video_extension = 'mp4'
  3312. webpage = self._download_webpage(mrss_url, video_id)
  3313. self.report_extraction(video_id)
  3314. video_url = self._html_search_regex(r'<media:player url="(?P<mp4url>http://mp4.ina.fr/[^"]+\.mp4)',
  3315. webpage, u'video URL')
  3316. video_title = self._search_regex(r'<title><!\[CDATA\[(?P<titre>.*?)]]></title>',
  3317. webpage, u'title')
  3318. return [{
  3319. 'id': video_id,
  3320. 'url': video_url,
  3321. 'ext': video_extension,
  3322. 'title': video_title,
  3323. }]
  3324. class HowcastIE(InfoExtractor):
  3325. """Information Extractor for Howcast.com"""
  3326. _VALID_URL = r'(?:https?://)?(?:www\.)?howcast\.com/videos/(?P<id>\d+)'
  3327. def _real_extract(self, url):
  3328. mobj = re.match(self._VALID_URL, url)
  3329. video_id = mobj.group('id')
  3330. webpage_url = 'http://www.howcast.com/videos/' + video_id
  3331. webpage = self._download_webpage(webpage_url, video_id)
  3332. self.report_extraction(video_id)
  3333. video_url = self._search_regex(r'\'?file\'?: "(http://mobile-media\.howcast\.com/[0-9]+\.mp4)',
  3334. webpage, u'video URL')
  3335. video_title = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') property=\'og:title\'',
  3336. webpage, u'title')
  3337. video_description = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') name=\'description\'',
  3338. webpage, u'description', fatal=False)
  3339. thumbnail = self._html_search_regex(r'<meta content=\'(.+?)\' property=\'og:image\'',
  3340. webpage, u'thumbnail', fatal=False)
  3341. return [{
  3342. 'id': video_id,
  3343. 'url': video_url,
  3344. 'ext': 'mp4',
  3345. 'title': video_title,
  3346. 'description': video_description,
  3347. 'thumbnail': thumbnail,
  3348. }]
  3349. class VineIE(InfoExtractor):
  3350. """Information Extractor for Vine.co"""
  3351. _VALID_URL = r'(?:https?://)?(?:www\.)?vine\.co/v/(?P<id>\w+)'
  3352. def _real_extract(self, url):
  3353. mobj = re.match(self._VALID_URL, url)
  3354. video_id = mobj.group('id')
  3355. webpage_url = 'https://vine.co/v/' + video_id
  3356. webpage = self._download_webpage(webpage_url, video_id)
  3357. self.report_extraction(video_id)
  3358. video_url = self._html_search_regex(r'<meta property="twitter:player:stream" content="(.+?)"',
  3359. webpage, u'video URL')
  3360. video_title = self._html_search_regex(r'<meta property="og:title" content="(.+?)"',
  3361. webpage, u'title')
  3362. thumbnail = self._html_search_regex(r'<meta property="og:image" content="(.+?)(\?.*?)?"',
  3363. webpage, u'thumbnail', fatal=False)
  3364. uploader = self._html_search_regex(r'<div class="user">.*?<h2>(.+?)</h2>',
  3365. webpage, u'uploader', fatal=False, flags=re.DOTALL)
  3366. return [{
  3367. 'id': video_id,
  3368. 'url': video_url,
  3369. 'ext': 'mp4',
  3370. 'title': video_title,
  3371. 'thumbnail': thumbnail,
  3372. 'uploader': uploader,
  3373. }]
  3374. class FlickrIE(InfoExtractor):
  3375. """Information Extractor for Flickr videos"""
  3376. _VALID_URL = r'(?:https?://)?(?:www\.)?flickr\.com/photos/(?P<uploader_id>[\w\-_@]+)/(?P<id>\d+).*'
  3377. def _real_extract(self, url):
  3378. mobj = re.match(self._VALID_URL, url)
  3379. video_id = mobj.group('id')
  3380. video_uploader_id = mobj.group('uploader_id')
  3381. webpage_url = 'http://www.flickr.com/photos/' + video_uploader_id + '/' + video_id
  3382. webpage = self._download_webpage(webpage_url, video_id)
  3383. secret = self._search_regex(r"photo_secret: '(\w+)'", webpage, u'secret')
  3384. first_url = 'https://secure.flickr.com/apps/video/video_mtl_xml.gne?v=x&photo_id=' + video_id + '&secret=' + secret + '&bitrate=700&target=_self'
  3385. first_xml = self._download_webpage(first_url, video_id, 'Downloading first data webpage')
  3386. node_id = self._html_search_regex(r'<Item id="id">(\d+-\d+)</Item>',
  3387. first_xml, u'node_id')
  3388. 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'
  3389. second_xml = self._download_webpage(second_url, video_id, 'Downloading second data webpage')
  3390. self.report_extraction(video_id)
  3391. mobj = re.search(r'<STREAM APP="(.+?)" FULLPATH="(.+?)"', second_xml)
  3392. if mobj is None:
  3393. raise ExtractorError(u'Unable to extract video url')
  3394. video_url = mobj.group(1) + unescapeHTML(mobj.group(2))
  3395. video_title = self._html_search_regex(r'<meta property="og:title" content=(?:"([^"]+)"|\'([^\']+)\')',
  3396. webpage, u'video title')
  3397. video_description = self._html_search_regex(r'<meta property="og:description" content=(?:"([^"]+)"|\'([^\']+)\')',
  3398. webpage, u'description', fatal=False)
  3399. thumbnail = self._html_search_regex(r'<meta property="og:image" content=(?:"([^"]+)"|\'([^\']+)\')',
  3400. webpage, u'thumbnail', fatal=False)
  3401. return [{
  3402. 'id': video_id,
  3403. 'url': video_url,
  3404. 'ext': 'mp4',
  3405. 'title': video_title,
  3406. 'description': video_description,
  3407. 'thumbnail': thumbnail,
  3408. 'uploader_id': video_uploader_id,
  3409. }]
  3410. class TeamcocoIE(InfoExtractor):
  3411. _VALID_URL = r'http://teamcoco\.com/video/(?P<url_title>.*)'
  3412. def _real_extract(self, url):
  3413. mobj = re.match(self._VALID_URL, url)
  3414. if mobj is None:
  3415. raise ExtractorError(u'Invalid URL: %s' % url)
  3416. url_title = mobj.group('url_title')
  3417. webpage = self._download_webpage(url, url_title)
  3418. video_id = self._html_search_regex(r'<article class="video" data-id="(\d+?)"',
  3419. webpage, u'video id')
  3420. self.report_extraction(video_id)
  3421. video_title = self._html_search_regex(r'<meta property="og:title" content="(.+?)"',
  3422. webpage, u'title')
  3423. thumbnail = self._html_search_regex(r'<meta property="og:image" content="(.+?)"',
  3424. webpage, u'thumbnail', fatal=False)
  3425. video_description = self._html_search_regex(r'<meta property="og:description" content="(.*?)"',
  3426. webpage, u'description', fatal=False)
  3427. data_url = 'http://teamcoco.com/cvp/2.0/%s.xml' % video_id
  3428. data = self._download_webpage(data_url, video_id, 'Downloading data webpage')
  3429. video_url = self._html_search_regex(r'<file type="high".*?>(.*?)</file>',
  3430. data, u'video URL')
  3431. return [{
  3432. 'id': video_id,
  3433. 'url': video_url,
  3434. 'ext': 'mp4',
  3435. 'title': video_title,
  3436. 'thumbnail': thumbnail,
  3437. 'description': video_description,
  3438. }]
  3439. class XHamsterIE(InfoExtractor):
  3440. """Information Extractor for xHamster"""
  3441. _VALID_URL = r'(?:http://)?(?:www.)?xhamster\.com/movies/(?P<id>[0-9]+)/.*\.html'
  3442. def _real_extract(self,url):
  3443. mobj = re.match(self._VALID_URL, url)
  3444. video_id = mobj.group('id')
  3445. mrss_url = 'http://xhamster.com/movies/%s/.html' % video_id
  3446. webpage = self._download_webpage(mrss_url, video_id)
  3447. mobj = re.search(r'\'srv\': \'(?P<server>[^\']*)\',\s*\'file\': \'(?P<file>[^\']+)\',', webpage)
  3448. if mobj is None:
  3449. raise ExtractorError(u'Unable to extract media URL')
  3450. if len(mobj.group('server')) == 0:
  3451. video_url = compat_urllib_parse.unquote(mobj.group('file'))
  3452. else:
  3453. video_url = mobj.group('server')+'/key='+mobj.group('file')
  3454. video_extension = video_url.split('.')[-1]
  3455. video_title = self._html_search_regex(r'<title>(?P<title>.+?) - xHamster\.com</title>',
  3456. webpage, u'title')
  3457. # Can't see the description anywhere in the UI
  3458. # video_description = self._html_search_regex(r'<span>Description: </span>(?P<description>[^<]+)',
  3459. # webpage, u'description', fatal=False)
  3460. # if video_description: video_description = unescapeHTML(video_description)
  3461. 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)
  3462. if mobj:
  3463. video_upload_date = mobj.group('upload_date_Y')+mobj.group('upload_date_m')+mobj.group('upload_date_d')
  3464. else:
  3465. video_upload_date = None
  3466. self._downloader.report_warning(u'Unable to extract upload date')
  3467. video_uploader_id = self._html_search_regex(r'<a href=\'/user/[^>]+>(?P<uploader_id>[^<]+)',
  3468. webpage, u'uploader id', default=u'anonymous')
  3469. video_thumbnail = self._search_regex(r'\'image\':\'(?P<thumbnail>[^\']+)\'',
  3470. webpage, u'thumbnail', fatal=False)
  3471. return [{
  3472. 'id': video_id,
  3473. 'url': video_url,
  3474. 'ext': video_extension,
  3475. 'title': video_title,
  3476. # 'description': video_description,
  3477. 'upload_date': video_upload_date,
  3478. 'uploader_id': video_uploader_id,
  3479. 'thumbnail': video_thumbnail
  3480. }]
  3481. class HypemIE(InfoExtractor):
  3482. """Information Extractor for hypem"""
  3483. _VALID_URL = r'(?:http://)?(?:www\.)?hypem\.com/track/([^/]+)/([^/]+)'
  3484. def _real_extract(self, url):
  3485. mobj = re.match(self._VALID_URL, url)
  3486. if mobj is None:
  3487. raise ExtractorError(u'Invalid URL: %s' % url)
  3488. track_id = mobj.group(1)
  3489. data = { 'ax': 1, 'ts': time.time() }
  3490. data_encoded = compat_urllib_parse.urlencode(data)
  3491. complete_url = url + "?" + data_encoded
  3492. request = compat_urllib_request.Request(complete_url)
  3493. response, urlh = self._download_webpage_handle(request, track_id, u'Downloading webpage with the url')
  3494. cookie = urlh.headers.get('Set-Cookie', '')
  3495. self.report_extraction(track_id)
  3496. html_tracks = self._html_search_regex(r'<script type="application/json" id="displayList-data">(.*?)</script>',
  3497. response, u'tracks', flags=re.MULTILINE|re.DOTALL).strip()
  3498. try:
  3499. track_list = json.loads(html_tracks)
  3500. track = track_list[u'tracks'][0]
  3501. except ValueError:
  3502. raise ExtractorError(u'Hypemachine contained invalid JSON.')
  3503. key = track[u"key"]
  3504. track_id = track[u"id"]
  3505. artist = track[u"artist"]
  3506. title = track[u"song"]
  3507. serve_url = "http://hypem.com/serve/source/%s/%s" % (compat_str(track_id), compat_str(key))
  3508. request = compat_urllib_request.Request(serve_url, "" , {'Content-Type': 'application/json'})
  3509. request.add_header('cookie', cookie)
  3510. song_data_json = self._download_webpage(request, track_id, u'Downloading metadata')
  3511. try:
  3512. song_data = json.loads(song_data_json)
  3513. except ValueError:
  3514. raise ExtractorError(u'Hypemachine contained invalid JSON.')
  3515. final_url = song_data[u"url"]
  3516. return [{
  3517. 'id': track_id,
  3518. 'url': final_url,
  3519. 'ext': "mp3",
  3520. 'title': title,
  3521. 'artist': artist,
  3522. }]
  3523. class Vbox7IE(InfoExtractor):
  3524. """Information Extractor for Vbox7"""
  3525. _VALID_URL = r'(?:http://)?(?:www\.)?vbox7\.com/play:([^/]+)'
  3526. def _real_extract(self,url):
  3527. mobj = re.match(self._VALID_URL, url)
  3528. if mobj is None:
  3529. raise ExtractorError(u'Invalid URL: %s' % url)
  3530. video_id = mobj.group(1)
  3531. redirect_page, urlh = self._download_webpage_handle(url, video_id)
  3532. new_location = self._search_regex(r'window\.location = \'(.*)\';', redirect_page, u'redirect location')
  3533. redirect_url = urlh.geturl() + new_location
  3534. webpage = self._download_webpage(redirect_url, video_id, u'Downloading redirect page')
  3535. title = self._html_search_regex(r'<title>(.*)</title>',
  3536. webpage, u'title').split('/')[0].strip()
  3537. ext = "flv"
  3538. info_url = "http://vbox7.com/play/magare.do"
  3539. data = compat_urllib_parse.urlencode({'as3':'1','vid':video_id})
  3540. info_request = compat_urllib_request.Request(info_url, data)
  3541. info_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  3542. info_response = self._download_webpage(info_request, video_id, u'Downloading info webpage')
  3543. if info_response is None:
  3544. raise ExtractorError(u'Unable to extract the media url')
  3545. (final_url, thumbnail_url) = map(lambda x: x.split('=')[1], info_response.split('&'))
  3546. return [{
  3547. 'id': video_id,
  3548. 'url': final_url,
  3549. 'ext': ext,
  3550. 'title': title,
  3551. 'thumbnail': thumbnail_url,
  3552. }]
  3553. class GametrailersIE(InfoExtractor):
  3554. _VALID_URL = r'http://www.gametrailers.com/(?P<type>videos|reviews|full-episodes)/(?P<id>.*?)/(?P<title>.*)'
  3555. def _real_extract(self, url):
  3556. mobj = re.match(self._VALID_URL, url)
  3557. if mobj is None:
  3558. raise ExtractorError(u'Invalid URL: %s' % url)
  3559. video_id = mobj.group('id')
  3560. video_type = mobj.group('type')
  3561. webpage = self._download_webpage(url, video_id)
  3562. if video_type == 'full-episodes':
  3563. mgid_re = r'data-video="(?P<mgid>mgid:.*?)"'
  3564. else:
  3565. mgid_re = r'data-contentId=\'(?P<mgid>mgid:.*?)\''
  3566. mgid = self._search_regex(mgid_re, webpage, u'mgid')
  3567. data = compat_urllib_parse.urlencode({'uri': mgid, 'acceptMethods': 'fms'})
  3568. info_page = self._download_webpage('http://www.gametrailers.com/feeds/mrss?' + data,
  3569. video_id, u'Downloading video info')
  3570. links_webpage = self._download_webpage('http://www.gametrailers.com/feeds/mediagen/?' + data,
  3571. video_id, u'Downloading video urls info')
  3572. self.report_extraction(video_id)
  3573. info_re = r'''<title><!\[CDATA\[(?P<title>.*?)\]\]></title>.*
  3574. <description><!\[CDATA\[(?P<description>.*?)\]\]></description>.*
  3575. <image>.*
  3576. <url>(?P<thumb>.*?)</url>.*
  3577. </image>'''
  3578. m_info = re.search(info_re, info_page, re.VERBOSE|re.DOTALL)
  3579. if m_info is None:
  3580. raise ExtractorError(u'Unable to extract video info')
  3581. video_title = m_info.group('title')
  3582. video_description = m_info.group('description')
  3583. video_thumb = m_info.group('thumb')
  3584. m_urls = list(re.finditer(r'<src>(?P<url>.*)</src>', links_webpage))
  3585. if m_urls is None or len(m_urls) == 0:
  3586. raise ExtractError(u'Unable to extrat video url')
  3587. # They are sorted from worst to best quality
  3588. video_url = m_urls[-1].group('url')
  3589. return {'url': video_url,
  3590. 'id': video_id,
  3591. 'title': video_title,
  3592. # Videos are actually flv not mp4
  3593. 'ext': 'flv',
  3594. 'thumbnail': video_thumb,
  3595. 'description': video_description,
  3596. }
  3597. class StatigramIE(InfoExtractor):
  3598. _VALID_URL = r'(?:http://)?(?:www\.)?statigr\.am/p/([^/]+)'
  3599. def _real_extract(self, url):
  3600. mobj = re.match(self._VALID_URL, url)
  3601. video_id = mobj.group(1)
  3602. webpage = self._download_webpage(url, video_id)
  3603. video_url = self._html_search_regex(
  3604. r'<meta property="og:video:secure_url" content="(.+?)">',
  3605. webpage, u'video URL')
  3606. thumbnail_url = self._html_search_regex(
  3607. r'<meta property="og:image" content="(.+?)" />',
  3608. webpage, u'thumbnail URL', fatal=False)
  3609. html_title = self._html_search_regex(
  3610. r'<title>(.+?)</title>',
  3611. webpage, u'title')
  3612. title = html_title.rpartition(u' | Statigram')[0]
  3613. uploader_id = self._html_search_regex(
  3614. r'@([^ ]+)', title, u'uploader name', fatal=False)
  3615. ext = 'mp4'
  3616. return [{
  3617. 'id': video_id,
  3618. 'url': video_url,
  3619. 'ext': ext,
  3620. 'title': title,
  3621. 'thumbnail': thumbnail_url,
  3622. 'uploader_id' : uploader_id
  3623. }]
  3624. def gen_extractors():
  3625. """ Return a list of an instance of every supported extractor.
  3626. The order does matter; the first extractor matched is the one handling the URL.
  3627. """
  3628. return [
  3629. YoutubePlaylistIE(),
  3630. YoutubeChannelIE(),
  3631. YoutubeUserIE(),
  3632. YoutubeSearchIE(),
  3633. YoutubeIE(),
  3634. MetacafeIE(),
  3635. DailymotionIE(),
  3636. GoogleSearchIE(),
  3637. PhotobucketIE(),
  3638. YahooIE(),
  3639. YahooSearchIE(),
  3640. DepositFilesIE(),
  3641. FacebookIE(),
  3642. BlipTVIE(),
  3643. BlipTVUserIE(),
  3644. VimeoIE(),
  3645. MyVideoIE(),
  3646. ComedyCentralIE(),
  3647. EscapistIE(),
  3648. CollegeHumorIE(),
  3649. XVideosIE(),
  3650. SoundcloudSetIE(),
  3651. SoundcloudIE(),
  3652. InfoQIE(),
  3653. MixcloudIE(),
  3654. StanfordOpenClassroomIE(),
  3655. MTVIE(),
  3656. YoukuIE(),
  3657. XNXXIE(),
  3658. YouJizzIE(),
  3659. PornotubeIE(),
  3660. YouPornIE(),
  3661. GooglePlusIE(),
  3662. ArteTvIE(),
  3663. NBAIE(),
  3664. WorldStarHipHopIE(),
  3665. JustinTVIE(),
  3666. FunnyOrDieIE(),
  3667. SteamIE(),
  3668. UstreamIE(),
  3669. RBMARadioIE(),
  3670. EightTracksIE(),
  3671. KeekIE(),
  3672. TEDIE(),
  3673. MySpassIE(),
  3674. SpiegelIE(),
  3675. LiveLeakIE(),
  3676. ARDIE(),
  3677. ZDFIE(),
  3678. TumblrIE(),
  3679. BandcampIE(),
  3680. RedTubeIE(),
  3681. InaIE(),
  3682. HowcastIE(),
  3683. VineIE(),
  3684. FlickrIE(),
  3685. TeamcocoIE(),
  3686. XHamsterIE(),
  3687. HypemIE(),
  3688. Vbox7IE(),
  3689. GametrailersIE(),
  3690. StatigramIE(),
  3691. GenericIE()
  3692. ]
  3693. def get_info_extractor(ie_name):
  3694. """Returns the info extractor class with the given ie_name"""
  3695. return globals()[ie_name+'IE']