python-gallery/gallery/api.py

220 lines
6 KiB
Python
Raw Normal View History

2023-03-04 13:45:26 +00:00
"""
Onlylegs - API endpoints
"""
from uuid import uuid4
import os
import pathlib
2023-03-04 13:45:26 +00:00
import logging
import platformdirs
from flask import Blueprint, send_from_directory, abort, flash, request, current_app
2023-03-04 13:45:26 +00:00
from werkzeug.utils import secure_filename
from flask_login import login_required, current_user
from colorthief import ColorThief
from gallery.extensions import db
from gallery.models import Posts, Groups, GroupJunction
from gallery.utils import metadata as mt
from gallery.utils.generate_image import generate_thumbnail
2023-04-07 12:35:30 +00:00
blueprint = Blueprint("api", __name__, url_prefix="/api")
2023-04-07 12:35:30 +00:00
@blueprint.route("/file/<file_name>", methods=["GET"])
def file(file_name):
2023-03-04 13:45:26 +00:00
"""
Returns a file from the uploads folder
r for resolution, 400x400 or thumb for thumbnail
2023-03-04 13:45:26 +00:00
"""
2023-04-07 12:35:30 +00:00
res = request.args.get("r", default=None, type=str) # Type of file (thumb, etc)
ext = request.args.get("e", default=None, type=str) # File extension
file_name = secure_filename(file_name) # Sanitize file name
# if no args are passed, return the raw file
2023-04-04 14:21:16 +00:00
if not res and not ext:
2023-04-07 12:35:30 +00:00
if not os.path.exists(
os.path.join(current_app.config["UPLOAD_FOLDER"], file_name)
):
2023-03-04 13:45:26 +00:00
abort(404)
2023-04-07 12:35:30 +00:00
return send_from_directory(current_app.config["UPLOAD_FOLDER"], file_name)
thumb = generate_thumbnail(file_name, res, ext)
2023-03-26 20:58:17 +00:00
if not thumb:
2023-03-04 13:45:26 +00:00
abort(404)
2023-03-26 20:58:17 +00:00
return send_from_directory(os.path.dirname(thumb), os.path.basename(thumb))
2023-04-07 12:35:30 +00:00
@blueprint.route("/upload", methods=["POST"])
@login_required
def upload():
2023-03-04 13:45:26 +00:00
"""
Uploads an image to the server and saves it to the database
"""
2023-04-07 12:35:30 +00:00
form_file = request.files["file"]
form = request.form
# If no image is uploaded, return 404 error
if not form_file:
return abort(404)
# Get file extension, generate random name and set file path
2023-04-07 12:35:30 +00:00
img_ext = pathlib.Path(form_file.filename).suffix.replace(".", "").lower()
img_name = "GWAGWA_" + str(uuid4())
2023-04-07 12:35:30 +00:00
img_path = os.path.join(
current_app.config["UPLOAD_FOLDER"], img_name + "." + img_ext
)
# Check if file extension is allowed
2023-04-07 12:35:30 +00:00
if img_ext not in current_app.config["ALLOWED_EXTENSIONS"].keys():
logging.info("File extension not allowed: %s", img_ext)
abort(403)
# Save file
try:
form_file.save(img_path)
2023-04-02 16:50:52 +00:00
except OSError as err:
2023-04-07 12:35:30 +00:00
logging.info("Error saving file %s because of %s", img_path, err)
abort(500)
img_exif = mt.Metadata(img_path).yoink() # Get EXIF data
2023-04-02 16:50:52 +00:00
img_colors = ColorThief(img_path).get_palette(color_count=3) # Get color palette
# Save to database
query = Posts(
2023-04-07 12:35:30 +00:00
author_id=current_user.id,
filename=img_name + "." + img_ext,
mimetype=img_ext,
exif=img_exif,
colours=img_colors,
description=form["description"],
alt=form["alt"],
)
2023-04-02 16:50:52 +00:00
db.session.add(query)
db.session.commit()
2023-04-02 16:50:52 +00:00
2023-04-07 12:35:30 +00:00
return "Gwa Gwa" # Return something so the browser doesn't show an error
2023-04-07 12:35:30 +00:00
@blueprint.route("/delete/<int:image_id>", methods=["POST"])
@login_required
def delete_image(image_id):
2023-03-04 13:45:26 +00:00
"""
Deletes an image from the server and database
"""
img = Posts.query.filter_by(id=image_id).first()
2023-03-26 20:58:17 +00:00
# Check if image exists and if user is allowed to delete it (author)
if img is None:
abort(404)
if img.author_id != current_user.id:
abort(403)
2023-03-26 20:58:17 +00:00
# Delete file
try:
2023-04-07 12:35:30 +00:00
os.remove(os.path.join(current_app.config["UPLOAD_FOLDER"], img.filename))
2023-03-04 13:45:26 +00:00
except FileNotFoundError:
2023-04-07 12:35:30 +00:00
logging.warning(
"File not found: %s, already deleted or never existed", img.filename
)
2023-03-26 20:58:17 +00:00
# Delete cached files
2023-04-07 12:35:30 +00:00
cache_path = os.path.join(platformdirs.user_config_dir("onlylegs"), "cache")
cache_name = img.filename.rsplit(".")[0]
for cache_file in pathlib.Path(cache_path).glob(cache_name + "*"):
os.remove(cache_file)
post = Posts.query.filter_by(id=image_id).first()
db.session.delete(post)
2023-04-10 15:43:42 +00:00
groups = GroupJunction.query.filter_by(post_id=image_id).all()
2023-03-26 20:58:17 +00:00
for group in groups:
db.session.delete(group)
2023-03-26 20:58:17 +00:00
# Commit all changes
db.session.commit()
2023-04-07 12:35:30 +00:00
logging.info("Removed image (%s) %s", image_id, img.filename)
flash(["Image was all in Le Head!", "1"])
return "Gwa Gwa"
2023-01-31 23:44:44 +00:00
2023-04-07 12:35:30 +00:00
@blueprint.route("/group/create", methods=["POST"])
@login_required
def create_group():
"""
Creates a group
"""
new_group = Groups(
2023-04-07 12:35:30 +00:00
name=request.form["name"],
description=request.form["description"],
author_id=current_user.id,
)
db.session.add(new_group)
db.session.commit()
2023-04-07 12:35:30 +00:00
return ":3"
2023-04-07 12:35:30 +00:00
@blueprint.route("/group/modify", methods=["POST"])
@login_required
def modify_group():
"""
Changes the images in a group
"""
2023-04-07 12:35:30 +00:00
group_id = request.form["group"]
image_id = request.form["image"]
action = request.form["action"]
group = Groups.query.filter_by(id=group_id).first()
if group is None:
abort(404)
elif group.author_id != current_user.id:
abort(403)
2023-04-07 12:35:30 +00:00
if action == "add":
2023-04-10 15:43:42 +00:00
if not GroupJunction.query.filter_by(
group_id=group_id, post_id=image_id
).first():
db.session.add(GroupJunction(group_id=group_id, post_id=image_id))
2023-04-07 12:35:30 +00:00
elif request.form["action"] == "remove":
2023-04-10 15:43:42 +00:00
db.session.delete(
GroupJunction.query.filter_by(group_id=group_id, post_id=image_id).first()
)
db.session.commit()
2023-04-07 12:35:30 +00:00
return ":3"
2023-04-07 12:35:30 +00:00
@blueprint.route("/group/delete", methods=["POST"])
def delete_group():
2023-03-04 13:45:26 +00:00
"""
Deletes a group
2023-03-04 13:45:26 +00:00
"""
2023-04-07 12:35:30 +00:00
group_id = request.form["group"]
group = Groups.query.filter_by(id=group_id).first()
if group is None:
abort(404)
elif group.author_id != current_user.id:
abort(403)
2023-01-31 23:44:44 +00:00
group_del = Groups.query.filter_by(id=group_id).first()
db.session.delete(group_del)
2023-04-10 15:43:42 +00:00
junction_del = GroupJunction.query.filter_by(group_id=group_id).all()
for junction in junction_del:
db.session.delete(junction)
2023-04-10 15:43:42 +00:00
db.session.commit()
2023-04-07 12:35:30 +00:00
flash(["Group yeeted!", "1"])
return ":3"