InfoExtractors.py 163 KB

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