Clean up theme compiler and thumbnail generation

Fix signup not clearning blanks - Thanks to Fennec
This commit is contained in:
Michał Gdula 2023-04-01 16:59:17 +00:00
parent 0e24004c0b
commit 95e5f3938f
7 changed files with 55 additions and 73 deletions

View file

@ -60,7 +60,7 @@ def create_app(test_config=None):
app.config.from_mapping(test_config) app.config.from_mapping(test_config)
# Load theme # Load theme
theme_manager.CompileTheme('default', app.root_path) theme_manager.compile_theme('default', app.root_path)
# Bundle JS files # Bundle JS files
js_scripts = Bundle('js/*.js', output='gen/packed.js') js_scripts = Bundle('js/*.js', output='gen/packed.js')
@ -82,7 +82,7 @@ def create_app(test_config=None):
app.register_blueprint(auth.blueprint) app.register_blueprint(auth.blueprint)
# Load the different routes # Load the different routes
from .routes import api, groups, routing, settings from gallery.routes import api, groups, routing, settings
app.register_blueprint(api.blueprint) app.register_blueprint(api.blueprint)
app.register_blueprint(groups.blueprint) app.register_blueprint(groups.blueprint)
app.register_blueprint(routing.blueprint) app.register_blueprint(routing.blueprint)

View file

@ -65,15 +65,16 @@ def register():
""" """
Register a new user Register a new user
""" """
username = request.form['username'] # Thanks Fennec for reminding me to strip out the whitespace lol
email = request.form['email'] username = request.form['username'].strip()
password = request.form['password'] email = request.form['email'].strip()
password_repeat = request.form['password-repeat'] password = request.form['password'].strip()
password_repeat = request.form['password-repeat'].strip()
error = [] error = []
email_regex = re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b') email_regex = re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b')
username_regex = re.compile(r'\b[A-Za-z0-9._%+-]+\b') username_regex = re.compile(r'\b[A-Za-z0-9._-]+\b')
if not username or not username_regex.match(username): if not username or not username_regex.match(username):
error.append('Username is invalid!') error.append('Username is invalid!')
@ -116,8 +117,8 @@ def login():
""" """
Log in a registered user by adding the user id to the session Log in a registered user by adding the user id to the session
""" """
username = request.form['username'] username = request.form['username'].strip()
password = request.form['password'] password = request.form['password'].strip()
user = db_session.query(db.Users).filter_by(username=username).first() user = db_session.query(db.Users).filter_by(username=username).first()
error = [] error = []

View file

View file

@ -33,6 +33,7 @@ def file(file_name):
r for resolution, 400x400 or thumb for thumbnail r for resolution, 400x400 or thumb for thumbnail
""" """
res = request.args.get('r', default=None, type=str) # Type of file (thumb, etc) 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 file_name = secure_filename(file_name) # Sanitize file name
# if no args are passed, return the raw file # if no args are passed, return the raw file
@ -42,7 +43,7 @@ def file(file_name):
return send_from_directory(current_app.config['UPLOAD_FOLDER'], file_name) return send_from_directory(current_app.config['UPLOAD_FOLDER'], file_name)
thumb = generate_thumbnail(file_name, res) thumb = generate_thumbnail(file_name, res, ext)
if not thumb: if not thumb:
abort(404) abort(404)

View file

@ -34,10 +34,12 @@ def generate_thumbnail(file_name, resolution, ext=None):
ext = "jpeg" ext = "jpeg"
# Set resolution based on preset resolutions # Set resolution based on preset resolutions
if resolution in ['thumb', 'thumbnail']: if resolution in ['prev', 'preview']:
res_x, res_y = (400, 400)
elif resolution in ['prev', 'preview']:
res_x, res_y = (1920, 1080) res_x, res_y = (1920, 1080)
elif resolution in ['thumb', 'thumbnail']:
res_x, res_y = (400, 400)
elif resolution in ['icon', 'favicon']:
res_x, res_y = (10, 10)
elif len(resolution.split('x')) == 2: elif len(resolution.split('x')) == 2:
res_x, res_y = resolution.split('x') res_x, res_y = resolution.split('x')
else: else:

View file

@ -8,75 +8,53 @@ from datetime import datetime
import sass import sass
class CompileTheme: def compile_theme(theme_name, app_path):
""" """
Compiles the theme into the static folder Compiles the theme into the static folder
""" """
def __init__(self, theme_name, app_path):
"""
Initialize the theme manager
Compiles the theme into the static folder and loads the fonts
"""
print(f"Loading '{theme_name}' theme...") print(f"Loading '{theme_name}' theme...")
theme_path = os.path.join(app_path, 'themes', theme_name) # Set Paths
theme_dest = os.path.join(app_path, 'static', 'theme') THEME_SRC = os.path.join(app_path, 'themes', theme_name)
THEME_DEST = os.path.join(app_path, 'static', 'theme')
if not os.path.exists(theme_path): # If the theme doesn't exist, exit
if not os.path.exists(THEME_SRC):
print("Theme does not exist!") print("Theme does not exist!")
sys.exit(1) sys.exit(1)
if not os.path.exists(theme_dest): # If the destination folder doesn't exist, create it
os.makedirs(theme_dest) if not os.path.exists(THEME_DEST):
os.makedirs(THEME_DEST)
self.load_sass(theme_path, theme_dest) # Theme source file doesn't exist, exit
self.load_fonts(theme_path, theme_dest) if not os.path.join(THEME_SRC, 'style.sass'):
print(f"{datetime.now().hour}:{datetime.now().minute}:{datetime.now().second} - Done!\n")
@staticmethod
def load_sass(source_path, css_dest):
"""
Compile the sass (or scss) file into css and save it to the static folder
"""
if os.path.join(source_path, 'style.sass'):
sass_path = os.path.join(source_path, 'style.sass')
elif os.path.join(source_path, 'style.scss'):
sass_path = os.path.join(source_path, 'style.scss')
else:
print("No sass file found!") print("No sass file found!")
sys.exit(1) sys.exit(1)
with open(os.path.join(css_dest, 'style.css'), encoding='utf-8', mode='w+') as file: # Compile the theme
with open(os.path.join(THEME_DEST, 'style.css'), encoding='utf-8', mode='w+') as file:
try: try:
file.write(sass.compile(filename=sass_path,output_style='compressed')) file.write(sass.compile(filename=os.path.join(THEME_SRC, 'style.sass'),output_style='compressed'))
except sass.CompileError as err: except sass.CompileError as err:
print("Failed to compile!\n", err) print("Failed to compile!\n", err)
sys.exit(1) sys.exit(1)
print("Compiled successfully!") print("Compiled successfully!")
@staticmethod # If the destination folder exists, remove it
def load_fonts(source_path, font_dest): if os.path.exists(os.path.join(THEME_DEST, 'fonts')):
"""
Copy the fonts folder to the static folder
"""
# Append fonts to the destination path
source_path = os.path.join(source_path, 'fonts')
font_dest = os.path.join(font_dest, 'fonts')
if os.path.exists(font_dest):
try: try:
shutil.rmtree(font_dest) shutil.rmtree(os.path.join(THEME_DEST, 'fonts'))
except Exception as err: except Exception as err:
print("Failed to remove old fonts!\n", err) print("Failed to remove old fonts!\n", err)
sys.exit(1) sys.exit(1)
# Copy the fonts
try: try:
shutil.copytree(source_path, font_dest) shutil.copytree(os.path.join(THEME_SRC, 'fonts'), os.path.join(THEME_DEST, 'fonts'))
print("Fonts copied successfully!")
except Exception as err: except Exception as err:
print("Failed to copy fonts!\n", err) print("Failed to copy fonts!\n", err)
sys.exit(1) sys.exit(1)
print("Fonts copied successfully!") print(f"{datetime.now().hour}:{datetime.now().minute}:{datetime.now().second} - Done!\n")