[options] Mention quoted string literals for --match-filter
[youtube-dl] / youtube_dl / options.py
1 from __future__ import unicode_literals
2
3 import os.path
4 import optparse
5 import re
6 import sys
7
8 from .downloader.external import list_external_downloaders
9 from .compat import (
10     compat_expanduser,
11     compat_get_terminal_size,
12     compat_getenv,
13     compat_kwargs,
14     compat_shlex_split,
15 )
16 from .utils import (
17     preferredencoding,
18     write_string,
19 )
20 from .version import __version__
21
22
23 def parseOpts(overrideArguments=None):
24     def _readOptions(filename_bytes, default=[]):
25         try:
26             optionf = open(filename_bytes)
27         except IOError:
28             return default  # silently skip if file is not present
29         try:
30             # FIXME: https://github.com/rg3/youtube-dl/commit/dfe5fa49aed02cf36ba9f743b11b0903554b5e56
31             contents = optionf.read()
32             if sys.version_info < (3,):
33                 contents = contents.decode(preferredencoding())
34             res = compat_shlex_split(contents, comments=True)
35         finally:
36             optionf.close()
37         return res
38
39     def _readUserConf():
40         xdg_config_home = compat_getenv('XDG_CONFIG_HOME')
41         if xdg_config_home:
42             userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')
43             if not os.path.isfile(userConfFile):
44                 userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
45         else:
46             userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl', 'config')
47             if not os.path.isfile(userConfFile):
48                 userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl.conf')
49         userConf = _readOptions(userConfFile, None)
50
51         if userConf is None:
52             appdata_dir = compat_getenv('appdata')
53             if appdata_dir:
54                 userConf = _readOptions(
55                     os.path.join(appdata_dir, 'youtube-dl', 'config'),
56                     default=None)
57                 if userConf is None:
58                     userConf = _readOptions(
59                         os.path.join(appdata_dir, 'youtube-dl', 'config.txt'),
60                         default=None)
61
62         if userConf is None:
63             userConf = _readOptions(
64                 os.path.join(compat_expanduser('~'), 'youtube-dl.conf'),
65                 default=None)
66         if userConf is None:
67             userConf = _readOptions(
68                 os.path.join(compat_expanduser('~'), 'youtube-dl.conf.txt'),
69                 default=None)
70
71         if userConf is None:
72             userConf = []
73
74         return userConf
75
76     def _format_option_string(option):
77         ''' ('-o', '--option') -> -o, --format METAVAR'''
78
79         opts = []
80
81         if option._short_opts:
82             opts.append(option._short_opts[0])
83         if option._long_opts:
84             opts.append(option._long_opts[0])
85         if len(opts) > 1:
86             opts.insert(1, ', ')
87
88         if option.takes_value():
89             opts.append(' %s' % option.metavar)
90
91         return ''.join(opts)
92
93     def _comma_separated_values_options_callback(option, opt_str, value, parser):
94         setattr(parser.values, option.dest, value.split(','))
95
96     def _hide_login_info(opts):
97         PRIVATE_OPTS = ['-p', '--password', '-u', '--username', '--video-password', '--ap-password', '--ap-username']
98         eqre = re.compile('^(?P<key>' + ('|'.join(re.escape(po) for po in PRIVATE_OPTS)) + ')=.+$')
99
100         def _scrub_eq(o):
101             m = eqre.match(o)
102             if m:
103                 return m.group('key') + '=PRIVATE'
104             else:
105                 return o
106
107         opts = list(map(_scrub_eq, opts))
108         for private_opt in PRIVATE_OPTS:
109             try:
110                 i = opts.index(private_opt)
111                 opts[i + 1] = 'PRIVATE'
112             except ValueError:
113                 pass
114         return opts
115
116     # No need to wrap help messages if we're on a wide console
117     columns = compat_get_terminal_size().columns
118     max_width = columns if columns else 80
119     max_help_position = 80
120
121     fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
122     fmt.format_option_strings = _format_option_string
123
124     kw = {
125         'version': __version__,
126         'formatter': fmt,
127         'usage': '%prog [OPTIONS] URL [URL...]',
128         'conflict_handler': 'resolve',
129     }
130
131     parser = optparse.OptionParser(**compat_kwargs(kw))
132
133     general = optparse.OptionGroup(parser, 'General Options')
134     general.add_option(
135         '-h', '--help',
136         action='help',
137         help='Print this help text and exit')
138     general.add_option(
139         '-v', '--version',
140         action='version',
141         help='Print program version and exit')
142     general.add_option(
143         '-U', '--update',
144         action='store_true', dest='update_self',
145         help='Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
146     general.add_option(
147         '-i', '--ignore-errors',
148         action='store_true', dest='ignoreerrors', default=False,
149         help='Continue on download errors, for example to skip unavailable videos in a playlist')
150     general.add_option(
151         '--abort-on-error',
152         action='store_false', dest='ignoreerrors',
153         help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')
154     general.add_option(
155         '--dump-user-agent',
156         action='store_true', dest='dump_user_agent', default=False,
157         help='Display the current browser identification')
158     general.add_option(
159         '--list-extractors',
160         action='store_true', dest='list_extractors', default=False,
161         help='List all supported extractors')
162     general.add_option(
163         '--extractor-descriptions',
164         action='store_true', dest='list_extractor_descriptions', default=False,
165         help='Output descriptions of all supported extractors')
166     general.add_option(
167         '--force-generic-extractor',
168         action='store_true', dest='force_generic_extractor', default=False,
169         help='Force extraction to use the generic extractor')
170     general.add_option(
171         '--default-search',
172         dest='default_search', metavar='PREFIX',
173         help='Use this prefix for unqualified URLs. For example "gvsearch2:" downloads two videos from google videos for youtube-dl "large apple". Use the value "auto" to let youtube-dl guess ("auto_warning" to emit a warning when guessing). "error" just throws an error. The default value "fixup_error" repairs broken URLs, but emits an error if this is not possible instead of searching.')
174     general.add_option(
175         '--ignore-config',
176         action='store_true',
177         help='Do not read configuration files. '
178         'When given in the global configuration file /etc/youtube-dl.conf: '
179         'Do not read the user configuration in ~/.config/youtube-dl/config '
180         '(%APPDATA%/youtube-dl/config.txt on Windows)')
181     general.add_option(
182         '--config-location',
183         dest='config_location', metavar='PATH',
184         help='Location of the configuration file; either the path to the config or its containing directory.')
185     general.add_option(
186         '--flat-playlist',
187         action='store_const', dest='extract_flat', const='in_playlist',
188         default=False,
189         help='Do not extract the videos of a playlist, only list them.')
190     general.add_option(
191         '--mark-watched',
192         action='store_true', dest='mark_watched', default=False,
193         help='Mark videos watched (YouTube only)')
194     general.add_option(
195         '--no-mark-watched',
196         action='store_false', dest='mark_watched', default=False,
197         help='Do not mark videos watched (YouTube only)')
198     general.add_option(
199         '--no-color', '--no-colors',
200         action='store_true', dest='no_color',
201         default=False,
202         help='Do not emit color codes in output')
203
204     network = optparse.OptionGroup(parser, 'Network Options')
205     network.add_option(
206         '--proxy', dest='proxy',
207         default=None, metavar='URL',
208         help='Use the specified HTTP/HTTPS/SOCKS proxy. To enable experimental '
209              'SOCKS proxy, specify a proper scheme. For example '
210              'socks5://127.0.0.1:1080/. Pass in an empty string (--proxy "") '
211              'for direct connection')
212     network.add_option(
213         '--socket-timeout',
214         dest='socket_timeout', type=float, default=None, metavar='SECONDS',
215         help='Time to wait before giving up, in seconds')
216     network.add_option(
217         '--source-address',
218         metavar='IP', dest='source_address', default=None,
219         help='Client-side IP address to bind to',
220     )
221     network.add_option(
222         '-4', '--force-ipv4',
223         action='store_const', const='0.0.0.0', dest='source_address',
224         help='Make all connections via IPv4',
225     )
226     network.add_option(
227         '-6', '--force-ipv6',
228         action='store_const', const='::', dest='source_address',
229         help='Make all connections via IPv6',
230     )
231     network.add_option(
232         '--geo-verification-proxy',
233         dest='geo_verification_proxy', default=None, metavar='URL',
234         help='Use this proxy to verify the IP address for some geo-restricted sites. '
235         'The default proxy specified by --proxy (or none, if the options is not present) is used for the actual downloading.'
236     )
237     network.add_option(
238         '--cn-verification-proxy',
239         dest='cn_verification_proxy', default=None, metavar='URL',
240         help=optparse.SUPPRESS_HELP,
241     )
242
243     selection = optparse.OptionGroup(parser, 'Video Selection')
244     selection.add_option(
245         '--playlist-start',
246         dest='playliststart', metavar='NUMBER', default=1, type=int,
247         help='Playlist video to start at (default is %default)')
248     selection.add_option(
249         '--playlist-end',
250         dest='playlistend', metavar='NUMBER', default=None, type=int,
251         help='Playlist video to end at (default is last)')
252     selection.add_option(
253         '--playlist-items',
254         dest='playlist_items', metavar='ITEM_SPEC', default=None,
255         help='Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: "--playlist-items 1,2,5,8" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: "--playlist-items 1-3,7,10-13", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13.')
256     selection.add_option(
257         '--match-title',
258         dest='matchtitle', metavar='REGEX',
259         help='Download only matching titles (regex or caseless sub-string)')
260     selection.add_option(
261         '--reject-title',
262         dest='rejecttitle', metavar='REGEX',
263         help='Skip download for matching titles (regex or caseless sub-string)')
264     selection.add_option(
265         '--max-downloads',
266         dest='max_downloads', metavar='NUMBER', type=int, default=None,
267         help='Abort after downloading NUMBER files')
268     selection.add_option(
269         '--min-filesize',
270         metavar='SIZE', dest='min_filesize', default=None,
271         help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
272     selection.add_option(
273         '--max-filesize',
274         metavar='SIZE', dest='max_filesize', default=None,
275         help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
276     selection.add_option(
277         '--date',
278         metavar='DATE', dest='date', default=None,
279         help='Download only videos uploaded in this date')
280     selection.add_option(
281         '--datebefore',
282         metavar='DATE', dest='datebefore', default=None,
283         help='Download only videos uploaded on or before this date (i.e. inclusive)')
284     selection.add_option(
285         '--dateafter',
286         metavar='DATE', dest='dateafter', default=None,
287         help='Download only videos uploaded on or after this date (i.e. inclusive)')
288     selection.add_option(
289         '--min-views',
290         metavar='COUNT', dest='min_views', default=None, type=int,
291         help='Do not download any videos with less than COUNT views')
292     selection.add_option(
293         '--max-views',
294         metavar='COUNT', dest='max_views', default=None, type=int,
295         help='Do not download any videos with more than COUNT views')
296     selection.add_option(
297         '--match-filter',
298         metavar='FILTER', dest='match_filter', default=None,
299         help=(
300             'Generic video filter. '
301             'Specify any key (see help for -o for a list of available keys) to '
302             'match if the key is present, '
303             '!key to check if the key is not present, '
304             'key > NUMBER (like "comment_count > 12", also works with '
305             '>=, <, <=, !=, =) to compare against a number, '
306             'key = \'LITERAL\' (like "uploader = \'Mike Smith\'", also works with !=) '
307             'to match against a string literal '
308             'and & to require multiple matches. '
309             'Values which are not known are excluded unless you '
310             'put a question mark (?) after the operator. '
311             'For example, to only match videos that have been liked more than '
312             '100 times and disliked less than 50 times (or the dislike '
313             'functionality is not available at the given service), but who '
314             'also have a description, use --match-filter '
315             '"like_count > 100 & dislike_count <? 50 & description" .'
316         ))
317     selection.add_option(
318         '--no-playlist',
319         action='store_true', dest='noplaylist', default=False,
320         help='Download only the video, if the URL refers to a video and a playlist.')
321     selection.add_option(
322         '--yes-playlist',
323         action='store_false', dest='noplaylist', default=False,
324         help='Download the playlist, if the URL refers to a video and a playlist.')
325     selection.add_option(
326         '--age-limit',
327         metavar='YEARS', dest='age_limit', default=None, type=int,
328         help='Download only videos suitable for the given age')
329     selection.add_option(
330         '--download-archive', metavar='FILE',
331         dest='download_archive',
332         help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
333     selection.add_option(
334         '--include-ads',
335         dest='include_ads', action='store_true',
336         help='Download advertisements as well (experimental)')
337
338     authentication = optparse.OptionGroup(parser, 'Authentication Options')
339     authentication.add_option(
340         '-u', '--username',
341         dest='username', metavar='USERNAME',
342         help='Login with this account ID')
343     authentication.add_option(
344         '-p', '--password',
345         dest='password', metavar='PASSWORD',
346         help='Account password. If this option is left out, youtube-dl will ask interactively.')
347     authentication.add_option(
348         '-2', '--twofactor',
349         dest='twofactor', metavar='TWOFACTOR',
350         help='Two-factor authentication code')
351     authentication.add_option(
352         '-n', '--netrc',
353         action='store_true', dest='usenetrc', default=False,
354         help='Use .netrc authentication data')
355     authentication.add_option(
356         '--video-password',
357         dest='videopassword', metavar='PASSWORD',
358         help='Video password (vimeo, smotri, youku)')
359
360     adobe_pass = optparse.OptionGroup(parser, 'Adobe Pass Options')
361     adobe_pass.add_option(
362         '--ap-mso',
363         dest='ap_mso', metavar='MSO',
364         help='Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs')
365     adobe_pass.add_option(
366         '--ap-username',
367         dest='ap_username', metavar='USERNAME',
368         help='Multiple-system operator account login')
369     adobe_pass.add_option(
370         '--ap-password',
371         dest='ap_password', metavar='PASSWORD',
372         help='Multiple-system operator account password. If this option is left out, youtube-dl will ask interactively.')
373     adobe_pass.add_option(
374         '--ap-list-mso',
375         action='store_true', dest='ap_list_mso', default=False,
376         help='List all supported multiple-system operators')
377
378     video_format = optparse.OptionGroup(parser, 'Video Format Options')
379     video_format.add_option(
380         '-f', '--format',
381         action='store', dest='format', metavar='FORMAT', default=None,
382         help='Video format code, see the "FORMAT SELECTION" for all the info')
383     video_format.add_option(
384         '--all-formats',
385         action='store_const', dest='format', const='all',
386         help='Download all available video formats')
387     video_format.add_option(
388         '--prefer-free-formats',
389         action='store_true', dest='prefer_free_formats', default=False,
390         help='Prefer free video formats unless a specific one is requested')
391     video_format.add_option(
392         '-F', '--list-formats',
393         action='store_true', dest='listformats',
394         help='List all available formats of requested videos')
395     video_format.add_option(
396         '--youtube-include-dash-manifest',
397         action='store_true', dest='youtube_include_dash_manifest', default=True,
398         help=optparse.SUPPRESS_HELP)
399     video_format.add_option(
400         '--youtube-skip-dash-manifest',
401         action='store_false', dest='youtube_include_dash_manifest',
402         help='Do not download the DASH manifests and related data on YouTube videos')
403     video_format.add_option(
404         '--merge-output-format',
405         action='store', dest='merge_output_format', metavar='FORMAT', default=None,
406         help=(
407             'If a merge is required (e.g. bestvideo+bestaudio), '
408             'output to given container format. One of mkv, mp4, ogg, webm, flv. '
409             'Ignored if no merge is required'))
410
411     subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
412     subtitles.add_option(
413         '--write-sub', '--write-srt',
414         action='store_true', dest='writesubtitles', default=False,
415         help='Write subtitle file')
416     subtitles.add_option(
417         '--write-auto-sub', '--write-automatic-sub',
418         action='store_true', dest='writeautomaticsub', default=False,
419         help='Write automatically generated subtitle file (YouTube only)')
420     subtitles.add_option(
421         '--all-subs',
422         action='store_true', dest='allsubtitles', default=False,
423         help='Download all the available subtitles of the video')
424     subtitles.add_option(
425         '--list-subs',
426         action='store_true', dest='listsubtitles', default=False,
427         help='List all available subtitles for the video')
428     subtitles.add_option(
429         '--sub-format',
430         action='store', dest='subtitlesformat', metavar='FORMAT', default='best',
431         help='Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"')
432     subtitles.add_option(
433         '--sub-lang', '--sub-langs', '--srt-lang',
434         action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
435         default=[], callback=_comma_separated_values_options_callback,
436         help='Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags')
437
438     downloader = optparse.OptionGroup(parser, 'Download Options')
439     downloader.add_option(
440         '-r', '--limit-rate', '--rate-limit',
441         dest='ratelimit', metavar='RATE',
442         help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)')
443     downloader.add_option(
444         '-R', '--retries',
445         dest='retries', metavar='RETRIES', default=10,
446         help='Number of retries (default is %default), or "infinite".')
447     downloader.add_option(
448         '--fragment-retries',
449         dest='fragment_retries', metavar='RETRIES', default=10,
450         help='Number of retries for a fragment (default is %default), or "infinite" (DASH and hlsnative only)')
451     downloader.add_option(
452         '--skip-unavailable-fragments',
453         action='store_true', dest='skip_unavailable_fragments', default=True,
454         help='Skip unavailable fragments (DASH and hlsnative only)')
455     downloader.add_option(
456         '--abort-on-unavailable-fragment',
457         action='store_false', dest='skip_unavailable_fragments',
458         help='Abort downloading when some fragment is not available')
459     downloader.add_option(
460         '--buffer-size',
461         dest='buffersize', metavar='SIZE', default='1024',
462         help='Size of download buffer (e.g. 1024 or 16K) (default is %default)')
463     downloader.add_option(
464         '--no-resize-buffer',
465         action='store_true', dest='noresizebuffer', default=False,
466         help='Do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.')
467     downloader.add_option(
468         '--test',
469         action='store_true', dest='test', default=False,
470         help=optparse.SUPPRESS_HELP)
471     downloader.add_option(
472         '--playlist-reverse',
473         action='store_true',
474         help='Download playlist videos in reverse order')
475     downloader.add_option(
476         '--playlist-random',
477         action='store_true',
478         help='Download playlist videos in random order')
479     downloader.add_option(
480         '--xattr-set-filesize',
481         dest='xattr_set_filesize', action='store_true',
482         help='Set file xattribute ytdl.filesize with expected file size (experimental)')
483     downloader.add_option(
484         '--hls-prefer-native',
485         dest='hls_prefer_native', action='store_true', default=None,
486         help='Use the native HLS downloader instead of ffmpeg')
487     downloader.add_option(
488         '--hls-prefer-ffmpeg',
489         dest='hls_prefer_native', action='store_false', default=None,
490         help='Use ffmpeg instead of the native HLS downloader')
491     downloader.add_option(
492         '--hls-use-mpegts',
493         dest='hls_use_mpegts', action='store_true',
494         help='Use the mpegts container for HLS videos, allowing to play the '
495              'video while downloading (some players may not be able to play it)')
496     downloader.add_option(
497         '--external-downloader',
498         dest='external_downloader', metavar='COMMAND',
499         help='Use the specified external downloader. '
500              'Currently supports %s' % ','.join(list_external_downloaders()))
501     downloader.add_option(
502         '--external-downloader-args',
503         dest='external_downloader_args', metavar='ARGS',
504         help='Give these arguments to the external downloader')
505
506     workarounds = optparse.OptionGroup(parser, 'Workarounds')
507     workarounds.add_option(
508         '--encoding',
509         dest='encoding', metavar='ENCODING',
510         help='Force the specified encoding (experimental)')
511     workarounds.add_option(
512         '--no-check-certificate',
513         action='store_true', dest='no_check_certificate', default=False,
514         help='Suppress HTTPS certificate validation')
515     workarounds.add_option(
516         '--prefer-insecure',
517         '--prefer-unsecure', action='store_true', dest='prefer_insecure',
518         help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
519     workarounds.add_option(
520         '--user-agent',
521         metavar='UA', dest='user_agent',
522         help='Specify a custom user agent')
523     workarounds.add_option(
524         '--referer',
525         metavar='URL', dest='referer', default=None,
526         help='Specify a custom referer, use if the video access is restricted to one domain',
527     )
528     workarounds.add_option(
529         '--add-header',
530         metavar='FIELD:VALUE', dest='headers', action='append',
531         help='Specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
532     )
533     workarounds.add_option(
534         '--bidi-workaround',
535         dest='bidi_workaround', action='store_true',
536         help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
537     workarounds.add_option(
538         '--sleep-interval', '--min-sleep-interval', metavar='SECONDS',
539         dest='sleep_interval', type=float,
540         help=(
541             'Number of seconds to sleep before each download when used alone '
542             'or a lower bound of a range for randomized sleep before each download '
543             '(minimum possible number of seconds to sleep) when used along with '
544             '--max-sleep-interval.'))
545     workarounds.add_option(
546         '--max-sleep-interval', metavar='SECONDS',
547         dest='max_sleep_interval', type=float,
548         help=(
549             'Upper bound of a range for randomized sleep before each download '
550             '(maximum possible number of seconds to sleep). Must only be used '
551             'along with --min-sleep-interval.'))
552
553     verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
554     verbosity.add_option(
555         '-q', '--quiet',
556         action='store_true', dest='quiet', default=False,
557         help='Activate quiet mode')
558     verbosity.add_option(
559         '--no-warnings',
560         dest='no_warnings', action='store_true', default=False,
561         help='Ignore warnings')
562     verbosity.add_option(
563         '-s', '--simulate',
564         action='store_true', dest='simulate', default=False,
565         help='Do not download the video and do not write anything to disk')
566     verbosity.add_option(
567         '--skip-download',
568         action='store_true', dest='skip_download', default=False,
569         help='Do not download the video')
570     verbosity.add_option(
571         '-g', '--get-url',
572         action='store_true', dest='geturl', default=False,
573         help='Simulate, quiet but print URL')
574     verbosity.add_option(
575         '-e', '--get-title',
576         action='store_true', dest='gettitle', default=False,
577         help='Simulate, quiet but print title')
578     verbosity.add_option(
579         '--get-id',
580         action='store_true', dest='getid', default=False,
581         help='Simulate, quiet but print id')
582     verbosity.add_option(
583         '--get-thumbnail',
584         action='store_true', dest='getthumbnail', default=False,
585         help='Simulate, quiet but print thumbnail URL')
586     verbosity.add_option(
587         '--get-description',
588         action='store_true', dest='getdescription', default=False,
589         help='Simulate, quiet but print video description')
590     verbosity.add_option(
591         '--get-duration',
592         action='store_true', dest='getduration', default=False,
593         help='Simulate, quiet but print video length')
594     verbosity.add_option(
595         '--get-filename',
596         action='store_true', dest='getfilename', default=False,
597         help='Simulate, quiet but print output filename')
598     verbosity.add_option(
599         '--get-format',
600         action='store_true', dest='getformat', default=False,
601         help='Simulate, quiet but print output format')
602     verbosity.add_option(
603         '-j', '--dump-json',
604         action='store_true', dest='dumpjson', default=False,
605         help='Simulate, quiet but print JSON information. See --output for a description of available keys.')
606     verbosity.add_option(
607         '-J', '--dump-single-json',
608         action='store_true', dest='dump_single_json', default=False,
609         help='Simulate, quiet but print JSON information for each command-line argument. If the URL refers to a playlist, dump the whole playlist information in a single line.')
610     verbosity.add_option(
611         '--print-json',
612         action='store_true', dest='print_json', default=False,
613         help='Be quiet and print the video information as JSON (video is still being downloaded).',
614     )
615     verbosity.add_option(
616         '--newline',
617         action='store_true', dest='progress_with_newline', default=False,
618         help='Output progress bar as new lines')
619     verbosity.add_option(
620         '--no-progress',
621         action='store_true', dest='noprogress', default=False,
622         help='Do not print progress bar')
623     verbosity.add_option(
624         '--console-title',
625         action='store_true', dest='consoletitle', default=False,
626         help='Display progress in console titlebar')
627     verbosity.add_option(
628         '-v', '--verbose',
629         action='store_true', dest='verbose', default=False,
630         help='Print various debugging information')
631     verbosity.add_option(
632         '--dump-pages', '--dump-intermediate-pages',
633         action='store_true', dest='dump_intermediate_pages', default=False,
634         help='Print downloaded pages encoded using base64 to debug problems (very verbose)')
635     verbosity.add_option(
636         '--write-pages',
637         action='store_true', dest='write_pages', default=False,
638         help='Write downloaded intermediary pages to files in the current directory to debug problems')
639     verbosity.add_option(
640         '--youtube-print-sig-code',
641         action='store_true', dest='youtube_print_sig_code', default=False,
642         help=optparse.SUPPRESS_HELP)
643     verbosity.add_option(
644         '--print-traffic', '--dump-headers',
645         dest='debug_printtraffic', action='store_true', default=False,
646         help='Display sent and read HTTP traffic')
647     verbosity.add_option(
648         '-C', '--call-home',
649         dest='call_home', action='store_true', default=False,
650         help='Contact the youtube-dl server for debugging')
651     verbosity.add_option(
652         '--no-call-home',
653         dest='call_home', action='store_false', default=False,
654         help='Do NOT contact the youtube-dl server for debugging')
655
656     filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
657     filesystem.add_option(
658         '-a', '--batch-file',
659         dest='batchfile', metavar='FILE',
660         help='File containing URLs to download (\'-\' for stdin)')
661     filesystem.add_option(
662         '--id', default=False,
663         action='store_true', dest='useid', help='Use only video ID in file name')
664     filesystem.add_option(
665         '-o', '--output',
666         dest='outtmpl', metavar='TEMPLATE',
667         help=('Output filename template, see the "OUTPUT TEMPLATE" for all the info'))
668     filesystem.add_option(
669         '--autonumber-size',
670         dest='autonumber_size', metavar='NUMBER', default=5, type=int,
671         help='Specify the number of digits in %(autonumber)s when it is present in output filename template or --auto-number option is given (default is %default)')
672     filesystem.add_option(
673         '--autonumber-start',
674         dest='autonumber_start', metavar='NUMBER', default=1, type=int,
675         help='Specify the start value for %(autonumber)s (default is %default)')
676     filesystem.add_option(
677         '--restrict-filenames',
678         action='store_true', dest='restrictfilenames', default=False,
679         help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
680     filesystem.add_option(
681         '-A', '--auto-number',
682         action='store_true', dest='autonumber', default=False,
683         help='[deprecated; use -o "%(autonumber)s-%(title)s.%(ext)s" ] Number downloaded files starting from 00000')
684     filesystem.add_option(
685         '-t', '--title',
686         action='store_true', dest='usetitle', default=False,
687         help='[deprecated] Use title in file name (default)')
688     filesystem.add_option(
689         '-l', '--literal', default=False,
690         action='store_true', dest='usetitle',
691         help='[deprecated] Alias of --title')
692     filesystem.add_option(
693         '-w', '--no-overwrites',
694         action='store_true', dest='nooverwrites', default=False,
695         help='Do not overwrite files')
696     filesystem.add_option(
697         '-c', '--continue',
698         action='store_true', dest='continue_dl', default=True,
699         help='Force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.')
700     filesystem.add_option(
701         '--no-continue',
702         action='store_false', dest='continue_dl',
703         help='Do not resume partially downloaded files (restart from beginning)')
704     filesystem.add_option(
705         '--no-part',
706         action='store_true', dest='nopart', default=False,
707         help='Do not use .part files - write directly into output file')
708     filesystem.add_option(
709         '--no-mtime',
710         action='store_false', dest='updatetime', default=True,
711         help='Do not use the Last-modified header to set the file modification time')
712     filesystem.add_option(
713         '--write-description',
714         action='store_true', dest='writedescription', default=False,
715         help='Write video description to a .description file')
716     filesystem.add_option(
717         '--write-info-json',
718         action='store_true', dest='writeinfojson', default=False,
719         help='Write video metadata to a .info.json file')
720     filesystem.add_option(
721         '--write-annotations',
722         action='store_true', dest='writeannotations', default=False,
723         help='Write video annotations to a .annotations.xml file')
724     filesystem.add_option(
725         '--load-info-json', '--load-info',
726         dest='load_info_filename', metavar='FILE',
727         help='JSON file containing the video information (created with the "--write-info-json" option)')
728     filesystem.add_option(
729         '--cookies',
730         dest='cookiefile', metavar='FILE',
731         help='File to read cookies from and dump cookie jar in')
732     filesystem.add_option(
733         '--cache-dir', dest='cachedir', default=None, metavar='DIR',
734         help='Location in the filesystem where youtube-dl can store some downloaded information permanently. By default $XDG_CACHE_HOME/youtube-dl or ~/.cache/youtube-dl . At the moment, only YouTube player files (for videos with obfuscated signatures) are cached, but that may change.')
735     filesystem.add_option(
736         '--no-cache-dir', action='store_const', const=False, dest='cachedir',
737         help='Disable filesystem caching')
738     filesystem.add_option(
739         '--rm-cache-dir',
740         action='store_true', dest='rm_cachedir',
741         help='Delete all filesystem cache files')
742
743     thumbnail = optparse.OptionGroup(parser, 'Thumbnail images')
744     thumbnail.add_option(
745         '--write-thumbnail',
746         action='store_true', dest='writethumbnail', default=False,
747         help='Write thumbnail image to disk')
748     thumbnail.add_option(
749         '--write-all-thumbnails',
750         action='store_true', dest='write_all_thumbnails', default=False,
751         help='Write all thumbnail image formats to disk')
752     thumbnail.add_option(
753         '--list-thumbnails',
754         action='store_true', dest='list_thumbnails', default=False,
755         help='Simulate and list all available thumbnail formats')
756
757     postproc = optparse.OptionGroup(parser, 'Post-processing Options')
758     postproc.add_option(
759         '-x', '--extract-audio',
760         action='store_true', dest='extractaudio', default=False,
761         help='Convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
762     postproc.add_option(
763         '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
764         help='Specify audio format: "best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; "%default" by default; No effect without -x')
765     postproc.add_option(
766         '--audio-quality', metavar='QUALITY',
767         dest='audioquality', default='5',
768         help='Specify ffmpeg/avconv audio quality, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default %default)')
769     postproc.add_option(
770         '--recode-video',
771         metavar='FORMAT', dest='recodevideo', default=None,
772         help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)')
773     postproc.add_option(
774         '--postprocessor-args',
775         dest='postprocessor_args', metavar='ARGS',
776         help='Give these arguments to the postprocessor')
777     postproc.add_option(
778         '-k', '--keep-video',
779         action='store_true', dest='keepvideo', default=False,
780         help='Keep the video file on disk after the post-processing; the video is erased by default')
781     postproc.add_option(
782         '--no-post-overwrites',
783         action='store_true', dest='nopostoverwrites', default=False,
784         help='Do not overwrite post-processed files; the post-processed files are overwritten by default')
785     postproc.add_option(
786         '--embed-subs',
787         action='store_true', dest='embedsubtitles', default=False,
788         help='Embed subtitles in the video (only for mp4, webm and mkv videos)')
789     postproc.add_option(
790         '--embed-thumbnail',
791         action='store_true', dest='embedthumbnail', default=False,
792         help='Embed thumbnail in the audio as cover art')
793     postproc.add_option(
794         '--add-metadata',
795         action='store_true', dest='addmetadata', default=False,
796         help='Write metadata to the video file')
797     postproc.add_option(
798         '--metadata-from-title',
799         metavar='FORMAT', dest='metafromtitle',
800         help='Parse additional metadata like song title / artist from the video title. '
801              'The format syntax is the same as --output, '
802              'the parsed parameters replace existing values. '
803              'Additional templates: %(album)s, %(artist)s. '
804              'Example: --metadata-from-title "%(artist)s - %(title)s" matches a title like '
805              '"Coldplay - Paradise"')
806     postproc.add_option(
807         '--xattrs',
808         action='store_true', dest='xattrs', default=False,
809         help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
810     postproc.add_option(
811         '--fixup',
812         metavar='POLICY', dest='fixup', default='detect_or_warn',
813         help='Automatically correct known faults of the file. '
814              'One of never (do nothing), warn (only emit a warning), '
815              'detect_or_warn (the default; fix file if we can, warn otherwise)')
816     postproc.add_option(
817         '--prefer-avconv',
818         action='store_false', dest='prefer_ffmpeg',
819         help='Prefer avconv over ffmpeg for running the postprocessors (default)')
820     postproc.add_option(
821         '--prefer-ffmpeg',
822         action='store_true', dest='prefer_ffmpeg',
823         help='Prefer ffmpeg over avconv for running the postprocessors')
824     postproc.add_option(
825         '--ffmpeg-location', '--avconv-location', metavar='PATH',
826         dest='ffmpeg_location',
827         help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.')
828     postproc.add_option(
829         '--exec',
830         metavar='CMD', dest='exec_cmd',
831         help='Execute a command on the file after downloading, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'')
832     postproc.add_option(
833         '--convert-subs', '--convert-subtitles',
834         metavar='FORMAT', dest='convertsubtitles', default=None,
835         help='Convert the subtitles to other format (currently supported: srt|ass|vtt)')
836
837     parser.add_option_group(general)
838     parser.add_option_group(network)
839     parser.add_option_group(selection)
840     parser.add_option_group(downloader)
841     parser.add_option_group(filesystem)
842     parser.add_option_group(thumbnail)
843     parser.add_option_group(verbosity)
844     parser.add_option_group(workarounds)
845     parser.add_option_group(video_format)
846     parser.add_option_group(subtitles)
847     parser.add_option_group(authentication)
848     parser.add_option_group(adobe_pass)
849     parser.add_option_group(postproc)
850
851     if overrideArguments is not None:
852         opts, args = parser.parse_args(overrideArguments)
853         if opts.verbose:
854             write_string('[debug] Override config: ' + repr(overrideArguments) + '\n')
855     else:
856         def compat_conf(conf):
857             if sys.version_info < (3,):
858                 return [a.decode(preferredencoding(), 'replace') for a in conf]
859             return conf
860
861         command_line_conf = compat_conf(sys.argv[1:])
862         opts, args = parser.parse_args(command_line_conf)
863
864         system_conf = user_conf = custom_conf = []
865
866         if '--config-location' in command_line_conf:
867             location = compat_expanduser(opts.config_location)
868             if os.path.isdir(location):
869                 location = os.path.join(location, 'youtube-dl.conf')
870             if not os.path.exists(location):
871                 parser.error('config-location %s does not exist.' % location)
872             custom_conf = _readOptions(location)
873         elif '--ignore-config' in command_line_conf:
874             pass
875         else:
876             system_conf = _readOptions('/etc/youtube-dl.conf')
877             if '--ignore-config' not in system_conf:
878                 user_conf = _readUserConf()
879
880         argv = system_conf + user_conf + custom_conf + command_line_conf
881         opts, args = parser.parse_args(argv)
882         if opts.verbose:
883             for conf_label, conf in (
884                     ('System config', system_conf),
885                     ('User config', user_conf),
886                     ('Custom config', custom_conf),
887                     ('Command-line args', command_line_conf)):
888                 write_string('[debug] %s: %s\n' % (conf_label, repr(_hide_login_info(conf))))
889
890     return parser, opts, args