InfoExtractors.py 172 KB

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