InfoExtractors.py 158 KB

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