iso7010print/main.py

118 lines
3.9 KiB
Python
Raw Normal View History

2023-08-16 18:30:07 +01:00
import os
import sqlite3
import json
from quart import Quart, render_template, websocket, request, redirect, send_from_directory
import re
2023-08-18 16:32:29 +01:00
import aiohttp
import aiofiles
2023-08-16 18:30:07 +01:00
import subprocess
from io import UnsupportedOperation
2023-08-18 16:32:29 +01:00
STICKERS_ENDPOINT = "https://files.wlcx.cc/stickers.json"
2023-08-16 18:30:07 +01:00
app = Quart(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
headers = {
'User-Agent': 'iso7010print/0.0.1',
}
2023-08-17 14:53:55 +01:00
defs = {
"Official ISO7010": "warns.json",
"Unofficial": "custom.json",
}
def load_things():
out = dict()
for section, fname in defs.items():
with open(fname) as f:
out[section] = sorted(json.load(f), key=lambda e: e["name"])
return out
2023-08-18 16:32:29 +01:00
stickers = dict()
indexed = dict()
2023-08-16 18:30:07 +01:00
db = sqlite3.connect("counts.db")
cur = db.cursor()
2023-08-17 14:53:55 +01:00
cur.execute("CREATE TABLE IF NOT EXISTS counts(what TEXT UNIQUE, count INTEGER)")
def get_db():
db = sqlite3.connect("counts.db")
cur = db.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS counts(what TEXT UNIQUE, count INTEGER)")
return db
2023-08-16 18:30:07 +01:00
@app.route("/", methods=["GET"])
async def home():
2023-08-18 16:32:29 +01:00
if not stickers:
print("Fetching stickers now")
await fetch_stickers()
else:
print("fetching stickers in the background")
app.add_background_task(fetch_stickers)
2023-08-17 14:53:55 +01:00
cur = get_db().cursor()
counts = {c[0]: c[1] for c in cur.execute("select what, count from counts").fetchall()}
2023-08-18 16:32:29 +01:00
return await render_template("index.html", ws=stickers, counts=counts)
2023-08-16 18:30:07 +01:00
@app.route('/static/<path:path>')
def staticfile(path):
return send_from_directory('static', path)
2023-08-18 16:32:29 +01:00
async def fetch_stickers():
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as session:
async with session.get(STICKERS_ENDPOINT) as res:
global stickers
global indexed
stickers = await res.json()
indexed = {w["name"]: w for kj in stickers.values() for w in kj}
print("Stickers updated")
2023-08-16 18:30:07 +01:00
def printit(filename):
subprocess.run(f"brother_ql -b pyusb -p usb://0x04f9:0x2042 -m QL-700 print -l62 {filename}", shell=True, check=True)
@app.route("/", methods=["POST"])
2023-08-18 16:32:29 +01:00
async def printio():
2023-08-16 18:30:07 +01:00
w = (await request.form)["w"]
2023-08-18 16:32:29 +01:00
global indexed
2023-08-16 18:30:07 +01:00
thewarn = indexed[w]
2023-08-17 14:53:55 +01:00
if not thewarn["url"].startswith("http"):
# it's local
filename = thewarn["url"].removeprefix("/")
2023-08-16 18:30:07 +01:00
lol = thewarn["name"]
2023-08-17 14:53:55 +01:00
png_filename = f"{lol.replace(' ', '_')}.png"
2023-08-16 18:30:07 +01:00
else:
filename = thewarn["url"].split("/")[-1]
2023-08-18 16:32:29 +01:00
lol = re.search('W\d+', filename)
if lol:
lol = lol[0]
else:
lol = filename
png_filename = f"stuff/{lol}.png"
quad_png_filename = f"stuff/{lol}_quad.png"
if not os.path.exists(f"stuff/{filename}"):
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as session:
async with session.get(thewarn["url"], headers=headers) as res:
res.raise_for_status()
async with aiofiles.open(f"stuff/{filename}", "wb") as file:
await file.write(await res.read())
2023-08-17 14:53:55 +01:00
if not os.path.exists(png_filename):
2023-08-18 16:32:29 +01:00
subprocess.run(f"resvg stuff/{filename} {png_filename}", shell=True, check=True)
2023-08-17 14:53:55 +01:00
subprocess.run(f"convert {png_filename} -resize 696x -background white -alpha remove -alpha off -monochrome -threshold 20% {png_filename}", shell=True, check=True)
#if not os.path.exists(quad_png_filename):
# subprocess.run("magick -size 696x xc:white ({png_filename} -resize 50%x)
2023-08-18 13:37:01 +01:00
for _ in range(int((await request.form)["count"])):
printit(png_filename)
cur.execute("""INSERT OR REPLACE INTO counts(what, count)
VALUES (:what,
COALESCE(
(SELECT count FROM counts
WHERE what=:what),
0) + 1);
""", dict(what=lol))
db.commit()
with open("counts.txt", "a") as f:
f.write(f"{lol}\n")
2023-08-16 18:30:07 +01:00
return redirect("/")
if __name__ == "__main__":
app.run()