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.

906 lines
41 KiB

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