1
0
mirror of https://github.com/janeczku/calibre-web synced 2024-12-26 01:50:31 +00:00

Fix restart server

Some code cosmetics
This commit is contained in:
Ozzie Isaacs 2021-03-14 14:29:40 +01:00
parent 9b80c84794
commit f52fa41439
6 changed files with 126 additions and 88 deletions

View File

@ -384,14 +384,14 @@ class Custom_Columns(Base):
class AlchemyEncoder(json.JSONEncoder): class AlchemyEncoder(json.JSONEncoder):
def default(self, obj): def default(self, o):
if isinstance(obj.__class__, DeclarativeMeta): if isinstance(o.__class__, DeclarativeMeta):
# an SQLAlchemy class # an SQLAlchemy class
fields = {} fields = {}
for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']: for field in [x for x in dir(o) if not x.startswith('_') and x != 'metadata']:
if field == 'books': if field == 'books':
continue continue
data = obj.__getattribute__(field) data = o.__getattribute__(field)
try: try:
if isinstance(data, str): if isinstance(data, str):
data = data.replace("'", "\'") data = data.replace("'", "\'")
@ -411,12 +411,12 @@ class AlchemyEncoder(json.JSONEncoder):
else: else:
json.dumps(data) json.dumps(data)
fields[field] = data fields[field] = data
except: except Exception:
fields[field] = "" fields[field] = ""
# a json-encodable dict # a json-encodable dict
return fields return fields
return json.JSONEncoder.default(self, obj) return json.JSONEncoder.default(self, o)
class CalibreDB(): class CalibreDB():
@ -563,8 +563,8 @@ class CalibreDB():
def get_book_by_uuid(self, book_uuid): def get_book_by_uuid(self, book_uuid):
return self.session.query(Books).filter(Books.uuid == book_uuid).first() return self.session.query(Books).filter(Books.uuid == book_uuid).first()
def get_book_format(self, book_id, format): def get_book_format(self, book_id, file_format):
return self.session.query(Data).filter(Data.book == book_id).filter(Data.format == format).first() return self.session.query(Data).filter(Data.book == book_id).filter(Data.format == file_format).first()
# Language and content filters for displaying in the UI # Language and content filters for displaying in the UI
def common_filters(self, allow_show_archived=False): def common_filters(self, allow_show_archived=False):
@ -742,7 +742,7 @@ class CalibreDB():
if old_session: if old_session:
try: try:
old_session.close() old_session.close()
except: except Exception:
pass pass
if old_session.bind: if old_session.bind:
try: try:

View File

@ -138,7 +138,7 @@ class WebServer(object):
return sock, _readable_listen_address(*address) return sock, _readable_listen_address(*address)
@staticmethod @staticmethod
def _get_args_for_reloading(self): def _get_args_for_reloading():
"""Determine how the script was executed, and return the args needed """Determine how the script was executed, and return the args needed
to execute it again in a new process. to execute it again in a new process.
Code from https://github.com/pyload/pyload. Author GammaC0de, voulter Code from https://github.com/pyload/pyload. Author GammaC0de, voulter

View File

@ -1,8 +1,8 @@
body.serieslist.grid-view div.container-fluid > div > div.col-sm-10:before{ body.serieslist.grid-view div.container-fluid > div > div.col-sm-10::before {
display: none; display: none;
} }
.cover .badge{ .cover .badge {
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;
@ -10,15 +10,15 @@ body.serieslist.grid-view div.container-fluid > div > div.col-sm-10:before{
background-color: #cc7b19; background-color: #cc7b19;
border-radius: 0; border-radius: 0;
padding: 0 8px; padding: 0 8px;
box-shadow: 0 0 4px rgba(0, 0, 0, .6); box-shadow: 0 0 4px rgba(0, 0, 0, 0.6);
line-height: 24px; line-height: 24px;
} }
.cover { .cover {
box-shadow: 0 0 4px rgba(0, 0, 0, .6); box-shadow: 0 0 4px rgba(0, 0, 0, 0.6);
} }
.cover .read { .cover .read {
padding: 0px 0px; padding: 0 0;
line-height: 15px; line-height: 15px;
} }

View File

@ -114,7 +114,7 @@ $(document).ready(function() {
} }
}); });
function ConfirmDialog(id, dataValue, yesFn, noFn) { function confirmDialog(id, dataValue, yesFn, noFn) {
var $confirm = $("#GeneralDeleteModal"); var $confirm = $("#GeneralDeleteModal");
// var dataValue= e.data('value'); // target.data('value'); // var dataValue= e.data('value'); // target.data('value');
$confirm.modal('show'); $confirm.modal('show');
@ -481,7 +481,7 @@ $(function() {
}); });
$("#config_delete_kobo_token").click(function() { $("#config_delete_kobo_token").click(function() {
ConfirmDialog( confirmDialog(
$(this).attr('id'), $(this).attr('id'),
$(this).data('value'), $(this).data('value'),
function (value) { function (value) {
@ -509,7 +509,7 @@ $(function() {
}); });
$("#btndeluser").click(function() { $("#btndeluser").click(function() {
ConfirmDialog( confirmDialog(
$(this).attr('id'), $(this).attr('id'),
$(this).data('value'), $(this).data('value'),
function(value){ function(value){
@ -527,7 +527,7 @@ $(function() {
}); });
$("#delete_shelf").click(function() { $("#delete_shelf").click(function() {
ConfirmDialog( confirmDialog(
$(this).attr('id'), $(this).attr('id'),
$(this).data('value'), $(this).data('value'),
function(value){ function(value){

View File

@ -16,7 +16,7 @@
*/ */
/* exported TableActions, RestrictionActions, EbookActions, responseHandler */ /* exported TableActions, RestrictionActions, EbookActions, responseHandler */
/* global getPath, ConfirmDialog */ /* global getPath, confirmDialog */
var selections = []; var selections = [];
@ -210,7 +210,7 @@ $(function() {
striped: false striped: false
}); });
function domain_handle(domainId) { function domainHandle(domainId) {
$.ajax({ $.ajax({
method:"post", method:"post",
url: window.location.pathname + "/../../ajax/deletedomain", url: window.location.pathname + "/../../ajax/deletedomain",
@ -237,12 +237,12 @@ $(function() {
} }
$("#domain-allow-table").on("click-cell.bs.table", function (field, value, row, $element) { $("#domain-allow-table").on("click-cell.bs.table", function (field, value, row, $element) {
if (value === 2) { if (value === 2) {
ConfirmDialog("btndeletedomain", $element.id, domain_handle); confirmDialog("btndeletedomain", $element.id, domainHandle);
} }
}); });
$("#domain-deny-table").on("click-cell.bs.table", function (field, value, row, $element) { $("#domain-deny-table").on("click-cell.bs.table", function (field, value, row, $element) {
if (value === 2) { if (value === 2) {
ConfirmDialog("btndeletedomain", $element.id, domain_handle); confirmDialog("btndeletedomain", $element.id, domainHandle);
} }
}); });
@ -256,12 +256,12 @@ $(function() {
$("#h3").addClass("hidden"); $("#h3").addClass("hidden");
$("#h4").addClass("hidden"); $("#h4").addClass("hidden");
}); });
function startTable(type, user_id) { function startTable(type, userId) {
$("#restrict-elements-table").bootstrapTable({ $("#restrict-elements-table").bootstrapTable({
formatNoMatches: function () { formatNoMatches: function () {
return ""; return "";
}, },
url: getPath() + "/ajax/listrestriction/" + type + "/" + user_id, url: getPath() + "/ajax/listrestriction/" + type + "/" + userId,
rowStyle: function(row) { rowStyle: function(row) {
// console.log('Reihe :' + row + " Index :" + index); // console.log('Reihe :' + row + " Index :" + index);
if (row.id.charAt(0) === "a") { if (row.id.charAt(0) === "a") {
@ -275,13 +275,13 @@ $(function() {
$.ajax ({ $.ajax ({
type: "Post", type: "Post",
data: "id=" + row.id + "&type=" + row.type + "&Element=" + encodeURIComponent(row.Element), data: "id=" + row.id + "&type=" + row.type + "&Element=" + encodeURIComponent(row.Element),
url: getPath() + "/ajax/deleterestriction/" + type + "/" + user_id, url: getPath() + "/ajax/deleterestriction/" + type + "/" + userId,
async: true, async: true,
timeout: 900, timeout: 900,
success:function() { success:function() {
$.ajax({ $.ajax({
method:"get", method:"get",
url: getPath() + "/ajax/listrestriction/" + type + "/" + user_id, url: getPath() + "/ajax/listrestriction/" + type + "/" + userId,
async: true, async: true,
timeout: 900, timeout: 900,
success:function(data) { success:function(data) {
@ -297,7 +297,7 @@ $(function() {
$("#restrict-elements-table").removeClass("table-hover"); $("#restrict-elements-table").removeClass("table-hover");
$("#restrict-elements-table").on("editable-save.bs.table", function (e, field, row) { $("#restrict-elements-table").on("editable-save.bs.table", function (e, field, row) {
$.ajax({ $.ajax({
url: getPath() + "/ajax/editrestriction/" + type + "/" + user_id, url: getPath() + "/ajax/editrestriction/" + type + "/" + userId,
type: "Post", type: "Post",
data: row data: row
}); });
@ -305,13 +305,13 @@ $(function() {
$("[id^=submit_]").click(function() { $("[id^=submit_]").click(function() {
$(this)[0].blur(); $(this)[0].blur();
$.ajax({ $.ajax({
url: getPath() + "/ajax/addrestriction/" + type + "/" + user_id, url: getPath() + "/ajax/addrestriction/" + type + "/" + userId,
type: "Post", type: "Post",
data: $(this).closest("form").serialize() + "&" + $(this)[0].name + "=", data: $(this).closest("form").serialize() + "&" + $(this)[0].name + "=",
success: function () { success: function () {
$.ajax ({ $.ajax ({
method:"get", method:"get",
url: getPath() + "/ajax/listrestriction/" + type + "/" + user_id, url: getPath() + "/ajax/listrestriction/" + type + "/" + userId,
async: true, async: true,
timeout: 900, timeout: 900,
success:function(data) { success:function(data) {
@ -333,12 +333,12 @@ $(function() {
$("#h1").removeClass("hidden"); $("#h1").removeClass("hidden");
}); });
$("#get_user_column_values").on("click", function() { $("#get_user_column_values").on("click", function() {
startTable(3, $(this).data('id')); startTable(3, $(this).data("id"));
$("#h4").removeClass("hidden"); $("#h4").removeClass("hidden");
}); });
$("#get_user_tags").on("click", function() { $("#get_user_tags").on("click", function() {
startTable(2, $(this).data('id')); startTable(2, $(this).data("id"));
$(this)[0].blur(); $(this)[0].blur();
$("#h3").removeClass("hidden"); $("#h3").removeClass("hidden");
}); });

View File

@ -977,6 +977,82 @@ def search():
title=_(u"Search"), title=_(u"Search"),
page="search") page="search")
def adv_search_custom_columns(cc, term, q):
for c in cc:
custom_query = term.get('custom_column_' + str(c.id))
if custom_query != '' and custom_query is not None:
if c.datatype == 'bool':
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
db.cc_classes[c.id].value == (custom_query == "True")))
elif c.datatype == 'int' or c.datatype == 'float':
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
db.cc_classes[c.id].value == custom_query))
elif c.datatype == 'rating':
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
db.cc_classes[c.id].value == int(float(custom_query) * 2)))
else:
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
func.lower(db.cc_classes[c.id].value).ilike("%" + custom_query + "%")))
return q
def extend_search_term(searchterm,
author_name,
book_title,
publisher,
pub_start,
pub_end,
include_tag_inputs,
exclude_tag_inputs,
include_series_inputs,
exclude_series_inputs,
include_languages_inputs,
rating_high,
rating_low,
read_status,
include_extension_inputs,
exclude_extension_inputs
):
searchterm.extend((author_name.replace('|', ','), book_title, publisher))
if pub_start:
try:
searchterm.extend([_(u"Published after ") +
format_date(datetime.strptime(pub_start, "%Y-%m-%d"),
format='medium', locale=get_locale())])
except ValueError:
pub_start = u""
if pub_end:
try:
searchterm.extend([_(u"Published before ") +
format_date(datetime.strptime(pub_end, "%Y-%m-%d"),
format='medium', locale=get_locale())])
except ValueError:
pub_start = u""
tag_names = calibre_db.session.query(db.Tags).filter(db.Tags.id.in_(include_tag_inputs)).all()
searchterm.extend(tag.name for tag in tag_names)
tag_names = calibre_db.session.query(db.Tags).filter(db.Tags.id.in_(exclude_tag_inputs)).all()
searchterm.extend(tag.name for tag in tag_names)
serie_names = calibre_db.session.query(db.Series).filter(db.Series.id.in_(include_series_inputs)).all()
searchterm.extend(serie.name for serie in serie_names)
serie_names = calibre_db.session.query(db.Series).filter(db.Series.id.in_(exclude_series_inputs)).all()
searchterm.extend(serie.name for serie in serie_names)
language_names = calibre_db.session.query(db.Languages). \
filter(db.Languages.id.in_(include_languages_inputs)).all()
if language_names:
language_names = calibre_db.speaking_language(language_names)
searchterm.extend(language.name for language in language_names)
if rating_high:
searchterm.extend([_(u"Rating <= %(rating)s", rating=rating_high)])
if rating_low:
searchterm.extend([_(u"Rating >= %(rating)s", rating=rating_low)])
if read_status:
searchterm.extend([_(u"Read Status = %(status)s", status=read_status)])
searchterm.extend(ext for ext in include_extension_inputs)
searchterm.extend(ext for ext in exclude_extension_inputs)
# handle custom columns
searchterm = " + ".join(filter(None, searchterm))
return searchterm
@web.route("/advsearch", methods=['POST']) @web.route("/advsearch", methods=['POST'])
@login_required_if_no_ano @login_required_if_no_ano
@ -1034,47 +1110,22 @@ def render_adv_search_results(term, offset=None, order=None, limit=None):
include_languages_inputs or exclude_languages_inputs or author_name or book_title or \ include_languages_inputs or exclude_languages_inputs or author_name or book_title or \
publisher or pub_start or pub_end or rating_low or rating_high or description or cc_present or \ publisher or pub_start or pub_end or rating_low or rating_high or description or cc_present or \
include_extension_inputs or exclude_extension_inputs or read_status: include_extension_inputs or exclude_extension_inputs or read_status:
searchterm.extend((author_name.replace('|', ','), book_title, publisher)) searchterm = extend_search_term(searchterm,
if pub_start: author_name,
try: book_title,
searchterm.extend([_(u"Published after ") + publisher,
format_date(datetime.strptime(pub_start, "%Y-%m-%d"), pub_start,
format='medium', locale=get_locale())]) pub_end,
except ValueError: include_tag_inputs,
pub_start = u"" exclude_tag_inputs,
if pub_end: include_series_inputs,
try: exclude_series_inputs,
searchterm.extend([_(u"Published before ") + include_languages_inputs,
format_date(datetime.strptime(pub_end, "%Y-%m-%d"), rating_high,
format='medium', locale=get_locale())]) rating_low,
except ValueError: read_status,
pub_start = u"" include_extension_inputs,
tag_names = calibre_db.session.query(db.Tags).filter(db.Tags.id.in_(include_tag_inputs)).all() exclude_extension_inputs)
searchterm.extend(tag.name for tag in tag_names)
tag_names = calibre_db.session.query(db.Tags).filter(db.Tags.id.in_(exclude_tag_inputs)).all()
searchterm.extend(tag.name for tag in tag_names)
serie_names = calibre_db.session.query(db.Series).filter(db.Series.id.in_(include_series_inputs)).all()
searchterm.extend(serie.name for serie in serie_names)
serie_names = calibre_db.session.query(db.Series).filter(db.Series.id.in_(exclude_series_inputs)).all()
searchterm.extend(serie.name for serie in serie_names)
language_names = calibre_db.session.query(db.Languages).\
filter(db.Languages.id.in_(include_languages_inputs)).all()
if language_names:
language_names = calibre_db.speaking_language(language_names)
searchterm.extend(language.name for language in language_names)
if rating_high:
searchterm.extend([_(u"Rating <= %(rating)s", rating=rating_high)])
if rating_low:
searchterm.extend([_(u"Rating >= %(rating)s", rating=rating_low)])
if read_status:
searchterm.extend([_(u"Read Status = %(status)s", status=read_status)])
searchterm.extend(ext for ext in include_extension_inputs)
searchterm.extend(ext for ext in exclude_extension_inputs)
# handle custom columns
#for c in cc:
# if term.get('custom_column_' + str(c.id)):
# searchterm.extend([(u"%s: %s" % (c.name, term.get('custom_column_' + str(c.id))))])
searchterm = " + ".join(filter(None, searchterm))
q = q.filter() q = q.filter()
if author_name: if author_name:
q = q.filter(db.Books.authors.any(func.lower(db.Authors.name).ilike("%" + author_name + "%"))) q = q.filter(db.Books.authors.any(func.lower(db.Authors.name).ilike("%" + author_name + "%")))
@ -1132,21 +1183,8 @@ def render_adv_search_results(term, offset=None, order=None, limit=None):
q = q.filter(db.Books.comments.any(func.lower(db.Comments.text).ilike("%" + description + "%"))) q = q.filter(db.Books.comments.any(func.lower(db.Comments.text).ilike("%" + description + "%")))
# search custom culumns # search custom culumns
for c in cc: q = adv_search_custom_columns(cc, term, q)
custom_query = term.get('custom_column_' + str(c.id))
if custom_query != '' and custom_query is not None:
if c.datatype == 'bool':
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
db.cc_classes[c.id].value == (custom_query == "True")))
elif c.datatype == 'int' or c.datatype == 'float':
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
db.cc_classes[c.id].value == custom_query))
elif c.datatype == 'rating':
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
db.cc_classes[c.id].value == int(float(custom_query) * 2)))
else:
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
func.lower(db.cc_classes[c.id].value).ilike("%" + custom_query + "%")))
q = q.order_by(*order).all() q = q.order_by(*order).all()
flask_session['query'] = json.dumps(term) flask_session['query'] = json.dumps(term)
ub.store_ids(q) ub.store_ids(q)