Files
kawaandClaude Opus 5 2c06806814 feat: driver rename, driver icons, web image + driver search
Driver rename and icons: `Driver.display_name` plus a `DriverIcon` table, both
global/shared like the `Driver` row they hang off, so a rename or an icon is
what every Owner sees. The rename/icon dialog keeps its forms as siblings
(nested forms are invalid HTML) and the icon routes return an `hx-swap-oob`
thumbnail refresh rather than re-rendering the table, which would tear the open
`<dialog>` out of the DOM.

Web image picker: `GET /web/images` renders a pickable grid for a printer or a
driver icon, with the search term prefilled from the entity name and editable.
Picking one downloads it server-side and normalizes it.

Driver download search: `GET /web/drivers` searches for a vendor-wide driver
(the term is rewritten into the vendor's real product name for 15 brands) or for
the exact model as typed. Links only — nothing is downloaded, and the fragment
says the results are unvetted.

Icon uploads no longer reject off-size or non-PNG files: `normalize_icon()`
letterboxes any decodable raster into a 256x256 PNG. An already-exact 256x256
PNG is returned byte-identical, because icon storage is content-addressed and
re-encoding would move the file on every save.

`fetch_image()` makes the request from the server, so `assert_fetchable()`
refuses any URL resolving to a private, loopback, or link-local address, and
re-runs on every redirect. ImpTune sits on the same LAN as the printers it
configures; an unguarded fetcher would be a port scanner for anyone who can
reach the UI.

DuckDuckGo is scraped, not called through an API — no key needed, but fragile,
so both search functions swallow parse failures and return [] instead of 500ing
a page. `WEB_SEARCH=false` disables every outbound request and hides the
controls, for air-gapped installs.

Also: one shared `Jinja2Templates` in `templating.py` instead of five per-router
instances, so a template global is declared once; `_add_missing_columns()` in
`database.py` adds new nullable columns to a pre-existing table, which
`create_tables(safe=True)` skips; `db_env` in test_db.py now closes its
connection on teardown, or the next test's ORM writes land in the previous
test's DB file.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 10:44:47 +02:00

94 lines
2.9 KiB
Python

"""Icon storage shared by printer icons and driver icons.
Both live in `ICONS_DIR`, content-addressed by the SHA256 of the *normalized*
bytes, so two entities that end up with the same 256x256 PNG share one file.
"""
from __future__ import annotations
import hashlib
from pathlib import Path
import imptune.config as cfg
from imptune.db.models import Driver, DriverIcon, Icon
from imptune.services.image_utils import ImageError, normalize_icon
MAX_ICON_BYTES = 750 * 1024 # 750 KB, on the bytes as uploaded
__all__ = [
"ImageError",
"IconTooLarge",
"MAX_ICON_BYTES",
"driver_icon_ids",
"icon_path",
"set_driver_icon",
"set_printer_icon",
"store_bytes",
]
class IconTooLarge(ValueError):
"""Raised when the source file is over `MAX_ICON_BYTES`."""
def icon_path(sha256: str) -> Path:
"""On-disk location of a stored icon. Read `cfg` late — tests patch it."""
return Path(cfg.ICONS_DIR) / sha256
def store_bytes(data: bytes) -> tuple[str, int]:
"""Normalize `data` to a 256x256 PNG, write it, return `(sha256, size)`.
Raises `IconTooLarge` or `ImageError` before anything touches the disk.
"""
if len(data) > MAX_ICON_BYTES:
raise IconTooLarge(f"Icon exceeds {MAX_ICON_BYTES // 1024} KB limit.")
png = normalize_icon(data)
sha256 = hashlib.sha256(png).hexdigest()
path = icon_path(sha256)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(png)
return sha256, len(png)
def set_printer_icon(printer_id: int, data: bytes, filename: str) -> Icon:
"""Replace this printer's icon. One `Icon` row per printer, always."""
sha256, size = store_bytes(data)
Icon.delete().where(Icon.printer == printer_id).execute()
return Icon.create(
printer=printer_id,
sha256=sha256,
original_filename=filename or "icon.png",
size_bytes=size,
)
def set_driver_icon(driver_id: int, data: bytes, filename: str) -> DriverIcon:
"""Replace this driver's icon. Driver rows are global, so this icon is too."""
sha256, size = store_bytes(data)
DriverIcon.delete().where(DriverIcon.driver == driver_id).execute()
return DriverIcon.create(
driver=driver_id,
sha256=sha256,
original_filename=filename or "icon.png",
size_bytes=size,
)
def driver_icon_ids(drivers=None) -> set[int]:
"""Ids of drivers that have an icon, for the library listing."""
query = DriverIcon.select(DriverIcon.driver)
if drivers is not None:
ids = [d.id for d in drivers] or [0]
query = query.where(DriverIcon.driver.in_(ids))
return {row.driver_id for row in query}
def driver_search_text(driver: Driver, names: list[str]) -> str:
"""Best guess at what this driver is, for prefilling a search box."""
if driver.display_name:
return driver.display_name
if names:
return names[0]
return Path(driver.original_filename).stem.replace("_", " ").replace("-", " ")