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.

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