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.

588 lines
28 KiB

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