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.

912 lines
41 KiB

8 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. '--http-chunk-size',
  451. dest='http_chunk_size', metavar='SIZE', default=None,
  452. help='Size of a chunk for chunk-based HTTP downloading (e.g. 10485760 or 10M) (default is disabled). '
  453. 'May be useful for bypassing bandwidth throttling imposed by a webserver (experimental)')
  454. downloader.add_option(
  455. '--test',
  456. action='store_true', dest='test', default=False,
  457. help=optparse.SUPPRESS_HELP)
  458. downloader.add_option(
  459. '--playlist-reverse',
  460. action='store_true',
  461. help='Download playlist videos in reverse order')
  462. downloader.add_option(
  463. '--playlist-random',
  464. action='store_true',
  465. help='Download playlist videos in random order')
  466. downloader.add_option(
  467. '--xattr-set-filesize',
  468. dest='xattr_set_filesize', action='store_true',
  469. help='Set file xattribute ytdl.filesize with expected file size (experimental)')
  470. downloader.add_option(
  471. '--hls-prefer-native',
  472. dest='hls_prefer_native', action='store_true', default=None,
  473. help='Use the native HLS downloader instead of ffmpeg')
  474. downloader.add_option(
  475. '--hls-prefer-ffmpeg',
  476. dest='hls_prefer_native', action='store_false', default=None,
  477. help='Use ffmpeg instead of the native HLS downloader')
  478. downloader.add_option(
  479. '--hls-use-mpegts',
  480. dest='hls_use_mpegts', action='store_true',
  481. help='Use the mpegts container for HLS videos, allowing to play the '
  482. 'video while downloading (some players may not be able to play it)')
  483. downloader.add_option(
  484. '--external-downloader',
  485. dest='external_downloader', metavar='COMMAND',
  486. help='Use the specified external downloader. '
  487. 'Currently supports %s' % ','.join(list_external_downloaders()))
  488. downloader.add_option(
  489. '--external-downloader-args',
  490. dest='external_downloader_args', metavar='ARGS',
  491. help='Give these arguments to the external downloader')
  492. workarounds = optparse.OptionGroup(parser, 'Workarounds')
  493. workarounds.add_option(
  494. '--encoding',
  495. dest='encoding', metavar='ENCODING',
  496. help='Force the specified encoding (experimental)')
  497. workarounds.add_option(
  498. '--no-check-certificate',
  499. action='store_true', dest='no_check_certificate', default=False,
  500. help='Suppress HTTPS certificate validation')
  501. workarounds.add_option(
  502. '--prefer-insecure',
  503. '--prefer-unsecure', action='store_true', dest='prefer_insecure',
  504. help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
  505. workarounds.add_option(
  506. '--user-agent',
  507. metavar='UA', dest='user_agent',
  508. help='Specify a custom user agent')
  509. workarounds.add_option(
  510. '--referer',
  511. metavar='URL', dest='referer', default=None,
  512. help='Specify a custom referer, use if the video access is restricted to one domain',
  513. )
  514. workarounds.add_option(
  515. '--add-header',
  516. metavar='FIELD:VALUE', dest='headers', action='append',
  517. help='Specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
  518. )
  519. workarounds.add_option(
  520. '--bidi-workaround',
  521. dest='bidi_workaround', action='store_true',
  522. help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
  523. workarounds.add_option(
  524. '--sleep-interval', '--min-sleep-interval', metavar='SECONDS',
  525. dest='sleep_interval', type=float,
  526. help=(
  527. 'Number of seconds to sleep before each download when used alone '
  528. 'or a lower bound of a range for randomized sleep before each download '
  529. '(minimum possible number of seconds to sleep) when used along with '
  530. '--max-sleep-interval.'))
  531. workarounds.add_option(
  532. '--max-sleep-interval', metavar='SECONDS',
  533. dest='max_sleep_interval', type=float,
  534. help=(
  535. 'Upper bound of a range for randomized sleep before each download '
  536. '(maximum possible number of seconds to sleep). Must only be used '
  537. 'along with --min-sleep-interval.'))
  538. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  539. verbosity.add_option(
  540. '-q', '--quiet',
  541. action='store_true', dest='quiet', default=False,
  542. help='Activate quiet mode')
  543. verbosity.add_option(
  544. '--no-warnings',
  545. dest='no_warnings', action='store_true', default=False,
  546. help='Ignore warnings')
  547. verbosity.add_option(
  548. '-s', '--simulate',
  549. action='store_true', dest='simulate', default=False,
  550. help='Do not download the video and do not write anything to disk')
  551. verbosity.add_option(
  552. '--skip-download',
  553. action='store_true', dest='skip_download', default=False,
  554. help='Do not download the video')
  555. verbosity.add_option(
  556. '-g', '--get-url',
  557. action='store_true', dest='geturl', default=False,
  558. help='Simulate, quiet but print URL')
  559. verbosity.add_option(
  560. '-e', '--get-title',
  561. action='store_true', dest='gettitle', default=False,
  562. help='Simulate, quiet but print title')
  563. verbosity.add_option(
  564. '--get-id',
  565. action='store_true', dest='getid', default=False,
  566. help='Simulate, quiet but print id')
  567. verbosity.add_option(
  568. '--get-thumbnail',
  569. action='store_true', dest='getthumbnail', default=False,
  570. help='Simulate, quiet but print thumbnail URL')
  571. verbosity.add_option(
  572. '--get-description',
  573. action='store_true', dest='getdescription', default=False,
  574. help='Simulate, quiet but print video description')
  575. verbosity.add_option(
  576. '--get-duration',
  577. action='store_true', dest='getduration', default=False,
  578. help='Simulate, quiet but print video length')
  579. verbosity.add_option(
  580. '--get-filename',
  581. action='store_true', dest='getfilename', default=False,
  582. help='Simulate, quiet but print output filename')
  583. verbosity.add_option(
  584. '--get-format',
  585. action='store_true', dest='getformat', default=False,
  586. help='Simulate, quiet but print output format')
  587. verbosity.add_option(
  588. '-j', '--dump-json',
  589. action='store_true', dest='dumpjson', default=False,
  590. help='Simulate, quiet but print JSON information. See the "OUTPUT TEMPLATE" for a description of available keys.')
  591. verbosity.add_option(
  592. '-J', '--dump-single-json',
  593. action='store_true', dest='dump_single_json', default=False,
  594. 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.')
  595. verbosity.add_option(
  596. '--print-json',
  597. action='store_true', dest='print_json', default=False,
  598. help='Be quiet and print the video information as JSON (video is still being downloaded).',
  599. )
  600. verbosity.add_option(
  601. '--newline',
  602. action='store_true', dest='progress_with_newline', default=False,
  603. help='Output progress bar as new lines')
  604. verbosity.add_option(
  605. '--no-progress',
  606. action='store_true', dest='noprogress', default=False,
  607. help='Do not print progress bar')
  608. verbosity.add_option(
  609. '--console-title',
  610. action='store_true', dest='consoletitle', default=False,
  611. help='Display progress in console titlebar')
  612. verbosity.add_option(
  613. '-v', '--verbose',
  614. action='store_true', dest='verbose', default=False,
  615. help='Print various debugging information')
  616. verbosity.add_option(
  617. '--dump-pages', '--dump-intermediate-pages',
  618. action='store_true', dest='dump_intermediate_pages', default=False,
  619. help='Print downloaded pages encoded using base64 to debug problems (very verbose)')
  620. verbosity.add_option(
  621. '--write-pages',
  622. action='store_true', dest='write_pages', default=False,
  623. help='Write downloaded intermediary pages to files in the current directory to debug problems')
  624. verbosity.add_option(
  625. '--youtube-print-sig-code',
  626. action='store_true', dest='youtube_print_sig_code', default=False,
  627. help=optparse.SUPPRESS_HELP)
  628. verbosity.add_option(
  629. '--print-traffic', '--dump-headers',
  630. dest='debug_printtraffic', action='store_true', default=False,
  631. help='Display sent and read HTTP traffic')
  632. verbosity.add_option(
  633. '-C', '--call-home',
  634. dest='call_home', action='store_true', default=False,
  635. help='Contact the youtube-dl server for debugging')
  636. verbosity.add_option(
  637. '--no-call-home',
  638. dest='call_home', action='store_false', default=False,
  639. help='Do NOT contact the youtube-dl server for debugging')
  640. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  641. filesystem.add_option(
  642. '-a', '--batch-file',
  643. dest='batchfile', metavar='FILE',
  644. help="File containing URLs to download ('-' for stdin), one URL per line. "
  645. "Lines starting with '#', ';' or ']' are considered as comments and ignored.")
  646. filesystem.add_option(
  647. '--id', default=False,
  648. action='store_true', dest='useid', help='Use only video ID in file name')
  649. filesystem.add_option(
  650. '-o', '--output',
  651. dest='outtmpl', metavar='TEMPLATE',
  652. help=('Output filename template, see the "OUTPUT TEMPLATE" for all the info'))
  653. filesystem.add_option(
  654. '--autonumber-size',
  655. dest='autonumber_size', metavar='NUMBER', type=int,
  656. help=optparse.SUPPRESS_HELP)
  657. filesystem.add_option(
  658. '--autonumber-start',
  659. dest='autonumber_start', metavar='NUMBER', default=1, type=int,
  660. help='Specify the start value for %(autonumber)s (default is %default)')
  661. filesystem.add_option(
  662. '--restrict-filenames',
  663. action='store_true', dest='restrictfilenames', default=False,
  664. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
  665. filesystem.add_option(
  666. '-A', '--auto-number',
  667. action='store_true', dest='autonumber', default=False,
  668. help=optparse.SUPPRESS_HELP)
  669. filesystem.add_option(
  670. '-t', '--title',
  671. action='store_true', dest='usetitle', default=False,
  672. help=optparse.SUPPRESS_HELP)
  673. filesystem.add_option(
  674. '-l', '--literal', default=False,
  675. action='store_true', dest='usetitle',
  676. help=optparse.SUPPRESS_HELP)
  677. filesystem.add_option(
  678. '-w', '--no-overwrites',
  679. action='store_true', dest='nooverwrites', default=False,
  680. help='Do not overwrite files')
  681. filesystem.add_option(
  682. '-c', '--continue',
  683. action='store_true', dest='continue_dl', default=True,
  684. help='Force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.')
  685. filesystem.add_option(
  686. '--no-continue',
  687. action='store_false', dest='continue_dl',
  688. help='Do not resume partially downloaded files (restart from beginning)')
  689. filesystem.add_option(
  690. '--no-part',
  691. action='store_true', dest='nopart', default=False,
  692. help='Do not use .part files - write directly into output file')
  693. filesystem.add_option(
  694. '--no-mtime',
  695. action='store_false', dest='updatetime', default=True,
  696. help='Do not use the Last-modified header to set the file modification time')
  697. filesystem.add_option(
  698. '--write-description',
  699. action='store_true', dest='writedescription', default=False,
  700. help='Write video description to a .description file')
  701. filesystem.add_option(
  702. '--write-info-json',
  703. action='store_true', dest='writeinfojson', default=False,
  704. help='Write video metadata to a .info.json file')
  705. filesystem.add_option(
  706. '--write-annotations',
  707. action='store_true', dest='writeannotations', default=False,
  708. help='Write video annotations to a .annotations.xml file')
  709. filesystem.add_option(
  710. '--load-info-json', '--load-info',
  711. dest='load_info_filename', metavar='FILE',
  712. help='JSON file containing the video information (created with the "--write-info-json" option)')
  713. filesystem.add_option(
  714. '--cookies',
  715. dest='cookiefile', metavar='FILE',
  716. help='File to read cookies from and dump cookie jar in')
  717. filesystem.add_option(
  718. '--cache-dir', dest='cachedir', default=None, metavar='DIR',
  719. 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.')
  720. filesystem.add_option(
  721. '--no-cache-dir', action='store_const', const=False, dest='cachedir',
  722. help='Disable filesystem caching')
  723. filesystem.add_option(
  724. '--rm-cache-dir',
  725. action='store_true', dest='rm_cachedir',
  726. help='Delete all filesystem cache files')
  727. thumbnail = optparse.OptionGroup(parser, 'Thumbnail images')
  728. thumbnail.add_option(
  729. '--write-thumbnail',
  730. action='store_true', dest='writethumbnail', default=False,
  731. help='Write thumbnail image to disk')
  732. thumbnail.add_option(
  733. '--write-all-thumbnails',
  734. action='store_true', dest='write_all_thumbnails', default=False,
  735. help='Write all thumbnail image formats to disk')
  736. thumbnail.add_option(
  737. '--list-thumbnails',
  738. action='store_true', dest='list_thumbnails', default=False,
  739. help='Simulate and list all available thumbnail formats')
  740. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  741. postproc.add_option(
  742. '-x', '--extract-audio',
  743. action='store_true', dest='extractaudio', default=False,
  744. help='Convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
  745. postproc.add_option(
  746. '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  747. help='Specify audio format: "best", "aac", "flac", "mp3", "m4a", "opus", "vorbis", or "wav"; "%default" by default; No effect without -x')
  748. postproc.add_option(
  749. '--audio-quality', metavar='QUALITY',
  750. dest='audioquality', default='5',
  751. 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)')
  752. postproc.add_option(
  753. '--recode-video',
  754. metavar='FORMAT', dest='recodevideo', default=None,
  755. help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)')
  756. postproc.add_option(
  757. '--postprocessor-args',
  758. dest='postprocessor_args', metavar='ARGS',
  759. help='Give these arguments to the postprocessor')
  760. postproc.add_option(
  761. '-k', '--keep-video',
  762. action='store_true', dest='keepvideo', default=False,
  763. help='Keep the video file on disk after the post-processing; the video is erased by default')
  764. postproc.add_option(
  765. '--no-post-overwrites',
  766. action='store_true', dest='nopostoverwrites', default=False,
  767. help='Do not overwrite post-processed files; the post-processed files are overwritten by default')
  768. postproc.add_option(
  769. '--embed-subs',
  770. action='store_true', dest='embedsubtitles', default=False,
  771. help='Embed subtitles in the video (only for mp4, webm and mkv videos)')
  772. postproc.add_option(
  773. '--embed-thumbnail',
  774. action='store_true', dest='embedthumbnail', default=False,
  775. help='Embed thumbnail in the audio as cover art')
  776. postproc.add_option(
  777. '--add-metadata',
  778. action='store_true', dest='addmetadata', default=False,
  779. help='Write metadata to the video file')
  780. postproc.add_option(
  781. '--metadata-from-title',
  782. metavar='FORMAT', dest='metafromtitle',
  783. help='Parse additional metadata like song title / artist from the video title. '
  784. 'The format syntax is the same as --output. Regular expression with '
  785. 'named capture groups may also be used. '
  786. 'The parsed parameters replace existing values. '
  787. 'Example: --metadata-from-title "%(artist)s - %(title)s" matches a title like '
  788. '"Coldplay - Paradise". '
  789. 'Example (regex): --metadata-from-title "(?P<artist>.+?) - (?P<title>.+)"')
  790. postproc.add_option(
  791. '--xattrs',
  792. action='store_true', dest='xattrs', default=False,
  793. help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
  794. postproc.add_option(
  795. '--fixup',
  796. metavar='POLICY', dest='fixup', default='detect_or_warn',
  797. help='Automatically correct known faults of the file. '
  798. 'One of never (do nothing), warn (only emit a warning), '
  799. 'detect_or_warn (the default; fix file if we can, warn otherwise)')
  800. postproc.add_option(
  801. '--prefer-avconv',
  802. action='store_false', dest='prefer_ffmpeg',
  803. help='Prefer avconv over ffmpeg for running the postprocessors (default)')
  804. postproc.add_option(
  805. '--prefer-ffmpeg',
  806. action='store_true', dest='prefer_ffmpeg',
  807. help='Prefer ffmpeg over avconv for running the postprocessors')
  808. postproc.add_option(
  809. '--ffmpeg-location', '--avconv-location', metavar='PATH',
  810. dest='ffmpeg_location',
  811. help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.')
  812. postproc.add_option(
  813. '--exec',
  814. metavar='CMD', dest='exec_cmd',
  815. help='Execute a command on the file after downloading, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'')
  816. postproc.add_option(
  817. '--convert-subs', '--convert-subtitles',
  818. metavar='FORMAT', dest='convertsubtitles', default=None,
  819. help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)')
  820. parser.add_option_group(general)
  821. parser.add_option_group(network)
  822. parser.add_option_group(geo)
  823. parser.add_option_group(selection)
  824. parser.add_option_group(downloader)
  825. parser.add_option_group(filesystem)
  826. parser.add_option_group(thumbnail)
  827. parser.add_option_group(verbosity)
  828. parser.add_option_group(workarounds)
  829. parser.add_option_group(video_format)
  830. parser.add_option_group(subtitles)
  831. parser.add_option_group(authentication)
  832. parser.add_option_group(adobe_pass)
  833. parser.add_option_group(postproc)
  834. if overrideArguments is not None:
  835. opts, args = parser.parse_args(overrideArguments)
  836. if opts.verbose:
  837. write_string('[debug] Override config: ' + repr(overrideArguments) + '\n')
  838. else:
  839. def compat_conf(conf):
  840. if sys.version_info < (3,):
  841. return [a.decode(preferredencoding(), 'replace') for a in conf]
  842. return conf
  843. command_line_conf = compat_conf(sys.argv[1:])
  844. opts, args = parser.parse_args(command_line_conf)
  845. system_conf = user_conf = custom_conf = []
  846. if '--config-location' in command_line_conf:
  847. location = compat_expanduser(opts.config_location)
  848. if os.path.isdir(location):
  849. location = os.path.join(location, 'youtube-dl.conf')
  850. if not os.path.exists(location):
  851. parser.error('config-location %s does not exist.' % location)
  852. custom_conf = _readOptions(location)
  853. elif '--ignore-config' in command_line_conf:
  854. pass
  855. else:
  856. system_conf = _readOptions('/etc/youtube-dl.conf')
  857. if '--ignore-config' not in system_conf:
  858. user_conf = _readUserConf()
  859. argv = system_conf + user_conf + custom_conf + command_line_conf
  860. opts, args = parser.parse_args(argv)
  861. if opts.verbose:
  862. for conf_label, conf in (
  863. ('System config', system_conf),
  864. ('User config', user_conf),
  865. ('Custom config', custom_conf),
  866. ('Command-line args', command_line_conf)):
  867. write_string('[debug] %s: %s\n' % (conf_label, repr(_hide_login_info(conf))))
  868. return parser, opts, args