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.

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