__init__.py 22 KB

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