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.

605 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. )
  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='onlysubtitles',
  168. help='downloads only the subtitles (no video)', 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='LANG',
  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-thumbnail',
  192. action='store_true', dest='getthumbnail',
  193. help='simulate, quiet but print thumbnail URL', default=False)
  194. verbosity.add_option('--get-description',
  195. action='store_true', dest='getdescription',
  196. help='simulate, quiet but print video description', default=False)
  197. verbosity.add_option('--get-filename',
  198. action='store_true', dest='getfilename',
  199. help='simulate, quiet but print output filename', default=False)
  200. verbosity.add_option('--get-format',
  201. action='store_true', dest='getformat',
  202. help='simulate, quiet but print output format', default=False)
  203. verbosity.add_option('--newline',
  204. action='store_true', dest='progress_with_newline', help='output progress bar as new lines', default=False)
  205. verbosity.add_option('--no-progress',
  206. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  207. verbosity.add_option('--console-title',
  208. action='store_true', dest='consoletitle',
  209. help='display progress in console titlebar', default=False)
  210. verbosity.add_option('-v', '--verbose',
  211. action='store_true', dest='verbose', help='print various debugging information', default=False)
  212. verbosity.add_option('--dump-intermediate-pages',
  213. action='store_true', dest='dump_intermediate_pages', default=False,
  214. help='print downloaded pages to debug problems(very verbose)')
  215. filesystem.add_option('-t', '--title',
  216. action='store_true', dest='usetitle', help='use title in file name (default)', default=False)
  217. filesystem.add_option('--id',
  218. action='store_true', dest='useid', help='use only video ID in file name', default=False)
  219. filesystem.add_option('-l', '--literal',
  220. action='store_true', dest='usetitle', help='[deprecated] alias of --title', default=False)
  221. filesystem.add_option('-A', '--auto-number',
  222. action='store_true', dest='autonumber',
  223. help='number downloaded files starting from 00000', default=False)
  224. filesystem.add_option('-o', '--output',
  225. dest='outtmpl', metavar='TEMPLATE',
  226. help=('output filename template. Use %(title)s to get the title, '
  227. '%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
  228. '%(autonumber)s to get an automatically incremented number, '
  229. '%(ext)s for the filename extension, %(upload_date)s for the upload date (YYYYMMDD), '
  230. '%(extractor)s for the provider (youtube, metacafe, etc), '
  231. '%(id)s for the video id , %(playlist)s for the playlist the video is in, '
  232. '%(playlist_index)s for the position in the playlist and %% for a literal percent. '
  233. 'Use - to output to stdout. Can also be used to download to a different directory, '
  234. 'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
  235. filesystem.add_option('--autonumber-size',
  236. dest='autonumber_size', metavar='NUMBER',
  237. help='Specifies the number of digits in %(autonumber)s when it is present in output filename template or --autonumber option is given')
  238. filesystem.add_option('--restrict-filenames',
  239. action='store_true', dest='restrictfilenames',
  240. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames', default=False)
  241. filesystem.add_option('-a', '--batch-file',
  242. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  243. filesystem.add_option('-w', '--no-overwrites',
  244. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  245. filesystem.add_option('-c', '--continue',
  246. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=True)
  247. filesystem.add_option('--no-continue',
  248. action='store_false', dest='continue_dl',
  249. help='do not resume partially downloaded files (restart from beginning)')
  250. filesystem.add_option('--cookies',
  251. dest='cookiefile', metavar='FILE', help='file to read cookies from and dump cookie jar in')
  252. filesystem.add_option('--no-part',
  253. action='store_true', dest='nopart', help='do not use .part files', default=False)
  254. filesystem.add_option('--no-mtime',
  255. action='store_false', dest='updatetime',
  256. help='do not use the Last-modified header to set the file modification time', default=True)
  257. filesystem.add_option('--write-description',
  258. action='store_true', dest='writedescription',
  259. help='write video description to a .description file', default=False)
  260. filesystem.add_option('--write-info-json',
  261. action='store_true', dest='writeinfojson',
  262. help='write video metadata to a .info.json file', default=False)
  263. filesystem.add_option('--write-thumbnail',
  264. action='store_true', dest='writethumbnail',
  265. help='write thumbnail image to disk', default=False)
  266. postproc.add_option('-x', '--extract-audio', action='store_true', dest='extractaudio', default=False,
  267. help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
  268. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  269. help='"best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; best by default')
  270. postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='5',
  271. 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)')
  272. postproc.add_option('--recode-video', metavar='FORMAT', dest='recodevideo', default=None,
  273. help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm)')
  274. postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
  275. help='keeps the video file on disk after the post-processing; the video is erased by default')
  276. postproc.add_option('--no-post-overwrites', action='store_true', dest='nopostoverwrites', default=False,
  277. help='do not overwrite post-processed files; the post-processed files are overwritten by default')
  278. parser.add_option_group(general)
  279. parser.add_option_group(selection)
  280. parser.add_option_group(filesystem)
  281. parser.add_option_group(verbosity)
  282. parser.add_option_group(video_format)
  283. parser.add_option_group(authentication)
  284. parser.add_option_group(postproc)
  285. if overrideArguments is not None:
  286. opts, args = parser.parse_args(overrideArguments)
  287. if opts.verbose:
  288. print(u'[debug] Override config: ' + repr(overrideArguments))
  289. else:
  290. xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
  291. if xdg_config_home:
  292. userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
  293. else:
  294. userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
  295. systemConf = _readOptions('/etc/youtube-dl.conf')
  296. userConf = _readOptions(userConfFile)
  297. commandLineConf = sys.argv[1:]
  298. argv = systemConf + userConf + commandLineConf
  299. opts, args = parser.parse_args(argv)
  300. if opts.verbose:
  301. print(u'[debug] System config: ' + repr(systemConf))
  302. print(u'[debug] User config: ' + repr(userConf))
  303. print(u'[debug] Command-line args: ' + repr(commandLineConf))
  304. return parser, opts, args
  305. def _real_main(argv=None):
  306. # Compatibility fixes for Windows
  307. if sys.platform == 'win32':
  308. # https://github.com/rg3/youtube-dl/issues/820
  309. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
  310. parser, opts, args = parseOpts(argv)
  311. # Open appropriate CookieJar
  312. if opts.cookiefile is None:
  313. jar = compat_cookiejar.CookieJar()
  314. else:
  315. try:
  316. jar = compat_cookiejar.MozillaCookieJar(opts.cookiefile)
  317. if os.access(opts.cookiefile, os.R_OK):
  318. jar.load()
  319. except (IOError, OSError) as err:
  320. if opts.verbose:
  321. traceback.print_exc()
  322. sys.stderr.write(u'ERROR: unable to open cookie file\n')
  323. sys.exit(101)
  324. # Set user agent
  325. if opts.user_agent is not None:
  326. std_headers['User-Agent'] = opts.user_agent
  327. # Set referer
  328. if opts.referer is not None:
  329. std_headers['Referer'] = opts.referer
  330. # Dump user agent
  331. if opts.dump_user_agent:
  332. print(std_headers['User-Agent'])
  333. sys.exit(0)
  334. # Batch file verification
  335. batchurls = []
  336. if opts.batchfile is not None:
  337. try:
  338. if opts.batchfile == '-':
  339. batchfd = sys.stdin
  340. else:
  341. batchfd = open(opts.batchfile, 'r')
  342. batchurls = batchfd.readlines()
  343. batchurls = [x.strip() for x in batchurls]
  344. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  345. except IOError:
  346. sys.exit(u'ERROR: batch file could not be read')
  347. all_urls = batchurls + args
  348. all_urls = [url.strip() for url in all_urls]
  349. # General configuration
  350. cookie_processor = compat_urllib_request.HTTPCookieProcessor(jar)
  351. if opts.proxy:
  352. proxies = {'http': opts.proxy, 'https': opts.proxy}
  353. else:
  354. proxies = compat_urllib_request.getproxies()
  355. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  356. if 'http' in proxies and 'https' not in proxies:
  357. proxies['https'] = proxies['http']
  358. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  359. https_handler = make_HTTPS_handler(opts)
  360. opener = compat_urllib_request.build_opener(https_handler, proxy_handler, cookie_processor, YoutubeDLHandler())
  361. compat_urllib_request.install_opener(opener)
  362. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  363. extractors = gen_extractors()
  364. if opts.list_extractors:
  365. for ie in extractors:
  366. print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  367. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  368. all_urls = [url for url in all_urls if url not in matchedUrls]
  369. for mu in matchedUrls:
  370. print(u' ' + mu)
  371. sys.exit(0)
  372. # Conflicting, missing and erroneous options
  373. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  374. parser.error(u'using .netrc conflicts with giving username/password')
  375. if opts.password is not None and opts.username is None:
  376. parser.error(u'account username missing')
  377. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  378. parser.error(u'using output template conflicts with using title, video ID or auto number')
  379. if opts.usetitle and opts.useid:
  380. parser.error(u'using title conflicts with using video ID')
  381. if opts.username is not None and opts.password is None:
  382. opts.password = getpass.getpass(u'Type account password and press return:')
  383. if opts.ratelimit is not None:
  384. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  385. if numeric_limit is None:
  386. parser.error(u'invalid rate limit specified')
  387. opts.ratelimit = numeric_limit
  388. if opts.min_filesize is not None:
  389. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  390. if numeric_limit is None:
  391. parser.error(u'invalid min_filesize specified')
  392. opts.min_filesize = numeric_limit
  393. if opts.max_filesize is not None:
  394. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  395. if numeric_limit is None:
  396. parser.error(u'invalid max_filesize specified')
  397. opts.max_filesize = numeric_limit
  398. if opts.retries is not None:
  399. try:
  400. opts.retries = int(opts.retries)
  401. except (TypeError, ValueError) as err:
  402. parser.error(u'invalid retry count specified')
  403. if opts.buffersize is not None:
  404. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  405. if numeric_buffersize is None:
  406. parser.error(u'invalid buffer size specified')
  407. opts.buffersize = numeric_buffersize
  408. try:
  409. opts.playliststart = int(opts.playliststart)
  410. if opts.playliststart <= 0:
  411. raise ValueError(u'Playlist start must be positive')
  412. except (TypeError, ValueError) as err:
  413. parser.error(u'invalid playlist start number specified')
  414. try:
  415. opts.playlistend = int(opts.playlistend)
  416. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  417. raise ValueError(u'Playlist end must be greater than playlist start')
  418. except (TypeError, ValueError) as err:
  419. parser.error(u'invalid playlist end number specified')
  420. if opts.extractaudio:
  421. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  422. parser.error(u'invalid audio format specified')
  423. if opts.audioquality:
  424. opts.audioquality = opts.audioquality.strip('k').strip('K')
  425. if not opts.audioquality.isdigit():
  426. parser.error(u'invalid audio quality specified')
  427. if opts.recodevideo is not None:
  428. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg']:
  429. parser.error(u'invalid video recode format specified')
  430. if opts.date is not None:
  431. date = DateRange.day(opts.date)
  432. else:
  433. date = DateRange(opts.dateafter, opts.datebefore)
  434. if sys.version_info < (3,):
  435. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  436. if opts.outtmpl is not None:
  437. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  438. outtmpl =((opts.outtmpl is not None and opts.outtmpl)
  439. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  440. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  441. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  442. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  443. or (opts.useid and u'%(id)s.%(ext)s')
  444. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  445. or u'%(title)s-%(id)s.%(ext)s')
  446. # File downloader
  447. fd = FileDownloader({
  448. 'usenetrc': opts.usenetrc,
  449. 'username': opts.username,
  450. 'password': opts.password,
  451. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  452. 'forceurl': opts.geturl,
  453. 'forcetitle': opts.gettitle,
  454. 'forcethumbnail': opts.getthumbnail,
  455. 'forcedescription': opts.getdescription,
  456. 'forcefilename': opts.getfilename,
  457. 'forceformat': opts.getformat,
  458. 'simulate': opts.simulate,
  459. '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),
  460. 'format': opts.format,
  461. 'format_limit': opts.format_limit,
  462. 'listformats': opts.listformats,
  463. 'outtmpl': outtmpl,
  464. 'autonumber_size': opts.autonumber_size,
  465. 'restrictfilenames': opts.restrictfilenames,
  466. 'ignoreerrors': opts.ignoreerrors,
  467. 'ratelimit': opts.ratelimit,
  468. 'nooverwrites': opts.nooverwrites,
  469. 'retries': opts.retries,
  470. 'buffersize': opts.buffersize,
  471. 'noresizebuffer': opts.noresizebuffer,
  472. 'continuedl': opts.continue_dl,
  473. 'noprogress': opts.noprogress,
  474. 'progress_with_newline': opts.progress_with_newline,
  475. 'playliststart': opts.playliststart,
  476. 'playlistend': opts.playlistend,
  477. 'logtostderr': opts.outtmpl == '-',
  478. 'consoletitle': opts.consoletitle,
  479. 'nopart': opts.nopart,
  480. 'updatetime': opts.updatetime,
  481. 'writedescription': opts.writedescription,
  482. 'writeinfojson': opts.writeinfojson,
  483. 'writethumbnail': opts.writethumbnail,
  484. 'writesubtitles': opts.writesubtitles,
  485. 'onlysubtitles': opts.onlysubtitles,
  486. 'allsubtitles': opts.allsubtitles,
  487. 'listsubtitles': opts.listsubtitles,
  488. 'subtitlesformat': opts.subtitlesformat,
  489. 'subtitleslang': opts.subtitleslang,
  490. 'matchtitle': decodeOption(opts.matchtitle),
  491. 'rejecttitle': decodeOption(opts.rejecttitle),
  492. 'max_downloads': opts.max_downloads,
  493. 'prefer_free_formats': opts.prefer_free_formats,
  494. 'verbose': opts.verbose,
  495. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  496. 'test': opts.test,
  497. 'keepvideo': opts.keepvideo,
  498. 'min_filesize': opts.min_filesize,
  499. 'max_filesize': opts.max_filesize,
  500. 'daterange': date,
  501. })
  502. if opts.verbose:
  503. fd.to_screen(u'[debug] youtube-dl version ' + __version__)
  504. try:
  505. sp = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  506. cwd=os.path.dirname(os.path.abspath(__file__)))
  507. out, err = sp.communicate()
  508. out = out.decode().strip()
  509. if re.match('[0-9a-f]+', out):
  510. fd.to_screen(u'[debug] Git HEAD: ' + out)
  511. except:
  512. pass
  513. fd.to_screen(u'[debug] Python version %s - %s' %(platform.python_version(), platform.platform()))
  514. fd.to_screen(u'[debug] Proxy map: ' + str(proxy_handler.proxies))
  515. for extractor in extractors:
  516. fd.add_info_extractor(extractor)
  517. # PostProcessors
  518. if opts.extractaudio:
  519. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, nopostoverwrites=opts.nopostoverwrites))
  520. if opts.recodevideo:
  521. fd.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
  522. # Update version
  523. if opts.update_self:
  524. update_self(fd.to_screen, opts.verbose, sys.argv[0])
  525. # Maybe do nothing
  526. if len(all_urls) < 1:
  527. if not opts.update_self:
  528. parser.error(u'you must provide at least one URL')
  529. else:
  530. sys.exit()
  531. try:
  532. retcode = fd.download(all_urls)
  533. except MaxDownloadsReached:
  534. fd.to_screen(u'--max-download limit reached, aborting.')
  535. retcode = 101
  536. # Dump cookie jar if requested
  537. if opts.cookiefile is not None:
  538. try:
  539. jar.save()
  540. except (IOError, OSError) as err:
  541. sys.exit(u'ERROR: unable to save cookie jar')
  542. sys.exit(retcode)
  543. def main(argv=None):
  544. try:
  545. _real_main(argv)
  546. except DownloadError:
  547. sys.exit(1)
  548. except SameFileError:
  549. sys.exit(u'ERROR: fixed output name but more than one file to download')
  550. except KeyboardInterrupt:
  551. sys.exit(u'\nERROR: Interrupted by user')