InfoExtractors.py 118 KB

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