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

902 lines
41 KiB

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