InfoExtractors.py 165 KB

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