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.

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