Exemplo n.º 1
0
 def static(self, name):
     'Serves static content'
     name = name.lower()
     fname = posixpath.basename(name)
     try:
         cherrypy.response.headers['Content-Type'] = {
             'js': 'text/javascript',
             'css': 'text/css',
             'png': 'image/png',
             'gif': 'image/gif',
             'html': 'text/html',
         }[fname.rpartition('.')[-1].lower()]
     except KeyError:
         raise cherrypy.HTTPError(404,
                                  '%r not a valid resource type' % name)
     cherrypy.response.headers['Last-Modified'] = self.last_modified(
         self.build_time)
     basedir = os.path.abspath(P('content_server'))
     path = os.path.join(basedir, name.replace('/', os.sep))
     path = os.path.abspath(path)
     if not path.startswith(basedir):
         raise cherrypy.HTTPError(403, 'Access to %s is forbidden' % name)
     if not os.path.exists(path) or not os.path.isfile(path):
         raise cherrypy.HTTPError(404, '%s not found' % name)
     if self.opts.develop:
         lm = fromtimestamp(os.stat(path).st_mtime)
         cherrypy.response.headers['Last-Modified'] = self.last_modified(lm)
     with open(path, 'rb') as f:
         ans = f.read()
     if path.endswith('.css'):
         ans = ans.replace('/static/', self.opts.url_prefix + '/static/')
     return ans
Exemplo n.º 2
0
 def static(self, name):
     'Serves static content'
     name = name.lower()
     fname = posixpath.basename(name)
     try:
         cherrypy.response.headers['Content-Type'] = {
                  'js'   : 'text/javascript',
                  'css'  : 'text/css',
                  'png'  : 'image/png',
                  'gif'  : 'image/gif',
                  'html' : 'text/html',
                  }[fname.rpartition('.')[-1].lower()]
     except KeyError:
         raise cherrypy.HTTPError(404, '%r not a valid resource type'%name)
     cherrypy.response.headers['Last-Modified'] = self.last_modified(self.build_time)
     basedir = os.path.abspath(P('content_server'))
     path = os.path.join(basedir, name.replace('/', os.sep))
     path = os.path.abspath(path)
     if not path.startswith(basedir):
         raise cherrypy.HTTPError(403, 'Access to %s is forbidden'%name)
     if not os.path.exists(path) or not os.path.isfile(path):
         raise cherrypy.HTTPError(404, '%s not found'%name)
     if self.opts.develop:
         lm = fromtimestamp(os.stat(path).st_mtime)
         cherrypy.response.headers['Last-Modified'] = self.last_modified(lm)
     with open(path, 'rb') as f:
         ans = f.read()
     if path.endswith('.css'):
         ans = ans.replace('/static/', self.opts.url_prefix + '/static/')
     return ans
Exemplo n.º 3
0
def make_app():
    init_calibre()

    import handlers
    from calibre.db.legacy import LibraryDatabase
    from calibre.utils.date import fromtimestamp

    auth_db_path = CONF['user_database']
    logging.info("Init library with [%s]" % options.with_library)
    logging.info("Init AuthDB  with [%s]" % auth_db_path)
    logging.info("Init Static  with [%s]" % CONF['static_path'])
    logging.info("Init HTML    with [%s]" % CONF['html_path'])
    book_db = LibraryDatabase(os.path.expanduser(options.with_library))
    cache = book_db.new_api

    # hook 1: 按字母作为第一级目录,解决书库子目录太多的问题
    if CONF['BOOK_NAMES_FORMAT'].lower() == 'utf8':
        bind_utf8_book_names(cache)
    else:
        bind_topdir_book_names(cache)

    # hook 2: don't force GUI
    from calibre import gui2
    old_must_use_qt = gui2.must_use_qt

    def new_must_use_qt(headless=True):
        try:
            old_must_use_qt(headless)
        except:
            pass

    gui2.must_use_qt = new_must_use_qt

    # build sql session factory
    engine = create_engine(auth_db_path, echo=False)
    ScopedSession = scoped_session(
        sessionmaker(bind=engine, autoflush=True, autocommit=False))
    models.bind_session(ScopedSession)
    init_social(models.Base, ScopedSession, CONF)

    if options.syncdb:
        models.user_syncdb(engine)
        logging.info("Create tables into DB")
        sys.exit(0)

    path = CONF['static_path'] + '/calibre/default_cover.jpg'
    with open(path, 'rb') as cover_file:
        default_cover = cover_file.read()
    app_settings = dict(CONF)
    app_settings.update({
        "legacy": book_db,
        "cache": cache,
        "ScopedSession": ScopedSession,
        "build_time": fromtimestamp(os.stat(path).st_mtime),
        "default_cover": default_cover,
    })

    logging.info("Now, Running...")
    return web.Application(
        social_routes.SOCIAL_AUTH_ROUTES + handlers.routes(), **app_settings)
Exemplo n.º 4
0
 def initialize(self):
     self.session = self.settings['session']
     self.session.close()
     self.db = self.settings['legacy']
     self.cache = self.db.new_api
     path = self.settings['static_path'] + '/img/default_cover.jpg'
     self.build_time = fromtimestamp(os.stat(path).st_mtime)
     self.default_cover = open(path, 'rb').read()
     self.admin_user = None
     self.static_host = self.settings.get("static_host", "")
     if self.static_host:
         self.static_host = self.request.protocol + "://" + self.static_host
Exemplo n.º 5
0
    def __init__(self, db, opts, embedded=False, show_tracebacks=True,
            wsgi=False):
        self.is_wsgi = bool(wsgi)
        self.opts = opts
        self.embedded = embedded
        self.state_callback = None
        self.start_failure_callback = None
        try:
            self.max_cover_width, self.max_cover_height = \
                        map(int, self.opts.max_cover.split('x'))
        except:
            self.max_cover_width = 1200
            self.max_cover_height = 1600
        path = P('content_server')
        self.build_time = fromtimestamp(os.stat(path).st_mtime)
        self.default_cover = open(P('content_server/default_cover.jpg'), 'rb').read()
        if not opts.url_prefix:
            opts.url_prefix = ''

        cherrypy.engine.bonjour.ip_address = listen_on
        cherrypy.engine.bonjour.port = opts.port
        cherrypy.engine.bonjour.prefix = opts.url_prefix

        Cache.__init__(self)

        self.set_database(db)

        st = 0.1 if opts.develop else 1

        cherrypy.config.update({
            'log.screen'             : opts.develop,
            'engine.autoreload_on'   : getattr(opts,
                                        'auto_reload', False),
            'tools.log_headers.on'   : opts.develop,
            'tools.encode.encoding'  : 'UTF-8',
            'checker.on'             : opts.develop,
            'request.show_tracebacks': show_tracebacks,
            'server.socket_host'     : listen_on,
            'server.socket_port'     : opts.port,
            'server.socket_timeout'  : opts.timeout, #seconds
            'server.thread_pool'     : opts.thread_pool, # number of threads
            'server.shutdown_timeout': st, # minutes
        })
        if embedded or wsgi:
            cherrypy.config.update({'engine.SIGHUP'          : None,
                                    'engine.SIGTERM'         : None,})
        self.config = {}
        self.is_running = False
        self.exception = None
        auth_controller = None
        self.users_dict = {}
        #self.config['/'] = {
        #    'tools.sessions.on' : True,
        #    'tools.sessions.timeout': 60, # Session times out after 60 minutes
        #}

        if not wsgi:
            self.setup_loggers()
            cherrypy.engine.bonjour.subscribe()
            self.config['global'] = {
                'tools.gzip.on'        : True,
                'tools.gzip.mime_types': ['text/html', 'text/plain',
                    'text/xml', 'text/javascript', 'text/css'],
            }

            if opts.password:
                self.users_dict[opts.username.strip()] = opts.password.strip()
                auth_controller = AuthController('Your calibre library',
                        self.users_dict)

        self.__dispatcher__ = DispatchController(self.opts.url_prefix,
                wsgi=wsgi, auth_controller=auth_controller)
        for x in self.__class__.__bases__:
            if hasattr(x, 'add_routes'):
                x.__init__(self)
                x.add_routes(self, self.__dispatcher__)
        root_conf = self.config.get('/', {})
        root_conf['request.dispatch'] = self.__dispatcher__.dispatcher
        self.config['/'] = root_conf
Exemplo n.º 6
0
    def __init__(self, db, opts, embedded=False, show_tracebacks=True,
            wsgi=False):
        self.is_wsgi = bool(wsgi)
        self.opts = opts
        self.embedded = embedded
        self.state_callback = None
        self.start_failure_callback = None
        try:
            self.max_cover_width, self.max_cover_height = \
                        map(int, self.opts.max_cover.split('x'))
        except:
            self.max_cover_width = 1200
            self.max_cover_height = 1600
        path = P('content_server')
        self.build_time = fromtimestamp(os.stat(path).st_mtime)
        self.default_cover = open(P('content_server/default_cover.jpg'), 'rb').read()
        if not opts.url_prefix:
            opts.url_prefix = ''

        cherrypy.engine.bonjour.ip_address = listen_on
        cherrypy.engine.bonjour.port = opts.port
        cherrypy.engine.bonjour.prefix = opts.url_prefix

        Cache.__init__(self)

        self.set_database(db)

        st = 0.1 if opts.develop else 1

        cherrypy.config.update({
            'log.screen'             : opts.develop,
            'engine.autoreload_on'   : getattr(opts,
                                        'auto_reload', False),
            'tools.log_headers.on'   : opts.develop,
            'tools.encode.encoding'  : 'UTF-8',
            'checker.on'             : opts.develop,
            'request.show_tracebacks': show_tracebacks,
            'server.socket_host'     : listen_on,
            'server.socket_port'     : opts.port,
            'server.socket_timeout'  : opts.timeout,  # seconds
            'server.thread_pool'     : opts.thread_pool,  # number of threads
            'server.shutdown_timeout': st,  # minutes
        })
        if embedded or wsgi:
            cherrypy.config.update({'engine.SIGHUP'          : None,
                                    'engine.SIGTERM'         : None,})
        self.config = {}
        self.is_running = False
        self.exception = None
        auth_controller = None
        self.users_dict = {}
        # self.config['/'] = {
        #    'tools.sessions.on' : True,
        # 'tools.sessions.timeout': 60, # Session times out after 60 minutes
        #}

        if not wsgi:
            self.setup_loggers()
            cherrypy.engine.bonjour.subscribe()
            self.config['global'] = {
                'tools.gzip.on'        : True,
                'tools.gzip.mime_types': ['text/html', 'text/plain',
                    'text/xml', 'text/javascript', 'text/css'],
            }

            if opts.username and opts.password:
                self.users_dict[opts.username.strip()] = opts.password.strip()
                auth_controller = AuthController('Your calibre library',
                        self.users_dict)

        self.__dispatcher__ = DispatchController(self.opts.url_prefix,
                wsgi=wsgi, auth_controller=auth_controller)
        for x in self.__class__.__bases__:
            if hasattr(x, 'add_routes'):
                x.__init__(self)
                x.add_routes(self, self.__dispatcher__)
        root_conf = self.config.get('/', {})
        root_conf['request.dispatch'] = self.__dispatcher__.dispatcher
        self.config['/'] = root_conf
Exemplo n.º 7
0
    def __init__(self,
                 db,
                 opts,
                 embedded=False,
                 show_tracebacks=True,
                 wsgi=False):
        self.is_wsgi = bool(wsgi)
        self.opts = opts
        self.embedded = embedded
        self.state_callback = None
        self.start_failure_callback = None
        try:
            self.max_cover_width, self.max_cover_height = \
                        map(int, self.opts.max_cover.split('x'))
        except:
            self.max_cover_width = 1200
            self.max_cover_height = 1600
        path = P('content_server')
        self.build_time = fromtimestamp(os.stat(path).st_mtime)
        self.default_cover = open(P('content_server/m/img/default_cover.jpg'),
                                  'rb').read()
        if not opts.url_prefix:
            opts.url_prefix = ''

        cherrypy.engine.bonjour.ip_address = listen_on
        cherrypy.engine.bonjour.port = opts.port
        cherrypy.engine.bonjour.prefix = opts.url_prefix

        self.last_lang = "en"
        self.all_langs = dict(get_all_translators())
        cherrypy.request.hooks.attach('before_handler', self.update_lang)
        cherrypy.request.hooks.attach('before_handler', self.load_user)
        #cherrypy.request.hooks.attach('on_end_resource', self.save_session)

        #cherrypy.tools.authenticate = cherrypy.Tool('before_handler', self.load_user)
        #cherrypy.tools.session = cherrypy.Tool('on_end_resource', self.save_session)

        Cache.__init__(self)

        self.set_database(db)

        st = 1 if opts.develop else 1

        cherrypy.config.update({
            'log.screen':
            opts.develop,
            'engine.autoreload_on':
            getattr(opts, 'auto_reload', False),
            'tools.log_headers.on':
            opts.develop,
            'tools.encode.encoding':
            'UTF-8',
            'checker.on':
            opts.develop,
            'request.show_tracebacks':
            show_tracebacks,
            'server.socket_host':
            listen_on,
            'server.socket_port':
            opts.port,
            'server.socket_timeout':
            opts.timeout,  # seconds
            'server.thread_pool':
            opts.thread_pool,  # number of threads
            'server.shutdown_timeout':
            st,  # minutes
            'tools.sessions.on':
            True,
            #'tools.sessions.storage_type': 'ram',
            'tools.sessions.timeout':
            60000,  # Session times out after 60 minutes
            'tools.sessions.storage_type':
            "file",
            'tools.sessions.storage_path':
            "/data/tmp/cherrypy/",
            'SOCIAL_AUTH_USER_MODEL':
            'calibre.library.server.auth.FuckUser',
            'SOCIAL_AUTH_LOGIN_URL':
            '/auth/',
            'SOCIAL_AUTH_LOGIN_REDIRECT_URL':
            '/',
            'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
                'social.backends.douban.DoubanOAuth',
                'social.backends.douban.DoubanOAuth2',
            ),
            'SOCIAL_AUTH_DOUBAN_OAUTH2_KEY':
            '052c9ac15e9870500f85d0441bc950f0',
            'SOCIAL_AUTH_DOUBAN_OAUTH2_SECRET':
            '3b524f1487999fc6',
        })
        cherrypy.tools.jinja2env = build_jinja2_env()
        if embedded or wsgi:
            cherrypy.config.update({
                'engine.SIGHUP': None,
                'engine.SIGTERM': None,
            })
        self.config = {}
        self.is_running = False
        self.exception = None
        auth_controller = None
        self.users_dict = {}

        if not wsgi:
            self.setup_loggers()
            cherrypy.engine.bonjour.subscribe()
            self.config['global'] = {
                'tools.gzip.on':
                True,
                'tools.gzip.mime_types': [
                    'text/html', 'text/plain', 'text/xml', 'text/javascript',
                    'text/css'
                ],
            }

            if opts.username and opts.password:
                self.users_dict[opts.username.strip()] = opts.password.strip()
                auth_controller = AuthController('Your calibre library',
                                                 self.users_dict)

        self.__dispatcher__ = DispatchController(
            self.opts.url_prefix, wsgi=wsgi, auth_controller=auth_controller)
        for x in self.__class__.__bases__:
            if hasattr(x, 'add_routes'):
                x.__init__(self)
                x.add_routes(self, self.__dispatcher__)
        root_conf = self.config.get('/', {})
        root_conf['request.dispatch'] = self.__dispatcher__.dispatcher
        self.config['/'] = root_conf
Exemplo n.º 8
0
def make_app():
    init_calibre()

    import handlers
    from calibre.db.legacy import LibraryDatabase
    from calibre.utils.date import fromtimestamp

    auth_db_path = CONF['user_database']
    logging.info("Init library with [%s]" % options.with_library)
    logging.info("Init AuthDB  with [%s]" % auth_db_path )
    logging.info("Init Static  with [%s]" % CONF['static_path'] )
    logging.info("Init HTML    with [%s]" % CONF['html_path'] )
    logging.info("Init LANG    with [%s]" % P('localization/locales.zip') )
    book_db = LibraryDatabase(os.path.expanduser(options.with_library))
    cache = book_db.new_api


    # hook 1: 按字母作为第一级目录,解决书库子目录太多的问题
    old_construct_path_name = cache.backend.construct_path_name
    def new_construct_path_name(*args, **kwargs):
        s = old_construct_path_name(*args, **kwargs)
        ns = s[0] + "/" + s
        logging.debug("new str = %s" % ns)
        return ns
    cache.backend.construct_path_name = new_construct_path_name

    # hook 2: don't force GUI
    from calibre import gui2
    old_must_use_qt = gui2.must_use_qt
    def new_must_use_qt(headless=True):
        try:
            old_must_use_qt(headless)
        except:
            pass
    gui2.must_use_qt = new_must_use_qt

    # build sql session factory
    engine = create_engine(auth_db_path, echo=False)
    ScopedSession = scoped_session(sessionmaker(bind=engine, autoflush=True, autocommit=False))
    models.bind_session(ScopedSession)
    init_social(models.Base, ScopedSession, CONF)

    if options.syncdb:
        models.user_syncdb(engine)
        logging.info("Create tables into DB")
        sys.exit(0)

    path = CONF['static_path'] + '/calibre/default_cover.jpg'
    app_settings = dict(CONF)
    app_settings.update({
        "legacy": book_db,
        "cache": cache,
        "ScopedSession": ScopedSession ,
        "build_time": fromtimestamp(os.stat(path).st_mtime),
        "default_cover": open(path, 'rb').read(),
        })

    #load_calibre_translations()
    logging.info("Now, Running...")
    return web.Application(
            SOCIAL_AUTH_ROUTES + handlers.routes(),
            **app_settings)
Exemplo n.º 9
0
    def __init__(self, db, opts, embedded=False, show_tracebacks=True,
            wsgi=False):
        self.is_wsgi = bool(wsgi)
        self.opts = opts
        self.embedded = embedded
        self.state_callback = None
        self.start_failure_callback = None
        try:
            self.max_cover_width, self.max_cover_height = \
                        map(int, self.opts.max_cover.split('x'))
        except:
            self.max_cover_width = 1200
            self.max_cover_height = 1600
        path = P('content_server')
        self.build_time = fromtimestamp(os.stat(path).st_mtime)
        self.default_cover = open(P('content_server/m/img/default_cover.jpg'), 'rb').read()
        if not opts.url_prefix:
            opts.url_prefix = ''


        cherrypy.engine.bonjour.ip_address = listen_on
        cherrypy.engine.bonjour.port = opts.port
        cherrypy.engine.bonjour.prefix = opts.url_prefix

        self.last_lang = "en"
        self.all_langs = dict(get_all_translators())
        cherrypy.request.hooks.attach('before_handler', self.update_lang)
        cherrypy.request.hooks.attach('before_handler', self.load_user)
        #cherrypy.request.hooks.attach('on_end_resource', self.save_session)

        #cherrypy.tools.authenticate = cherrypy.Tool('before_handler', self.load_user)
        #cherrypy.tools.session = cherrypy.Tool('on_end_resource', self.save_session)

        Cache.__init__(self)

        self.set_database(db)

        st = 1 if opts.develop else 1

        cherrypy.config.update({
            'log.screen'             : opts.develop,
            'engine.autoreload_on'   : getattr(opts,
                                        'auto_reload', False),
            'tools.log_headers.on'   : opts.develop,
            'tools.encode.encoding'  : 'UTF-8',
            'checker.on'             : opts.develop,
            'request.show_tracebacks': show_tracebacks,
            'server.socket_host'     : listen_on,
            'server.socket_port'     : opts.port,
            'server.socket_timeout'  : opts.timeout,  # seconds
            'server.thread_pool'     : opts.thread_pool,  # number of threads
            'server.shutdown_timeout': st,  # minutes
            'tools.sessions.on' : True,
            #'tools.sessions.storage_type': 'ram',
            'tools.sessions.timeout': 60000, # Session times out after 60 minutes
            'tools.sessions.storage_type': "file",
            'tools.sessions.storage_path': "/data/tmp/cherrypy/",
            'SOCIAL_AUTH_USER_MODEL': 'calibre.library.server.auth.FuckUser',
            'SOCIAL_AUTH_LOGIN_URL': '/auth/',
            'SOCIAL_AUTH_LOGIN_REDIRECT_URL': '/',
            'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
                'social.backends.douban.DoubanOAuth',
                'social.backends.douban.DoubanOAuth2',
            ),
            'SOCIAL_AUTH_DOUBAN_OAUTH2_KEY': '052c9ac15e9870500f85d0441bc950f0',
            'SOCIAL_AUTH_DOUBAN_OAUTH2_SECRET': '3b524f1487999fc6',
        });
        cherrypy.tools.jinja2env = build_jinja2_env()
        if embedded or wsgi:
            cherrypy.config.update({'engine.SIGHUP'          : None,
                                    'engine.SIGTERM'         : None,})
        self.config = {}
        self.is_running = False
        self.exception = None
        auth_controller = None
        self.users_dict = {}

        if not wsgi:
            self.setup_loggers()
            cherrypy.engine.bonjour.subscribe()
            self.config['global'] = {
                'tools.gzip.on'        : True,
                'tools.gzip.mime_types': ['text/html', 'text/plain',
                    'text/xml', 'text/javascript', 'text/css'],
            }

            if opts.username and opts.password:
                self.users_dict[opts.username.strip()] = opts.password.strip()
                auth_controller = AuthController('Your calibre library',
                        self.users_dict)

        self.__dispatcher__ = DispatchController(self.opts.url_prefix,
                wsgi=wsgi, auth_controller=auth_controller)
        for x in self.__class__.__bases__:
            if hasattr(x, 'add_routes'):
                x.__init__(self)
                x.add_routes(self, self.__dispatcher__)
        root_conf = self.config.get('/', {})
        root_conf['request.dispatch'] = self.__dispatcher__.dispatcher
        self.config['/'] = root_conf