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.

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