logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

options.py (42794B)


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