Skip to content

Commit

Permalink
implemented jit-optimization for images
Browse files Browse the repository at this point in the history
  • Loading branch information
Barakudum committed Feb 25, 2024
1 parent 68adf1d commit 92dd73f
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 9 deletions.
21 changes: 16 additions & 5 deletions scripts/wizard.sh
Original file line number Diff line number Diff line change
Expand Up @@ -185,13 +185,21 @@ function wizard_create_config() {
)
fi

if whiptail --title "$TITLE - gzip" --yesno "Whether to gzip the content. Reduces the response-size and thus loading time of text-based responses on cost of CPU-Time.
if whiptail --title "$TITLE - Server" --yesno "Whether to gzip the content. Reduces the response-size and thus loading time of text-based responses on cost of CPU-Time.
note: Should be done by the Proxy-Server if possible. Otherwise, this is the option." 20 60; then
GZIP="yes"
else
GZIP="no"
fi

if whiptail --title "$TITLE - Server" --yesno "Allow media optimization.
Enabling this option allows for faster downloads as supported media is just-in-time optimized.
Important: only use this option for a very small userbase as it can take up lots of system-resources." 20 60; then
OPTIMIZE=true
else
OPTIMIZE=false
fi

if whiptail --title "$TITLE - Auth" --yesno "Do you want to require authentication?" 20 60; then
USERNAME=$(
whiptail --title "$TITLE - Auth" --inputbox "Username:" 20 60 3>&2 2>&1 1>&3
Expand Down Expand Up @@ -243,6 +251,9 @@ Blacklist: directories or files are disabled/hidden" --yes-button "Whitelist" --
echo " username: \"$USERNAME\""
echo " password: \"$PASSWORD\""
fi
if [ $OPTIMIZE = true ]; then
echo " optimize: yes"
fi
echo "ignore:"
if [ $WHITELIST = true ]; then
echo " - \"/*\""
Expand Down Expand Up @@ -281,10 +292,10 @@ function wizard_main() {
}

case $1 in
#install)
# wizard_install ;;
#uninstall)
# wizard_uninstall ;;
install)
wizard_install ;;
uninstall)
wizard_uninstall ;;
"") # no command
wizard_main "${@:2}" ;;
-h | --help)
Expand Down
2 changes: 2 additions & 0 deletions src/jarklin/_commands/web/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ def make_session_permanent() -> None:
app.config['SESSION_REFRESH_EACH_REQUEST'] = \
config.getbool('web', 'session', 'refresh_each_request', fallback=False)

app.config['JIT_OPTIMIZATION'] = config.getbool('web', 'optimize', fallback=False)

if config.getbool('web', 'gzip', fallback=True):
from flask_compress import Compress # no need to load unless required
Compress(app)
Expand Down
46 changes: 42 additions & 4 deletions src/jarklin/web/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@
r"""
"""
import io
import os
import os.path as p
import mimetypes
from http import HTTPStatus
import flask
from PIL import Image
from werkzeug.exceptions import Unauthorized as HTTPUnauthorized, BadRequest as HTTPBadRequest, NotFound as HTTPNotFound
from .utility import requires_authenticated, validate_user
from .utility import requires_authenticated, validate_user, to_bool


WEB_UI = p.join(p.dirname(__file__), 'web-ui')
Expand All @@ -16,11 +19,46 @@

@app.get("/files/<path:resource>")
@requires_authenticated
def files(resource: str, download: bool = False):
fp = p.join(os.getcwd(), resource)
def files(resource: str):
optimize = flask.request.args.get("optimize", default=False, type=to_bool)
download = flask.request.args.get("download", default=False, type=to_bool)

root = p.abspath(os.getcwd())
fp = p.join(root, resource)
if fp in app.config['EXCLUDE']:
raise HTTPNotFound()
return flask.send_from_directory(os.getcwd(), resource, as_attachment=download)
if p.commonpath([root, fp]) != root:
raise HTTPNotFound(f"{fp!s}")

file = fp

if optimize and flask.current_app.config['JIT_OPTIMIZATION']:
mimetype, _ = mimetypes.guess_type(fp)
if mimetype and mimetype.startswith("image/"):
with Image.open(fp) as image:
# we don't support animated images
if not getattr(image, 'is_animated', False):
# support for giant image commonly found in comics or mangas
boundary = (2000, 2000)
if image.width > 2 * image.height or image.height > image.width * 2:
boundary = (4000, 4000)

image.thumbnail(boundary, resample=Image.Resampling.BICUBIC) # resize but keep aspect

buffer = io.BytesIO()
image.save(buffer, format='WEBP') # WebP should be better than JPEG or PNG
buffer.seek(0)
file = buffer

# ensure image gets closed
image.close()
del image

if isinstance(file, io.BytesIO):
return flask.send_file(file, "image/webp", as_attachment=download,
download_name="optimized.webp", conditional=False, etag=False)

return flask.send_file(file, as_attachment=download)


@app.get("/auth/username")
Expand Down
5 changes: 5 additions & 0 deletions src/jarklin/web/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,8 @@ def wrapper(*args, **kwargs):
return fn(*args, **kwargs)

return wrapper


def to_bool(value: str) -> bool:
# important: this evaluates empty strings to true (/resource?download)
return value.lower() in {"true", "yes", "1", ""}

0 comments on commit 92dd73f

Please sign in to comment.