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.

854 lines
39 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']
  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. '--flat-playlist',
  160. action='store_const', dest='extract_flat', const='in_playlist',
  161. default=False,
  162. help='Do not extract the videos of a playlist, only list them.')
  163. general.add_option(
  164. '--mark-watched',
  165. action='store_true', dest='mark_watched', default=False,
  166. help='Mark videos watched (YouTube only)')
  167. general.add_option(
  168. '--no-mark-watched',
  169. action='store_false', dest='mark_watched', default=False,
  170. help='Do not mark videos watched (YouTube only)')
  171. general.add_option(
  172. '--no-color', '--no-colors',
  173. action='store_true', dest='no_color',
  174. default=False,
  175. help='Do not emit color codes in output')
  176. network = optparse.OptionGroup(parser, 'Network Options')
  177. network.add_option(
  178. '--proxy', dest='proxy',
  179. default=None, metavar='URL',
  180. help='Use the specified HTTP/HTTPS/SOCKS proxy. To enable experimental '
  181. 'SOCKS proxy, specify a proper scheme. For example '
  182. 'socks5://127.0.0.1:1080/. Pass in an empty string (--proxy "") '
  183. 'for direct connection')
  184. network.add_option(
  185. '--socket-timeout',
  186. dest='socket_timeout', type=float, default=None, metavar='SECONDS',
  187. help='Time to wait before giving up, in seconds')
  188. network.add_option(
  189. '--source-address',
  190. metavar='IP', dest='source_address', default=None,
  191. help='Client-side IP address to bind to (experimental)',
  192. )
  193. network.add_option(
  194. '-4', '--force-ipv4',
  195. action='store_const', const='0.0.0.0', dest='source_address',
  196. help='Make all connections via IPv4 (experimental)',
  197. )
  198. network.add_option(
  199. '-6', '--force-ipv6',
  200. action='store_const', const='::', dest='source_address',
  201. help='Make all connections via IPv6 (experimental)',
  202. )
  203. network.add_option(
  204. '--geo-verification-proxy',
  205. dest='geo_verification_proxy', default=None, metavar='URL',
  206. help='Use this proxy to verify the IP address for some geo-restricted sites. '
  207. 'The default proxy specified by --proxy (or none, if the options is not present) is used for the actual downloading. (experimental)'
  208. )
  209. network.add_option(
  210. '--cn-verification-proxy',
  211. dest='cn_verification_proxy', default=None, metavar='URL',
  212. help=optparse.SUPPRESS_HELP,
  213. )
  214. selection = optparse.OptionGroup(parser, 'Video Selection')
  215. selection.add_option(
  216. '--playlist-start',
  217. dest='playliststart', metavar='NUMBER', default=1, type=int,
  218. help='Playlist video to start at (default is %default)')
  219. selection.add_option(
  220. '--playlist-end',
  221. dest='playlistend', metavar='NUMBER', default=None, type=int,
  222. help='Playlist video to end at (default is last)')
  223. selection.add_option(
  224. '--playlist-items',
  225. dest='playlist_items', metavar='ITEM_SPEC', default=None,
  226. 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.')
  227. selection.add_option(
  228. '--match-title',
  229. dest='matchtitle', metavar='REGEX',
  230. help='Download only matching titles (regex or caseless sub-string)')
  231. selection.add_option(
  232. '--reject-title',
  233. dest='rejecttitle', metavar='REGEX',
  234. help='Skip download for matching titles (regex or caseless sub-string)')
  235. selection.add_option(
  236. '--max-downloads',
  237. dest='max_downloads', metavar='NUMBER', type=int, default=None,
  238. help='Abort after downloading NUMBER files')
  239. selection.add_option(
  240. '--min-filesize',
  241. metavar='SIZE', dest='min_filesize', default=None,
  242. help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
  243. selection.add_option(
  244. '--max-filesize',
  245. metavar='SIZE', dest='max_filesize', default=None,
  246. help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
  247. selection.add_option(
  248. '--date',
  249. metavar='DATE', dest='date', default=None,
  250. help='Download only videos uploaded in this date')
  251. selection.add_option(
  252. '--datebefore',
  253. metavar='DATE', dest='datebefore', default=None,
  254. help='Download only videos uploaded on or before this date (i.e. inclusive)')
  255. selection.add_option(
  256. '--dateafter',
  257. metavar='DATE', dest='dateafter', default=None,
  258. help='Download only videos uploaded on or after this date (i.e. inclusive)')
  259. selection.add_option(
  260. '--min-views',
  261. metavar='COUNT', dest='min_views', default=None, type=int,
  262. help='Do not download any videos with less than COUNT views')
  263. selection.add_option(
  264. '--max-views',
  265. metavar='COUNT', dest='max_views', default=None, type=int,
  266. help='Do not download any videos with more than COUNT views')
  267. selection.add_option(
  268. '--match-filter',
  269. metavar='FILTER', dest='match_filter', default=None,
  270. help=(
  271. 'Generic video filter (experimental). '
  272. 'Specify any key (see help for -o for a list of available keys) to'
  273. ' match if the key is present, '
  274. '!key to check if the key is not present,'
  275. 'key > NUMBER (like "comment_count > 12", also works with '
  276. '>=, <, <=, !=, =) to compare against a number, and '
  277. '& to require multiple matches. '
  278. 'Values which are not known are excluded unless you'
  279. ' put a question mark (?) after the operator.'
  280. 'For example, to only match videos that have been liked more than '
  281. '100 times and disliked less than 50 times (or the dislike '
  282. 'functionality is not available at the given service), but who '
  283. 'also have a description, use --match-filter '
  284. '"like_count > 100 & dislike_count <? 50 & description" .'
  285. ))
  286. selection.add_option(
  287. '--no-playlist',
  288. action='store_true', dest='noplaylist', default=False,
  289. help='Download only the video, if the URL refers to a video and a playlist.')
  290. selection.add_option(
  291. '--yes-playlist',
  292. action='store_false', dest='noplaylist', default=False,
  293. help='Download the playlist, if the URL refers to a video and a playlist.')
  294. selection.add_option(
  295. '--age-limit',
  296. metavar='YEARS', dest='age_limit', default=None, type=int,
  297. help='Download only videos suitable for the given age')
  298. selection.add_option(
  299. '--download-archive', metavar='FILE',
  300. dest='download_archive',
  301. help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
  302. selection.add_option(
  303. '--include-ads',
  304. dest='include_ads', action='store_true',
  305. help='Download advertisements as well (experimental)')
  306. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  307. authentication.add_option(
  308. '-u', '--username',
  309. dest='username', metavar='USERNAME',
  310. help='Login with this account ID')
  311. authentication.add_option(
  312. '-p', '--password',
  313. dest='password', metavar='PASSWORD',
  314. help='Account password. If this option is left out, youtube-dl will ask interactively.')
  315. authentication.add_option(
  316. '-2', '--twofactor',
  317. dest='twofactor', metavar='TWOFACTOR',
  318. help='Two-factor auth code')
  319. authentication.add_option(
  320. '-n', '--netrc',
  321. action='store_true', dest='usenetrc', default=False,
  322. help='Use .netrc authentication data')
  323. authentication.add_option(
  324. '--video-password',
  325. dest='videopassword', metavar='PASSWORD',
  326. help='Video password (vimeo, smotri, youku)')
  327. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  328. video_format.add_option(
  329. '-f', '--format',
  330. action='store', dest='format', metavar='FORMAT', default=None,
  331. help='Video format code, see the "FORMAT SELECTION" for all the info')
  332. video_format.add_option(
  333. '--all-formats',
  334. action='store_const', dest='format', const='all',
  335. help='Download all available video formats')
  336. video_format.add_option(
  337. '--prefer-free-formats',
  338. action='store_true', dest='prefer_free_formats', default=False,
  339. help='Prefer free video formats unless a specific one is requested')
  340. video_format.add_option(
  341. '-F', '--list-formats',
  342. action='store_true', dest='listformats',
  343. help='List all available formats of requested videos')
  344. video_format.add_option(
  345. '--youtube-include-dash-manifest',
  346. action='store_true', dest='youtube_include_dash_manifest', default=True,
  347. help=optparse.SUPPRESS_HELP)
  348. video_format.add_option(
  349. '--youtube-skip-dash-manifest',
  350. action='store_false', dest='youtube_include_dash_manifest',
  351. help='Do not download the DASH manifests and related data on YouTube videos')
  352. video_format.add_option(
  353. '--merge-output-format',
  354. action='store', dest='merge_output_format', metavar='FORMAT', default=None,
  355. help=(
  356. 'If a merge is required (e.g. bestvideo+bestaudio), '
  357. 'output to given container format. One of mkv, mp4, ogg, webm, flv. '
  358. 'Ignored if no merge is required'))
  359. subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
  360. subtitles.add_option(
  361. '--write-sub', '--write-srt',
  362. action='store_true', dest='writesubtitles', default=False,
  363. help='Write subtitle file')
  364. subtitles.add_option(
  365. '--write-auto-sub', '--write-automatic-sub',
  366. action='store_true', dest='writeautomaticsub', default=False,
  367. help='Write automatically generated subtitle file (YouTube only)')
  368. subtitles.add_option(
  369. '--all-subs',
  370. action='store_true', dest='allsubtitles', default=False,
  371. help='Download all the available subtitles of the video')
  372. subtitles.add_option(
  373. '--list-subs',
  374. action='store_true', dest='listsubtitles', default=False,
  375. help='List all available subtitles for the video')
  376. subtitles.add_option(
  377. '--sub-format',
  378. action='store', dest='subtitlesformat', metavar='FORMAT', default='best',
  379. help='Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"')
  380. subtitles.add_option(
  381. '--sub-lang', '--sub-langs', '--srt-lang',
  382. action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
  383. default=[], callback=_comma_separated_values_options_callback,
  384. help='Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags')
  385. downloader = optparse.OptionGroup(parser, 'Download Options')
  386. downloader.add_option(
  387. '-r', '--limit-rate', '--rate-limit',
  388. dest='ratelimit', metavar='RATE',
  389. help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)')
  390. downloader.add_option(
  391. '-R', '--retries',
  392. dest='retries', metavar='RETRIES', default=10,
  393. help='Number of retries (default is %default), or "infinite".')
  394. downloader.add_option(
  395. '--fragment-retries',
  396. dest='fragment_retries', metavar='RETRIES', default=10,
  397. help='Number of retries for a fragment (default is %default), or "infinite" (DASH only)')
  398. downloader.add_option(
  399. '--buffer-size',
  400. dest='buffersize', metavar='SIZE', default='1024',
  401. help='Size of download buffer (e.g. 1024 or 16K) (default is %default)')
  402. downloader.add_option(
  403. '--no-resize-buffer',
  404. action='store_true', dest='noresizebuffer', default=False,
  405. help='Do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.')
  406. downloader.add_option(
  407. '--test',
  408. action='store_true', dest='test', default=False,
  409. help=optparse.SUPPRESS_HELP)
  410. downloader.add_option(
  411. '--playlist-reverse',
  412. action='store_true',
  413. help='Download playlist videos in reverse order')
  414. downloader.add_option(
  415. '--xattr-set-filesize',
  416. dest='xattr_set_filesize', action='store_true',
  417. help='Set file xattribute ytdl.filesize with expected filesize (experimental)')
  418. downloader.add_option(
  419. '--hls-prefer-native',
  420. dest='hls_prefer_native', action='store_true', default=None,
  421. help='Use the native HLS downloader instead of ffmpeg')
  422. downloader.add_option(
  423. '--hls-prefer-ffmpeg',
  424. dest='hls_prefer_native', action='store_false', default=None,
  425. help='Use ffmpeg instead of the native HLS downloader')
  426. downloader.add_option(
  427. '--hls-use-mpegts',
  428. dest='hls_use_mpegts', action='store_true',
  429. help='Use the mpegts container for HLS videos, allowing to play the '
  430. 'video while downloading (some players may not be able to play it)')
  431. downloader.add_option(
  432. '--external-downloader',
  433. dest='external_downloader', metavar='COMMAND',
  434. help='Use the specified external downloader. '
  435. 'Currently supports %s' % ','.join(list_external_downloaders()))
  436. downloader.add_option(
  437. '--external-downloader-args',
  438. dest='external_downloader_args', metavar='ARGS',
  439. help='Give these arguments to the external downloader')
  440. workarounds = optparse.OptionGroup(parser, 'Workarounds')
  441. workarounds.add_option(
  442. '--encoding',
  443. dest='encoding', metavar='ENCODING',
  444. help='Force the specified encoding (experimental)')
  445. workarounds.add_option(
  446. '--no-check-certificate',
  447. action='store_true', dest='no_check_certificate', default=False,
  448. help='Suppress HTTPS certificate validation')
  449. workarounds.add_option(
  450. '--prefer-insecure',
  451. '--prefer-unsecure', action='store_true', dest='prefer_insecure',
  452. help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
  453. workarounds.add_option(
  454. '--user-agent',
  455. metavar='UA', dest='user_agent',
  456. help='Specify a custom user agent')
  457. workarounds.add_option(
  458. '--referer',
  459. metavar='URL', dest='referer', default=None,
  460. help='Specify a custom referer, use if the video access is restricted to one domain',
  461. )
  462. workarounds.add_option(
  463. '--add-header',
  464. metavar='FIELD:VALUE', dest='headers', action='append',
  465. help='Specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
  466. )
  467. workarounds.add_option(
  468. '--bidi-workaround',
  469. dest='bidi_workaround', action='store_true',
  470. help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
  471. workarounds.add_option(
  472. '--sleep-interval', '--min-sleep-interval', metavar='SECONDS',
  473. dest='sleep_interval', type=float,
  474. help=(
  475. 'Number of seconds to sleep before each download when used alone '
  476. 'or a lower bound of a range for randomized sleep before each download '
  477. '(minimum possible number of seconds to sleep) when used along with '
  478. '--max-sleep-interval.'))
  479. workarounds.add_option(
  480. '--max-sleep-interval', metavar='SECONDS',
  481. dest='max_sleep_interval', type=float,
  482. help=(
  483. 'Upper bound of a range for randomized sleep before each download '
  484. '(maximum possible number of seconds to sleep). Must only be used '
  485. 'along with --min-sleep-interval.'))
  486. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  487. verbosity.add_option(
  488. '-q', '--quiet',
  489. action='store_true', dest='quiet', default=False,
  490. help='Activate quiet mode')
  491. verbosity.add_option(
  492. '--no-warnings',
  493. dest='no_warnings', action='store_true', default=False,
  494. help='Ignore warnings')
  495. verbosity.add_option(
  496. '-s', '--simulate',
  497. action='store_true', dest='simulate', default=False,
  498. help='Do not download the video and do not write anything to disk')
  499. verbosity.add_option(
  500. '--skip-download',
  501. action='store_true', dest='skip_download', default=False,
  502. help='Do not download the video')
  503. verbosity.add_option(
  504. '-g', '--get-url',
  505. action='store_true', dest='geturl', default=False,
  506. help='Simulate, quiet but print URL')
  507. verbosity.add_option(
  508. '-e', '--get-title',
  509. action='store_true', dest='gettitle', default=False,
  510. help='Simulate, quiet but print title')
  511. verbosity.add_option(
  512. '--get-id',
  513. action='store_true', dest='getid', default=False,
  514. help='Simulate, quiet but print id')
  515. verbosity.add_option(
  516. '--get-thumbnail',
  517. action='store_true', dest='getthumbnail', default=False,
  518. help='Simulate, quiet but print thumbnail URL')
  519. verbosity.add_option(
  520. '--get-description',
  521. action='store_true', dest='getdescription', default=False,
  522. help='Simulate, quiet but print video description')
  523. verbosity.add_option(
  524. '--get-duration',
  525. action='store_true', dest='getduration', default=False,
  526. help='Simulate, quiet but print video length')
  527. verbosity.add_option(
  528. '--get-filename',
  529. action='store_true', dest='getfilename', default=False,
  530. help='Simulate, quiet but print output filename')
  531. verbosity.add_option(
  532. '--get-format',
  533. action='store_true', dest='getformat', default=False,
  534. help='Simulate, quiet but print output format')
  535. verbosity.add_option(
  536. '-j', '--dump-json',
  537. action='store_true', dest='dumpjson', default=False,
  538. help='Simulate, quiet but print JSON information. See --output for a description of available keys.')
  539. verbosity.add_option(
  540. '-J', '--dump-single-json',
  541. action='store_true', dest='dump_single_json', default=False,
  542. 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.')
  543. verbosity.add_option(
  544. '--print-json',
  545. action='store_true', dest='print_json', default=False,
  546. help='Be quiet and print the video information as JSON (video is still being downloaded).',
  547. )
  548. verbosity.add_option(
  549. '--newline',
  550. action='store_true', dest='progress_with_newline', default=False,
  551. help='Output progress bar as new lines')
  552. verbosity.add_option(
  553. '--no-progress',
  554. action='store_true', dest='noprogress', default=False,
  555. help='Do not print progress bar')
  556. verbosity.add_option(
  557. '--console-title',
  558. action='store_true', dest='consoletitle', default=False,
  559. help='Display progress in console titlebar')
  560. verbosity.add_option(
  561. '-v', '--verbose',
  562. action='store_true', dest='verbose', default=False,
  563. help='Print various debugging information')
  564. verbosity.add_option(
  565. '--dump-pages', '--dump-intermediate-pages',
  566. action='store_true', dest='dump_intermediate_pages', default=False,
  567. help='Print downloaded pages encoded using base64 to debug problems (very verbose)')
  568. verbosity.add_option(
  569. '--write-pages',
  570. action='store_true', dest='write_pages', default=False,
  571. help='Write downloaded intermediary pages to files in the current directory to debug problems')
  572. verbosity.add_option(
  573. '--youtube-print-sig-code',
  574. action='store_true', dest='youtube_print_sig_code', default=False,
  575. help=optparse.SUPPRESS_HELP)
  576. verbosity.add_option(
  577. '--print-traffic', '--dump-headers',
  578. dest='debug_printtraffic', action='store_true', default=False,
  579. help='Display sent and read HTTP traffic')
  580. verbosity.add_option(
  581. '-C', '--call-home',
  582. dest='call_home', action='store_true', default=False,
  583. help='Contact the youtube-dl server for debugging')
  584. verbosity.add_option(
  585. '--no-call-home',
  586. dest='call_home', action='store_false', default=False,
  587. help='Do NOT contact the youtube-dl server for debugging')
  588. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  589. filesystem.add_option(
  590. '-a', '--batch-file',
  591. dest='batchfile', metavar='FILE',
  592. help='File containing URLs to download (\'-\' for stdin)')
  593. filesystem.add_option(
  594. '--id', default=False,
  595. action='store_true', dest='useid', help='Use only video ID in file name')
  596. filesystem.add_option(
  597. '-o', '--output',
  598. dest='outtmpl', metavar='TEMPLATE',
  599. help=('Output filename template. Use %(title)s to get the title, '
  600. '%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
  601. '%(autonumber)s to get an automatically incremented number, '
  602. '%(ext)s for the filename extension, '
  603. '%(format)s for the format description (like "22 - 1280x720" or "HD"), '
  604. '%(format_id)s for the unique id of the format (like YouTube\'s itags: "137"), '
  605. '%(upload_date)s for the upload date (YYYYMMDD), '
  606. '%(extractor)s for the provider (youtube, metacafe, etc), '
  607. '%(id)s for the video id, '
  608. '%(playlist_title)s, %(playlist_id)s, or %(playlist)s (=title if present, ID otherwise) for the playlist the video is in, '
  609. '%(playlist_index)s for the position in the playlist. '
  610. '%(height)s and %(width)s for the width and height of the video format. '
  611. '%(resolution)s for a textual description of the resolution of the video format. '
  612. '%% for a literal percent. '
  613. 'Use - to output to stdout. Can also be used to download to a different directory, '
  614. 'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
  615. filesystem.add_option(
  616. '--autonumber-size',
  617. dest='autonumber_size', metavar='NUMBER',
  618. help='Specify the number of digits in %(autonumber)s when it is present in output filename template or --auto-number option is given')
  619. filesystem.add_option(
  620. '--restrict-filenames',
  621. action='store_true', dest='restrictfilenames', default=False,
  622. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
  623. filesystem.add_option(
  624. '-A', '--auto-number',
  625. action='store_true', dest='autonumber', default=False,
  626. help='[deprecated; use -o "%(autonumber)s-%(title)s.%(ext)s" ] Number downloaded files starting from 00000')
  627. filesystem.add_option(
  628. '-t', '--title',
  629. action='store_true', dest='usetitle', default=False,
  630. help='[deprecated] Use title in file name (default)')
  631. filesystem.add_option(
  632. '-l', '--literal', default=False,
  633. action='store_true', dest='usetitle',
  634. help='[deprecated] Alias of --title')
  635. filesystem.add_option(
  636. '-w', '--no-overwrites',
  637. action='store_true', dest='nooverwrites', default=False,
  638. help='Do not overwrite files')
  639. filesystem.add_option(
  640. '-c', '--continue',
  641. action='store_true', dest='continue_dl', default=True,
  642. help='Force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.')
  643. filesystem.add_option(
  644. '--no-continue',
  645. action='store_false', dest='continue_dl',
  646. help='Do not resume partially downloaded files (restart from beginning)')
  647. filesystem.add_option(
  648. '--no-part',
  649. action='store_true', dest='nopart', default=False,
  650. help='Do not use .part files - write directly into output file')
  651. filesystem.add_option(
  652. '--no-mtime',
  653. action='store_false', dest='updatetime', default=True,
  654. help='Do not use the Last-modified header to set the file modification time')
  655. filesystem.add_option(
  656. '--write-description',
  657. action='store_true', dest='writedescription', default=False,
  658. help='Write video description to a .description file')
  659. filesystem.add_option(
  660. '--write-info-json',
  661. action='store_true', dest='writeinfojson', default=False,
  662. help='Write video metadata to a .info.json file')
  663. filesystem.add_option(
  664. '--write-annotations',
  665. action='store_true', dest='writeannotations', default=False,
  666. help='Write video annotations to a .annotations.xml file')
  667. filesystem.add_option(
  668. '--load-info-json', '--load-info',
  669. dest='load_info_filename', metavar='FILE',
  670. help='JSON file containing the video information (created with the "--write-info-json" option)')
  671. filesystem.add_option(
  672. '--cookies',
  673. dest='cookiefile', metavar='FILE',
  674. help='File to read cookies from and dump cookie jar in')
  675. filesystem.add_option(
  676. '--cache-dir', dest='cachedir', default=None, metavar='DIR',
  677. 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.')
  678. filesystem.add_option(
  679. '--no-cache-dir', action='store_const', const=False, dest='cachedir',
  680. help='Disable filesystem caching')
  681. filesystem.add_option(
  682. '--rm-cache-dir',
  683. action='store_true', dest='rm_cachedir',
  684. help='Delete all filesystem cache files')
  685. thumbnail = optparse.OptionGroup(parser, 'Thumbnail images')
  686. thumbnail.add_option(
  687. '--write-thumbnail',
  688. action='store_true', dest='writethumbnail', default=False,
  689. help='Write thumbnail image to disk')
  690. thumbnail.add_option(
  691. '--write-all-thumbnails',
  692. action='store_true', dest='write_all_thumbnails', default=False,
  693. help='Write all thumbnail image formats to disk')
  694. thumbnail.add_option(
  695. '--list-thumbnails',
  696. action='store_true', dest='list_thumbnails', default=False,
  697. help='Simulate and list all available thumbnail formats')
  698. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  699. postproc.add_option(
  700. '-x', '--extract-audio',
  701. action='store_true', dest='extractaudio', default=False,
  702. help='Convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
  703. postproc.add_option(
  704. '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  705. help='Specify audio format: "best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; "%default" by default')
  706. postproc.add_option(
  707. '--audio-quality', metavar='QUALITY',
  708. dest='audioquality', default='5',
  709. 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)')
  710. postproc.add_option(
  711. '--recode-video',
  712. metavar='FORMAT', dest='recodevideo', default=None,
  713. help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)')
  714. postproc.add_option(
  715. '--postprocessor-args',
  716. dest='postprocessor_args', metavar='ARGS',
  717. help='Give these arguments to the postprocessor')
  718. postproc.add_option(
  719. '-k', '--keep-video',
  720. action='store_true', dest='keepvideo', default=False,
  721. help='Keep the video file on disk after the post-processing; the video is erased by default')
  722. postproc.add_option(
  723. '--no-post-overwrites',
  724. action='store_true', dest='nopostoverwrites', default=False,
  725. help='Do not overwrite post-processed files; the post-processed files are overwritten by default')
  726. postproc.add_option(
  727. '--embed-subs',
  728. action='store_true', dest='embedsubtitles', default=False,
  729. help='Embed subtitles in the video (only for mp4, webm and mkv videos)')
  730. postproc.add_option(
  731. '--embed-thumbnail',
  732. action='store_true', dest='embedthumbnail', default=False,
  733. help='Embed thumbnail in the audio as cover art')
  734. postproc.add_option(
  735. '--add-metadata',
  736. action='store_true', dest='addmetadata', default=False,
  737. help='Write metadata to the video file')
  738. postproc.add_option(
  739. '--metadata-from-title',
  740. metavar='FORMAT', dest='metafromtitle',
  741. help='Parse additional metadata like song title / artist from the video title. '
  742. 'The format syntax is the same as --output, '
  743. 'the parsed parameters replace existing values. '
  744. 'Additional templates: %(album)s, %(artist)s. '
  745. 'Example: --metadata-from-title "%(artist)s - %(title)s" matches a title like '
  746. '"Coldplay - Paradise"')
  747. postproc.add_option(
  748. '--xattrs',
  749. action='store_true', dest='xattrs', default=False,
  750. help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
  751. postproc.add_option(
  752. '--fixup',
  753. metavar='POLICY', dest='fixup', default='detect_or_warn',
  754. help='Automatically correct known faults of the file. '
  755. 'One of never (do nothing), warn (only emit a warning), '
  756. 'detect_or_warn (the default; fix file if we can, warn otherwise)')
  757. postproc.add_option(
  758. '--prefer-avconv',
  759. action='store_false', dest='prefer_ffmpeg',
  760. help='Prefer avconv over ffmpeg for running the postprocessors (default)')
  761. postproc.add_option(
  762. '--prefer-ffmpeg',
  763. action='store_true', dest='prefer_ffmpeg',
  764. help='Prefer ffmpeg over avconv for running the postprocessors')
  765. postproc.add_option(
  766. '--ffmpeg-location', '--avconv-location', metavar='PATH',
  767. dest='ffmpeg_location',
  768. help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.')
  769. postproc.add_option(
  770. '--exec',
  771. metavar='CMD', dest='exec_cmd',
  772. help='Execute a command on the file after downloading, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'')
  773. postproc.add_option(
  774. '--convert-subs', '--convert-subtitles',
  775. metavar='FORMAT', dest='convertsubtitles', default=None,
  776. help='Convert the subtitles to other format (currently supported: srt|ass|vtt)')
  777. parser.add_option_group(general)
  778. parser.add_option_group(network)
  779. parser.add_option_group(selection)
  780. parser.add_option_group(downloader)
  781. parser.add_option_group(filesystem)
  782. parser.add_option_group(thumbnail)
  783. parser.add_option_group(verbosity)
  784. parser.add_option_group(workarounds)
  785. parser.add_option_group(video_format)
  786. parser.add_option_group(subtitles)
  787. parser.add_option_group(authentication)
  788. parser.add_option_group(postproc)
  789. if overrideArguments is not None:
  790. opts, args = parser.parse_args(overrideArguments)
  791. if opts.verbose:
  792. write_string('[debug] Override config: ' + repr(overrideArguments) + '\n')
  793. else:
  794. def compat_conf(conf):
  795. if sys.version_info < (3,):
  796. return [a.decode(preferredencoding(), 'replace') for a in conf]
  797. return conf
  798. command_line_conf = compat_conf(sys.argv[1:])
  799. if '--ignore-config' in command_line_conf:
  800. system_conf = []
  801. user_conf = []
  802. else:
  803. system_conf = _readOptions('/etc/youtube-dl.conf')
  804. if '--ignore-config' in system_conf:
  805. user_conf = []
  806. else:
  807. user_conf = _readUserConf()
  808. argv = system_conf + user_conf + command_line_conf
  809. opts, args = parser.parse_args(argv)
  810. if opts.verbose:
  811. write_string('[debug] System config: ' + repr(_hide_login_info(system_conf)) + '\n')
  812. write_string('[debug] User config: ' + repr(_hide_login_info(user_conf)) + '\n')
  813. write_string('[debug] Command-line args: ' + repr(_hide_login_info(command_line_conf)) + '\n')
  814. return parser, opts, args