InfoExtractors.py 168 KB

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