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.

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