InfoExtractors.py 178 KB

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