Compare commits

...

2 Commits

Author SHA1 Message Date
Anika 94a154c363 checkboxen mit verknüfung 2024-03-21 20:37:21 +01:00
Anika 8d91c63a12 cleanup and bug fixed
upload saved the key of the dict as int not str
2024-03-20 13:28:19 +01:00
5 changed files with 139 additions and 48 deletions

96
app.py
View File

@ -9,21 +9,24 @@ app = Flask(__name__)
activeAlarms = dict()
previousAlarms = dict()
logs = list()
todos_dict = dict()
preprocessed = False
alarmIndex = 0
def preprocess():
print('start init alarms and logs')
#versuch beide files zu laden, wenn das fehlschlägt, initiiere beide files als json
try:
alarmsFile = json.load(open('alarms.json'))
logsFile = json.load(open('logs.json'))
todoFile = json.load(open('todos.json'))
except:
alarmsFile = list()
logsFile = list()
todoFile = list()
json.dump(alarmsFile, open('alarms.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
# alle anderen in active alarms
for (alarm) in alarmsFile:
@ -34,6 +37,12 @@ def preprocess():
global alarmIndex
if(int(alarm)>alarmIndex):
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
for log in logsFile:
logs.append(log)
@ -43,8 +52,6 @@ def preprocess():
@app.route("/", methods=('GET', 'POST'))
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:
preprocess()
@ -67,12 +74,9 @@ def setAlarm():
alarmIndex += 1
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
with open('alarms.json', 'w') as f:
json.dump(allAlarms, f, indent=2)
# Closing file
f.close()
return redirect(url_for('index'))
@ -84,15 +88,13 @@ def sendLog():
logs.append(log)
with open('logs.json', 'w') as f:
json.dump(logs, f, indent=2)
# Closing file
f.close()
return redirect(url_for('index'))
# sounds the alarm
@app.route('/alarms', methods=('GET','POST'))
def alarm():
# needs update to dict
if request.method == 'GET':
return json.dumps(activeAlarms)
@ -100,8 +102,8 @@ def alarm():
print('ALARM')
subprocess.call(['mpv','./alarm.mp3'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
data = json.loads(request.data.decode('UTF-8'))
previousAlarms.append(data)
activeAlarms.remove(data)
previousAlarms[data] = activeAlarms[data]
activeAlarms.pop(data)
return redirect(url_for('index'))
@app.route('/deletealarm', methods=('GET','POST'))
@ -112,36 +114,57 @@ def deleteAlarm():
previousAlarms[id] = alarm
activeAlarms.pop(id)
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'))
def upload():
# if upload successful back to index
# else show error und bleib auf der Seite
if request.method == 'POST':
# try:
data = json.load(request.files['alarmFile'].stream)
for alarm in data:
print(alarm)
data = json.load(request.files['alarmFile'].stream)
for alarm in data:
content = alarm["message"]
global alarmIndex
alarmIndex += 1
if alarm["type"] != "checkbox":
time = datetime.combine(datetime.today(),datetime.strptime(alarm["time"], "%H:%M").time())
if time<datetime.now():
time = time + timedelta(days=1)
content = alarm["message"]
global alarmIndex
alarmIndex += 1
activeAlarms[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}
if(alarm["type"]=="both"):
todos_dict[str(alarmIndex)]= {'done':False, 'message':content}
else:
todos_dict[str(alarmIndex)]= {'done':False, 'message':content}
# ja, wir schreiben einfach das ganze File neu, ist aber einfacher
with open('alarms.json', 'w') as f:
json.dump(activeAlarms, f, indent=2)
with open('todos.json', 'w') as g:
json.dump(todos_dict, g, indent=2)
f.close()
g.close()
return redirect(url_for('index'))
# ja, wir schreiben einfach das ganze File neu, ist aber einfacher
with open('alarms.json', 'w') as f:
json.dump(activeAlarms, f, indent=2)
# Closing file
f.close()
return redirect(url_for('index'))
# except:
# print("error :(")
# 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')
def processAlarm():
return render_template('alarms.html', alarms=activeAlarms)
@ -150,9 +173,20 @@ def processAlarm():
def processpAlarm():
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")
def help():
return render_template('help.html')
@app.route("/about")
def about():
return render_template('about.html')
return render_template('about.html')

View File

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

View File

@ -60,35 +60,23 @@
<h3>Vergangene Alarme</h3>
<script>
alarms = {{ alarms|tojson }};
console.log(alarms);
async function postAlarm(alarm){
var body = JSON.stringify(alarm)
const response = await fetch("http://127.0.0.1:5000/alarms", {
method: "POST",
body: body,
});
fetch("/processAlarm", {
method: "GET"
}).then(response => {
return response.text();
})
.then(html => {
upcomingAlarms.innerHTML = html
})
fetch("/processpAlarm", {
method: "GET"
}).then(response => {
return response.text();
})
.then(html => {
previousAlarms.innerHTML = html
})
reloadAlarms();
}
async function deleteAlarm(id){
const response = await fetch("http://127.0.0.1:5000/deletealarm", {
method: "POST",
body: id,
});
reloadAlarms();
}
function reloadAlarms(){
fetch("/processAlarm", {
method: "GET"
}).then(response => {
@ -105,6 +93,7 @@
.then(html => {
previousAlarms.innerHTML = html
})
}
function checkAlarms(){

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 %}