InfoExtractors.py 176 KB

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