Ajout du module utils.py et modification du html

This commit is contained in:
augustin64 2022-08-16 15:21:12 +02:00
parent 45240c4347
commit 8e7671af12
7 changed files with 279 additions and 243 deletions

View File

@ -10,7 +10,7 @@ from flask import (Blueprint, abort, flash, redirect, render_template, request,
from .auth import login_required
from .db import get_db
from . import user
from .utils import User, Album
bp = Blueprint("albums", __name__, url_prefix="/albums")
@ -18,7 +18,8 @@ bp = Blueprint("albums", __name__, url_prefix="/albums")
@bp.route("/")
@login_required
def index():
albums = user.get_albums(session.get("user_id"))
user = User(session.get("user_id"))
albums = user.get_albums()
return render_template("albums/index.html", albums=albums)
@ -28,36 +29,26 @@ def album(uuid):
"""
Album page
"""
db = get_db()
album = db.execute(
"""
SELECT id, name, uuid FROM album
WHERE uuid = ?
""",
(uuid,),
).fetchone()
try:
album = Album(uuid=uuid)
user = User(session.get("user_id"))
partitions = album.get_partitions()
if user.id is None:
# On ne propose pas aux gens non connectés de rejoindre l'album
not_participant = False
else:
not_participant = not user.is_participant(album.uuid)
if album is None:
return render_template(
"albums/album.html",
album=album,
partitions=partitions,
not_participant=not_participant
)
except LookupError:
return abort(404)
partitions = db.execute(
"""
SELECT partition.uuid, partition.name, partition.author FROM partition
JOIN contient_partition ON partition_uuid = partition.uuid
JOIN album ON album.id = album_id
WHERE album.uuid = ?
""",
(uuid,),
).fetchall()
if session.get("user_id") is None:
# On ne propose pas aux gens non connectés de rejoindre l'album
not_participant = False
else:
not_participant = not user.is_participant(session.get("user_id"), uuid)
return render_template("albums/album.html", album=album, partitions=partitions, not_participant=not_participant)
@bp.route("/<album_uuid>/<partition_uuid>")
def partition(album_uuid, partition_uuid):
@ -106,21 +97,13 @@ def create_album():
(uuid, name),
)
db.commit()
album_id = db.execute(
"""
SELECT id FROM album
WHERE uuid = ?
""",
(uuid,),
).fetchone()["id"]
album = Album(uuid=uuid)
db.execute(
"""
INSERT INTO contient_user (user_id, album_id)
VALUES (?, ?)
""",
(session.get("user_id"), album_id),
(session.get("user_id"), album.id),
)
db.commit()
@ -137,149 +120,61 @@ def create_album():
@bp.route("/<uuid>/join")
@login_required
def join_album(uuid):
if session.get("user_id") is None:
flash("Vous n'êtes pas connecté.")
return redirect(f"/albums/{uuid}")
db = get_db()
album_id = db.execute(
"""
SELECT id FROM album
WHERE uuid = ?
""",
(uuid,)
).fetchone()["id"]
if album_id is None:
user = User(session.get("user_id"))
try:
user.join_album(uuid)
except LookupError:
flash("Cet album n'existe pas.")
return redirect(f"/albums/{uuid}")
db.execute(
"""
INSERT INTO contient_user (user_id, album_id)
VALUES (?, ?)
""",
(session.get("user_id"), album_id)
)
db.commit()
flash("Album ajouté à la collection.")
return redirect(f"/albums/{uuid}")
@bp.route("/<uuid>/delete", methods=["GET", "POST"])
@login_required
def delete_album(uuid):
db = get_db()
if session.get("user_id") is None:
flash("Vous n'êtes pas connecté.")
return redirect(f"/albums/{uuid}")
album = Album(uuid=uuid)
if request.method == "GET":
album = db.execute(
"""
SELECT * FROM album
WHERE uuid = ?
""",
(uuid,)
).fetchone()
return render_template("albums/delete-album.html", album=album)
error = None
users = user.get_users(uuid)
users = album.get_users()
user = User(session.get("user_id"))
if len(users) > 1:
error = "Vous n'êtes pas seul dans cet album."
elif len(users) == 1 and users[0]["id"] != session.get("user_id"):
elif len(users) == 1 and users[0]["id"] != user.id:
error = "Vous ne possédez pas cet album."
if user.access_level(session.get("user_id")) == 1:
if user.access_level == 1:
error = None
if error is not None:
flash(error)
return redirect(f"/albums/{uuid}")
album_id = db.execute(
"""
SELECT id FROM album
WHERE uuid = ?
""",
(uuid,)
).fetchone()["id"]
album.delete()
db.execute(
"""
DELETE FROM album
WHERE uuid = ?
""",
(uuid,)
)
db.execute(
"""
DELETE FROM contient_user
WHERE album_id = ?
""",
(album_id,)
)
db.execute(
"""
DELETE FROM contient_partition
WHERE album_id = ?
""",
(album_id,)
)
db.commit()
# Delete orphan partitions
partitions = db.execute(
"""
SELECT partition.uuid FROM partition
WHERE NOT EXISTS (
SELECT NULL FROM contient_partition
WHERE partition.uuid = partition_uuid
)
"""
)
for partition in partitions.fetchall():
os.remove(f"partitioncloud/partitions/{partition['uuid']}.pdf")
if os.path.exists(f"partitioncloud/static/thumbnails/{partition['uuid']}.jpg"):
os.remove(f"partitioncloud/static/thumbnails/{partition['uuid']}.jpg")
partitions = db.execute(
"""
DELETE FROM partition
WHERE uuid IN (
SELECT partition.uuid FROM partition
WHERE NOT EXISTS (
SELECT NULL FROM contient_partition
WHERE partition.uuid = partition_uuid
)
)
"""
)
db.commit()
flash("Album supprimé.")
return redirect("/albums")
@bp.route("/<album_uuid>/add-partition", methods=["GET", "POST"])
@login_required
def add_partition(album_uuid):
user_id = session.get("user_id")
db = get_db()
if user_id is None:
flash("Vous n'êtes pas connecté.")
return redirect(f"/albums/{album_uuid}")
user = User(session.get("user_id"))
album = Album(uuid=album_uuid)
if (not user.is_participant(user_id, album_uuid)) and (user.access_level(user_id) != 1):
if (not user.is_participant(album.uuid)) and (user.access_level != 1):
flash("Vous ne participez pas à cet album.")
return redirect(f"/albums/{album_uuid}")
return redirect(f"/albums/{album.uuid}")
if request.method == "GET":
album = db.execute(
"""
SELECT * FROM album
WHERE uuid = ?
""",
(album_uuid,)
).fetchone()
return render_template("albums/add-partition.html", album=album)
error = None
@ -291,7 +186,7 @@ def add_partition(album_uuid):
if error is not None:
flash(error)
return redirect(f"/albums/{album_uuid}")
return redirect(f"/albums/{album.uuid}")
if "author" in request.form:
author = request.form["author"]
@ -331,7 +226,7 @@ def add_partition(album_uuid):
SELECT id FROM album
WHERE uuid = ?
""",
(album_uuid,)
(album.uuid,)
).fetchone()["id"]
db.execute(
@ -339,7 +234,7 @@ def add_partition(album_uuid):
INSERT INTO contient_partition (partition_uuid, album_id)
VALUES (?, ?)
""",
(partition_uuid, album_id),
(partition_uuid, album.id),
)
db.commit()
@ -348,4 +243,4 @@ def add_partition(album_uuid):
pass
flash(f"Partition {request.form['name']} ajoutée")
return redirect(f"/albums/{album_uuid}")
return redirect(f"/albums/{album.uuid}")

View File

@ -1,18 +1,18 @@
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}Ajouter une partition à {{ album["name"] }}{% endblock %}</h1>
<h1>{% block title %}Ajouter une partition à {{ album.name }}{% endblock %}</h1>
{% endblock %}
{% block content %}
<form method="post" enctype="multipart/form-data">
Titre*
<input name="name" type="text" required/>
Auteur
<input name="author" type="text"/>
Paroles
<input name="body" type="text"/>
<input name="file" type="file" required/>
<input type="submit" value="Ajouter"/>
</form>
<form method="post" enctype="multipart/form-data">
Titre*
<input name="name" type="text" required />
Auteur
<input name="author" type="text" />
Paroles
<textarea name="body" type="text"></textarea>
<input name="file" type="file" required />
<input type="submit" value="Ajouter" />
</form>
{% endblock %}

View File

@ -1,17 +1,17 @@
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}{{ album["name"] }}{% endblock %}</h1>
<h1>{% block title %}{{ album.name }}{% endblock %}</h1>
{% endblock %}
{% block header_actions %}
{% if not_participant %}
<a href="/albums/{{ album['uuid'] }}/join">
<a class="button-href" href="/albums/{{ album.uuid }}/join">
<button id="join-album">Rejoindre</button>
</a>
{% endif %}
{% if g.user %}
<a href="/albums/{{ album['uuid'] }}/add-partition">
<a class="button-href" href="/albums/{{ album.uuid }}/add-partition">
<button id="add-partition">Ajouter une partition</button>
</a>
{% endif %}
@ -21,15 +21,15 @@
{% if partitions|length != 0 %}
<div id="partitions-grid">
{% for partition in partitions %}
<div class="partition" id="partition-{{ partition['uuid'] }}">
<a href="{{ album['uuid'] }}/{{ partition['uuid'] }}">
<img src="/static/thumbnails/{{ partition['uuid'] }}.jpg">
<a href="{{ album.uuid }}/{{ partition['uuid'] }}">
<div class="partition" id="partition-{{ partition['uuid'] }}">
<img class="partition-thumbnail" src="/static/thumbnails/{{ partition['uuid'] }}.jpg">
<div class="partition-description">
<div class="partition-name">{{ partition["name"] }}</div>
<div class="partition-author">{{ partition["author"] }}</div>
</div>
</a>
</div>
</div>
</a>
{% endfor %}
</div>
{% else %}

View File

@ -1,13 +1,16 @@
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}Supprimer {{ album["name"] }}{% endblock %}</h1>
<h1>{% block title %}Supprimer {{ album.name }}{% endblock %}</h1>
{% endblock %}
{% block content %}
Êtes vous sûr de vouloir supprimer cet album ?
<form method="post">
<input type="submit" value="Supprimer">
</form>
<a href="/albums/{{ album['uuid'] }}"><button>Annuler</button></a>
Êtes vous sûr de vouloir supprimer cet album ?
<form method="post">
<input type="submit" value="Supprimer">
</form>
<a class="button-href" href="/albums/{{ album.uuid }}">
<button id="cancel-deletion">Annuler</button>
</a>
{% endblock %}

View File

@ -1,16 +1,21 @@
<!doctype html>
<title>{% block title %}{% endblock %} - PartitionCloud</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{% block title %}{% endblock %} - PartitionCloud</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='mobile.css') }}">
</head>
<nav>
<h1><a href="{{ url_for('albums.index') }}">PartitionCloud</a></h1>
<ul>
{% if g.user %}
<li><span>{{ g.user['username'] }}</span>
<li><a href="{{ url_for('auth.logout') }}">Déconnexion</a>
{% else %}
<li><a href="{{ url_for('auth.register') }}">Créer un compte</a>
<li><a href="{{ url_for('auth.login') }}">Se connecter</a>
{% endif %}
<li><span>{{ g.user['username'] }}</span>
<li><a href="{{ url_for('auth.logout') }}">Déconnexion</a>
{% else %}
<li><a href="{{ url_for('auth.register') }}">Créer un compte</a>
<li><a href="{{ url_for('auth.login') }}">Se connecter</a>
{% endif %}
</ul>
</nav>
<section class="content">
@ -20,9 +25,9 @@
{% block header_actions %}{% endblock %}
</div>
</header>
<br/>
{% for message in get_flashed_messages() %}
<div class="flash">{{ message }}</div>
<div class="flash">{{ message }}</div>
{% endfor %}
<br />
{% block content %}{% endblock %}
</section>

View File

@ -1,60 +0,0 @@
#!/usr/bin/python3
from .db import get_db
def access_level(user_id):
db = get_db()
if user_id is None:
return -1
return db.execute(
"""
SELECT access_level FROM user
WHERE id = ?
""",
(user_id,)
).fetchone()["access_level"]
def is_participant(user_id, uuid):
db = get_db()
return len(db.execute(
"""
SELECT album.id FROM album
JOIN contient_user ON album_id = album.id
JOIN user ON user_id = user.id
WHERE user.id = ? AND album.uuid = ?
""",
(user_id, uuid)
).fetchall()) == 1
def get_albums(user_id):
db = get_db()
if access_level(user_id) == 1:
return db.execute(
"""
SELECT * FROM album
"""
).fetchall()
return db.execute(
"""
SELECT album.id, name, uuid FROM album
JOIN contient_user ON album_id = album.id
JOIN user ON user_id = user.id
WHERE user.id = ?
""",
(user_id,),
).fetchall()
def get_users(album_uuid):
db = get_db()
return db.execute(
"""
SELECT * FROM user
JOIN contient_user ON user_id = user.id
JOIN album ON album.id = album_id
WHERE album.uuid = ?
""",
(album_uuid,)
).fetchall()

193
partitioncloud/utils.py Normal file
View File

@ -0,0 +1,193 @@
#!/usr/bin/python3
import os
from .db import get_db
class User():
def __init__(self, user_id):
self.id = user_id
db = get_db()
if self.id is None:
self.username = ""
self.access_level = -1
else:
data = db.execute(
"""
SELECT username, access_level FROM user
WHERE id = ?
""",
(self.id,)
).fetchone()
self.username = data["username"]
self.access_level = data["access_level"]
def is_participant(self, album_uuid):
db = get_db()
return len(db.execute(
"""
SELECT album.id FROM album
JOIN contient_user ON album_id = album.id
JOIN user ON user_id = user.id
WHERE user.id = ? AND album.uuid = ?
""",
(self.id, album_uuid)
).fetchall()) == 1
def get_albums(self):
db = get_db()
if self.access_level == 1:
return db.execute(
"""
SELECT * FROM album
"""
).fetchall()
return db.execute(
"""
SELECT album.id, name, uuid FROM album
JOIN contient_user ON album_id = album.id
JOIN user ON user_id = user.id
WHERE user.id = ?
""",
(self.id,),
).fetchall()
def join_album(self, album_uuid):
db = get_db()
album = Album(uuid=album_uuid)
db.execute(
"""
INSERT INTO contient_user (user_id, album_id)
VALUES (?, ?)
""",
(self.id, album.id)
)
db.commit()
class Album():
def __init__(self, uuid=None, id=None):
db = get_db()
if uuid is not None:
self.uuid = uuid
data = db.execute(
"""
SELECT id, name FROM album
WHERE uuid = ?
""",
(self.uuid,)
).fetchone()
if data is None:
raise LookupError
self.id = data["id"]
self.name = data["name"]
elif id is not None:
self.id = id
data = db.execute(
"""
SELECT uuid, name FROM album
WHERE id = ?
""",
(self.id,)
).fetchone()
if data is None:
raise LookupError
self.uuid = data["uuid"]
self.name = data["name"]
else:
raise LookupError
def get_users(self):
"""
Renvoie les utilisateurs liés à l'album
"""
db = get_db()
return db.execute(
"""
SELECT * FROM user
JOIN contient_user ON user_id = user.id
JOIN album ON album.id = album_id
WHERE album.uuid = ?
""",
(self.uuid,)
).fetchall()
def get_partitions(self):
"""
Renvoie les partitions liées à l'album
"""
db = get_db()
return db.execute(
"""
SELECT partition.uuid, partition.name, partition.author FROM partition
JOIN contient_partition ON partition_uuid = partition.uuid
JOIN album ON album.id = album_id
WHERE album.uuid = ?
""",
(self.uuid,),
).fetchall()
def delete(self):
"""
Supprimer l'album
"""
db = get_db()
db.execute(
"""
DELETE FROM album
WHERE uuid = ?
""",
(self.uuid,)
)
db.execute(
"""
DELETE FROM contient_user
WHERE album_id = ?
""",
(self.id,)
)
db.execute(
"""
DELETE FROM contient_partition
WHERE album_id = ?
""",
(self.id,)
)
db.commit()
# Delete orphan partitions
partitions = db.execute(
"""
SELECT partition.uuid FROM partition
WHERE NOT EXISTS (
SELECT NULL FROM contient_partition
WHERE partition.uuid = partition_uuid
)
"""
)
for partition in partitions.fetchall():
os.remove(f"partitioncloud/partitions/{partition['uuid']}.pdf")
if os.path.exists(f"partitioncloud/static/thumbnails/{partition['uuid']}.jpg"):
os.remove(f"partitioncloud/static/thumbnails/{partition['uuid']}.jpg")
partitions = db.execute(
"""
DELETE FROM partition
WHERE uuid IN (
SELECT partition.uuid FROM partition
WHERE NOT EXISTS (
SELECT NULL FROM contient_partition
WHERE partition.uuid = partition_uuid
)
)
"""
)
db.commit()