InfoExtractors.py 177 KB

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