InfoExtractors.py 175 KB

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