add counter.svg

Signed-off-by: Ari Archer <ari@ari.lt>
This commit is contained in:
Arija A. 2024-06-06 17:33:18 +03:00
parent dd15783241
commit 8ab5ca1f79
2 changed files with 60 additions and 1 deletions

View file

@ -2,6 +2,8 @@
# -*- coding: utf-8 -*-
"""utilities"""
from html import escape as html_escape
import bleach
from markdown import markdown
from markupsafe import Markup
@ -23,3 +25,43 @@ def markdown_to_html(text: str) -> Markup:
protocols={"http", "https"},
)
)
def text2svg(
text: str,
fill: str = "#fff",
font: str = "sans-serif",
size: float = 16,
baseline: float = 1,
padding: float = 1,
ratio: float = 1, # usually 2 for monospace
) -> str:
"""convert count to svg
fill -- text colour
font -- font family
size -- font size in pixels
baseline -- baseline offset
padding -- padding of characters
ratio -- character ratio
embedding :
<img
id="my-stuff"
src="..."
style="display:inline;height:1em;vertical-align:top"
alt="my stuff :3"
/>
"""
fill = html_escape(fill)
font = html_escape(font)
svg: str = (
f'<svg xmlns="http://www.w3.org/2000/svg" width="{len(text) + padding * ratio}ch" height="{size}" font-size="{size}">'
)
svg += f'<text x="50%" y="{size - baseline}" text-anchor="middle" fill="{fill}" font-family="{font}">{html_escape(text)}</text>'
svg += "</svg>"
return svg

View file

@ -10,7 +10,7 @@ import flask
import validators
from werkzeug.wrappers import Response
from . import email, models
from . import email, models, util
from .c import c
from .routing import Bp
@ -229,6 +229,23 @@ def favicon() -> Response:
)
@views.get("/counter.svg")
def counter() -> flask.Response:
"""counter"""
return flask.Response(
util.text2svg(
text=str(models.Counter.first().inc().count),
fill=flask.request.args.get("fill", "#fff"),
font=flask.request.args.get("font", "sans-serif"),
size=float(flask.request.args.get("size", 16)),
baseline=float(flask.request.args.get("baseline", 1)),
padding=float(flask.request.args.get("padding", 1)),
ratio=float(flask.request.args.get("radio", 1)),
),
mimetype="image/svg+xml",
)
@views.get("/captcha.png")
def captcha() -> flask.Response:
"""CAPTCHA"""