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.

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