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.

832 lines
38 KiB

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