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.

609 lines
29 KiB

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