options.py 43 KB

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