InfoExtractors.py 166 KB

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