mirror of
https://github.com/Derpy-Leggies/OnlyLegs.git
synced 2025-06-29 03:26:16 +00:00
Submitted to PyLints needs :3
This commit is contained in:
parent
4cfcd178f1
commit
7ed3b455dd
12 changed files with 509 additions and 460 deletions
151
gallery/api.py
151
gallery/api.py
|
@ -1,38 +1,48 @@
|
|||
from flask import Blueprint, current_app, send_from_directory, send_file, request, g, abort, flash, jsonify
|
||||
"""
|
||||
Onlylegs - API endpoints
|
||||
Used intermally by the frontend and possibly by other applications
|
||||
"""
|
||||
from uuid import uuid4
|
||||
import os
|
||||
import io
|
||||
import logging
|
||||
|
||||
from flask import (
|
||||
Blueprint, current_app, send_from_directory, send_file, request, g, abort, flash, jsonify)
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
from PIL import Image, ImageOps # ImageFilter
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from gallery.auth import login_required
|
||||
|
||||
from . import db
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
db_session = sessionmaker(bind=db.engine)
|
||||
db_session = db_session()
|
||||
|
||||
from PIL import Image, ImageOps, ImageFilter
|
||||
from . import db # Import db to create a session
|
||||
from . import metadata as mt
|
||||
|
||||
from .logger import logger
|
||||
|
||||
from uuid import uuid4
|
||||
import io
|
||||
import os
|
||||
|
||||
blueprint = Blueprint('api', __name__, url_prefix='/api')
|
||||
db_session = sessionmaker(bind=db.engine)
|
||||
db_session = db_session()
|
||||
|
||||
|
||||
@blueprint.route('/uploads/<file>', methods=['GET'])
|
||||
def uploads(file):
|
||||
"""
|
||||
Returns a file from the uploads folder
|
||||
w and h are the width and height of the image for resizing
|
||||
f is whether to apply filters to the image, such as blurring NSFW images
|
||||
"""
|
||||
# Get args
|
||||
width = request.args.get('w', default=0, type=int) # Width of image
|
||||
height = request.args.get('h', default=0, type=int) # Height of image
|
||||
filtered = request.args.get('f', default=False, type=bool) # Whether to apply filters to image,
|
||||
# such as blur for NSFW images
|
||||
filtered = request.args.get('f', default=False, type=bool) # Whether to apply filters
|
||||
|
||||
# if no args are passed, return the raw file
|
||||
if width == 0 and height == 0 and not filtered:
|
||||
return send_from_directory(current_app.config['UPLOAD_FOLDER'],
|
||||
secure_filename(file),
|
||||
as_attachment=True)
|
||||
if not os.path.exists(os.path.join(current_app.config['UPLOAD_FOLDER'],
|
||||
secure_filename(file))):
|
||||
abort(404)
|
||||
return send_from_directory(current_app.config['UPLOAD_FOLDER'], file ,as_attachment=True)
|
||||
|
||||
# Of either width or height is 0, set it to the other value to keep aspect ratio
|
||||
if width > 0 and height == 0:
|
||||
|
@ -45,29 +55,28 @@ def uploads(file):
|
|||
|
||||
# Open image and set extension
|
||||
try:
|
||||
img = Image.open(
|
||||
os.path.join(current_app.config['UPLOAD_FOLDER'],
|
||||
secure_filename(file)))
|
||||
except Exception as e:
|
||||
logger.server(600, f"Error opening image: {e}")
|
||||
img = Image.open(os.path.join(current_app.config['UPLOAD_FOLDER'],file))
|
||||
except FileNotFoundError:
|
||||
logging.error('File not found: %s, possibly broken upload', file)
|
||||
abort(404)
|
||||
except Exception as err:
|
||||
logging.error('Error opening image: %s', err)
|
||||
abort(500)
|
||||
|
||||
img_ext = os.path.splitext(secure_filename(file))[-1].lower().replace(
|
||||
'.', '')
|
||||
img_ext = os.path.splitext(file)[-1].lower().replace('.', '')
|
||||
img_ext = set_ext[img_ext]
|
||||
img_icc = img.info.get(
|
||||
"icc_profile") # Get ICC profile as it alters colours
|
||||
# Get ICC profile as it alters colours when saving
|
||||
img_icc = img.info.get("icc_profile")
|
||||
|
||||
# Resize image and orientate correctly
|
||||
img.thumbnail((width, height), Image.LANCZOS)
|
||||
img = ImageOps.exif_transpose(img)
|
||||
|
||||
# TODO: Add filters
|
||||
|
||||
# If has NSFW tag, blur image, etc.
|
||||
if filtered:
|
||||
#pass
|
||||
img = img.filter(ImageFilter.GaussianBlur(20))
|
||||
|
||||
#img = img.filter(ImageFilter.GaussianBlur(20))
|
||||
pass
|
||||
|
||||
try:
|
||||
img.save(buff, img_ext, icc_profile=img_icc)
|
||||
except OSError:
|
||||
|
@ -75,8 +84,8 @@ def uploads(file):
|
|||
# Convert to RGB and try again
|
||||
img = img.convert('RGB')
|
||||
img.save(buff, img_ext, icc_profile=img_icc)
|
||||
except:
|
||||
logger.server(600, f"Error resizing image: {file}")
|
||||
except Exception as err:
|
||||
logging.error('Could not resize image %s, error: %s', file, err)
|
||||
abort(500)
|
||||
|
||||
img.close()
|
||||
|
@ -89,47 +98,51 @@ def uploads(file):
|
|||
@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 not form_file:
|
||||
return abort(404)
|
||||
|
||||
img_ext = os.path.splitext(secure_filename(
|
||||
form_file.filename))[-1].replace('.', '').lower()
|
||||
img_name = f"GWAGWA_{uuid4().__str__()}.{img_ext}"
|
||||
img_ext = os.path.splitext(form_file.filename)[-1].replace('.', '').lower()
|
||||
img_name = f"GWAGWA_{str(uuid4())}.{img_ext}"
|
||||
|
||||
if not img_ext in current_app.config['ALLOWED_EXTENSIONS'].keys():
|
||||
logger.add(303, f"File extension not allowed: {img_ext}")
|
||||
logging.info('File extension not allowed: %s', img_ext)
|
||||
abort(403)
|
||||
|
||||
if os.path.isdir(current_app.config['UPLOAD_FOLDER']) == False:
|
||||
if os.path.isdir(current_app.config['UPLOAD_FOLDER']) is False:
|
||||
os.mkdir(current_app.config['UPLOAD_FOLDER'])
|
||||
|
||||
# Save to database
|
||||
try:
|
||||
tr = db.posts(img_name, form['description'], form['alt'], g.user.id)
|
||||
db_session.add(tr)
|
||||
db_session.add(db.posts(img_name, form['description'], form['alt'], g.user.id))
|
||||
db_session.commit()
|
||||
except Exception as e:
|
||||
logger.server(600, f"Error saving to database: {e}")
|
||||
except Exception as err:
|
||||
logging.error('Could not save to database: %s', err)
|
||||
abort(500)
|
||||
|
||||
# Save file
|
||||
try:
|
||||
form_file.save(
|
||||
os.path.join(current_app.config['UPLOAD_FOLDER'], img_name))
|
||||
except Exception as e:
|
||||
logger.server(600, f"Error saving file: {e}")
|
||||
except Exception as err:
|
||||
logging.error('Could not save file: %s', err)
|
||||
abort(500)
|
||||
|
||||
return 'Gwa Gwa'
|
||||
|
||||
|
||||
@blueprint.route('/remove/<int:id>', methods=['POST'])
|
||||
@blueprint.route('/remove/<int:img_id>', methods=['POST'])
|
||||
@login_required
|
||||
def remove(id):
|
||||
img = db_session.query(db.posts).filter_by(id=id).first()
|
||||
def remove(img_id):
|
||||
"""
|
||||
Deletes an image from the server and database
|
||||
"""
|
||||
img = db_session.query(db.posts).filter_by(id=img_id).first()
|
||||
|
||||
if img is None:
|
||||
abort(404)
|
||||
|
@ -137,28 +150,32 @@ def remove(id):
|
|||
abort(403)
|
||||
|
||||
try:
|
||||
os.remove(
|
||||
os.path.join(current_app.config['UPLOAD_FOLDER'],
|
||||
img.file_name))
|
||||
except Exception as e:
|
||||
logger.server(600, f"Error removing file: {e}")
|
||||
os.remove(os.path.join(current_app.config['UPLOAD_FOLDER'],img.file_name))
|
||||
except FileNotFoundError:
|
||||
# File was already deleted or doesn't exist
|
||||
logging.warning('File not found: %s, already deleted or never existed', img.file_name)
|
||||
except Exception as err:
|
||||
logging.error('Could not remove file: %s', err)
|
||||
abort(500)
|
||||
|
||||
try:
|
||||
db_session.query(db.posts).filter_by(id=id).delete()
|
||||
db_session.query(db.posts).filter_by(id=img_id).delete()
|
||||
db_session.commit()
|
||||
except Exception as e:
|
||||
logger.server(600, f"Error removing from database: {e}")
|
||||
except Exception as err:
|
||||
logging.error('Could not remove from database: %s', err)
|
||||
abort(500)
|
||||
|
||||
logger.server(301, f"Removed image {id}")
|
||||
logging.info('Removed image (%s) %s', img_id, img.file_name)
|
||||
flash(['Image was all in Le Head!', 1])
|
||||
return 'Gwa Gwa'
|
||||
|
||||
|
||||
@blueprint.route('/metadata/<int:id>', methods=['GET'])
|
||||
def metadata(id):
|
||||
img = db_session.query(db.posts).filter_by(id=id).first()
|
||||
@blueprint.route('/metadata/<int:img_id>', methods=['GET'])
|
||||
def metadata(img_id):
|
||||
"""
|
||||
Yoinks metadata from an image
|
||||
"""
|
||||
img = db_session.query(db.posts).filter_by(id=img_id).first()
|
||||
|
||||
if img is None:
|
||||
abort(404)
|
||||
|
@ -172,12 +189,15 @@ def metadata(id):
|
|||
@blueprint.route('/logfile')
|
||||
@login_required
|
||||
def logfile():
|
||||
filename = logger.filename()
|
||||
"""
|
||||
Gets the log file and returns it as a JSON object
|
||||
"""
|
||||
filename = logging.getLoggerClass().root.handlers[0].baseFilename
|
||||
log_dict = {}
|
||||
i = 0
|
||||
|
||||
with open(filename) as f:
|
||||
for line in f:
|
||||
with open(filename, encoding='utf-8') as file:
|
||||
for line in file:
|
||||
line = line.split(' : ')
|
||||
|
||||
event = line[0].strip().split(' ')
|
||||
|
@ -194,11 +214,14 @@ def logfile():
|
|||
'code': int(message[1:4]),
|
||||
'message': message[5:].strip()
|
||||
}
|
||||
except:
|
||||
except ValueError:
|
||||
message_data = {'code': 0, 'message': message}
|
||||
except Exception as err:
|
||||
logging.error('Could not parse log file: %s', err)
|
||||
abort(500)
|
||||
|
||||
log_dict[i] = {'event': event_data, 'message': message_data}
|
||||
|
||||
i += 1 # Line number, starts at 0
|
||||
|
||||
return jsonify(log_dict)
|
||||
return jsonify(log_dict)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue