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.

774 lines
35 KiB

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