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.

657 lines
32 KiB

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