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.

900 lines
43 KiB

13 years ago
12 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. __authors__ = (
  4. 'Ricardo Garcia Gonzalez',
  5. 'Danny Colligan',
  6. 'Benjamin Johnson',
  7. 'Vasyl\' Vavrychuk',
  8. 'Witold Baryluk',
  9. 'Paweł Paprota',
  10. 'Gergely Imreh',
  11. 'Rogério Brito',
  12. 'Philipp Hagemeister',
  13. 'Sören Schulze',
  14. 'Kevin Ngo',
  15. 'Ori Avtalion',
  16. 'shizeeg',
  17. 'Filippo Valsorda',
  18. 'Christian Albrecht',
  19. 'Dave Vasilevsky',
  20. 'Jaime Marquínez Ferrándiz',
  21. 'Jeff Crouse',
  22. 'Osama Khalid',
  23. 'Michael Walter',
  24. 'M. Yasoob Ullah Khalid',
  25. 'Julien Fraichard',
  26. 'Johny Mo Swag',
  27. 'Axel Noack',
  28. 'Albert Kim',
  29. 'Pierre Rudloff',
  30. 'Huarong Huo',
  31. 'Ismael Mejía',
  32. 'Steffan \'Ruirize\' James',
  33. 'Andras Elso',
  34. 'Jelle van der Waa',
  35. 'Marcin Cieślak',
  36. 'Anton Larionov',
  37. 'Takuya Tsuchida',
  38. 'Sergey M.',
  39. 'Michael Orlitzky',
  40. 'Chris Gahan',
  41. 'Saimadhav Heblikar',
  42. 'Mike Col',
  43. 'Oleg Prutz',
  44. 'pulpe',
  45. 'Andreas Schmitz',
  46. 'Michael Kaiser',
  47. 'Niklas Laxström',
  48. 'David Triendl',
  49. 'Anthony Weems',
  50. 'David Wagner',
  51. 'Juan C. Olivares',
  52. 'Mattias Harrysson',
  53. 'phaer',
  54. 'Sainyam Kapoor',
  55. 'Nicolas Évrard',
  56. 'Jason Normore',
  57. 'Hoje Lee',
  58. 'Adam Thalhammer',
  59. 'Georg Jähnig',
  60. 'Ralf Haring',
  61. 'Koki Takahashi',
  62. 'Ariset Llerena',
  63. 'Adam Malcontenti-Wilson',
  64. 'Tobias Bell',
  65. 'Naglis Jonaitis',
  66. 'Charles Chen',
  67. 'Hassaan Ali',
  68. 'Dobrosław Żybort',
  69. 'David Fabijan',
  70. 'Sebastian Haas',
  71. 'Alexander Kirk',
  72. 'Erik Johnson',
  73. )
  74. __license__ = 'Public Domain'
  75. import codecs
  76. import io
  77. import optparse
  78. import os
  79. import random
  80. import shlex
  81. import shutil
  82. import sys
  83. from .utils import (
  84. compat_getpass,
  85. compat_print,
  86. DateRange,
  87. DEFAULT_OUTTMPL,
  88. decodeOption,
  89. get_term_width,
  90. DownloadError,
  91. get_cachedir,
  92. MaxDownloadsReached,
  93. preferredencoding,
  94. read_batch_urls,
  95. SameFileError,
  96. setproctitle,
  97. std_headers,
  98. write_string,
  99. )
  100. from .update import update_self
  101. from .downloader import (
  102. FileDownloader,
  103. )
  104. from .extractor import gen_extractors
  105. from .version import __version__
  106. from .YoutubeDL import YoutubeDL
  107. from .postprocessor import (
  108. AtomicParsleyPP,
  109. FFmpegAudioFixPP,
  110. FFmpegMetadataPP,
  111. FFmpegVideoConvertor,
  112. FFmpegExtractAudioPP,
  113. FFmpegEmbedSubtitlePP,
  114. XAttrMetadataPP,
  115. )
  116. def parseOpts(overrideArguments=None):
  117. def _readOptions(filename_bytes, default=[]):
  118. try:
  119. optionf = open(filename_bytes)
  120. except IOError:
  121. return default # silently skip if file is not present
  122. try:
  123. res = []
  124. for l in optionf:
  125. res += shlex.split(l, comments=True)
  126. finally:
  127. optionf.close()
  128. return res
  129. def _readUserConf():
  130. xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
  131. if xdg_config_home:
  132. userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')
  133. if not os.path.isfile(userConfFile):
  134. userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
  135. else:
  136. userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl', 'config')
  137. if not os.path.isfile(userConfFile):
  138. userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
  139. userConf = _readOptions(userConfFile, None)
  140. if userConf is None:
  141. appdata_dir = os.environ.get('appdata')
  142. if appdata_dir:
  143. userConf = _readOptions(
  144. os.path.join(appdata_dir, 'youtube-dl', 'config'),
  145. default=None)
  146. if userConf is None:
  147. userConf = _readOptions(
  148. os.path.join(appdata_dir, 'youtube-dl', 'config.txt'),
  149. default=None)
  150. if userConf is None:
  151. userConf = _readOptions(
  152. os.path.join(os.path.expanduser('~'), 'youtube-dl.conf'),
  153. default=None)
  154. if userConf is None:
  155. userConf = _readOptions(
  156. os.path.join(os.path.expanduser('~'), 'youtube-dl.conf.txt'),
  157. default=None)
  158. if userConf is None:
  159. userConf = []
  160. return userConf
  161. def _format_option_string(option):
  162. ''' ('-o', '--option') -> -o, --format METAVAR'''
  163. opts = []
  164. if option._short_opts:
  165. opts.append(option._short_opts[0])
  166. if option._long_opts:
  167. opts.append(option._long_opts[0])
  168. if len(opts) > 1:
  169. opts.insert(1, ', ')
  170. if option.takes_value(): opts.append(' %s' % option.metavar)
  171. return "".join(opts)
  172. def _comma_separated_values_options_callback(option, opt_str, value, parser):
  173. setattr(parser.values, option.dest, value.split(','))
  174. def _hide_login_info(opts):
  175. opts = list(opts)
  176. for private_opt in ['-p', '--password', '-u', '--username', '--video-password']:
  177. try:
  178. i = opts.index(private_opt)
  179. opts[i+1] = '<PRIVATE>'
  180. except ValueError:
  181. pass
  182. return opts
  183. max_width = 80
  184. max_help_position = 80
  185. # No need to wrap help messages if we're on a wide console
  186. columns = get_term_width()
  187. if columns: max_width = columns
  188. fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
  189. fmt.format_option_strings = _format_option_string
  190. kw = {
  191. 'version' : __version__,
  192. 'formatter' : fmt,
  193. 'usage' : '%prog [options] url [url...]',
  194. 'conflict_handler' : 'resolve',
  195. }
  196. parser = optparse.OptionParser(**kw)
  197. # option groups
  198. general = optparse.OptionGroup(parser, 'General Options')
  199. selection = optparse.OptionGroup(parser, 'Video Selection')
  200. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  201. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  202. subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
  203. downloader = optparse.OptionGroup(parser, 'Download Options')
  204. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  205. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  206. workarounds = optparse.OptionGroup(parser, 'Workarounds')
  207. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  208. general.add_option('-h', '--help',
  209. action='help', help='print this help text and exit')
  210. general.add_option('-v', '--version',
  211. action='version', help='print program version and exit')
  212. general.add_option('-U', '--update',
  213. action='store_true', dest='update_self', help='update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
  214. general.add_option('-i', '--ignore-errors',
  215. action='store_true', dest='ignoreerrors', help='continue on download errors, for example to skip unavailable videos in a playlist', default=False)
  216. general.add_option('--abort-on-error',
  217. action='store_false', dest='ignoreerrors',
  218. help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')
  219. general.add_option('--dump-user-agent',
  220. action='store_true', dest='dump_user_agent',
  221. help='display the current browser identification', default=False)
  222. general.add_option('--list-extractors',
  223. action='store_true', dest='list_extractors',
  224. help='List all supported extractors and the URLs they would handle', default=False)
  225. general.add_option('--extractor-descriptions',
  226. action='store_true', dest='list_extractor_descriptions',
  227. help='Output descriptions of all supported extractors', default=False)
  228. general.add_option(
  229. '--proxy', dest='proxy', default=None, metavar='URL',
  230. help='Use the specified HTTP/HTTPS proxy. Pass in an empty string (--proxy "") for direct connection')
  231. general.add_option(
  232. '--socket-timeout', dest='socket_timeout',
  233. type=float, default=None, help=u'Time to wait before giving up, in seconds')
  234. general.add_option(
  235. '--default-search',
  236. dest='default_search', metavar='PREFIX',
  237. 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.')
  238. general.add_option(
  239. '--ignore-config',
  240. action='store_true',
  241. help='Do not read configuration files. When given in the global configuration file /etc/youtube-dl.conf: do not read the user configuration in ~/.config/youtube-dl.conf (%APPDATA%/youtube-dl/config.txt on Windows)')
  242. selection.add_option(
  243. '--playlist-start',
  244. dest='playliststart', metavar='NUMBER', default=1, type=int,
  245. help='playlist video to start at (default is %default)')
  246. selection.add_option(
  247. '--playlist-end',
  248. dest='playlistend', metavar='NUMBER', default=None, type=int,
  249. help='playlist video to end at (default is last)')
  250. selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
  251. selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
  252. selection.add_option('--max-downloads', metavar='NUMBER',
  253. dest='max_downloads', type=int, default=None,
  254. help='Abort after downloading NUMBER files')
  255. selection.add_option('--min-filesize', metavar='SIZE', dest='min_filesize', help="Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)", default=None)
  256. selection.add_option('--max-filesize', metavar='SIZE', dest='max_filesize', help="Do not download any videos larger than SIZE (e.g. 50k or 44.6m)", default=None)
  257. selection.add_option('--date', metavar='DATE', dest='date', help='download only videos uploaded in this date', default=None)
  258. selection.add_option(
  259. '--datebefore', metavar='DATE', dest='datebefore', default=None,
  260. help='download only videos uploaded on or before this date (i.e. inclusive)')
  261. selection.add_option(
  262. '--dateafter', metavar='DATE', dest='dateafter', default=None,
  263. help='download only videos uploaded on or after this date (i.e. inclusive)')
  264. selection.add_option(
  265. '--min-views', metavar='COUNT', dest='min_views',
  266. default=None, type=int,
  267. help="Do not download any videos with less than COUNT views",)
  268. selection.add_option(
  269. '--max-views', metavar='COUNT', dest='max_views',
  270. default=None, type=int,
  271. help="Do not download any videos with more than COUNT views",)
  272. selection.add_option('--no-playlist', action='store_true', dest='noplaylist', help='download only the currently playing video', default=False)
  273. selection.add_option('--age-limit', metavar='YEARS', dest='age_limit',
  274. help='download only videos suitable for the given age',
  275. default=None, type=int)
  276. selection.add_option('--download-archive', metavar='FILE',
  277. dest='download_archive',
  278. help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
  279. selection.add_option(
  280. '--include-ads', dest='include_ads',
  281. action='store_true',
  282. help='Download advertisements as well (experimental)')
  283. selection.add_option(
  284. '--youtube-include-dash-manifest', action='store_true',
  285. dest='youtube_include_dash_manifest', default=False,
  286. help='Try to download the DASH manifest on YouTube videos (experimental)')
  287. authentication.add_option('-u', '--username',
  288. dest='username', metavar='USERNAME', help='account username')
  289. authentication.add_option('-p', '--password',
  290. dest='password', metavar='PASSWORD', help='account password')
  291. authentication.add_option('-n', '--netrc',
  292. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  293. authentication.add_option('--video-password',
  294. dest='videopassword', metavar='PASSWORD', help='video password (vimeo, smotri)')
  295. video_format.add_option('-f', '--format',
  296. action='store', dest='format', metavar='FORMAT', default=None,
  297. help='video format code, specify the order of preference using slashes: "-f 22/17/18". "-f mp4" and "-f flv" are also supported. You can also use the special names "best", "bestvideo", "bestaudio", "worst", "worstvideo" and "worstaudio". By default, youtube-dl will pick the best quality.')
  298. video_format.add_option('--all-formats',
  299. action='store_const', dest='format', help='download all available video formats', const='all')
  300. video_format.add_option('--prefer-free-formats',
  301. action='store_true', dest='prefer_free_formats', default=False, help='prefer free video formats unless a specific one is requested')
  302. video_format.add_option('--max-quality',
  303. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  304. video_format.add_option('-F', '--list-formats',
  305. action='store_true', dest='listformats', help='list all available formats')
  306. subtitles.add_option('--write-sub', '--write-srt',
  307. action='store_true', dest='writesubtitles',
  308. help='write subtitle file', default=False)
  309. subtitles.add_option('--write-auto-sub', '--write-automatic-sub',
  310. action='store_true', dest='writeautomaticsub',
  311. help='write automatic subtitle file (youtube only)', default=False)
  312. subtitles.add_option('--all-subs',
  313. action='store_true', dest='allsubtitles',
  314. help='downloads all the available subtitles of the video', default=False)
  315. subtitles.add_option('--list-subs',
  316. action='store_true', dest='listsubtitles',
  317. help='lists all available subtitles for the video', default=False)
  318. subtitles.add_option('--sub-format',
  319. action='store', dest='subtitlesformat', metavar='FORMAT',
  320. help='subtitle format (default=srt) ([sbv/vtt] youtube only)', default='srt')
  321. subtitles.add_option('--sub-lang', '--sub-langs', '--srt-lang',
  322. action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
  323. default=[], callback=_comma_separated_values_options_callback,
  324. help='languages of the subtitles to download (optional) separated by commas, use IETF language tags like \'en,pt\'')
  325. downloader.add_option('-r', '--rate-limit',
  326. dest='ratelimit', metavar='LIMIT', help='maximum download rate in bytes per second (e.g. 50K or 4.2M)')
  327. downloader.add_option('-R', '--retries',
  328. dest='retries', metavar='RETRIES', help='number of retries (default is %default)', default=10)
  329. downloader.add_option('--buffer-size',
  330. dest='buffersize', metavar='SIZE', help='size of download buffer (e.g. 1024 or 16K) (default is %default)', default="1024")
  331. downloader.add_option('--no-resize-buffer',
  332. action='store_true', dest='noresizebuffer',
  333. help='do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.', default=False)
  334. downloader.add_option('--test', action='store_true', dest='test', default=False, help=optparse.SUPPRESS_HELP)
  335. workarounds.add_option(
  336. '--encoding', dest='encoding', metavar='ENCODING',
  337. help='Force the specified encoding (experimental)')
  338. workarounds.add_option(
  339. '--no-check-certificate', action='store_true',
  340. dest='no_check_certificate', default=False,
  341. help='Suppress HTTPS certificate validation.')
  342. workarounds.add_option(
  343. '--prefer-insecure', '--prefer-unsecure', action='store_true', dest='prefer_insecure',
  344. help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
  345. workarounds.add_option(
  346. '--user-agent', metavar='UA',
  347. dest='user_agent', help='specify a custom user agent')
  348. workarounds.add_option(
  349. '--referer', metavar='REF',
  350. dest='referer', default=None,
  351. help='specify a custom referer, use if the video access is restricted to one domain',
  352. )
  353. workarounds.add_option(
  354. '--add-header', metavar='FIELD:VALUE',
  355. dest='headers', action='append',
  356. help='specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
  357. )
  358. workarounds.add_option(
  359. '--bidi-workaround', dest='bidi_workaround', action='store_true',
  360. help=u'Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
  361. verbosity.add_option('-q', '--quiet',
  362. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  363. verbosity.add_option(
  364. '--no-warnings',
  365. dest='no_warnings', action='store_true', default=False,
  366. help='Ignore warnings')
  367. verbosity.add_option('-s', '--simulate',
  368. action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
  369. verbosity.add_option('--skip-download',
  370. action='store_true', dest='skip_download', help='do not download the video', default=False)
  371. verbosity.add_option('-g', '--get-url',
  372. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  373. verbosity.add_option('-e', '--get-title',
  374. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  375. verbosity.add_option('--get-id',
  376. action='store_true', dest='getid', help='simulate, quiet but print id', default=False)
  377. verbosity.add_option('--get-thumbnail',
  378. action='store_true', dest='getthumbnail',
  379. help='simulate, quiet but print thumbnail URL', default=False)
  380. verbosity.add_option('--get-description',
  381. action='store_true', dest='getdescription',
  382. help='simulate, quiet but print video description', default=False)
  383. verbosity.add_option('--get-duration',
  384. action='store_true', dest='getduration',
  385. help='simulate, quiet but print video length', default=False)
  386. verbosity.add_option('--get-filename',
  387. action='store_true', dest='getfilename',
  388. help='simulate, quiet but print output filename', default=False)
  389. verbosity.add_option('--get-format',
  390. action='store_true', dest='getformat',
  391. help='simulate, quiet but print output format', default=False)
  392. verbosity.add_option('-j', '--dump-json',
  393. action='store_true', dest='dumpjson',
  394. help='simulate, quiet but print JSON information. See --output for a description of available keys.', default=False)
  395. verbosity.add_option('--newline',
  396. action='store_true', dest='progress_with_newline', help='output progress bar as new lines', default=False)
  397. verbosity.add_option('--no-progress',
  398. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  399. verbosity.add_option('--console-title',
  400. action='store_true', dest='consoletitle',
  401. help='display progress in console titlebar', default=False)
  402. verbosity.add_option('-v', '--verbose',
  403. action='store_true', dest='verbose', help='print various debugging information', default=False)
  404. verbosity.add_option('--dump-intermediate-pages',
  405. action='store_true', dest='dump_intermediate_pages', default=False,
  406. help='print downloaded pages to debug problems (very verbose)')
  407. verbosity.add_option('--write-pages',
  408. action='store_true', dest='write_pages', default=False,
  409. help='Write downloaded intermediary pages to files in the current directory to debug problems')
  410. verbosity.add_option('--youtube-print-sig-code',
  411. action='store_true', dest='youtube_print_sig_code', default=False,
  412. help=optparse.SUPPRESS_HELP)
  413. verbosity.add_option('--print-traffic',
  414. dest='debug_printtraffic', action='store_true', default=False,
  415. help='Display sent and read HTTP traffic')
  416. filesystem.add_option('-a', '--batch-file',
  417. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  418. filesystem.add_option('--id',
  419. action='store_true', dest='useid', help='use only video ID in file name', default=False)
  420. filesystem.add_option('-A', '--auto-number',
  421. action='store_true', dest='autonumber',
  422. help='number downloaded files starting from 00000', default=False)
  423. filesystem.add_option('-o', '--output',
  424. dest='outtmpl', metavar='TEMPLATE',
  425. help=('output filename template. Use %(title)s to get the title, '
  426. '%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
  427. '%(autonumber)s to get an automatically incremented number, '
  428. '%(ext)s for the filename extension, '
  429. '%(format)s for the format description (like "22 - 1280x720" or "HD"), '
  430. '%(format_id)s for the unique id of the format (like Youtube\'s itags: "137"), '
  431. '%(upload_date)s for the upload date (YYYYMMDD), '
  432. '%(extractor)s for the provider (youtube, metacafe, etc), '
  433. '%(id)s for the video id, %(playlist)s for the playlist the video is in, '
  434. '%(playlist_index)s for the position in the playlist and %% for a literal percent. '
  435. '%(height)s and %(width)s for the width and height of the video format. '
  436. '%(resolution)s for a textual description of the resolution of the video format. '
  437. 'Use - to output to stdout. Can also be used to download to a different directory, '
  438. 'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
  439. filesystem.add_option('--autonumber-size',
  440. dest='autonumber_size', metavar='NUMBER',
  441. help='Specifies the number of digits in %(autonumber)s when it is present in output filename template or --auto-number option is given')
  442. filesystem.add_option('--restrict-filenames',
  443. action='store_true', dest='restrictfilenames',
  444. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames', default=False)
  445. filesystem.add_option('-t', '--title',
  446. action='store_true', dest='usetitle', help='[deprecated] use title in file name (default)', default=False)
  447. filesystem.add_option('-l', '--literal',
  448. action='store_true', dest='usetitle', help='[deprecated] alias of --title', default=False)
  449. filesystem.add_option('-w', '--no-overwrites',
  450. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  451. filesystem.add_option('-c', '--continue',
  452. action='store_true', dest='continue_dl', help='force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.', default=True)
  453. filesystem.add_option('--no-continue',
  454. action='store_false', dest='continue_dl',
  455. help='do not resume partially downloaded files (restart from beginning)')
  456. filesystem.add_option('--no-part',
  457. action='store_true', dest='nopart', help='do not use .part files', default=False)
  458. filesystem.add_option('--no-mtime',
  459. action='store_false', dest='updatetime',
  460. help='do not use the Last-modified header to set the file modification time', default=True)
  461. filesystem.add_option('--write-description',
  462. action='store_true', dest='writedescription',
  463. help='write video description to a .description file', default=False)
  464. filesystem.add_option('--write-info-json',
  465. action='store_true', dest='writeinfojson',
  466. help='write video metadata to a .info.json file', default=False)
  467. filesystem.add_option('--write-annotations',
  468. action='store_true', dest='writeannotations',
  469. help='write video annotations to a .annotation file', default=False)
  470. filesystem.add_option('--write-thumbnail',
  471. action='store_true', dest='writethumbnail',
  472. help='write thumbnail image to disk', default=False)
  473. filesystem.add_option('--load-info',
  474. dest='load_info_filename', metavar='FILE',
  475. help='json file containing the video information (created with the "--write-json" option)')
  476. filesystem.add_option('--cookies',
  477. dest='cookiefile', metavar='FILE', help='file to read cookies from and dump cookie jar in')
  478. filesystem.add_option(
  479. '--cache-dir', dest='cachedir', default=get_cachedir(), metavar='DIR',
  480. 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.')
  481. filesystem.add_option(
  482. '--no-cache-dir', action='store_const', const=None, dest='cachedir',
  483. help='Disable filesystem caching')
  484. filesystem.add_option(
  485. '--rm-cache-dir', action='store_true', dest='rm_cachedir',
  486. help='Delete all filesystem cache files')
  487. postproc.add_option('-x', '--extract-audio', action='store_true', dest='extractaudio', default=False,
  488. help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
  489. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  490. help='"best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; best by default')
  491. postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='5',
  492. help='ffmpeg/avconv audio quality specification, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default 5)')
  493. postproc.add_option('--recode-video', metavar='FORMAT', dest='recodevideo', default=None,
  494. help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv)')
  495. postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
  496. help='keeps the video file on disk after the post-processing; the video is erased by default')
  497. postproc.add_option('--no-post-overwrites', action='store_true', dest='nopostoverwrites', default=False,
  498. help='do not overwrite post-processed files; the post-processed files are overwritten by default')
  499. postproc.add_option('--embed-subs', action='store_true', dest='embedsubtitles', default=False,
  500. help='embed subtitles in the video (only for mp4 videos)')
  501. postproc.add_option('--embed-thumbnail', action='store_true', dest='embedthumbnail', default=False,
  502. help='embed thumbnail in the audio as cover art')
  503. postproc.add_option('--add-metadata', action='store_true', dest='addmetadata', default=False,
  504. help='write metadata to the video file')
  505. postproc.add_option('--xattrs', action='store_true', dest='xattrs', default=False,
  506. help='write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
  507. postproc.add_option('--prefer-avconv', action='store_false', dest='prefer_ffmpeg',
  508. help='Prefer avconv over ffmpeg for running the postprocessors (default)')
  509. postproc.add_option('--prefer-ffmpeg', action='store_true', dest='prefer_ffmpeg',
  510. help='Prefer ffmpeg over avconv for running the postprocessors')
  511. parser.add_option_group(general)
  512. parser.add_option_group(selection)
  513. parser.add_option_group(downloader)
  514. parser.add_option_group(filesystem)
  515. parser.add_option_group(verbosity)
  516. parser.add_option_group(workarounds)
  517. parser.add_option_group(video_format)
  518. parser.add_option_group(subtitles)
  519. parser.add_option_group(authentication)
  520. parser.add_option_group(postproc)
  521. if overrideArguments is not None:
  522. opts, args = parser.parse_args(overrideArguments)
  523. if opts.verbose:
  524. write_string(u'[debug] Override config: ' + repr(overrideArguments) + '\n')
  525. else:
  526. commandLineConf = sys.argv[1:]
  527. if '--ignore-config' in commandLineConf:
  528. systemConf = []
  529. userConf = []
  530. else:
  531. systemConf = _readOptions('/etc/youtube-dl.conf')
  532. if '--ignore-config' in systemConf:
  533. userConf = []
  534. else:
  535. userConf = _readUserConf()
  536. argv = systemConf + userConf + commandLineConf
  537. opts, args = parser.parse_args(argv)
  538. if opts.verbose:
  539. write_string(u'[debug] System config: ' + repr(_hide_login_info(systemConf)) + '\n')
  540. write_string(u'[debug] User config: ' + repr(_hide_login_info(userConf)) + '\n')
  541. write_string(u'[debug] Command-line args: ' + repr(_hide_login_info(commandLineConf)) + '\n')
  542. return parser, opts, args
  543. def _real_main(argv=None):
  544. # Compatibility fixes for Windows
  545. if sys.platform == 'win32':
  546. # https://github.com/rg3/youtube-dl/issues/820
  547. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
  548. setproctitle(u'youtube-dl')
  549. parser, opts, args = parseOpts(argv)
  550. # Set user agent
  551. if opts.user_agent is not None:
  552. std_headers['User-Agent'] = opts.user_agent
  553. # Set referer
  554. if opts.referer is not None:
  555. std_headers['Referer'] = opts.referer
  556. # Custom HTTP headers
  557. if opts.headers is not None:
  558. for h in opts.headers:
  559. if h.find(':', 1) < 0:
  560. parser.error(u'wrong header formatting, it should be key:value, not "%s"'%h)
  561. key, value = h.split(':', 2)
  562. if opts.verbose:
  563. write_string(u'[debug] Adding header from command line option %s:%s\n'%(key, value))
  564. std_headers[key] = value
  565. # Dump user agent
  566. if opts.dump_user_agent:
  567. compat_print(std_headers['User-Agent'])
  568. sys.exit(0)
  569. # Batch file verification
  570. batch_urls = []
  571. if opts.batchfile is not None:
  572. try:
  573. if opts.batchfile == '-':
  574. batchfd = sys.stdin
  575. else:
  576. batchfd = io.open(opts.batchfile, 'r', encoding='utf-8', errors='ignore')
  577. batch_urls = read_batch_urls(batchfd)
  578. if opts.verbose:
  579. write_string(u'[debug] Batch file urls: ' + repr(batch_urls) + u'\n')
  580. except IOError:
  581. sys.exit(u'ERROR: batch file could not be read')
  582. all_urls = batch_urls + args
  583. all_urls = [url.strip() for url in all_urls]
  584. _enc = preferredencoding()
  585. all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
  586. extractors = gen_extractors()
  587. if opts.list_extractors:
  588. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  589. compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  590. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  591. for mu in matchedUrls:
  592. compat_print(u' ' + mu)
  593. sys.exit(0)
  594. if opts.list_extractor_descriptions:
  595. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  596. if not ie._WORKING:
  597. continue
  598. desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
  599. if desc is False:
  600. continue
  601. if hasattr(ie, 'SEARCH_KEY'):
  602. _SEARCHES = (u'cute kittens', u'slithering pythons', u'falling cat', u'angry poodle', u'purple fish', u'running tortoise', u'sleeping bunny')
  603. _COUNTS = (u'', u'5', u'10', u'all')
  604. desc += u' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
  605. compat_print(desc)
  606. sys.exit(0)
  607. # Conflicting, missing and erroneous options
  608. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  609. parser.error(u'using .netrc conflicts with giving username/password')
  610. if opts.password is not None and opts.username is None:
  611. parser.error(u'account username missing\n')
  612. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  613. parser.error(u'using output template conflicts with using title, video ID or auto number')
  614. if opts.usetitle and opts.useid:
  615. parser.error(u'using title conflicts with using video ID')
  616. if opts.username is not None and opts.password is None:
  617. opts.password = compat_getpass(u'Type account password and press [Return]: ')
  618. if opts.ratelimit is not None:
  619. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  620. if numeric_limit is None:
  621. parser.error(u'invalid rate limit specified')
  622. opts.ratelimit = numeric_limit
  623. if opts.min_filesize is not None:
  624. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  625. if numeric_limit is None:
  626. parser.error(u'invalid min_filesize specified')
  627. opts.min_filesize = numeric_limit
  628. if opts.max_filesize is not None:
  629. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  630. if numeric_limit is None:
  631. parser.error(u'invalid max_filesize specified')
  632. opts.max_filesize = numeric_limit
  633. if opts.retries is not None:
  634. try:
  635. opts.retries = int(opts.retries)
  636. except (TypeError, ValueError):
  637. parser.error(u'invalid retry count specified')
  638. if opts.buffersize is not None:
  639. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  640. if numeric_buffersize is None:
  641. parser.error(u'invalid buffer size specified')
  642. opts.buffersize = numeric_buffersize
  643. if opts.playliststart <= 0:
  644. raise ValueError(u'Playlist start must be positive')
  645. if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
  646. raise ValueError(u'Playlist end must be greater than playlist start')
  647. if opts.extractaudio:
  648. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  649. parser.error(u'invalid audio format specified')
  650. if opts.audioquality:
  651. opts.audioquality = opts.audioquality.strip('k').strip('K')
  652. if not opts.audioquality.isdigit():
  653. parser.error(u'invalid audio quality specified')
  654. if opts.recodevideo is not None:
  655. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
  656. parser.error(u'invalid video recode format specified')
  657. if opts.date is not None:
  658. date = DateRange.day(opts.date)
  659. else:
  660. date = DateRange(opts.dateafter, opts.datebefore)
  661. if opts.default_search not in ('auto', 'auto_warning', 'error', 'fixup_error', None) and ':' not in opts.default_search:
  662. parser.error(u'--default-search invalid; did you forget a colon (:) at the end?')
  663. # Do not download videos when there are audio-only formats
  664. if opts.extractaudio and not opts.keepvideo and opts.format is None:
  665. opts.format = 'bestaudio/best'
  666. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  667. # this was the old behaviour if only --all-sub was given.
  668. if opts.allsubtitles and (opts.writeautomaticsub == False):
  669. opts.writesubtitles = True
  670. if sys.version_info < (3,):
  671. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  672. if opts.outtmpl is not None:
  673. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  674. outtmpl =((opts.outtmpl is not None and opts.outtmpl)
  675. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  676. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  677. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  678. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  679. or (opts.useid and u'%(id)s.%(ext)s')
  680. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  681. or DEFAULT_OUTTMPL)
  682. if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
  683. parser.error(u'Cannot download a video and extract audio into the same'
  684. u' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
  685. u' template'.format(outtmpl))
  686. any_printing = opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat or opts.getduration or opts.dumpjson
  687. download_archive_fn = os.path.expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
  688. ydl_opts = {
  689. 'usenetrc': opts.usenetrc,
  690. 'username': opts.username,
  691. 'password': opts.password,
  692. 'videopassword': opts.videopassword,
  693. 'quiet': (opts.quiet or any_printing),
  694. 'no_warnings': opts.no_warnings,
  695. 'forceurl': opts.geturl,
  696. 'forcetitle': opts.gettitle,
  697. 'forceid': opts.getid,
  698. 'forcethumbnail': opts.getthumbnail,
  699. 'forcedescription': opts.getdescription,
  700. 'forceduration': opts.getduration,
  701. 'forcefilename': opts.getfilename,
  702. 'forceformat': opts.getformat,
  703. 'forcejson': opts.dumpjson,
  704. 'simulate': opts.simulate,
  705. 'skip_download': (opts.skip_download or opts.simulate or any_printing),
  706. 'format': opts.format,
  707. 'format_limit': opts.format_limit,
  708. 'listformats': opts.listformats,
  709. 'outtmpl': outtmpl,
  710. 'autonumber_size': opts.autonumber_size,
  711. 'restrictfilenames': opts.restrictfilenames,
  712. 'ignoreerrors': opts.ignoreerrors,
  713. 'ratelimit': opts.ratelimit,
  714. 'nooverwrites': opts.nooverwrites,
  715. 'retries': opts.retries,
  716. 'buffersize': opts.buffersize,
  717. 'noresizebuffer': opts.noresizebuffer,
  718. 'continuedl': opts.continue_dl,
  719. 'noprogress': opts.noprogress,
  720. 'progress_with_newline': opts.progress_with_newline,
  721. 'playliststart': opts.playliststart,
  722. 'playlistend': opts.playlistend,
  723. 'noplaylist': opts.noplaylist,
  724. 'logtostderr': opts.outtmpl == '-',
  725. 'consoletitle': opts.consoletitle,
  726. 'nopart': opts.nopart,
  727. 'updatetime': opts.updatetime,
  728. 'writedescription': opts.writedescription,
  729. 'writeannotations': opts.writeannotations,
  730. 'writeinfojson': opts.writeinfojson,
  731. 'writethumbnail': opts.writethumbnail,
  732. 'writesubtitles': opts.writesubtitles,
  733. 'writeautomaticsub': opts.writeautomaticsub,
  734. 'allsubtitles': opts.allsubtitles,
  735. 'listsubtitles': opts.listsubtitles,
  736. 'subtitlesformat': opts.subtitlesformat,
  737. 'subtitleslangs': opts.subtitleslangs,
  738. 'matchtitle': decodeOption(opts.matchtitle),
  739. 'rejecttitle': decodeOption(opts.rejecttitle),
  740. 'max_downloads': opts.max_downloads,
  741. 'prefer_free_formats': opts.prefer_free_formats,
  742. 'verbose': opts.verbose,
  743. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  744. 'write_pages': opts.write_pages,
  745. 'test': opts.test,
  746. 'keepvideo': opts.keepvideo,
  747. 'min_filesize': opts.min_filesize,
  748. 'max_filesize': opts.max_filesize,
  749. 'min_views': opts.min_views,
  750. 'max_views': opts.max_views,
  751. 'daterange': date,
  752. 'cachedir': opts.cachedir,
  753. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  754. 'age_limit': opts.age_limit,
  755. 'download_archive': download_archive_fn,
  756. 'cookiefile': opts.cookiefile,
  757. 'nocheckcertificate': opts.no_check_certificate,
  758. 'prefer_insecure': opts.prefer_insecure,
  759. 'proxy': opts.proxy,
  760. 'socket_timeout': opts.socket_timeout,
  761. 'bidi_workaround': opts.bidi_workaround,
  762. 'debug_printtraffic': opts.debug_printtraffic,
  763. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  764. 'include_ads': opts.include_ads,
  765. 'default_search': opts.default_search,
  766. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  767. 'encoding': opts.encoding,
  768. }
  769. with YoutubeDL(ydl_opts) as ydl:
  770. ydl.print_debug_header()
  771. ydl.add_default_info_extractors()
  772. # PostProcessors
  773. # Add the metadata pp first, the other pps will copy it
  774. if opts.addmetadata:
  775. ydl.add_post_processor(FFmpegMetadataPP())
  776. if opts.extractaudio:
  777. ydl.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, nopostoverwrites=opts.nopostoverwrites))
  778. if opts.recodevideo:
  779. ydl.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
  780. if opts.embedsubtitles:
  781. ydl.add_post_processor(FFmpegEmbedSubtitlePP(subtitlesformat=opts.subtitlesformat))
  782. if opts.xattrs:
  783. ydl.add_post_processor(XAttrMetadataPP())
  784. if opts.embedthumbnail:
  785. if not opts.addmetadata:
  786. ydl.add_post_processor(FFmpegAudioFixPP())
  787. ydl.add_post_processor(AtomicParsleyPP())
  788. # Update version
  789. if opts.update_self:
  790. update_self(ydl.to_screen, opts.verbose)
  791. # Remove cache dir
  792. if opts.rm_cachedir:
  793. if opts.cachedir is None:
  794. ydl.to_screen(u'No cache dir specified (Did you combine --no-cache-dir and --rm-cache-dir?)')
  795. else:
  796. if ('.cache' not in opts.cachedir) or ('youtube-dl' not in opts.cachedir):
  797. ydl.to_screen(u'Not removing directory %s - this does not look like a cache dir')
  798. retcode = 141
  799. else:
  800. ydl.to_screen(
  801. u'Removing cache dir %s .' % opts.cachedir,
  802. skip_eol=True)
  803. if os.path.exists(opts.cachedir):
  804. ydl.to_screen(u'.', skip_eol=True)
  805. shutil.rmtree(opts.cachedir)
  806. ydl.to_screen(u'.')
  807. # Maybe do nothing
  808. if (len(all_urls) < 1) and (opts.load_info_filename is None):
  809. if not (opts.update_self or opts.rm_cachedir):
  810. parser.error(u'you must provide at least one URL')
  811. else:
  812. sys.exit()
  813. try:
  814. if opts.load_info_filename is not None:
  815. retcode = ydl.download_with_info_file(opts.load_info_filename)
  816. else:
  817. retcode = ydl.download(all_urls)
  818. except MaxDownloadsReached:
  819. ydl.to_screen(u'--max-download limit reached, aborting.')
  820. retcode = 101
  821. sys.exit(retcode)
  822. def main(argv=None):
  823. try:
  824. _real_main(argv)
  825. except DownloadError:
  826. sys.exit(1)
  827. except SameFileError:
  828. sys.exit(u'ERROR: fixed output name but more than one file to download')
  829. except KeyboardInterrupt:
  830. sys.exit(u'\nERROR: Interrupted by user')