options.py 42 KB

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