InfoExtractors.py 174 KB

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