InfoExtractors.py 178 KB

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