Skip to content

Commit

Permalink
Refactored web.py to shrink size of file
Browse files Browse the repository at this point in the history
  • Loading branch information
OzzieIsaacs committed Apr 26, 2022
1 parent 47414ad commit e7464f2
Show file tree
Hide file tree
Showing 27 changed files with 639 additions and 581 deletions.
85 changes: 23 additions & 62 deletions cps/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,32 +23,22 @@
import os
import mimetypes

from babel import Locale as LC
from babel import negotiate_locale
from babel.core import UnknownLocaleError
from flask import request, g
from flask import Flask
from .MyLoginManager import MyLoginManager
from flask_babel import Babel
from flask_principal import Principal

from . import config_sql
from . import logger
from . import cache_buster
from .cli import CliParameter
from .constants import CONFIG_DIR
from . import ub, db
from .reverseproxy import ReverseProxied
from .server import WebServer
from .dep_check import dependency_check
from . import services
from .updater import Updater

try:
import lxml
lxml_present = True
except ImportError:
lxml_present = False
from .babel import babel, BABEL_TRANSLATIONS
from . import config_sql
from . import logger
from . import cache_buster
from . import ub, db

try:
from flask_wtf.csrf import CSRFProtect
Expand Down Expand Up @@ -78,6 +68,8 @@
mimetypes.add_type('text/css', '.css')
mimetypes.add_type('text/javascript; charset=UTF-8', '.js')

log = logger.create()

app = Flask(__name__)
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
Expand All @@ -86,14 +78,8 @@
WTF_CSRF_SSL_STRICT=False
)


lm = MyLoginManager()

babel = Babel()
_BABEL_TRANSLATIONS = set()

log = logger.create()

config = config_sql._ConfigSQL()

cli_param = CliParameter()
Expand All @@ -120,9 +106,8 @@ def create_app():

cli_param.init()

ub.init_db(os.path.join(CONFIG_DIR, "app.db"), cli_param.user_credentials)
ub.init_db(cli_param.settings_path, cli_param.user_credentials)

# ub.init_db(os.path.join(CONFIG_DIR, "app.db"))
# pylint: disable=no-member
config_sql.load_configuration(config, ub.session, cli_param)

Expand All @@ -139,26 +124,26 @@ def create_app():

if sys.version_info < (3, 0):
log.info(
'*** Python2 is EOL since end of 2019, this version of Calibre-Web is no longer supporting Python2, please update your installation to Python3 ***')
'*** Python2 is EOL since end of 2019, this version of Calibre-Web is no longer supporting Python2, '
'please update your installation to Python3 ***')
print(
'*** Python2 is EOL since end of 2019, this version of Calibre-Web is no longer supporting Python2, please update your installation to Python3 ***')
'*** Python2 is EOL since end of 2019, this version of Calibre-Web is no longer supporting Python2, '
'please update your installation to Python3 ***')
web_server.stop(True)
sys.exit(5)
if not lxml_present:
log.info('*** "lxml" is needed for calibre-web to run. Please install it using pip: "pip install lxml" ***')
print('*** "lxml" is needed for calibre-web to run. Please install it using pip: "pip install lxml" ***')
web_server.stop(True)
sys.exit(6)
if not wtf_present:
log.info('*** "flask-WTF" is needed for calibre-web to run. Please install it using pip: "pip install flask-WTF" ***')
print('*** "flask-WTF" is needed for calibre-web to run. Please install it using pip: "pip install flask-WTF" ***')
log.info('*** "flask-WTF" is needed for calibre-web to run. '
'Please install it using pip: "pip install flask-WTF" ***')
print('*** "flask-WTF" is needed for calibre-web to run. '
'Please install it using pip: "pip install flask-WTF" ***')
web_server.stop(True)
sys.exit(7)
for res in dependency_check() + dependency_check(True):
log.info('*** "{}" version does not fit the requirements. Should: {}, Found: {}, please consider installing required version ***'
.format(res['name'],
res['target'],
res['found']))
log.info('*** "{}" version does not fit the requirements. '
'Should: {}, Found: {}, please consider installing required version ***'
.format(res['name'],
res['target'],
res['found']))
app.wsgi_app = ReverseProxied(app.wsgi_app)

if os.environ.get('FLASK_DEBUG'):
Expand All @@ -172,8 +157,8 @@ def create_app():
web_server.init_app(app, config)

babel.init_app(app)
_BABEL_TRANSLATIONS.update(str(item) for item in babel.list_translations())
_BABEL_TRANSLATIONS.add('en')
BABEL_TRANSLATIONS.update(str(item) for item in babel.list_translations())
BABEL_TRANSLATIONS.add('en')

if services.ldap:
services.ldap.init_app(app, config)
Expand All @@ -185,27 +170,3 @@ def create_app():
return app


@babel.localeselector
def get_locale():
# if a user is logged in, use the locale from the user settings
user = getattr(g, 'user', None)
if user is not None and hasattr(user, "locale"):
if user.name != 'Guest': # if the account is the guest account bypass the config lang settings
return user.locale

preferred = list()
if request.accept_languages:
for x in request.accept_languages.values():
try:
preferred.append(str(LC.parse(x.replace('-', '_'))))
except (UnknownLocaleError, ValueError) as e:
log.debug('Could not parse locale "%s": %s', x, e)

return negotiate_locale(preferred or ['en'], _BABEL_TRANSLATIONS)


'''@babel.timezoneselector
def get_timezone():
user = getattr(g, 'user', None)
return user.timezone if user else None'''

2 changes: 1 addition & 1 deletion cps/about.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
SQLite=sqlite3.sqlite_version,
)
_VERSIONS.update(ret)
_VERSIONS.update(uploader.get_versions(False))
_VERSIONS.update(uploader.get_versions())


def collect_stats():
Expand Down
22 changes: 10 additions & 12 deletions cps/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,25 @@
from datetime import datetime, timedelta, time
from functools import wraps

from babel import Locale
from babel.dates import format_datetime, format_time, format_timedelta
from flask import Blueprint, flash, redirect, url_for, abort, request, make_response, send_from_directory, g, Response
from flask_login import login_required, current_user, logout_user, confirm_login
from flask_babel import gettext as _
from flask_babel import get_locale, format_time, format_datetime, format_timedelta
from flask import session as flask_session
from sqlalchemy import and_
from sqlalchemy.orm.attributes import flag_modified
from sqlalchemy.exc import IntegrityError, OperationalError, InvalidRequestError
from sqlalchemy.sql.expression import func, or_, text

from . import constants, logger, helper, services, cli
from . import db, calibre_db, ub, web_server, get_locale, config, updater_thread, babel, gdriveutils, \
from . import db, calibre_db, ub, web_server, config, updater_thread, babel, gdriveutils, \
kobo_sync_status, schedule
from .helper import check_valid_domain, send_test_mail, reset_password, generate_password_hash, check_email, \
valid_email, check_username, update_thumbnail_cache
from .gdriveutils import is_gdrive_ready, gdrive_support
from .render_template import render_title_template, get_sidebar_config
from .services.worker import WorkerThread
from . import debug_info, _BABEL_TRANSLATIONS
from . import debug_info, BABEL_TRANSLATIONS


log = logger.create()
Expand Down Expand Up @@ -205,9 +204,9 @@ def admin():

all_user = ub.session.query(ub.User).all()
email_settings = config.get_mail_settings()
schedule_time = format_time(time(hour=config.schedule_start_time), format="short", locale=locale)
schedule_time = format_time(time(hour=config.schedule_start_time), format="short")
t = timedelta(hours=config.schedule_duration // 60, minutes=config.schedule_duration % 60)
schedule_duration = format_timedelta(t, format="short", threshold=.99, locale=locale)
schedule_duration = format_timedelta(t, threshold=.99)

return render_title_template("admin.html", allUser=all_user, email=email_settings, config=config, commit=commit,
feature_support=feature_support, schedule_time=schedule_time,
Expand Down Expand Up @@ -279,7 +278,7 @@ def view_configuration():
def edit_user_table():
visibility = current_user.view_settings.get('useredit', {})
languages = calibre_db.speaking_language()
translations = babel.list_translations() + [Locale('en')]
translations = [LC('en')] + babel.list_translations()
all_user = ub.session.query(ub.User)
tags = calibre_db.session.query(db.Tags)\
.join(db.books_tags_link)\
Expand Down Expand Up @@ -398,7 +397,7 @@ def delete_user():
@login_required
@admin_required
def table_get_locale():
locale = babel.list_translations() + [Locale('en')]
locale = [LC('en')] + babel.list_translations()
ret = list()
current_locale = get_locale()
for loc in locale:
Expand Down Expand Up @@ -499,7 +498,7 @@ def edit_list_user(param):
elif param == 'locale':
if user.name == "Guest":
raise Exception(_("Guest's Locale is determined automatically and can't be set"))
if vals['value'] in _BABEL_TRANSLATIONS:
if vals['value'] in BABEL_TRANSLATIONS:
user.locale = vals['value']
else:
raise Exception(_("No Valid Locale Given"))
Expand Down Expand Up @@ -1668,12 +1667,11 @@ def edit_scheduledtasks():
time_field = list()
duration_field = list()

locale = get_locale()
for n in range(24):
time_field.append((n , format_time(time(hour=n), format="short", locale=locale)))
time_field.append((n , format_time(time(hour=n), format="short",)))
for n in range(5, 65, 5):
t = timedelta(hours=n // 60, minutes=n % 60)
duration_field.append((n, format_timedelta(t, format="short", threshold=.99, locale=locale)))
duration_field.append((n, format_timedelta(t, threshold=.9)))

return render_title_template("schedule_edit.html", config=content, starttime=time_field, duration=duration_field, title=_(u"Edit Scheduled Tasks Settings"))

Expand Down
30 changes: 30 additions & 0 deletions cps/babel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from babel import Locale as LC
from babel import negotiate_locale
from flask_babel import Babel
from babel.core import UnknownLocaleError
from flask import request, g

from . import logger

log = logger.create()

babel = Babel()
BABEL_TRANSLATIONS = set()

@babel.localeselector
def get_locale():
# if a user is logged in, use the locale from the user settings
user = getattr(g, 'user', None)
if user is not None and hasattr(user, "locale"):
if user.name != 'Guest': # if the account is the guest account bypass the config lang settings
return user.locale

preferred = list()
if request.accept_languages:
for x in request.accept_languages.values():
try:
preferred.append(str(LC.parse(x.replace('-', '_'))))
except (UnknownLocaleError, ValueError) as e:
log.debug('Could not parse locale "%s": %s', x, e)

return negotiate_locale(preferred or ['en'], BABEL_TRANSLATIONS)
2 changes: 1 addition & 1 deletion cps/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
from sqlalchemy.ext.associationproxy import association_proxy
from flask_login import current_user
from flask_babel import gettext as _
from flask_babel import get_locale
from flask import flash

from . import logger, ub, isoLanguages
Expand Down Expand Up @@ -898,7 +899,6 @@ def get_search_results(self, term, config, offset=None, order=None, limit=None,

# Creates for all stored languages a translated speaking name in the array for the UI
def speaking_language(self, languages=None, return_all_languages=False, with_count=False, reverse_order=False):
from . import get_locale

if with_count:
if not languages:
Expand Down
3 changes: 2 additions & 1 deletion cps/editbooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,12 @@
from flask import Blueprint, request, flash, redirect, url_for, abort, Markup, Response
from flask_babel import gettext as _
from flask_babel import lazy_gettext as N_
from flask_babel import get_locale
from flask_login import current_user, login_required
from sqlalchemy.exc import OperationalError, IntegrityError
# from sqlite3 import OperationalError as sqliteOperationalError
from . import constants, logger, isoLanguages, gdriveutils, uploader, helper, kobo_sync_status
from . import config, get_locale, ub, db
from . import config, ub, db
from . import calibre_db
from .services.worker import WorkerThread
from .tasks.upload import TaskUpload
Expand Down
1 change: 1 addition & 0 deletions cps/error_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import traceback

from flask import render_template
from werkzeug.exceptions import default_exceptions
try:
Expand Down
5 changes: 0 additions & 5 deletions cps/gdriveutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -680,8 +680,3 @@ def get_error_text(client_secrets=None):
return 'Callback url (redirect url) is missing in client_secrets.json'
if client_secrets:
client_secrets.update(filedata['web'])


def get_versions():
return { # 'six': six_version,
'httplib2': httplib2_version}
Loading

0 comments on commit e7464f2

Please sign in to comment.