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.

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