Skip to content

Commit

Permalink
moved media-optimization to own file
Browse files Browse the repository at this point in the history
  • Loading branch information
Barakudum committed Feb 26, 2024
1 parent 1248e0a commit 30926f1
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 31 deletions.
47 changes: 16 additions & 31 deletions src/jarklin/web/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@
r"""
"""
import io
import os
import os.path as p
import mimetypes
import logging
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, to_bool
from . import optimization


WEB_UI = p.join(p.dirname(__file__), 'web-ui')
Expand All @@ -20,41 +19,27 @@
@app.get("/files/<path:resource>")
@requires_authenticated
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)
attempt_optimization = flask.request.args.get("optimize", default=False, type=to_bool)
as_download = flask.request.args.get("download", default=False, type=to_bool)

root = p.abspath(os.getcwd())
fp = p.join(root, resource)
fp = p.abspath(p.join(root, resource))
if fp in app.config['EXCLUDE']:
raise HTTPNotFound()
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

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)
if attempt_optimization and flask.current_app.config['JIT_OPTIMIZATION']:
try:
response = optimization.optimize_file(fp)
if response is not None:
return response
except NotImplementedError: # this is fine
pass
except Exception as error: # no-fail
logging.error(f"optimization for {resource!r} failed", exc_info=error)

return flask.send_file(fp, as_attachment=as_download)


@app.get("/auth/username")
Expand Down
49 changes: 49 additions & 0 deletions src/jarklin/web/optimization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# -*- coding=utf-8 -*-
r"""
"""
import io
import mimetypes
import os
from zlib import adler32
import flask
from PIL import Image


def optimize_file(fp: str):
mimetype, _ = mimetypes.guess_type(fp)
if not mimetype:
return None
if mimetype.startswith("image/"):
return optimize_image(fp)
if mimetype.startswith("video/"):
return optimize_video(fp)


def optimize_image(fp: str):
with Image.open(fp) as image:
# we don't support animated images
if getattr(image, 'is_animated', False):
return None

# 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)

stat = os.stat(fp)
check = adler32(fp.encode('utf-8')) & 0xFFFFFFFF
etag = f"{stat.st_mtime}-{stat.st_size}-{check}-optimized"

return flask.send_file(buffer, "image/webp", as_attachment=False,
download_name="optimized.webp", conditional=False, etag=etag)


def optimize_video(_fp: str):
raise NotImplementedError()

0 comments on commit 30926f1

Please sign in to comment.