InfoExtractors.py 186 KB

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