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.

671 lines
32 KiB

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