InfoExtractors.py 176 KB

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