Skip to content

Commit

Permalink
Moved from regex to toml config reader
Browse files Browse the repository at this point in the history
  • Loading branch information
Mario committed Dec 8, 2024
1 parent 2560dee commit 63c869f
Show file tree
Hide file tree
Showing 12 changed files with 88 additions and 13,446 deletions.
2 changes: 0 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ WORKDIR /app

COPY requirements.txt /app/requirements.txt
COPY app.py /app/app.py
COPY read.py /app/read.py
COPY save.py /app/save.py
COPY config.py /app/config.py
COPY templates /app/templates
COPY static /app/static
Expand Down
42 changes: 20 additions & 22 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
from time import time
import toml

from read import read_topics, read_server_addr, read_qos
from save import save_topics, save_server_addr, save_qos
from config import config, LOGIN_ATTEMPTS, MAX_ATTEMPTS, BLOCK_TIME, LOGIN_REQUIRED, LOGIN_PASSWORD
#from read import read_topics, read_server_addr, read_qos, read_connection_timeout
#from save import save_topics, save_server_addr, save_qos, save_connection_timeout
from config import config, LOGIN_ATTEMPTS, MAX_ATTEMPTS, BLOCK_TIME, LOGIN_REQUIRED, LOGIN_PASSWORD, TELEGRAF_CONFIG, TELEGRAF_CONFIG_PATH

app = Flask(__name__)
app.secret_key = config["auth"]["secret_key"]

def update_toml(input_data):
for section, section_data in input_data.items():
if section in TELEGRAF_CONFIG:
for key, value in section_data.items():
if isinstance(value, dict):
if key in TELEGRAF_CONFIG[section]:
update_toml(TELEGRAF_CONFIG[section], {key: value})
else:
TELEGRAF_CONFIG[section][key] = value
return TELEGRAF_CONFIG

# Checks if an IP is blocked
def is_blocked(ip):
if ip in LOGIN_ATTEMPTS:
Expand Down Expand Up @@ -73,34 +85,20 @@ def get_config():
if LOGIN_REQUIRED and not session.get("logged_in"):
return jsonify({"error": "Nicht autorisiert."}), 403

topics = read_topics()
server_addr = read_server_addr()
qos = read_qos()
conf = TELEGRAF_CONFIG["inputs"]["mqtt_consumer"]

return jsonify({"topics": topics, "server_addr": server_addr, "qos": qos})
return jsonify(conf)

@app.route('/api/save-config', methods=['POST'])
def save_config():
if LOGIN_REQUIRED and not session.get("logged_in"):
return jsonify({"error": "Not authorized."}), 403

data = request.get_json()
new_config = update_toml(data)

topics = data.get('topics', [])
server_addr = data.get('server_addr', [])
qos = data.get('qos', None)

if topics:
if not save_topics(topics):
return jsonify({"error": "Failed to save topics."}), 500

if server_addr:
if not save_server_addr(server_addr):
return jsonify({"error": "Failed to save Server adress."}), 500

if qos:
if not save_qos(qos):
return jsonify({"error": "Failed to save qos value."}), 500
with open(TELEGRAF_CONFIG_PATH, 'w') as f:
toml.dump(new_config, f)

return jsonify({"status": "success", "message": "config saved succesfully!"})

Expand Down
4 changes: 3 additions & 1 deletion config.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import configparser
import toml

config = configparser.ConfigParser()
config.read('app.conf')

TELEGRAF_CONFIG_PATH = "telegraf.conf"
TELEGRAF_CONFIG = toml.load(config["config"]["telegraf_config_path"])
TELEGRAF_CONFIG_PATH = config["config"]["telegraf_config_path"]
LOGIN_REQUIRED = config.getboolean("auth", "login_required", fallback=False)
LOGIN_PASSWORD = config.get("auth", "password", fallback="")

Expand Down
42 changes: 0 additions & 42 deletions read.py

This file was deleted.

3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Flask==3.0.3
configparser==7.1.0
configparser==7.1.0
toml==0.10.2
68 changes: 0 additions & 68 deletions save.py

This file was deleted.

30 changes: 15 additions & 15 deletions static/dashboard.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
// Funktion, um Nachrichten anzuzeigen
// Shows Messages
function showMessage(message, type = "success") {
const messageBox = document.getElementById("message-box");
messageBox.textContent = message;
messageBox.className = `message-box ${type}`; // Typ (success, error) hinzufügen

// Nachricht nach 5 Sekunden ausblenden
// Removes message after 5 seconds
setTimeout(() => {
messageBox.textContent = "";
messageBox.className = "message-box";
}, 5000);
}

// Funktion, um die Topics dynamisch hinzuzufügen
// Adds Topics dynamically
function loadTopics() {
fetch('/api/config') // API-Request für Topics
fetch('/api/config') // API-Request for Topics
.then(response => response.json())
.then(data => {
const topics = data.topics || []; // Falls keine Topics vorhanden sind, leere Liste
const topics = data.topics || []; // When no topics are available, an empty array is returned
const topicsList = document.getElementById('topics-list');

// Entfernen aller vorhandenen Topics im DOM, bevor wir die neuen hinzufügen
// Remove all existing topics
topicsList.innerHTML = '';

topics.forEach(topic => {
// Neues Topic-Element erstellen
// Create new topic item
const topicItem = document.createElement('div');
topicItem.classList.add('topic-item');
topicItem.innerHTML = `
Expand All @@ -37,34 +37,34 @@ function loadTopics() {
.catch(error => showMessage("Fehler beim Laden der Topics!", "error"));
}

// Hinzufügen eines neuen Topic-Feldes
// Create new topic field
document.getElementById('add-topic-btn').addEventListener('click', function() {
const topicItem = document.createElement('div');
topicItem.classList.add('topic-item');
topicItem.innerHTML = '<input type="text" name="topics" value=""><button type="button" class="remove-topic-btn">-</button>';
document.getElementById('topics-list').appendChild(topicItem);
});

// Entfernen eines Topics
// Remove topic
document.addEventListener('click', function(event) {
if (event.target.classList.contains('remove-topic-btn')) {
event.target.parentElement.remove();
}
});

// Formular absenden
// Send formular data
document.getElementById('topics-form').addEventListener('submit', function(event) {
event.preventDefault(); // Verhindert das Standard-Submit-Verhalten
event.preventDefault(); // prevents the default form submission

// Alle aktuellen Topics aus den Eingabefeldern sammeln
// Collect all topics
const topics = [];
document.querySelectorAll('input[name="topics"]').forEach(input => {
if (input.value.trim()) {
topics.push(input.value.trim());
}
});

// Die geänderten Topics an die API senden
// Send changed topics to api
fetch('/api/save-config', {
method: 'POST',
headers: {
Expand All @@ -75,10 +75,10 @@ document.getElementById('topics-form').addEventListener('submit', function(event
.then(response => response.json())
.then(data => {
showMessage(data.message, "success");
loadTopics(); // Aktualisieren der angezeigten Topics
loadTopics(); // Update displayed topics
})
.catch(error => showMessage("Fehler beim Speichern der Topics!", "error"));
});

// Laden der Topics beim ersten Aufruf der Seite
// Load topics on page load
window.onload = loadTopics;
2 changes: 1 addition & 1 deletion static/login.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Funktion zum Umschalten der Passwortsichtbarkeit
// Function to toggle password visibility
function togglePasswordVisibility() {
const passwordInput = document.getElementById('password');
const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
Expand Down
Loading

0 comments on commit 63c869f

Please sign in to comment.