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.

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