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.

908 lines
41 KiB

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