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.

699 lines
34 KiB

13 years ago
12 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. )
  34. __license__ = 'Public Domain'
  35. import codecs
  36. import getpass
  37. import optparse
  38. import os
  39. import random
  40. import re
  41. import shlex
  42. import socket
  43. import subprocess
  44. import sys
  45. import warnings
  46. import platform
  47. from .utils import *
  48. from .update import update_self
  49. from .version import __version__
  50. from .FileDownloader import *
  51. from .extractor import gen_extractors
  52. from .YoutubeDL import YoutubeDL
  53. from .PostProcessor import *
  54. def parseOpts(overrideArguments=None):
  55. def _readOptions(filename_bytes):
  56. try:
  57. optionf = open(filename_bytes)
  58. except IOError:
  59. return [] # silently skip if file is not present
  60. try:
  61. res = []
  62. for l in optionf:
  63. res += shlex.split(l, comments=True)
  64. finally:
  65. optionf.close()
  66. return res
  67. def _format_option_string(option):
  68. ''' ('-o', '--option') -> -o, --format METAVAR'''
  69. opts = []
  70. if option._short_opts:
  71. opts.append(option._short_opts[0])
  72. if option._long_opts:
  73. opts.append(option._long_opts[0])
  74. if len(opts) > 1:
  75. opts.insert(1, ', ')
  76. if option.takes_value(): opts.append(' %s' % option.metavar)
  77. return "".join(opts)
  78. def _comma_separated_values_options_callback(option, opt_str, value, parser):
  79. setattr(parser.values, option.dest, value.split(','))
  80. def _find_term_columns():
  81. columns = os.environ.get('COLUMNS', None)
  82. if columns:
  83. return int(columns)
  84. try:
  85. sp = subprocess.Popen(['stty', 'size'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  86. out,err = sp.communicate()
  87. return int(out.split()[1])
  88. except:
  89. pass
  90. return None
  91. def _hide_login_info(opts):
  92. opts = list(opts)
  93. for private_opt in ['-p', '--password', '-u', '--username']:
  94. try:
  95. i = opts.index(private_opt)
  96. opts[i+1] = '<PRIVATE>'
  97. except ValueError:
  98. pass
  99. return opts
  100. max_width = 80
  101. max_help_position = 80
  102. # No need to wrap help messages if we're on a wide console
  103. columns = _find_term_columns()
  104. if columns: max_width = columns
  105. fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
  106. fmt.format_option_strings = _format_option_string
  107. kw = {
  108. 'version' : __version__,
  109. 'formatter' : fmt,
  110. 'usage' : '%prog [options] url [url...]',
  111. 'conflict_handler' : 'resolve',
  112. }
  113. parser = optparse.OptionParser(**kw)
  114. # option groups
  115. general = optparse.OptionGroup(parser, 'General Options')
  116. selection = optparse.OptionGroup(parser, 'Video Selection')
  117. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  118. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  119. subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
  120. downloader = optparse.OptionGroup(parser, 'Download Options')
  121. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  122. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  123. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  124. general.add_option('-h', '--help',
  125. action='help', help='print this help text and exit')
  126. general.add_option('-v', '--version',
  127. action='version', help='print program version and exit')
  128. general.add_option('-U', '--update',
  129. 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)')
  130. general.add_option('-i', '--ignore-errors',
  131. action='store_true', dest='ignoreerrors', help='continue on download errors, for example to to skip unavailable videos in a playlist', default=False)
  132. general.add_option('--dump-user-agent',
  133. action='store_true', dest='dump_user_agent',
  134. help='display the current browser identification', default=False)
  135. general.add_option('--user-agent',
  136. dest='user_agent', help='specify a custom user agent', metavar='UA')
  137. general.add_option('--referer',
  138. dest='referer', help='specify a custom referer, use if the video access is restricted to one domain',
  139. metavar='REF', default=None)
  140. general.add_option('--list-extractors',
  141. action='store_true', dest='list_extractors',
  142. help='List all supported extractors and the URLs they would handle', default=False)
  143. general.add_option('--extractor-descriptions',
  144. action='store_true', dest='list_extractor_descriptions',
  145. help='Output descriptions of all supported extractors', default=False)
  146. general.add_option('--proxy', dest='proxy', default=None, help='Use the specified HTTP/HTTPS proxy', metavar='URL')
  147. general.add_option('--no-check-certificate', action='store_true', dest='no_check_certificate', default=False, help='Suppress HTTPS certificate validation.')
  148. general.add_option(
  149. '--cache-dir', dest='cachedir', default=get_cachedir(),
  150. help='Location in the filesystem where youtube-dl can store downloaded information permanently. By default $XDG_CACHE_HOME/youtube-dl or ~/.cache/youtube-dl .')
  151. general.add_option(
  152. '--no-cache-dir', action='store_const', const=None, dest='cachedir',
  153. help='Disable filesystem caching')
  154. selection.add_option('--playlist-start',
  155. dest='playliststart', metavar='NUMBER', help='playlist video to start at (default is %default)', default=1)
  156. selection.add_option('--playlist-end',
  157. dest='playlistend', metavar='NUMBER', help='playlist video to end at (default is last)', default=-1)
  158. selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
  159. selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
  160. selection.add_option('--max-downloads', metavar='NUMBER', dest='max_downloads', help='Abort after downloading NUMBER files', default=None)
  161. 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)
  162. 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)
  163. selection.add_option('--date', metavar='DATE', dest='date', help='download only videos uploaded in this date', default=None)
  164. selection.add_option('--datebefore', metavar='DATE', dest='datebefore', help='download only videos uploaded before this date', default=None)
  165. selection.add_option('--dateafter', metavar='DATE', dest='dateafter', help='download only videos uploaded after this date', default=None)
  166. selection.add_option('--no-playlist', action='store_true', dest='noplaylist', help='download only the currently playing video', default=False)
  167. authentication.add_option('-u', '--username',
  168. dest='username', metavar='USERNAME', help='account username')
  169. authentication.add_option('-p', '--password',
  170. dest='password', metavar='PASSWORD', help='account password')
  171. authentication.add_option('-n', '--netrc',
  172. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  173. authentication.add_option('--video-password',
  174. dest='videopassword', metavar='PASSWORD', help='video password (vimeo only)')
  175. video_format.add_option('-f', '--format',
  176. action='store', dest='format', metavar='FORMAT',
  177. help='video format code, specifiy the order of preference using slashes: "-f 22/17/18". "-f mp4" and "-f flv" are also supported')
  178. video_format.add_option('--all-formats',
  179. action='store_const', dest='format', help='download all available video formats', const='all')
  180. video_format.add_option('--prefer-free-formats',
  181. action='store_true', dest='prefer_free_formats', default=False, help='prefer free video formats unless a specific one is requested')
  182. video_format.add_option('--max-quality',
  183. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  184. video_format.add_option('-F', '--list-formats',
  185. action='store_true', dest='listformats', help='list all available formats (currently youtube only)')
  186. subtitles.add_option('--write-sub', '--write-srt',
  187. action='store_true', dest='writesubtitles',
  188. help='write subtitle file', default=False)
  189. subtitles.add_option('--write-auto-sub', '--write-automatic-sub',
  190. action='store_true', dest='writeautomaticsub',
  191. help='write automatic subtitle file (youtube only)', default=False)
  192. subtitles.add_option('--all-subs',
  193. action='store_true', dest='allsubtitles',
  194. help='downloads all the available subtitles of the video', default=False)
  195. subtitles.add_option('--list-subs',
  196. action='store_true', dest='listsubtitles',
  197. help='lists all available subtitles for the video', default=False)
  198. subtitles.add_option('--sub-format',
  199. action='store', dest='subtitlesformat', metavar='FORMAT',
  200. help='subtitle format (default=srt) ([sbv/vtt] youtube only)', default='srt')
  201. subtitles.add_option('--sub-lang', '--sub-langs', '--srt-lang',
  202. action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
  203. default=[], callback=_comma_separated_values_options_callback,
  204. help='languages of the subtitles to download (optional) separated by commas, use IETF language tags like \'en,pt\'')
  205. downloader.add_option('-r', '--rate-limit',
  206. dest='ratelimit', metavar='LIMIT', help='maximum download rate (e.g. 50k or 44.6m)')
  207. downloader.add_option('-R', '--retries',
  208. dest='retries', metavar='RETRIES', help='number of retries (default is %default)', default=10)
  209. downloader.add_option('--buffer-size',
  210. dest='buffersize', metavar='SIZE', help='size of download buffer (e.g. 1024 or 16k) (default is %default)', default="1024")
  211. downloader.add_option('--no-resize-buffer',
  212. action='store_true', dest='noresizebuffer',
  213. help='do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.', default=False)
  214. downloader.add_option('--test', action='store_true', dest='test', default=False, help=optparse.SUPPRESS_HELP)
  215. verbosity.add_option('-q', '--quiet',
  216. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  217. verbosity.add_option('-s', '--simulate',
  218. action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
  219. verbosity.add_option('--skip-download',
  220. action='store_true', dest='skip_download', help='do not download the video', default=False)
  221. verbosity.add_option('-g', '--get-url',
  222. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  223. verbosity.add_option('-e', '--get-title',
  224. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  225. verbosity.add_option('--get-id',
  226. action='store_true', dest='getid', help='simulate, quiet but print id', default=False)
  227. verbosity.add_option('--get-thumbnail',
  228. action='store_true', dest='getthumbnail',
  229. help='simulate, quiet but print thumbnail URL', default=False)
  230. verbosity.add_option('--get-description',
  231. action='store_true', dest='getdescription',
  232. help='simulate, quiet but print video description', default=False)
  233. verbosity.add_option('--get-filename',
  234. action='store_true', dest='getfilename',
  235. help='simulate, quiet but print output filename', default=False)
  236. verbosity.add_option('--get-format',
  237. action='store_true', dest='getformat',
  238. help='simulate, quiet but print output format', default=False)
  239. verbosity.add_option('--newline',
  240. action='store_true', dest='progress_with_newline', help='output progress bar as new lines', default=False)
  241. verbosity.add_option('--no-progress',
  242. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  243. verbosity.add_option('--console-title',
  244. action='store_true', dest='consoletitle',
  245. help='display progress in console titlebar', default=False)
  246. verbosity.add_option('-v', '--verbose',
  247. action='store_true', dest='verbose', help='print various debugging information', default=False)
  248. verbosity.add_option('--dump-intermediate-pages',
  249. action='store_true', dest='dump_intermediate_pages', default=False,
  250. help='print downloaded pages to debug problems(very verbose)')
  251. verbosity.add_option('--youtube-print-sig-code',
  252. action='store_true', dest='youtube_print_sig_code', default=False,
  253. help=optparse.SUPPRESS_HELP)
  254. filesystem.add_option('-t', '--title',
  255. action='store_true', dest='usetitle', help='use title in file name (default)', default=False)
  256. filesystem.add_option('--id',
  257. action='store_true', dest='useid', help='use only video ID in file name', default=False)
  258. filesystem.add_option('-l', '--literal',
  259. action='store_true', dest='usetitle', help='[deprecated] alias of --title', default=False)
  260. filesystem.add_option('-A', '--auto-number',
  261. action='store_true', dest='autonumber',
  262. help='number downloaded files starting from 00000', default=False)
  263. filesystem.add_option('-o', '--output',
  264. dest='outtmpl', metavar='TEMPLATE',
  265. help=('output filename template. Use %(title)s to get the title, '
  266. '%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
  267. '%(autonumber)s to get an automatically incremented number, '
  268. '%(ext)s for the filename extension, %(upload_date)s for the upload date (YYYYMMDD), '
  269. '%(extractor)s for the provider (youtube, metacafe, etc), '
  270. '%(id)s for the video id , %(playlist)s for the playlist the video is in, '
  271. '%(playlist_index)s for the position in the playlist and %% for a literal percent. '
  272. 'Use - to output to stdout. Can also be used to download to a different directory, '
  273. 'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
  274. filesystem.add_option('--autonumber-size',
  275. dest='autonumber_size', metavar='NUMBER',
  276. help='Specifies the number of digits in %(autonumber)s when it is present in output filename template or --autonumber option is given')
  277. filesystem.add_option('--restrict-filenames',
  278. action='store_true', dest='restrictfilenames',
  279. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames', default=False)
  280. filesystem.add_option('-a', '--batch-file',
  281. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  282. filesystem.add_option('-w', '--no-overwrites',
  283. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  284. filesystem.add_option('-c', '--continue',
  285. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=True)
  286. filesystem.add_option('--no-continue',
  287. action='store_false', dest='continue_dl',
  288. help='do not resume partially downloaded files (restart from beginning)')
  289. filesystem.add_option('--cookies',
  290. dest='cookiefile', metavar='FILE', help='file to read cookies from and dump cookie jar in')
  291. filesystem.add_option('--no-part',
  292. action='store_true', dest='nopart', help='do not use .part files', default=False)
  293. filesystem.add_option('--no-mtime',
  294. action='store_false', dest='updatetime',
  295. help='do not use the Last-modified header to set the file modification time', default=True)
  296. filesystem.add_option('--write-description',
  297. action='store_true', dest='writedescription',
  298. help='write video description to a .description file', default=False)
  299. filesystem.add_option('--write-info-json',
  300. action='store_true', dest='writeinfojson',
  301. help='write video metadata to a .info.json file', default=False)
  302. filesystem.add_option('--write-thumbnail',
  303. action='store_true', dest='writethumbnail',
  304. help='write thumbnail image to disk', default=False)
  305. postproc.add_option('-x', '--extract-audio', action='store_true', dest='extractaudio', default=False,
  306. help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
  307. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  308. help='"best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; best by default')
  309. postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='5',
  310. 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)')
  311. postproc.add_option('--recode-video', metavar='FORMAT', dest='recodevideo', default=None,
  312. help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm)')
  313. postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
  314. help='keeps the video file on disk after the post-processing; the video is erased by default')
  315. postproc.add_option('--no-post-overwrites', action='store_true', dest='nopostoverwrites', default=False,
  316. help='do not overwrite post-processed files; the post-processed files are overwritten by default')
  317. postproc.add_option('--embed-subs', action='store_true', dest='embedsubtitles', default=False,
  318. help='embed subtitles in the video (only for mp4 videos)')
  319. parser.add_option_group(general)
  320. parser.add_option_group(selection)
  321. parser.add_option_group(downloader)
  322. parser.add_option_group(filesystem)
  323. parser.add_option_group(verbosity)
  324. parser.add_option_group(video_format)
  325. parser.add_option_group(subtitles)
  326. parser.add_option_group(authentication)
  327. parser.add_option_group(postproc)
  328. if overrideArguments is not None:
  329. opts, args = parser.parse_args(overrideArguments)
  330. if opts.verbose:
  331. write_string(u'[debug] Override config: ' + repr(overrideArguments) + '\n')
  332. else:
  333. xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
  334. if xdg_config_home:
  335. userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')
  336. if not os.path.isfile(userConfFile):
  337. userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
  338. else:
  339. userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl', 'config')
  340. if not os.path.isfile(userConfFile):
  341. userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
  342. systemConf = _readOptions('/etc/youtube-dl.conf')
  343. userConf = _readOptions(userConfFile)
  344. commandLineConf = sys.argv[1:]
  345. argv = systemConf + userConf + commandLineConf
  346. opts, args = parser.parse_args(argv)
  347. if opts.verbose:
  348. write_string(u'[debug] System config: ' + repr(_hide_login_info(systemConf)) + '\n')
  349. write_string(u'[debug] User config: ' + repr(_hide_login_info(userConf)) + '\n')
  350. write_string(u'[debug] Command-line args: ' + repr(_hide_login_info(commandLineConf)) + '\n')
  351. return parser, opts, args
  352. def _real_main(argv=None):
  353. # Compatibility fixes for Windows
  354. if sys.platform == 'win32':
  355. # https://github.com/rg3/youtube-dl/issues/820
  356. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
  357. parser, opts, args = parseOpts(argv)
  358. # Open appropriate CookieJar
  359. if opts.cookiefile is None:
  360. jar = compat_cookiejar.CookieJar()
  361. else:
  362. try:
  363. jar = compat_cookiejar.MozillaCookieJar(opts.cookiefile)
  364. if os.access(opts.cookiefile, os.R_OK):
  365. jar.load()
  366. except (IOError, OSError) as err:
  367. if opts.verbose:
  368. traceback.print_exc()
  369. write_string(u'ERROR: unable to open cookie file\n')
  370. sys.exit(101)
  371. # Set user agent
  372. if opts.user_agent is not None:
  373. std_headers['User-Agent'] = opts.user_agent
  374. # Set referer
  375. if opts.referer is not None:
  376. std_headers['Referer'] = opts.referer
  377. # Dump user agent
  378. if opts.dump_user_agent:
  379. compat_print(std_headers['User-Agent'])
  380. sys.exit(0)
  381. # Batch file verification
  382. batchurls = []
  383. if opts.batchfile is not None:
  384. try:
  385. if opts.batchfile == '-':
  386. batchfd = sys.stdin
  387. else:
  388. batchfd = open(opts.batchfile, 'r')
  389. batchurls = batchfd.readlines()
  390. batchurls = [x.strip() for x in batchurls]
  391. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  392. if opts.verbose:
  393. write_string(u'[debug] Batch file urls: ' + repr(batchurls) + u'\n')
  394. except IOError:
  395. sys.exit(u'ERROR: batch file could not be read')
  396. all_urls = batchurls + args
  397. all_urls = [url.strip() for url in all_urls]
  398. # General configuration
  399. cookie_processor = compat_urllib_request.HTTPCookieProcessor(jar)
  400. if opts.proxy is not None:
  401. if opts.proxy == '':
  402. proxies = {}
  403. else:
  404. proxies = {'http': opts.proxy, 'https': opts.proxy}
  405. else:
  406. proxies = compat_urllib_request.getproxies()
  407. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  408. if 'http' in proxies and 'https' not in proxies:
  409. proxies['https'] = proxies['http']
  410. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  411. https_handler = make_HTTPS_handler(opts)
  412. opener = compat_urllib_request.build_opener(https_handler, proxy_handler, cookie_processor, YoutubeDLHandler())
  413. # Delete the default user-agent header, which would otherwise apply in
  414. # cases where our custom HTTP handler doesn't come into play
  415. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  416. opener.addheaders =[]
  417. compat_urllib_request.install_opener(opener)
  418. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  419. extractors = gen_extractors()
  420. if opts.list_extractors:
  421. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  422. compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  423. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  424. all_urls = [url for url in all_urls if url not in matchedUrls]
  425. for mu in matchedUrls:
  426. compat_print(u' ' + mu)
  427. sys.exit(0)
  428. if opts.list_extractor_descriptions:
  429. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  430. if not ie._WORKING:
  431. continue
  432. desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
  433. if hasattr(ie, 'SEARCH_KEY'):
  434. _SEARCHES = (u'cute kittens', u'slithering pythons', u'falling cat', u'angry poodle', u'purple fish', u'running tortoise')
  435. _COUNTS = (u'', u'5', u'10', u'all')
  436. desc += u' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
  437. compat_print(desc)
  438. sys.exit(0)
  439. # Conflicting, missing and erroneous options
  440. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  441. parser.error(u'using .netrc conflicts with giving username/password')
  442. if opts.password is not None and opts.username is None:
  443. parser.error(u' account username missing\n')
  444. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  445. parser.error(u'using output template conflicts with using title, video ID or auto number')
  446. if opts.usetitle and opts.useid:
  447. parser.error(u'using title conflicts with using video ID')
  448. if opts.username is not None and opts.password is None:
  449. opts.password = getpass.getpass(u'Type account password and press return:')
  450. if opts.ratelimit is not None:
  451. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  452. if numeric_limit is None:
  453. parser.error(u'invalid rate limit specified')
  454. opts.ratelimit = numeric_limit
  455. if opts.min_filesize is not None:
  456. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  457. if numeric_limit is None:
  458. parser.error(u'invalid min_filesize specified')
  459. opts.min_filesize = numeric_limit
  460. if opts.max_filesize is not None:
  461. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  462. if numeric_limit is None:
  463. parser.error(u'invalid max_filesize specified')
  464. opts.max_filesize = numeric_limit
  465. if opts.retries is not None:
  466. try:
  467. opts.retries = int(opts.retries)
  468. except (TypeError, ValueError) as err:
  469. parser.error(u'invalid retry count specified')
  470. if opts.buffersize is not None:
  471. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  472. if numeric_buffersize is None:
  473. parser.error(u'invalid buffer size specified')
  474. opts.buffersize = numeric_buffersize
  475. try:
  476. opts.playliststart = int(opts.playliststart)
  477. if opts.playliststart <= 0:
  478. raise ValueError(u'Playlist start must be positive')
  479. except (TypeError, ValueError) as err:
  480. parser.error(u'invalid playlist start number specified')
  481. try:
  482. opts.playlistend = int(opts.playlistend)
  483. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  484. raise ValueError(u'Playlist end must be greater than playlist start')
  485. except (TypeError, ValueError) as err:
  486. parser.error(u'invalid playlist end number specified')
  487. if opts.extractaudio:
  488. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  489. parser.error(u'invalid audio format specified')
  490. if opts.audioquality:
  491. opts.audioquality = opts.audioquality.strip('k').strip('K')
  492. if not opts.audioquality.isdigit():
  493. parser.error(u'invalid audio quality specified')
  494. if opts.recodevideo is not None:
  495. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg']:
  496. parser.error(u'invalid video recode format specified')
  497. if opts.date is not None:
  498. date = DateRange.day(opts.date)
  499. else:
  500. date = DateRange(opts.dateafter, opts.datebefore)
  501. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  502. # this was the old behaviour if only --all-sub was given.
  503. if opts.allsubtitles and (opts.writeautomaticsub == False):
  504. opts.writesubtitles = True
  505. if sys.version_info < (3,):
  506. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  507. if opts.outtmpl is not None:
  508. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  509. outtmpl =((opts.outtmpl is not None and opts.outtmpl)
  510. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  511. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  512. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  513. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  514. or (opts.useid and u'%(id)s.%(ext)s')
  515. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  516. or u'%(title)s-%(id)s.%(ext)s')
  517. if '%(ext)s' not in outtmpl and opts.extractaudio:
  518. parser.error(u'Cannot download a video and extract audio into the same'
  519. u' file! Use "%%(ext)s" instead of %r' %
  520. determine_ext(outtmpl, u''))
  521. # YoutubeDL
  522. ydl = YoutubeDL({
  523. 'usenetrc': opts.usenetrc,
  524. 'username': opts.username,
  525. 'password': opts.password,
  526. 'videopassword': opts.videopassword,
  527. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  528. 'forceurl': opts.geturl,
  529. 'forcetitle': opts.gettitle,
  530. 'forceid': opts.getid,
  531. 'forcethumbnail': opts.getthumbnail,
  532. 'forcedescription': opts.getdescription,
  533. 'forcefilename': opts.getfilename,
  534. 'forceformat': opts.getformat,
  535. 'simulate': opts.simulate,
  536. 'skip_download': (opts.skip_download or opts.simulate or opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  537. 'format': opts.format,
  538. 'format_limit': opts.format_limit,
  539. 'listformats': opts.listformats,
  540. 'outtmpl': outtmpl,
  541. 'autonumber_size': opts.autonumber_size,
  542. 'restrictfilenames': opts.restrictfilenames,
  543. 'ignoreerrors': opts.ignoreerrors,
  544. 'ratelimit': opts.ratelimit,
  545. 'nooverwrites': opts.nooverwrites,
  546. 'retries': opts.retries,
  547. 'buffersize': opts.buffersize,
  548. 'noresizebuffer': opts.noresizebuffer,
  549. 'continuedl': opts.continue_dl,
  550. 'noprogress': opts.noprogress,
  551. 'progress_with_newline': opts.progress_with_newline,
  552. 'playliststart': opts.playliststart,
  553. 'playlistend': opts.playlistend,
  554. 'noplaylist': opts.noplaylist,
  555. 'logtostderr': opts.outtmpl == '-',
  556. 'consoletitle': opts.consoletitle,
  557. 'nopart': opts.nopart,
  558. 'updatetime': opts.updatetime,
  559. 'writedescription': opts.writedescription,
  560. 'writeinfojson': opts.writeinfojson,
  561. 'writethumbnail': opts.writethumbnail,
  562. 'writesubtitles': opts.writesubtitles,
  563. 'writeautomaticsub': opts.writeautomaticsub,
  564. 'allsubtitles': opts.allsubtitles,
  565. 'listsubtitles': opts.listsubtitles,
  566. 'subtitlesformat': opts.subtitlesformat,
  567. 'subtitleslangs': opts.subtitleslangs,
  568. 'matchtitle': decodeOption(opts.matchtitle),
  569. 'rejecttitle': decodeOption(opts.rejecttitle),
  570. 'max_downloads': opts.max_downloads,
  571. 'prefer_free_formats': opts.prefer_free_formats,
  572. 'verbose': opts.verbose,
  573. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  574. 'test': opts.test,
  575. 'keepvideo': opts.keepvideo,
  576. 'min_filesize': opts.min_filesize,
  577. 'max_filesize': opts.max_filesize,
  578. 'daterange': date,
  579. 'cachedir': opts.cachedir,
  580. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  581. })
  582. if opts.verbose:
  583. write_string(u'[debug] youtube-dl version ' + __version__ + u'\n')
  584. try:
  585. sp = subprocess.Popen(
  586. ['git', 'rev-parse', '--short', 'HEAD'],
  587. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  588. cwd=os.path.dirname(os.path.abspath(__file__)))
  589. out, err = sp.communicate()
  590. out = out.decode().strip()
  591. if re.match('[0-9a-f]+', out):
  592. write_string(u'[debug] Git HEAD: ' + out + u'\n')
  593. except:
  594. try:
  595. sys.exc_clear()
  596. except:
  597. pass
  598. write_string(u'[debug] Python version %s - %s' %(platform.python_version(), platform_name()) + u'\n')
  599. write_string(u'[debug] Proxy map: ' + str(proxy_handler.proxies) + u'\n')
  600. ydl.add_default_info_extractors()
  601. # PostProcessors
  602. if opts.extractaudio:
  603. ydl.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, nopostoverwrites=opts.nopostoverwrites))
  604. if opts.recodevideo:
  605. ydl.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
  606. if opts.embedsubtitles:
  607. ydl.add_post_processor(FFmpegEmbedSubtitlePP(subtitlesformat=opts.subtitlesformat))
  608. # Update version
  609. if opts.update_self:
  610. update_self(ydl.to_screen, opts.verbose)
  611. # Maybe do nothing
  612. if len(all_urls) < 1:
  613. if not opts.update_self:
  614. parser.error(u'you must provide at least one URL')
  615. else:
  616. sys.exit()
  617. try:
  618. retcode = ydl.download(all_urls)
  619. except MaxDownloadsReached:
  620. ydl.to_screen(u'--max-download limit reached, aborting.')
  621. retcode = 101
  622. # Dump cookie jar if requested
  623. if opts.cookiefile is not None:
  624. try:
  625. jar.save()
  626. except (IOError, OSError) as err:
  627. sys.exit(u'ERROR: unable to save cookie jar')
  628. sys.exit(retcode)
  629. def main(argv=None):
  630. try:
  631. _real_main(argv)
  632. except DownloadError:
  633. sys.exit(1)
  634. except SameFileError:
  635. sys.exit(u'ERROR: fixed output name but more than one file to download')
  636. except KeyboardInterrupt:
  637. sys.exit(u'\nERROR: Interrupted by user')