InfoExtractors.py 169 KB

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