home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1361 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  6.9 KB  |  203 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __license__ = 'GPL v3'
  5. __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
  6. __docformat__ = 'restructuredtext en'
  7. import os
  8. import logging
  9. from logging.handlers import RotatingFileHandler
  10. import cherrypy
  11. from calibre.constants import __appname__, __version__
  12. from calibre.utils.date import fromtimestamp
  13. from calibre.library.server import listen_on, log_access_file, log_error_file
  14. from calibre.library.server.utils import expose
  15. from calibre.utils.mdns import publish as publish_zeroconf, stop_server as stop_zeroconf, get_external_ip
  16. from calibre.library.server.content import ContentServer
  17. from calibre.library.server.mobile import MobileServer
  18. from calibre.library.server.xml import XMLServer
  19. from calibre.library.server.opds import OPDSServer
  20. from calibre.library.server.cache import Cache
  21.  
  22. class DispatchController(object):
  23.     
  24.     def __init__(self):
  25.         self.dispatcher = cherrypy.dispatch.RoutesDispatcher()
  26.         self.funcs = []
  27.         self.seen = set([])
  28.  
  29.     
  30.     def __call__(self, name, route, func, **kwargs):
  31.         if name in self.seen:
  32.             raise NameError('Route name: ' + repr(name) + ' already used')
  33.         name in self.seen
  34.         self.seen.add(name)
  35.         kwargs['action'] = 'f_%d' % len(self.funcs)
  36.         self.dispatcher.connect(name, route, self, **kwargs)
  37.         self.funcs.append(expose(func))
  38.  
  39.     
  40.     def __getattr__(self, attr):
  41.         if not attr.startswith('f_'):
  42.             raise AttributeError(attr + ' not found')
  43.         attr.startswith('f_')
  44.         num = attr.rpartition('_')[-1]
  45.         
  46.         try:
  47.             num = int(num)
  48.         except:
  49.             raise AttributeError(attr + ' not found')
  50.  
  51.         if num < 0 or num >= len(self.funcs):
  52.             raise AttributeError(attr + ' not found')
  53.         num >= len(self.funcs)
  54.         return self.funcs[num]
  55.  
  56.  
  57.  
  58. class LibraryServer(ContentServer, MobileServer, XMLServer, OPDSServer, Cache):
  59.     server_name = __appname__ + '/' + __version__
  60.     
  61.     def __init__(self, db, opts, embedded = False, show_tracebacks = True):
  62.         self.db = db
  63.         for item in self.db:
  64.             item
  65.         
  66.         self.opts = opts
  67.         self.embedded = embedded
  68.         self.state_callback = None
  69.         (self.max_cover_width, self.max_cover_height) = map(int, self.opts.max_cover.split('x'))
  70.         path = P('content_server')
  71.         self.build_time = fromtimestamp(os.stat(path).st_mtime)
  72.         self.default_cover = open(P('content_server/default_cover.jpg'), 'rb').read()
  73.         cherrypy.config.update({
  74.             'log.screen': opts.develop,
  75.             'engine.autoreload_on': opts.develop,
  76.             'tools.log_headers.on': opts.develop,
  77.             'checker.on': opts.develop,
  78.             'request.show_tracebacks': show_tracebacks,
  79.             'server.socket_host': listen_on,
  80.             'server.socket_port': opts.port,
  81.             'server.socket_timeout': opts.timeout,
  82.             'server.thread_pool': opts.thread_pool })
  83.         if embedded:
  84.             cherrypy.config.update({
  85.                 'engine.SIGHUP': None,
  86.                 'engine.SIGTERM': None })
  87.         
  88.         self.config = {
  89.             'global': {
  90.                 'tools.gzip.on': True,
  91.                 'tools.gzip.mime_types': [
  92.                     'text/html',
  93.                     'text/plain',
  94.                     'text/xml',
  95.                     'text/javascript',
  96.                     'text/css'] } }
  97.         if opts.password:
  98.             self.config['/'] = {
  99.                 'tools.digest_auth.on': True,
  100.                 'tools.digest_auth.realm': (_('Password to access your calibre library. Username is ') + opts.username.strip()).encode('ascii', 'replace'),
  101.                 'tools.digest_auth.users': {
  102.                     opts.username.strip(): opts.password.strip() } }
  103.         
  104.         self.is_running = False
  105.         self.exception = None
  106.  
  107.     
  108.     def setup_loggers(self):
  109.         access_file = log_access_file
  110.         error_file = log_error_file
  111.         log = cherrypy.log
  112.         maxBytes = getattr(log, 'rot_maxBytes', 10000000)
  113.         backupCount = getattr(log, 'rot_backupCount', 1000)
  114.         h = RotatingFileHandler(error_file, 'a', maxBytes, backupCount)
  115.         h.setLevel(logging.DEBUG)
  116.         h.setFormatter(cherrypy._cplogging.logfmt)
  117.         log.error_log.addHandler(h)
  118.         h = RotatingFileHandler(access_file, 'a', maxBytes, backupCount)
  119.         h.setLevel(logging.DEBUG)
  120.         h.setFormatter(cherrypy._cplogging.logfmt)
  121.         log.access_log.addHandler(h)
  122.  
  123.     
  124.     def start(self):
  125.         self.is_running = False
  126.         d = DispatchController()
  127.         for x in self.__class__.__bases__:
  128.             if hasattr(x, 'add_routes'):
  129.                 x.add_routes(self, d)
  130.                 continue
  131.         
  132.         root_conf = self.config.get('/', { })
  133.         root_conf['request.dispatch'] = d.dispatcher
  134.         self.config['/'] = root_conf
  135.         self.setup_loggers()
  136.         cherrypy.tree.mount(root = None, config = self.config)
  137.         
  138.         try:
  139.             
  140.             try:
  141.                 cherrypy.engine.start()
  142.             except:
  143.                 ip = get_external_ip()
  144.                 if not ip or ip == '127.0.0.1':
  145.                     raise 
  146.                 ip == '127.0.0.1'
  147.                 cherrypy.log('Trying to bind to single interface: ' + ip)
  148.                 cherrypy.config.update({
  149.                     'server.socket_host': ip })
  150.                 cherrypy.engine.start()
  151.  
  152.             self.is_running = True
  153.             
  154.             try:
  155.                 publish_zeroconf('Books in calibre', '_stanza._tcp', self.opts.port, {
  156.                     'path': '/stanza' })
  157.             except:
  158.                 import traceback
  159.                 cherrypy.log.error('Failed to start BonJour:')
  160.                 cherrypy.log.error(traceback.format_exc())
  161.  
  162.             cherrypy.engine.block()
  163.         except Exception:
  164.             e = None
  165.             self.exception = e
  166.         finally:
  167.             self.is_running = False
  168.             
  169.             try:
  170.                 stop_zeroconf()
  171.             except:
  172.                 import traceback
  173.                 cherrypy.log.error('Failed to stop BonJour:')
  174.                 cherrypy.log.error(traceback.format_exc())
  175.  
  176.             
  177.             try:
  178.                 if callable(self.state_callback):
  179.                     self.state_callback(self.is_running)
  180.             except:
  181.                 pass
  182.  
  183.  
  184.  
  185.     
  186.     def exit(self):
  187.         
  188.         try:
  189.             cherrypy.engine.exit()
  190.         finally:
  191.             cherrypy.server.httpserver = None
  192.             self.is_running = False
  193.             
  194.             try:
  195.                 if callable(self.state_callback):
  196.                     self.state_callback(self.is_running)
  197.             except:
  198.                 pass
  199.  
  200.  
  201.  
  202.  
  203.