]> jfr.im git - yt-dlp.git/blob - youtube_dlc/options.py
[pyinst.py] Move back to root dir (Closes #63)
[yt-dlp.git] / youtube_dlc / 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 expand_path,
18 get_executable_path,
19 OUTTMPL_TYPES,
20 preferredencoding,
21 REMUX_EXTENSIONS,
22 write_string,
23 )
24 from .version import __version__
25
26
27 def _hide_login_info(opts):
28 PRIVATE_OPTS = set(['-p', '--password', '-u', '--username', '--video-password', '--ap-password', '--ap-username'])
29 eqre = re.compile('^(?P<key>' + ('|'.join(re.escape(po) for po in PRIVATE_OPTS)) + ')=.+$')
30
31 def _scrub_eq(o):
32 m = eqre.match(o)
33 if m:
34 return m.group('key') + '=PRIVATE'
35 else:
36 return o
37
38 opts = list(map(_scrub_eq, opts))
39 for idx, opt in enumerate(opts):
40 if opt in PRIVATE_OPTS and idx + 1 < len(opts):
41 opts[idx + 1] = 'PRIVATE'
42 return opts
43
44
45 def parseOpts(overrideArguments=None):
46 def _readOptions(filename_bytes, default=[]):
47 try:
48 optionf = open(filename_bytes)
49 except IOError:
50 return default # silently skip if file is not present
51 try:
52 # FIXME: https://github.com/ytdl-org/youtube-dl/commit/dfe5fa49aed02cf36ba9f743b11b0903554b5e56
53 contents = optionf.read()
54 if sys.version_info < (3,):
55 contents = contents.decode(preferredencoding())
56 res = compat_shlex_split(contents, comments=True)
57 finally:
58 optionf.close()
59 return res
60
61 def _readUserConf(package_name, default=[]):
62 # .config
63 xdg_config_home = compat_getenv('XDG_CONFIG_HOME') or compat_expanduser('~/.config')
64 userConfFile = os.path.join(xdg_config_home, package_name, 'config')
65 if not os.path.isfile(userConfFile):
66 userConfFile = os.path.join(xdg_config_home, '%s.conf' % package_name)
67 userConf = _readOptions(userConfFile, default=None)
68 if userConf is not None:
69 return userConf, userConfFile
70
71 # appdata
72 appdata_dir = compat_getenv('appdata')
73 if appdata_dir:
74 userConfFile = os.path.join(appdata_dir, package_name, 'config')
75 userConf = _readOptions(userConfFile, default=None)
76 if userConf is None:
77 userConfFile += '.txt'
78 userConf = _readOptions(userConfFile, default=None)
79 if userConf is not None:
80 return userConf, userConfFile
81
82 # home
83 userConfFile = os.path.join(compat_expanduser('~'), '%s.conf' % package_name)
84 userConf = _readOptions(userConfFile, default=None)
85 if userConf is None:
86 userConfFile += '.txt'
87 userConf = _readOptions(userConfFile, default=None)
88 if userConf is not None:
89 return userConf, userConfFile
90
91 return default, None
92
93 def _format_option_string(option):
94 ''' ('-o', '--option') -> -o, --format METAVAR'''
95
96 opts = []
97
98 if option._short_opts:
99 opts.append(option._short_opts[0])
100 if option._long_opts:
101 opts.append(option._long_opts[0])
102 if len(opts) > 1:
103 opts.insert(1, ', ')
104
105 if option.takes_value():
106 opts.append(' %s' % option.metavar)
107
108 return ''.join(opts)
109
110 def _comma_separated_values_options_callback(option, opt_str, value, parser):
111 setattr(parser.values, option.dest, value.split(','))
112
113 def _dict_from_multiple_values_options_callback(
114 option, opt_str, value, parser, allowed_keys=r'[\w-]+', delimiter=':', default_key=None, process=None):
115
116 out_dict = getattr(parser.values, option.dest)
117 mobj = re.match(r'(?i)(?P<key>%s)%s(?P<val>.*)$' % (allowed_keys, delimiter), value)
118 if mobj is not None:
119 key, val = mobj.group('key').lower(), mobj.group('val')
120 elif default_key is not None:
121 key, val = default_key, value
122 else:
123 raise optparse.OptionValueError(
124 'wrong %s formatting; it should be %s, not "%s"' % (opt_str, option.metavar, value))
125 out_dict[key] = process(val) if callable(process) else val
126
127 # No need to wrap help messages if we're on a wide console
128 columns = compat_get_terminal_size().columns
129 max_width = columns if columns else 80
130 max_help_position = 80
131
132 fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
133 fmt.format_option_strings = _format_option_string
134
135 kw = {
136 'version': __version__,
137 'formatter': fmt,
138 'usage': '%prog [OPTIONS] URL [URL...]',
139 'conflict_handler': 'resolve',
140 }
141
142 parser = optparse.OptionParser(**compat_kwargs(kw))
143
144 general = optparse.OptionGroup(parser, 'General Options')
145 general.add_option(
146 '-h', '--help',
147 action='help',
148 help='Print this help text and exit')
149 general.add_option(
150 '--version',
151 action='version',
152 help='Print program version and exit')
153 general.add_option(
154 '-U', '--update',
155 action='store_true', dest='update_self',
156 help='[BROKEN] Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
157 general.add_option(
158 '-i', '--ignore-errors', '--no-abort-on-error',
159 action='store_true', dest='ignoreerrors', default=True,
160 help='Continue on download errors, for example to skip unavailable videos in a playlist (default) (Alias: --no-abort-on-error)')
161 general.add_option(
162 '--abort-on-error', '--no-ignore-errors',
163 action='store_false', dest='ignoreerrors',
164 help='Abort downloading of further videos if an error occurs (Alias: --no-ignore-errors)')
165 general.add_option(
166 '--dump-user-agent',
167 action='store_true', dest='dump_user_agent', default=False,
168 help='Display the current browser identification')
169 general.add_option(
170 '--list-extractors',
171 action='store_true', dest='list_extractors', default=False,
172 help='List all supported extractors')
173 general.add_option(
174 '--extractor-descriptions',
175 action='store_true', dest='list_extractor_descriptions', default=False,
176 help='Output descriptions of all supported extractors')
177 general.add_option(
178 '--force-generic-extractor',
179 action='store_true', dest='force_generic_extractor', default=False,
180 help='Force extraction to use the generic extractor')
181 general.add_option(
182 '--default-search',
183 dest='default_search', metavar='PREFIX',
184 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')
185 general.add_option(
186 '--ignore-config', '--no-config',
187 action='store_true',
188 help=(
189 'Disable loading any configuration files except the one provided by --config-location. '
190 'When given inside a configuration file, no further configuration files are loaded. '
191 'Additionally, (for backward compatibility) if this option is found inside the '
192 'system configuration file, the user configuration is not loaded'))
193 general.add_option(
194 '--config-location',
195 dest='config_location', metavar='PATH',
196 help='Location of the main configuration file; either the path to the config or its containing directory')
197 general.add_option(
198 '--flat-playlist',
199 action='store_const', dest='extract_flat', const='in_playlist', default=False,
200 help='Do not extract the videos of a playlist, only list them')
201 general.add_option(
202 '--flat-videos',
203 action='store_true', dest='extract_flat',
204 help='Do not resolve the video urls')
205 general.add_option(
206 '--no-flat-playlist',
207 action='store_false', dest='extract_flat',
208 help='Extract the videos of a playlist')
209 general.add_option(
210 '--mark-watched',
211 action='store_true', dest='mark_watched', default=False,
212 help='Mark videos watched (YouTube only)')
213 general.add_option(
214 '--no-mark-watched',
215 action='store_false', dest='mark_watched', default=False,
216 help='Do not mark videos watched')
217 general.add_option(
218 '--no-colors',
219 action='store_true', dest='no_color',
220 default=False,
221 help='Do not emit color codes in output')
222
223 network = optparse.OptionGroup(parser, 'Network Options')
224 network.add_option(
225 '--proxy', dest='proxy',
226 default=None, metavar='URL',
227 help=(
228 'Use the specified HTTP/HTTPS/SOCKS proxy. To enable '
229 'SOCKS proxy, specify a proper scheme. For example '
230 'socks5://127.0.0.1:1080/. Pass in an empty string (--proxy "") '
231 'for direct connection'))
232 network.add_option(
233 '--socket-timeout',
234 dest='socket_timeout', type=float, default=None, metavar='SECONDS',
235 help='Time to wait before giving up, in seconds')
236 network.add_option(
237 '--source-address',
238 metavar='IP', dest='source_address', default=None,
239 help='Client-side IP address to bind to',
240 )
241 network.add_option(
242 '-4', '--force-ipv4',
243 action='store_const', const='0.0.0.0', dest='source_address',
244 help='Make all connections via IPv4',
245 )
246 network.add_option(
247 '-6', '--force-ipv6',
248 action='store_const', const='::', dest='source_address',
249 help='Make all connections via IPv6',
250 )
251
252 geo = optparse.OptionGroup(parser, 'Geo Restriction')
253 geo.add_option(
254 '--geo-verification-proxy',
255 dest='geo_verification_proxy', default=None, metavar='URL',
256 help=(
257 'Use this proxy to verify the IP address for some geo-restricted sites. '
258 'The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading'))
259 geo.add_option(
260 '--cn-verification-proxy',
261 dest='cn_verification_proxy', default=None, metavar='URL',
262 help=optparse.SUPPRESS_HELP)
263 geo.add_option(
264 '--geo-bypass',
265 action='store_true', dest='geo_bypass', default=True,
266 help='Bypass geographic restriction via faking X-Forwarded-For HTTP header')
267 geo.add_option(
268 '--no-geo-bypass',
269 action='store_false', dest='geo_bypass', default=True,
270 help='Do not bypass geographic restriction via faking X-Forwarded-For HTTP header')
271 geo.add_option(
272 '--geo-bypass-country', metavar='CODE',
273 dest='geo_bypass_country', default=None,
274 help='Force bypass geographic restriction with explicitly provided two-letter ISO 3166-2 country code')
275 geo.add_option(
276 '--geo-bypass-ip-block', metavar='IP_BLOCK',
277 dest='geo_bypass_ip_block', default=None,
278 help='Force bypass geographic restriction with explicitly provided IP block in CIDR notation')
279
280 selection = optparse.OptionGroup(parser, 'Video Selection')
281 selection.add_option(
282 '--playlist-start',
283 dest='playliststart', metavar='NUMBER', default=1, type=int,
284 help='Playlist video to start at (default is %default)')
285 selection.add_option(
286 '--playlist-end',
287 dest='playlistend', metavar='NUMBER', default=None, type=int,
288 help='Playlist video to end at (default is last)')
289 selection.add_option(
290 '--playlist-items',
291 dest='playlist_items', metavar='ITEM_SPEC', default=None,
292 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')
293 selection.add_option(
294 '--match-title',
295 dest='matchtitle', metavar='REGEX',
296 help='Download only matching titles (regex or caseless sub-string)')
297 selection.add_option(
298 '--reject-title',
299 dest='rejecttitle', metavar='REGEX',
300 help='Skip download for matching titles (regex or caseless sub-string)')
301 selection.add_option(
302 '--max-downloads',
303 dest='max_downloads', metavar='NUMBER', type=int, default=None,
304 help='Abort after downloading NUMBER files')
305 selection.add_option(
306 '--min-filesize',
307 metavar='SIZE', dest='min_filesize', default=None,
308 help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
309 selection.add_option(
310 '--max-filesize',
311 metavar='SIZE', dest='max_filesize', default=None,
312 help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
313 selection.add_option(
314 '--date',
315 metavar='DATE', dest='date', default=None,
316 help=(
317 'Download only videos uploaded in this date. '
318 'The date can be "YYYYMMDD" or in the format '
319 '"(now|today)[+-][0-9](day|week|month|year)(s)?"'))
320 selection.add_option(
321 '--datebefore',
322 metavar='DATE', dest='datebefore', default=None,
323 help=(
324 'Download only videos uploaded on or before this date. '
325 'The date formats accepted is the same as --date'))
326 selection.add_option(
327 '--dateafter',
328 metavar='DATE', dest='dateafter', default=None,
329 help=(
330 'Download only videos uploaded on or after this date. '
331 'The date formats accepted is the same as --date'))
332 selection.add_option(
333 '--min-views',
334 metavar='COUNT', dest='min_views', default=None, type=int,
335 help='Do not download any videos with less than COUNT views')
336 selection.add_option(
337 '--max-views',
338 metavar='COUNT', dest='max_views', default=None, type=int,
339 help='Do not download any videos with more than COUNT views')
340 selection.add_option(
341 '--match-filter',
342 metavar='FILTER', dest='match_filter', default=None,
343 help=(
344 'Generic video filter. '
345 'Specify any key (see "OUTPUT TEMPLATE" for a list of available keys) to '
346 'match if the key is present, '
347 '!key to check if the key is not present, '
348 'key>NUMBER (like "comment_count > 12", also works with '
349 '>=, <, <=, !=, =) to compare against a number, '
350 'key = \'LITERAL\' (like "uploader = \'Mike Smith\'", also works with !=) '
351 'to match against a string literal '
352 'and & to require multiple matches. '
353 'Values which are not known are excluded unless you '
354 'put a question mark (?) after the operator. '
355 'For example, to only match videos that have been liked more than '
356 '100 times and disliked less than 50 times (or the dislike '
357 'functionality is not available at the given service), but who '
358 'also have a description, use --match-filter '
359 '"like_count > 100 & dislike_count <? 50 & description"'))
360 selection.add_option(
361 '--no-match-filter',
362 metavar='FILTER', dest='match_filter', action='store_const', const=None,
363 help='Do not use generic video filter (default)')
364 selection.add_option(
365 '--no-playlist',
366 action='store_true', dest='noplaylist', default=False,
367 help='Download only the video, if the URL refers to a video and a playlist')
368 selection.add_option(
369 '--yes-playlist',
370 action='store_false', dest='noplaylist', default=False,
371 help='Download the playlist, if the URL refers to a video and a playlist')
372 selection.add_option(
373 '--age-limit',
374 metavar='YEARS', dest='age_limit', default=None, type=int,
375 help='Download only videos suitable for the given age')
376 selection.add_option(
377 '--download-archive', metavar='FILE',
378 dest='download_archive',
379 help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it')
380 selection.add_option(
381 '--break-on-existing',
382 action='store_true', dest='break_on_existing', default=False,
383 help='Stop the download process when encountering a file that is in the archive')
384 selection.add_option(
385 '--break-on-reject',
386 action='store_true', dest='break_on_reject', default=False,
387 help='Stop the download process when encountering a file that has been filtered out')
388 selection.add_option(
389 '--no-download-archive',
390 dest='download_archive', action="store_const", const=None,
391 help='Do not use archive file (default)')
392 selection.add_option(
393 '--include-ads',
394 dest='include_ads', action='store_true',
395 help='Download advertisements as well (experimental)')
396 selection.add_option(
397 '--no-include-ads',
398 dest='include_ads', action='store_false',
399 help='Do not download advertisements (default)')
400
401 authentication = optparse.OptionGroup(parser, 'Authentication Options')
402 authentication.add_option(
403 '-u', '--username',
404 dest='username', metavar='USERNAME',
405 help='Login with this account ID')
406 authentication.add_option(
407 '-p', '--password',
408 dest='password', metavar='PASSWORD',
409 help='Account password. If this option is left out, youtube-dlc will ask interactively')
410 authentication.add_option(
411 '-2', '--twofactor',
412 dest='twofactor', metavar='TWOFACTOR',
413 help='Two-factor authentication code')
414 authentication.add_option(
415 '-n', '--netrc',
416 action='store_true', dest='usenetrc', default=False,
417 help='Use .netrc authentication data')
418 authentication.add_option(
419 '--video-password',
420 dest='videopassword', metavar='PASSWORD',
421 help='Video password (vimeo, youku)')
422
423 adobe_pass = optparse.OptionGroup(parser, 'Adobe Pass Options')
424 adobe_pass.add_option(
425 '--ap-mso',
426 dest='ap_mso', metavar='MSO',
427 help='Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs')
428 adobe_pass.add_option(
429 '--ap-username',
430 dest='ap_username', metavar='USERNAME',
431 help='Multiple-system operator account login')
432 adobe_pass.add_option(
433 '--ap-password',
434 dest='ap_password', metavar='PASSWORD',
435 help='Multiple-system operator account password. If this option is left out, youtube-dlc will ask interactively')
436 adobe_pass.add_option(
437 '--ap-list-mso',
438 action='store_true', dest='ap_list_mso', default=False,
439 help='List all supported multiple-system operators')
440
441 video_format = optparse.OptionGroup(parser, 'Video Format Options')
442 video_format.add_option(
443 '-f', '--format',
444 action='store', dest='format', metavar='FORMAT', default=None,
445 help='Video format code, see "FORMAT SELECTION" for more details')
446 video_format.add_option(
447 '-S', '--format-sort', metavar='SORTORDER',
448 dest='format_sort', default=[],
449 action='callback', callback=_comma_separated_values_options_callback, type='str',
450 help='Sort the formats by the fields given, see "Sorting Formats" for more details')
451 video_format.add_option(
452 '--format-sort-force', '--S-force',
453 action='store_true', dest='format_sort_force', metavar='FORMAT', default=False,
454 help=(
455 'Force user specified sort order to have precedence over all fields, '
456 'see "Sorting Formats" for more details'))
457 video_format.add_option(
458 '--no-format-sort-force',
459 action='store_false', dest='format_sort_force', metavar='FORMAT', default=False,
460 help=(
461 'Some fields have precedence over the user specified sort order (default), '
462 'see "Sorting Formats" for more details'))
463 video_format.add_option(
464 '--video-multistreams',
465 action='store_true', dest='allow_multiple_video_streams', default=False,
466 help='Allow multiple video streams to be merged into a single file')
467 video_format.add_option(
468 '--no-video-multistreams',
469 action='store_false', dest='allow_multiple_video_streams',
470 help='Only one video stream is downloaded for each output file (default)')
471 video_format.add_option(
472 '--audio-multistreams',
473 action='store_true', dest='allow_multiple_audio_streams', default=False,
474 help='Allow multiple audio streams to be merged into a single file')
475 video_format.add_option(
476 '--no-audio-multistreams',
477 action='store_false', dest='allow_multiple_audio_streams',
478 help='Only one audio stream is downloaded for each output file (default)')
479 video_format.add_option(
480 '--all-formats',
481 action='store_const', dest='format', const='all',
482 help='Download all available video formats')
483 video_format.add_option(
484 '--prefer-free-formats',
485 action='store_true', dest='prefer_free_formats', default=False,
486 help='Prefer free video formats over non-free formats of same quality')
487 video_format.add_option(
488 '-F', '--list-formats',
489 action='store_true', dest='listformats',
490 help='List all available formats of requested videos')
491 video_format.add_option(
492 '--list-formats-as-table',
493 action='store_true', dest='listformats_table', default=True,
494 help='Present the output of -F in tabular form (default)')
495 video_format.add_option(
496 '--list-formats-old', '--no-list-formats-as-table',
497 action='store_false', dest='listformats_table',
498 help='Present the output of -F in the old form (Alias: --no-list-formats-as-table)')
499 video_format.add_option(
500 '--youtube-include-dash-manifest', '--no-youtube-skip-dash-manifest',
501 action='store_true', dest='youtube_include_dash_manifest', default=True,
502 help='Download the DASH manifests and related data on YouTube videos (default) (Alias: --no-youtube-skip-dash-manifest)')
503 video_format.add_option(
504 '--youtube-skip-dash-manifest', '--no-youtube-include-dash-manifest',
505 action='store_false', dest='youtube_include_dash_manifest',
506 help='Do not download the DASH manifests and related data on YouTube videos (Alias: --no-youtube-include-dash-manifest)')
507 video_format.add_option(
508 '--youtube-include-hls-manifest', '--no-youtube-skip-hls-manifest',
509 action='store_true', dest='youtube_include_hls_manifest', default=True,
510 help='Download the HLS manifests and related data on YouTube videos (default) (Alias: --no-youtube-skip-hls-manifest)')
511 video_format.add_option(
512 '--youtube-skip-hls-manifest', '--no-youtube-include-hls-manifest',
513 action='store_false', dest='youtube_include_hls_manifest',
514 help='Do not download the HLS manifests and related data on YouTube videos (Alias: --no-youtube-include-hls-manifest)')
515 video_format.add_option(
516 '--merge-output-format',
517 action='store', dest='merge_output_format', metavar='FORMAT', default=None,
518 help=(
519 'If a merge is required (e.g. bestvideo+bestaudio), '
520 'output to given container format. One of mkv, mp4, ogg, webm, flv. '
521 'Ignored if no merge is required'))
522
523 subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
524 subtitles.add_option(
525 '--write-subs', '--write-srt',
526 action='store_true', dest='writesubtitles', default=False,
527 help='Write subtitle file')
528 subtitles.add_option(
529 '--no-write-subs', '--no-write-srt',
530 action='store_false', dest='writesubtitles',
531 help='Do not write subtitle file (default)')
532 subtitles.add_option(
533 '--write-auto-subs', '--write-automatic-subs',
534 action='store_true', dest='writeautomaticsub', default=False,
535 help='Write automatically generated subtitle file (YouTube only)')
536 subtitles.add_option(
537 '--no-write-auto-subs', '--no-write-automatic-subs',
538 action='store_false', dest='writeautomaticsub', default=False,
539 help='Do not write automatically generated subtitle file (default)')
540 subtitles.add_option(
541 '--all-subs',
542 action='store_true', dest='allsubtitles', default=False,
543 help='Download all the available subtitles of the video')
544 subtitles.add_option(
545 '--list-subs',
546 action='store_true', dest='listsubtitles', default=False,
547 help='List all available subtitles for the video')
548 subtitles.add_option(
549 '--sub-format',
550 action='store', dest='subtitlesformat', metavar='FORMAT', default='best',
551 help='Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"')
552 subtitles.add_option(
553 '--sub-lang', '--sub-langs', '--srt-lang',
554 action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
555 default=[], callback=_comma_separated_values_options_callback,
556 help='Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags')
557
558 downloader = optparse.OptionGroup(parser, 'Download Options')
559 downloader.add_option(
560 '-r', '--limit-rate', '--rate-limit',
561 dest='ratelimit', metavar='RATE',
562 help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)')
563 downloader.add_option(
564 '-R', '--retries',
565 dest='retries', metavar='RETRIES', default=10,
566 help='Number of retries (default is %default), or "infinite"')
567 downloader.add_option(
568 '--fragment-retries',
569 dest='fragment_retries', metavar='RETRIES', default=10,
570 help='Number of retries for a fragment (default is %default), or "infinite" (DASH, hlsnative and ISM)')
571 downloader.add_option(
572 '--skip-unavailable-fragments', '--no-abort-on-unavailable-fragment',
573 action='store_true', dest='skip_unavailable_fragments', default=True,
574 help='Skip unavailable fragments for DASH, hlsnative and ISM (default) (Alias: --no-abort-on-unavailable-fragment)')
575 downloader.add_option(
576 '--abort-on-unavailable-fragment', '--no-skip-unavailable-fragments',
577 action='store_false', dest='skip_unavailable_fragments',
578 help='Abort downloading if a fragment is unavailable (Alias: --no-skip-unavailable-fragments)')
579 downloader.add_option(
580 '--keep-fragments',
581 action='store_true', dest='keep_fragments', default=False,
582 help='Keep downloaded fragments on disk after downloading is finished')
583 downloader.add_option(
584 '--no-keep-fragments',
585 action='store_false', dest='keep_fragments',
586 help='Delete downloaded fragments after downloading is finished (default)')
587 downloader.add_option(
588 '--buffer-size',
589 dest='buffersize', metavar='SIZE', default='1024',
590 help='Size of download buffer (e.g. 1024 or 16K) (default is %default)')
591 downloader.add_option(
592 '--resize-buffer',
593 action='store_false', dest='noresizebuffer',
594 help='The buffer size is automatically resized from an initial value of --buffer-size (default)')
595 downloader.add_option(
596 '--no-resize-buffer',
597 action='store_true', dest='noresizebuffer', default=False,
598 help='Do not automatically adjust the buffer size')
599 downloader.add_option(
600 '--http-chunk-size',
601 dest='http_chunk_size', metavar='SIZE', default=None,
602 help=(
603 'Size of a chunk for chunk-based HTTP downloading (e.g. 10485760 or 10M) (default is disabled). '
604 'May be useful for bypassing bandwidth throttling imposed by a webserver (experimental)'))
605 downloader.add_option(
606 '--test',
607 action='store_true', dest='test', default=False,
608 help=optparse.SUPPRESS_HELP)
609 downloader.add_option(
610 '--playlist-reverse',
611 action='store_true',
612 help='Download playlist videos in reverse order')
613 downloader.add_option(
614 '--no-playlist-reverse',
615 action='store_false', dest='playlist_reverse',
616 help='Download playlist videos in default order (default)')
617 downloader.add_option(
618 '--playlist-random',
619 action='store_true',
620 help='Download playlist videos in random order')
621 downloader.add_option(
622 '--xattr-set-filesize',
623 dest='xattr_set_filesize', action='store_true',
624 help='Set file xattribute ytdl.filesize with expected file size')
625 downloader.add_option(
626 '--hls-prefer-native',
627 dest='hls_prefer_native', action='store_true', default=None,
628 help='Use the native HLS downloader instead of ffmpeg')
629 downloader.add_option(
630 '--hls-prefer-ffmpeg',
631 dest='hls_prefer_native', action='store_false', default=None,
632 help='Use ffmpeg instead of the native HLS downloader')
633 downloader.add_option(
634 '--hls-use-mpegts',
635 dest='hls_use_mpegts', action='store_true',
636 help=(
637 'Use the mpegts container for HLS videos, allowing to play the '
638 'video while downloading (some players may not be able to play it)'))
639 downloader.add_option(
640 '--external-downloader',
641 dest='external_downloader', metavar='NAME',
642 help=(
643 'Use the specified external downloader. '
644 'Currently supports %s' % ', '.join(list_external_downloaders())))
645 downloader.add_option(
646 '--downloader-args', '--external-downloader-args',
647 metavar='NAME:ARGS', dest='external_downloader_args', default={}, type='str',
648 action='callback', callback=_dict_from_multiple_values_options_callback,
649 callback_kwargs={
650 'allowed_keys': '|'.join(list_external_downloaders()),
651 'default_key': 'default', 'process': compat_shlex_split},
652 help=(
653 'Give these arguments to the external downloader. '
654 'Specify the downloader name and the arguments separated by a colon ":". '
655 'You can use this option multiple times (Alias: --external-downloader-args)'))
656
657 workarounds = optparse.OptionGroup(parser, 'Workarounds')
658 workarounds.add_option(
659 '--encoding',
660 dest='encoding', metavar='ENCODING',
661 help='Force the specified encoding (experimental)')
662 workarounds.add_option(
663 '--no-check-certificate',
664 action='store_true', dest='no_check_certificate', default=False,
665 help='Suppress HTTPS certificate validation')
666 workarounds.add_option(
667 '--prefer-insecure', '--prefer-unsecure',
668 action='store_true', dest='prefer_insecure',
669 help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
670 workarounds.add_option(
671 '--user-agent',
672 metavar='UA', dest='user_agent',
673 help='Specify a custom user agent')
674 workarounds.add_option(
675 '--referer',
676 metavar='URL', dest='referer', default=None,
677 help='Specify a custom referer, use if the video access is restricted to one domain',
678 )
679 workarounds.add_option(
680 '--add-header',
681 metavar='FIELD:VALUE', dest='headers', default={}, type='str',
682 action='callback', callback=_dict_from_multiple_values_options_callback,
683 help='Specify a custom HTTP header and its value, separated by a colon ":". You can use this option multiple times',
684 )
685 workarounds.add_option(
686 '--bidi-workaround',
687 dest='bidi_workaround', action='store_true',
688 help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
689 workarounds.add_option(
690 '--sleep-interval', '--min-sleep-interval', metavar='SECONDS',
691 dest='sleep_interval', type=float,
692 help=(
693 'Number of seconds to sleep before each download when used alone '
694 'or a lower bound of a range for randomized sleep before each download '
695 '(minimum possible number of seconds to sleep) when used along with '
696 '--max-sleep-interval'))
697 workarounds.add_option(
698 '--max-sleep-interval', metavar='SECONDS',
699 dest='max_sleep_interval', type=float,
700 help=(
701 'Upper bound of a range for randomized sleep before each download '
702 '(maximum possible number of seconds to sleep). Must only be used '
703 'along with --min-sleep-interval'))
704 workarounds.add_option(
705 '--sleep-subtitles', metavar='SECONDS',
706 dest='sleep_interval_subtitles', default=0, type=int,
707 help='Enforce sleep interval on subtitles as well')
708
709 verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
710 verbosity.add_option(
711 '-q', '--quiet',
712 action='store_true', dest='quiet', default=False,
713 help='Activate quiet mode')
714 verbosity.add_option(
715 '--no-warnings',
716 dest='no_warnings', action='store_true', default=False,
717 help='Ignore warnings')
718 verbosity.add_option(
719 '-s', '--simulate',
720 action='store_true', dest='simulate', default=False,
721 help='Do not download the video and do not write anything to disk')
722 verbosity.add_option(
723 '--skip-download', '--no-download',
724 action='store_true', dest='skip_download', default=False,
725 help='Do not download the video')
726 verbosity.add_option(
727 '-g', '--get-url',
728 action='store_true', dest='geturl', default=False,
729 help='Simulate, quiet but print URL')
730 verbosity.add_option(
731 '-e', '--get-title',
732 action='store_true', dest='gettitle', default=False,
733 help='Simulate, quiet but print title')
734 verbosity.add_option(
735 '--get-id',
736 action='store_true', dest='getid', default=False,
737 help='Simulate, quiet but print id')
738 verbosity.add_option(
739 '--get-thumbnail',
740 action='store_true', dest='getthumbnail', default=False,
741 help='Simulate, quiet but print thumbnail URL')
742 verbosity.add_option(
743 '--get-description',
744 action='store_true', dest='getdescription', default=False,
745 help='Simulate, quiet but print video description')
746 verbosity.add_option(
747 '--get-duration',
748 action='store_true', dest='getduration', default=False,
749 help='Simulate, quiet but print video length')
750 verbosity.add_option(
751 '--get-filename',
752 action='store_true', dest='getfilename', default=False,
753 help='Simulate, quiet but print output filename')
754 verbosity.add_option(
755 '--get-format',
756 action='store_true', dest='getformat', default=False,
757 help='Simulate, quiet but print output format')
758 verbosity.add_option(
759 '-j', '--dump-json',
760 action='store_true', dest='dumpjson', default=False,
761 help='Simulate, quiet but print JSON information. See "OUTPUT TEMPLATE" for a description of available keys')
762 verbosity.add_option(
763 '-J', '--dump-single-json',
764 action='store_true', dest='dump_single_json', default=False,
765 help=(
766 'Simulate, quiet but print JSON information for each command-line argument. '
767 'If the URL refers to a playlist, dump the whole playlist information in a single line'))
768 verbosity.add_option(
769 '--print-json',
770 action='store_true', dest='print_json', default=False,
771 help='Be quiet and print the video information as JSON (video is still being downloaded)')
772 verbosity.add_option(
773 '--force-write-archive', '--force-write-download-archive', '--force-download-archive',
774 action='store_true', dest='force_write_download_archive', default=False,
775 help=(
776 'Force download archive entries to be written as far as no errors occur,'
777 'even if -s or another simulation switch is used (Alias: --force-download-archive)'))
778 verbosity.add_option(
779 '--newline',
780 action='store_true', dest='progress_with_newline', default=False,
781 help='Output progress bar as new lines')
782 verbosity.add_option(
783 '--no-progress',
784 action='store_true', dest='noprogress', default=False,
785 help='Do not print progress bar')
786 verbosity.add_option(
787 '--console-title',
788 action='store_true', dest='consoletitle', default=False,
789 help='Display progress in console titlebar')
790 verbosity.add_option(
791 '-v', '--verbose',
792 action='store_true', dest='verbose', default=False,
793 help='Print various debugging information')
794 verbosity.add_option(
795 '--dump-pages', '--dump-intermediate-pages',
796 action='store_true', dest='dump_intermediate_pages', default=False,
797 help='Print downloaded pages encoded using base64 to debug problems (very verbose)')
798 verbosity.add_option(
799 '--write-pages',
800 action='store_true', dest='write_pages', default=False,
801 help='Write downloaded intermediary pages to files in the current directory to debug problems')
802 verbosity.add_option(
803 '--youtube-print-sig-code',
804 action='store_true', dest='youtube_print_sig_code', default=False,
805 help=optparse.SUPPRESS_HELP)
806 verbosity.add_option(
807 '--print-traffic', '--dump-headers',
808 dest='debug_printtraffic', action='store_true', default=False,
809 help='Display sent and read HTTP traffic')
810 verbosity.add_option(
811 '-C', '--call-home',
812 dest='call_home', action='store_true', default=False,
813 help='[Broken] Contact the youtube-dlc server for debugging')
814 verbosity.add_option(
815 '--no-call-home',
816 dest='call_home', action='store_false',
817 help='Do not contact the youtube-dlc server for debugging (default)')
818
819 filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
820 filesystem.add_option(
821 '-a', '--batch-file',
822 dest='batchfile', metavar='FILE',
823 help="File containing URLs to download ('-' for stdin), one URL per line. "
824 "Lines starting with '#', ';' or ']' are considered as comments and ignored")
825 filesystem.add_option(
826 '--id', default=False,
827 action='store_true', dest='useid', help=optparse.SUPPRESS_HELP)
828 filesystem.add_option(
829 '-P', '--paths',
830 metavar='TYPE:PATH', dest='paths', default={}, type='str',
831 action='callback', callback=_dict_from_multiple_values_options_callback,
832 callback_kwargs={
833 'allowed_keys': 'home|temp|%s' % '|'.join(OUTTMPL_TYPES.keys()),
834 'process': lambda x: x.strip()},
835 help=(
836 'The paths where the files should be downloaded. '
837 'Specify the type of file and the path separated by a colon ":". '
838 'All the same types as --output are supported. '
839 'Additionally, you can also provide "home" and "temp" paths. '
840 'All intermediary files are first downloaded to the temp path and '
841 'then the final files are moved over to the home path after download is finished. '
842 'This option is ignored if --output is an absolute path'))
843 filesystem.add_option(
844 '-o', '--output',
845 metavar='[TYPE:]TEMPLATE', dest='outtmpl', default={}, type='str',
846 action='callback', callback=_dict_from_multiple_values_options_callback,
847 callback_kwargs={
848 'allowed_keys': '|'.join(OUTTMPL_TYPES.keys()),
849 'default_key': 'default', 'process': lambda x: x.strip()},
850 help='Output filename template, see "OUTPUT TEMPLATE" for details')
851 filesystem.add_option(
852 '--output-na-placeholder',
853 dest='outtmpl_na_placeholder', metavar='TEXT', default='NA',
854 help=('Placeholder value for unavailable meta fields in output filename template (default: "%default")'))
855 filesystem.add_option(
856 '--autonumber-size',
857 dest='autonumber_size', metavar='NUMBER', type=int,
858 help=optparse.SUPPRESS_HELP)
859 filesystem.add_option(
860 '--autonumber-start',
861 dest='autonumber_start', metavar='NUMBER', default=1, type=int,
862 help='Specify the start value for %(autonumber)s (default is %default)')
863 filesystem.add_option(
864 '--restrict-filenames',
865 action='store_true', dest='restrictfilenames', default=False,
866 help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
867 filesystem.add_option(
868 '--no-restrict-filenames',
869 action='store_false', dest='restrictfilenames', default=False,
870 help='Allow Unicode characters, "&" and spaces in filenames (default)')
871 filesystem.add_option(
872 '-A', '--auto-number',
873 action='store_true', dest='autonumber', default=False,
874 help=optparse.SUPPRESS_HELP)
875 filesystem.add_option(
876 '-t', '--title',
877 action='store_true', dest='usetitle', default=False,
878 help=optparse.SUPPRESS_HELP)
879 filesystem.add_option(
880 '-l', '--literal', default=False,
881 action='store_true', dest='usetitle',
882 help=optparse.SUPPRESS_HELP)
883 filesystem.add_option(
884 '-w', '--no-overwrites',
885 action='store_false', dest='overwrites', default=None,
886 help='Do not overwrite any files')
887 filesystem.add_option(
888 '--force-overwrites', '--yes-overwrites',
889 action='store_true', dest='overwrites',
890 help='Overwrite all video and metadata files. This option includes --no-continue')
891 filesystem.add_option(
892 '--no-force-overwrites',
893 action='store_const', dest='overwrites', const=None,
894 help='Do not overwrite the video, but overwrite related files (default)')
895 filesystem.add_option(
896 '-c', '--continue',
897 action='store_true', dest='continue_dl', default=True,
898 help='Resume partially downloaded files/fragments (default)')
899 filesystem.add_option(
900 '--no-continue',
901 action='store_false', dest='continue_dl',
902 help=(
903 'Do not resume partially downloaded fragments. '
904 'If the file is unfragmented, restart download of the entire file'))
905 filesystem.add_option(
906 '--part',
907 action='store_false', dest='nopart', default=False,
908 help='Use .part files instead of writing directly into output file (default)')
909 filesystem.add_option(
910 '--no-part',
911 action='store_true', dest='nopart',
912 help='Do not use .part files - write directly into output file')
913 filesystem.add_option(
914 '--mtime',
915 action='store_true', dest='updatetime', default=True,
916 help='Use the Last-modified header to set the file modification time (default)')
917 filesystem.add_option(
918 '--no-mtime',
919 action='store_false', dest='updatetime',
920 help='Do not use the Last-modified header to set the file modification time')
921 filesystem.add_option(
922 '--write-description',
923 action='store_true', dest='writedescription', default=False,
924 help='Write video description to a .description file')
925 filesystem.add_option(
926 '--no-write-description',
927 action='store_false', dest='writedescription',
928 help='Do not write video description (default)')
929 filesystem.add_option(
930 '--write-info-json',
931 action='store_true', dest='writeinfojson', default=False,
932 help='Write video metadata to a .info.json file (this may contain personal information)')
933 filesystem.add_option(
934 '--no-write-info-json',
935 action='store_false', dest='writeinfojson',
936 help='Do not write video metadata (default)')
937 filesystem.add_option(
938 '--write-annotations',
939 action='store_true', dest='writeannotations', default=False,
940 help='Write video annotations to a .annotations.xml file')
941 filesystem.add_option(
942 '--no-write-annotations',
943 action='store_false', dest='writeannotations',
944 help='Do not write video annotations (default)')
945 filesystem.add_option(
946 '--write-playlist-metafiles',
947 action='store_true', dest='allow_playlist_files', default=True,
948 help=(
949 'Write playlist metadata in addition to the video metadata '
950 'when using --write-info-json, --write-description etc. (default)'))
951 filesystem.add_option(
952 '--no-write-playlist-metafiles',
953 action='store_false', dest='allow_playlist_files',
954 help=(
955 'Do not write playlist metadata when using '
956 '--write-info-json, --write-description etc.'))
957 filesystem.add_option(
958 '--get-comments',
959 action='store_true', dest='getcomments', default=False,
960 help='Retrieve video comments to be placed in the .info.json file')
961 filesystem.add_option(
962 '--load-info-json', '--load-info',
963 dest='load_info_filename', metavar='FILE',
964 help='JSON file containing the video information (created with the "--write-info-json" option)')
965 filesystem.add_option(
966 '--cookies',
967 dest='cookiefile', metavar='FILE',
968 help='File to read cookies from and dump cookie jar in')
969 filesystem.add_option(
970 '--no-cookies',
971 action='store_const', const=None, dest='cookiefile', metavar='FILE',
972 help='Do not read/dump cookies (default)')
973 filesystem.add_option(
974 '--cache-dir', dest='cachedir', default=None, metavar='DIR',
975 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')
976 filesystem.add_option(
977 '--no-cache-dir', action='store_false', dest='cachedir',
978 help='Disable filesystem caching')
979 filesystem.add_option(
980 '--rm-cache-dir',
981 action='store_true', dest='rm_cachedir',
982 help='Delete all filesystem cache files')
983 filesystem.add_option(
984 '--trim-file-name', metavar='LENGTH',
985 dest='trim_file_name', default=0, type=int,
986 help='Limit the filename length (extension excluded)')
987
988 thumbnail = optparse.OptionGroup(parser, 'Thumbnail Images')
989 thumbnail.add_option(
990 '--write-thumbnail',
991 action='store_true', dest='writethumbnail', default=False,
992 help='Write thumbnail image to disk')
993 thumbnail.add_option(
994 '--no-write-thumbnail',
995 action='store_false', dest='writethumbnail',
996 help='Do not write thumbnail image to disk (default)')
997 thumbnail.add_option(
998 '--write-all-thumbnails',
999 action='store_true', dest='write_all_thumbnails', default=False,
1000 help='Write all thumbnail image formats to disk')
1001 thumbnail.add_option(
1002 '--list-thumbnails',
1003 action='store_true', dest='list_thumbnails', default=False,
1004 help='Simulate and list all available thumbnail formats')
1005
1006 link = optparse.OptionGroup(parser, 'Internet Shortcut Options')
1007 link.add_option(
1008 '--write-link',
1009 action='store_true', dest='writelink', default=False,
1010 help='Write an internet shortcut file, depending on the current platform (.url, .webloc or .desktop). The URL may be cached by the OS')
1011 link.add_option(
1012 '--write-url-link',
1013 action='store_true', dest='writeurllink', default=False,
1014 help='Write a .url Windows internet shortcut. The OS caches the URL based on the file path')
1015 link.add_option(
1016 '--write-webloc-link',
1017 action='store_true', dest='writewebloclink', default=False,
1018 help='Write a .webloc macOS internet shortcut')
1019 link.add_option(
1020 '--write-desktop-link',
1021 action='store_true', dest='writedesktoplink', default=False,
1022 help='Write a .desktop Linux internet shortcut')
1023
1024 postproc = optparse.OptionGroup(parser, 'Post-Processing Options')
1025 postproc.add_option(
1026 '-x', '--extract-audio',
1027 action='store_true', dest='extractaudio', default=False,
1028 help='Convert video files to audio-only files (requires ffmpeg and ffprobe)')
1029 postproc.add_option(
1030 '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
1031 help='Specify audio format: "best", "aac", "flac", "mp3", "m4a", "opus", "vorbis", or "wav"; "%default" by default; No effect without -x')
1032 postproc.add_option(
1033 '--audio-quality', metavar='QUALITY',
1034 dest='audioquality', default='5',
1035 help='Specify ffmpeg audio quality, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default %default)')
1036 postproc.add_option(
1037 '--remux-video',
1038 metavar='FORMAT', dest='remuxvideo', default=None,
1039 help=(
1040 'Remux the video into another container if necessary (currently supported: %s). '
1041 'If target container does not support the video/audio codec, remuxing will fail. '
1042 'You can specify multiple rules; eg. "aac>m4a/mov>mp4/mkv" will remux aac to m4a, mov to mp4 '
1043 'and anything else to mkv.' % '|'.join(REMUX_EXTENSIONS)))
1044 postproc.add_option(
1045 '--recode-video',
1046 metavar='FORMAT', dest='recodevideo', default=None,
1047 help=(
1048 'Re-encode the video into another format if re-encoding is necessary. '
1049 'The supported formats are the same as --remux-video'))
1050 postproc.add_option(
1051 '--postprocessor-args', '--ppa',
1052 metavar='NAME:ARGS', dest='postprocessor_args', default={}, type='str',
1053 action='callback', callback=_dict_from_multiple_values_options_callback,
1054 callback_kwargs={'default_key': 'default-compat', 'allowed_keys': r'\w+(?:\+\w+)?', 'process': compat_shlex_split},
1055 help=(
1056 'Give these arguments to the postprocessors. '
1057 'Specify the postprocessor/executable name and the arguments separated by a colon ":" '
1058 'to give the argument to the specified postprocessor/executable. Supported postprocessors are: '
1059 'SponSkrub, ExtractAudio, VideoRemuxer, VideoConvertor, EmbedSubtitle, Metadata, Merger, '
1060 'FixupStretched, FixupM4a, FixupM3u8, SubtitlesConvertor and EmbedThumbnail. '
1061 'The supported executables are: SponSkrub, FFmpeg, FFprobe, and AtomicParsley. '
1062 'You can use this option multiple times to give different arguments to different postprocessors. '
1063 'You can also specify "PP+EXE:ARGS" to give the arguments to the specified executable '
1064 'only when being used by the specified postprocessor. '
1065 'You can use this option multiple times (Alias: --ppa)'))
1066 postproc.add_option(
1067 '-k', '--keep-video',
1068 action='store_true', dest='keepvideo', default=False,
1069 help='Keep the intermediate video file on disk after post-processing')
1070 postproc.add_option(
1071 '--no-keep-video',
1072 action='store_false', dest='keepvideo',
1073 help='Delete the intermediate video file after post-processing (default)')
1074 postproc.add_option(
1075 '--post-overwrites',
1076 action='store_false', dest='nopostoverwrites',
1077 help='Overwrite post-processed files (default)')
1078 postproc.add_option(
1079 '--no-post-overwrites',
1080 action='store_true', dest='nopostoverwrites', default=False,
1081 help='Do not overwrite post-processed files')
1082 postproc.add_option(
1083 '--embed-subs',
1084 action='store_true', dest='embedsubtitles', default=False,
1085 help='Embed subtitles in the video (only for mp4, webm and mkv videos)')
1086 postproc.add_option(
1087 '--no-embed-subs',
1088 action='store_false', dest='embedsubtitles',
1089 help='Do not embed subtitles (default)')
1090 postproc.add_option(
1091 '--embed-thumbnail',
1092 action='store_true', dest='embedthumbnail', default=False,
1093 help='Embed thumbnail in the audio as cover art')
1094 postproc.add_option(
1095 '--no-embed-thumbnail',
1096 action='store_false', dest='embedthumbnail',
1097 help='Do not embed thumbnail (default)')
1098 postproc.add_option(
1099 '--add-metadata',
1100 action='store_true', dest='addmetadata', default=False,
1101 help='Write metadata to the video file')
1102 postproc.add_option(
1103 '--no-add-metadata',
1104 action='store_false', dest='addmetadata',
1105 help='Do not write metadata (default)')
1106 postproc.add_option(
1107 '--metadata-from-title',
1108 metavar='FORMAT', dest='metafromtitle',
1109 help=optparse.SUPPRESS_HELP)
1110 postproc.add_option(
1111 '--parse-metadata',
1112 metavar='FIELD:FORMAT', dest='metafromfield', action='append',
1113 help=(
1114 'Parse additional metadata like title/artist from other fields. '
1115 'Give field name to extract data from, and format of the field seperated by a ":". '
1116 'Either regular expression with named capture groups or a '
1117 'similar syntax to the output template can also be used. '
1118 'The parsed parameters replace any existing values and can be use in output template'
1119 'This option can be used multiple times. '
1120 'Example: --parse-metadata "title:%(artist)s - %(title)s" matches a title like '
1121 '"Coldplay - Paradise". '
1122 'Example (regex): --parse-metadata "description:Artist - (?P<artist>.+?)"'))
1123 postproc.add_option(
1124 '--xattrs',
1125 action='store_true', dest='xattrs', default=False,
1126 help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
1127 postproc.add_option(
1128 '--fixup',
1129 metavar='POLICY', dest='fixup', default='detect_or_warn',
1130 help=(
1131 'Automatically correct known faults of the file. '
1132 'One of never (do nothing), warn (only emit a warning), '
1133 'detect_or_warn (the default; fix file if we can, warn otherwise)'))
1134 postproc.add_option(
1135 '--prefer-avconv', '--no-prefer-ffmpeg',
1136 action='store_false', dest='prefer_ffmpeg',
1137 help=optparse.SUPPRESS_HELP)
1138 postproc.add_option(
1139 '--prefer-ffmpeg', '--no-prefer-avconv',
1140 action='store_true', dest='prefer_ffmpeg', default=True,
1141 help=optparse.SUPPRESS_HELP)
1142 postproc.add_option(
1143 '--ffmpeg-location', '--avconv-location', metavar='PATH',
1144 dest='ffmpeg_location',
1145 help='Location of the ffmpeg binary; either the path to the binary or its containing directory')
1146 postproc.add_option(
1147 '--exec',
1148 metavar='CMD', dest='exec_cmd',
1149 help='Execute a command on the file after downloading and post-processing, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'')
1150 postproc.add_option(
1151 '--convert-subs', '--convert-subtitles',
1152 metavar='FORMAT', dest='convertsubtitles', default=None,
1153 help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)')
1154
1155 sponskrub = optparse.OptionGroup(parser, 'SponSkrub (SponsorBlock) Options', description=(
1156 'SponSkrub (https://github.com/pukkandan/SponSkrub) is a utility to mark/remove sponsor segments '
1157 'from downloaded YouTube videos using SponsorBlock API (https://sponsor.ajay.app)'))
1158 sponskrub.add_option(
1159 '--sponskrub',
1160 action='store_true', dest='sponskrub', default=None,
1161 help=(
1162 'Use sponskrub to mark sponsored sections. '
1163 'This is enabled by default if the sponskrub binary exists (Youtube only)'))
1164 sponskrub.add_option(
1165 '--no-sponskrub',
1166 action='store_false', dest='sponskrub',
1167 help='Do not use sponskrub')
1168 sponskrub.add_option(
1169 '--sponskrub-cut', default=False,
1170 action='store_true', dest='sponskrub_cut',
1171 help='Cut out the sponsor sections instead of simply marking them')
1172 sponskrub.add_option(
1173 '--no-sponskrub-cut',
1174 action='store_false', dest='sponskrub_cut',
1175 help='Simply mark the sponsor sections, not cut them out (default)')
1176 sponskrub.add_option(
1177 '--sponskrub-force', default=False,
1178 action='store_true', dest='sponskrub_force',
1179 help='Run sponskrub even if the video was already downloaded')
1180 sponskrub.add_option(
1181 '--no-sponskrub-force',
1182 action='store_true', dest='sponskrub_force',
1183 help='Do not cut out the sponsor sections if the video was already downloaded (default)')
1184 sponskrub.add_option(
1185 '--sponskrub-location', metavar='PATH',
1186 dest='sponskrub_path', default='',
1187 help='Location of the sponskrub binary; either the path to the binary or its containing directory')
1188 sponskrub.add_option(
1189 '--sponskrub-args', dest='sponskrub_args', metavar='ARGS',
1190 help=optparse.SUPPRESS_HELP)
1191
1192 extractor = optparse.OptionGroup(parser, 'Extractor Options')
1193 extractor.add_option(
1194 '--allow-dynamic-mpd', '--no-ignore-dynamic-mpd',
1195 action='store_true', dest='dynamic_mpd', default=True,
1196 help='Process dynamic DASH manifests (default) (Alias: --no-ignore-dynamic-mpd)')
1197 extractor.add_option(
1198 '--ignore-dynamic-mpd', '--no-allow-dynamic-mpd',
1199 action='store_false', dest='dynamic_mpd',
1200 help='Do not process dynamic DASH manifests (Alias: --no-allow-dynamic-mpd)')
1201
1202 parser.add_option_group(general)
1203 parser.add_option_group(network)
1204 parser.add_option_group(geo)
1205 parser.add_option_group(selection)
1206 parser.add_option_group(downloader)
1207 parser.add_option_group(filesystem)
1208 parser.add_option_group(thumbnail)
1209 parser.add_option_group(link)
1210 parser.add_option_group(verbosity)
1211 parser.add_option_group(workarounds)
1212 parser.add_option_group(video_format)
1213 parser.add_option_group(subtitles)
1214 parser.add_option_group(authentication)
1215 parser.add_option_group(adobe_pass)
1216 parser.add_option_group(postproc)
1217 parser.add_option_group(sponskrub)
1218 parser.add_option_group(extractor)
1219
1220 if overrideArguments is not None:
1221 opts, args = parser.parse_args(overrideArguments)
1222 if opts.verbose:
1223 write_string('[debug] Override config: ' + repr(overrideArguments) + '\n')
1224 else:
1225 def compat_conf(conf):
1226 if sys.version_info < (3,):
1227 return [a.decode(preferredencoding(), 'replace') for a in conf]
1228 return conf
1229
1230 configs = {
1231 'command-line': compat_conf(sys.argv[1:]),
1232 'custom': [], 'home': [], 'portable': [], 'user': [], 'system': []}
1233 paths = {'command-line': False}
1234 opts, args = parser.parse_args(configs['command-line'])
1235
1236 def get_configs():
1237 if '--config-location' in configs['command-line']:
1238 location = compat_expanduser(opts.config_location)
1239 if os.path.isdir(location):
1240 location = os.path.join(location, 'youtube-dlc.conf')
1241 if not os.path.exists(location):
1242 parser.error('config-location %s does not exist.' % location)
1243 configs['custom'] = _readOptions(location, default=None)
1244 if configs['custom'] is None:
1245 configs['custom'] = []
1246 else:
1247 paths['custom'] = location
1248 if '--ignore-config' in configs['command-line']:
1249 return
1250 if '--ignore-config' in configs['custom']:
1251 return
1252
1253 def read_options(path, user=False):
1254 for package in ('yt-dlp', 'youtube-dlc'):
1255 if user:
1256 config, current_path = _readUserConf(package, default=None)
1257 else:
1258 current_path = os.path.join(path, '%s.conf' % package)
1259 config = _readOptions(current_path, default=None)
1260 if config is not None:
1261 return config, current_path
1262 return [], None
1263
1264 configs['portable'], paths['portable'] = read_options(get_executable_path())
1265 if '--ignore-config' in configs['portable']:
1266 return
1267
1268 def get_home_path():
1269 opts = parser.parse_args(configs['portable'] + configs['custom'] + configs['command-line'])[0]
1270 return expand_path(opts.paths.get('home', '')).strip()
1271
1272 configs['home'], paths['home'] = read_options(get_home_path())
1273 if '--ignore-config' in configs['home']:
1274 return
1275
1276 configs['system'], paths['system'] = read_options('/etc')
1277 if '--ignore-config' in configs['system']:
1278 return
1279
1280 configs['user'], paths['user'] = read_options('', True)
1281 if '--ignore-config' in configs['user']:
1282 configs['system'], paths['system'] = [], None
1283
1284 get_configs()
1285 argv = configs['system'] + configs['user'] + configs['home'] + configs['portable'] + configs['custom'] + configs['command-line']
1286 opts, args = parser.parse_args(argv)
1287 if opts.verbose:
1288 for label in ('System', 'User', 'Portable', 'Home', 'Custom', 'Command-line'):
1289 key = label.lower()
1290 if paths.get(key) is None:
1291 continue
1292 if paths[key]:
1293 write_string('[debug] %s config file: %s\n' % (label, paths[key]))
1294 write_string('[debug] %s config: %s\n' % (label, repr(_hide_login_info(configs[key]))))
1295
1296 return parser, opts, args