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.

646 lines
31 KiB

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