HabitTracker/app.py

463 lines
12 KiB
Python
Raw Normal View History

2024-01-12 10:57:58 +01:00
import datetime
2024-01-12 16:53:03 +01:00
import hashlib
import os
from PIL import Image
2024-01-12 10:57:58 +01:00
from flask import Flask, render_template, redirect, url_for, request, jsonify
2024-01-12 16:53:03 +01:00
from flask_login import login_required, LoginManager, login_user, logout_user, current_user
2024-01-12 10:57:58 +01:00
from models.Habit import Habit
from models.HabitList import HabitList
from models.HabitTracking import HabitTracking
2024-01-12 10:57:58 +01:00
from models.User import User
2024-01-12 16:53:03 +01:00
from utils import anonymous_required
2024-01-12 10:57:58 +01:00
# Create a new Flask instance
app = Flask(__name__)
2024-01-12 16:53:03 +01:00
app.secret_key = 'PSSSSSHHHT!'
# Initialize the Flask-Login extension
login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return User.get(user_id)
@app.context_processor
def inject_user():
return dict(user=current_user)
2024-01-12 10:57:58 +01:00
@app.route('/login')
2024-01-12 16:53:03 +01:00
@anonymous_required
2024-01-12 10:57:58 +01:00
def login():
2024-01-12 16:53:03 +01:00
return render_template('auth/login.html', errors={})
2024-01-12 10:57:58 +01:00
@app.route('/signup')
2024-01-12 16:53:03 +01:00
@anonymous_required
2024-01-12 10:57:58 +01:00
def signup():
return render_template('auth/signup.html', errors={})
2024-01-12 16:53:03 +01:00
@app.route('/login', methods=['POST'])
def login_post():
2024-01-12 10:57:58 +01:00
email = request.form.get('email')
password = request.form.get('password')
# Check for errors
errors = {}
if not email:
errors['email'] = 'Die E-Mail Adresse ist erforderlich.'
2024-01-12 10:57:58 +01:00
if not password:
errors['password'] = 'Das Passwort ist erforderlich.'
2024-01-12 10:57:58 +01:00
# Check if user exists
user = User.get_by_email(email)
if not user:
errors['email'] = 'E-Mail Adresse nicht gefunden.'
elif user.password is None or hashlib.sha256(password.encode()).hexdigest() != user.password:
errors['password'] = 'Das Passwort ist falsch.'
2024-01-12 16:53:03 +01:00
if errors:
return render_template(
'auth/login.html',
2024-01-12 16:53:03 +01:00
email=email,
password=password,
errors=errors
)
2024-01-12 10:57:58 +01:00
2024-01-12 16:53:03 +01:00
login_user(user)
# Redirect to login page
return redirect(url_for('index'))
2024-01-12 16:53:03 +01:00
@app.route('/signup', methods=['POST'])
def signup_post():
2024-01-12 16:53:03 +01:00
email = request.form.get('email')
name = request.form.get('name')
2024-01-12 16:53:03 +01:00
password = request.form.get('password')
# Check for errors
errors = {}
if not email:
errors['email'] = 'Die E-Mail Adresse ist erforderlich.'
if not name:
errors['name'] = 'Der Name ist erforderlich.'
2024-01-12 16:53:03 +01:00
if not password:
errors['password'] = 'Das Passwort ist erforderlich.'
2024-01-12 16:53:03 +01:00
if errors:
return render_template(
'auth/signup.html',
2024-01-12 16:53:03 +01:00
email=email,
name=name,
2024-01-12 16:53:03 +01:00
password=password,
errors=errors
)
# Save user to database. Maybe log the user in directly.
user = User.create(name, email, password)
2024-01-12 16:53:03 +01:00
login_user(user)
2024-01-12 10:57:58 +01:00
# Redirect to login page
return redirect(url_for('index'))
2024-01-12 10:57:58 +01:00
@app.route('/logout')
@login_required
def logout():
# Log out functionality
2024-01-12 16:53:03 +01:00
logout_user()
2024-01-12 10:57:58 +01:00
return redirect(url_for('index'))
# Create a new route
@app.route('/')
def index():
if current_user.is_authenticated:
habit_lists = current_user.get_habitLists()
2024-01-23 11:00:37 +01:00
name = "Hallo " + current_user.name
else:
habit_lists = []
2024-01-26 11:07:41 +01:00
name = "Bitte melde dich an."
2024-01-26 10:09:57 +01:00
# Sort habits by whether they have been checked today and then by slot
2024-02-12 22:31:51 +01:00
for habit_list in habit_lists:
habit_list.habits = sorted(habit_list.get_habits(), key=lambda habit: (not habit.checked, habit.slot))
2024-01-26 10:09:57 +01:00
return render_template(
'index.html',
title=name,
utc_dt=datetime.datetime.now().strftime("%d.%m.%Y %H:%M %A"),
habit_lists=habit_lists,
errors={},
)
@app.route('/habit')
@login_required
def habit_creation():
return render_template(
'habit.html',
title='Erstelle ein Habit',
2024-01-26 10:25:01 +01:00
unit="Woche",
errors={},
)
@app.route('/habit', methods=['POST'])
@login_required
def habit_create():
name = request.form.get('name')
note = request.form.get('note')
times = request.form.get('times')
unit = request.form.get('unit')
list_id = request.form.get('list_query')
# Check for errors
errors = {}
if not name:
errors['name'] = 'Der Name ist erforderlich.'
if not times:
errors['times'] = 'Die Anzahl ist erforderlich.'
if not note:
note = ''
if not unit:
errors['unit'] = 'Die Einheit ist erforderlich.'
if not list_id:
errors['list_query'] = 'Die Habitliste ist erforderlich.'
# Check if times is an integer
try:
times = int(times)
2024-01-23 10:46:52 +01:00
# Check that times is greater than 0
if times <= 0:
errors['times'] = 'Die Anzahl muss größer als 0 sein.'
except ValueError:
errors['times'] = 'Die Anzahl muss eine Zahl sein.'
2024-01-19 11:05:27 +01:00
# Check that unit is valid
if unit not in ['Tag', 'Woche', 'Monat', 'Jahr']:
errors['unit'] = 'Die Einheit ist ungültig.'
2024-02-13 10:07:22 +01:00
# check if list_id is an int
try:
list_id = int(list_id)
except ValueError:
errors['list_query'] = 'Die Anzahl muss eine Zahl sein.'
if errors:
return render_template(
'habit.html',
title='Erstelle ein Habit',
name=name,
note=note,
times=times,
unit=unit,
errors=errors,
list_id=list_id
)
# Map unit to integer
if unit == 'Tag':
unit = 0
elif unit == 'Woche':
unit = 1
elif unit == 'Monat':
unit = 2
elif unit == 'Jahr':
unit = 3
else:
unit = 1
# Save habit to database
2024-02-13 10:07:22 +01:00
habit = Habit.create(list_id, name, times, note, unit)
# Back to index
return redirect(url_for('index'))
2024-01-26 08:30:06 +01:00
@app.route('/habit-list')
@login_required
def habit_list_creation():
return render_template(
'habit-list.html',
title='Erstelle eine Habitliste',
errors={},
)
@app.route('/habit-list', methods=['POST'])
@login_required
def habit_list_create():
name = request.form.get('name')
description = request.form.get('description')
# Check for errors
errors = {}
if not name:
errors['name'] = 'Der Name ist erforderlich.'
if not description:
note = ''
if errors:
return render_template(
'habit-list.html',
title='Erstelle eine Habitliste',
name=name,
description=description,
errors=errors
)
# Save habit to database
habit = HabitList.create(current_user.id, name, description)
# Back to index
return redirect(url_for('index'))
2024-01-26 10:25:01 +01:00
@app.route('/profile')
@login_required
def profile():
return render_template(
"profile.html",
name=current_user.name,
email=current_user.email,
profile_image_url=current_user.profile_image,
2024-01-26 10:25:01 +01:00
)
@app.route('/profile', methods=['POST'])
@login_required
def profile_change():
newName = request.form.get('newName')
newEmail = request.form.get('newEmail')
# Update user
current_user.name = newName
current_user.email = newEmail
current_user.update()
2024-01-26 10:40:12 +01:00
# Back to profile
return render_template(
"profile.html",
name=current_user.name,
email=current_user.email,
profile_image_url=current_user.profile_image,
)
2024-01-26 10:40:12 +01:00
@app.route('/check_password', methods=['POST'])
@login_required
def check_password():
# Get the password sent from the client
password = request.json.get('password')
2024-01-26 10:25:01 +01:00
if hashlib.sha256(password.encode()).hexdigest() == current_user.password:
return jsonify({"valid": True})
else:
return jsonify({"valid": False})
@app.route('/password', methods=['POST'])
@login_required
def password_change():
newPassword = request.form.get('newPassword')
2024-01-26 10:25:01 +01:00
2024-01-26 10:40:12 +01:00
# Update user
if newPassword:
current_user.password = hashlib.sha256(newPassword.encode()).hexdigest()
current_user.update()
2024-01-26 10:25:01 +01:00
2024-01-26 10:40:12 +01:00
# Back to profile
return render_template(
"profile.html",
name=current_user.name,
email=current_user.email,
profile_image_url=current_user.profile_image,
)
UPLOAD_FOLDER = 'static/profile_images/' # Folder to store profile images
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def save_profile_image(image_file):
filename = image_file.filename
if '.' not in filename:
# Ensure the filename has an extension
raise ValueError("Invalid filename")
# Check if the file extension is allowed
allowed_extensions = {'jpg', 'jpeg', 'png', 'gif'}
file_extension = filename.rsplit('.', 1)[1].lower()
if file_extension not in allowed_extensions:
raise ValueError("Invalid file extension")
# Get the filename from the image path saved in the user
filename = os.path.basename(current_user.profile_image)
# Open the uploaded image
image = Image.open(image_file)
# Convert the image to RGB mode (required for JPEG)
image = image.convert('RGB')
# Determine the size of the square image
min_dimension = min(image.size)
square_size = (min_dimension, min_dimension)
# Calculate the coordinates for cropping
left = (image.width - min_dimension) / 2
top = (image.height - min_dimension) / 2
right = (image.width + min_dimension) / 2
bottom = (image.height + min_dimension) / 2
# Crop the image to a square and resize it
image = image.crop((left, top, right, bottom))
image.thumbnail(square_size)
image = image.resize((256, 256))
# Save the processed image
image_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
image.save(image_path, 'JPEG', quality=100)
@app.route('/upload', methods=['POST'])
def upload_profile_image():
if 'file' not in request.files:
return 'No file part'
file = request.files['file']
save_profile_image(file)
# Back to profile
return render_template(
"profile.html",
name=current_user.name,
email=current_user.email,
profile_image_url=current_user.profile_image,
2024-01-26 10:40:12 +01:00
errors={}
)
2024-01-26 10:25:01 +01:00
@app.route('/check', methods=['POST'])
@login_required
def check_habit():
2024-01-26 09:06:31 +01:00
habit_id = request.get_json()["habitId"]
habit = Habit.get(habit_id)
if habit is None:
return {"error": "Habit not found"}
# Check if habit belongs to user
2024-02-12 22:31:51 +01:00
users = habit.habit_list().get_users()
if current_user not in users:
2024-01-26 09:06:31 +01:00
return {"error": "Habit does not belong to user"}
trackings = habit.get_habitTracking()
2024-01-26 09:06:31 +01:00
# Check if habit has been tracked today
2024-01-30 09:55:44 +01:00
delete_tracking = None
2024-01-26 09:06:31 +01:00
for tracking in trackings:
if tracking.created_at.date() == datetime.date.today():
delete_tracking = tracking
2024-01-26 10:01:02 +01:00
if not delete_tracking:
HabitTracking.create(habit_id)
2024-01-26 10:01:02 +01:00
else:
delete_tracking.delete()
2024-01-26 09:06:31 +01:00
# Update habit
habit.fill_statistics()
2024-01-26 09:06:31 +01:00
return {
"habitId": habit_id,
2024-01-30 10:41:05 +01:00
"unchecked": not delete_tracking,
"percentage": habit.percentage,
2024-01-26 09:06:31 +01:00
}
2024-01-26 11:07:41 +01:00
@app.route('/delete', methods=['POST'])
@login_required
def delete_habit():
habit_id = request.get_json()["habitId"]
habit = Habit.get(habit_id)
if habit is None:
return {"error": "Habit not found"}
# Check if habit belongs to user
2024-02-12 22:31:51 +01:00
if current_user not in habit.habit_list().get_users():
2024-01-26 11:07:41 +01:00
return {"error": "Habit does not belong to user"}
habit.delete()
return {}
2024-02-12 21:07:55 +01:00
@app.route('/reorder', methods=['POST'])
@login_required
def reorder_habits():
2024-02-13 10:46:54 +01:00
new_index = request.get_json()["newIndex"]+1
2024-02-12 21:07:55 +01:00
habit = Habit.get(request.get_json()["habitId"])
if habit is None:
return {"error": "Habit not found"}
# Check if habit belongs to user
2024-02-12 22:31:51 +01:00
users = habit.habit_list().get_users()
if current_user not in users:
2024-02-12 21:07:55 +01:00
return {"error": "Habit does not belong to user"}
habit.update_slot(new_index)
return {}
2024-01-12 10:57:58 +01:00
# Run the application
if __name__ == '__main__':
app.run(port=5000, debug=True)