mirror of
https://github.com/Derpy-Leggies/OnlyLegs.git
synced 2025-06-29 11:36:16 +00:00
Move views/routes to seperate files
This commit is contained in:
parent
7eb4355b52
commit
f33842ead3
13 changed files with 150 additions and 116 deletions
|
@ -1,210 +0,0 @@
|
|||
"""
|
||||
Onlylegs - API endpoints
|
||||
"""
|
||||
from uuid import uuid4
|
||||
import os
|
||||
import pathlib
|
||||
import logging
|
||||
import platformdirs
|
||||
|
||||
from flask import Blueprint, send_from_directory, abort, flash, request, current_app
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
from flask_login import login_required, current_user
|
||||
|
||||
from colorthief import ColorThief
|
||||
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from gallery import db
|
||||
from gallery.utils import metadata as mt
|
||||
from gallery.utils.generate_image import generate_thumbnail
|
||||
|
||||
|
||||
blueprint = Blueprint('api', __name__, url_prefix='/api')
|
||||
db_session = sessionmaker(bind=db.engine)
|
||||
db_session = db_session()
|
||||
|
||||
|
||||
@blueprint.route('/file/<file_name>', methods=['GET'])
|
||||
def file(file_name):
|
||||
"""
|
||||
Returns a file from the uploads folder
|
||||
r for resolution, 400x400 or thumb for thumbnail
|
||||
"""
|
||||
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
|
||||
if not res and not ext:
|
||||
if not os.path.exists(os.path.join(current_app.config['UPLOAD_FOLDER'], file_name)):
|
||||
abort(404)
|
||||
return send_from_directory(current_app.config['UPLOAD_FOLDER'], file_name)
|
||||
|
||||
thumb = generate_thumbnail(file_name, res, ext)
|
||||
if not thumb:
|
||||
abort(404)
|
||||
|
||||
return send_from_directory(os.path.dirname(thumb), os.path.basename(thumb))
|
||||
|
||||
|
||||
@blueprint.route('/upload', methods=['POST'])
|
||||
@login_required
|
||||
def upload():
|
||||
"""
|
||||
Uploads an image to the server and saves it to the database
|
||||
"""
|
||||
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
|
||||
img_ext = pathlib.Path(form_file.filename).suffix.replace('.', '').lower()
|
||||
img_name = "GWAGWA_" + str(uuid4())
|
||||
img_path = os.path.join(current_app.config['UPLOAD_FOLDER'], img_name+'.'+img_ext)
|
||||
|
||||
# Check if file extension is allowed
|
||||
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)
|
||||
except OSError as err:
|
||||
logging.info('Error saving file %s because of %s', img_path, err)
|
||||
abort(500)
|
||||
|
||||
img_exif = mt.Metadata(img_path).yoink() # Get EXIF data
|
||||
img_colors = ColorThief(img_path).get_palette(color_count=3) # Get color palette
|
||||
|
||||
# Save to database
|
||||
query = db.Posts(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'])
|
||||
|
||||
db_session.add(query)
|
||||
db_session.commit()
|
||||
|
||||
return 'Gwa Gwa' # Return something so the browser doesn't show an error
|
||||
|
||||
|
||||
@blueprint.route('/delete/<int:image_id>', methods=['POST'])
|
||||
@login_required
|
||||
def delete_image(image_id):
|
||||
"""
|
||||
Deletes an image from the server and database
|
||||
"""
|
||||
img = db_session.query(db.Posts).filter_by(id=image_id).first()
|
||||
|
||||
# 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)
|
||||
|
||||
# Delete file
|
||||
try:
|
||||
os.remove(os.path.join(current_app.config['UPLOAD_FOLDER'], img.filename))
|
||||
except FileNotFoundError:
|
||||
logging.warning('File not found: %s, already deleted or never existed', img.filename)
|
||||
|
||||
# Delete cached files
|
||||
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)
|
||||
|
||||
# Delete from database
|
||||
db_session.query(db.Posts).filter_by(id=image_id).delete()
|
||||
|
||||
# Remove all entries in junction table
|
||||
groups = db_session.query(db.GroupJunction).filter_by(post_id=image_id).all()
|
||||
for group in groups:
|
||||
db_session.delete(group)
|
||||
|
||||
# Commit all changes
|
||||
db_session.commit()
|
||||
|
||||
logging.info('Removed image (%s) %s', image_id, img.filename)
|
||||
flash(['Image was all in Le Head!', '1'])
|
||||
return 'Gwa Gwa'
|
||||
|
||||
|
||||
@blueprint.route('/group/create', methods=['POST'])
|
||||
@login_required
|
||||
def create_group():
|
||||
"""
|
||||
Creates a group
|
||||
"""
|
||||
new_group = db.Groups(name=request.form['name'],
|
||||
description=request.form['description'],
|
||||
author_id=current_user.id)
|
||||
|
||||
db_session.add(new_group)
|
||||
db_session.commit()
|
||||
|
||||
return ':3'
|
||||
|
||||
|
||||
@blueprint.route('/group/modify', methods=['POST'])
|
||||
@login_required
|
||||
def modify_group():
|
||||
"""
|
||||
Changes the images in a group
|
||||
"""
|
||||
group_id = request.form['group']
|
||||
image_id = request.form['image']
|
||||
action = request.form['action']
|
||||
|
||||
group = db_session.query(db.Groups).filter_by(id=group_id).first()
|
||||
|
||||
if group is None:
|
||||
abort(404)
|
||||
elif group.author_id != current_user.id:
|
||||
abort(403)
|
||||
|
||||
if action == 'add':
|
||||
if not (db_session.query(db.GroupJunction)
|
||||
.filter_by(group_id=group_id, post_id=image_id)
|
||||
.first()):
|
||||
db_session.add(db.GroupJunction(group_id=group_id,
|
||||
post_id=image_id))
|
||||
elif request.form['action'] == 'remove':
|
||||
(db_session.query(db.GroupJunction)
|
||||
.filter_by(group_id=group_id, post_id=image_id)
|
||||
.delete())
|
||||
|
||||
db_session.commit()
|
||||
|
||||
return ':3'
|
||||
|
||||
|
||||
@blueprint.route('/group/delete', methods=['POST'])
|
||||
def delete_group():
|
||||
"""
|
||||
Deletes a group
|
||||
"""
|
||||
group_id = request.form['group']
|
||||
|
||||
group = db_session.query(db.Groups).filter_by(id=group_id).first()
|
||||
|
||||
if group is None:
|
||||
abort(404)
|
||||
elif group.author_id != current_user.id:
|
||||
abort(403)
|
||||
|
||||
db_session.query(db.Groups).filter_by(id=group_id).delete()
|
||||
db_session.query(db.GroupJunction).filter_by(group_id=group_id).delete()
|
||||
db_session.commit()
|
||||
|
||||
flash(['Group yeeted!', '1'])
|
||||
return ':3'
|
|
@ -42,7 +42,7 @@ def groups():
|
|||
.filter(db.Posts.id == image[0])
|
||||
.first())
|
||||
|
||||
return render_template('groups/list.html', groups=groups)
|
||||
return render_template('list.html', groups=groups)
|
||||
|
||||
|
||||
@blueprint.route('/<int:group_id>')
|
||||
|
@ -83,7 +83,7 @@ def group(group_id):
|
|||
'rgb(var(--fg-black))',
|
||||
'rgb(var(--fg-white))')
|
||||
|
||||
return render_template('groups/group.html',
|
||||
return render_template('group.html',
|
||||
group=group,
|
||||
images=images,
|
||||
text_colour=text_colour)
|
59
gallery/views/image.py
Normal file
59
gallery/views/image.py
Normal file
|
@ -0,0 +1,59 @@
|
|||
"""
|
||||
Onlylegs - Image View
|
||||
"""
|
||||
from flask import Blueprint, abort, render_template, url_for
|
||||
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from gallery import db
|
||||
|
||||
|
||||
blueprint = Blueprint('image', __name__, url_prefix='/image')
|
||||
db_session = sessionmaker(bind=db.engine)
|
||||
db_session = db_session()
|
||||
|
||||
|
||||
@blueprint.route('/<int:image_id>')
|
||||
def image(image_id):
|
||||
"""
|
||||
Image view, shows the image and its metadata
|
||||
"""
|
||||
# Get the image, if it doesn't exist, 404
|
||||
image = db_session.query(db.Posts).filter(db.Posts.id == image_id).first()
|
||||
if not image:
|
||||
abort(404, 'Image not found :<')
|
||||
|
||||
# Get the image's author username
|
||||
image.author_username = (db_session.query(db.Users.username)
|
||||
.filter(db.Users.id == image.author_id)
|
||||
.first()[0])
|
||||
|
||||
# Get the image's groups
|
||||
groups = (db_session.query(db.GroupJunction.group_id)
|
||||
.filter(db.GroupJunction.post_id == image_id)
|
||||
.all())
|
||||
|
||||
# For each group, get the group data and add it to the image item
|
||||
image.groups = []
|
||||
for group in groups:
|
||||
image.groups.append(db_session.query(db.Groups.id, db.Groups.name)
|
||||
.filter(db.Groups.id == group[0])
|
||||
.first())
|
||||
|
||||
# Get the next and previous images
|
||||
# Check if there is a group ID set
|
||||
next_url = (db_session.query(db.Posts.id)
|
||||
.filter(db.Posts.id > image_id)
|
||||
.order_by(db.Posts.id.asc())
|
||||
.first())
|
||||
prev_url = (db_session.query(db.Posts.id)
|
||||
.filter(db.Posts.id < image_id)
|
||||
.order_by(db.Posts.id.desc())
|
||||
.first())
|
||||
|
||||
# If there is a next or previous image, get the url
|
||||
if next_url:
|
||||
next_url = url_for('image.image', image_id=next_url[0])
|
||||
if prev_url:
|
||||
prev_url = url_for('image.image', image_id=prev_url[0])
|
||||
|
||||
return render_template('image.html', image=image, next_url=next_url, prev_url=prev_url)
|
30
gallery/views/index.py
Normal file
30
gallery/views/index.py
Normal file
|
@ -0,0 +1,30 @@
|
|||
"""
|
||||
Onlylegs Gallery - Index view
|
||||
"""
|
||||
from flask import Blueprint, render_template, request
|
||||
from werkzeug.exceptions import abort
|
||||
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from gallery import db
|
||||
|
||||
|
||||
blueprint = Blueprint('gallery', __name__)
|
||||
db_session = sessionmaker(bind=db.engine)
|
||||
db_session = db_session()
|
||||
|
||||
|
||||
@blueprint.route('/')
|
||||
def index():
|
||||
"""
|
||||
Home page of the website, shows the feed of the latest images
|
||||
"""
|
||||
images = db_session.query(db.Posts.filename,
|
||||
db.Posts.alt,
|
||||
db.Posts.colours,
|
||||
db.Posts.created_at,
|
||||
db.Posts.id).order_by(db.Posts.id.desc()).all()
|
||||
|
||||
if request.args.get('coffee') == 'please':
|
||||
abort(418)
|
||||
|
||||
return render_template('index.html', images=images)
|
39
gallery/views/profile.py
Normal file
39
gallery/views/profile.py
Normal file
|
@ -0,0 +1,39 @@
|
|||
"""
|
||||
Onlylegs Gallery - Profile view
|
||||
"""
|
||||
from flask import Blueprint, render_template, request
|
||||
from werkzeug.exceptions import abort
|
||||
from flask_login import current_user
|
||||
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from gallery import db
|
||||
|
||||
|
||||
blueprint = Blueprint('profile', __name__, url_prefix='/profile')
|
||||
db_session = sessionmaker(bind=db.engine)
|
||||
db_session = db_session()
|
||||
|
||||
|
||||
@blueprint.route('/profile')
|
||||
def profile():
|
||||
"""
|
||||
Profile overview, shows all profiles on the onlylegs gallery
|
||||
"""
|
||||
user_id = request.args.get('id', default=None, type=int)
|
||||
|
||||
# If there is no userID set, check if the user is logged in and display their profile
|
||||
if not user_id:
|
||||
if current_user.is_authenticated:
|
||||
user_id = current_user.id
|
||||
else:
|
||||
abort(404, 'You must be logged in to view your own profile!')
|
||||
|
||||
# Get the user's data
|
||||
user = db_session.query(db.Users).filter(db.Users.id == user_id).first()
|
||||
|
||||
if not user:
|
||||
abort(404, 'User not found :c')
|
||||
|
||||
images = db_session.query(db.Posts).filter(db.Posts.author_id == user_id).all()
|
||||
|
||||
return render_template('profile.html', user=user, images=images)
|
|
@ -1,102 +0,0 @@
|
|||
"""
|
||||
Onlylegs Gallery - Routing
|
||||
"""
|
||||
from flask import Blueprint, render_template, url_for, request
|
||||
from werkzeug.exceptions import abort
|
||||
from flask_login import current_user
|
||||
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from gallery import db
|
||||
|
||||
|
||||
blueprint = Blueprint('gallery', __name__)
|
||||
db_session = sessionmaker(bind=db.engine)
|
||||
db_session = db_session()
|
||||
|
||||
|
||||
@blueprint.route('/')
|
||||
def index():
|
||||
"""
|
||||
Home page of the website, shows the feed of the latest images
|
||||
"""
|
||||
images = db_session.query(db.Posts.filename,
|
||||
db.Posts.alt,
|
||||
db.Posts.colours,
|
||||
db.Posts.created_at,
|
||||
db.Posts.id).order_by(db.Posts.id.desc()).all()
|
||||
|
||||
if request.args.get('coffee') == 'please':
|
||||
abort(418)
|
||||
|
||||
return render_template('index.html', images=images)
|
||||
|
||||
|
||||
@blueprint.route('/image/<int:image_id>')
|
||||
def image(image_id):
|
||||
"""
|
||||
Image view, shows the image and its metadata
|
||||
"""
|
||||
# Get the image, if it doesn't exist, 404
|
||||
image = db_session.query(db.Posts).filter(db.Posts.id == image_id).first()
|
||||
if not image:
|
||||
abort(404, 'Image not found :<')
|
||||
|
||||
# Get the image's author username
|
||||
image.author_username = (db_session.query(db.Users.username)
|
||||
.filter(db.Users.id == image.author_id)
|
||||
.first()[0])
|
||||
|
||||
# Get the image's groups
|
||||
groups = (db_session.query(db.GroupJunction.group_id)
|
||||
.filter(db.GroupJunction.post_id == image_id)
|
||||
.all())
|
||||
|
||||
# For each group, get the group data and add it to the image item
|
||||
image.groups = []
|
||||
for group in groups:
|
||||
image.groups.append(db_session.query(db.Groups.id, db.Groups.name)
|
||||
.filter(db.Groups.id == group[0])
|
||||
.first())
|
||||
|
||||
# Get the next and previous images
|
||||
next_url = (db_session.query(db.Posts.id)
|
||||
.filter(db.Posts.id > image_id)
|
||||
.order_by(db.Posts.id.asc())
|
||||
.first())
|
||||
prev_url = (db_session.query(db.Posts.id)
|
||||
.filter(db.Posts.id < image_id)
|
||||
.order_by(db.Posts.id.desc())
|
||||
.first())
|
||||
|
||||
# If there is a next or previous image, get the url
|
||||
if next_url:
|
||||
next_url = url_for('gallery.image', image_id=next_url[0])
|
||||
if prev_url:
|
||||
prev_url = url_for('gallery.image', image_id=prev_url[0])
|
||||
|
||||
return render_template('image.html', image=image, next_url=next_url, prev_url=prev_url)
|
||||
|
||||
|
||||
@blueprint.route('/profile')
|
||||
def profile():
|
||||
"""
|
||||
Profile overview, shows all profiles on the onlylegs gallery
|
||||
"""
|
||||
user_id = request.args.get('id', default=None, type=int)
|
||||
|
||||
# If there is no userID set, check if the user is logged in and display their profile
|
||||
if not user_id:
|
||||
if current_user.is_authenticated:
|
||||
user_id = current_user.id
|
||||
else:
|
||||
abort(404, 'You must be logged in to view your own profile!')
|
||||
|
||||
# Get the user's data
|
||||
user = db_session.query(db.Users).filter(db.Users.id == user_id).first()
|
||||
|
||||
if not user:
|
||||
abort(404, 'User not found :c')
|
||||
|
||||
images = db_session.query(db.Posts).filter(db.Posts.author_id == user_id).all()
|
||||
|
||||
return render_template('profile.html', user=user, images=images)
|
Loading…
Add table
Add a link
Reference in a new issue