InfoExtractors.py 169 KB

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