InfoExtractors.py 106 KB

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