Skip to content

Commit

Permalink
Attempting to improve user experiance when using convert-library from…
Browse files Browse the repository at this point in the history
… the Web UI
  • Loading branch information
crocodilestick committed Dec 12, 2024
1 parent 24cbe2f commit 93edaa0
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 106 deletions.
127 changes: 34 additions & 93 deletions root/app/calibre-web/cps/cwa_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
import os.path
from time import sleep

import json
from threading import Thread

import sys
sys.path.insert(1, '/app/calibre-web-automated/scripts/')
from cwa_db import CWA_DB
Expand Down Expand Up @@ -233,100 +236,38 @@ def cwa_flash_status():
return redirect(url_for('admin.admin'))


def flask_logger():
def convert_library_start():
subprocess.Popen(['python3', '/app/calibre-web-automated/scripts/convert_library.py'])
if os.path.isfile("/config/convert-library.log") == False:
with open('/config/convert-library.log', 'w') as create_new_log:
pass
with open("/config/convert-library.log", 'r') as log_info:
while True:
data = log_info.read()
yield data.encode()
sleep(1)
if "FIN" in data:
break

@convert_library.route("/cwa-library-convert", methods=["GET", "POST"])
@login_required_if_no_ano
@admin_required
def cwa_library_convert():
return Response(flask_logger(), mimetype="text/plain", content_type="text/event-stream")

# @convert_library.route("/convert-progress", methods=["GET"])
@convert_library.route('/cwa-library-convert', methods=['GET'])
def start_conversion():
t1 = Thread(target=convert_library_start)
t1.start()
return render_title_template('cwa_convert_library.html', title=_("Calibre-Web Automated - Convert Library"), page="cwa-library-convert")

@convert_library.route('/convert-library-status', methods=['GET'])
def getStatus():
with open("/config/convert-library.log", 'r') as f:
status = f.read()
statusList = {'status':status}
return json.dumps(statusList)


# def flask_logger():
# subprocess.Popen(['python3', '/app/calibre-web-automated/scripts/convert_library.py'])
# if os.path.isfile("/config/convert-library.log") == False:
# with open('/config/convert-library.log', 'w') as create_new_log:
# pass
# with open("/config/convert-library.log", 'r') as log_info:
# while True:
# data = log_info.read()
# yield data.encode()
# sleep(1)
# if "FIN" in data:
# break

# @convert_library.route("/cwa-library-convert", methods=["GET", "POST"])
# @login_required_if_no_ano
# @admin_required
# def convert_progress():
# # return render_title_template("cwa_convert_library.html", title=_("CWA Convert Library"), page="cwa-library-convert")
# def convert_progress():
# return '''
# <!DOCTYPE html>
# <html lang="en">
# <head>
# <meta charset="UTF-8">
# <meta name="viewport" content="width=device-width, initial-scale=1.0">
# <title>Log Viewer</title>
# <style>
# body {
# font-family: Arial, sans-serif;
# background-color: #f4f4f4;
# margin: 0;
# padding: 20px;
# }
# #log {
# background: #fff;
# border: 1px solid #ccc;
# padding: 10px;
# height: 400px;
# overflow-y: scroll;
# font-family: monospace;
# white-space: pre-wrap;
# }
# .log-entry {
# margin-bottom: 5px;
# }
# .info {
# color: blue;
# }
# .warning {
# color: orange;
# }
# .error {
# color: red;
# }
# </style>
# </head>
# <body>
# <h1>Log Viewer</h1>
# <div id="log"></div>
# <script>
# const eventSource = new EventSource("/logs");

# eventSource.onopen = function(event) {
# console.log("Connection to server opened.");
# };

# eventSource.onmessage = function(event) {
# console.log("Received message:", event.data); // Log incoming messages for debugging
# const logEntry = document.createElement("div");
# logEntry.className = "log-entry";

# if (event.data.includes("ERROR")) {
# logEntry.classList.add("error");
# } else if (event.data.includes("WARNING")) {
# logEntry.classList.add("warning");
# } else {
# logEntry.classList.add("info");
# }

# logEntry.textContent = event.data;
# document.getElementById("log").appendChild(logEntry);
# document.getElementById("log").scrollTop = document.getElementById("log").scrollHeight;
# };

# eventSource.onerror = function(event) {
# console.error("EventSource failed:", event);
# };
# </script>
# </body>
# </html>
# '''
# def cwa_library_convert():
# return Response(flask_logger(), mimetype="text/plain", content_type="text/event-stream")
44 changes: 32 additions & 12 deletions root/app/calibre-web/cps/templates/cwa_convert_library.html
Original file line number Diff line number Diff line change
@@ -1,25 +1,45 @@
{% extends "layout.html" %}
{% block script %}
$(document).ready(function(){
var output = document.getElementById('output');
var xhr = new XMLHttpRequest();
xhr.open('GET', '{{ url_for('convert_library.cwa_library_convert') }}', true);
xhr.send();
setInterval(function() {
output.textContent = xhr.responseText;
}, 500);
});
{% endblock %}

{% block body %}
<div class="discover">
<h2>{{title}}</h2>
<div>
<h3>CWA Library Convertor</h3><br>
<div class="row">
<div class="logging_window">
<pre id="output"></pre>
<h2 id="innerStatus">Loading...</h2>
</div>
</div>
</div>
</div>
{% endblock %}

{% block js %}
<script>
var timeout;

async function getStatus() {

let get;

try {
const res = await fetch("/convert-library-status");
get = await res.json();
} catch (e) {
console.error("Error: ", e);
}

document.getElementById("innerStatus").innerHTML = get.status.replace(/\n/g, "<br>"); // * 10 + "&percnt;"

if (get.status == "Done!"){
document.getElementById("innerStatus").innerHTML;
clearTimeout(timeout);
return false;
}

timeout = setTimeout(getStatus, 1000);
}

getStatus();
</script>
{% endblock %}
6 changes: 5 additions & 1 deletion scripts/convert_library.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@


logger = logging.getLogger(__name__)
logging.basicConfig(filename='/config/convert-library.log', level=logging.INFO, filemode='w')
LOG_FORMAT = '%(message)s'
logging.basicConfig(filename='/config/convert-library.log',
level=logging.INFO,
filemode='w',
format=LOG_FORMAT)

def print_and_log(string) -> None:
logging.info(string)
Expand Down

0 comments on commit 93edaa0

Please sign in to comment.