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.

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