checkboxen mit verknüfung

This commit is contained in:
Anika 2024-03-21 20:37:21 +01:00
parent 8d91c63a12
commit 94a154c363
5 changed files with 133 additions and 31 deletions

95
app.py
View File

@ -9,21 +9,24 @@ app = Flask(__name__)
activeAlarms = dict() activeAlarms = dict()
previousAlarms = dict() previousAlarms = dict()
logs = list() logs = list()
todos_dict = dict()
preprocessed = False preprocessed = False
alarmIndex = 0 alarmIndex = 0
def preprocess(): def preprocess():
print('start init alarms and logs') print('start init alarms and logs')
#versuch beide files zu laden, wenn das fehlschlägt, initiiere beide files als json #versuch beide files zu laden, wenn das fehlschlägt, initiiere beide files als json
try: try:
alarmsFile = json.load(open('alarms.json')) alarmsFile = json.load(open('alarms.json'))
logsFile = json.load(open('logs.json')) logsFile = json.load(open('logs.json'))
todoFile = json.load(open('todos.json'))
except: except:
alarmsFile = list() alarmsFile = list()
logsFile = list() logsFile = list()
todoFile = list()
json.dump(alarmsFile, open('alarms.json','w'), indent=2) json.dump(alarmsFile, open('alarms.json','w'), indent=2)
json.dump(logsFile, open('logs.json','w'), indent=2) json.dump(logsFile, open('logs.json','w'), indent=2)
json.dump(todoFile, open('todos.json','w'), indent=2)
# schreib alle alarme im File in previousAlarms, wenn sie älter als 2 mins sind # schreib alle alarme im File in previousAlarms, wenn sie älter als 2 mins sind
# alle anderen in active alarms # alle anderen in active alarms
for (alarm) in alarmsFile: for (alarm) in alarmsFile:
@ -34,6 +37,12 @@ def preprocess():
global alarmIndex global alarmIndex
if(int(alarm)>alarmIndex): if(int(alarm)>alarmIndex):
alarmIndex = int(alarm) alarmIndex = int(alarm)
for todo in todoFile:
todos_dict[todo] = todoFile[todo]
if todoFile[todo]['done'] and todo in activeAlarms:
previousAlarms[id] = activeAlarms[id]
activeAlarms.pop(id)
# lies alle log aus dem file ein # lies alle log aus dem file ein
for log in logsFile: for log in logsFile:
logs.append(log) logs.append(log)
@ -43,8 +52,6 @@ def preprocess():
@app.route("/", methods=('GET', 'POST')) @app.route("/", methods=('GET', 'POST'))
def index(): def index():
# wenn die logs leer sind, gehen wir davon aus, dass noch nicht initialisiert wurde
# alarme werden gedoppelt, sollten schon welche da sein
if not preprocessed: if not preprocessed:
preprocess() preprocess()
@ -67,12 +74,9 @@ def setAlarm():
alarmIndex += 1 alarmIndex += 1
activeAlarms[alarmIndex]({'datetime':datetime.strftime(time,"%d.%m.%Y %H:%M"),'message':content}) activeAlarms[alarmIndex]({'datetime':datetime.strftime(time,"%d.%m.%Y %H:%M"),'message':content})
# ja, wir schreiben einfach das ganze File neu, ist aber einfacher
allAlarms = activeAlarms+previousAlarms allAlarms = activeAlarms+previousAlarms
with open('alarms.json', 'w') as f: with open('alarms.json', 'w') as f:
json.dump(allAlarms, f, indent=2) json.dump(allAlarms, f, indent=2)
# Closing file
f.close() f.close()
return redirect(url_for('index')) return redirect(url_for('index'))
@ -84,15 +88,13 @@ def sendLog():
logs.append(log) logs.append(log)
with open('logs.json', 'w') as f: with open('logs.json', 'w') as f:
json.dump(logs, f, indent=2) json.dump(logs, f, indent=2)
# Closing file
f.close() f.close()
return redirect(url_for('index')) return redirect(url_for('index'))
# sounds the alarm
@app.route('/alarms', methods=('GET','POST')) @app.route('/alarms', methods=('GET','POST'))
def alarm(): def alarm():
# needs update to dict
if request.method == 'GET': if request.method == 'GET':
return json.dumps(activeAlarms) return json.dumps(activeAlarms)
@ -100,8 +102,8 @@ def alarm():
print('ALARM') print('ALARM')
subprocess.call(['mpv','./alarm.mp3'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) subprocess.call(['mpv','./alarm.mp3'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
data = json.loads(request.data.decode('UTF-8')) data = json.loads(request.data.decode('UTF-8'))
previousAlarms.append(data) previousAlarms[data] = activeAlarms[data]
activeAlarms.remove(data) activeAlarms.pop(data)
return redirect(url_for('index')) return redirect(url_for('index'))
@app.route('/deletealarm', methods=('GET','POST')) @app.route('/deletealarm', methods=('GET','POST'))
@ -112,35 +114,57 @@ def deleteAlarm():
previousAlarms[id] = alarm previousAlarms[id] = alarm
activeAlarms.pop(id) activeAlarms.pop(id)
return redirect(url_for('index')) return redirect(url_for('index'))
# invert todo checkbox
# if alarm attached to checkbox -> move to previous or active alarm accordingly
@app.route('/checktodo', methods=('GET','POST'))
def checktodo():
if request.method == 'POST':
id = request.data.decode('UTF-8')
todos_dict[id] = {'done': not todos_dict[id]['done'], 'message': todos_dict[id]['message']}
if id in activeAlarms:
previousAlarms[id] = activeAlarms[id]
activeAlarms.pop(id)
elif id in previousAlarms:
activeAlarms[id] = previousAlarms[id]
previousAlarms.pop(id)
with open('todos.json', 'w') as f:
json.dump(todos_dict, f, indent=2)
return render_template('todo.html', todos = todos_dict, alarms = activeAlarms)
@app.route('/upload', methods=('GET','POST')) @app.route('/upload', methods=('GET','POST'))
def upload(): def upload():
# if upload successful back to index # if upload successful back to index
# else show error und bleib auf der Seite # else show error und bleib auf der Seite
if request.method == 'POST': if request.method == 'POST':
# try: data = json.load(request.files['alarmFile'].stream)
data = json.load(request.files['alarmFile'].stream) for alarm in data:
for alarm in data: content = alarm["message"]
print(alarm) global alarmIndex
alarmIndex += 1
if alarm["type"] != "checkbox":
time = datetime.combine(datetime.today(),datetime.strptime(alarm["time"], "%H:%M").time()) time = datetime.combine(datetime.today(),datetime.strptime(alarm["time"], "%H:%M").time())
if time<datetime.now(): if time<datetime.now():
time = time + timedelta(days=1) time = time + timedelta(days=1)
content = alarm["message"]
global alarmIndex
alarmIndex += 1
activeAlarms[str(alarmIndex)] = {'datetime':datetime.strftime(time,"%d.%m.%Y %H:%M"),'message':content} activeAlarms[str(alarmIndex)] = {'datetime':datetime.strftime(time,"%d.%m.%Y %H:%M"),'message':content}
# ja, wir schreiben einfach das ganze File neu, ist aber einfacher if(alarm["type"]=="both"):
with open('alarms.json', 'w') as f: todos_dict[str(alarmIndex)]= {'done':False, 'message':content}
json.dump(activeAlarms, f, indent=2) else:
todos_dict[str(alarmIndex)]= {'done':False, 'message':content}
# Closing file # ja, wir schreiben einfach das ganze File neu, ist aber einfacher
f.close() with open('alarms.json', 'w') as f:
return redirect(url_for('index')) json.dump(activeAlarms, f, indent=2)
# except: with open('todos.json', 'w') as g:
# print("error :(") json.dump(todos_dict, g, indent=2)
# return render_template('upload.html', uploadFailed=True) f.close()
g.close()
return redirect(url_for('index'))
return render_template('upload.html', uploadFailed=True) return render_template('upload.html', uploadFailed=True)
# ab hier statisches gerendere, keine große Logik mehr :D
@app.route('/processAlarm') @app.route('/processAlarm')
def processAlarm(): def processAlarm():
return render_template('alarms.html', alarms=activeAlarms) return render_template('alarms.html', alarms=activeAlarms)
@ -149,9 +173,20 @@ def processAlarm():
def processpAlarm(): def processpAlarm():
return render_template('palarms.html', previousAlarms=previousAlarms) return render_template('palarms.html', previousAlarms=previousAlarms)
@app.route('/reloadChecklist')
def reloadChecklist():
return render_template('todolist.html', todos=todos_dict)
@app.route('/todos')
def todos():
if not preprocessed:
preprocess()
return render_template('todo.html', todos = todos_dict, alarms = activeAlarms)
@app.route("/help") @app.route("/help")
def help(): def help():
return render_template('help.html') return render_template('help.html')
@app.route("/about") @app.route("/about")
def about(): def about():
return render_template('about.html') return render_template('about.html')

View File

@ -18,6 +18,9 @@
</button> </button>
<div class="collapse navbar-collapse" id="navbarNav"> <div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav"> <ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{{url_for('todos')}}">ToDos</a>
</li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="{{url_for('upload')}}">Upload</a> <a class="nav-link" href="{{url_for('upload')}}">Upload</a>
</li> </li>

View File

@ -60,7 +60,6 @@
<h3>Vergangene Alarme</h3> <h3>Vergangene Alarme</h3>
<script> <script>
alarms = {{ alarms|tojson }}; alarms = {{ alarms|tojson }};
console.log(alarms);
async function postAlarm(alarm){ async function postAlarm(alarm){
var body = JSON.stringify(alarm) var body = JSON.stringify(alarm)
const response = await fetch("http://127.0.0.1:5000/alarms", { const response = await fetch("http://127.0.0.1:5000/alarms", {

56
templates/todo.html Normal file
View File

@ -0,0 +1,56 @@
{% extends 'base.html' %}
{% block content %}
<h1>{% block title %} ToDos {% endblock %}</h1>
<div id="todoList">
{% for todo in todos %}
<div>
{% if todos[todo].done%}
<input type="checkbox" style="margin-right: 2mm; " onclick="checkTodo({{todo}})" checked/><font color="green">{{todos[todo].message}}</font>
{% else %}
<input type="checkbox" style="margin-right: 2mm; " onclick="checkTodo({{todo}})"/>{{todos[todo].message}}
{% endif %}
</div>
{% endfor %}
</div>
<script>
async function checkTodo(id){
const response = await fetch("http://127.0.0.1:5000/checktodo", {
method: "POST",
body: id,
});
fetch("/reloadChecklist", {
method: "GET"
}).then(response => {
return response.text();
})
.then(html => {
todoList.innerHTML = html
})
}
// check alarms in here too
alarms = {{ alarms|tojson }};
function checkAlarms(){
for(var i = 0; i < alarms.length; i++){
const [dateComponents, timeComponents] = alarms[i].datetime.split(' ');
const [day, month, year] = dateComponents.split('.');
const [hours, minutes] = timeComponents.split(':');
const date = new Date(+year, +month - 1, +day, +hours, +minutes);
if(date <=new Date()){
postAlarm(alarms[i]);
alert(alarms[i].message);
alarms.splice(i, 1);
}
}
setTimeout(checkAlarms, 15000);
}
checkAlarms();
</script>
{% endblock %}

9
templates/todolist.html Normal file
View File

@ -0,0 +1,9 @@
{% for todo in todos %}
<div>
{% if todos[todo].done%}
<input type="checkbox" style="margin-right: 2mm; " onclick="checkTodo({{todo}})" checked/><font color="green">{{todos[todo].message}}</font>
{% else %}
<input type="checkbox" style="margin-right: 2mm; " onclick="checkTodo({{todo}})"/>{{todos[todo].message}}
{% endif %}
</div>
{% endfor %}