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