Code cosmetics

This commit is contained in:
Ozzieisaacs 2022-05-21 21:52:59 +01:00
parent 034d57134d
commit 4ea80e9810
9 changed files with 52 additions and 44 deletions

View File

@ -160,7 +160,7 @@ def shutdown():
return json.dumps(showtext), 400 return json.dumps(showtext), 400
# method is available without login and not protected by CSRF to make it easy reachable, is per default switched of # method is available without login and not protected by CSRF to make it easy reachable, is per default switched off
# needed for docker applications, as changes on metadata.db from host are not visible to application # needed for docker applications, as changes on metadata.db from host are not visible to application
@admi.route("/reconnect", methods=['GET']) @admi.route("/reconnect", methods=['GET'])
def reconnect(): def reconnect():
@ -615,7 +615,8 @@ def load_dialogtexts(element_id):
elif element_id == "db_submit": elif element_id == "db_submit":
texts["main"] = _('Are you sure you want to change Calibre library location?') texts["main"] = _('Are you sure you want to change Calibre library location?')
elif element_id == "admin_refresh_cover_cache": elif element_id == "admin_refresh_cover_cache":
texts["main"] = _('Calibre-Web will search for updated Covers and update Cover Thumbnails, this may take a while?') texts["main"] = _('Calibre-Web will search for updated Covers '
'and update Cover Thumbnails, this may take a while?')
elif element_id == "btnfullsync": elif element_id == "btnfullsync":
texts["main"] = _("Are you sure you want delete Calibre-Web's sync database " texts["main"] = _("Are you sure you want delete Calibre-Web's sync database "
"to force a full sync with your Kobo Reader?") "to force a full sync with your Kobo Reader?")
@ -746,6 +747,7 @@ def edit_restriction(res_type, user_id):
ub.session_commit("Changed denied columns of user {} to {}".format(usr.name, usr.denied_column_value)) ub.session_commit("Changed denied columns of user {} to {}".format(usr.name, usr.denied_column_value))
return "" return ""
@admi.route("/ajax/addrestriction/<int:res_type>", methods=['POST']) @admi.route("/ajax/addrestriction/<int:res_type>", methods=['POST'])
@login_required @login_required
@admin_required @admin_required
@ -1084,7 +1086,7 @@ def _configuration_gdrive_helper(to_save):
gdrive_secrets['redirect_uris'][0] gdrive_secrets['redirect_uris'][0]
) )
# always show google drive settings, but in case of error deny support # always show Google Drive settings, but in case of error deny support
new_gdrive_value = (not gdrive_error) and ("config_use_google_drive" in to_save) new_gdrive_value = (not gdrive_error) and ("config_use_google_drive" in to_save)
if config.config_use_google_drive and not new_gdrive_value: if config.config_use_google_drive and not new_gdrive_value:
config.config_google_drive_watch_changes_response = {} config.config_google_drive_watch_changes_response = {}
@ -1837,7 +1839,7 @@ def _handle_new_user(to_save, content, languages, translations, kobo_support):
log.info("Missing entries on new user") log.info("Missing entries on new user")
raise Exception(_(u"Please fill out all fields!")) raise Exception(_(u"Please fill out all fields!"))
content.email = check_email(to_save["email"]) content.email = check_email(to_save["email"])
# Query User name, if not existing, change # Query username, if not existing, change
content.name = check_username(to_save["name"]) content.name = check_username(to_save["name"])
if to_save.get("kindle_mail"): if to_save.get("kindle_mail"):
content.kindle_mail = valid_email(to_save["kindle_mail"]) content.kindle_mail = valid_email(to_save["kindle_mail"])
@ -1956,7 +1958,7 @@ def _handle_edit_user(to_save, content, languages, translations, kobo_support):
try: try:
if to_save.get("email", content.email) != content.email: if to_save.get("email", content.email) != content.email:
content.email = check_email(to_save["email"]) content.email = check_email(to_save["email"])
# Query User name, if not existing, change # Query username, if not existing, change
if to_save.get("name", content.name) != content.name: if to_save.get("name", content.name) != content.name:
if to_save.get("name") == "Guest": if to_save.get("name") == "Guest":
raise Exception(_("Guest Name can't be changed")) raise Exception(_("Guest Name can't be changed"))

View File

@ -32,8 +32,10 @@ def get_locale():
def get_user_locale_language(user_language): def get_user_locale_language(user_language):
return Locale.parse(user_language).get_language_name(get_locale()) return Locale.parse(user_language).get_language_name(get_locale())
def get_available_locale(): def get_available_locale():
return [Locale('en')] + babel.list_translations() return [Locale('en')] + babel.list_translations()
def get_available_translations(): def get_available_translations():
return set(str(item) for item in get_available_locale()) return set(str(item) for item in get_available_locale())

View File

@ -59,11 +59,11 @@ def init_cache_busting(app):
log.debug('Finished computing cache-busting values') log.debug('Finished computing cache-busting values')
def bust_filename(filename): def bust_filename(file_name):
return hash_table.get(filename, "") return hash_table.get(file_name, "")
def unbust_filename(filename): def unbust_filename(file_name):
return filename.split("?", 1)[0] return file_name.split("?", 1)[0]
@app.url_defaults @app.url_defaults
# pylint: disable=unused-variable # pylint: disable=unused-variable
@ -76,11 +76,11 @@ def init_cache_busting(app):
if file_hash: if file_hash:
values["q"] = file_hash values["q"] = file_hash
def debusting_static_view(filename): def debusting_static_view(file_name):
""" """
Serve a request for a static file having a busted name. Serve a request for a static file having a busted name.
""" """
return original_static_view(filename=unbust_filename(filename)) return original_static_view(filename=unbust_filename(file_name))
# Replace the default static file view with our debusting view. # Replace the default static file view with our debusting view.
original_static_view = app.view_functions["static"] original_static_view = app.view_functions["static"]

View File

@ -26,26 +26,28 @@ from .constants import STABLE_VERSION as _STABLE_VERSION
from .constants import NIGHTLY_VERSION as _NIGHTLY_VERSION from .constants import NIGHTLY_VERSION as _NIGHTLY_VERSION
from .constants import DEFAULT_SETTINGS_FILE, DEFAULT_GDRIVE_FILE from .constants import DEFAULT_SETTINGS_FILE, DEFAULT_GDRIVE_FILE
def version_info(): def version_info():
if _NIGHTLY_VERSION[1].startswith('$Format'): if _NIGHTLY_VERSION[1].startswith('$Format'):
return "Calibre-Web version: %s - unkown git-clone" % _STABLE_VERSION['version'] return "Calibre-Web version: %s - unkown git-clone" % _STABLE_VERSION['version']
return "Calibre-Web version: %s -%s" % (_STABLE_VERSION['version'], _NIGHTLY_VERSION[1]) return "Calibre-Web version: %s -%s" % (_STABLE_VERSION['version'], _NIGHTLY_VERSION[1])
class CliParameter(object): class CliParameter(object):
def init(self): def init(self):
self.arg_parser() self.arg_parser()
def arg_parser(self): def arg_parser(self):
parser = argparse.ArgumentParser(description='Calibre Web is a web app' parser = argparse.ArgumentParser(description='Calibre Web is a web app providing '
' providing a interface for browsing, reading and downloading eBooks\n', 'a interface for browsing, reading and downloading eBooks\n',
prog='cps.py') prog='cps.py')
parser.add_argument('-p', metavar='path', help='path and name to settings db, e.g. /opt/cw.db') parser.add_argument('-p', metavar='path', help='path and name to settings db, e.g. /opt/cw.db')
parser.add_argument('-g', metavar='path', help='path and name to gdrive db, e.g. /opt/gd.db') parser.add_argument('-g', metavar='path', help='path and name to gdrive db, e.g. /opt/gd.db')
parser.add_argument('-c', metavar='path', parser.add_argument('-c', metavar='path', help='path and name to SSL certfile, e.g. /opt/test.cert, '
help='path and name to SSL certfile, e.g. /opt/test.cert, works only in combination with keyfile') 'works only in combination with keyfile')
parser.add_argument('-k', metavar='path', parser.add_argument('-k', metavar='path', help='path and name to SSL keyfile, e.g. /opt/test.key, '
help='path and name to SSL keyfile, e.g. /opt/test.key, works only in combination with certfile') 'works only in combination with certfile')
parser.add_argument('-v', '--version', action='version', help='Shows version number and exits Calibre-Web', parser.add_argument('-v', '--version', action='version', help='Shows version number and exits Calibre-Web',
version=version_info()) version=version_info())
parser.add_argument('-i', metavar='ip-address', help='Server IP-Address to listen') parser.add_argument('-i', metavar='ip-address', help='Server IP-Address to listen')
@ -67,7 +69,6 @@ class CliParameter(object):
if os.path.isdir(self.gd_path): if os.path.isdir(self.gd_path):
self.gd_path = os.path.join(self.gd_path, DEFAULT_GDRIVE_FILE) self.gd_path = os.path.join(self.gd_path, DEFAULT_GDRIVE_FILE)
# handle and check parameter for ssl encryption # handle and check parameter for ssl encryption
self.certfilepath = None self.certfilepath = None
self.keyfilepath = None self.keyfilepath = None
@ -96,7 +97,7 @@ class CliParameter(object):
self.keyfilepath = "" self.keyfilepath = ""
# dry run updater # dry run updater
self.dry_run =args.d or None self.dry_run = args.d or None
# enable reconnect endpoint for docker database reconnect # enable reconnect endpoint for docker database reconnect
self.reconnect_enable = args.r or os.environ.get("CALIBRE_RECONNECT", None) self.reconnect_enable = args.r or os.environ.get("CALIBRE_RECONNECT", None)
# load covers from localhost # load covers from localhost
@ -112,7 +113,7 @@ class CliParameter(object):
else: else:
socket.inet_pton(socket.AF_INET, self.ip_address) socket.inet_pton(socket.AF_INET, self.ip_address)
else: else:
# on windows python < 3.4, inet_pton is not available # on Windows python < 3.4, inet_pton is not available
# inet_atom only handles IPv4 addresses # inet_atom only handles IPv4 addresses
socket.inet_aton(self.ip_address) socket.inet_aton(self.ip_address)
except socket.error as err: except socket.error as err:

View File

@ -35,6 +35,7 @@ from . import constants, logger
log = logger.create() log = logger.create()
_Base = declarative_base() _Base = declarative_base()
class _Flask_Settings(_Base): class _Flask_Settings(_Base):
__tablename__ = 'flask_settings' __tablename__ = 'flask_settings'
@ -67,7 +68,7 @@ class _Settings(_Base):
config_external_port = Column(Integer, default=constants.DEFAULT_PORT) config_external_port = Column(Integer, default=constants.DEFAULT_PORT)
config_certfile = Column(String) config_certfile = Column(String)
config_keyfile = Column(String) config_keyfile = Column(String)
config_trustedhosts = Column(String,default='') config_trustedhosts = Column(String, default='')
config_calibre_web_title = Column(String, default=u'Calibre-Web') config_calibre_web_title = Column(String, default=u'Calibre-Web')
config_books_per_page = Column(Integer, default=60) config_books_per_page = Column(Integer, default=60)
config_random_books = Column(Integer, default=4) config_random_books = Column(Integer, default=4)
@ -123,7 +124,7 @@ class _Settings(_Base):
config_ldap_key_path = Column(String, default="") config_ldap_key_path = Column(String, default="")
config_ldap_dn = Column(String, default='dc=example,dc=org') config_ldap_dn = Column(String, default='dc=example,dc=org')
config_ldap_user_object = Column(String, default='uid=%s') config_ldap_user_object = Column(String, default='uid=%s')
config_ldap_member_user_object = Column(String, default='') # config_ldap_member_user_object = Column(String, default='')
config_ldap_openldap = Column(Boolean, default=True) config_ldap_openldap = Column(Boolean, default=True)
config_ldap_group_object_filter = Column(String, default='(&(objectclass=posixGroup)(cn=%s))') config_ldap_group_object_filter = Column(String, default='(&(objectclass=posixGroup)(cn=%s))')
config_ldap_group_members_field = Column(String, default='memberUid') config_ldap_group_members_field = Column(String, default='memberUid')
@ -171,7 +172,6 @@ class _ConfigSQL(object):
self.config_converterpath = autodetect_calibre_binary() self.config_converterpath = autodetect_calibre_binary()
if self.config_kepubifypath == None: # pylint: disable=access-member-before-definition if self.config_kepubifypath == None: # pylint: disable=access-member-before-definition
change = True change = True
self.config_kepubifypath = autodetect_kepubify_binary() self.config_kepubifypath = autodetect_kepubify_binary()
@ -257,14 +257,14 @@ class _ConfigSQL(object):
return logger.get_level_name(self.config_log_level) return logger.get_level_name(self.config_log_level)
def get_mail_settings(self): def get_mail_settings(self):
return {k:v for k, v in self.__dict__.items() if k.startswith('mail_')} return {k: v for k, v in self.__dict__.items() if k.startswith('mail_')}
def get_mail_server_configured(self): def get_mail_server_configured(self):
return bool((self.mail_server != constants.DEFAULT_MAIL_SERVER and self.mail_server_type == 0) return bool((self.mail_server != constants.DEFAULT_MAIL_SERVER and self.mail_server_type == 0)
or (self.mail_gmail_token != {} and self.mail_server_type == 1)) or (self.mail_gmail_token != {} and self.mail_server_type == 1))
def get_scheduled_task_settings(self): def get_scheduled_task_settings(self):
return {k:v for k, v in self.__dict__.items() if k.startswith('schedule_')} return {k: v for k, v in self.__dict__.items() if k.startswith('schedule_')}
def set_from_dictionary(self, dictionary, field, convertor=None, default=None, encode=None): def set_from_dictionary(self, dictionary, field, convertor=None, default=None, encode=None):
"""Possibly updates a field of this object. """Possibly updates a field of this object.
@ -301,7 +301,7 @@ class _ConfigSQL(object):
return storage return storage
def load(self): def load(self):
'''Load all configuration values from the underlying storage.''' """Load all configuration values from the underlying storage."""
s = self._read_from_storage() # type: _Settings s = self._read_from_storage() # type: _Settings
for k, v in s.__dict__.items(): for k, v in s.__dict__.items():
if k[0] != '_': if k[0] != '_':
@ -334,7 +334,7 @@ class _ConfigSQL(object):
self._session.rollback() self._session.rollback()
def save(self): def save(self):
'''Apply all configuration values to the underlying storage.''' """Apply all configuration values to the underlying storage."""
s = self._read_from_storage() # type: _Settings s = self._read_from_storage() # type: _Settings
for k, v in self.__dict__.items(): for k, v in self.__dict__.items():
@ -369,6 +369,7 @@ class _ConfigSQL(object):
except AttributeError: except AttributeError:
pass pass
def _migrate_table(session, orm_class): def _migrate_table(session, orm_class):
changed = False changed = False
@ -462,6 +463,7 @@ def load_configuration(conf, session, cli):
conf.init_config(session, cli) conf.init_config(session, cli)
# return conf # return conf
def get_flask_session_key(_session): def get_flask_session_key(_session):
flask_settings = _session.query(_Flask_Settings).one_or_none() flask_settings = _session.query(_Flask_Settings).one_or_none()
if flask_settings == None: if flask_settings == None:

View File

@ -54,10 +54,9 @@ def get_calibre_version():
def get_unrar_version(): def get_unrar_version():
unrar_version = _get_command_version(config.config_rarfile_location, r'UNRAR.*\d') unrar_version = _get_command_version(config.config_rarfile_location, r'UNRAR.*\d')
if unrar_version == "not installed": if unrar_version == "not installed":
unrar_version = _get_command_version(config.config_rarfile_location, r'unrar.*\d','-V') unrar_version = _get_command_version(config.config_rarfile_location, r'unrar.*\d', '-V')
return unrar_version return unrar_version
def get_kepubify_version(): def get_kepubify_version():
return _get_command_version(config.config_kepubifypath, r'kepubify\s','--version') return _get_command_version(config.config_kepubifypath, r'kepubify\s', '--version')

View File

@ -32,6 +32,7 @@ from .about import collect_stats
log = logger.create() log = logger.create()
def assemble_logfiles(file_name): def assemble_logfiles(file_name):
log_list = sorted(glob.glob(file_name + '*'), reverse=True) log_list = sorted(glob.glob(file_name + '*'), reverse=True)
wfd = BytesIO() wfd = BytesIO()

View File

@ -42,7 +42,7 @@ def load_dependencies(optional=False):
res = re.match(r'(.*?)([<=>\s]+)([\d\.]+),?\s?([<=>\s]+)?([\d\.]+)?', line.strip()) res = re.match(r'(.*?)([<=>\s]+)([\d\.]+),?\s?([<=>\s]+)?([\d\.]+)?', line.strip())
try: try:
if getattr(sys, 'frozen', False): if getattr(sys, 'frozen', False):
dep_version = exe_deps[res.group(1).lower().replace('_','-')] dep_version = exe_deps[res.group(1).lower().replace('_', '-')]
else: else:
if importlib: if importlib:
dep_version = version(res.group(1)) dep_version = version(res.group(1))

View File

@ -54,7 +54,6 @@ class _Logger(logging.Logger):
else: else:
self.error(message, *args, **kwargs) self.error(message, *args, **kwargs)
def debug_no_auth(self, message, *args, **kwargs): def debug_no_auth(self, message, *args, **kwargs):
message = message.strip("\r\n") message = message.strip("\r\n")
if message.startswith("send: AUTH"): if message.startswith("send: AUTH"):
@ -66,6 +65,7 @@ class _Logger(logging.Logger):
def get(name=None): def get(name=None):
return logging.getLogger(name) return logging.getLogger(name)
def create(): def create():
parent_frame = inspect.stack(0)[1] parent_frame = inspect.stack(0)[1]
if hasattr(parent_frame, 'frame'): if hasattr(parent_frame, 'frame'):
@ -75,9 +75,11 @@ def create():
parent_module = inspect.getmodule(parent_frame) parent_module = inspect.getmodule(parent_frame)
return get(parent_module.__name__) return get(parent_module.__name__)
def is_debug_enabled(): def is_debug_enabled():
return logging.root.level <= logging.DEBUG return logging.root.level <= logging.DEBUG
def is_info_enabled(logger): def is_info_enabled(logger):
return logging.getLogger(logger).level <= logging.INFO return logging.getLogger(logger).level <= logging.INFO
@ -114,10 +116,10 @@ def get_accesslogfile(log_file):
def setup(log_file, log_level=None): def setup(log_file, log_level=None):
''' """
Configure the logging output. Configure the logging output.
May be called multiple times. May be called multiple times.
''' """
log_level = log_level or DEFAULT_LOG_LEVEL log_level = log_level or DEFAULT_LOG_LEVEL
logging.setLoggerClass(_Logger) logging.setLoggerClass(_Logger)
logging.getLogger(__package__).setLevel(log_level) logging.getLogger(__package__).setLevel(log_level)
@ -127,7 +129,7 @@ def setup(log_file, log_level=None):
# avoid spamming the log with debug messages from libraries # avoid spamming the log with debug messages from libraries
r.setLevel(log_level) r.setLevel(log_level)
# Otherwise name get's destroyed on windows # Otherwise, name gets destroyed on Windows
if log_file != LOG_TO_STDERR and log_file != LOG_TO_STDOUT: if log_file != LOG_TO_STDERR and log_file != LOG_TO_STDOUT:
log_file = _absolute_log_file(log_file, DEFAULT_LOG_FILE) log_file = _absolute_log_file(log_file, DEFAULT_LOG_FILE)
@ -164,9 +166,9 @@ def setup(log_file, log_level=None):
def create_access_log(log_file, log_name, formatter): def create_access_log(log_file, log_name, formatter):
''' """
One-time configuration for the web server's access log. One-time configuration for the web server's access log.
''' """
log_file = _absolute_log_file(log_file, DEFAULT_ACCESS_LOG) log_file = _absolute_log_file(log_file, DEFAULT_ACCESS_LOG)
logging.debug("access log: %s", log_file) logging.debug("access log: %s", log_file)
@ -183,8 +185,7 @@ def create_access_log(log_file, log_name, formatter):
file_handler.setFormatter(formatter) file_handler.setFormatter(formatter)
access_log.addHandler(file_handler) access_log.addHandler(file_handler)
return access_log, \ return access_log, "" if _absolute_log_file(log_file, DEFAULT_ACCESS_LOG) == DEFAULT_ACCESS_LOG else log_file
"" if _absolute_log_file(log_file, DEFAULT_ACCESS_LOG) == DEFAULT_ACCESS_LOG else log_file
# Enable logging of smtp lib debug output # Enable logging of smtp lib debug output