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.

555 lines
26 KiB

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