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.

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