You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

574 lines
24 KiB

13 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import with_statement
  4. from __future__ import absolute_import
  5. __authors__ = (
  6. 'Ricardo Garcia Gonzalez',
  7. 'Danny Colligan',
  8. 'Benjamin Johnson',
  9. 'Vasyl\' Vavrychuk',
  10. 'Witold Baryluk',
  11. 'Paweł Paprota',
  12. 'Gergely Imreh',
  13. 'Rogério Brito',
  14. 'Philipp Hagemeister',
  15. 'Sören Schulze',
  16. 'Kevin Ngo',
  17. 'Ori Avtalion',
  18. 'shizeeg',
  19. 'Filippo Valsorda',
  20. 'Christian Albrecht',
  21. )
  22. __license__ = 'Public Domain'
  23. __version__ = '2012.11.29'
  24. UPDATE_URL = 'https://raw.github.com/rg3/youtube-dl/master/youtube-dl'
  25. UPDATE_URL_VERSION = 'https://raw.github.com/rg3/youtube-dl/master/LATEST_VERSION'
  26. UPDATE_URL_EXE = 'https://raw.github.com/rg3/youtube-dl/master/youtube-dl.exe'
  27. import getpass
  28. import optparse
  29. import os
  30. import re
  31. import shlex
  32. import socket
  33. import subprocess
  34. import sys
  35. import warnings
  36. from .utils import *
  37. from .FileDownloader import *
  38. from .InfoExtractors import *
  39. from .PostProcessor import *
  40. def updateSelf(downloader, filename):
  41. ''' Update the program file with the latest version from the repository '''
  42. # Note: downloader only used for options
  43. if not os.access(filename, os.W_OK):
  44. sys.exit('ERROR: no write permissions on %s' % filename)
  45. downloader.to_screen(u'Updating to latest version...')
  46. urlv = compat_urllib_request.urlopen(UPDATE_URL_VERSION)
  47. newversion = urlv.read().strip()
  48. if newversion == __version__:
  49. downloader.to_screen(u'youtube-dl is up-to-date (' + __version__ + ')')
  50. return
  51. urlv.close()
  52. if hasattr(sys, "frozen"): #py2exe
  53. exe = os.path.abspath(filename)
  54. directory = os.path.dirname(exe)
  55. if not os.access(directory, os.W_OK):
  56. sys.exit('ERROR: no write permissions on %s' % directory)
  57. try:
  58. urlh = compat_urllib_request.urlopen(UPDATE_URL_EXE)
  59. newcontent = urlh.read()
  60. urlh.close()
  61. with open(exe + '.new', 'wb') as outf:
  62. outf.write(newcontent)
  63. except (IOError, OSError) as err:
  64. sys.exit('ERROR: unable to download latest version')
  65. try:
  66. bat = os.path.join(directory, 'youtube-dl-updater.bat')
  67. b = open(bat, 'w')
  68. b.write("""
  69. echo Updating youtube-dl...
  70. ping 127.0.0.1 -n 5 -w 1000 > NUL
  71. move /Y "%s.new" "%s"
  72. del "%s"
  73. \n""" %(exe, exe, bat))
  74. b.close()
  75. os.startfile(bat)
  76. except (IOError, OSError) as err:
  77. sys.exit('ERROR: unable to overwrite current version')
  78. else:
  79. try:
  80. urlh = compat_urllib_request.urlopen(UPDATE_URL)
  81. newcontent = urlh.read()
  82. urlh.close()
  83. except (IOError, OSError) as err:
  84. sys.exit('ERROR: unable to download latest version')
  85. try:
  86. with open(filename, 'wb') as outf:
  87. outf.write(newcontent)
  88. except (IOError, OSError) as err:
  89. sys.exit('ERROR: unable to overwrite current version')
  90. downloader.to_screen(u'Updated youtube-dl. Restart youtube-dl to use the new version.')
  91. def parseOpts():
  92. def _readOptions(filename_bytes):
  93. try:
  94. optionf = open(filename_bytes)
  95. except IOError:
  96. return [] # silently skip if file is not present
  97. try:
  98. res = []
  99. for l in optionf:
  100. res += shlex.split(l, comments=True)
  101. finally:
  102. optionf.close()
  103. return res
  104. def _format_option_string(option):
  105. ''' ('-o', '--option') -> -o, --format METAVAR'''
  106. opts = []
  107. if option._short_opts:
  108. opts.append(option._short_opts[0])
  109. if option._long_opts:
  110. opts.append(option._long_opts[0])
  111. if len(opts) > 1:
  112. opts.insert(1, ', ')
  113. if option.takes_value(): opts.append(' %s' % option.metavar)
  114. return "".join(opts)
  115. def _find_term_columns():
  116. columns = os.environ.get('COLUMNS', None)
  117. if columns:
  118. return int(columns)
  119. try:
  120. sp = subprocess.Popen(['stty', 'size'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  121. out,err = sp.communicate()
  122. return int(out.split()[1])
  123. except:
  124. pass
  125. return None
  126. max_width = 80
  127. max_help_position = 80
  128. # No need to wrap help messages if we're on a wide console
  129. columns = _find_term_columns()
  130. if columns: max_width = columns
  131. fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
  132. fmt.format_option_strings = _format_option_string
  133. kw = {
  134. 'version' : __version__,
  135. 'formatter' : fmt,
  136. 'usage' : '%prog [options] url [url...]',
  137. 'conflict_handler' : 'resolve',
  138. }
  139. parser = optparse.OptionParser(**kw)
  140. # option groups
  141. general = optparse.OptionGroup(parser, 'General Options')
  142. selection = optparse.OptionGroup(parser, 'Video Selection')
  143. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  144. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  145. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  146. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  147. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  148. general.add_option('-h', '--help',
  149. action='help', help='print this help text and exit')
  150. general.add_option('-v', '--version',
  151. action='version', help='print program version and exit')
  152. general.add_option('-U', '--update',
  153. action='store_true', dest='update_self', help='update this program to latest version')
  154. general.add_option('-i', '--ignore-errors',
  155. action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
  156. general.add_option('-r', '--rate-limit',
  157. dest='ratelimit', metavar='LIMIT', help='download rate limit (e.g. 50k or 44.6m)')
  158. general.add_option('-R', '--retries',
  159. dest='retries', metavar='RETRIES', help='number of retries (default is %default)', default=10)
  160. general.add_option('--buffer-size',
  161. dest='buffersize', metavar='SIZE', help='size of download buffer (e.g. 1024 or 16k) (default is %default)', default="1024")
  162. general.add_option('--no-resize-buffer',
  163. action='store_true', dest='noresizebuffer',
  164. help='do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.', default=False)
  165. general.add_option('--dump-user-agent',
  166. action='store_true', dest='dump_user_agent',
  167. help='display the current browser identification', default=False)
  168. general.add_option('--user-agent',
  169. dest='user_agent', help='specify a custom user agent', metavar='UA')
  170. general.add_option('--list-extractors',
  171. action='store_true', dest='list_extractors',
  172. help='List all supported extractors and the URLs they would handle', default=False)
  173. selection.add_option('--playlist-start',
  174. dest='playliststart', metavar='NUMBER', help='playlist video to start at (default is %default)', default=1)
  175. selection.add_option('--playlist-end',
  176. dest='playlistend', metavar='NUMBER', help='playlist video to end at (default is last)', default=-1)
  177. selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
  178. selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
  179. selection.add_option('--max-downloads', metavar='NUMBER', dest='max_downloads', help='Abort after downloading NUMBER files', default=None)
  180. authentication.add_option('-u', '--username',
  181. dest='username', metavar='USERNAME', help='account username')
  182. authentication.add_option('-p', '--password',
  183. dest='password', metavar='PASSWORD', help='account password')
  184. authentication.add_option('-n', '--netrc',
  185. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  186. video_format.add_option('-f', '--format',
  187. action='store', dest='format', metavar='FORMAT', help='video format code')
  188. video_format.add_option('--all-formats',
  189. action='store_const', dest='format', help='download all available video formats', const='all')
  190. video_format.add_option('--prefer-free-formats',
  191. action='store_true', dest='prefer_free_formats', default=False, help='prefer free video formats unless a specific one is requested')
  192. video_format.add_option('--max-quality',
  193. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  194. video_format.add_option('-F', '--list-formats',
  195. action='store_true', dest='listformats', help='list all available formats (currently youtube only)')
  196. video_format.add_option('--write-srt',
  197. action='store_true', dest='writesubtitles',
  198. help='write video closed captions to a .srt file (currently youtube only)', default=False)
  199. video_format.add_option('--srt-lang',
  200. action='store', dest='subtitleslang', metavar='LANG',
  201. help='language of the closed captions to download (optional) use IETF language tags like \'en\'')
  202. verbosity.add_option('-q', '--quiet',
  203. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  204. verbosity.add_option('-s', '--simulate',
  205. action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
  206. verbosity.add_option('--skip-download',
  207. action='store_true', dest='skip_download', help='do not download the video', default=False)
  208. verbosity.add_option('-g', '--get-url',
  209. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  210. verbosity.add_option('-e', '--get-title',
  211. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  212. verbosity.add_option('--get-thumbnail',
  213. action='store_true', dest='getthumbnail',
  214. help='simulate, quiet but print thumbnail URL', default=False)
  215. verbosity.add_option('--get-description',
  216. action='store_true', dest='getdescription',
  217. help='simulate, quiet but print video description', default=False)
  218. verbosity.add_option('--get-filename',
  219. action='store_true', dest='getfilename',
  220. help='simulate, quiet but print output filename', default=False)
  221. verbosity.add_option('--get-format',
  222. action='store_true', dest='getformat',
  223. help='simulate, quiet but print output format', default=False)
  224. verbosity.add_option('--no-progress',
  225. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  226. verbosity.add_option('--console-title',
  227. action='store_true', dest='consoletitle',
  228. help='display progress in console titlebar', default=False)
  229. verbosity.add_option('-v', '--verbose',
  230. action='store_true', dest='verbose', help='print various debugging information', default=False)
  231. filesystem.add_option('-t', '--title',
  232. action='store_true', dest='usetitle', help='use title in file name', default=False)
  233. filesystem.add_option('--id',
  234. action='store_true', dest='useid', help='use video ID in file name', default=False)
  235. filesystem.add_option('-l', '--literal',
  236. action='store_true', dest='usetitle', help='[deprecated] alias of --title', default=False)
  237. filesystem.add_option('-A', '--auto-number',
  238. action='store_true', dest='autonumber',
  239. help='number downloaded files starting from 00000', default=False)
  240. filesystem.add_option('-o', '--output',
  241. dest='outtmpl', metavar='TEMPLATE', help='output filename template. Use %(title)s to get the title, %(uploader)s for the uploader name, %(autonumber)s to get an automatically incremented number, %(ext)s for the filename extension, %(upload_date)s for the upload date (YYYYMMDD), %(extractor)s for the provider (youtube, metacafe, etc), %(id)s for the video id and %% for a literal percent. Use - to output to stdout.')
  242. filesystem.add_option('--restrict-filenames',
  243. action='store_true', dest='restrictfilenames',
  244. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames', default=False)
  245. filesystem.add_option('-a', '--batch-file',
  246. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  247. filesystem.add_option('-w', '--no-overwrites',
  248. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  249. filesystem.add_option('-c', '--continue',
  250. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=True)
  251. filesystem.add_option('--no-continue',
  252. action='store_false', dest='continue_dl',
  253. help='do not resume partially downloaded files (restart from beginning)')
  254. filesystem.add_option('--cookies',
  255. dest='cookiefile', metavar='FILE', help='file to read cookies from and dump cookie jar in')
  256. filesystem.add_option('--no-part',
  257. action='store_true', dest='nopart', help='do not use .part files', default=False)
  258. filesystem.add_option('--no-mtime',
  259. action='store_false', dest='updatetime',
  260. help='do not use the Last-modified header to set the file modification time', default=True)
  261. filesystem.add_option('--write-description',
  262. action='store_true', dest='writedescription',
  263. help='write video description to a .description file', default=False)
  264. filesystem.add_option('--write-info-json',
  265. action='store_true', dest='writeinfojson',
  266. help='write video metadata to a .info.json file', default=False)
  267. postproc.add_option('-x', '--extract-audio', action='store_true', dest='extractaudio', default=False,
  268. help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
  269. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  270. help='"best", "aac", "vorbis", "mp3", "m4a", or "wav"; best by default')
  271. postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='5',
  272. help='ffmpeg/avconv audio quality specification, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default 5)')
  273. postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
  274. help='keeps the video file on disk after the post-processing; the video is erased by default')
  275. parser.add_option_group(general)
  276. parser.add_option_group(selection)
  277. parser.add_option_group(filesystem)
  278. parser.add_option_group(verbosity)
  279. parser.add_option_group(video_format)
  280. parser.add_option_group(authentication)
  281. parser.add_option_group(postproc)
  282. xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
  283. if xdg_config_home:
  284. userConf = os.path.join(xdg_config_home, 'youtube-dl.conf')
  285. else:
  286. userConf = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
  287. argv = _readOptions('/etc/youtube-dl.conf') + _readOptions(userConf) + sys.argv[1:]
  288. opts, args = parser.parse_args(argv)
  289. return parser, opts, args
  290. def gen_extractors():
  291. """ Return a list of an instance of every supported extractor.
  292. The order does matter; the first extractor matched is the one handling the URL.
  293. """
  294. return [
  295. YoutubePlaylistIE(),
  296. YoutubeChannelIE(),
  297. YoutubeUserIE(),
  298. YoutubeSearchIE(),
  299. YoutubeIE(),
  300. MetacafeIE(),
  301. DailymotionIE(),
  302. GoogleIE(),
  303. GoogleSearchIE(),
  304. PhotobucketIE(),
  305. YahooIE(),
  306. YahooSearchIE(),
  307. DepositFilesIE(),
  308. FacebookIE(),
  309. BlipTVUserIE(),
  310. BlipTVIE(),
  311. VimeoIE(),
  312. MyVideoIE(),
  313. ComedyCentralIE(),
  314. EscapistIE(),
  315. CollegeHumorIE(),
  316. XVideosIE(),
  317. SoundcloudIE(),
  318. InfoQIE(),
  319. MixcloudIE(),
  320. StanfordOpenClassroomIE(),
  321. MTVIE(),
  322. YoukuIE(),
  323. XNXXIE(),
  324. GooglePlusIE(),
  325. ArteTvIE(),
  326. GenericIE()
  327. ]
  328. def _real_main():
  329. parser, opts, args = parseOpts()
  330. # Open appropriate CookieJar
  331. if opts.cookiefile is None:
  332. jar = compat_cookiejar.CookieJar()
  333. else:
  334. try:
  335. jar = compat_cookiejar.MozillaCookieJar(opts.cookiefile)
  336. if os.path.isfile(opts.cookiefile) and os.access(opts.cookiefile, os.R_OK):
  337. jar.load()
  338. except (IOError, OSError) as err:
  339. sys.exit(u'ERROR: unable to open cookie file')
  340. # Set user agent
  341. if opts.user_agent is not None:
  342. std_headers['User-Agent'] = opts.user_agent
  343. # Dump user agent
  344. if opts.dump_user_agent:
  345. print(std_headers['User-Agent'])
  346. sys.exit(0)
  347. # Batch file verification
  348. batchurls = []
  349. if opts.batchfile is not None:
  350. try:
  351. if opts.batchfile == '-':
  352. batchfd = sys.stdin
  353. else:
  354. batchfd = open(opts.batchfile, 'r')
  355. batchurls = batchfd.readlines()
  356. batchurls = [x.strip() for x in batchurls]
  357. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  358. except IOError:
  359. sys.exit(u'ERROR: batch file could not be read')
  360. all_urls = batchurls + args
  361. all_urls = [url.strip() for url in all_urls]
  362. # General configuration
  363. cookie_processor = compat_urllib_request.HTTPCookieProcessor(jar)
  364. proxy_handler = compat_urllib_request.ProxyHandler()
  365. opener = compat_urllib_request.build_opener(proxy_handler, cookie_processor, YoutubeDLHandler())
  366. compat_urllib_request.install_opener(opener)
  367. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  368. extractors = gen_extractors()
  369. if opts.list_extractors:
  370. for ie in extractors:
  371. print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  372. matchedUrls = filter(lambda url: ie.suitable(url), all_urls)
  373. all_urls = filter(lambda url: url not in matchedUrls, all_urls)
  374. for mu in matchedUrls:
  375. print(u' ' + mu)
  376. sys.exit(0)
  377. # Conflicting, missing and erroneous options
  378. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  379. parser.error(u'using .netrc conflicts with giving username/password')
  380. if opts.password is not None and opts.username is None:
  381. parser.error(u'account username missing')
  382. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  383. parser.error(u'using output template conflicts with using title, video ID or auto number')
  384. if opts.usetitle and opts.useid:
  385. parser.error(u'using title conflicts with using video ID')
  386. if opts.username is not None and opts.password is None:
  387. opts.password = getpass.getpass(u'Type account password and press return:')
  388. if opts.ratelimit is not None:
  389. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  390. if numeric_limit is None:
  391. parser.error(u'invalid rate limit specified')
  392. opts.ratelimit = numeric_limit
  393. if opts.retries is not None:
  394. try:
  395. opts.retries = int(opts.retries)
  396. except (TypeError, ValueError) as err:
  397. parser.error(u'invalid retry count specified')
  398. if opts.buffersize is not None:
  399. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  400. if numeric_buffersize is None:
  401. parser.error(u'invalid buffer size specified')
  402. opts.buffersize = numeric_buffersize
  403. try:
  404. opts.playliststart = int(opts.playliststart)
  405. if opts.playliststart <= 0:
  406. raise ValueError(u'Playlist start must be positive')
  407. except (TypeError, ValueError) as err:
  408. parser.error(u'invalid playlist start number specified')
  409. try:
  410. opts.playlistend = int(opts.playlistend)
  411. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  412. raise ValueError(u'Playlist end must be greater than playlist start')
  413. except (TypeError, ValueError) as err:
  414. parser.error(u'invalid playlist end number specified')
  415. if opts.extractaudio:
  416. if opts.audioformat not in ['best', 'aac', 'mp3', 'vorbis', 'm4a', 'wav']:
  417. parser.error(u'invalid audio format specified')
  418. if opts.audioquality:
  419. opts.audioquality = opts.audioquality.strip('k').strip('K')
  420. if not opts.audioquality.isdigit():
  421. parser.error(u'invalid audio quality specified')
  422. # File downloader
  423. fd = FileDownloader({
  424. 'usenetrc': opts.usenetrc,
  425. 'username': opts.username,
  426. 'password': opts.password,
  427. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  428. 'forceurl': opts.geturl,
  429. 'forcetitle': opts.gettitle,
  430. 'forcethumbnail': opts.getthumbnail,
  431. 'forcedescription': opts.getdescription,
  432. 'forcefilename': opts.getfilename,
  433. 'forceformat': opts.getformat,
  434. 'simulate': opts.simulate,
  435. 'skip_download': (opts.skip_download or opts.simulate or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  436. 'format': opts.format,
  437. 'format_limit': opts.format_limit,
  438. 'listformats': opts.listformats,
  439. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(preferredencoding()))
  440. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  441. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  442. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  443. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  444. or (opts.useid and u'%(id)s.%(ext)s')
  445. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  446. or u'%(id)s.%(ext)s'),
  447. 'restrictfilenames': opts.restrictfilenames,
  448. 'ignoreerrors': opts.ignoreerrors,
  449. 'ratelimit': opts.ratelimit,
  450. 'nooverwrites': opts.nooverwrites,
  451. 'retries': opts.retries,
  452. 'buffersize': opts.buffersize,
  453. 'noresizebuffer': opts.noresizebuffer,
  454. 'continuedl': opts.continue_dl,
  455. 'noprogress': opts.noprogress,
  456. 'playliststart': opts.playliststart,
  457. 'playlistend': opts.playlistend,
  458. 'logtostderr': opts.outtmpl == '-',
  459. 'consoletitle': opts.consoletitle,
  460. 'nopart': opts.nopart,
  461. 'updatetime': opts.updatetime,
  462. 'writedescription': opts.writedescription,
  463. 'writeinfojson': opts.writeinfojson,
  464. 'writesubtitles': opts.writesubtitles,
  465. 'subtitleslang': opts.subtitleslang,
  466. 'matchtitle': opts.matchtitle,
  467. 'rejecttitle': opts.rejecttitle,
  468. 'max_downloads': opts.max_downloads,
  469. 'prefer_free_formats': opts.prefer_free_formats,
  470. 'verbose': opts.verbose,
  471. })
  472. if opts.verbose:
  473. fd.to_screen(u'[debug] Proxy map: ' + str(proxy_handler.proxies))
  474. for extractor in extractors:
  475. fd.add_info_extractor(extractor)
  476. # PostProcessors
  477. if opts.extractaudio:
  478. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, keepvideo=opts.keepvideo))
  479. # Update version
  480. if opts.update_self:
  481. updateSelf(fd, sys.argv[0])
  482. # Maybe do nothing
  483. if len(all_urls) < 1:
  484. if not opts.update_self:
  485. parser.error(u'you must provide at least one URL')
  486. else:
  487. sys.exit()
  488. try:
  489. retcode = fd.download(all_urls)
  490. except MaxDownloadsReached:
  491. fd.to_screen(u'--max-download limit reached, aborting.')
  492. retcode = 101
  493. # Dump cookie jar if requested
  494. if opts.cookiefile is not None:
  495. try:
  496. jar.save()
  497. except (IOError, OSError) as err:
  498. sys.exit(u'ERROR: unable to save cookie jar')
  499. sys.exit(retcode)
  500. def main():
  501. try:
  502. _real_main()
  503. except DownloadError:
  504. sys.exit(1)
  505. except SameFileError:
  506. sys.exit(u'ERROR: fixed output name but more than one file to download')
  507. except KeyboardInterrupt:
  508. sys.exit(u'\nERROR: Interrupted by user')