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.

612 lines
29 KiB

13 years ago
12 years ago
11 years ago
11 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='FORMAT',
  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 is not None:
  356. if opts.proxy == '':
  357. proxies = {}
  358. else:
  359. proxies = {'http': opts.proxy, 'https': opts.proxy}
  360. else:
  361. proxies = compat_urllib_request.getproxies()
  362. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  363. if 'http' in proxies and 'https' not in proxies:
  364. proxies['https'] = proxies['http']
  365. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  366. https_handler = make_HTTPS_handler(opts)
  367. opener = compat_urllib_request.build_opener(https_handler, proxy_handler, cookie_processor, YoutubeDLHandler())
  368. compat_urllib_request.install_opener(opener)
  369. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  370. extractors = gen_extractors()
  371. if opts.list_extractors:
  372. for ie in extractors:
  373. print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  374. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  375. all_urls = [url for url in all_urls if url not in matchedUrls]
  376. for mu in matchedUrls:
  377. print(u' ' + mu)
  378. sys.exit(0)
  379. # Conflicting, missing and erroneous options
  380. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  381. parser.error(u'using .netrc conflicts with giving username/password')
  382. if opts.password is not None and opts.username is None:
  383. parser.error(u'account username missing')
  384. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  385. parser.error(u'using output template conflicts with using title, video ID or auto number')
  386. if opts.usetitle and opts.useid:
  387. parser.error(u'using title conflicts with using video ID')
  388. if opts.username is not None and opts.password is None:
  389. opts.password = getpass.getpass(u'Type account password and press return:')
  390. if opts.ratelimit is not None:
  391. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  392. if numeric_limit is None:
  393. parser.error(u'invalid rate limit specified')
  394. opts.ratelimit = numeric_limit
  395. if opts.min_filesize is not None:
  396. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  397. if numeric_limit is None:
  398. parser.error(u'invalid min_filesize specified')
  399. opts.min_filesize = numeric_limit
  400. if opts.max_filesize is not None:
  401. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  402. if numeric_limit is None:
  403. parser.error(u'invalid max_filesize specified')
  404. opts.max_filesize = numeric_limit
  405. if opts.retries is not None:
  406. try:
  407. opts.retries = int(opts.retries)
  408. except (TypeError, ValueError) as err:
  409. parser.error(u'invalid retry count specified')
  410. if opts.buffersize is not None:
  411. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  412. if numeric_buffersize is None:
  413. parser.error(u'invalid buffer size specified')
  414. opts.buffersize = numeric_buffersize
  415. try:
  416. opts.playliststart = int(opts.playliststart)
  417. if opts.playliststart <= 0:
  418. raise ValueError(u'Playlist start must be positive')
  419. except (TypeError, ValueError) as err:
  420. parser.error(u'invalid playlist start number specified')
  421. try:
  422. opts.playlistend = int(opts.playlistend)
  423. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  424. raise ValueError(u'Playlist end must be greater than playlist start')
  425. except (TypeError, ValueError) as err:
  426. parser.error(u'invalid playlist end number specified')
  427. if opts.extractaudio:
  428. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  429. parser.error(u'invalid audio format specified')
  430. if opts.audioquality:
  431. opts.audioquality = opts.audioquality.strip('k').strip('K')
  432. if not opts.audioquality.isdigit():
  433. parser.error(u'invalid audio quality specified')
  434. if opts.recodevideo is not None:
  435. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg']:
  436. parser.error(u'invalid video recode format specified')
  437. if opts.date is not None:
  438. date = DateRange.day(opts.date)
  439. else:
  440. date = DateRange(opts.dateafter, opts.datebefore)
  441. if sys.version_info < (3,):
  442. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  443. if opts.outtmpl is not None:
  444. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  445. outtmpl =((opts.outtmpl is not None and opts.outtmpl)
  446. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  447. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  448. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  449. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  450. or (opts.useid and u'%(id)s.%(ext)s')
  451. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  452. or u'%(title)s-%(id)s.%(ext)s')
  453. # File downloader
  454. fd = FileDownloader({
  455. 'usenetrc': opts.usenetrc,
  456. 'username': opts.username,
  457. 'password': opts.password,
  458. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  459. 'forceurl': opts.geturl,
  460. 'forcetitle': opts.gettitle,
  461. 'forceid': opts.getid,
  462. 'forcethumbnail': opts.getthumbnail,
  463. 'forcedescription': opts.getdescription,
  464. 'forcefilename': opts.getfilename,
  465. 'forceformat': opts.getformat,
  466. 'simulate': opts.simulate,
  467. '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),
  468. 'format': opts.format,
  469. 'format_limit': opts.format_limit,
  470. 'listformats': opts.listformats,
  471. 'outtmpl': outtmpl,
  472. 'autonumber_size': opts.autonumber_size,
  473. 'restrictfilenames': opts.restrictfilenames,
  474. 'ignoreerrors': opts.ignoreerrors,
  475. 'ratelimit': opts.ratelimit,
  476. 'nooverwrites': opts.nooverwrites,
  477. 'retries': opts.retries,
  478. 'buffersize': opts.buffersize,
  479. 'noresizebuffer': opts.noresizebuffer,
  480. 'continuedl': opts.continue_dl,
  481. 'noprogress': opts.noprogress,
  482. 'progress_with_newline': opts.progress_with_newline,
  483. 'playliststart': opts.playliststart,
  484. 'playlistend': opts.playlistend,
  485. 'logtostderr': opts.outtmpl == '-',
  486. 'consoletitle': opts.consoletitle,
  487. 'nopart': opts.nopart,
  488. 'updatetime': opts.updatetime,
  489. 'writedescription': opts.writedescription,
  490. 'writeinfojson': opts.writeinfojson,
  491. 'writethumbnail': opts.writethumbnail,
  492. 'writesubtitles': opts.writesubtitles,
  493. 'allsubtitles': opts.allsubtitles,
  494. 'listsubtitles': opts.listsubtitles,
  495. 'subtitlesformat': opts.subtitlesformat,
  496. 'subtitleslang': opts.subtitleslang,
  497. 'matchtitle': decodeOption(opts.matchtitle),
  498. 'rejecttitle': decodeOption(opts.rejecttitle),
  499. 'max_downloads': opts.max_downloads,
  500. 'prefer_free_formats': opts.prefer_free_formats,
  501. 'verbose': opts.verbose,
  502. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  503. 'test': opts.test,
  504. 'keepvideo': opts.keepvideo,
  505. 'min_filesize': opts.min_filesize,
  506. 'max_filesize': opts.max_filesize,
  507. 'daterange': date,
  508. })
  509. if opts.verbose:
  510. fd.to_screen(u'[debug] youtube-dl version ' + __version__)
  511. try:
  512. sp = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  513. cwd=os.path.dirname(os.path.abspath(__file__)))
  514. out, err = sp.communicate()
  515. out = out.decode().strip()
  516. if re.match('[0-9a-f]+', out):
  517. fd.to_screen(u'[debug] Git HEAD: ' + out)
  518. except:
  519. pass
  520. fd.to_screen(u'[debug] Python version %s - %s' %(platform.python_version(), platform.platform()))
  521. fd.to_screen(u'[debug] Proxy map: ' + str(proxy_handler.proxies))
  522. for extractor in extractors:
  523. fd.add_info_extractor(extractor)
  524. # PostProcessors
  525. if opts.extractaudio:
  526. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, nopostoverwrites=opts.nopostoverwrites))
  527. if opts.recodevideo:
  528. fd.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
  529. # Update version
  530. if opts.update_self:
  531. update_self(fd.to_screen, opts.verbose, sys.argv[0])
  532. # Maybe do nothing
  533. if len(all_urls) < 1:
  534. if not opts.update_self:
  535. parser.error(u'you must provide at least one URL')
  536. else:
  537. sys.exit()
  538. try:
  539. retcode = fd.download(all_urls)
  540. except MaxDownloadsReached:
  541. fd.to_screen(u'--max-download limit reached, aborting.')
  542. retcode = 101
  543. # Dump cookie jar if requested
  544. if opts.cookiefile is not None:
  545. try:
  546. jar.save()
  547. except (IOError, OSError) as err:
  548. sys.exit(u'ERROR: unable to save cookie jar')
  549. sys.exit(retcode)
  550. def main(argv=None):
  551. try:
  552. _real_main(argv)
  553. except DownloadError:
  554. sys.exit(1)
  555. except SameFileError:
  556. sys.exit(u'ERROR: fixed output name but more than one file to download')
  557. except KeyboardInterrupt:
  558. sys.exit(u'\nERROR: Interrupted by user')