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.

603 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. NBAIE(),
  349. GenericIE()
  350. ]
  351. def _real_main():
  352. parser, opts, args = parseOpts()
  353. # Open appropriate CookieJar
  354. if opts.cookiefile is None:
  355. jar = compat_cookiejar.CookieJar()
  356. else:
  357. try:
  358. jar = compat_cookiejar.MozillaCookieJar(opts.cookiefile)
  359. if os.path.isfile(opts.cookiefile) and os.access(opts.cookiefile, os.R_OK):
  360. jar.load()
  361. except (IOError, OSError) as err:
  362. sys.exit(u'ERROR: unable to open cookie file')
  363. # Set user agent
  364. if opts.user_agent is not None:
  365. std_headers['User-Agent'] = opts.user_agent
  366. # Dump user agent
  367. if opts.dump_user_agent:
  368. print(std_headers['User-Agent'])
  369. sys.exit(0)
  370. # Batch file verification
  371. batchurls = []
  372. if opts.batchfile is not None:
  373. try:
  374. if opts.batchfile == '-':
  375. batchfd = sys.stdin
  376. else:
  377. batchfd = open(opts.batchfile, 'r')
  378. batchurls = batchfd.readlines()
  379. batchurls = [x.strip() for x in batchurls]
  380. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  381. except IOError:
  382. sys.exit(u'ERROR: batch file could not be read')
  383. all_urls = batchurls + args
  384. all_urls = [url.strip() for url in all_urls]
  385. # General configuration
  386. cookie_processor = compat_urllib_request.HTTPCookieProcessor(jar)
  387. proxy_handler = compat_urllib_request.ProxyHandler()
  388. opener = compat_urllib_request.build_opener(proxy_handler, cookie_processor, YoutubeDLHandler())
  389. compat_urllib_request.install_opener(opener)
  390. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  391. extractors = gen_extractors()
  392. if opts.list_extractors:
  393. for ie in extractors:
  394. print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  395. matchedUrls = filter(lambda url: ie.suitable(url), all_urls)
  396. all_urls = filter(lambda url: url not in matchedUrls, all_urls)
  397. for mu in matchedUrls:
  398. print(u' ' + mu)
  399. sys.exit(0)
  400. # Conflicting, missing and erroneous options
  401. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  402. parser.error(u'using .netrc conflicts with giving username/password')
  403. if opts.password is not None and opts.username is None:
  404. parser.error(u'account username missing')
  405. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  406. parser.error(u'using output template conflicts with using title, video ID or auto number')
  407. if opts.usetitle and opts.useid:
  408. parser.error(u'using title conflicts with using video ID')
  409. if opts.username is not None and opts.password is None:
  410. opts.password = getpass.getpass(u'Type account password and press return:')
  411. if opts.ratelimit is not None:
  412. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  413. if numeric_limit is None:
  414. parser.error(u'invalid rate limit specified')
  415. opts.ratelimit = numeric_limit
  416. if opts.retries is not None:
  417. try:
  418. opts.retries = int(opts.retries)
  419. except (TypeError, ValueError) as err:
  420. parser.error(u'invalid retry count specified')
  421. if opts.buffersize is not None:
  422. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  423. if numeric_buffersize is None:
  424. parser.error(u'invalid buffer size specified')
  425. opts.buffersize = numeric_buffersize
  426. try:
  427. opts.playliststart = int(opts.playliststart)
  428. if opts.playliststart <= 0:
  429. raise ValueError(u'Playlist start must be positive')
  430. except (TypeError, ValueError) as err:
  431. parser.error(u'invalid playlist start number specified')
  432. try:
  433. opts.playlistend = int(opts.playlistend)
  434. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  435. raise ValueError(u'Playlist end must be greater than playlist start')
  436. except (TypeError, ValueError) as err:
  437. parser.error(u'invalid playlist end number specified')
  438. if opts.extractaudio:
  439. if opts.audioformat not in ['best', 'aac', 'mp3', 'vorbis', 'm4a', 'wav']:
  440. parser.error(u'invalid audio format specified')
  441. if opts.audioquality:
  442. opts.audioquality = opts.audioquality.strip('k').strip('K')
  443. if not opts.audioquality.isdigit():
  444. parser.error(u'invalid audio quality specified')
  445. # File downloader
  446. fd = FileDownloader({
  447. 'usenetrc': opts.usenetrc,
  448. 'username': opts.username,
  449. 'password': opts.password,
  450. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  451. 'forceurl': opts.geturl,
  452. 'forcetitle': opts.gettitle,
  453. 'forcethumbnail': opts.getthumbnail,
  454. 'forcedescription': opts.getdescription,
  455. 'forcefilename': opts.getfilename,
  456. 'forceformat': opts.getformat,
  457. 'simulate': opts.simulate,
  458. '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),
  459. 'format': opts.format,
  460. 'format_limit': opts.format_limit,
  461. 'listformats': opts.listformats,
  462. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(preferredencoding()))
  463. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  464. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  465. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  466. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  467. or (opts.useid and u'%(id)s.%(ext)s')
  468. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  469. or u'%(id)s.%(ext)s'),
  470. 'restrictfilenames': opts.restrictfilenames,
  471. 'ignoreerrors': opts.ignoreerrors,
  472. 'ratelimit': opts.ratelimit,
  473. 'nooverwrites': opts.nooverwrites,
  474. 'retries': opts.retries,
  475. 'buffersize': opts.buffersize,
  476. 'noresizebuffer': opts.noresizebuffer,
  477. 'continuedl': opts.continue_dl,
  478. 'noprogress': opts.noprogress,
  479. 'playliststart': opts.playliststart,
  480. 'playlistend': opts.playlistend,
  481. 'logtostderr': opts.outtmpl == '-',
  482. 'consoletitle': opts.consoletitle,
  483. 'nopart': opts.nopart,
  484. 'updatetime': opts.updatetime,
  485. 'writedescription': opts.writedescription,
  486. 'writeinfojson': opts.writeinfojson,
  487. 'writesubtitles': opts.writesubtitles,
  488. 'subtitleslang': opts.subtitleslang,
  489. 'matchtitle': opts.matchtitle,
  490. 'rejecttitle': opts.rejecttitle,
  491. 'max_downloads': opts.max_downloads,
  492. 'prefer_free_formats': opts.prefer_free_formats,
  493. 'verbose': opts.verbose,
  494. 'test': opts.test,
  495. })
  496. if opts.verbose:
  497. fd.to_screen(u'[debug] Proxy map: ' + str(proxy_handler.proxies))
  498. for extractor in extractors:
  499. fd.add_info_extractor(extractor)
  500. # PostProcessors
  501. if opts.extractaudio:
  502. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, keepvideo=opts.keepvideo))
  503. # Update version
  504. if opts.update_self:
  505. updateSelf(fd, sys.argv[0])
  506. # Maybe do nothing
  507. if len(all_urls) < 1:
  508. if not opts.update_self:
  509. parser.error(u'you must provide at least one URL')
  510. else:
  511. sys.exit()
  512. try:
  513. retcode = fd.download(all_urls)
  514. except MaxDownloadsReached:
  515. fd.to_screen(u'--max-download limit reached, aborting.')
  516. retcode = 101
  517. # Dump cookie jar if requested
  518. if opts.cookiefile is not None:
  519. try:
  520. jar.save()
  521. except (IOError, OSError) as err:
  522. sys.exit(u'ERROR: unable to save cookie jar')
  523. sys.exit(retcode)
  524. def main():
  525. try:
  526. _real_main()
  527. except DownloadError:
  528. sys.exit(1)
  529. except SameFileError:
  530. sys.exit(u'ERROR: fixed output name but more than one file to download')
  531. except KeyboardInterrupt:
  532. sys.exit(u'\nERROR: Interrupted by user')