some
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
.gradle/
|
||||
build/
|
||||
logs/
|
||||
@@ -0,0 +1,98 @@
|
||||
# wowmine stickers
|
||||
|
||||
NeoForge 1.21.1 / 21.1.250 mod. It keeps vanilla chat and adds a sticker picker
|
||||
beside the Voice Messages microphone. Server and client are deployed; the
|
||||
canonical updater publishes this mod in client release `v21-stickers`.
|
||||
|
||||
The server importer owns Telegram credentials and converts packs into cached
|
||||
PNG atlases. Clients receive only the catalog and content-addressed images
|
||||
through the existing Minecraft connection.
|
||||
|
||||
## Shared catalog
|
||||
|
||||
`catalog.json` contains:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [{
|
||||
"id": "PackShortName",
|
||||
"title": "Pack title",
|
||||
"stickers": [{
|
||||
"id": "lowercase SHA-256 of the PNG atlas, exactly 64 hex characters",
|
||||
"emoji": "",
|
||||
"frames": 1
|
||||
}]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
Assets live in `assets/<id>.png`. Each frame is 128 by 128 pixels; an atlas has
|
||||
`min(8, frames)` columns and enough rows for every frame. Animations run at
|
||||
20 frames per second, with 1 to 60 frames. Static stickers have one frame.
|
||||
Limits: 64 packs, 200 entries per pack, 2048 entries overall, a 512 KiB catalog
|
||||
and 2 MiB per PNG. IDs are content hashes, never filesystem paths or URLs.
|
||||
Duplicate PNGs inside one pack must be deduplicated by the importer.
|
||||
|
||||
## UI contract
|
||||
|
||||
Primary action: choose and send one sticker. Priorities: existing vanilla chat
|
||||
and microphone remain usable; packs and sticker previews are easy to scan;
|
||||
loading and import errors have visible explanations.
|
||||
|
||||
Layout: an icon button beside the existing microphone opens an anchored picker.
|
||||
Only the sticker grid scrolls; pack selection remains visible. Escape dismisses
|
||||
the picker and returns to chat without clearing the input. No replacement chat,
|
||||
private messenger, reactions or new voice recorder.
|
||||
|
||||
Every ordinary player can paste a public `https://t.me/addstickers/SET_NAME`
|
||||
link into a labelled picker field and press Add. OP is not required. The server
|
||||
extracts the set name, queues a bounded import and reports progress or an error
|
||||
to that player. It never fetches the supplied URL directly. Existing packs are
|
||||
reused, imports are serialized, and per-player/global quotas protect the shared
|
||||
cache. Successful imports refresh the shared catalog.
|
||||
|
||||
Verification must use a separate test client/world, never the user's live
|
||||
Prism instance or production chat.
|
||||
|
||||
## Build and use
|
||||
|
||||
From this directory, using the repository's existing Gradle wrapper and Java 21:
|
||||
|
||||
```sh
|
||||
sh ../wowmine-client-info/gradlew -p . check jar
|
||||
```
|
||||
|
||||
The JAR is `build/libs/wowmine-stickers-1.0.0.jar`. Install the same JAR on
|
||||
server and clients. Open vanilla chat, then click the sticker button beside
|
||||
the microphone or press Alt+S. Click a loaded sticker to send it; arrows and
|
||||
Enter provide keyboard selection. Tab moves between enabled controls.
|
||||
Escape or the sticker button closes the picker; both input drafts survive.
|
||||
Paste a public Telegram pack URL in the labelled field and press Add.
|
||||
Imported packs are shared with all players.
|
||||
|
||||
Server deployment is declared in
|
||||
`nixos/system/neuro/minecraft/wowmine.nix`. It installs the importer and passes
|
||||
the bot token using systemd `LoadCredential`, from the SOPS-managed
|
||||
`minecraft/telegram-stickers-token` secret in `sus/neuro-minecraft.yaml`.
|
||||
Edit that file with SOPS; NixOS provisions the root-owned runtime secret with
|
||||
mode 0400. Do not put the token in Nix expressions or manual persistent files.
|
||||
The bot
|
||||
needs access to public sticker sets; players do not need their own bot,
|
||||
Telegram account or operator permission. See `importer/README.md` for limits
|
||||
and the CLI protocol.
|
||||
|
||||
The isolated integration test imported generated WEBP/TGS/WEBM through a local
|
||||
Bot API fixture with a non-OP player, then sent static and animated stickers
|
||||
in vanilla chat. A real Telegram import of the 50-sticker Animals pack also
|
||||
passed from the deployed Minecraft service's namespace and user, using its
|
||||
actual systemd credential.
|
||||
|
||||
Neuro cannot reach the default `api.telegram.org` IPv4 address. Its Minecraft
|
||||
unit uses a private, read-only hosts file pointing that hostname to the
|
||||
reachable official Telegram endpoint `149.154.167.220`. The original hostname
|
||||
and TLS certificate verification remain enabled. The host's nscd cache is
|
||||
hidden from this unit so it cannot bypass the private hosts entry; ordinary
|
||||
NSS file/DNS lookups remain available. Global hosts, DNS and routes are unchanged.
|
||||
The endpoint was checked for valid `api.telegram.org` TLS and Bot API behavior
|
||||
before the full import test. Its address is maintained in the NixOS module.
|
||||
@@ -0,0 +1,124 @@
|
||||
plugins {
|
||||
id 'java-library'
|
||||
id 'net.neoforged.moddev' version '2.0.148'
|
||||
}
|
||||
|
||||
group = 'net.wowmine'
|
||||
version = '1.1.0'
|
||||
|
||||
base {
|
||||
archivesName = 'wowmine-stickers'
|
||||
}
|
||||
|
||||
java {
|
||||
toolchain.languageVersion = JavaLanguageVersion.of(21)
|
||||
withSourcesJar()
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri('https://api.modrinth.com/maven') }
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
qaBaseline {
|
||||
compileClasspath += sourceSets.main.compileClasspath
|
||||
runtimeClasspath += sourceSets.main.runtimeClasspath - sourceSets.main.output
|
||||
}
|
||||
protocolTest {
|
||||
compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath
|
||||
runtimeClasspath += sourceSets.main.output + sourceSets.main.compileClasspath
|
||||
}
|
||||
}
|
||||
|
||||
neoForge {
|
||||
version = '21.1.250'
|
||||
mods {
|
||||
wowmine_stickers {
|
||||
sourceSet(sourceSets.main)
|
||||
}
|
||||
}
|
||||
runs {
|
||||
stickerQaClient {
|
||||
client()
|
||||
gameDirectory = file('/tmp/wowmine-stickers/qa-client')
|
||||
programArguments = ['--quickPlayMultiplayer', '127.0.0.1:25575']
|
||||
jvmArgument('-Xmx2G')
|
||||
environment('DISPLAY', ':197')
|
||||
environment('ALSOFT_DRIVERS', 'null')
|
||||
environment('LIBGL_ALWAYS_SOFTWARE', '1')
|
||||
}
|
||||
stickerQaBaseline {
|
||||
client()
|
||||
gameDirectory = file('/tmp/wowmine-stickers/qa-baseline')
|
||||
sourceSet = sourceSets.qaBaseline
|
||||
loadedMods = []
|
||||
programArguments = ['--quickPlayMultiplayer', '127.0.0.1:25575']
|
||||
jvmArgument('-Xmx2G')
|
||||
environment('DISPLAY', ':197')
|
||||
environment('ALSOFT_DRIVERS', 'null')
|
||||
environment('LIBGL_ALWAYS_SOFTWARE', '1')
|
||||
}
|
||||
stickerQaServer {
|
||||
server()
|
||||
gameDirectory = file('/tmp/wowmine-stickers/qa-server')
|
||||
programArgument('--nogui')
|
||||
jvmArgument('-Xmx1536M')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
jarJar(implementation('org.xerial:sqlite-jdbc')) {
|
||||
version {
|
||||
strictly '[3.45,4.0)'
|
||||
prefer '3.54.1.0'
|
||||
}
|
||||
transitive = false
|
||||
}
|
||||
additionalRuntimeClasspath('org.xerial:sqlite-jdbc:3.54.1.0') {
|
||||
transitive = false
|
||||
}
|
||||
compileOnly('maven.modrinth:WWLeFuHa:EMJ5tqkD') {
|
||||
transitive = false
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
options.encoding = 'UTF-8'
|
||||
options.release = 21
|
||||
}
|
||||
|
||||
tasks.withType(AbstractArchiveTask).configureEach {
|
||||
preserveFileTimestamps = false
|
||||
reproducibleFileOrder = true
|
||||
}
|
||||
|
||||
tasks.register('protocolTest', JavaExec) {
|
||||
dependsOn tasks.named('protocolTestClasses')
|
||||
classpath = sourceSets.protocolTest.runtimeClasspath
|
||||
mainClass = 'net.wowmine.stickers.StickerProtocolTest'
|
||||
}
|
||||
|
||||
tasks.named('check') {
|
||||
dependsOn protocolTest
|
||||
dependsOn 'chatArchiveTest', 'voiceFramesTest', 'historyProtocolTest'
|
||||
}
|
||||
|
||||
tasks.register('chatArchiveTest', JavaExec) {
|
||||
dependsOn tasks.named('protocolTestClasses')
|
||||
classpath = sourceSets.protocolTest.runtimeClasspath
|
||||
mainClass = 'net.wowmine.stickers.ChatArchiveTest'
|
||||
}
|
||||
|
||||
tasks.register('voiceFramesTest', JavaExec) {
|
||||
dependsOn tasks.named('protocolTestClasses')
|
||||
classpath = sourceSets.protocolTest.runtimeClasspath
|
||||
mainClass = 'net.wowmine.stickers.VoiceFramesTest'
|
||||
}
|
||||
|
||||
tasks.register('historyProtocolTest', JavaExec) {
|
||||
dependsOn tasks.named('protocolTestClasses')
|
||||
classpath = sourceSets.protocolTest.runtimeClasspath
|
||||
mainClass = 'net.wowmine.stickers.HistoryProtocolTest'
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
# Telegram sticker importer
|
||||
|
||||
Server-side CLI. No deployment, Telegram messages or player interaction.
|
||||
Only `getStickerSet`, `getFile` and file downloads are used. Real Telegram
|
||||
credential verification is pending; tests use an independent HTTP fixture
|
||||
and generated WEBP, vector TGS and alpha VP9 WEBM.
|
||||
|
||||
From repository root:
|
||||
|
||||
```sh
|
||||
mkdir -p /tmp/wowmine-stickers-importer
|
||||
nix build --impure --expr \
|
||||
'import ./script/wowmine-stickers/importer/default.nix {}' \
|
||||
--out-link /tmp/wowmine-stickers-importer/result
|
||||
/tmp/wowmine-stickers-importer/result/bin/wowmine-stickers-import \
|
||||
--token-file /operator/provided/bot-token \
|
||||
--pack https://t.me/addstickers/PackShortName --output /srv/sticker-cache
|
||||
|
||||
nix-shell --impure script/wowmine-stickers/importer/shell.nix --run \
|
||||
'python -m pytest -q -o cache_dir=/tmp/wowmine-stickers-importer/pytest-cache --basetemp=/tmp/wowmine-stickers-importer/tests script/wowmine-stickers/importer/tests'
|
||||
```
|
||||
|
||||
Python runtime attrs: `python3Packages.pillow`, `python3Packages.lottie`
|
||||
(python-lottie 0.7.2), `python3Packages.cairosvg` (Cairo renderer),
|
||||
`python3Packages.pydantic`, `python3Packages.typer`, `python3Packages.httpx`; executable attr:
|
||||
`ffmpeg` (includes ffprobe and libvpx). Test/check attrs: `python3Packages.pytest`,
|
||||
`ruff`, `basedpyright`. Both Nix files pin repository's Nixpkgs revision
|
||||
`bfc1b8a4574108ceef22f02bafcf6611380c100d`; accept explicit `pkgs` override.
|
||||
HTTPX 0.28.1 is selected explicitly because this pinned Nixpkgs provides it;
|
||||
httpx2 is absent. No packages install into shared Python environments.
|
||||
|
||||
Token comes only from the explicit file (max 256 bytes). Keep file readable only
|
||||
by importer operator. CLI prints structured status, never response
|
||||
content, token, traceback or credential-bearing URL. Tokens are not subprocess
|
||||
arguments. Environment proxies and HTTP redirects are disabled. `--api-base`
|
||||
supports an operator's local Bot API server: HTTPS origin or loopback HTTP,
|
||||
without path, query or user information. Returned file paths must be safe
|
||||
relative paths; absolute paths from Bot API `--local` mode are intentionally
|
||||
rejected. Configure local server to serve relative file downloads over HTTP.
|
||||
Only configured origin receives token; pack URLs are parsed, never fetched.
|
||||
|
||||
Catalog exactly matches shared version 1 schema:
|
||||
|
||||
```json
|
||||
{"version":1,"packs":[{"id":"PackShortName","title":"Pack title","stickers":[{"id":"lowercase64hexSHA256","emoji":"","frames":1}]}]}
|
||||
```
|
||||
|
||||
`id` is SHA-256 of actual PNG bytes; assets live at `assets/<id>.png`.
|
||||
Every PNG contains deterministic text chunk `wowmine_frames` with decimal
|
||||
frame count. Identical pixels at different timings therefore have distinct
|
||||
hash identities. Catalog also rejects conflicting frame counts for one hash.
|
||||
RGBA cells are aspect-preserving, centered, transparent 128x128. Atlas is
|
||||
row-major, `min(8,frames)` columns, enough rows; unused cells stay transparent.
|
||||
Static WEBP produces one frame. TGS and VP8/VP9 WEBM sample at 20 fps, retaining
|
||||
at most first 60 frames (three seconds). VPX software decoder preserves alpha.
|
||||
Opaque source pixels remain opaque. TGS renders through python-lottie/Cairo;
|
||||
external/embedded raster images, text/font resources and expressions are rejected.
|
||||
Complex effects unsupported by python-lottie may not match Telegram perfectly.
|
||||
|
||||
Limits: PNG 2 MiB, catalog 512 KiB, 64 packs, 200 stickers/pack, 2048 overall.
|
||||
Title max 256 and emoji max 64 UTF-16 code units, matching Java.
|
||||
Identical PNGs within imported pack retain first emoji. Existing duplicate pack
|
||||
IDs or sticker hashes inside a pack reject catalog. Import replaces one pack by
|
||||
canonical Telegram name, preserving other packs. Existing catalog fields are
|
||||
strictly parsed; unknown fields reject. Empty existing packs/catalog are allowed.
|
||||
|
||||
Additional safety budgets: 4 MiB/download; 128 MiB total network bytes and
|
||||
generated PNG bytes per import; Bot API response 512 KiB; source dimensions
|
||||
at most 512x512; TGS expanded JSON 2 MiB, depth 32, 50,000 nodes, rate at most
|
||||
120 fps and frame timeline at most 7200. Reads/connects time out after 10/5
|
||||
seconds, requests enforce 30 seconds checked per received chunk (a pending
|
||||
socket read adds at most 10 seconds). Worker wall time 45 seconds, CPU 35
|
||||
seconds, address space 768 MiB, file size 8 MiB; ffmpeg decode 30 seconds.
|
||||
Imports are sequential; no retries. Bounded conversions run without token
|
||||
input, network protocols or arbitrary file resource loading.
|
||||
|
||||
Pack URL/name is untrusted ordinary-player input. No OP requirement exists in
|
||||
this CLI; main server owns authorization policy, queue, rate limits and request
|
||||
deduplication. `--api-base`, `--token-file` and `--output` are operator configuration,
|
||||
never player-controlled. Invoke with an argument array, never a shell string.
|
||||
|
||||
Status is JSON Lines: stdout emits `{"status":"fetching"}`, then
|
||||
`{"status":"converting","completed":0,"total":3}` before each conversion and
|
||||
`{"status":"complete","pack":"PackShortName","stickers":3}` after publication.
|
||||
Counts in progress track source stickers; final count is unique PNGs.
|
||||
Exit 0 means complete. Runtime errors emit
|
||||
`{"status":"error","code":"import_failed"}` on stderr and exit 1.
|
||||
Whole-job deadline emits code `job_timeout` instead. Fetch/conversion deadline
|
||||
is 270 seconds, leaving server's proposed 300-second kill deadline cleanup
|
||||
headroom. Deadline disarms for atomic publication and bounded final cleanup.
|
||||
300 seconds cannot guarantee importing every 200-sticker animated pack:
|
||||
individual conversion CPU caps alone permit 200 * 35 = 7000 CPU seconds.
|
||||
Keep 300 seconds if timeout failures are acceptable; do not promise every
|
||||
public pack finishes within that budget.
|
||||
Argument syntax errors remain Typer usage errors (exit 2); server must provide
|
||||
all required options. No exception text or remote metadata enters error status.
|
||||
|
||||
Output directory is trusted operator-owned local storage; keep other writers
|
||||
out. **Single-writer contract:** main server serializes all imports globally.
|
||||
Importer does not provide a queue or concurrent writer coordination.
|
||||
Import stages in `.wowmine-stickers-importer-v1/job-*`, publishes hash assets
|
||||
then fsyncs and atomically replaces catalog. Input/conversion/validation failures
|
||||
retain old catalog. Capacity checks run before conversion when definitely full,
|
||||
and complete 2048-entry validation happens before publishing any asset.
|
||||
|
||||
Owned staging has a format marker and per-job asset journal written atomically
|
||||
before publication. Normal failure cleans staging and any journaled unreferenced
|
||||
assets. Next import recovers interrupted jobs before allocating new staging.
|
||||
Replacement reclaims obsolete assets of replaced packs. Every deletion excludes
|
||||
all IDs referenced by current catalog; a candidate must also have matching
|
||||
SHA-256 contents and be a regular non-symlink file. Files absent from ownership
|
||||
journals and other directories are preserved, including unrelated files inside
|
||||
cache. Output's marked staging namespace is reserved for importer scratch.
|
||||
Malformed journals or invalid catalog stop recovery rather than guess ownership.
|
||||
Failed recovery leaves its journal and prevents further staging growth.
|
||||
|
||||
Managed cache contains at most 2048 referenced PNGs (2 MiB each), plus bounded
|
||||
in-flight pack (128 MiB generated PNG budget, one 4 MiB input and one transient
|
||||
atlas). Interruption may leave journaled unreferenced blobs, reclaimed on next
|
||||
import. This bound excludes unrelated pre-existing operator files, which importer
|
||||
must not delete. No global garbage collection of unknown hash-named files occurs.
|
||||
Process interruption before catalog rename keeps old catalog; power-loss
|
||||
durability of directory entries is filesystem-dependent.
|
||||
|
||||
Sources consulted: official Bot API `getStickerSet`/`getFile` method docs and
|
||||
python-lottie Cairo exporter API; installed `Animation.load(lottiedict)` and
|
||||
`export_png(animation, fp, frame=0, dpi=96)` signatures verified.
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Single-writer cache transaction with an owned recovery journal."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from tempfile import mkdtemp
|
||||
from typing import TYPE_CHECKING, Annotated, Final, Literal
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from models import (
|
||||
ASSET_BYTES,
|
||||
CATALOG_BYTES,
|
||||
AssetId,
|
||||
Catalog,
|
||||
FailureReason,
|
||||
Frozen,
|
||||
ImportFailureError,
|
||||
Pack,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
OWNER: Final = b"wowmine-stickers-importer-v1\n"
|
||||
JOB_NAME: Final = re.compile(r"job-[a-z0-9_]{8}")
|
||||
|
||||
|
||||
def load_catalog(path: Path) -> Catalog:
|
||||
"""Read bounded catalog before trusting any asset ownership or references."""
|
||||
if not path.exists():
|
||||
return Catalog()
|
||||
with path.open("rb") as source:
|
||||
raw = source.read(CATALOG_BYTES + 1)
|
||||
if len(raw) > CATALOG_BYTES:
|
||||
raise ImportFailureError(FailureReason.CATALOG_EXCEEDS_512_KIB)
|
||||
return Catalog.model_validate_json(raw)
|
||||
|
||||
|
||||
class Journal(Frozen):
|
||||
"""Only IDs recorded before publication may be reclaimed."""
|
||||
|
||||
version: Literal[1] = 1
|
||||
assets: Annotated[list[AssetId], Field(max_length=2248)]
|
||||
|
||||
|
||||
def reclaim(stage: Path, output: Path) -> None:
|
||||
"""Reclaim owned jobs while retaining live IDs, symlinks and unrelated files."""
|
||||
catalog = load_catalog(output / "catalog.json")
|
||||
live = {s.id for pack in catalog.packs for s in pack.stickers}
|
||||
journal_path = stage / "journal.json"
|
||||
if journal_path.is_file():
|
||||
with journal_path.open("rb") as source:
|
||||
raw = source.read(CATALOG_BYTES + 1)
|
||||
journal = Journal.model_validate_json(raw)
|
||||
for asset_id in set(journal.assets) - live:
|
||||
asset = output / "assets" / (asset_id + ".png")
|
||||
if asset.is_file() and not asset.is_symlink():
|
||||
with asset.open("rb") as source:
|
||||
png = source.read(ASSET_BYTES + 1)
|
||||
if (
|
||||
len(png) <= ASSET_BYTES
|
||||
and hashlib.sha256(png).hexdigest() == asset_id
|
||||
):
|
||||
asset.unlink()
|
||||
# Reserved job directories contain importer scratch only.
|
||||
shutil.rmtree(stage)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Cache:
|
||||
"""Stage and publish one pack, under server's global single-writer lock."""
|
||||
|
||||
output: Path
|
||||
stage: Path
|
||||
|
||||
def publish(self, pack: Pack) -> None:
|
||||
"""Validate whole merged catalog before publishing even one asset."""
|
||||
old = load_catalog(self.output / "catalog.json")
|
||||
merged = Catalog(packs=[p for p in old.packs if p.id != pack.id] + [pack])
|
||||
raw = merged.model_dump_json().encode()
|
||||
if len(raw) > CATALOG_BYTES:
|
||||
raise ImportFailureError(FailureReason.CATALOG_SIZE_LIMIT_EXCEEDED)
|
||||
ids = {s.id for p in old.packs for s in p.stickers} | {
|
||||
s.id for s in pack.stickers
|
||||
}
|
||||
temporary = self.stage / "journal.new"
|
||||
_ = temporary.write_text(Journal(assets=sorted(ids)).model_dump_json())
|
||||
_ = temporary.replace(self.stage / "journal.json")
|
||||
assets = self.output / "assets"
|
||||
assets.mkdir(exist_ok=True)
|
||||
for sticker in pack.stickers:
|
||||
_ = (self.stage / (sticker.id + ".png")).replace(
|
||||
assets / (sticker.id + ".png")
|
||||
)
|
||||
temporary = self.stage / "catalog.new"
|
||||
with temporary.open("wb") as target:
|
||||
_ = target.write(raw)
|
||||
target.flush()
|
||||
os.fsync(target.fileno())
|
||||
_ = temporary.replace(self.output / "catalog.json")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def transaction(output: Path) -> Iterator[Cache]:
|
||||
"""Recover only importer-owned staging before allocating another job."""
|
||||
_ = load_catalog(output / "catalog.json")
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
root = output / ".wowmine-stickers-importer-v1"
|
||||
if root.is_symlink():
|
||||
raise ImportFailureError(FailureReason.STAGING_ROOT_IS_A_SYMLINK)
|
||||
root.mkdir(exist_ok=True)
|
||||
marker = root / "owner"
|
||||
if not marker.exists():
|
||||
if any(root.iterdir()):
|
||||
raise ImportFailureError(FailureReason.UNOWNED_STAGING_DIRECTORY)
|
||||
_ = marker.write_bytes(OWNER)
|
||||
with marker.open("rb") as source:
|
||||
if source.read(len(OWNER) + 1) != OWNER:
|
||||
raise ImportFailureError(FailureReason.UNOWNED_STAGING_DIRECTORY)
|
||||
for child in root.iterdir():
|
||||
if JOB_NAME.fullmatch(child.name) and child.is_dir() and not child.is_symlink():
|
||||
reclaim(child, output)
|
||||
stage = Path(mkdtemp(prefix="job-", dir=root))
|
||||
try:
|
||||
yield Cache(output, stage)
|
||||
finally:
|
||||
reclaim(stage, output)
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Credential-free conversion worker; caller bounds CPU, memory and wall time."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import io
|
||||
import math
|
||||
import resource
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import ClassVar, Final, Literal, assert_never
|
||||
|
||||
from lottie.exporters.cairo import export_png
|
||||
from lottie.objects import Animation
|
||||
from PIL import Image
|
||||
from PIL.PngImagePlugin import PngInfo
|
||||
from pydantic import BaseModel, ConfigDict, Field, JsonValue, TypeAdapter
|
||||
|
||||
from models import ASSET_BYTES, FailureReason, ImportFailureError
|
||||
|
||||
CELL: Final = 128
|
||||
SOURCE_SIDE: Final = 512
|
||||
TGS_BYTES: Final = 2_097_152
|
||||
TGS_DEPTH: Final = 32
|
||||
TGS_NODES: Final = 50_000
|
||||
TEXT_LAYER: Final = 5
|
||||
Format = Literal["webp", "tgs", "webm"]
|
||||
JSON_VALUE: Final = TypeAdapter[JsonValue](JsonValue)
|
||||
|
||||
|
||||
class Timing(BaseModel):
|
||||
"""Bounded vector dimensions and finite animation interval."""
|
||||
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(strict=True)
|
||||
w: int = Field(ge=1, le=512)
|
||||
h: int = Field(ge=1, le=512)
|
||||
fr: float = Field(gt=0, le=120, allow_inf_nan=False)
|
||||
ip: float = Field(ge=0, le=7200, allow_inf_nan=False)
|
||||
op: float = Field(gt=0, le=7200, allow_inf_nan=False)
|
||||
|
||||
|
||||
def check_vector(value: JsonValue, depth: int = 0) -> int:
|
||||
"""Reject resources and excessive nesting before rendering vector JSON."""
|
||||
if depth > TGS_DEPTH:
|
||||
raise ImportFailureError(FailureReason.TGS_NESTING_LIMIT)
|
||||
nodes = 1
|
||||
match value:
|
||||
case dict():
|
||||
if isinstance(value.get("p"), str) or isinstance(value.get("u"), str):
|
||||
raise ImportFailureError(FailureReason.TGS_IMAGE_RESOURCES_UNSUPPORTED)
|
||||
if "fonts" in value or "chars" in value or value.get("ty") == TEXT_LAYER:
|
||||
raise ImportFailureError(FailureReason.TGS_TEXT_RESOURCES_UNSUPPORTED)
|
||||
if isinstance(value.get("x"), str):
|
||||
raise ImportFailureError(FailureReason.TGS_EXPRESSIONS_UNSUPPORTED)
|
||||
children = value.values()
|
||||
case list():
|
||||
children = value
|
||||
case str() | int() | float() | None:
|
||||
return nodes
|
||||
case _:
|
||||
assert_never(value)
|
||||
for child in children:
|
||||
nodes += check_vector(child, depth + 1)
|
||||
if nodes > TGS_NODES:
|
||||
raise ImportFailureError(FailureReason.TGS_COMPLEXITY_LIMIT)
|
||||
return nodes
|
||||
|
||||
|
||||
def normalize(image: Image.Image) -> Image.Image:
|
||||
"""Fit a bounded source into one transparent client atlas cell."""
|
||||
if not (1 <= image.width <= SOURCE_SIDE and 1 <= image.height <= SOURCE_SIDE):
|
||||
raise ImportFailureError(FailureReason.SOURCE_IMAGE_DIMENSIONS_EXCEED_512)
|
||||
frame = image.convert("RGBA")
|
||||
frame.thumbnail((CELL, CELL), Image.Resampling.LANCZOS)
|
||||
cell = Image.new("RGBA", (CELL, CELL))
|
||||
cell.alpha_composite(frame, ((CELL - frame.width) // 2, (CELL - frame.height) // 2))
|
||||
return cell
|
||||
|
||||
|
||||
def vector_frames(source: Path) -> list[Image.Image]:
|
||||
"""Render bounded TGS input at 20 FPS for at most 60 frames."""
|
||||
with gzip.open(source, "rb") as compressed:
|
||||
raw = compressed.read(TGS_BYTES + 1)
|
||||
if len(raw) > TGS_BYTES:
|
||||
raise ImportFailureError(FailureReason.TGS_EXPANSION_EXCEEDS_2_MIB)
|
||||
value = JSON_VALUE.validate_json(raw)
|
||||
_ = check_vector(value)
|
||||
timing = Timing.model_validate(value)
|
||||
if timing.op <= timing.ip:
|
||||
raise ImportFailureError(FailureReason.INVALID_TGS_FRAME_INTERVAL)
|
||||
if not isinstance(value, dict):
|
||||
raise ImportFailureError(FailureReason.INVALID_TGS_ROOT)
|
||||
animation = Animation.load(value)
|
||||
count = min(60, math.ceil((timing.op - timing.ip) * 20 / timing.fr))
|
||||
frames: list[Image.Image] = []
|
||||
for index in range(count):
|
||||
with io.BytesIO() as png:
|
||||
export_png(animation, png, timing.ip + index * timing.fr / 20)
|
||||
_ = png.seek(0)
|
||||
with Image.open(png) as image:
|
||||
frames.append(normalize(image))
|
||||
return frames
|
||||
|
||||
|
||||
class VideoStream(BaseModel):
|
||||
"""Accepted WebM video stream dimensions and decoder family."""
|
||||
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(strict=True)
|
||||
width: int = Field(ge=1, le=512)
|
||||
height: int = Field(ge=1, le=512)
|
||||
codec_name: Literal["vp8", "vp9"]
|
||||
|
||||
|
||||
class VideoProbe(BaseModel):
|
||||
"""Require exactly one selected video stream from ffprobe."""
|
||||
|
||||
streams: list[VideoStream] = Field(min_length=1, max_length=1)
|
||||
|
||||
|
||||
def executable(name: Literal["ffmpeg", "ffprobe"]) -> str:
|
||||
"""Resolve required decoders on the wrapper's configured runtime path."""
|
||||
path = shutil.which(name)
|
||||
if path is None:
|
||||
raise ImportFailureError(FailureReason.CONVERSION_FAILED)
|
||||
return path
|
||||
|
||||
|
||||
def video_frames(source: Path) -> list[Image.Image]:
|
||||
"""Decode bounded local WebM frames without enabling network protocols."""
|
||||
probe = subprocess.run(
|
||||
[
|
||||
executable("ffprobe"),
|
||||
"-v",
|
||||
"error",
|
||||
"-protocol_whitelist",
|
||||
"file",
|
||||
"-f",
|
||||
"matroska",
|
||||
"-select_streams",
|
||||
"v:0",
|
||||
"-show_entries",
|
||||
"stream=width,height,codec_name",
|
||||
"-of",
|
||||
"json",
|
||||
str(source),
|
||||
],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=10,
|
||||
)
|
||||
stream = VideoProbe.model_validate_json(probe.stdout).streams[0]
|
||||
match stream.codec_name:
|
||||
case "vp8":
|
||||
decoder = "libvpx"
|
||||
case "vp9":
|
||||
decoder = "libvpx-vp9"
|
||||
case _:
|
||||
assert_never(stream.codec_name)
|
||||
result = subprocess.run(
|
||||
[
|
||||
executable("ffmpeg"),
|
||||
"-v",
|
||||
"error",
|
||||
"-nostdin",
|
||||
"-threads",
|
||||
"1",
|
||||
"-protocol_whitelist",
|
||||
"file",
|
||||
"-c:v",
|
||||
decoder,
|
||||
"-f",
|
||||
"matroska",
|
||||
"-i",
|
||||
str(source),
|
||||
"-an",
|
||||
"-sn",
|
||||
"-dn",
|
||||
"-vf",
|
||||
",".join(
|
||||
(
|
||||
"fps=20",
|
||||
f"scale={CELL}:{CELL}:force_original_aspect_ratio=decrease",
|
||||
f"pad={CELL}:{CELL}:(ow-iw)/2:(oh-ih)/2:color=black@0",
|
||||
"format=rgba",
|
||||
)
|
||||
),
|
||||
"-frames:v",
|
||||
"60",
|
||||
"-threads",
|
||||
"1",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
"-pix_fmt",
|
||||
"rgba",
|
||||
"pipe:1",
|
||||
],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=30,
|
||||
)
|
||||
stride = CELL * CELL * 4
|
||||
if (
|
||||
not result.stdout
|
||||
or len(result.stdout) % stride
|
||||
or len(result.stdout) > stride * 60
|
||||
):
|
||||
raise ImportFailureError(FailureReason.INVALID_DECODED_VIDEO_FRAMES)
|
||||
return [
|
||||
Image.frombytes("RGBA", (CELL, CELL), result.stdout[start : start + stride])
|
||||
for start in range(0, len(result.stdout), stride)
|
||||
]
|
||||
|
||||
|
||||
def convert(source: Path, kind: Format, destination: Path) -> int:
|
||||
"""Write an atlas whose PNG identity includes its frame count."""
|
||||
match kind:
|
||||
case "webp":
|
||||
with Image.open(source) as image:
|
||||
if image.format != "WEBP" or getattr(image, "n_frames", 1) != 1:
|
||||
raise ImportFailureError(FailureReason.EXPECTED_STATIC_WEBP)
|
||||
frames = [normalize(image)]
|
||||
case "tgs":
|
||||
frames = vector_frames(source)
|
||||
case "webm":
|
||||
frames = video_frames(source)
|
||||
case _:
|
||||
assert_never(kind)
|
||||
columns = min(8, len(frames))
|
||||
atlas = Image.new("RGBA", (columns * CELL, math.ceil(len(frames) / columns) * CELL))
|
||||
for index, frame in enumerate(frames):
|
||||
atlas.paste(frame, ((index % columns) * CELL, (index // columns) * CELL))
|
||||
metadata = PngInfo()
|
||||
metadata.add_text("wowmine_frames", str(len(frames)))
|
||||
atlas.save(destination, format="PNG", optimize=False, pnginfo=metadata)
|
||||
if destination.stat().st_size > ASSET_BYTES:
|
||||
raise ImportFailureError(FailureReason.PNG_EXCEEDS_2_MIB)
|
||||
return len(frames)
|
||||
|
||||
|
||||
def worker() -> None:
|
||||
"""Only validated format literals enter conversion."""
|
||||
resource.setrlimit(resource.RLIMIT_AS, (805306368, 805306368))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (35, 35))
|
||||
resource.setrlimit(resource.RLIMIT_FSIZE, (8388608, 8388608))
|
||||
kind = TypeAdapter[Format](Format).validate_python(sys.argv[2])
|
||||
_ = sys.stdout.write(f"{convert(Path(sys.argv[1]), kind, Path(sys.argv[3]))}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
worker()
|
||||
@@ -0,0 +1,14 @@
|
||||
{ pkgs ? import (builtins.getFlake
|
||||
"github:nixos/nixpkgs/bfc1b8a4574108ceef22f02bafcf6611380c100d").outPath {}
|
||||
}:
|
||||
let
|
||||
python = pkgs.python3.withPackages (ps: with ps; [
|
||||
pillow lottie cairosvg pydantic typer httpx
|
||||
]);
|
||||
in pkgs.writeShellApplication {
|
||||
name = "wowmine-stickers-import";
|
||||
runtimeInputs = [ python pkgs.ffmpeg ];
|
||||
text = ''
|
||||
exec python ${./.}/import_pack.py "$@"
|
||||
'';
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
#!/usr/bin/env python3
|
||||
# /// script
|
||||
# requires-python = ">=3.13"
|
||||
# dependencies = ["pillow", "lottie", "cairosvg", "pydantic>=2", "typer", "httpx"]
|
||||
# ///
|
||||
# How to run: prefer Nix wrapper (README.md); python import_pack.py --help.
|
||||
"""Import a Telegram sticker pack without disclosing bot credentials."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Annotated, Final
|
||||
|
||||
import typer
|
||||
from PIL import Image
|
||||
|
||||
from cache import load_catalog, transaction
|
||||
from models import (
|
||||
ASSET_BYTES,
|
||||
PACK_LIMIT,
|
||||
STICKER_LIMIT,
|
||||
TOTAL_BYTES,
|
||||
Envelope,
|
||||
FailureReason,
|
||||
ImportFailureError,
|
||||
Pack,
|
||||
RemoteFile,
|
||||
RemotePack,
|
||||
Sticker,
|
||||
)
|
||||
from telegram import Telegram, pack_name, read_token
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from types import FrameType
|
||||
|
||||
ROOT: Final = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
class JobTimeoutError(Exception):
|
||||
"""Import exceeded server-compatible whole-job deadline."""
|
||||
|
||||
|
||||
def deadline_expired(_signum: int, _frame: FrameType | None) -> None:
|
||||
"""Interrupt the CLI when its whole-job timer expires."""
|
||||
raise JobTimeoutError
|
||||
|
||||
|
||||
def render_atlas(source: Path, kind: str, destination: Path) -> int:
|
||||
"""Run the bounded conversion worker and reap its entire process group."""
|
||||
with subprocess.Popen(
|
||||
[
|
||||
sys.executable,
|
||||
str(ROOT / "convert.py"),
|
||||
str(source),
|
||||
kind,
|
||||
str(destination),
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
) as worker:
|
||||
try:
|
||||
stdout, _ = worker.communicate(timeout=45)
|
||||
finally:
|
||||
# Kill entire worker group, including a still-running decoder.
|
||||
try:
|
||||
os.killpg(worker.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
_ = worker.poll()
|
||||
if worker.returncode != 0:
|
||||
raise ImportFailureError(FailureReason.CONVERSION_FAILED)
|
||||
return int(stdout)
|
||||
|
||||
|
||||
def import_pack(api: Telegram, name: str, output: Path) -> Pack:
|
||||
"""Download, convert and atomically publish one credential-free pack."""
|
||||
stickers: list[Sticker] = []
|
||||
seen: set[str] = set()
|
||||
generated_bytes = 0
|
||||
with transaction(output) as cache:
|
||||
stage = cache.stage
|
||||
remote = (
|
||||
Envelope[RemotePack]
|
||||
.model_validate_json(api.method("getStickerSet", "name", name))
|
||||
.result
|
||||
)
|
||||
if remote.name.casefold() != name.casefold():
|
||||
raise ImportFailureError(FailureReason.BOT_API_RETURNED_A_DIFFERENT_PACK)
|
||||
old = load_catalog(output / "catalog.json")
|
||||
remaining = [p for p in old.packs if p.id != remote.name]
|
||||
if (
|
||||
len(remaining) >= PACK_LIMIT
|
||||
or sum(len(p.stickers) for p in remaining) >= STICKER_LIMIT
|
||||
):
|
||||
raise ImportFailureError(FailureReason.CATALOG_HAS_NO_ROOM_FOR_ANOTHER_PACK)
|
||||
for completed, item in enumerate(remote.stickers):
|
||||
info = (
|
||||
Envelope[RemoteFile]
|
||||
.model_validate_json(
|
||||
api.method("getFile", "file_id", item.file_id),
|
||||
)
|
||||
.result
|
||||
)
|
||||
kind = "tgs" if item.is_animated else "webm" if item.is_video else "webp"
|
||||
if not info.file_path.lower().endswith("." + kind):
|
||||
raise ImportFailureError(FailureReason.BOT_API_FILE_FORMAT_MISMATCH)
|
||||
data = api.download(info.file_path)
|
||||
if any(
|
||||
size is not None and size != len(data)
|
||||
for size in (info.file_size, item.file_size)
|
||||
):
|
||||
raise ImportFailureError(FailureReason.BOT_API_FILE_SIZE_MISMATCH)
|
||||
source = stage / ("input." + kind)
|
||||
_ = source.write_bytes(data)
|
||||
typer.echo(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "converting",
|
||||
"completed": completed,
|
||||
"total": len(remote.stickers),
|
||||
}
|
||||
)
|
||||
)
|
||||
atlas_path = stage / "atlas.png"
|
||||
frames = render_atlas(source, kind, atlas_path)
|
||||
png = atlas_path.read_bytes()
|
||||
generated_bytes += len(png)
|
||||
if len(png) > ASSET_BYTES or generated_bytes > TOTAL_BYTES:
|
||||
raise ImportFailureError(
|
||||
FailureReason.GENERATED_ASSET_SIZE_LIMIT_EXCEEDED
|
||||
)
|
||||
sticker = Sticker(
|
||||
id=hashlib.sha256(png).hexdigest(), emoji=item.emoji, frames=frames
|
||||
)
|
||||
columns = min(8, frames)
|
||||
with Image.open(atlas_path) as image:
|
||||
if image.format != "PNG" or image.size != (
|
||||
columns * 128,
|
||||
((frames + columns - 1) // columns) * 128,
|
||||
):
|
||||
raise ImportFailureError(FailureReason.INVALID_ATLAS_DIMENSIONS)
|
||||
image.verify()
|
||||
if sticker.id not in seen:
|
||||
seen.add(sticker.id)
|
||||
_ = atlas_path.rename(stage / (sticker.id + ".png"))
|
||||
stickers.append(sticker)
|
||||
pack = Pack(id=remote.name, title=remote.title, stickers=stickers)
|
||||
if api.token in pack.model_dump_json() or api.token in old.model_dump_json():
|
||||
raise ImportFailureError(FailureReason.CATALOG_CREDENTIAL_SAFETY_VIOLATION)
|
||||
# Do not turn a committed catalog into a reported timeout during cleanup.
|
||||
_ = signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
cache.publish(pack)
|
||||
return pack
|
||||
|
||||
|
||||
def main(
|
||||
token_file: Annotated[
|
||||
Path, typer.Option(help="Explicit bot token file; never read from environment.")
|
||||
],
|
||||
pack: Annotated[
|
||||
str, typer.Option(help="Telegram short name or HTTPS addstickers URL.")
|
||||
],
|
||||
output: Annotated[
|
||||
Path, typer.Option(help="Catalog and content-addressed asset cache.")
|
||||
],
|
||||
api_base: Annotated[
|
||||
str, typer.Option(help="Bot API origin; HTTP only for loopback local servers.")
|
||||
] = "https://api.telegram.org",
|
||||
) -> None:
|
||||
"""Emit the CLI status protocol without exposing credential-bearing errors."""
|
||||
# Transport and validation errors can contain secrets; never echo their text.
|
||||
previous = signal.signal(signal.SIGALRM, deadline_expired)
|
||||
try:
|
||||
_ = signal.setitimer(signal.ITIMER_REAL, 270)
|
||||
name = pack_name(pack)
|
||||
token = read_token(token_file)
|
||||
typer.echo('{"status":"fetching"}')
|
||||
with Telegram(api_base, token) as api:
|
||||
imported = import_pack(api, name, output)
|
||||
typer.echo(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "complete",
|
||||
"pack": imported.id,
|
||||
"stickers": len(imported.stickers),
|
||||
}
|
||||
)
|
||||
)
|
||||
except JobTimeoutError:
|
||||
typer.echo('{"status":"error","code":"job_timeout"}', err=True)
|
||||
raise typer.Exit(1) from None
|
||||
except Exception: # noqa: BLE001 # noqa: BROAD_EXCEPT_OK (credential-safe CLI boundary)
|
||||
typer.echo('{"status":"error","code":"import_failed"}', err=True)
|
||||
raise typer.Exit(1) from None
|
||||
finally:
|
||||
_ = signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
_ = signal.signal(signal.SIGALRM, previous)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
typer.run(main)
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Validated Bot API inputs and shared client catalog."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
from typing import Annotated, ClassVar, Final, Literal, final
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
CATALOG_BYTES: Final = 524_288
|
||||
ASSET_BYTES: Final = 2_097_152
|
||||
DOWNLOAD_BYTES: Final = 4_194_304
|
||||
TOTAL_BYTES: Final = 134_217_728
|
||||
PACK_LIMIT: Final = 64
|
||||
STICKER_LIMIT: Final = 2048
|
||||
EMOJI_UTF16_BYTES: Final = 128
|
||||
TITLE_UTF16_BYTES: Final = 512
|
||||
PackId = Annotated[str, Field(pattern=r"^[A-Za-z0-9_]{1,64}$")]
|
||||
AssetId = Annotated[str, Field(pattern=r"^[0-9a-f]{64}$")]
|
||||
|
||||
|
||||
class FailureReason(Enum):
|
||||
"""Static failure descriptions safe to retain without request credentials."""
|
||||
|
||||
CATALOG_EXCEEDS_512_KIB = "catalog exceeds 512 KiB"
|
||||
CATALOG_SIZE_LIMIT_EXCEEDED = "catalog size limit exceeded"
|
||||
STAGING_ROOT_IS_A_SYMLINK = "staging root is a symlink"
|
||||
UNOWNED_STAGING_DIRECTORY = "unowned staging directory"
|
||||
TGS_NESTING_LIMIT = "TGS nesting limit"
|
||||
TGS_IMAGE_RESOURCES_UNSUPPORTED = "TGS image resources unsupported"
|
||||
TGS_TEXT_RESOURCES_UNSUPPORTED = "TGS text resources unsupported"
|
||||
TGS_EXPRESSIONS_UNSUPPORTED = "TGS expressions unsupported"
|
||||
TGS_COMPLEXITY_LIMIT = "TGS complexity limit"
|
||||
SOURCE_IMAGE_DIMENSIONS_EXCEED_512 = "source image dimensions exceed 512"
|
||||
TGS_EXPANSION_EXCEEDS_2_MIB = "TGS expansion exceeds 2 MiB"
|
||||
INVALID_TGS_FRAME_INTERVAL = "invalid TGS frame interval"
|
||||
INVALID_TGS_ROOT = "invalid TGS root"
|
||||
INVALID_DECODED_VIDEO_FRAMES = "invalid decoded video frames"
|
||||
EXPECTED_STATIC_WEBP = "expected static WEBP"
|
||||
PNG_EXCEEDS_2_MIB = "PNG exceeds 2 MiB"
|
||||
BOT_API_RETURNED_A_DIFFERENT_PACK = "Bot API returned a different pack"
|
||||
CATALOG_HAS_NO_ROOM_FOR_ANOTHER_PACK = "catalog has no room for another pack"
|
||||
BOT_API_FILE_FORMAT_MISMATCH = "Bot API file format mismatch"
|
||||
BOT_API_FILE_SIZE_MISMATCH = "Bot API file size mismatch"
|
||||
CONVERSION_FAILED = "conversion failed"
|
||||
GENERATED_ASSET_SIZE_LIMIT_EXCEEDED = "generated asset size limit exceeded"
|
||||
INVALID_ATLAS_DIMENSIONS = "invalid atlas dimensions"
|
||||
CATALOG_CREDENTIAL_SAFETY_VIOLATION = "catalog credential safety violation"
|
||||
EMOJI_EXCEEDS_64_UTF_16_UNITS = "emoji exceeds 64 UTF-16 units"
|
||||
INVALID_PACK_TITLE = "invalid pack title"
|
||||
DUPLICATE_STICKER_ID = "duplicate sticker id"
|
||||
DUPLICATE_PACK_ID = "duplicate pack id"
|
||||
CATALOG_EXCEEDS_2048_STICKERS = "catalog exceeds 2048 stickers"
|
||||
ASSET_ID_HAS_CONFLICTING_FRAME_COUNTS = "asset id has conflicting frame counts"
|
||||
CONFLICTING_STICKER_FORMATS = "conflicting sticker formats"
|
||||
INVALID_PACK_REFERENCE = (
|
||||
"expected Telegram sticker pack short name or HTTPS addstickers URL"
|
||||
)
|
||||
INVALID_API_ORIGIN = "API base must be an origin without credentials or path"
|
||||
INSECURE_API_ORIGIN = "HTTP API base allowed only on loopback"
|
||||
INVALID_CREDENTIAL_FILE = "invalid token file"
|
||||
BOT_API_REQUEST_REJECTED = "Bot API request rejected"
|
||||
DOWNLOAD_SIZE_OR_TIME_LIMIT_EXCEEDED = "download size or time limit exceeded"
|
||||
UNSAFE_BOT_API_FILE_PATH = "unsafe Bot API file path"
|
||||
|
||||
|
||||
@final
|
||||
class ImportFailureError(Exception):
|
||||
"""Typed failure; exception traceback state must remain mutable."""
|
||||
|
||||
def __init__(self, reason: FailureReason) -> None:
|
||||
"""Retain a typed cause while leaving traceback state mutable."""
|
||||
super().__init__(reason.value)
|
||||
self.reason = reason
|
||||
|
||||
|
||||
class Frozen(BaseModel):
|
||||
"""Reject extra fields and coercion in immutable catalog values."""
|
||||
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(
|
||||
frozen=True, strict=True, extra="forbid"
|
||||
)
|
||||
|
||||
|
||||
class Sticker(Frozen):
|
||||
"""Content-addressed atlas reference with client-compatible timing."""
|
||||
|
||||
id: AssetId
|
||||
emoji: str
|
||||
frames: Annotated[int, Field(ge=1, le=60)]
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_emoji(self) -> Sticker:
|
||||
"""Bound emoji length using the client's UTF-16 representation."""
|
||||
if len(self.emoji.encode("utf-16-le")) > EMOJI_UTF16_BYTES:
|
||||
raise ImportFailureError(FailureReason.EMOJI_EXCEEDS_64_UTF_16_UNITS)
|
||||
return self
|
||||
|
||||
|
||||
class Pack(Frozen):
|
||||
"""Named sticker collection published as one cache transaction."""
|
||||
|
||||
id: PackId
|
||||
title: str
|
||||
stickers: Annotated[list[Sticker], Field(max_length=200)]
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_pack(self) -> Pack:
|
||||
"""Reject unusable titles and repeated asset references."""
|
||||
if (
|
||||
not self.title.strip()
|
||||
or len(self.title.encode("utf-16-le")) > TITLE_UTF16_BYTES
|
||||
):
|
||||
raise ImportFailureError(FailureReason.INVALID_PACK_TITLE)
|
||||
if len({s.id for s in self.stickers}) != len(self.stickers):
|
||||
raise ImportFailureError(FailureReason.DUPLICATE_STICKER_ID)
|
||||
return self
|
||||
|
||||
|
||||
class Catalog(Frozen):
|
||||
"""Versioned client manifest with globally consistent asset timing."""
|
||||
|
||||
version: Annotated[int, Field(ge=1, le=1)] = 1
|
||||
packs: Annotated[list[Pack], Field(max_length=PACK_LIMIT)] = Field(
|
||||
default_factory=list
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_catalog(self) -> Catalog:
|
||||
"""Bound total stickers and reject conflicting shared identities."""
|
||||
if len({p.id for p in self.packs}) != len(self.packs):
|
||||
raise ImportFailureError(FailureReason.DUPLICATE_PACK_ID)
|
||||
if sum(len(p.stickers) for p in self.packs) > STICKER_LIMIT:
|
||||
raise ImportFailureError(FailureReason.CATALOG_EXCEEDS_2048_STICKERS)
|
||||
frames: dict[str, int] = {}
|
||||
for pack in self.packs:
|
||||
for sticker in pack.stickers:
|
||||
if sticker.id in frames and frames[sticker.id] != sticker.frames:
|
||||
raise ImportFailureError(
|
||||
FailureReason.ASSET_ID_HAS_CONFLICTING_FRAME_COUNTS
|
||||
)
|
||||
frames[sticker.id] = sticker.frames
|
||||
return self
|
||||
|
||||
|
||||
class ApiModel(Frozen):
|
||||
"""Parse known Bot API fields while tolerating upstream additions."""
|
||||
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(
|
||||
frozen=True, strict=True, extra="ignore"
|
||||
)
|
||||
|
||||
|
||||
class Envelope[T](ApiModel):
|
||||
"""Successful Bot API response carrying a validated result."""
|
||||
|
||||
ok: Literal[True]
|
||||
result: T
|
||||
|
||||
|
||||
class RemoteSticker(ApiModel):
|
||||
"""Bounded source metadata used to select the conversion format."""
|
||||
|
||||
file_id: Annotated[str, Field(min_length=1, max_length=512)]
|
||||
width: Annotated[int, Field(ge=1, le=512)]
|
||||
height: Annotated[int, Field(ge=1, le=512)]
|
||||
is_animated: bool
|
||||
is_video: bool
|
||||
emoji: Annotated[str, Field(max_length=64)] = ""
|
||||
file_size: Annotated[int, Field(ge=1, le=DOWNLOAD_BYTES)] | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_format(self) -> RemoteSticker:
|
||||
"""Reject mutually exclusive animated and video flags."""
|
||||
if self.is_animated and self.is_video:
|
||||
raise ImportFailureError(FailureReason.CONFLICTING_STICKER_FORMATS)
|
||||
return self
|
||||
|
||||
|
||||
class RemotePack(ApiModel):
|
||||
"""Bounded Bot API sticker set before downloading any files."""
|
||||
|
||||
name: PackId
|
||||
title: Annotated[str, Field(min_length=1, max_length=256)]
|
||||
stickers: Annotated[list[RemoteSticker], Field(min_length=1, max_length=200)]
|
||||
|
||||
|
||||
class RemoteFile(ApiModel):
|
||||
"""Bot API download location and optional declared size."""
|
||||
|
||||
file_path: Annotated[str, Field(min_length=1, max_length=512)]
|
||||
file_size: Annotated[int, Field(ge=1, le=DOWNLOAD_BYTES)] | None = None
|
||||
@@ -0,0 +1,22 @@
|
||||
[project]
|
||||
name = "wowmine-stickers-importer"
|
||||
version = "0.1.0"
|
||||
requires-python = ">=3.13"
|
||||
dependencies = ["pillow", "lottie", "cairosvg", "pydantic>=2", "typer", "httpx"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = ["."]
|
||||
addopts = "--strict-config --strict-markers"
|
||||
|
||||
[tool.basedpyright]
|
||||
typeCheckingMode = "all"
|
||||
pythonVersion = "3.13"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["ALL"]
|
||||
# Choose D211/D212 where docstring rules conflict; the formatter owns commas.
|
||||
ignore = ["D203", "D213", "COM812"]
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
known-first-party = ["cache", "convert", "import_pack", "models", "telegram", "tests"]
|
||||
known-third-party = ["lottie"]
|
||||
@@ -0,0 +1,12 @@
|
||||
{ pkgs ? import (builtins.getFlake
|
||||
"github:nixos/nixpkgs/bfc1b8a4574108ceef22f02bafcf6611380c100d").outPath {}
|
||||
}:
|
||||
pkgs.mkShell {
|
||||
packages = [
|
||||
(pkgs.python3.withPackages (ps: with ps; [
|
||||
pillow lottie cairosvg pydantic typer httpx pytest
|
||||
]))
|
||||
pkgs.ffmpeg pkgs.ruff pkgs.basedpyright
|
||||
];
|
||||
PYTHONDONTWRITEBYTECODE = "1";
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Single-origin, bounded Bot API transport. Never expose response diagnostics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import time
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING, Final, Self, final
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import httpx
|
||||
|
||||
from models import (
|
||||
CATALOG_BYTES,
|
||||
DOWNLOAD_BYTES,
|
||||
TOTAL_BYTES,
|
||||
FailureReason,
|
||||
ImportFailureError,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
from types import TracebackType
|
||||
|
||||
TOKEN: Final = re.compile(r"[0-9]{1,20}:[A-Za-z0-9_-]{20,128}")
|
||||
NAME: Final = re.compile(r"[A-Za-z0-9_]{1,64}")
|
||||
FILE_PATH: Final = re.compile(r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_.-]+)+")
|
||||
TOKEN_BYTES: Final = 256
|
||||
REQUEST_SECONDS: Final = 30
|
||||
|
||||
|
||||
def pack_name(value: str) -> str:
|
||||
"""Accept only short names or credential-free Telegram addstickers links."""
|
||||
if NAME.fullmatch(value):
|
||||
return value
|
||||
parsed = urlsplit(value)
|
||||
if (
|
||||
parsed.scheme == "https"
|
||||
and parsed.netloc in {"t.me", "telegram.me"}
|
||||
and not parsed.query
|
||||
and not parsed.fragment
|
||||
and parsed.path.startswith("/addstickers/")
|
||||
):
|
||||
name = parsed.path.removeprefix("/addstickers/")
|
||||
if NAME.fullmatch(name):
|
||||
return name
|
||||
raise ImportFailureError(FailureReason.INVALID_PACK_REFERENCE)
|
||||
|
||||
|
||||
def api_origin(value: str) -> str:
|
||||
"""Require one credential-free origin, allowing HTTP only on loopback."""
|
||||
parsed = urlsplit(value)
|
||||
if (
|
||||
parsed.username is not None
|
||||
or parsed.password is not None
|
||||
or not parsed.hostname
|
||||
or parsed.path not in {"", "/"}
|
||||
or parsed.query
|
||||
or parsed.fragment
|
||||
or parsed.scheme not in {"https", "http"}
|
||||
):
|
||||
raise ImportFailureError(FailureReason.INVALID_API_ORIGIN)
|
||||
if parsed.scheme == "http" and parsed.hostname not in {
|
||||
"localhost",
|
||||
"127.0.0.1",
|
||||
"::1",
|
||||
}:
|
||||
raise ImportFailureError(FailureReason.INSECURE_API_ORIGIN)
|
||||
# Force port validation before any credential is used.
|
||||
_ = parsed.port
|
||||
return value.rstrip("/")
|
||||
|
||||
|
||||
def read_token(path: Path) -> str:
|
||||
"""Read one bounded, syntactically valid credential from an explicit file."""
|
||||
with path.open("rb") as source:
|
||||
raw = source.read(TOKEN_BYTES + 1)
|
||||
if len(raw) > TOKEN_BYTES:
|
||||
raise ImportFailureError(FailureReason.INVALID_CREDENTIAL_FILE)
|
||||
token = raw.decode("ascii").strip()
|
||||
if TOKEN.fullmatch(token) is None:
|
||||
raise ImportFailureError(FailureReason.INVALID_CREDENTIAL_FILE)
|
||||
return token
|
||||
|
||||
|
||||
@final
|
||||
class Telegram:
|
||||
"""Mutable byte accounting belongs to one sequential import."""
|
||||
|
||||
def __init__(self, origin: str, token: str) -> None:
|
||||
"""Own a sequential transport without redirects or environment trust."""
|
||||
self.origin = api_origin(origin)
|
||||
self.token = token
|
||||
self.total = 0
|
||||
self.client = httpx.Client(
|
||||
timeout=httpx.Timeout(10, connect=5),
|
||||
limits=httpx.Limits(max_connections=1, max_keepalive_connections=1),
|
||||
follow_redirects=False,
|
||||
trust_env=False,
|
||||
headers={"Accept-Encoding": "identity"},
|
||||
)
|
||||
|
||||
def __enter__(self) -> Self:
|
||||
"""Return this import's transport."""
|
||||
return self
|
||||
|
||||
def __exit__(
|
||||
self,
|
||||
exc_type: type[BaseException] | None,
|
||||
exc: BaseException | None,
|
||||
traceback: TracebackType | None,
|
||||
) -> None:
|
||||
"""Close the transport after success or failure."""
|
||||
self.client.close()
|
||||
|
||||
def request(self, suffix: str, limit: int) -> bytes:
|
||||
"""Bound raw response bytes, total transfer bytes and elapsed time."""
|
||||
start = time.monotonic()
|
||||
chunks: list[bytes] = []
|
||||
size = 0
|
||||
with self.client.stream("GET", self.origin + suffix) as response:
|
||||
if (
|
||||
response.status_code != HTTPStatus.OK
|
||||
or response.headers.get("content-encoding", "identity") != "identity"
|
||||
):
|
||||
raise ImportFailureError(FailureReason.BOT_API_REQUEST_REJECTED)
|
||||
for chunk in response.iter_raw():
|
||||
size += len(chunk)
|
||||
self.total += len(chunk)
|
||||
if (
|
||||
size > limit
|
||||
or self.total > TOTAL_BYTES
|
||||
or time.monotonic() - start > REQUEST_SECONDS
|
||||
):
|
||||
raise ImportFailureError(
|
||||
FailureReason.DOWNLOAD_SIZE_OR_TIME_LIMIT_EXCEEDED
|
||||
)
|
||||
chunks.append(chunk)
|
||||
return b"".join(chunks)
|
||||
|
||||
def method(self, method: str, parameter: str, value: str) -> bytes:
|
||||
"""Encode method parameters as query data on the configured origin."""
|
||||
# Values are encoded as query data, never interpreted as a URL/path.
|
||||
query = str(httpx.QueryParams({parameter: value}))
|
||||
return self.request(f"/bot{self.token}/{method}?{query}", CATALOG_BYTES)
|
||||
|
||||
def download(self, path: str) -> bytes:
|
||||
"""Fetch a bounded file only after rejecting traversal and URL syntax."""
|
||||
if FILE_PATH.fullmatch(path) is None or any(
|
||||
p in {".", ".."} for p in path.split("/")
|
||||
):
|
||||
raise ImportFailureError(FailureReason.UNSAFE_BOT_API_FILE_PATH)
|
||||
return self.request(f"/file/bot{self.token}/{path}", DOWNLOAD_BYTES)
|
||||
@@ -0,0 +1 @@
|
||||
"""Importer boundary tests."""
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Wire fixture and independent conversion assets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import io
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Final, override
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
from pydantic import JsonValue
|
||||
|
||||
TOKEN: Final = "123456:FixtureCredential_Only_0123456789"
|
||||
ROOT: Final = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Reply:
|
||||
"""Immutable wire response for one fixture route."""
|
||||
|
||||
body: bytes
|
||||
status: int = 200
|
||||
location: str = ""
|
||||
|
||||
|
||||
def encoded(value: JsonValue) -> bytes:
|
||||
"""Serialize independent fixture JSON into a wire response."""
|
||||
return json.dumps(value).encode()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def api_server(
|
||||
routes: dict[str, Reply], received: list[str] | None = None
|
||||
) -> Iterator[str]:
|
||||
"""Serve fixture routes on loopback without logging request credentials."""
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None:
|
||||
if received is not None:
|
||||
received.append(self.path)
|
||||
parsed = urlsplit(self.path)
|
||||
key = parsed.path.rsplit("/", 1)[-1]
|
||||
if key == "getFile":
|
||||
key = parse_qs(parsed.query)["file_id"][0]
|
||||
reply = routes.get(key, Reply(b"", 404))
|
||||
self.send_response(reply.status)
|
||||
if reply.location:
|
||||
self.send_header("Location", reply.location)
|
||||
self.send_header("Content-Length", str(len(reply.body)))
|
||||
self.end_headers()
|
||||
try:
|
||||
_ = self.wfile.write(reply.body)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
return # Expected when bounded client rejects oversized fixture.
|
||||
|
||||
@override
|
||||
def log_message(self, format: str, *args: str | int) -> None:
|
||||
return # Never log credential-bearing fixture paths.
|
||||
|
||||
with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
yield f"http://127.0.0.1:{server.server_port}"
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def routes_for(assets: dict[str, bytes]) -> dict[str, Reply]:
|
||||
"""Describe source files using Bot API envelopes and download routes."""
|
||||
stickers: list[JsonValue] = []
|
||||
routes: dict[str, Reply] = {}
|
||||
for index, (filename, data) in enumerate(assets.items()):
|
||||
file_id = f"file{index}"
|
||||
stickers.append(
|
||||
{
|
||||
"file_id": file_id,
|
||||
"width": 512,
|
||||
"height": 512,
|
||||
"is_animated": filename.endswith(".tgs"),
|
||||
"is_video": filename.endswith(".webm"),
|
||||
"emoji": "😀",
|
||||
"file_size": len(data),
|
||||
}
|
||||
)
|
||||
routes[file_id] = Reply(
|
||||
encoded(
|
||||
{
|
||||
"ok": True,
|
||||
"result": {
|
||||
"file_path": "stickers/" + filename,
|
||||
"file_size": len(data),
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
routes[filename] = Reply(data)
|
||||
routes["getStickerSet"] = Reply(
|
||||
encoded(
|
||||
{
|
||||
"ok": True,
|
||||
"result": {
|
||||
"name": "FixturePack",
|
||||
"title": "Fixture pack",
|
||||
"stickers": stickers,
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
return routes
|
||||
|
||||
|
||||
def vector_data() -> JsonValue:
|
||||
"""Describe a moving solid layer independently of the converter."""
|
||||
return {
|
||||
"v": "5.5.2",
|
||||
"w": 512,
|
||||
"h": 512,
|
||||
"fr": 30,
|
||||
"ip": 0,
|
||||
"op": 30,
|
||||
"layers": [
|
||||
{
|
||||
"ty": 1,
|
||||
"ind": 1,
|
||||
"ip": 0,
|
||||
"op": 30,
|
||||
"st": 0,
|
||||
"sw": 128,
|
||||
"sh": 128,
|
||||
"sc": "#00ff00",
|
||||
"ks": {
|
||||
"o": {"a": 0, "k": 100},
|
||||
"r": {"a": 0, "k": 0},
|
||||
"p": {
|
||||
"a": 1,
|
||||
"k": [
|
||||
{
|
||||
"t": 0,
|
||||
"s": [64, 192],
|
||||
"e": [320, 192],
|
||||
"i": {"x": 1, "y": 1},
|
||||
"o": {"x": 0, "y": 0},
|
||||
},
|
||||
{"t": 30, "s": [320, 192]},
|
||||
],
|
||||
},
|
||||
"a": {"a": 0, "k": [0, 0]},
|
||||
"s": {"a": 0, "k": [100, 100]},
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def make_conversion_assets() -> dict[str, bytes]:
|
||||
"""Generate source media shared by CLI tests and the isolated game API fixture."""
|
||||
image = Image.new("RGBA", (256, 128))
|
||||
ImageDraw.Draw(image).rectangle((64, 32, 191, 95), fill=(255, 0, 0, 255))
|
||||
with io.BytesIO() as buffer:
|
||||
image.save(buffer, format="WEBP", lossless=True)
|
||||
webp = buffer.getvalue()
|
||||
frames: list[bytes] = []
|
||||
for index in range(80):
|
||||
image = Image.new("RGBA", (128, 128))
|
||||
ImageDraw.Draw(image).rectangle(
|
||||
(index % 64, 32, index % 64 + 31, 63), fill=(0, 0, 255, 255)
|
||||
)
|
||||
frames.append(image.tobytes())
|
||||
ffmpeg = shutil.which("ffmpeg")
|
||||
if ffmpeg is None:
|
||||
pytest.fail("ffmpeg is required to generate independent video fixtures")
|
||||
video = subprocess.run(
|
||||
[
|
||||
ffmpeg,
|
||||
"-v",
|
||||
"error",
|
||||
"-nostdin",
|
||||
"-threads",
|
||||
"1",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
"-pixel_format",
|
||||
"rgba",
|
||||
"-video_size",
|
||||
"128x128",
|
||||
"-framerate",
|
||||
"20",
|
||||
"-i",
|
||||
"pipe:0",
|
||||
"-c:v",
|
||||
"libvpx-vp9",
|
||||
"-threads",
|
||||
"1",
|
||||
"-pix_fmt",
|
||||
"yuva420p",
|
||||
"-auto-alt-ref",
|
||||
"0",
|
||||
"-f",
|
||||
"webm",
|
||||
"pipe:1",
|
||||
],
|
||||
input=b"".join(frames),
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=30,
|
||||
).stdout
|
||||
return {
|
||||
"static.webp": webp,
|
||||
"vector.tgs": gzip.compress(encoded(vector_data())),
|
||||
"video.webm": video,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def conversion_assets() -> dict[str, bytes]:
|
||||
"""Provide the same independent source media to parametrized import checks."""
|
||||
return make_conversion_assets()
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Hostile wire responses and invalid committed catalogs for CLI scenarios."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, assert_never
|
||||
|
||||
from tests.conftest import TOKEN, Reply, encoded
|
||||
|
||||
WireFailure = Literal[
|
||||
"traversal",
|
||||
"absolute",
|
||||
"encoded_path",
|
||||
"redirect_api",
|
||||
"redirect_file",
|
||||
"oversize_download",
|
||||
"bad_json",
|
||||
"api_error",
|
||||
]
|
||||
CatalogFailure = Literal[
|
||||
"duplicate_packs", "bad_catalog", "catalog_bytes", "pack_limit", "overall_limit"
|
||||
]
|
||||
Failure = (
|
||||
WireFailure
|
||||
| CatalogFailure
|
||||
| Literal[
|
||||
"dimensions",
|
||||
"expansion",
|
||||
"external_tgs",
|
||||
"credential_metadata",
|
||||
"late_conversion",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def reject_wire(routes: dict[str, Reply], failure: WireFailure) -> None:
|
||||
"""Replace a fixture route with the requested hostile Bot API response."""
|
||||
match failure:
|
||||
case "traversal" | "absolute" | "encoded_path":
|
||||
path = {
|
||||
"traversal": "stickers/../secret.webp",
|
||||
"absolute": "https://evil.test/file.webp",
|
||||
"encoded_path": "stickers/%2e%2e/file.webp",
|
||||
}[failure]
|
||||
routes["file0"] = Reply(
|
||||
encoded({"ok": True, "result": {"file_path": path}})
|
||||
)
|
||||
case "redirect_api" | "redirect_file":
|
||||
key = "getStickerSet" if failure == "redirect_api" else "static.webp"
|
||||
routes[key] = Reply(b"", 302, "https://evil.test/" + TOKEN)
|
||||
case "oversize_download":
|
||||
routes["static.webp"] = Reply(b"x" * 4_194_305)
|
||||
case "bad_json":
|
||||
routes["getStickerSet"] = Reply(b"{broken " + TOKEN.encode())
|
||||
case "api_error":
|
||||
routes["getStickerSet"] = Reply(
|
||||
encoded({"ok": False, "description": TOKEN})
|
||||
)
|
||||
case _:
|
||||
assert_never(failure)
|
||||
|
||||
|
||||
def invalid_catalog(failure: CatalogFailure) -> bytes:
|
||||
"""Encode one independently constructed invalid on-disk catalog."""
|
||||
match failure:
|
||||
case "duplicate_packs":
|
||||
return encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{"id": "Old", "title": "One", "stickers": []},
|
||||
{"id": "Old", "title": "Two", "stickers": []},
|
||||
],
|
||||
}
|
||||
)
|
||||
case "bad_catalog":
|
||||
return b"{invalid"
|
||||
case "catalog_bytes":
|
||||
return b" " * 524_289
|
||||
case "pack_limit":
|
||||
return encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{"id": f"Old{i}", "title": "Old", "stickers": []}
|
||||
for i in range(64)
|
||||
],
|
||||
}
|
||||
)
|
||||
case "overall_limit":
|
||||
return encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{
|
||||
"id": f"Old{i}",
|
||||
"title": "Old",
|
||||
"stickers": [
|
||||
{"id": f"{j:064x}", "emoji": "", "frames": 1}
|
||||
for j in range(128)
|
||||
],
|
||||
}
|
||||
for i in range(16)
|
||||
],
|
||||
}
|
||||
)
|
||||
case _:
|
||||
assert_never(failure)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Disk ownership and interrupted-job recovery through the real CLI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import selectors
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import TYPE_CHECKING, Literal, assert_never
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from tests.conftest import ROOT, TOKEN, api_server, encoded, routes_for
|
||||
from tests.test_import import run_cli
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def png(color: str) -> bytes:
|
||||
"""Encode a deterministic opaque asset for cache ownership scenarios."""
|
||||
with io.BytesIO() as buffer:
|
||||
Image.new("RGBA", (128, 128), color).save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def test_recovery_and_replacement_reclaim_only_owned_unreferenced_assets(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
) -> None:
|
||||
"""Retain shared and unrelated files while reclaiming stale owned assets."""
|
||||
cache = tmp_path / "cache"
|
||||
assets = cache / "assets"
|
||||
assets.mkdir(parents=True)
|
||||
ids: list[str] = []
|
||||
for color in ("red", "green", "blue", "yellow"):
|
||||
data = png(color)
|
||||
asset_id = hashlib.sha256(data).hexdigest()
|
||||
_ = (assets / (asset_id + ".png")).write_bytes(data)
|
||||
ids.append(asset_id)
|
||||
_ = (assets / "unrelated.txt").write_text("keep")
|
||||
_ = (cache / "catalog.json").write_bytes(
|
||||
encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{
|
||||
"id": "FixturePack",
|
||||
"title": "Old",
|
||||
"stickers": [
|
||||
{"id": ids[0], "emoji": "", "frames": 1},
|
||||
{"id": ids[1], "emoji": "", "frames": 1},
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "KeepMe",
|
||||
"title": "Protected",
|
||||
"stickers": [
|
||||
{"id": ids[0], "emoji": "", "frames": 1},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
root = cache / ".wowmine-stickers-importer-v1"
|
||||
job = root / "job-12345678"
|
||||
job.mkdir(parents=True)
|
||||
_ = (root / "owner").write_bytes(b"wowmine-stickers-importer-v1\n")
|
||||
_ = (job / "journal.json").write_bytes(
|
||||
encoded({"version": 1, "assets": [ids[0], ids[2]]})
|
||||
)
|
||||
_ = (job / "input.webp").write_bytes(b"stale input")
|
||||
_ = (root / "unrelated.txt").write_text("keep too")
|
||||
with api_server(
|
||||
routes_for({"static.webp": conversion_assets["static.webp"]})
|
||||
) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert (assets / (ids[0] + ".png")).read_bytes() == png("red")
|
||||
assert not (assets / (ids[1] + ".png")).exists()
|
||||
assert not (assets / (ids[2] + ".png")).exists()
|
||||
assert (assets / (ids[3] + ".png")).read_bytes() == png("yellow")
|
||||
assert (assets / "unrelated.txt").read_text() == "keep"
|
||||
assert (root / "unrelated.txt").read_text() == "keep too"
|
||||
assert sorted(p.name for p in root.iterdir()) == ["owner", "unrelated.txt"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("interrupt", [signal.SIGKILL, signal.SIGALRM])
|
||||
def test_interrupted_job_retains_catalog_and_next_import_recovers_staging(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
interrupt: Literal[signal.Signals.SIGKILL, signal.Signals.SIGALRM],
|
||||
) -> None:
|
||||
"""Recover killed or timed-out jobs without changing the committed catalog."""
|
||||
token = tmp_path / "token"
|
||||
_ = token.write_text(TOKEN)
|
||||
cache = tmp_path / "cache"
|
||||
cache.mkdir()
|
||||
original = b'{"version":1,"packs":[]}'
|
||||
_ = (cache / "catalog.json").write_bytes(original)
|
||||
command = (
|
||||
[os.environ["IMPORTER_BINARY"]]
|
||||
if "IMPORTER_BINARY" in os.environ
|
||||
else [
|
||||
sys.executable,
|
||||
str(ROOT / "import_pack.py"),
|
||||
]
|
||||
)
|
||||
with api_server(routes_for(conversion_assets)) as origin:
|
||||
with subprocess.Popen(
|
||||
[
|
||||
*command,
|
||||
"--token-file",
|
||||
str(token),
|
||||
"--pack",
|
||||
"FixturePack",
|
||||
"--output",
|
||||
str(cache),
|
||||
"--api-base",
|
||||
origin,
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
bufsize=0,
|
||||
) as child:
|
||||
assert child.stdout is not None
|
||||
with selectors.DefaultSelector() as selector:
|
||||
_ = selector.register(child.stdout, selectors.EVENT_READ)
|
||||
assert selector.select(timeout=10)
|
||||
assert child.stdout.readline() == b'{"status":"fetching"}\n'
|
||||
assert selector.select(timeout=10)
|
||||
assert b'"status": "converting"' in child.stdout.readline()
|
||||
child.send_signal(interrupt)
|
||||
stdout, stderr = child.communicate(timeout=10)
|
||||
match interrupt:
|
||||
case signal.SIGKILL:
|
||||
assert child.returncode == -signal.SIGKILL
|
||||
case signal.SIGALRM:
|
||||
assert child.returncode == 1
|
||||
assert stderr == b'{"status":"error","code":"job_timeout"}\n'
|
||||
case _:
|
||||
assert_never(interrupt)
|
||||
assert TOKEN.encode() not in stdout + stderr
|
||||
assert (cache / "catalog.json").read_bytes() == original
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert sorted(
|
||||
p.name for p in (cache / ".wowmine-stickers-importer-v1").iterdir()
|
||||
) == ["owner"]
|
||||
@@ -0,0 +1,76 @@
|
||||
"""PNG identity includes timing, even when visible atlas pixels are identical."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from models import Catalog, ImportFailureError
|
||||
from tests.conftest import api_server, encoded, routes_for
|
||||
from tests.test_import import run_cli
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_transparent_animations_with_different_timing_keep_distinct_ids(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Distinguish frame counts even when transparent atlas pixels match."""
|
||||
assets = {
|
||||
f"empty{count}.tgs": gzip.compress(
|
||||
encoded(
|
||||
{
|
||||
"v": "5.5.2",
|
||||
"w": 512,
|
||||
"h": 512,
|
||||
"fr": 20,
|
||||
"ip": 0,
|
||||
"op": count,
|
||||
"layers": [],
|
||||
}
|
||||
)
|
||||
)
|
||||
for count in (9, 10)
|
||||
}
|
||||
with api_server(routes_for(assets)) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 0, result.stderr
|
||||
catalog = Catalog.model_validate_json(
|
||||
(tmp_path / "cache" / "catalog.json").read_bytes()
|
||||
)
|
||||
stickers = catalog.packs[0].stickers
|
||||
assert [s.frames for s in stickers] == [9, 10]
|
||||
assert stickers[0].id != stickers[1].id
|
||||
pixels: list[bytes] = []
|
||||
for sticker in stickers:
|
||||
with Image.open(tmp_path / "cache" / "assets" / (sticker.id + ".png")) as image:
|
||||
assert image.size == (1024, 256)
|
||||
assert image.info["wowmine_frames"] == str(sticker.frames)
|
||||
pixels.append(image.tobytes())
|
||||
assert pixels[0] == pixels[1]
|
||||
|
||||
|
||||
def test_catalog_rejects_conflicting_frames_for_shared_asset_id() -> None:
|
||||
"""Reject an asset ID associated with incompatible animation timing."""
|
||||
with pytest.raises(ImportFailureError, match="conflicting frame counts"):
|
||||
_ = Catalog.model_validate_json(
|
||||
encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{
|
||||
"id": f"Pack{count}",
|
||||
"title": "Title",
|
||||
"stickers": [
|
||||
{"id": "a" * 64, "emoji": "", "frames": count},
|
||||
],
|
||||
}
|
||||
for count in (9, 10)
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,242 @@
|
||||
"""CLI conversion, catalog compatibility and hostile input rejection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import TYPE_CHECKING, assert_never
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
from pydantic import JsonValue, TypeAdapter
|
||||
|
||||
from models import Catalog
|
||||
from tests.conftest import ROOT, TOKEN, Reply, api_server, encoded, routes_for
|
||||
from tests.rejected_inputs import invalid_catalog, reject_wire
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from tests.rejected_inputs import Failure
|
||||
|
||||
|
||||
def run_cli(
|
||||
directory: Path, origin: str, pack: str = "https://t.me/addstickers/FixturePack"
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
"""Run the installed or source CLI against an isolated fixture origin."""
|
||||
token = directory / "token"
|
||||
_ = token.write_text(TOKEN)
|
||||
command = (
|
||||
[os.environ["IMPORTER_BINARY"]]
|
||||
if "IMPORTER_BINARY" in os.environ
|
||||
else [
|
||||
sys.executable,
|
||||
str(ROOT / "import_pack.py"),
|
||||
]
|
||||
)
|
||||
return subprocess.run(
|
||||
[
|
||||
*command,
|
||||
"--token-file",
|
||||
str(token),
|
||||
"--pack",
|
||||
pack,
|
||||
"--output",
|
||||
str(directory / "cache"),
|
||||
"--api-base",
|
||||
origin,
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=90,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
def test_import_converts_all_formats_preserves_packs_and_deduplicates(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
) -> None:
|
||||
"""Preserve the wire catalog, alpha, animation and deduplication contracts."""
|
||||
assets = {**conversion_assets, "duplicate.webp": conversion_assets["static.webp"]}
|
||||
cache = tmp_path / "cache"
|
||||
cache.mkdir()
|
||||
retained: JsonValue = {"id": "KeepMe", "title": "Other pack", "stickers": []}
|
||||
replaced: JsonValue = {"id": "FixturePack", "title": "Old title", "stickers": []}
|
||||
_ = (cache / "catalog.json").write_bytes(
|
||||
encoded({"version": 1, "packs": [retained, replaced]})
|
||||
)
|
||||
with api_server(routes_for(assets)) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 0, result.stderr
|
||||
statuses = [
|
||||
TypeAdapter[JsonValue](JsonValue).validate_json(line)
|
||||
for line in result.stdout.splitlines()
|
||||
]
|
||||
assert statuses == [
|
||||
{"status": "fetching"},
|
||||
*[{"status": "converting", "completed": i, "total": 4} for i in range(4)],
|
||||
{"status": "complete", "pack": "FixturePack", "stickers": 3},
|
||||
]
|
||||
raw = (cache / "catalog.json").read_bytes()
|
||||
assert TOKEN.encode() not in raw
|
||||
catalog = TypeAdapter[JsonValue](JsonValue).validate_json(raw)
|
||||
assert isinstance(catalog, dict)
|
||||
packs = catalog["packs"]
|
||||
assert isinstance(packs, list)
|
||||
assert packs[0] == retained
|
||||
pack = packs[1]
|
||||
assert isinstance(pack, dict)
|
||||
assert set(catalog) == {"version", "packs"}
|
||||
assert set(pack) == {"id", "title", "stickers"}
|
||||
assert pack["title"] == "Fixture pack"
|
||||
parsed = Catalog.model_validate_json(raw).packs[1]
|
||||
assert [sticker.frames for sticker in parsed.stickers] == [1, 20, 60]
|
||||
entries = pack["stickers"]
|
||||
assert isinstance(entries, list)
|
||||
for entry, sticker in zip(entries, parsed.stickers, strict=True):
|
||||
assert isinstance(entry, dict)
|
||||
assert set(entry) == {"id", "emoji", "frames"}
|
||||
asset = cache / "assets" / (sticker.id + ".png")
|
||||
assert hashlib.sha256(asset.read_bytes()).hexdigest() == sticker.id
|
||||
with Image.open(asset) as image:
|
||||
count = sticker.frames
|
||||
assert image.size == (
|
||||
min(8, count) * 128,
|
||||
((count + min(8, count) - 1) // min(8, count)) * 128,
|
||||
)
|
||||
assert image.mode == "RGBA"
|
||||
pixel = image.getpixel((0, 0))
|
||||
assert isinstance(pixel, tuple)
|
||||
assert pixel[3] == 0
|
||||
assert image.getchannel("A").getextrema() == (0, 255)
|
||||
if count == 1:
|
||||
assert image.getpixel((40, 60)) == (255, 0, 0, 255)
|
||||
if count > 1:
|
||||
last = ((count - 1) % 8 * 128, (count - 1) // 8 * 128)
|
||||
assert (
|
||||
image.crop((0, 0, 128, 128)).tobytes()
|
||||
!= image.crop(
|
||||
(*last, last[0] + 128, last[1] + 128),
|
||||
).tobytes()
|
||||
)
|
||||
assert TOKEN not in result.stdout + result.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"failure",
|
||||
[
|
||||
"traversal",
|
||||
"absolute",
|
||||
"encoded_path",
|
||||
"redirect_api",
|
||||
"redirect_file",
|
||||
"oversize_download",
|
||||
"bad_json",
|
||||
"api_error",
|
||||
"dimensions",
|
||||
"expansion",
|
||||
"external_tgs",
|
||||
"duplicate_packs",
|
||||
"bad_catalog",
|
||||
"credential_metadata",
|
||||
"late_conversion",
|
||||
"catalog_bytes",
|
||||
"pack_limit",
|
||||
"overall_limit",
|
||||
],
|
||||
)
|
||||
def test_rejected_import_retains_catalog_and_hides_credentials(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
failure: Failure,
|
||||
) -> None:
|
||||
"""Retain committed state and redact credentials on every rejection path."""
|
||||
assets = {"static.webp": conversion_assets["static.webp"]}
|
||||
routes = routes_for(assets)
|
||||
cache = tmp_path / "cache"
|
||||
cache.mkdir()
|
||||
original = encoded(
|
||||
{"version": 1, "packs": [{"id": "Old", "title": "Retained", "stickers": []}]}
|
||||
)
|
||||
match failure:
|
||||
case (
|
||||
"traversal"
|
||||
| "absolute"
|
||||
| "encoded_path"
|
||||
| "redirect_api"
|
||||
| "redirect_file"
|
||||
| "oversize_download"
|
||||
| "bad_json"
|
||||
| "api_error"
|
||||
):
|
||||
reject_wire(routes, failure)
|
||||
case "dimensions":
|
||||
with io.BytesIO() as buffer:
|
||||
Image.new("RGBA", (513, 1)).save(buffer, format="WEBP")
|
||||
routes = routes_for({"huge.webp": buffer.getvalue()})
|
||||
case "expansion":
|
||||
routes = routes_for({"bomb.tgs": gzip.compress(b" " * 2_097_153)})
|
||||
case "external_tgs":
|
||||
routes = routes_for(
|
||||
{
|
||||
"linked.tgs": gzip.compress(
|
||||
encoded(
|
||||
{
|
||||
"w": 512,
|
||||
"h": 512,
|
||||
"fr": 30,
|
||||
"ip": 0,
|
||||
"op": 30,
|
||||
"assets": [
|
||||
{
|
||||
"id": "external",
|
||||
"p": "file:///etc/passwd",
|
||||
"u": "",
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
)
|
||||
case (
|
||||
"duplicate_packs"
|
||||
| "bad_catalog"
|
||||
| "catalog_bytes"
|
||||
| "pack_limit"
|
||||
| "overall_limit"
|
||||
):
|
||||
original = invalid_catalog(failure)
|
||||
case "credential_metadata":
|
||||
value = TypeAdapter[JsonValue](JsonValue).validate_json(
|
||||
routes["getStickerSet"].body
|
||||
)
|
||||
assert isinstance(value, dict)
|
||||
remote = value["result"]
|
||||
assert isinstance(remote, dict)
|
||||
remote["title"] = TOKEN
|
||||
routes["getStickerSet"] = Reply(json.dumps(value).encode())
|
||||
case "late_conversion":
|
||||
routes = routes_for({**assets, "broken.tgs": b"not gzip"})
|
||||
case _:
|
||||
assert_never(failure)
|
||||
_ = (cache / "catalog.json").write_bytes(original)
|
||||
with api_server(routes) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 1
|
||||
assert (cache / "catalog.json").read_bytes() == original
|
||||
assert TOKEN not in result.stdout + result.stderr
|
||||
assert "Traceback" not in result.stderr
|
||||
assert TypeAdapter[JsonValue](JsonValue).validate_json(result.stderr) == {
|
||||
"status": "error",
|
||||
"code": "import_failed",
|
||||
}
|
||||
stage_root = cache / ".wowmine-stickers-importer-v1"
|
||||
if stage_root.exists():
|
||||
assert sorted(p.name for p in stage_root.iterdir()) == ["owner"]
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Client catalog compatibility and player-controlled input rejection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
from pydantic import JsonValue, ValidationError
|
||||
|
||||
from models import Catalog, ImportFailureError
|
||||
from tests.conftest import TOKEN, Reply, api_server, encoded, routes_for
|
||||
from tests.test_import import run_cli
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"pack",
|
||||
[
|
||||
"https://evil.test/addstickers/FixturePack",
|
||||
"https://t.me@evil.test/addstickers/FixturePack",
|
||||
"https://user@t.me/addstickers/FixturePack",
|
||||
"//t.me/addstickers/FixturePack",
|
||||
"https://t.me/addstickers/FixturePack?host=evil.test",
|
||||
"FixturePack/../secret",
|
||||
"FixturePack\n",
|
||||
],
|
||||
)
|
||||
def test_player_pack_input_cannot_select_fetch_origin(
|
||||
tmp_path: Path, pack: str
|
||||
) -> None:
|
||||
"""Reject player-controlled origins before making any fixture request."""
|
||||
received: list[str] = []
|
||||
with api_server({}, received) as origin:
|
||||
result = run_cli(tmp_path, origin, pack)
|
||||
assert result.returncode == 1
|
||||
assert received == []
|
||||
assert not (tmp_path / "cache" / "catalog.json").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route", ["getStickerSet", "static.webp"])
|
||||
def test_redirect_never_sends_token_to_destination(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
route: str,
|
||||
) -> None:
|
||||
"""Never forward credential-bearing API or file redirects."""
|
||||
received: list[str] = []
|
||||
with api_server({}, received) as destination:
|
||||
routes = routes_for({"static.webp": conversion_assets["static.webp"]})
|
||||
routes[route] = Reply(b"", 302, destination + "/" + TOKEN)
|
||||
with api_server(routes) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 1
|
||||
assert received == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value"),
|
||||
[
|
||||
("frames", 0),
|
||||
("frames", 61),
|
||||
("id", "A" * 64),
|
||||
("emoji", "😀" * 33),
|
||||
],
|
||||
)
|
||||
def test_catalog_rejects_values_client_cannot_use(field: str, value: str | int) -> None:
|
||||
"""Reject sticker values outside the client's catalog contract."""
|
||||
sticker: JsonValue = {"id": "a" * 64, "emoji": "", "frames": 1, field: value}
|
||||
with pytest.raises((ValueError, UnicodeError, ImportFailureError)):
|
||||
_ = Catalog.model_validate_json(
|
||||
encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [{"id": "Pack", "title": "Title", "stickers": [sticker]}],
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [True, 0, 2, "1"])
|
||||
def test_catalog_version_requires_integer_one(*, version: bool | int | str) -> None:
|
||||
"""Reject booleans, other versions and string coercion for catalog version."""
|
||||
with pytest.raises(ValidationError):
|
||||
_ = Catalog.model_validate_json(encoded({"version": version, "packs": []}))
|
||||
@@ -0,0 +1,8 @@
|
||||
# Local types for verified python-lottie Cairo exporter API.
|
||||
from typing import BinaryIO
|
||||
|
||||
from lottie.objects import Animation
|
||||
|
||||
def export_png(
|
||||
animation: Animation, fp: BinaryIO, frame: float = 0, dpi: float = 96
|
||||
) -> None: ...
|
||||
@@ -0,0 +1,6 @@
|
||||
# Local types for verified python-lottie 0.7.2 vector loading API.
|
||||
from pydantic import JsonValue
|
||||
|
||||
class Animation:
|
||||
@classmethod
|
||||
def load(cls, lottiedict: dict[str, JsonValue]) -> Animation: ...
|
||||
@@ -0,0 +1,8 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
gradlePluginPortal()
|
||||
maven { url = 'https://maven.neoforged.net/releases' }
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = 'wowmine-stickers'
|
||||
@@ -0,0 +1,178 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.security.DigestInputStream;
|
||||
import java.sql.SQLException;
|
||||
import java.time.DateTimeException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeFormatterBuilder;
|
||||
import java.time.format.ResolverStyle;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
/** Conservative migration, run before live capture. Completion freezes the migration forever. */
|
||||
public final class ArchiveLogImport {
|
||||
private static final DateTimeFormatter DATE = new DateTimeFormatterBuilder()
|
||||
.parseCaseInsensitive().appendPattern("ddMMMuuuu HH:mm:ss.SSS")
|
||||
.toFormatter(Locale.ENGLISH).withResolverStyle(ResolverStyle.STRICT);
|
||||
// MinecraftServer.logChatMessage logs public player chat; command feedback uses other decorations.
|
||||
// The supplied server log confirms this full logger naming and Server thread envelope.
|
||||
private static final Pattern PUBLIC_CHAT = Pattern.compile(
|
||||
"^\\[(\\d{2}[A-Za-z]{3}\\d{4} \\d{2}:\\d{2}:\\d{2}\\.\\d{3})\\] "
|
||||
+ "\\[Server thread/INFO\\] \\[net\\.minecraft\\.server\\.MinecraftServer/\\]: "
|
||||
+ "(?:\\[Not Secure\\] )?<([A-Za-z0-9_]{1,16})> ([^\\r\\n\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f]*)$");
|
||||
private static final int MAX_LINE = ChatHistory.BODY_CHARACTERS + 256;
|
||||
|
||||
private ArchiveLogImport() {}
|
||||
|
||||
/** Returns newly committed rows this invocation; retries may return fewer than total migration rows. */
|
||||
public static int importOnce(ChatArchive archive, Path logsDirectory, ZoneId zone)
|
||||
throws IOException, SQLException {
|
||||
// Serialize the entire snapshot/migration against live capture and another importer.
|
||||
synchronized (archive) {
|
||||
if (archive.legacyComplete()) {
|
||||
return 0;
|
||||
}
|
||||
List<Path> paths;
|
||||
try (var files = Files.list(logsDirectory)) {
|
||||
paths = files.filter(path -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS))
|
||||
.filter(path -> {
|
||||
String name = path.getFileName().toString();
|
||||
// Startup still writes latest/debug; only retained logs can be frozen.
|
||||
return (name.endsWith(".log") || name.endsWith(".log.gz"))
|
||||
&& !name.equals("latest.log") && !name.equals("debug.log")
|
||||
&& !name.startsWith("debug-");
|
||||
})
|
||||
.sorted().toList();
|
||||
}
|
||||
Map<String, Path> available = new HashMap<>();
|
||||
List<ChatArchive.LegacySource> snapshot = new ArrayList<>();
|
||||
for (Path path : paths) {
|
||||
String sha = sourceHash(path);
|
||||
if (available.putIfAbsent(sha, path) == null) {
|
||||
snapshot.add(new ChatArchive.LegacySource(sha, path.toAbsolutePath().toString()));
|
||||
}
|
||||
}
|
||||
var manifest = archive.legacyManifest();
|
||||
if (manifest.isEmpty()) {
|
||||
archive.beginLegacyImport(snapshot);
|
||||
manifest = archive.legacyManifest();
|
||||
}
|
||||
int imported = 0;
|
||||
for (ChatArchive.LegacySource source : manifest.orElseThrow()) {
|
||||
Path path = available.get(source.sha());
|
||||
if (path == null) {
|
||||
throw new IOException("Pending legacy source is missing or changed: " + source.path());
|
||||
}
|
||||
try (InputStream input = open(path);
|
||||
var reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT)))) {
|
||||
long number = 0;
|
||||
String line;
|
||||
while ((line = boundedLine(reader)) != null) {
|
||||
number++;
|
||||
var match = PUBLIC_CHAT.matcher(line);
|
||||
if (!match.matches() || match.group(3).startsWith("/")) {
|
||||
continue;
|
||||
}
|
||||
long time;
|
||||
try {
|
||||
time = LocalDateTime.parse(match.group(1), DATE).atZone(zone).toInstant().toEpochMilli();
|
||||
} catch (DateTimeException error) {
|
||||
continue;
|
||||
}
|
||||
if (time < 0) {
|
||||
continue;
|
||||
}
|
||||
var component = new JsonObject();
|
||||
component.addProperty("text", match.group(3));
|
||||
String body = component.toString();
|
||||
if (body.length() > ChatHistory.BODY_CHARACTERS
|
||||
|| body.getBytes(StandardCharsets.UTF_8).length > ChatHistory.BODY_BYTES) {
|
||||
continue;
|
||||
}
|
||||
String name = match.group(2);
|
||||
UUID author = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8));
|
||||
var draft = new ChatHistory.Draft(time, author, name, ChatHistory.Kind.TEXT, body, "", 0);
|
||||
if (archive.importLegacyLine(source.sha(), number, draft)) {
|
||||
imported = Math.incrementExact(imported);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!source.sha().equals(sourceHash(path))) {
|
||||
throw new IOException("Legacy log changed during migration: " + source.path());
|
||||
}
|
||||
}
|
||||
archive.completeLegacyImport();
|
||||
return imported;
|
||||
}
|
||||
}
|
||||
|
||||
// An oversized line is consumed, but never retained or parsed as a truncated public message.
|
||||
private static String boundedLine(BufferedReader input) throws IOException {
|
||||
var line = new StringBuilder();
|
||||
boolean overflow = false;
|
||||
int value;
|
||||
while ((value = input.read()) != -1 && value != '\n') {
|
||||
if (line.length() < MAX_LINE) {
|
||||
line.append((char) value);
|
||||
} else {
|
||||
overflow = true;
|
||||
}
|
||||
}
|
||||
if (value == -1 && line.isEmpty() && !overflow) {
|
||||
return null;
|
||||
}
|
||||
if (overflow) {
|
||||
return "";
|
||||
}
|
||||
if (!line.isEmpty() && line.charAt(line.length() - 1) == '\r') {
|
||||
line.setLength(line.length() - 1);
|
||||
}
|
||||
return line.toString();
|
||||
}
|
||||
|
||||
private static InputStream open(Path path) throws IOException {
|
||||
InputStream input = Files.newInputStream(path);
|
||||
if (!path.getFileName().toString().endsWith(".gz")) {
|
||||
return input;
|
||||
}
|
||||
try {
|
||||
return new GZIPInputStream(input);
|
||||
} catch (IOException error) {
|
||||
try {
|
||||
input.close();
|
||||
} catch (IOException closeError) {
|
||||
error.addSuppressed(closeError);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private static String sourceHash(Path path) throws IOException {
|
||||
var digest = ChatArchive.digest();
|
||||
try (InputStream input = open(path); var hashing = new DigestInputStream(input, digest)) {
|
||||
hashing.transferTo(OutputStream.nullOutputStream());
|
||||
}
|
||||
return HexFormat.of().formatHex(digest.digest());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import com.mojang.logging.LogUtils;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.sql.SQLException;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
import net.neoforged.fml.loading.FMLPaths;
|
||||
import net.neoforged.neoforge.event.ServerChatEvent;
|
||||
import net.neoforged.neoforge.network.PacketDistributor;
|
||||
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
|
||||
import net.wowmine.stickers.client.HistoryClient;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
/** Durable writes precede public text/sticker delivery; bounded reads never load the full archive. */
|
||||
public final class ArchiveServer implements AutoCloseable {
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
private final MinecraftServer server;
|
||||
private final ChatArchive archive;
|
||||
private final ThreadPoolExecutor reader = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
|
||||
new ArrayBlockingQueue<>(32),
|
||||
Thread.ofPlatform().daemon().name("wowmine-history-reader").factory());
|
||||
private final Map<UUID, Integer> pageAfter = new HashMap<>();
|
||||
private final Set<UUID> pagesPending = new HashSet<>();
|
||||
private final Set<UUID> mediaPending = new HashSet<>();
|
||||
private final ArrayDeque<Transfer> transfers = new ArrayDeque<>();
|
||||
private volatile boolean closed;
|
||||
|
||||
private ArchiveServer(MinecraftServer server, ChatArchive archive) {
|
||||
this.server = server;
|
||||
this.archive = archive;
|
||||
}
|
||||
|
||||
public static ArchiveServer open(MinecraftServer server) throws IOException, SQLException {
|
||||
Path root = server.getWorldPath(LevelResource.ROOT).resolve("data/wowmine-chat-history");
|
||||
var result = new ArchiveServer(server, new ChatArchive(root));
|
||||
try {
|
||||
// Client logs may contain other servers' private messages; never import them.
|
||||
int imported = server.isDedicatedServer()
|
||||
? ArchiveLogImport.importOnce(result.archive,
|
||||
FMLPaths.GAMEDIR.get().resolve("logs"), ZoneId.systemDefault())
|
||||
: 0;
|
||||
LOGGER.info("Chat archive ready: importedPublicMessages={}", imported);
|
||||
ArchiveVoiceServer.attach(result);
|
||||
return result;
|
||||
} catch (IOException | SQLException failure) {
|
||||
result.close();
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
public static void register(RegisterPayloadHandlersEvent event, Supplier<ArchiveServer> current) {
|
||||
var registrar = event.registrar("1").optional();
|
||||
registrar.playToClient(HistoryPackets.PageReply.TYPE, HistoryPackets.PageReply.CODEC,
|
||||
(packet, context) -> context.enqueueWork(() -> HistoryClient.onPage(packet)));
|
||||
registrar.playToClient(HistoryPackets.AttachmentChunk.TYPE, HistoryPackets.AttachmentChunk.CODEC,
|
||||
(packet, context) -> context.enqueueWork(() -> HistoryClient.onAttachment(packet)));
|
||||
registrar.playToClient(HistoryPackets.Problem.TYPE, HistoryPackets.Problem.CODEC,
|
||||
(packet, context) -> context.enqueueWork(() -> HistoryClient.onProblem(packet)));
|
||||
registrar.playToServer(HistoryPackets.PageRequest.TYPE, HistoryPackets.PageRequest.CODEC,
|
||||
(packet, context) -> {
|
||||
var player = (ServerPlayer) context.player();
|
||||
ArchiveServer active = current.get();
|
||||
if (active == null) {
|
||||
problem(player, packet.request(), ChatHistory.Failure.UNAVAILABLE);
|
||||
} else {
|
||||
active.page(player, packet);
|
||||
}
|
||||
});
|
||||
registrar.playToServer(HistoryPackets.AttachmentRequest.TYPE, HistoryPackets.AttachmentRequest.CODEC,
|
||||
(packet, context) -> {
|
||||
var player = (ServerPlayer) context.player();
|
||||
ArchiveServer active = current.get();
|
||||
if (active == null) {
|
||||
problem(player, packet.request(), ChatHistory.Failure.UNAVAILABLE);
|
||||
} else {
|
||||
active.attachment(player, packet);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void chat(ServerChatEvent event) {
|
||||
ServerPlayer player = event.getPlayer();
|
||||
try {
|
||||
archive.append(new ChatHistory.Draft(System.currentTimeMillis(), player.getUUID(),
|
||||
player.getGameProfile().getName(), ChatHistory.Kind.TEXT,
|
||||
serialize(event.getMessage()), "", 0), ChatHistory.PUBLIC, new byte[0]);
|
||||
} catch (IOException | SQLException failure) {
|
||||
LOGGER.error("Cannot commit public chat to archive", failure);
|
||||
event.setCanceled(true);
|
||||
player.displayClientMessage(Component.translatable("wowmine_history.error.not_sent"), false);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean sticker(ServerPlayer sender, ServerCatalog catalog, String id) {
|
||||
StickerCatalog.Sticker sticker = catalog.catalog().find(id).orElseThrow();
|
||||
try {
|
||||
byte[] bytes = catalog.asset(id);
|
||||
archive.append(new ChatHistory.Draft(System.currentTimeMillis(), sender.getUUID(),
|
||||
sender.getGameProfile().getName(), ChatHistory.Kind.STICKER,
|
||||
serialize(Component.empty()), id, sticker.frames()), ChatHistory.PUBLIC, bytes);
|
||||
return true;
|
||||
} catch (IOException | SQLException failure) {
|
||||
LOGGER.error("Cannot commit sticker to archive: id={}", id, failure);
|
||||
sender.displayClientMessage(Component.translatable("wowmine_history.error.not_sent"), false);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void recordVoice(ServerPlayer sender, List<byte[]> frames, String target,
|
||||
ChatHistory.Audience audience) {
|
||||
byte[] encoded = VoiceFrames.encode(frames);
|
||||
String id;
|
||||
try {
|
||||
id = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(encoded));
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new AssertionError(impossible);
|
||||
}
|
||||
try {
|
||||
Component description = switch (target) {
|
||||
case "all" -> Component.translatable("wowmine_stickers.history.voice.public");
|
||||
case "team" -> Component.translatable("wowmine_stickers.history.voice.team");
|
||||
default -> Component.translatable("wowmine_stickers.history.voice.to", target);
|
||||
};
|
||||
archive.append(new ChatHistory.Draft(System.currentTimeMillis(), sender.getUUID(),
|
||||
sender.getGameProfile().getName(), ChatHistory.Kind.VOICE,
|
||||
serialize(description), id, frames.size()), audience, encoded);
|
||||
} catch (IOException | SQLException failure) {
|
||||
LOGGER.error("Cannot commit voice message to archive", failure);
|
||||
sender.displayClientMessage(Component.translatable("wowmine_history.error.not_saved"), false);
|
||||
}
|
||||
}
|
||||
|
||||
private String serialize(Component component) {
|
||||
return Component.Serializer.toJson(component, server.registryAccess());
|
||||
}
|
||||
|
||||
private void page(ServerPlayer player, HistoryPackets.PageRequest request) {
|
||||
UUID viewer = player.getUUID();
|
||||
int now = server.getTickCount();
|
||||
if (pagesPending.contains(viewer) || pagesPending.size() >= 32
|
||||
|| now < pageAfter.getOrDefault(viewer, 0)) {
|
||||
problem(player, request.request(), ChatHistory.Failure.BUSY);
|
||||
return;
|
||||
}
|
||||
pagesPending.add(viewer);
|
||||
pageAfter.put(viewer, now + 10);
|
||||
try {
|
||||
reader.execute(() -> {
|
||||
try {
|
||||
ChatHistory.Page page = archive.page(viewer, request.query());
|
||||
onServer(() -> {
|
||||
pagesPending.remove(viewer);
|
||||
if (connected(player)) {
|
||||
PacketDistributor.sendToPlayer(player,
|
||||
new HistoryPackets.PageReply(request.request(), page));
|
||||
}
|
||||
});
|
||||
} catch (SQLException failure) {
|
||||
LOGGER.warn("Chat archive query failed", failure);
|
||||
onServer(() -> {
|
||||
pagesPending.remove(viewer);
|
||||
if (connected(player)) {
|
||||
problem(player, request.request(), ChatHistory.Failure.UNAVAILABLE);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (RejectedExecutionException busy) {
|
||||
pagesPending.remove(viewer);
|
||||
problem(player, request.request(), ChatHistory.Failure.BUSY);
|
||||
}
|
||||
}
|
||||
|
||||
private void attachment(ServerPlayer player, HistoryPackets.AttachmentRequest request) {
|
||||
UUID viewer = player.getUUID();
|
||||
if (mediaPending.contains(viewer) || mediaPending.size() >= 4) {
|
||||
problem(player, request.request(), ChatHistory.Failure.BUSY);
|
||||
return;
|
||||
}
|
||||
mediaPending.add(viewer);
|
||||
try {
|
||||
reader.execute(() -> {
|
||||
try {
|
||||
var attachment = archive.attachment(viewer, request.entry());
|
||||
onServer(() -> {
|
||||
if (!connected(player)) {
|
||||
mediaPending.remove(viewer);
|
||||
} else if (attachment.isEmpty()) {
|
||||
mediaPending.remove(viewer);
|
||||
problem(player, request.request(), ChatHistory.Failure.NOT_FOUND);
|
||||
} else {
|
||||
var value = attachment.orElseThrow();
|
||||
transfers.addLast(new Transfer(player, request.request(), value.id(), value.bytes()));
|
||||
}
|
||||
});
|
||||
} catch (SQLException failure) {
|
||||
LOGGER.warn("Chat archive attachment read failed: entry={}", request.entry(), failure);
|
||||
onServer(() -> {
|
||||
mediaPending.remove(viewer);
|
||||
if (connected(player)) {
|
||||
problem(player, request.request(), ChatHistory.Failure.UNAVAILABLE);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (RejectedExecutionException busy) {
|
||||
mediaPending.remove(viewer);
|
||||
problem(player, request.request(), ChatHistory.Failure.BUSY);
|
||||
}
|
||||
}
|
||||
|
||||
public void tick() {
|
||||
for (int budget = 0; budget < 2 && !transfers.isEmpty(); budget++) {
|
||||
Transfer transfer = transfers.removeFirst();
|
||||
if (!connected(transfer.player)) {
|
||||
mediaPending.remove(transfer.player.getUUID());
|
||||
continue;
|
||||
}
|
||||
int end = Math.min(transfer.bytes.length, transfer.offset + HistoryPackets.CHUNK_BYTES);
|
||||
PacketDistributor.sendToPlayer(transfer.player, new HistoryPackets.AttachmentChunk(
|
||||
transfer.request, transfer.id, transfer.offset / HistoryPackets.CHUNK_BYTES,
|
||||
transfer.bytes.length, Arrays.copyOfRange(transfer.bytes, transfer.offset, end)));
|
||||
transfer.offset = end;
|
||||
if (end == transfer.bytes.length) {
|
||||
mediaPending.remove(transfer.player.getUUID());
|
||||
} else {
|
||||
transfers.addLast(transfer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void forget(UUID player) {
|
||||
pageAfter.remove(player);
|
||||
// Pending work retains its slot until completion, including across reconnects.
|
||||
}
|
||||
|
||||
private void onServer(Runnable work) {
|
||||
if (!closed) {
|
||||
server.execute(() -> {
|
||||
if (!closed) {
|
||||
work.run();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private boolean connected(ServerPlayer player) {
|
||||
return !closed && server.getPlayerList().getPlayer(player.getUUID()) == player;
|
||||
}
|
||||
|
||||
private static void problem(ServerPlayer player, long request, ChatHistory.Failure failure) {
|
||||
PacketDistributor.sendToPlayer(player, new HistoryPackets.Problem(request, failure));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closed = true;
|
||||
ArchiveVoiceServer.detach(this);
|
||||
reader.close();
|
||||
transfers.clear();
|
||||
mediaPending.clear();
|
||||
pagesPending.clear();
|
||||
pageAfter.clear();
|
||||
try {
|
||||
archive.close();
|
||||
} catch (SQLException failure) {
|
||||
LOGGER.error("Cannot close chat archive", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Transfer {
|
||||
private final ServerPlayer player;
|
||||
private final long request;
|
||||
private final String id;
|
||||
private final byte[] bytes;
|
||||
private int offset;
|
||||
|
||||
private Transfer(ServerPlayer player, long request, String id, byte[] bytes) {
|
||||
this.player = player;
|
||||
this.request = request;
|
||||
this.id = id;
|
||||
this.bytes = bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.neoforged.fml.ModList;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import ru.dimaskama.voicemessages.api.VoiceMessageReceivedCallback;
|
||||
import ru.dimaskama.voicemessages.api.VoiceMessagesApi;
|
||||
import ru.dimaskama.voicemessages.api.VoiceMessagesApiInitCallback;
|
||||
|
||||
/** Observes completed VoiceMessages only; commands and upstream delivery are untouched. */
|
||||
public final class ArchiveVoiceServer {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ArchiveVoiceServer.class);
|
||||
private static volatile ArchiveServer archive;
|
||||
private static boolean initialized;
|
||||
|
||||
private ArchiveVoiceServer() {}
|
||||
|
||||
public static synchronized void init() {
|
||||
if (initialized) {
|
||||
return;
|
||||
}
|
||||
if (ModList.get().isLoaded("voicemessages")) {
|
||||
Supported.init();
|
||||
}
|
||||
NeoForge.EVENT_BUS.addListener((ServerStoppedEvent event) -> {
|
||||
archive = null;
|
||||
if (ModList.get().isLoaded("voicemessages")) {
|
||||
Supported.clear();
|
||||
}
|
||||
});
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
public static void attach(ArchiveServer server) {
|
||||
init();
|
||||
archive = java.util.Objects.requireNonNull(server);
|
||||
}
|
||||
|
||||
public static void detach(ArchiveServer server) {
|
||||
if (archive == server) {
|
||||
archive = null;
|
||||
if (ModList.get().isLoaded("voicemessages")) {
|
||||
Supported.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** All upstream types stay behind the optional-mod class-loading boundary. */
|
||||
private static final class Supported {
|
||||
private static volatile VoiceMessagesApi api;
|
||||
|
||||
private static void init() {
|
||||
VoiceMessagesApiInitCallback.EVENT.register(value -> api = value);
|
||||
VoiceMessageReceivedCallback.EVENT.register(Supported::received);
|
||||
}
|
||||
|
||||
private static void clear() {
|
||||
api = null;
|
||||
}
|
||||
|
||||
private static boolean received(Object sender, List<byte[]> frames, String target) {
|
||||
ArchiveServer current = archive;
|
||||
if (current == null || !(sender instanceof ServerPlayer player)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
ChatHistory.Audience audience = audience(player, target);
|
||||
if (audience != null) {
|
||||
// recordVoice snapshots and commits synchronously before upstream builder cleanup.
|
||||
current.recordVoice(player, frames, target, audience);
|
||||
}
|
||||
} catch (RuntimeException error) {
|
||||
LOGGER.warn("Cannot archive completed voice message", error);
|
||||
player.displayClientMessage(Component.translatable(
|
||||
"wowmine_stickers.history.voice.archive_failed"), false);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static ChatHistory.Audience audience(ServerPlayer sender, String target) {
|
||||
if ("all".equals(target)) {
|
||||
return ChatHistory.PUBLIC;
|
||||
}
|
||||
var playerList = sender.server.getPlayerList();
|
||||
ServerPlayer named = target == null ? null : playerList.getPlayerByName(target);
|
||||
if (!"team".equals(target) && named == null) {
|
||||
LOGGER.warn("Voice archive skipped unsupported custom target");
|
||||
sender.displayClientMessage(Component.translatable(
|
||||
"wowmine_stickers.history.voice.unsupported_target"), false);
|
||||
return null;
|
||||
}
|
||||
VoiceMessagesApi currentApi = api;
|
||||
if (currentApi == null) {
|
||||
throw new IllegalStateException("VoiceMessages server API is not initialized");
|
||||
}
|
||||
Set<UUID> recipients = new HashSet<>();
|
||||
addCompatible(recipients, sender, currentApi);
|
||||
if ("team".equals(target)) {
|
||||
var team = sender.getTeam();
|
||||
if (team != null) {
|
||||
// VM 1.0.14 resolves scoreboard entries as UUIDs, not player names.
|
||||
for (String member : team.getPlayers()) {
|
||||
ServerPlayer online = playerList.getPlayer(UUID.fromString(member));
|
||||
if (online != null) {
|
||||
addCompatible(recipients, online, currentApi);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
addCompatible(recipients, named, currentApi);
|
||||
}
|
||||
return new ChatHistory.Audience(false, recipients);
|
||||
}
|
||||
|
||||
private static void addCompatible(Set<UUID> recipients, ServerPlayer player, VoiceMessagesApi currentApi) {
|
||||
if (currentApi.isPlayerHasCompatibleModVersion(player.getUUID())) {
|
||||
recipients.add(player.getUUID());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFileAttributeView;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import net.wowmine.stickers.ChatHistory.Attachment;
|
||||
import net.wowmine.stickers.ChatHistory.Audience;
|
||||
import net.wowmine.stickers.ChatHistory.Cursor;
|
||||
import net.wowmine.stickers.ChatHistory.Draft;
|
||||
import net.wowmine.stickers.ChatHistory.Entry;
|
||||
import net.wowmine.stickers.ChatHistory.Kind;
|
||||
import net.wowmine.stickers.ChatHistory.Page;
|
||||
import net.wowmine.stickers.ChatHistory.Query;
|
||||
|
||||
/** One serialized connection; acknowledged appends include media and ACL in a FULL-synced commit. */
|
||||
public final class ChatArchive implements AutoCloseable {
|
||||
private static final String VISIBLE = "(e.public=1 OR EXISTS "
|
||||
+ "(SELECT 1 FROM recipients r WHERE r.entry_id=e.id AND r.uuid=?))";
|
||||
private final Connection connection;
|
||||
private boolean closed;
|
||||
|
||||
/** Root must be a dedicated archive subdirectory, never the world directory itself. */
|
||||
public ChatArchive(Path root) throws IOException, SQLException {
|
||||
Files.createDirectories(root);
|
||||
var permissions = Files.getFileAttributeView(root, PosixFileAttributeView.class);
|
||||
if (permissions != null) {
|
||||
permissions.setPermissions(PosixFilePermissions.fromString("rwx------"));
|
||||
}
|
||||
connection = DriverManager.getConnection("jdbc:sqlite:" + root.resolve("chat-archive.sqlite").toAbsolutePath());
|
||||
try (Statement sql = connection.createStatement()) {
|
||||
sql.execute("PRAGMA foreign_keys=ON");
|
||||
sql.execute("PRAGMA busy_timeout=5000");
|
||||
try (ResultSet mode = sql.executeQuery("PRAGMA journal_mode=WAL")) {
|
||||
if (!mode.next() || !"wal".equalsIgnoreCase(mode.getString(1))) {
|
||||
throw new SQLException("Archive requires WAL journal mode");
|
||||
}
|
||||
}
|
||||
sql.execute("PRAGMA synchronous=FULL");
|
||||
sql.execute("""
|
||||
CREATE TABLE IF NOT EXISTS media (
|
||||
sha TEXT PRIMARY KEY, kind TEXT NOT NULL, frames INTEGER NOT NULL,
|
||||
bytes BLOB NOT NULL)
|
||||
""");
|
||||
sql.execute("""
|
||||
CREATE TABLE IF NOT EXISTS entries (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, time INTEGER NOT NULL,
|
||||
author TEXT NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL,
|
||||
body TEXT NOT NULL, attachment TEXT REFERENCES media(sha),
|
||||
frames INTEGER NOT NULL, public INTEGER NOT NULL CHECK(public IN (0,1)))
|
||||
""");
|
||||
sql.execute("CREATE INDEX IF NOT EXISTS entries_time_id ON entries(time,id)");
|
||||
sql.execute("CREATE INDEX IF NOT EXISTS entries_public_time_id ON entries(time,id) WHERE public=1");
|
||||
sql.execute("""
|
||||
CREATE TABLE IF NOT EXISTS recipients (
|
||||
entry_id INTEGER NOT NULL REFERENCES entries(id), uuid TEXT NOT NULL, time INTEGER NOT NULL,
|
||||
PRIMARY KEY(entry_id,uuid)) WITHOUT ROWID
|
||||
""");
|
||||
sql.execute("CREATE INDEX IF NOT EXISTS recipients_viewer_time_id ON recipients(uuid,time,entry_id)");
|
||||
sql.execute("CREATE TABLE IF NOT EXISTS legacy_state (id INTEGER PRIMARY KEY CHECK(id=1), complete INTEGER NOT NULL)");
|
||||
sql.execute("CREATE TABLE IF NOT EXISTS legacy_sources (sha TEXT PRIMARY KEY, path TEXT NOT NULL)");
|
||||
sql.execute("""
|
||||
CREATE TABLE IF NOT EXISTS legacy_lines (
|
||||
source TEXT NOT NULL REFERENCES legacy_sources(sha), line INTEGER NOT NULL,
|
||||
entry_id INTEGER NOT NULL REFERENCES entries(id), PRIMARY KEY(source,line)) WITHOUT ROWID
|
||||
""");
|
||||
} catch (SQLException error) {
|
||||
try {
|
||||
connection.close();
|
||||
} catch (SQLException closeError) {
|
||||
error.addSuppressed(closeError);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized long append(Draft message, Audience audience, byte[] bytes) throws SQLException, IOException {
|
||||
requireOpen();
|
||||
Objects.requireNonNull(message);
|
||||
Objects.requireNonNull(audience);
|
||||
byte[] media = Objects.requireNonNull(bytes).clone();
|
||||
validateMedia(message, media);
|
||||
return transaction(() -> insert(message, audience, media));
|
||||
}
|
||||
|
||||
private long insert(Draft message, Audience audience, byte[] bytes) throws SQLException {
|
||||
if (message.kind() != Kind.TEXT) {
|
||||
try (PreparedStatement sql = connection.prepareStatement(
|
||||
"INSERT INTO media(sha,kind,frames,bytes) VALUES(?,?,?,?) ON CONFLICT(sha) DO NOTHING")) {
|
||||
sql.setString(1, message.attachment());
|
||||
sql.setString(2, message.kind().name());
|
||||
sql.setInt(3, message.frames());
|
||||
sql.setBytes(4, bytes);
|
||||
sql.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement sql = connection.prepareStatement("SELECT kind,frames FROM media WHERE sha=?")) {
|
||||
sql.setString(1, message.attachment());
|
||||
try (ResultSet row = sql.executeQuery()) {
|
||||
if (!row.next() || !message.kind().name().equals(row.getString(1))
|
||||
|| message.frames() != row.getInt(2)) {
|
||||
throw new SQLException("Attachment hash already has different type or timing");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
try (PreparedStatement sql = connection.prepareStatement("""
|
||||
INSERT INTO entries(time,author,name,kind,body,attachment,frames,public)
|
||||
VALUES(?,?,?,?,?,?,?,?)
|
||||
""")) {
|
||||
sql.setLong(1, message.time());
|
||||
sql.setString(2, message.author().toString());
|
||||
sql.setString(3, message.name());
|
||||
sql.setString(4, message.kind().name());
|
||||
sql.setString(5, message.body());
|
||||
sql.setString(6, message.kind() == Kind.TEXT ? null : message.attachment());
|
||||
sql.setInt(7, message.frames());
|
||||
sql.setInt(8, audience.publicMessage() ? 1 : 0);
|
||||
sql.executeUpdate();
|
||||
}
|
||||
long id;
|
||||
try (Statement sql = connection.createStatement(); ResultSet row = sql.executeQuery("SELECT last_insert_rowid()")) {
|
||||
if (!row.next()) {
|
||||
throw new SQLException("Missing inserted archive ID");
|
||||
}
|
||||
id = row.getLong(1);
|
||||
}
|
||||
try (PreparedStatement sql = connection.prepareStatement("INSERT INTO recipients(entry_id,uuid,time) VALUES(?,?,?)")) {
|
||||
for (UUID recipient : audience.recipients()) {
|
||||
sql.setLong(1, id);
|
||||
sql.setString(2, recipient.toString());
|
||||
sql.setLong(3, message.time());
|
||||
sql.addBatch();
|
||||
}
|
||||
sql.executeBatch();
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
public synchronized Page page(UUID requester, Query query) throws SQLException {
|
||||
requireOpen();
|
||||
Objects.requireNonNull(requester);
|
||||
Objects.requireNonNull(query);
|
||||
boolean ascending = switch (query.direction()) {
|
||||
case EARLIEST, AFTER -> true;
|
||||
case LATEST, BEFORE, AT_DATE -> false;
|
||||
};
|
||||
String order = ascending ? " ASC" : " DESC";
|
||||
String limit = " LIMIT " + ChatHistory.PAGE_SIZE;
|
||||
// Each disjoint visibility stream seeks its own index and contributes at most 50 rows.
|
||||
// The final merge sorts at most 100 rows, even for a viewer with a sparse private history.
|
||||
String select = "SELECT * FROM (SELECT * FROM (SELECT e.* FROM entries e INDEXED BY entries_public_time_id WHERE e.public=1"
|
||||
+ boundary(query, "e.time", "e.id") + " ORDER BY e.time" + order + ",e.id" + order + limit
|
||||
+ ") UNION ALL SELECT * FROM (SELECT e.* FROM recipients r INDEXED BY recipients_viewer_time_id"
|
||||
+ " CROSS JOIN entries e ON e.id=r.entry_id"
|
||||
+ " WHERE r.uuid=?" + boundary(query, "r.time", "r.entry_id")
|
||||
+ " ORDER BY r.time" + order + ",r.entry_id" + order + limit
|
||||
+ ")) ORDER BY time" + order + ",id" + order + limit;
|
||||
List<Entry> entries = new ArrayList<>();
|
||||
int budget = 0;
|
||||
try (PreparedStatement sql = connection.prepareStatement(select)) {
|
||||
int parameter = bindBoundary(sql, 1, query);
|
||||
sql.setString(parameter++, requester.toString());
|
||||
bindBoundary(sql, parameter, query);
|
||||
try (ResultSet rows = sql.executeQuery()) {
|
||||
while (rows.next()) {
|
||||
Entry entry = readEntry(rows);
|
||||
int size = entry.message().body().getBytes(StandardCharsets.UTF_8).length
|
||||
+ ChatHistory.ENTRY_OVERHEAD;
|
||||
if (budget + size > ChatHistory.PAGE_BYTES) {
|
||||
break;
|
||||
}
|
||||
entries.add(entry);
|
||||
budget += size;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!ascending) {
|
||||
Collections.reverse(entries);
|
||||
}
|
||||
if (!entries.isEmpty()) {
|
||||
return new Page(entries, exists(requester, "<", entries.getFirst().cursor()),
|
||||
exists(requester, ">", entries.getLast().cursor()));
|
||||
}
|
||||
return switch (query.direction()) {
|
||||
case LATEST, EARLIEST -> new Page(entries, false, false);
|
||||
case BEFORE -> new Page(entries, false, exists(requester, ">=", new Cursor(query.time(), query.id())));
|
||||
case AFTER -> new Page(entries, exists(requester, "<=", new Cursor(query.time(), query.id())), false);
|
||||
case AT_DATE -> new Page(entries, false, exists(requester, ">", new Cursor(query.time(), Long.MAX_VALUE)));
|
||||
};
|
||||
}
|
||||
|
||||
private static String boundary(Query query, String time, String id) {
|
||||
return switch (query.direction()) {
|
||||
case LATEST, EARLIEST -> "";
|
||||
case BEFORE -> " AND (" + time + "," + id + ")<(?,?)";
|
||||
case AFTER -> " AND (" + time + "," + id + ")>(?,?)";
|
||||
case AT_DATE -> " AND " + time + "<=?";
|
||||
};
|
||||
}
|
||||
|
||||
private static int bindBoundary(PreparedStatement sql, int parameter, Query query) throws SQLException {
|
||||
switch (query.direction()) {
|
||||
case BEFORE, AFTER -> {
|
||||
sql.setLong(parameter++, query.time());
|
||||
sql.setLong(parameter++, query.id());
|
||||
}
|
||||
case AT_DATE -> sql.setLong(parameter++, query.time());
|
||||
case LATEST, EARLIEST -> { }
|
||||
}
|
||||
return parameter;
|
||||
}
|
||||
|
||||
private boolean exists(UUID requester, String comparison, Cursor cursor) throws SQLException {
|
||||
try (PreparedStatement sql = connection.prepareStatement(
|
||||
"SELECT 1 FROM entries INDEXED BY entries_public_time_id WHERE public=1 AND (time,id)"
|
||||
+ comparison + "(?,?) LIMIT 1")) {
|
||||
sql.setLong(1, cursor.time());
|
||||
sql.setLong(2, cursor.id());
|
||||
try (ResultSet row = sql.executeQuery()) {
|
||||
if (row.next()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
try (PreparedStatement sql = connection.prepareStatement(
|
||||
"SELECT 1 FROM recipients INDEXED BY recipients_viewer_time_id WHERE uuid=? AND (time,entry_id)"
|
||||
+ comparison + "(?,?) LIMIT 1")) {
|
||||
sql.setString(1, requester.toString());
|
||||
sql.setLong(2, cursor.time());
|
||||
sql.setLong(3, cursor.id());
|
||||
try (ResultSet row = sql.executeQuery()) {
|
||||
return row.next();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized Optional<Attachment> attachment(UUID requester, long entryId) throws SQLException {
|
||||
requireOpen();
|
||||
Objects.requireNonNull(requester);
|
||||
if (entryId < 1) {
|
||||
throw new IllegalArgumentException("Invalid archive entry ID");
|
||||
}
|
||||
try (PreparedStatement sql = connection.prepareStatement("""
|
||||
SELECT m.* FROM entries e JOIN media m ON m.sha=e.attachment WHERE
|
||||
""" + VISIBLE + " AND e.id=?")) {
|
||||
sql.setString(1, requester.toString());
|
||||
sql.setLong(2, entryId);
|
||||
try (ResultSet row = sql.executeQuery()) {
|
||||
return row.next() ? Optional.of(new Attachment(row.getString("sha"),
|
||||
Kind.valueOf(row.getString("kind")), row.getInt("frames"), row.getBytes("bytes"))) : Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Entry readEntry(ResultSet row) throws SQLException {
|
||||
String attachment = row.getString("attachment");
|
||||
return new Entry(row.getLong("id"), new Draft(row.getLong("time"),
|
||||
UUID.fromString(row.getString("author")), row.getString("name"),
|
||||
Kind.valueOf(row.getString("kind")), row.getString("body"),
|
||||
attachment == null ? "" : attachment, row.getInt("frames")));
|
||||
}
|
||||
|
||||
private static void validateMedia(Draft message, byte[] bytes) throws IOException {
|
||||
switch (message.kind()) {
|
||||
case TEXT -> {
|
||||
if (bytes.length != 0) {
|
||||
throw new IllegalArgumentException("Text has no media");
|
||||
}
|
||||
}
|
||||
case STICKER, VOICE -> {
|
||||
new Attachment(message.attachment(), message.kind(), message.frames(), bytes);
|
||||
if (!sha256(bytes).equals(message.attachment())) {
|
||||
throw new IllegalArgumentException("Archive media SHA-256 mismatch");
|
||||
}
|
||||
switch (message.kind()) {
|
||||
case STICKER -> {
|
||||
var sticker = new StickerCatalog.Sticker(message.attachment(), "", message.frames());
|
||||
if (bytes.length < 33) {
|
||||
throw new IOException("Truncated sticker PNG");
|
||||
}
|
||||
ByteBuffer header = ByteBuffer.wrap(bytes);
|
||||
if (header.getLong() != 0x89504e470d0a1a0aL || header.getInt() != 13
|
||||
|| header.getInt() != 0x49484452 || header.getInt() != sticker.width()
|
||||
|| header.getInt() != sticker.height()) {
|
||||
throw new IOException("Archived PNG dimensions disagree with frame count");
|
||||
}
|
||||
try (var input = new ByteArrayInputStream(bytes)) {
|
||||
if (ImageIO.read(input) == null) {
|
||||
throw new IOException("Invalid sticker PNG");
|
||||
}
|
||||
}
|
||||
}
|
||||
case VOICE -> {
|
||||
try {
|
||||
if (VoiceFrames.decode(bytes).size() != message.frames()) {
|
||||
throw new IOException("Archived voice frame count mismatch");
|
||||
}
|
||||
} catch (IllegalArgumentException invalid) {
|
||||
throw new IOException("Invalid archived voice container", invalid);
|
||||
}
|
||||
}
|
||||
case TEXT -> throw new IllegalStateException("Text is not media");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String sha256(byte[] bytes) {
|
||||
return HexFormat.of().formatHex(digest().digest(bytes));
|
||||
}
|
||||
|
||||
static MessageDigest digest() {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException error) {
|
||||
throw new IllegalStateException("Java runtime is missing SHA-256", error);
|
||||
}
|
||||
}
|
||||
|
||||
record LegacySource(String sha, String path) {}
|
||||
|
||||
synchronized boolean legacyComplete() throws SQLException {
|
||||
requireOpen();
|
||||
try (Statement sql = connection.createStatement();
|
||||
ResultSet row = sql.executeQuery("SELECT complete FROM legacy_state WHERE id=1")) {
|
||||
return row.next() && row.getInt(1) == 1;
|
||||
}
|
||||
}
|
||||
|
||||
synchronized Optional<List<LegacySource>> legacyManifest() throws SQLException {
|
||||
requireOpen();
|
||||
try (Statement sql = connection.createStatement();
|
||||
ResultSet row = sql.executeQuery("SELECT 1 FROM legacy_state WHERE id=1")) {
|
||||
if (!row.next()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
List<LegacySource> sources = new ArrayList<>();
|
||||
try (Statement sql = connection.createStatement();
|
||||
ResultSet rows = sql.executeQuery("SELECT sha,path FROM legacy_sources ORDER BY path")) {
|
||||
while (rows.next()) {
|
||||
sources.add(new LegacySource(rows.getString(1), rows.getString(2)));
|
||||
}
|
||||
}
|
||||
return Optional.of(List.copyOf(sources));
|
||||
}
|
||||
|
||||
synchronized void beginLegacyImport(List<LegacySource> sources) throws SQLException {
|
||||
requireOpen();
|
||||
transaction(() -> {
|
||||
try (Statement sql = connection.createStatement()) {
|
||||
sql.executeUpdate("INSERT INTO legacy_state(id,complete) VALUES(1,0)");
|
||||
}
|
||||
try (PreparedStatement sql = connection.prepareStatement(
|
||||
"INSERT INTO legacy_sources(sha,path) VALUES(?,?) ON CONFLICT(sha) DO NOTHING")) {
|
||||
for (LegacySource source : sources) {
|
||||
sql.setString(1, source.sha());
|
||||
sql.setString(2, source.path());
|
||||
sql.addBatch();
|
||||
}
|
||||
sql.executeBatch();
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
synchronized boolean importLegacyLine(String source, long line, Draft message) throws SQLException {
|
||||
requireOpen();
|
||||
if (message.kind() != Kind.TEXT) {
|
||||
throw new IllegalArgumentException("Legacy logs contain text only");
|
||||
}
|
||||
return transaction(() -> {
|
||||
try (PreparedStatement sql = connection.prepareStatement(
|
||||
"SELECT 1 FROM legacy_lines WHERE source=? AND line=?")) {
|
||||
sql.setString(1, source);
|
||||
sql.setLong(2, line);
|
||||
try (ResultSet row = sql.executeQuery()) {
|
||||
if (row.next()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
long id = insert(message, ChatHistory.PUBLIC, new byte[0]);
|
||||
try (PreparedStatement sql = connection.prepareStatement(
|
||||
"INSERT INTO legacy_lines(source,line,entry_id) VALUES(?,?,?)")) {
|
||||
sql.setString(1, source);
|
||||
sql.setLong(2, line);
|
||||
sql.setLong(3, id);
|
||||
sql.executeUpdate();
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
synchronized void completeLegacyImport() throws SQLException {
|
||||
requireOpen();
|
||||
transaction(() -> {
|
||||
try (Statement sql = connection.createStatement()) {
|
||||
if (sql.executeUpdate("UPDATE legacy_state SET complete=1 WHERE id=1 AND complete=0") != 1) {
|
||||
throw new SQLException("No pending legacy import");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private <T> T transaction(SqlWork<T> action) throws SQLException {
|
||||
connection.setAutoCommit(false);
|
||||
try {
|
||||
T result = action.run();
|
||||
connection.commit();
|
||||
return result;
|
||||
} catch (SQLException | RuntimeException | Error error) {
|
||||
try {
|
||||
connection.rollback();
|
||||
} catch (SQLException rollbackError) {
|
||||
error.addSuppressed(rollbackError);
|
||||
closed = true;
|
||||
try {
|
||||
connection.close();
|
||||
} catch (SQLException closeError) {
|
||||
error.addSuppressed(closeError);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (!closed) {
|
||||
connection.setAutoCommit(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface SqlWork<T> {
|
||||
T run() throws SQLException;
|
||||
}
|
||||
|
||||
private void requireOpen() throws SQLException {
|
||||
if (closed) {
|
||||
throw new SQLException("Chat archive is closed");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void close() throws SQLException {
|
||||
if (!closed) {
|
||||
connection.close();
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Archive records and bounded windows; the durable archive itself has no age limit. */
|
||||
public final class ChatHistory {
|
||||
public static final int PAGE_SIZE = 50;
|
||||
public static final int PAGE_BYTES = 262_144;
|
||||
public static final int ENTRY_OVERHEAD = 512;
|
||||
public static final int BODY_CHARACTERS = 32_768;
|
||||
public static final int BODY_BYTES = 65_536;
|
||||
public static final int MEDIA_BYTES = 8_388_608;
|
||||
public static final int VOICE_FRAMES = 15_000;
|
||||
public static final int VOICE_FRAME_BYTES = 256;
|
||||
public static final Audience PUBLIC = new Audience(true, Set.of());
|
||||
|
||||
private ChatHistory() {}
|
||||
|
||||
public enum Kind {
|
||||
TEXT, STICKER, VOICE
|
||||
}
|
||||
|
||||
public enum Direction {
|
||||
LATEST, EARLIEST, BEFORE, AFTER, AT_DATE
|
||||
}
|
||||
|
||||
public enum Failure {
|
||||
BUSY, NOT_FOUND, UNAVAILABLE, INVALID_REQUEST, VOICE_UNAVAILABLE
|
||||
}
|
||||
|
||||
public record Cursor(long time, long id) {
|
||||
public Cursor {
|
||||
if (time < 0 || id < 1) {
|
||||
throw new IllegalArgumentException("Invalid history cursor");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record Query(Direction direction, long time, long id) {
|
||||
public Query {
|
||||
Objects.requireNonNull(direction);
|
||||
boolean valid = switch (direction) {
|
||||
case LATEST, EARLIEST -> time == 0 && id == 0;
|
||||
case BEFORE, AFTER -> time >= 0 && id > 0;
|
||||
case AT_DATE -> time >= 0 && id == 0;
|
||||
};
|
||||
if (!valid) {
|
||||
throw new IllegalArgumentException("Invalid history query");
|
||||
}
|
||||
}
|
||||
|
||||
public static Query latest() {
|
||||
return new Query(Direction.LATEST, 0, 0);
|
||||
}
|
||||
|
||||
public static Query earliest() {
|
||||
return new Query(Direction.EARLIEST, 0, 0);
|
||||
}
|
||||
|
||||
public static Query before(Cursor cursor) {
|
||||
return new Query(Direction.BEFORE, cursor.time(), cursor.id());
|
||||
}
|
||||
|
||||
public static Query after(Cursor cursor) {
|
||||
return new Query(Direction.AFTER, cursor.time(), cursor.id());
|
||||
}
|
||||
}
|
||||
|
||||
/** Public messages include offline readers; restricted voices retain their original audience. */
|
||||
public record Audience(boolean publicMessage, Set<UUID> recipients) {
|
||||
public Audience {
|
||||
recipients = Set.copyOf(recipients);
|
||||
if (publicMessage ? !recipients.isEmpty() : recipients.isEmpty()) {
|
||||
throw new IllegalArgumentException("Invalid history audience");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Body is a serialized Minecraft component, not a server log line. */
|
||||
public record Draft(long time, UUID author, String name, Kind kind, String body,
|
||||
String attachment, int frames) {
|
||||
public Draft {
|
||||
Objects.requireNonNull(author);
|
||||
Objects.requireNonNull(kind);
|
||||
Objects.requireNonNull(body);
|
||||
Objects.requireNonNull(attachment);
|
||||
if (time < 0 || name.isBlank() || name.length() > 64
|
||||
|| body.length() > BODY_CHARACTERS
|
||||
|| body.getBytes(StandardCharsets.UTF_8).length > BODY_BYTES) {
|
||||
throw new IllegalArgumentException("Invalid history message");
|
||||
}
|
||||
switch (kind) {
|
||||
case TEXT -> {
|
||||
if (!attachment.isEmpty() || frames != 0) {
|
||||
throw new IllegalArgumentException("Text has no attachment");
|
||||
}
|
||||
}
|
||||
case STICKER -> {
|
||||
StickerCatalog.requireAssetId(attachment);
|
||||
if (frames < 1 || frames > 60) {
|
||||
throw new IllegalArgumentException("Invalid archived sticker timing");
|
||||
}
|
||||
}
|
||||
case VOICE -> {
|
||||
StickerCatalog.requireAssetId(attachment);
|
||||
if (frames < 1 || frames > VOICE_FRAMES) {
|
||||
throw new IllegalArgumentException("Invalid archived voice duration");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int durationMs() {
|
||||
return kind == Kind.VOICE ? frames * 20 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
public record Entry(long id, Draft message) {
|
||||
public Entry {
|
||||
Objects.requireNonNull(message);
|
||||
if (id < 1) {
|
||||
throw new IllegalArgumentException("Invalid history record ID");
|
||||
}
|
||||
}
|
||||
|
||||
public Cursor cursor() {
|
||||
return new Cursor(message.time(), id);
|
||||
}
|
||||
}
|
||||
|
||||
/** Entries are chronological; paging replaces a window rather than retaining every page. */
|
||||
public record Page(List<Entry> entries, boolean hasOlder, boolean hasNewer) {
|
||||
public Page {
|
||||
entries = List.copyOf(entries);
|
||||
if (entries.size() > PAGE_SIZE || entries.stream()
|
||||
.mapToInt(entry -> entry.message().body().getBytes(StandardCharsets.UTF_8).length + ENTRY_OVERHEAD)
|
||||
.sum() > PAGE_BYTES) {
|
||||
throw new IllegalArgumentException("History page exceeds its budget");
|
||||
}
|
||||
for (int index = 1; index < entries.size(); index++) {
|
||||
Cursor previous = entries.get(index - 1).cursor();
|
||||
Cursor current = entries.get(index).cursor();
|
||||
if (current.time() < previous.time()
|
||||
|| (current.time() == previous.time() && current.id() <= previous.id())) {
|
||||
throw new IllegalArgumentException("History page is not chronological");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record Attachment(String id, Kind kind, int frames, byte[] bytes) {
|
||||
public Attachment {
|
||||
StickerCatalog.requireAssetId(id);
|
||||
Objects.requireNonNull(kind);
|
||||
if (kind == Kind.TEXT || bytes.length == 0 || bytes.length > MEDIA_BYTES
|
||||
|| (kind == Kind.STICKER && bytes.length > StickerCatalog.MAX_ASSET_BYTES)) {
|
||||
throw new IllegalArgumentException("Invalid history attachment");
|
||||
}
|
||||
if (frames < 1 || frames > (kind == Kind.STICKER ? 60 : VOICE_FRAMES)) {
|
||||
throw new IllegalArgumentException("Invalid history attachment timing");
|
||||
}
|
||||
bytes = bytes.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] bytes() {
|
||||
return bytes.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Objects;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
/** Metadata windows and authorized, bounded attachments are requested separately. */
|
||||
public final class HistoryPackets {
|
||||
public static final int CHUNK_BYTES = 24_576;
|
||||
|
||||
private HistoryPackets() {}
|
||||
|
||||
private static <T extends CustomPacketPayload> CustomPacketPayload.Type<T> type(String name) {
|
||||
return new CustomPacketPayload.Type<>(
|
||||
ResourceLocation.fromNamespaceAndPath("wowmine_stickers", name));
|
||||
}
|
||||
|
||||
private static void requireRequest(long request) {
|
||||
if (request < 1) {
|
||||
throw new IllegalArgumentException("Invalid history request ID");
|
||||
}
|
||||
}
|
||||
|
||||
public record PageRequest(long request, ChatHistory.Query query) implements CustomPacketPayload {
|
||||
public static final Type<PageRequest> TYPE = HistoryPackets.type("history_page_request");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, PageRequest> CODEC =
|
||||
StreamCodec.of((buffer, value) -> {
|
||||
buffer.writeLong(value.request);
|
||||
buffer.writeEnum(value.query.direction());
|
||||
buffer.writeLong(value.query.time());
|
||||
buffer.writeLong(value.query.id());
|
||||
}, buffer -> new PageRequest(buffer.readLong(), new ChatHistory.Query(
|
||||
buffer.readEnum(ChatHistory.Direction.class), buffer.readLong(), buffer.readLong())));
|
||||
|
||||
public PageRequest {
|
||||
requireRequest(request);
|
||||
Objects.requireNonNull(query);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<PageRequest> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
public record PageReply(long request, ChatHistory.Page page) implements CustomPacketPayload {
|
||||
public static final Type<PageReply> TYPE = HistoryPackets.type("history_page");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, PageReply> CODEC =
|
||||
StreamCodec.of((buffer, value) -> {
|
||||
buffer.writeLong(value.request);
|
||||
buffer.writeVarInt(value.page.entries().size());
|
||||
for (ChatHistory.Entry entry : value.page.entries()) {
|
||||
ChatHistory.Draft message = entry.message();
|
||||
buffer.writeLong(entry.id());
|
||||
buffer.writeLong(message.time());
|
||||
buffer.writeUUID(message.author());
|
||||
buffer.writeUtf(message.name(), 64);
|
||||
buffer.writeEnum(message.kind());
|
||||
buffer.writeUtf(message.body(), ChatHistory.BODY_CHARACTERS);
|
||||
buffer.writeUtf(message.attachment(), 64);
|
||||
buffer.writeVarInt(message.frames());
|
||||
}
|
||||
buffer.writeBoolean(value.page.hasOlder());
|
||||
buffer.writeBoolean(value.page.hasNewer());
|
||||
}, HistoryPackets::readPage);
|
||||
|
||||
public PageReply {
|
||||
requireRequest(request);
|
||||
Objects.requireNonNull(page);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<PageReply> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
private static PageReply readPage(RegistryFriendlyByteBuf buffer) {
|
||||
long request = buffer.readLong();
|
||||
int count = buffer.readVarInt();
|
||||
if (count < 0 || count > ChatHistory.PAGE_SIZE) {
|
||||
throw new IllegalArgumentException("Invalid history page count");
|
||||
}
|
||||
var entries = new ArrayList<ChatHistory.Entry>(count);
|
||||
int bytes = 0;
|
||||
for (int index = 0; index < count; index++) {
|
||||
long id = buffer.readLong();
|
||||
var draft = new ChatHistory.Draft(buffer.readLong(), buffer.readUUID(),
|
||||
buffer.readUtf(64), buffer.readEnum(ChatHistory.Kind.class),
|
||||
buffer.readUtf(ChatHistory.BODY_CHARACTERS), buffer.readUtf(64), buffer.readVarInt());
|
||||
bytes += draft.body().getBytes(java.nio.charset.StandardCharsets.UTF_8).length
|
||||
+ ChatHistory.ENTRY_OVERHEAD;
|
||||
if (bytes > ChatHistory.PAGE_BYTES) {
|
||||
throw new IllegalArgumentException("History page exceeds byte budget");
|
||||
}
|
||||
entries.add(new ChatHistory.Entry(id, draft));
|
||||
}
|
||||
return new PageReply(request,
|
||||
new ChatHistory.Page(entries, buffer.readBoolean(), buffer.readBoolean()));
|
||||
}
|
||||
|
||||
public record AttachmentRequest(long request, long entry) implements CustomPacketPayload {
|
||||
public static final Type<AttachmentRequest> TYPE = HistoryPackets.type("history_attachment_request");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, AttachmentRequest> CODEC =
|
||||
StreamCodec.of((buffer, value) -> {
|
||||
buffer.writeLong(value.request);
|
||||
buffer.writeLong(value.entry);
|
||||
}, buffer -> new AttachmentRequest(buffer.readLong(), buffer.readLong()));
|
||||
|
||||
public AttachmentRequest {
|
||||
requireRequest(request);
|
||||
if (entry < 1) {
|
||||
throw new IllegalArgumentException("Invalid history attachment entry");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<AttachmentRequest> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
public record AttachmentChunk(long request, String id, int part, int totalBytes, byte[] bytes)
|
||||
implements CustomPacketPayload {
|
||||
public static final Type<AttachmentChunk> TYPE = HistoryPackets.type("history_attachment");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, AttachmentChunk> CODEC =
|
||||
StreamCodec.of((buffer, value) -> {
|
||||
buffer.writeLong(value.request);
|
||||
buffer.writeUtf(value.id, 64);
|
||||
buffer.writeVarInt(value.part);
|
||||
buffer.writeVarInt(value.totalBytes);
|
||||
buffer.writeByteArray(value.bytes);
|
||||
}, buffer -> new AttachmentChunk(buffer.readLong(), buffer.readUtf(64), buffer.readVarInt(),
|
||||
buffer.readVarInt(), buffer.readByteArray(CHUNK_BYTES)));
|
||||
|
||||
public AttachmentChunk {
|
||||
requireRequest(request);
|
||||
StickerCatalog.requireAssetId(id);
|
||||
if (totalBytes < 1 || totalBytes > ChatHistory.MEDIA_BYTES || part < 0
|
||||
|| part >= (totalBytes + CHUNK_BYTES - 1) / CHUNK_BYTES
|
||||
|| bytes.length != Math.min(CHUNK_BYTES, totalBytes - part * CHUNK_BYTES)) {
|
||||
throw new IllegalArgumentException("Invalid history attachment chunk");
|
||||
}
|
||||
bytes = bytes.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] bytes() {
|
||||
return bytes.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<AttachmentChunk> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
public record Problem(long request, ChatHistory.Failure failure) implements CustomPacketPayload {
|
||||
public static final Type<Problem> TYPE = HistoryPackets.type("history_problem");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, Problem> CODEC =
|
||||
StreamCodec.of((buffer, value) -> {
|
||||
buffer.writeLong(value.request);
|
||||
buffer.writeEnum(value.failure);
|
||||
}, buffer -> new Problem(buffer.readLong(), buffer.readEnum(ChatHistory.Failure.class)));
|
||||
|
||||
public Problem {
|
||||
requireRequest(request);
|
||||
Objects.requireNonNull(failure);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<Problem> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import com.mojang.logging.LogUtils;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.neoforged.neoforge.network.PacketDistributor;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
/** Disk reads run off-thread; outgoing traffic has a global eight-chunk tick budget. */
|
||||
public final class ServerAssets implements AutoCloseable {
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
private final MinecraftServer server;
|
||||
private final ExecutorService reader = Executors.newSingleThreadExecutor(
|
||||
Thread.ofPlatform().daemon().name("wowmine-sticker-assets").factory());
|
||||
private final Set<UUID> pending = new HashSet<>();
|
||||
private final ArrayDeque<Transfer> transfers = new ArrayDeque<>();
|
||||
private boolean closed;
|
||||
|
||||
public ServerAssets(MinecraftServer server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
public void request(ServerPlayer player, ServerCatalog catalog, String id) {
|
||||
if (pending.contains(player.getUUID()) || pending.size() >= 8) {
|
||||
problem(player, id, "wowmine_stickers.error.asset_busy");
|
||||
return;
|
||||
}
|
||||
if (catalog.catalog().find(id).isEmpty()) {
|
||||
problem(player, id, "wowmine_stickers.error.asset_missing");
|
||||
return;
|
||||
}
|
||||
pending.add(player.getUUID());
|
||||
reader.execute(() -> {
|
||||
try {
|
||||
byte[] bytes = catalog.asset(id);
|
||||
server.execute(() -> {
|
||||
if (connected(player)) {
|
||||
transfers.addLast(new Transfer(player, id, bytes));
|
||||
} else {
|
||||
pending.remove(player.getUUID());
|
||||
}
|
||||
});
|
||||
} catch (IOException error) {
|
||||
LOGGER.warn("Sticker asset read failed: id={}", id, error);
|
||||
server.execute(() -> {
|
||||
pending.remove(player.getUUID());
|
||||
if (connected(player)) {
|
||||
problem(player, id, "wowmine_stickers.error.asset_read");
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void tick() {
|
||||
for (int budget = 0; budget < 8 && !transfers.isEmpty(); budget++) {
|
||||
Transfer transfer = transfers.removeFirst();
|
||||
if (!connected(transfer.player)) {
|
||||
pending.remove(transfer.player.getUUID());
|
||||
continue;
|
||||
}
|
||||
int end = Math.min(transfer.bytes.length, transfer.offset + StickerPackets.CHUNK_BYTES);
|
||||
int total = (transfer.bytes.length + StickerPackets.CHUNK_BYTES - 1)
|
||||
/ StickerPackets.CHUNK_BYTES;
|
||||
PacketDistributor.sendToPlayer(transfer.player, new StickerPackets.AssetChunk(
|
||||
transfer.id, transfer.offset / StickerPackets.CHUNK_BYTES, total,
|
||||
Arrays.copyOfRange(transfer.bytes, transfer.offset, end)));
|
||||
transfer.offset = end;
|
||||
if (end < transfer.bytes.length) {
|
||||
transfers.addLast(transfer);
|
||||
} else {
|
||||
pending.remove(transfer.player.getUUID());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean connected(ServerPlayer player) {
|
||||
return !closed && server.getPlayerList().getPlayer(player.getUUID()) == player;
|
||||
}
|
||||
|
||||
private static void problem(ServerPlayer player, String id, String reason) {
|
||||
PacketDistributor.sendToPlayer(player, new StickerPackets.AssetProblem(id, reason));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closed = true;
|
||||
reader.shutdownNow();
|
||||
transfers.clear();
|
||||
pending.clear();
|
||||
}
|
||||
|
||||
private static final class Transfer {
|
||||
private final ServerPlayer player;
|
||||
private final String id;
|
||||
private final byte[] bytes;
|
||||
private int offset;
|
||||
|
||||
private Transfer(ServerPlayer player, String id, byte[] bytes) {
|
||||
this.player = player;
|
||||
this.id = id;
|
||||
this.bytes = bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
|
||||
/** Atomic importer output is the only source of server-approved assets. */
|
||||
public record ServerCatalog(Path root, StickerCatalog catalog, String json) {
|
||||
public static ServerCatalog load(Path root) throws IOException {
|
||||
Path file = root.resolve("catalog.json");
|
||||
if (Files.notExists(file)) {
|
||||
StickerCatalog empty = new StickerCatalog(1, List.of());
|
||||
return new ServerCatalog(root, empty, new Gson().toJson(empty));
|
||||
}
|
||||
if (Files.size(file) > StickerCatalog.MAX_CATALOG_BYTES) {
|
||||
throw new IOException("Sticker catalog exceeds 512 KiB");
|
||||
}
|
||||
String json = Files.readString(file, StandardCharsets.UTF_8);
|
||||
StickerCatalog catalog = new Gson().fromJson(json, StickerCatalog.class);
|
||||
if (catalog == null) {
|
||||
throw new IOException("Sticker catalog must be an object");
|
||||
}
|
||||
return new ServerCatalog(root, catalog, json);
|
||||
}
|
||||
|
||||
public byte[] asset(String id) throws IOException {
|
||||
StickerCatalog.Sticker sticker = catalog.find(id)
|
||||
.orElseThrow(() -> new IOException("Sticker is absent from the catalog"));
|
||||
Path path = root.resolve("assets").resolve(sticker.id() + ".png");
|
||||
long size = Files.size(path);
|
||||
if (size < 33 || size > StickerCatalog.MAX_ASSET_BYTES) {
|
||||
throw new IOException("Sticker PNG has an invalid size");
|
||||
}
|
||||
byte[] bytes = Files.readAllBytes(path);
|
||||
if (bytes.length != size) {
|
||||
throw new IOException("Sticker PNG changed during reading");
|
||||
}
|
||||
try {
|
||||
String hash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
if (!sticker.id().equals(hash)) {
|
||||
throw new IOException("Sticker PNG content hash mismatch");
|
||||
}
|
||||
} catch (NoSuchAlgorithmException error) {
|
||||
throw new IllegalStateException("Java runtime is missing SHA-256", error);
|
||||
}
|
||||
ByteBuffer header = ByteBuffer.wrap(bytes);
|
||||
if (header.getLong() != 0x89504e470d0a1a0aL || header.getInt() != 13
|
||||
|| header.getInt() != 0x49484452 || header.getInt() != sticker.width()
|
||||
|| header.getInt() != sticker.height()) {
|
||||
throw new IOException("Sticker PNG dimensions do not match the catalog");
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.mojang.logging.LogUtils;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.neoforged.neoforge.network.PacketDistributor;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
/** Public imports are serialized and deduplicated; bot credentials remain server-side. */
|
||||
public final class ServerImports implements AutoCloseable {
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
private final MinecraftServer server;
|
||||
private final Supplier<ServerCatalog> catalog;
|
||||
private final Consumer<ServerCatalog> publish;
|
||||
private final ExecutorService worker = Executors.newSingleThreadExecutor(
|
||||
Thread.ofPlatform().daemon().name("wowmine-sticker-import").factory());
|
||||
private final Map<String, Job> pending = new HashMap<>();
|
||||
private final Map<UUID, Long> cooldown = new HashMap<>();
|
||||
private final Map<UUID, Long> requestAfter = new HashMap<>();
|
||||
private final ArrayDeque<Job> queue = new ArrayDeque<>();
|
||||
private Job active;
|
||||
private volatile Process process;
|
||||
private boolean closed;
|
||||
|
||||
public ServerImports(MinecraftServer server, Supplier<ServerCatalog> catalog,
|
||||
Consumer<ServerCatalog> publish) {
|
||||
this.server = server;
|
||||
this.catalog = catalog;
|
||||
this.publish = publish;
|
||||
}
|
||||
|
||||
public void request(ServerPlayer player, String input) {
|
||||
long now = Integer.toUnsignedLong(server.getTickCount());
|
||||
if (now < requestAfter.getOrDefault(player.getUUID(), 0L)) {
|
||||
status(player, "", "error", "wowmine_stickers.import.rate_limited");
|
||||
return;
|
||||
}
|
||||
requestAfter.put(player.getUUID(), now + 20);
|
||||
TelegramPack pack;
|
||||
try {
|
||||
pack = TelegramPack.fromInput(input);
|
||||
} catch (IllegalArgumentException error) {
|
||||
status(player, "", "error", "wowmine_stickers.import.invalid_link");
|
||||
return;
|
||||
}
|
||||
boolean exists = catalog.get().catalog().packs().stream()
|
||||
.anyMatch(existing -> existing.id().equalsIgnoreCase(pack.name()));
|
||||
if (exists) {
|
||||
PacketDistributor.sendToPlayer(player, new StickerPackets.CatalogReply(catalog.get().json()));
|
||||
status(player, pack.name(), "ready", "wowmine_stickers.import.already_available");
|
||||
return;
|
||||
}
|
||||
String key = pack.name().toLowerCase(Locale.ROOT);
|
||||
Job existing = pending.get(key);
|
||||
if (existing != null) {
|
||||
existing.players.add(player.getUUID());
|
||||
status(player, pack.name(), existing == active ? "importing" : "queued", "");
|
||||
return;
|
||||
}
|
||||
if (now < cooldown.getOrDefault(player.getUUID(), 0L)) {
|
||||
status(player, pack.name(), "error", "wowmine_stickers.import.cooldown");
|
||||
return;
|
||||
}
|
||||
if (pending.size() >= 8) {
|
||||
status(player, pack.name(), "error", "wowmine_stickers.import.queue_full");
|
||||
return;
|
||||
}
|
||||
String executable = System.getenv("WOWMINE_STICKERS_IMPORTER");
|
||||
String tokenFile = System.getenv("WOWMINE_STICKERS_TOKEN_FILE");
|
||||
if (executable == null || tokenFile == null || !Files.isReadable(Path.of(tokenFile))) {
|
||||
status(player, pack.name(), "error", "wowmine_stickers.import.not_configured");
|
||||
return;
|
||||
}
|
||||
Job job = new Job(pack, executable, tokenFile);
|
||||
job.players.add(player.getUUID());
|
||||
cooldown.put(player.getUUID(), now + 600);
|
||||
pending.put(key, job);
|
||||
queue.addLast(job);
|
||||
status(player, pack.name(), "queued", "");
|
||||
startNext();
|
||||
}
|
||||
|
||||
private void startNext() {
|
||||
if (closed || active != null || queue.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Job job = queue.removeFirst();
|
||||
active = job;
|
||||
notifyPlayers(job, "importing", "");
|
||||
Path root = catalog.get().root();
|
||||
worker.execute(() -> runImport(job, root));
|
||||
}
|
||||
|
||||
private void runImport(Job job, Path root) {
|
||||
try {
|
||||
Path logDirectory = root.resolve(".imports");
|
||||
Files.createDirectories(logDirectory,
|
||||
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")));
|
||||
Path log = Files.createTempFile(logDirectory, "import-" + System.currentTimeMillis() + "-", ".log",
|
||||
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
|
||||
try (var files = Files.list(logDirectory)) {
|
||||
var previous = files.filter(path -> !path.equals(log))
|
||||
.filter(path -> path.getFileName().toString().startsWith("import-")
|
||||
&& path.getFileName().toString().endsWith(".log"))
|
||||
.sorted().toList();
|
||||
for (int index = 0; index < previous.size() - 31; index++) {
|
||||
Files.delete(previous.get(index));
|
||||
}
|
||||
}
|
||||
Process started = new ProcessBuilder(job.executable, "--pack", job.pack.name(),
|
||||
"--token-file", job.tokenFile, "--output", root.toString())
|
||||
.redirectErrorStream(true).redirectOutput(log.toFile()).start();
|
||||
process = started;
|
||||
if (!started.waitFor(300, TimeUnit.SECONDS)) {
|
||||
terminate(started);
|
||||
LOGGER.warn("Sticker import timed out: pack={}", job.pack.name());
|
||||
finish(job, null, "wowmine_stickers.import.timeout");
|
||||
return;
|
||||
}
|
||||
if (started.exitValue() != 0) {
|
||||
LOGGER.warn("Sticker import failed: pack={} exit={} log={}",
|
||||
job.pack.name(), started.exitValue(), log);
|
||||
finish(job, null, "wowmine_stickers.import.failed");
|
||||
return;
|
||||
}
|
||||
ServerCatalog loaded = ServerCatalog.load(root);
|
||||
if (loaded.catalog().packs().stream()
|
||||
.noneMatch(pack -> pack.id().equalsIgnoreCase(job.pack.name()))) {
|
||||
throw new IOException("Importer succeeded without publishing the requested pack");
|
||||
}
|
||||
LOGGER.info("Sticker pack imported: pack={}", job.pack.name());
|
||||
Files.delete(log);
|
||||
finish(job, loaded, "");
|
||||
} catch (IOException | JsonParseException | IllegalArgumentException error) {
|
||||
LOGGER.warn("Sticker import could not complete: pack={}", job.pack.name(), error);
|
||||
finish(job, null, "wowmine_stickers.import.failed");
|
||||
} catch (InterruptedException error) {
|
||||
Process running = process;
|
||||
if (running != null) {
|
||||
terminate(running);
|
||||
}
|
||||
Thread.currentThread().interrupt();
|
||||
} finally {
|
||||
process = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void finish(Job job, ServerCatalog loaded, String error) {
|
||||
server.execute(() -> {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
if (loaded != null) {
|
||||
publish.accept(loaded);
|
||||
notifyPlayers(job, "ready", "wowmine_stickers.import.ready");
|
||||
} else {
|
||||
notifyPlayers(job, "error", error);
|
||||
}
|
||||
pending.remove(job.pack.name().toLowerCase(Locale.ROOT));
|
||||
active = null;
|
||||
startNext();
|
||||
});
|
||||
}
|
||||
|
||||
private void notifyPlayers(Job job, String state, String detail) {
|
||||
for (UUID id : job.players) {
|
||||
ServerPlayer player = server.getPlayerList().getPlayer(id);
|
||||
if (player != null && player.connection.hasChannel(StickerPackets.ImportStatus.TYPE)) {
|
||||
status(player, job.pack.name(), state, detail);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void forget(UUID player) {
|
||||
cooldown.remove(player);
|
||||
requestAfter.remove(player);
|
||||
for (Job job : pending.values()) {
|
||||
job.players.remove(player);
|
||||
}
|
||||
}
|
||||
|
||||
private static void status(ServerPlayer player, String pack, String state, String detail) {
|
||||
PacketDistributor.sendToPlayer(player, new StickerPackets.ImportStatus(pack, state, detail));
|
||||
}
|
||||
|
||||
private static void terminate(Process running) {
|
||||
running.descendants().forEach(child -> child.destroyForcibly());
|
||||
running.destroyForcibly();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closed = true;
|
||||
Process running = process;
|
||||
if (running != null) {
|
||||
terminate(running);
|
||||
}
|
||||
worker.shutdownNow();
|
||||
queue.clear();
|
||||
pending.clear();
|
||||
cooldown.clear();
|
||||
requestAfter.clear();
|
||||
}
|
||||
|
||||
private static final class Job {
|
||||
private final TelegramPack pack;
|
||||
private final String executable;
|
||||
private final String tokenFile;
|
||||
private final Set<UUID> players = new HashSet<>();
|
||||
|
||||
private Job(TelegramPack pack, String executable, String tokenFile) {
|
||||
this.pack = pack;
|
||||
this.executable = executable;
|
||||
this.tokenFile = tokenFile;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** The shared, credential-free manifest produced by the server importer. */
|
||||
public record StickerCatalog(int version, List<Pack> packs) {
|
||||
public static final int CELL_SIZE = 128;
|
||||
public static final int FRAME_RATE = 20;
|
||||
public static final int MAX_CATALOG_BYTES = 524_288;
|
||||
public static final int MAX_ASSET_BYTES = 2_097_152;
|
||||
public static final int MAX_STICKERS = 2_048;
|
||||
private static final Pattern ASSET_ID = Pattern.compile("[0-9a-f]{64}");
|
||||
private static final Pattern PACK_ID = Pattern.compile("[A-Za-z0-9_]{1,64}");
|
||||
|
||||
public StickerCatalog {
|
||||
packs = List.copyOf(packs);
|
||||
if (version != 1 || packs.size() > 64) {
|
||||
throw new IllegalArgumentException("Unsupported sticker catalog version or pack count");
|
||||
}
|
||||
if (packs.stream().mapToInt(pack -> pack.stickers().size()).sum() > MAX_STICKERS) {
|
||||
throw new IllegalArgumentException("Sticker catalog exceeds 2048 entries");
|
||||
}
|
||||
if (packs.stream().map(Pack::id).distinct().count() != packs.size()) {
|
||||
throw new IllegalArgumentException("Duplicate sticker pack id");
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<Sticker> find(String id) {
|
||||
return packs.stream().flatMap(pack -> pack.stickers().stream())
|
||||
.filter(sticker -> sticker.id().equals(id)).findFirst();
|
||||
}
|
||||
|
||||
public static void requireAssetId(String id) {
|
||||
if (!ASSET_ID.matcher(id).matches()) {
|
||||
throw new IllegalArgumentException("Sticker asset id must be a lowercase SHA-256");
|
||||
}
|
||||
}
|
||||
|
||||
public record Pack(String id, String title, List<Sticker> stickers) {
|
||||
public Pack {
|
||||
if (!PACK_ID.matcher(id).matches() || title.isBlank() || title.length() > 256) {
|
||||
throw new IllegalArgumentException("Invalid sticker pack id or title");
|
||||
}
|
||||
stickers = List.copyOf(stickers);
|
||||
if (stickers.size() > 200) {
|
||||
throw new IllegalArgumentException("Sticker pack exceeds 200 entries");
|
||||
}
|
||||
if (stickers.stream().map(Sticker::id).distinct().count() != stickers.size()) {
|
||||
throw new IllegalArgumentException("Duplicate sticker in pack");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record Sticker(String id, String emoji, int frames) {
|
||||
public Sticker {
|
||||
requireAssetId(id);
|
||||
Objects.requireNonNull(emoji);
|
||||
if (emoji.length() > 64 || frames < 1 || frames > 60) {
|
||||
throw new IllegalArgumentException("Invalid sticker emoji or frame count");
|
||||
}
|
||||
}
|
||||
|
||||
public int columns() {
|
||||
return Math.min(8, frames);
|
||||
}
|
||||
|
||||
public int width() {
|
||||
return columns() * CELL_SIZE;
|
||||
}
|
||||
|
||||
public int height() {
|
||||
return ((frames + columns() - 1) / columns()) * CELL_SIZE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
/** Separate requests keep clients from supplying authors, URLs or asset paths. */
|
||||
public final class StickerPackets {
|
||||
public static final int CHUNK_BYTES = 24_576;
|
||||
public static final int MAX_CHUNKS =
|
||||
(StickerCatalog.MAX_ASSET_BYTES + CHUNK_BYTES - 1) / CHUNK_BYTES;
|
||||
|
||||
private StickerPackets() {}
|
||||
|
||||
private static <T extends CustomPacketPayload> CustomPacketPayload.Type<T> type(String name) {
|
||||
return new CustomPacketPayload.Type<>(
|
||||
ResourceLocation.fromNamespaceAndPath("wowmine_stickers", name));
|
||||
}
|
||||
|
||||
public record ImportPack(String link) implements CustomPacketPayload {
|
||||
public static final Type<ImportPack> TYPE = StickerPackets.type("import_pack");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ImportPack> CODEC =
|
||||
StreamCodec.of((buffer, value) -> buffer.writeUtf(value.link, 256),
|
||||
buffer -> new ImportPack(buffer.readUtf(256)));
|
||||
|
||||
public ImportPack {
|
||||
if (link.isBlank() || link.length() > 256) {
|
||||
throw new IllegalArgumentException("Invalid sticker pack link length");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<ImportPack> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
public record ImportStatus(String pack, String state, String detail)
|
||||
implements CustomPacketPayload {
|
||||
public static final Type<ImportStatus> TYPE = StickerPackets.type("import_status");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ImportStatus> CODEC =
|
||||
StreamCodec.of((buffer, value) -> {
|
||||
buffer.writeUtf(value.pack, 64);
|
||||
buffer.writeUtf(value.state, 16);
|
||||
buffer.writeUtf(value.detail, 256);
|
||||
}, buffer -> new ImportStatus(buffer.readUtf(64), buffer.readUtf(16), buffer.readUtf(256)));
|
||||
|
||||
public ImportStatus {
|
||||
if (pack.length() > 64 || detail.length() > 256) {
|
||||
throw new IllegalArgumentException("Invalid import status length");
|
||||
}
|
||||
if (!java.util.Set.of("queued", "importing", "ready", "error").contains(state)) {
|
||||
throw new IllegalArgumentException("Invalid import status state");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<ImportStatus> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
public record CatalogRequest() implements CustomPacketPayload {
|
||||
public static final Type<CatalogRequest> TYPE = StickerPackets.type("catalog_request");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, CatalogRequest> CODEC =
|
||||
StreamCodec.unit(new CatalogRequest());
|
||||
|
||||
@Override
|
||||
public Type<CatalogRequest> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
public record CatalogReply(String json) implements CustomPacketPayload {
|
||||
public static final Type<CatalogReply> TYPE = StickerPackets.type("catalog");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, CatalogReply> CODEC =
|
||||
StreamCodec.of(
|
||||
(buffer, value) -> buffer.writeUtf(value.json, StickerCatalog.MAX_CATALOG_BYTES),
|
||||
buffer -> new CatalogReply(buffer.readUtf(StickerCatalog.MAX_CATALOG_BYTES)));
|
||||
|
||||
public CatalogReply {
|
||||
if (json.getBytes(StandardCharsets.UTF_8).length > StickerCatalog.MAX_CATALOG_BYTES) {
|
||||
throw new IllegalArgumentException("Sticker catalog exceeds 512 KiB");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<CatalogReply> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
public record AssetRequest(String id) implements CustomPacketPayload {
|
||||
public static final Type<AssetRequest> TYPE = StickerPackets.type("asset_request");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, AssetRequest> CODEC =
|
||||
StreamCodec.of((buffer, value) -> buffer.writeUtf(value.id, 64),
|
||||
buffer -> new AssetRequest(buffer.readUtf(64)));
|
||||
|
||||
public AssetRequest {
|
||||
StickerCatalog.requireAssetId(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<AssetRequest> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
public record AssetProblem(String id, String reason) implements CustomPacketPayload {
|
||||
public static final Type<AssetProblem> TYPE = StickerPackets.type("asset_problem");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, AssetProblem> CODEC =
|
||||
StreamCodec.of((buffer, value) -> {
|
||||
buffer.writeUtf(value.id, 64);
|
||||
buffer.writeUtf(value.reason, 256);
|
||||
}, buffer -> new AssetProblem(buffer.readUtf(64), buffer.readUtf(256)));
|
||||
|
||||
public AssetProblem {
|
||||
StickerCatalog.requireAssetId(id);
|
||||
if (reason.isBlank() || reason.length() > 256) {
|
||||
throw new IllegalArgumentException("Invalid asset failure description");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<AssetProblem> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
public record AssetChunk(String id, int part, int total, byte[] bytes)
|
||||
implements CustomPacketPayload {
|
||||
public static final Type<AssetChunk> TYPE = StickerPackets.type("asset_chunk");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, AssetChunk> CODEC =
|
||||
StreamCodec.of((buffer, value) -> {
|
||||
buffer.writeUtf(value.id, 64);
|
||||
buffer.writeVarInt(value.part);
|
||||
buffer.writeVarInt(value.total);
|
||||
buffer.writeByteArray(value.bytes);
|
||||
}, buffer -> new AssetChunk(buffer.readUtf(64), buffer.readVarInt(),
|
||||
buffer.readVarInt(), buffer.readByteArray(CHUNK_BYTES)));
|
||||
|
||||
public AssetChunk {
|
||||
StickerCatalog.requireAssetId(id);
|
||||
if (total < 1 || total > MAX_CHUNKS || part < 0 || part >= total
|
||||
|| bytes.length < 1 || bytes.length > CHUNK_BYTES
|
||||
|| (part < total - 1 && bytes.length != CHUNK_BYTES)) {
|
||||
throw new IllegalArgumentException("Invalid sticker asset chunk");
|
||||
}
|
||||
bytes = bytes.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] bytes() {
|
||||
return bytes.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<AssetChunk> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
public record SendSticker(String id) implements CustomPacketPayload {
|
||||
public static final Type<SendSticker> TYPE = StickerPackets.type("send");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, SendSticker> CODEC =
|
||||
StreamCodec.of((buffer, value) -> buffer.writeUtf(value.id, 64),
|
||||
buffer -> new SendSticker(buffer.readUtf(64)));
|
||||
|
||||
public SendSticker {
|
||||
StickerCatalog.requireAssetId(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<SendSticker> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
|
||||
public record StickerMessage(UUID author, String name, String id)
|
||||
implements CustomPacketPayload {
|
||||
public static final Type<StickerMessage> TYPE = StickerPackets.type("message");
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, StickerMessage> CODEC =
|
||||
StreamCodec.of((buffer, value) -> {
|
||||
buffer.writeUUID(value.author);
|
||||
buffer.writeUtf(value.name, 64);
|
||||
buffer.writeUtf(value.id, 64);
|
||||
}, buffer -> new StickerMessage(buffer.readUUID(), buffer.readUtf(64), buffer.readUtf(64)));
|
||||
|
||||
public StickerMessage {
|
||||
Objects.requireNonNull(author);
|
||||
if (name.isBlank() || name.length() > 64) {
|
||||
throw new IllegalArgumentException("Invalid sticker author name");
|
||||
}
|
||||
StickerCatalog.requireAssetId(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type<StickerMessage> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Extract a public set name; a player-supplied URL is never fetched directly. */
|
||||
public record TelegramPack(String name) {
|
||||
private static final Pattern NAME = Pattern.compile("[A-Za-z0-9_]{1,64}");
|
||||
|
||||
public TelegramPack {
|
||||
if (!NAME.matcher(name).matches()) {
|
||||
throw new IllegalArgumentException("Invalid Telegram sticker set name");
|
||||
}
|
||||
}
|
||||
|
||||
public static TelegramPack fromInput(String input) {
|
||||
String value = input.strip();
|
||||
if (NAME.matcher(value).matches()) {
|
||||
return new TelegramPack(value);
|
||||
}
|
||||
URI uri = URI.create(value);
|
||||
if (!"https".equalsIgnoreCase(uri.getScheme())
|
||||
|| !"t.me".equalsIgnoreCase(uri.getHost())
|
||||
|| uri.getPort() != -1 || uri.getUserInfo() != null
|
||||
|| uri.getRawQuery() != null || uri.getRawFragment() != null) {
|
||||
throw new IllegalArgumentException("Use https://t.me/addstickers/SET_NAME");
|
||||
}
|
||||
String prefix = "/addstickers/";
|
||||
String path = uri.getRawPath();
|
||||
if (!path.startsWith(prefix)) {
|
||||
throw new IllegalArgumentException("Use a Telegram sticker set link");
|
||||
}
|
||||
return new TelegramPack(path.substring(prefix.length()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.AbstractList;
|
||||
import java.util.List;
|
||||
import java.util.RandomAccess;
|
||||
|
||||
/** Versioned archive container: big-endian WVO1, frame count, then unsigned-short lengths and Opus bytes. */
|
||||
public final class VoiceFrames {
|
||||
private static final int MAGIC = 0x57564f31;
|
||||
private static final int HEADER_BYTES = 8;
|
||||
|
||||
private VoiceFrames() {}
|
||||
|
||||
public static byte[] encode(List<byte[]> frames) {
|
||||
if (frames == null || frames.isEmpty() || frames.size() > ChatHistory.VOICE_FRAMES) {
|
||||
throw new IllegalArgumentException("Invalid voice frame count");
|
||||
}
|
||||
byte[][] copies = new byte[frames.size()][];
|
||||
int size = HEADER_BYTES;
|
||||
for (int index = 0; index < copies.length; index++) {
|
||||
byte[] frame = frames.get(index);
|
||||
if (frame == null || frame.length < 1 || frame.length > ChatHistory.VOICE_FRAME_BYTES) {
|
||||
throw new IllegalArgumentException("Invalid voice frame size");
|
||||
}
|
||||
copies[index] = frame.clone();
|
||||
size += Short.BYTES + frame.length;
|
||||
if (size > ChatHistory.MEDIA_BYTES) {
|
||||
throw new IllegalArgumentException("Voice container exceeds media budget");
|
||||
}
|
||||
}
|
||||
ByteBuffer output = ByteBuffer.allocate(size);
|
||||
output.putInt(MAGIC).putInt(copies.length);
|
||||
for (byte[] frame : copies) {
|
||||
output.putShort((short) frame.length).put(frame);
|
||||
}
|
||||
return output.array();
|
||||
}
|
||||
|
||||
/** Neither the input buffer nor arrays obtained from this list can mutate its stored frames. */
|
||||
public static List<byte[]> decode(byte[] packed) {
|
||||
if (packed == null || packed.length < HEADER_BYTES || packed.length > ChatHistory.MEDIA_BYTES) {
|
||||
throw new IllegalArgumentException("Invalid voice container size");
|
||||
}
|
||||
ByteBuffer input = ByteBuffer.wrap(packed.clone());
|
||||
if (input.getInt() != MAGIC) {
|
||||
throw new IllegalArgumentException("Unknown voice container format");
|
||||
}
|
||||
int count = input.getInt();
|
||||
if (count < 1 || count > ChatHistory.VOICE_FRAMES || count > input.remaining() / 3) {
|
||||
throw new IllegalArgumentException("Invalid voice frame count");
|
||||
}
|
||||
byte[][] frames = new byte[count][];
|
||||
for (int index = 0; index < count; index++) {
|
||||
if (input.remaining() < Short.BYTES) {
|
||||
throw new IllegalArgumentException("Truncated voice frame length");
|
||||
}
|
||||
int length = Short.toUnsignedInt(input.getShort());
|
||||
if (length < 1 || length > ChatHistory.VOICE_FRAME_BYTES || length > input.remaining()) {
|
||||
throw new IllegalArgumentException("Invalid voice frame size");
|
||||
}
|
||||
frames[index] = new byte[length];
|
||||
input.get(frames[index]);
|
||||
}
|
||||
if (input.hasRemaining()) {
|
||||
throw new IllegalArgumentException("Trailing voice container bytes");
|
||||
}
|
||||
return new Frames(frames);
|
||||
}
|
||||
|
||||
private static final class Frames extends AbstractList<byte[]> implements RandomAccess {
|
||||
private final byte[][] frames;
|
||||
|
||||
private Frames(byte[][] frames) {
|
||||
this.frames = frames;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] get(int index) {
|
||||
return frames[index].clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return frames.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.neoforged.bus.api.IEventBus;
|
||||
import net.neoforged.bus.api.EventPriority;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.fml.common.Mod;
|
||||
import net.neoforged.fml.loading.FMLPaths;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import net.neoforged.neoforge.event.ServerChatEvent;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
|
||||
import net.neoforged.neoforge.event.server.ServerStartingEvent;
|
||||
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
import net.neoforged.neoforge.network.PacketDistributor;
|
||||
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
|
||||
import net.wowmine.stickers.client.StickerClient;
|
||||
|
||||
@Mod("wowmine_stickers")
|
||||
public final class WowmineStickers {
|
||||
private ServerCatalog catalog;
|
||||
private ServerAssets assets;
|
||||
private ServerImports imports;
|
||||
private ArchiveServer history;
|
||||
private final Map<UUID, Integer> sendAfter = new HashMap<>();
|
||||
private final Map<UUID, Integer> catalogAfter = new HashMap<>();
|
||||
|
||||
public WowmineStickers(IEventBus bus) {
|
||||
bus.addListener(this::registerPayloads);
|
||||
NeoForge.EVENT_BUS.register(this);
|
||||
NeoForge.EVENT_BUS.addListener(this::start);
|
||||
NeoForge.EVENT_BUS.addListener(this::stop);
|
||||
NeoForge.EVENT_BUS.addListener(this::tick);
|
||||
NeoForge.EVENT_BUS.addListener(this::logout);
|
||||
ArchiveVoiceServer.init();
|
||||
}
|
||||
|
||||
private void registerPayloads(RegisterPayloadHandlersEvent event) {
|
||||
var registrar = event.registrar("1").optional();
|
||||
registrar.playToClient(StickerPackets.CatalogReply.TYPE, StickerPackets.CatalogReply.CODEC,
|
||||
(packet, context) -> context.enqueueWork(() -> StickerClient.onCatalog(packet)));
|
||||
registrar.playToClient(StickerPackets.AssetChunk.TYPE, StickerPackets.AssetChunk.CODEC,
|
||||
(packet, context) -> context.enqueueWork(() -> StickerClient.onAssetChunk(packet)));
|
||||
registrar.playToClient(StickerPackets.AssetProblem.TYPE, StickerPackets.AssetProblem.CODEC,
|
||||
(packet, context) -> context.enqueueWork(() -> StickerClient.onAssetProblem(packet)));
|
||||
registrar.playToClient(StickerPackets.StickerMessage.TYPE, StickerPackets.StickerMessage.CODEC,
|
||||
(packet, context) -> context.enqueueWork(() -> StickerClient.onMessage(packet)));
|
||||
registrar.playToClient(StickerPackets.ImportStatus.TYPE, StickerPackets.ImportStatus.CODEC,
|
||||
(packet, context) -> context.enqueueWork(() -> StickerClient.onImportStatus(packet)));
|
||||
registrar.playToServer(StickerPackets.CatalogRequest.TYPE, StickerPackets.CatalogRequest.CODEC,
|
||||
(packet, context) -> {
|
||||
ServerPlayer player = (ServerPlayer) context.player();
|
||||
int now = player.server.getTickCount();
|
||||
if (now >= catalogAfter.getOrDefault(player.getUUID(), 0)) {
|
||||
catalogAfter.put(player.getUUID(), now + 20);
|
||||
PacketDistributor.sendToPlayer(player, new StickerPackets.CatalogReply(catalog.json()));
|
||||
}
|
||||
});
|
||||
registrar.playToServer(StickerPackets.AssetRequest.TYPE, StickerPackets.AssetRequest.CODEC,
|
||||
(packet, context) -> assets.request((ServerPlayer) context.player(), catalog, packet.id()));
|
||||
registrar.playToServer(StickerPackets.SendSticker.TYPE, StickerPackets.SendSticker.CODEC,
|
||||
(packet, context) -> send((ServerPlayer) context.player(), packet.id()));
|
||||
registrar.playToServer(StickerPackets.ImportPack.TYPE, StickerPackets.ImportPack.CODEC,
|
||||
(packet, context) -> imports.request((ServerPlayer) context.player(), packet.link()));
|
||||
ArchiveServer.register(event, () -> history);
|
||||
}
|
||||
|
||||
private void start(ServerStartingEvent event) {
|
||||
Path root = FMLPaths.CONFIGDIR.get().resolve("wowmine-stickers");
|
||||
try {
|
||||
catalog = ServerCatalog.load(root);
|
||||
history = ArchiveServer.open(event.getServer());
|
||||
} catch (IOException | SQLException error) {
|
||||
throw new IllegalStateException("Cannot load server chat data", error);
|
||||
}
|
||||
assets = new ServerAssets(event.getServer());
|
||||
imports = new ServerImports(event.getServer(), () -> catalog, loaded -> {
|
||||
catalog = loaded;
|
||||
for (ServerPlayer player : event.getServer().getPlayerList().getPlayers()) {
|
||||
if (player.connection.hasChannel(StickerPackets.CatalogReply.TYPE)) {
|
||||
PacketDistributor.sendToPlayer(player, new StickerPackets.CatalogReply(loaded.json()));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void send(ServerPlayer sender, String id) {
|
||||
if (catalog.catalog().find(id).isEmpty()) {
|
||||
sender.displayClientMessage(Component.translatable("wowmine_stickers.error.asset_missing"), true);
|
||||
return;
|
||||
}
|
||||
int now = sender.server.getTickCount();
|
||||
if (now < sendAfter.getOrDefault(sender.getUUID(), 0)) {
|
||||
sender.displayClientMessage(Component.translatable("wowmine_stickers.error.send_cooldown"), true);
|
||||
return;
|
||||
}
|
||||
sendAfter.put(sender.getUUID(), now + 20);
|
||||
if (!history.sticker(sender, catalog, id)) {
|
||||
return;
|
||||
}
|
||||
var message = new StickerPackets.StickerMessage(
|
||||
sender.getUUID(), sender.getGameProfile().getName(), id);
|
||||
for (ServerPlayer recipient : sender.server.getPlayerList().getPlayers()) {
|
||||
if (recipient.connection.hasChannel(StickerPackets.StickerMessage.TYPE)) {
|
||||
PacketDistributor.sendToPlayer(recipient, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void tick(ServerTickEvent.Post event) {
|
||||
assets.tick();
|
||||
history.tick();
|
||||
}
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.LOWEST)
|
||||
public void chat(ServerChatEvent event) {
|
||||
if (history != null) {
|
||||
history.chat(event);
|
||||
}
|
||||
}
|
||||
|
||||
private void logout(PlayerEvent.PlayerLoggedOutEvent event) {
|
||||
if (event.getEntity() instanceof ServerPlayer player) {
|
||||
sendAfter.remove(player.getUUID());
|
||||
catalogAfter.remove(player.getUUID());
|
||||
imports.forget(player.getUUID());
|
||||
history.forget(player.getUUID());
|
||||
}
|
||||
}
|
||||
|
||||
private void stop(ServerStoppedEvent event) {
|
||||
// Shutdown also follows a startup failure before these services exist.
|
||||
if (history != null) {
|
||||
history.close();
|
||||
history = null;
|
||||
}
|
||||
if (imports != null) {
|
||||
imports.close();
|
||||
}
|
||||
if (assets != null) {
|
||||
assets.close();
|
||||
}
|
||||
sendAfter.clear();
|
||||
catalogAfter.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.AbstractButton;
|
||||
import net.minecraft.client.gui.narration.NarrationElementOutput;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
/** Original archive glyph, sized like the existing chat controls. */
|
||||
final class HistoryButton extends AbstractButton {
|
||||
private static final String[] PIXELS = {
|
||||
"1111111111", "1000000001", "1011111101", "1000000001", "1011111101",
|
||||
"1000000001", "1011111101", "1000000001", "1000000001", "1111111111"
|
||||
};
|
||||
private final Runnable action;
|
||||
|
||||
HistoryButton(int x, int y, Runnable action) {
|
||||
super(x, y, 14, 14, Component.translatable("wowmine_stickers.history.open"));
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
@Override public void onPress() { action.run(); }
|
||||
|
||||
@Override
|
||||
protected void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float tick) {
|
||||
int color = active ? (isHoveredOrFocused() ? 0xFFFFFFA0 : 0xFFFFFFFF) : 0xFF777777;
|
||||
if (isFocused()) graphics.renderOutline(getX(), getY(), 14, 14, color);
|
||||
for (int y = 0; y < PIXELS.length; y++) {
|
||||
for (int x = 0; x < PIXELS[y].length(); x++) {
|
||||
if (PIXELS[y].charAt(x) == '1') {
|
||||
graphics.fill(getX() + x + 2, getY() + y + 2, getX() + x + 3, getY() + y + 3, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override protected void updateWidgetNarration(NarrationElementOutput output) {
|
||||
defaultButtonNarrationText(output);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.ClientPacketListener;
|
||||
import net.minecraft.client.renderer.texture.DynamicTexture;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.neoforged.neoforge.network.PacketDistributor;
|
||||
import net.wowmine.stickers.ChatHistory;
|
||||
import net.wowmine.stickers.HistoryPackets;
|
||||
import net.wowmine.stickers.StickerCatalog;
|
||||
import net.wowmine.stickers.VoiceFrames;
|
||||
|
||||
/** Client-thread-only archive session, independent of live chat and sticker catalog. */
|
||||
public final class HistoryClient {
|
||||
private static final long TIMEOUT = 20_000_000_000L;
|
||||
private static final int TEXTURE_LIMIT = 32;
|
||||
private static final int TEXTURE_BYTES = 64 * 1024 * 1024;
|
||||
private static final LinkedHashMap<String, Texture> textures = new LinkedHashMap<>(32, .75F, true);
|
||||
private static ChatHistory.Page page = new ChatHistory.Page(List.of(), false, false);
|
||||
private static long serial;
|
||||
private static long pendingPage;
|
||||
private static long pageStarted;
|
||||
private static int textureBytes;
|
||||
private static Component status = Component.empty();
|
||||
@Nullable private static Transfer transfer;
|
||||
|
||||
private HistoryClient() {}
|
||||
|
||||
public static boolean available() {
|
||||
ClientPacketListener connection = Minecraft.getInstance().getConnection();
|
||||
return connection != null && connection.hasChannel(HistoryPackets.PageRequest.TYPE);
|
||||
}
|
||||
|
||||
private static boolean mediaAvailable() {
|
||||
ClientPacketListener connection = Minecraft.getInstance().getConnection();
|
||||
return connection != null && connection.hasChannel(HistoryPackets.AttachmentRequest.TYPE);
|
||||
}
|
||||
|
||||
private static long nextRequest() {
|
||||
if (serial == Long.MAX_VALUE) {
|
||||
throw new IllegalStateException("History request IDs exhausted");
|
||||
}
|
||||
return ++serial;
|
||||
}
|
||||
|
||||
static ChatHistory.Page page() { return page; }
|
||||
static boolean busy() { return pendingPage != 0; }
|
||||
static Component status() { return status; }
|
||||
static boolean mediaBusy() { return transfer != null; }
|
||||
static boolean loading(long entry) { return transfer != null && transfer.entry.id() == entry; }
|
||||
|
||||
static void cancelAttachment() {
|
||||
if (transfer != null && transfer.entry.message().kind() == ChatHistory.Kind.VOICE) {
|
||||
transfer = null;
|
||||
status = Component.empty();
|
||||
}
|
||||
}
|
||||
|
||||
static void request(ChatHistory.Query query) {
|
||||
HistoryVoice.stop();
|
||||
transfer = null;
|
||||
if (!available()) {
|
||||
pendingPage = 0;
|
||||
status = Component.translatable("wowmine_stickers.history.offline");
|
||||
return;
|
||||
}
|
||||
pendingPage = nextRequest();
|
||||
pageStarted = System.nanoTime();
|
||||
status = Component.translatable("wowmine_stickers.history.loading");
|
||||
PacketDistributor.sendToServer(new HistoryPackets.PageRequest(pendingPage, query));
|
||||
}
|
||||
|
||||
public static void onPage(HistoryPackets.PageReply reply) {
|
||||
if (reply.request() != pendingPage) return;
|
||||
pendingPage = 0;
|
||||
page = reply.page();
|
||||
status = page.entries().isEmpty()
|
||||
? Component.translatable("wowmine_stickers.history.empty") : Component.empty();
|
||||
if (Minecraft.getInstance().screen instanceof HistoryScreen screen) screen.pageChanged();
|
||||
}
|
||||
|
||||
public static void onProblem(HistoryPackets.Problem problem) {
|
||||
if (problem.request() == pendingPage) {
|
||||
pendingPage = 0;
|
||||
status = Component.translatable("wowmine_stickers.history.problem",
|
||||
Component.translatable("wowmine_stickers.history.failure."
|
||||
+ problem.failure().name().toLowerCase(java.util.Locale.ROOT)));
|
||||
} else if (transfer != null && problem.request() == transfer.request) {
|
||||
transfer = null;
|
||||
status = Component.translatable("wowmine_stickers.history.problem",
|
||||
Component.translatable("wowmine_stickers.history.failure."
|
||||
+ problem.failure().name().toLowerCase(java.util.Locale.ROOT)));
|
||||
}
|
||||
}
|
||||
|
||||
static void attachment(ChatHistory.Entry entry) {
|
||||
if (transfer != null || !mediaAvailable()) {
|
||||
status = Component.translatable(transfer != null
|
||||
? "wowmine_stickers.history.busy" : "wowmine_stickers.history.offline");
|
||||
return;
|
||||
}
|
||||
transfer = new Transfer(nextRequest(), entry);
|
||||
status = Component.translatable("wowmine_stickers.history.media_loading");
|
||||
PacketDistributor.sendToServer(new HistoryPackets.AttachmentRequest(transfer.request, entry.id()));
|
||||
}
|
||||
|
||||
public static void onAttachment(HistoryPackets.AttachmentChunk chunk) {
|
||||
Transfer current = transfer;
|
||||
if (current == null || chunk.request() != current.request) return;
|
||||
byte[] part = chunk.bytes();
|
||||
int limit = current.entry.message().kind() == ChatHistory.Kind.STICKER
|
||||
? StickerCatalog.MAX_ASSET_BYTES : ChatHistory.MEDIA_BYTES;
|
||||
if (!chunk.id().equals(current.entry.message().attachment()) || chunk.part() != current.part
|
||||
|| chunk.totalBytes() > limit || (current.total != 0 && current.total != chunk.totalBytes())
|
||||
|| current.bytes.size() + part.length > limit) {
|
||||
transfer = null;
|
||||
status = Component.translatable("wowmine_stickers.history.invalid_media");
|
||||
return;
|
||||
}
|
||||
current.total = chunk.totalBytes();
|
||||
current.lastProgress = System.nanoTime();
|
||||
current.bytes.writeBytes(part);
|
||||
current.part++;
|
||||
if (current.bytes.size() != current.total) return;
|
||||
transfer = null;
|
||||
byte[] bytes = current.bytes.toByteArray();
|
||||
try {
|
||||
String hash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
if (!hash.equals(chunk.id())) throw new IOException("Attachment hash mismatch");
|
||||
if (current.entry.message().kind() == ChatHistory.Kind.STICKER) {
|
||||
upload(current.entry, bytes);
|
||||
} else {
|
||||
validateVoice(bytes, current.entry.message().frames());
|
||||
HistoryVoice.toggle(current.entry.id(), bytes);
|
||||
}
|
||||
status = Component.empty();
|
||||
} catch (IOException invalid) {
|
||||
status = Component.translatable("wowmine_stickers.history.invalid_media");
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new AssertionError("Java requires SHA-256", impossible);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateVoice(byte[] bytes, int frames) throws IOException {
|
||||
try {
|
||||
if (VoiceFrames.decode(bytes).size() != frames) {
|
||||
throw new IOException("Voice frame count differs from archive metadata");
|
||||
}
|
||||
} catch (IllegalArgumentException invalid) {
|
||||
throw new IOException("Invalid archived voice container", invalid);
|
||||
}
|
||||
}
|
||||
|
||||
private static void upload(ChatHistory.Entry entry, byte[] bytes) throws IOException {
|
||||
StickerCatalog.Sticker sticker = sticker(entry);
|
||||
StickerPng.verify(bytes, sticker);
|
||||
NativeImage image = NativeImage.read(new ByteArrayInputStream(bytes));
|
||||
if (image.getWidth() != sticker.width() || image.getHeight() != sticker.height()) {
|
||||
image.close();
|
||||
throw new IOException("Decoded image dimensions differ");
|
||||
}
|
||||
int size = sticker.width() * sticker.height() * 4;
|
||||
while (!textures.isEmpty() && (textures.size() >= TEXTURE_LIMIT || textureBytes + size > TEXTURE_BYTES)) {
|
||||
String oldest = textures.keySet().iterator().next();
|
||||
Texture removed = textures.remove(oldest);
|
||||
Minecraft.getInstance().getTextureManager().release(removed.location());
|
||||
textureBytes -= removed.bytes();
|
||||
}
|
||||
ResourceLocation location = ResourceLocation.fromNamespaceAndPath(
|
||||
"wowmine_stickers", "history/" + sticker.id());
|
||||
Minecraft.getInstance().getTextureManager().register(location, new DynamicTexture(image));
|
||||
textures.put(sticker.id(), new Texture(location, size));
|
||||
textureBytes += size;
|
||||
}
|
||||
|
||||
static StickerCatalog.Sticker sticker(ChatHistory.Entry entry) {
|
||||
return new StickerCatalog.Sticker(entry.message().attachment(), "", entry.message().frames());
|
||||
}
|
||||
|
||||
@Nullable static ResourceLocation texture(ChatHistory.Entry entry) {
|
||||
Texture texture = textures.get(entry.message().attachment());
|
||||
return texture == null ? null : texture.location();
|
||||
}
|
||||
|
||||
public static void tick() {
|
||||
long now = System.nanoTime();
|
||||
if (pendingPage != 0 && now - pageStarted > TIMEOUT) {
|
||||
pendingPage = 0;
|
||||
status = Component.translatable("wowmine_stickers.history.timeout");
|
||||
}
|
||||
if (transfer != null && now - transfer.lastProgress > TIMEOUT) {
|
||||
transfer = null;
|
||||
status = Component.translatable("wowmine_stickers.history.timeout");
|
||||
}
|
||||
}
|
||||
|
||||
static void close() {
|
||||
pendingPage = 0;
|
||||
transfer = null;
|
||||
HistoryVoice.stop();
|
||||
}
|
||||
|
||||
public static void disconnect() {
|
||||
close();
|
||||
page = new ChatHistory.Page(List.of(), false, false);
|
||||
status = Component.empty();
|
||||
for (Texture texture : textures.values()) {
|
||||
Minecraft.getInstance().getTextureManager().release(texture.location());
|
||||
}
|
||||
textures.clear();
|
||||
textureBytes = 0;
|
||||
}
|
||||
|
||||
private record Texture(ResourceLocation location, int bytes) {}
|
||||
|
||||
private static final class Transfer {
|
||||
final long request;
|
||||
final ChatHistory.Entry entry;
|
||||
long lastProgress = System.nanoTime();
|
||||
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
int part;
|
||||
int total;
|
||||
|
||||
Transfer(long request, ChatHistory.Entry entry) {
|
||||
this.request = request;
|
||||
this.entry = entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.client.gui.components.Tooltip;
|
||||
import net.minecraft.client.gui.screens.ChatScreen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.neoforged.api.distmarker.Dist;
|
||||
import net.neoforged.bus.api.EventPriority;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.fml.common.EventBusSubscriber;
|
||||
import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent;
|
||||
import net.neoforged.neoforge.client.event.ClientTickEvent;
|
||||
import net.neoforged.neoforge.client.event.ScreenEvent;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
|
||||
@EventBusSubscriber(modid = "wowmine_stickers", value = Dist.CLIENT)
|
||||
public final class HistoryClientEvents {
|
||||
@Nullable private static ChatScreen chat;
|
||||
@Nullable private static HistoryButton button;
|
||||
|
||||
private HistoryClientEvents() {}
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.LOWEST)
|
||||
public static void init(ScreenEvent.Init.Post event) {
|
||||
if (!(event.getScreen() instanceof ChatScreen screen)) return;
|
||||
chat = screen;
|
||||
EditBox input = ((StickerClientEvents.ChatInput) screen).wowmine_stickers$input();
|
||||
button = new HistoryButton(input.getX() - 3, input.getY() - 3, HistoryClientEvents::open);
|
||||
input.setX(input.getX() + 14);
|
||||
input.setWidth(Math.max(1, input.getWidth() - 14));
|
||||
button.active = HistoryClient.available();
|
||||
button.setTooltip(Tooltip.create(Component.translatable(button.active
|
||||
? "wowmine_stickers.history.open" : "wowmine_stickers.history.offline")));
|
||||
event.addListener(button);
|
||||
}
|
||||
|
||||
public static boolean hasButton(ChatScreen screen) {
|
||||
return screen == chat && button != null;
|
||||
}
|
||||
|
||||
private static void open() {
|
||||
if (chat != null && HistoryClient.available()) {
|
||||
String draft = ((StickerClientEvents.ChatInput) chat).wowmine_stickers$input().getValue();
|
||||
Minecraft.getInstance().setScreen(new HistoryScreen(draft));
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void render(ScreenEvent.Render.Post event) {
|
||||
if (event.getScreen() == chat && button != null) {
|
||||
boolean available = HistoryClient.available();
|
||||
if (button.active != available) {
|
||||
button.active = available;
|
||||
button.setTooltip(Tooltip.create(Component.translatable(available
|
||||
? "wowmine_stickers.history.open" : "wowmine_stickers.history.offline")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.HIGHEST)
|
||||
public static void key(ScreenEvent.KeyPressed.Pre event) {
|
||||
if (event.getScreen() == chat && event.getKeyCode() == GLFW.GLFW_KEY_H
|
||||
&& (event.getModifiers() & GLFW.GLFW_MOD_ALT) != 0 && HistoryClient.available()) {
|
||||
open();
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent public static void tick(ClientTickEvent.Post event) { HistoryClient.tick(); }
|
||||
|
||||
@SubscribeEvent public static void logout(ClientPlayerNetworkEvent.LoggingOut event) {
|
||||
HistoryClient.disconnect();
|
||||
chat = null;
|
||||
button = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.Button;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.client.gui.components.Tooltip;
|
||||
import net.minecraft.client.gui.screens.ChatScreen;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.util.FormattedCharSequence;
|
||||
import net.wowmine.stickers.ChatHistory;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
|
||||
/** Separate read-only archive; never writes to vanilla chat or follows component links. */
|
||||
final class HistoryScreen extends Screen {
|
||||
private static final int MARGIN = 6;
|
||||
private static final int LINE = 10;
|
||||
private static final int IMAGE = 48;
|
||||
private static final int BACKGROUND = 0xFF202020;
|
||||
private static final int BORDER = 0xFFAAAAAA;
|
||||
private static final int TEXT = 0xFFFFFFFF;
|
||||
private static final int MUTED = 0xFFCCCCCC;
|
||||
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
|
||||
private final String draft;
|
||||
private final Set<Long> requestedImages = new HashSet<>();
|
||||
private EditBox date;
|
||||
private Button older;
|
||||
private Button newer;
|
||||
private Button play;
|
||||
private int left;
|
||||
private int top;
|
||||
private int panelWidth;
|
||||
private int panelHeight;
|
||||
private int scroll;
|
||||
private int contentHeight;
|
||||
private boolean bottomOnReply = true;
|
||||
private boolean firstInit = true;
|
||||
private int selectedVoice = -1;
|
||||
private Component localStatus = Component.empty();
|
||||
private List<Row> rows = List.of();
|
||||
|
||||
HistoryScreen(String draft) {
|
||||
super(Component.translatable("wowmine_stickers.history.title"));
|
||||
this.draft = draft;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void init() {
|
||||
panelWidth = Math.min(500, width - 8);
|
||||
panelHeight = Math.min(360, height - 8);
|
||||
left = (width - panelWidth) / 2;
|
||||
top = (height - panelHeight) / 2;
|
||||
int row = top + panelHeight - 49;
|
||||
int unit = Math.max(34, (panelWidth - 5 * MARGIN) / 4);
|
||||
addRenderableWidget(Button.builder(Component.translatable("wowmine_stickers.history.earliest"),
|
||||
button -> request(ChatHistory.Query.earliest(), false))
|
||||
.bounds(left + MARGIN, row, unit, 18).build());
|
||||
older = addRenderableWidget(Button.builder(Component.translatable("wowmine_stickers.history.older"),
|
||||
button -> older()).bounds(left + 2 * MARGIN + unit, row, unit, 18).build());
|
||||
newer = addRenderableWidget(Button.builder(Component.translatable("wowmine_stickers.history.newer"),
|
||||
button -> newer()).bounds(left + 3 * MARGIN + 2 * unit, row, unit, 18).build());
|
||||
addRenderableWidget(Button.builder(Component.translatable("wowmine_stickers.history.latest"),
|
||||
button -> request(ChatHistory.Query.latest(), true))
|
||||
.bounds(left + 4 * MARGIN + 3 * unit, row, unit, 18).build());
|
||||
int dateRow = row + 23;
|
||||
date = addRenderableWidget(new EditBox(font, left + MARGIN, dateRow, 100, 18,
|
||||
Component.translatable("wowmine_stickers.history.date")));
|
||||
date.setMaxLength(10);
|
||||
date.setHint(Component.literal("YYYY-MM-DD"));
|
||||
addRenderableWidget(Button.builder(Component.translatable("wowmine_stickers.history.jump"),
|
||||
button -> jump()).bounds(left + 110, dateRow, 55, 18).build());
|
||||
play = addRenderableWidget(Button.builder(Component.translatable("wowmine_stickers.history.play"),
|
||||
button -> playSelected()).bounds(left + 170, dateRow, 60, 18).build());
|
||||
play.setTooltip(Tooltip.create(Component.translatable("wowmine_stickers.history.voice_help")));
|
||||
addRenderableWidget(Button.builder(Component.translatable("gui.done"), button -> onClose())
|
||||
.bounds(left + panelWidth - 66, dateRow, 60, 18).build());
|
||||
if (firstInit) {
|
||||
firstInit = false;
|
||||
request(ChatHistory.Query.latest(), true);
|
||||
}
|
||||
rebuildRows();
|
||||
}
|
||||
|
||||
private int contentTop() { return top + 20; }
|
||||
private int contentBottom() { return top + panelHeight - 65; }
|
||||
private int viewport() { return Math.max(1, contentBottom() - contentTop()); }
|
||||
private int maxScroll() { return Math.max(0, contentHeight - viewport()); }
|
||||
|
||||
private void request(ChatHistory.Query query, boolean bottom) {
|
||||
bottomOnReply = bottom;
|
||||
localStatus = Component.empty();
|
||||
HistoryClient.request(query);
|
||||
}
|
||||
|
||||
private void older() {
|
||||
List<ChatHistory.Entry> entries = HistoryClient.page().entries();
|
||||
if (!HistoryClient.busy() && HistoryClient.page().hasOlder() && !entries.isEmpty()) {
|
||||
request(ChatHistory.Query.before(entries.getFirst().cursor()), true);
|
||||
}
|
||||
}
|
||||
|
||||
private void newer() {
|
||||
List<ChatHistory.Entry> entries = HistoryClient.page().entries();
|
||||
if (!HistoryClient.busy() && HistoryClient.page().hasNewer() && !entries.isEmpty()) {
|
||||
request(ChatHistory.Query.after(entries.getLast().cursor()), false);
|
||||
}
|
||||
}
|
||||
|
||||
private void jump() {
|
||||
try {
|
||||
long time = LocalDate.parse(date.getValue()).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
|
||||
if (time < 0) throw new DateTimeParseException("Before epoch", date.getValue(), 0);
|
||||
request(new ChatHistory.Query(ChatHistory.Direction.AT_DATE, time, 0), false);
|
||||
} catch (DateTimeParseException invalid) {
|
||||
localStatus = Component.translatable("wowmine_stickers.history.invalid_date");
|
||||
}
|
||||
}
|
||||
|
||||
void pageChanged() {
|
||||
requestedImages.clear();
|
||||
selectedVoice = -1;
|
||||
rebuildRows();
|
||||
scroll = bottomOnReply ? Integer.MAX_VALUE : 0;
|
||||
}
|
||||
|
||||
private void playSelected() {
|
||||
List<ChatHistory.Entry> entries = HistoryClient.page().entries();
|
||||
if (selectedVoice < 0 || selectedVoice >= entries.size()) return;
|
||||
ChatHistory.Entry entry = entries.get(selectedVoice);
|
||||
if (entry.message().kind() != ChatHistory.Kind.VOICE) return;
|
||||
if (HistoryClient.loading(entry.id())) {
|
||||
HistoryClient.cancelAttachment();
|
||||
} else if (HistoryVoice.isPlaying(entry.id()) || HistoryVoice.isLoading(entry.id())) {
|
||||
HistoryVoice.stop();
|
||||
} else if (HistoryVoice.available()) {
|
||||
HistoryClient.attachment(entry);
|
||||
} else {
|
||||
localStatus = Component.translatable("wowmine_stickers.history.voice_unavailable");
|
||||
}
|
||||
}
|
||||
|
||||
private Component body(ChatHistory.Entry entry) {
|
||||
try {
|
||||
Component parsed = Component.Serializer.fromJson(entry.message().body(), minecraft.getConnection().registryAccess());
|
||||
return parsed == null ? Component.empty() : parsed;
|
||||
} catch (RuntimeException invalid) {
|
||||
return Component.translatable("wowmine_stickers.history.invalid_message");
|
||||
}
|
||||
}
|
||||
|
||||
private void rebuildRows() {
|
||||
rows = HistoryClient.page().entries().stream().map(entry -> {
|
||||
List<FormattedCharSequence> lines = font.split(body(entry), Math.max(1, panelWidth - 2 * MARGIN - 4));
|
||||
int media = switch (entry.message().kind()) {
|
||||
case TEXT -> 0;
|
||||
case STICKER -> IMAGE + MARGIN;
|
||||
case VOICE -> 20;
|
||||
};
|
||||
return new Row(entry, lines, LINE + Math.max(1, lines.size()) * LINE + media + MARGIN);
|
||||
}).toList();
|
||||
contentHeight = rows.stream().mapToInt(Row::height).sum();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) {
|
||||
renderBackground(graphics, mouseX, mouseY, partialTick);
|
||||
graphics.fill(left, top, left + panelWidth, top + panelHeight, BACKGROUND);
|
||||
graphics.renderOutline(left, top, panelWidth, panelHeight, BORDER);
|
||||
graphics.drawCenteredString(font, title, width / 2, top + MARGIN, TEXT);
|
||||
scroll = Math.clamp(scroll, 0, maxScroll());
|
||||
older.active = !HistoryClient.busy() && HistoryClient.page().hasOlder();
|
||||
newer.active = !HistoryClient.busy() && HistoryClient.page().hasNewer();
|
||||
play.active = selectedVoice >= 0 && !HistoryClient.busy();
|
||||
if (play.active) {
|
||||
long entry = rows.get(selectedVoice).entry().id();
|
||||
play.setMessage(Component.translatable(HistoryClient.loading(entry) || HistoryVoice.isPlaying(entry)
|
||||
|| HistoryVoice.isLoading(entry) ? "wowmine_stickers.history.stop" : "wowmine_stickers.history.play"));
|
||||
}
|
||||
graphics.enableScissor(left + MARGIN, contentTop(), left + panelWidth - MARGIN, contentBottom());
|
||||
int y = contentTop() - scroll;
|
||||
for (int index = 0; index < rows.size(); index++) {
|
||||
Row row = rows.get(index);
|
||||
ChatHistory.Entry entry = row.entry();
|
||||
int entryHeight = row.height();
|
||||
if (y + entryHeight >= contentTop() && y < contentBottom()) {
|
||||
if (index == selectedVoice) {
|
||||
graphics.renderOutline(left + MARGIN, y, panelWidth - 2 * MARGIN, entryHeight, BORDER);
|
||||
}
|
||||
String time = TIME.format(Instant.ofEpochMilli(entry.message().time()).atZone(ZoneId.systemDefault()));
|
||||
graphics.drawString(font, time + " " + entry.message().name(), left + MARGIN, y, MUTED);
|
||||
int lineY = y + LINE;
|
||||
for (FormattedCharSequence line : row.lines()) {
|
||||
graphics.drawString(font, line, left + MARGIN, lineY, TEXT);
|
||||
lineY += LINE;
|
||||
}
|
||||
if (entry.message().kind() == ChatHistory.Kind.STICKER) {
|
||||
var texture = HistoryClient.texture(entry);
|
||||
if (texture != null) {
|
||||
StickerImages.render(graphics, HistoryClient.sticker(entry),
|
||||
new StickerImages.Rectangle(left + MARGIN, lineY, IMAGE, 0, IMAGE, 255), texture);
|
||||
} else {
|
||||
graphics.drawString(font, Component.translatable("wowmine_stickers.history.sticker"),
|
||||
left + MARGIN, lineY, MUTED);
|
||||
if (!HistoryClient.mediaBusy() && requestedImages.add(entry.id())) HistoryClient.attachment(entry);
|
||||
}
|
||||
} else if (entry.message().kind() == ChatHistory.Kind.VOICE) {
|
||||
Component label = Component.translatable(HistoryClient.loading(entry.id()) || HistoryVoice.isLoading(entry.id())
|
||||
? "wowmine_stickers.history.media_loading" : HistoryVoice.isPlaying(entry.id())
|
||||
? "wowmine_stickers.history.stop" : "wowmine_stickers.history.voice_select");
|
||||
graphics.drawString(font, label, left + MARGIN, lineY, TEXT);
|
||||
if (HistoryVoice.isPlaying(entry.id())) {
|
||||
graphics.drawString(font, Math.round(HistoryVoice.progress(entry.id()) * 100) + "%",
|
||||
left + 45, lineY, MUTED);
|
||||
}
|
||||
graphics.drawString(font, HistoryVoice.error(entry.id()), left + 80, lineY, MUTED);
|
||||
}
|
||||
}
|
||||
y += entryHeight;
|
||||
}
|
||||
graphics.disableScissor();
|
||||
Component status = localStatus.getString().isEmpty() ? HistoryClient.status() : localStatus;
|
||||
graphics.drawString(font, font.plainSubstrByWidth(status.getString(), panelWidth - 2 * MARGIN),
|
||||
left + MARGIN, top + panelHeight - 61, MUTED);
|
||||
for (var renderable : renderables) renderable.render(graphics, mouseX, mouseY, partialTick);
|
||||
}
|
||||
|
||||
private void scrollBy(int delta) {
|
||||
int previous = scroll;
|
||||
scroll = Math.clamp(scroll + delta, 0, maxScroll());
|
||||
if (delta < 0 && previous == 0) older();
|
||||
if (delta > 0 && previous == maxScroll()) newer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mouseScrolled(double x, double y, double horizontal, double vertical) {
|
||||
if (x >= left && x < left + panelWidth && y >= contentTop() && y < contentBottom()) {
|
||||
if (vertical != 0) scrollBy(vertical > 0 ? -30 : 30);
|
||||
return true;
|
||||
}
|
||||
return super.mouseScrolled(x, y, horizontal, vertical);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mouseClicked(double x, double y, int button) {
|
||||
if (button == 0 && x >= left + MARGIN && x < left + panelWidth - MARGIN
|
||||
&& y >= contentTop() && y < contentBottom()) {
|
||||
int entryY = contentTop() - scroll;
|
||||
for (int index = 0; index < rows.size(); index++) {
|
||||
Row row = rows.get(index);
|
||||
ChatHistory.Entry entry = row.entry();
|
||||
int height = row.height();
|
||||
if (y >= entryY && y < entryY + height && entry.message().kind() == ChatHistory.Kind.VOICE) {
|
||||
if (selectedVoice != index) {
|
||||
HistoryClient.cancelAttachment();
|
||||
HistoryVoice.stop();
|
||||
}
|
||||
selectedVoice = index;
|
||||
return true;
|
||||
}
|
||||
if (y >= entryY && y < entryY + height && entry.message().kind() == ChatHistory.Kind.STICKER
|
||||
&& HistoryClient.texture(entry) == null) {
|
||||
requestedImages.remove(entry.id());
|
||||
return true;
|
||||
}
|
||||
entryY += height;
|
||||
}
|
||||
}
|
||||
return super.mouseClicked(x, y, button);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean keyPressed(int key, int scan, int modifiers) {
|
||||
if (!date.isFocused()) {
|
||||
if (key == GLFW.GLFW_KEY_LEFT_BRACKET || key == GLFW.GLFW_KEY_RIGHT_BRACKET) {
|
||||
List<ChatHistory.Entry> entries = HistoryClient.page().entries();
|
||||
int step = key == GLFW.GLFW_KEY_LEFT_BRACKET ? -1 : 1;
|
||||
int start = selectedVoice < 0 ? (step > 0 ? -1 : entries.size()) : selectedVoice;
|
||||
for (int i = start + step; i >= 0 && i < entries.size(); i += step) {
|
||||
if (entries.get(i).message().kind() == ChatHistory.Kind.VOICE) {
|
||||
HistoryClient.cancelAttachment();
|
||||
HistoryVoice.stop();
|
||||
selectedVoice = i;
|
||||
int selectedTop = 0;
|
||||
for (int preceding = 0; preceding < i; preceding++) {
|
||||
selectedTop += rows.get(preceding).height();
|
||||
}
|
||||
scroll = Math.clamp(selectedTop, 0, maxScroll());
|
||||
minecraft.getNarrator().sayNow(Component.translatable(
|
||||
"wowmine_stickers.history.selected_voice", entries.get(i).message().name()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (key == GLFW.GLFW_KEY_UP || key == GLFW.GLFW_KEY_PAGE_UP) {
|
||||
scrollBy(key == GLFW.GLFW_KEY_UP ? -LINE : -viewport());
|
||||
return true;
|
||||
}
|
||||
if (key == GLFW.GLFW_KEY_DOWN || key == GLFW.GLFW_KEY_PAGE_DOWN) {
|
||||
scrollBy(key == GLFW.GLFW_KEY_DOWN ? LINE : viewport());
|
||||
return true;
|
||||
}
|
||||
} else if (key == GLFW.GLFW_KEY_ENTER || key == GLFW.GLFW_KEY_KP_ENTER) {
|
||||
jump();
|
||||
return true;
|
||||
}
|
||||
return super.keyPressed(key, scan, modifiers);
|
||||
}
|
||||
|
||||
@Override public void onClose() { minecraft.setScreen(new ChatScreen(draft)); }
|
||||
@Override public void removed() { HistoryClient.close(); }
|
||||
@Override public boolean isPauseScreen() { return false; }
|
||||
|
||||
private record Row(ChatHistory.Entry entry, List<FormattedCharSequence> lines, int height) {}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import it.unimi.dsi.fastutil.floats.FloatList;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.neoforged.fml.ModList;
|
||||
import net.wowmine.stickers.ChatHistory;
|
||||
import net.wowmine.stickers.VoiceFrames;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import ru.dimaskama.voicemessages.VoiceMessagesMod;
|
||||
import ru.dimaskama.voicemessages.client.Playback;
|
||||
import ru.dimaskama.voicemessages.client.PlaybackManager;
|
||||
import ru.dimaskama.voicemessages.client.backend.VoiceBackend;
|
||||
import ru.dimaskama.voicemessages.client.backend.VoiceBackends;
|
||||
|
||||
/** Client-thread facade. The owning screen must call stop on close, page change and disconnect. */
|
||||
public final class HistoryVoice {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(HistoryVoice.class);
|
||||
private static long unavailableEntry = -1;
|
||||
|
||||
private HistoryVoice() {}
|
||||
|
||||
private static boolean installed() {
|
||||
return ModList.get().isLoaded("voicemessages");
|
||||
}
|
||||
|
||||
public static boolean available() {
|
||||
return installed() && Supported.available();
|
||||
}
|
||||
|
||||
public static void toggle(long entry, byte[] packedFrames) {
|
||||
unavailableEntry = -1;
|
||||
if (!available()) {
|
||||
stop();
|
||||
unavailableEntry = entry;
|
||||
return;
|
||||
}
|
||||
Supported.toggle(entry, packedFrames);
|
||||
}
|
||||
|
||||
public static boolean isPlaying(long entry) {
|
||||
return installed() && Supported.entry == entry && Supported.owned != null && Supported.owned.isPlaying();
|
||||
}
|
||||
|
||||
public static boolean isLoading(long entry) {
|
||||
return installed() && Supported.entry == entry && Supported.loading;
|
||||
}
|
||||
|
||||
public static float progress(long entry) {
|
||||
return installed() && Supported.entry == entry && Supported.owned != null
|
||||
? Math.clamp(Supported.owned.getProgress(), 0.0F, 1.0F) : 0.0F;
|
||||
}
|
||||
|
||||
public static Component error(long entry) {
|
||||
if (entry == unavailableEntry) {
|
||||
return Component.translatable("wowmine_stickers.history.voice.unavailable");
|
||||
}
|
||||
return installed() && Supported.entry == entry ? Supported.failure : Component.empty();
|
||||
}
|
||||
|
||||
public static void stop() {
|
||||
unavailableEntry = -1;
|
||||
if (installed()) {
|
||||
Supported.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/** No upstream class is resolved by the facade when VoiceMessages is absent. */
|
||||
private static final class Supported {
|
||||
private static final ThreadPoolExecutor DECODER = new ThreadPoolExecutor(
|
||||
1, 1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1), runnable -> {
|
||||
Thread thread = new Thread(runnable, "WowmineArchiveVoiceDecoder");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
private static volatile long generation;
|
||||
private static long entry = -1;
|
||||
private static boolean loading;
|
||||
private static Component failure = Component.empty();
|
||||
private static Future<?> request;
|
||||
private static Playback owned;
|
||||
|
||||
private static boolean available() {
|
||||
return VoiceMessagesMod.isClientActive();
|
||||
}
|
||||
|
||||
private static void toggle(long selected, byte[] packedFrames) {
|
||||
if (entry == selected && owned != null) {
|
||||
try {
|
||||
if (owned.isPlaying()) {
|
||||
owned.stop();
|
||||
} else {
|
||||
PlaybackManager.MAIN.play(owned);
|
||||
}
|
||||
} catch (RuntimeException error) {
|
||||
failed(generation, "playback_failed", error);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (entry == selected && loading) {
|
||||
stop();
|
||||
return;
|
||||
}
|
||||
stop();
|
||||
entry = selected;
|
||||
if (packedFrames == null || packedFrames.length == 0 || packedFrames.length > ChatHistory.MEDIA_BYTES) {
|
||||
failure = Component.translatable("wowmine_stickers.history.voice.invalid");
|
||||
return;
|
||||
}
|
||||
byte[] snapshot = packedFrames.clone();
|
||||
long expected = generation;
|
||||
try {
|
||||
VoiceBackend backend = VoiceBackends.get();
|
||||
loading = true;
|
||||
// stop clears the sole queued request; at most one stale decoder can still be unwinding.
|
||||
request = DECODER.submit(() -> decode(expected, snapshot, backend));
|
||||
} catch (RuntimeException error) {
|
||||
failed(expected, "decode_failed", error);
|
||||
}
|
||||
}
|
||||
|
||||
private static void decode(long expected, byte[] packed, VoiceBackend backend) {
|
||||
List<byte[]> frames;
|
||||
try {
|
||||
frames = VoiceFrames.decode(packed);
|
||||
} catch (IllegalArgumentException error) {
|
||||
postFailure(expected, "invalid", error);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
List<short[]> audio = new ArrayList<>(frames.size());
|
||||
try (VoiceBackend.Decoder decoder = backend.createDecoder()) {
|
||||
for (byte[] frame : frames) {
|
||||
if (generation != expected || Thread.currentThread().isInterrupted()) {
|
||||
return;
|
||||
}
|
||||
short[] decoded = decoder.decode(frame);
|
||||
if (decoded == null || decoded.length != 960) {
|
||||
throw new IllegalArgumentException("Archive voice frame is not 20ms mono at 48kHz");
|
||||
}
|
||||
audio.add(decoded.clone());
|
||||
}
|
||||
}
|
||||
if (generation != expected || Thread.currentThread().isInterrupted()) {
|
||||
return;
|
||||
}
|
||||
FloatList levels = Playback.calculateAudioLevels(audio);
|
||||
List<short[]> completed = List.copyOf(audio);
|
||||
Minecraft.getInstance().execute(() -> {
|
||||
if (generation != expected) {
|
||||
return;
|
||||
}
|
||||
loading = false;
|
||||
request = null;
|
||||
try {
|
||||
owned = new Playback(observedOutput(backend.createOutput(), expected), completed, levels);
|
||||
PlaybackManager.MAIN.play(owned);
|
||||
} catch (RuntimeException error) {
|
||||
failed(expected, "playback_failed", error);
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException error) {
|
||||
postFailure(expected, "decode_failed", error);
|
||||
}
|
||||
}
|
||||
|
||||
private static VoiceBackend.AudioOutput observedOutput(VoiceBackend.AudioOutput output, long expected) {
|
||||
return new VoiceBackend.AudioOutput() {
|
||||
@Override
|
||||
public void play(short[] frame) {
|
||||
try {
|
||||
output.play(frame);
|
||||
} catch (RuntimeException error) {
|
||||
postFailure(expected, "playback_failed", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
try {
|
||||
output.stop();
|
||||
} catch (RuntimeException error) {
|
||||
postFailure(expected, "playback_failed", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static void postFailure(long expected, String key, RuntimeException error) {
|
||||
LOGGER.warn("Archive voice operation failed: {}", key, error);
|
||||
Minecraft.getInstance().execute(() -> {
|
||||
if (generation == expected) {
|
||||
failed(expected, key, null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void failed(long expected, String key, RuntimeException error) {
|
||||
if (generation != expected) {
|
||||
return;
|
||||
}
|
||||
if (error != null) {
|
||||
LOGGER.warn("Archive voice operation failed: {}", key, error);
|
||||
}
|
||||
long selected = entry;
|
||||
stop();
|
||||
entry = selected;
|
||||
failure = Component.translatable("wowmine_stickers.history.voice." + key);
|
||||
}
|
||||
|
||||
private static void stop() {
|
||||
generation++;
|
||||
if (request != null) {
|
||||
request.cancel(true);
|
||||
request = null;
|
||||
}
|
||||
DECODER.getQueue().clear();
|
||||
Playback playback = owned;
|
||||
owned = null;
|
||||
loading = false;
|
||||
entry = -1;
|
||||
failure = Component.empty();
|
||||
if (playback != null) {
|
||||
// MAIN may now be playing a live message. Stop/remove only our own object.
|
||||
playback.stop();
|
||||
PlaybackManager.MAIN.remove(playback);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.texture.DynamicTexture;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.neoforged.neoforge.network.PacketDistributor;
|
||||
import net.wowmine.stickers.StickerCatalog;
|
||||
import net.wowmine.stickers.StickerPackets;
|
||||
|
||||
/** Session-local, content-addressed cache; all calls run on the client thread. */
|
||||
final class StickerAssets {
|
||||
private static final int MAX_TRANSFERS = 1;
|
||||
private static final int MAX_TEXTURES = 32;
|
||||
private static final int TEXTURE_BYTES = 64 * 1024 * 1024;
|
||||
private static final int CACHE_BYTES = 8 * 1024 * 1024;
|
||||
private final LinkedHashMap<String, Texture> textures = new LinkedHashMap<>(32, 0.75F, true);
|
||||
private final LinkedHashMap<String, byte[]> cache = new LinkedHashMap<>(32, 0.75F, true);
|
||||
private final Map<String, Transfer> transfers = new HashMap<>();
|
||||
private final Map<String, Component> failures = new HashMap<>();
|
||||
private final ArrayDeque<StickerCatalog.Sticker> queue = new ArrayDeque<>();
|
||||
private int textureBytes;
|
||||
private int cacheBytes;
|
||||
|
||||
@Nullable
|
||||
ResourceLocation get(StickerCatalog.Sticker sticker) {
|
||||
Texture texture = textures.get(sticker.id());
|
||||
if (texture != null) {
|
||||
return texture.location();
|
||||
}
|
||||
if (!failures.containsKey(sticker.id()) && !transfers.containsKey(sticker.id())) {
|
||||
queue.removeIf(s -> s.id().equals(sticker.id()));
|
||||
if (queue.size() == 64) {
|
||||
queue.removeLast();
|
||||
}
|
||||
queue.addFirst(sticker);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Component status(String id) {
|
||||
return failures.getOrDefault(id, Component.translatable("wowmine_stickers.asset.loading"));
|
||||
}
|
||||
|
||||
boolean failed(String id) {
|
||||
return failures.containsKey(id);
|
||||
}
|
||||
|
||||
void retry(StickerCatalog.Sticker sticker) {
|
||||
failures.remove(sticker.id());
|
||||
get(sticker);
|
||||
}
|
||||
|
||||
void problem(StickerPackets.AssetProblem problem) {
|
||||
if (transfers.remove(problem.id()) != null) {
|
||||
failures.put(problem.id(), Component.translatable(
|
||||
"wowmine_stickers.asset.problem", Component.translatable(problem.reason())));
|
||||
}
|
||||
}
|
||||
|
||||
void tick() {
|
||||
long now = System.nanoTime();
|
||||
transfers.entrySet().removeIf(entry -> {
|
||||
if (now - entry.getValue().started > 20_000_000_000L) {
|
||||
failures.put(entry.getKey(), Component.translatable("wowmine_stickers.asset.timeout"));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
if (!StickerClient.channelsAvailable() || queue.isEmpty() || transfers.size() >= MAX_TRANSFERS) {
|
||||
return;
|
||||
}
|
||||
StickerCatalog.Sticker sticker = queue.removeFirst();
|
||||
byte[] bytes = cache.get(sticker.id());
|
||||
if (bytes != null) {
|
||||
upload(sticker, bytes);
|
||||
} else {
|
||||
transfers.put(sticker.id(), new Transfer(sticker));
|
||||
PacketDistributor.sendToServer(new StickerPackets.AssetRequest(sticker.id()));
|
||||
}
|
||||
}
|
||||
|
||||
void receive(StickerPackets.AssetChunk chunk) {
|
||||
Transfer transfer = transfers.get(chunk.id());
|
||||
if (transfer == null) {
|
||||
return;
|
||||
}
|
||||
byte[] bytes = chunk.bytes();
|
||||
if (chunk.part() != transfer.next || (transfer.next > 0 && chunk.total() != transfer.total)
|
||||
|| transfer.bytes.size() + bytes.length > StickerCatalog.MAX_ASSET_BYTES) {
|
||||
transfers.remove(chunk.id());
|
||||
failures.put(chunk.id(), Component.translatable("wowmine_stickers.asset.invalid"));
|
||||
return;
|
||||
}
|
||||
transfer.total = chunk.total();
|
||||
transfer.bytes.writeBytes(bytes);
|
||||
transfer.next++;
|
||||
if (transfer.next == transfer.total) {
|
||||
transfers.remove(chunk.id());
|
||||
byte[] png = transfer.bytes.toByteArray();
|
||||
if (upload(transfer.sticker, png)) {
|
||||
while (!cache.isEmpty() && cacheBytes + png.length > CACHE_BYTES) {
|
||||
String oldest = cache.keySet().iterator().next();
|
||||
cacheBytes -= cache.remove(oldest).length;
|
||||
}
|
||||
byte[] previous = cache.put(chunk.id(), png);
|
||||
cacheBytes += png.length - (previous == null ? 0 : previous.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean upload(StickerCatalog.Sticker sticker, byte[] bytes) {
|
||||
try {
|
||||
StickerPng.verify(bytes, sticker);
|
||||
NativeImage image = NativeImage.read(new ByteArrayInputStream(bytes));
|
||||
if (image.getWidth() != sticker.width() || image.getHeight() != sticker.height()) {
|
||||
image.close();
|
||||
throw new IOException("Decoded image dimensions differ from IHDR");
|
||||
}
|
||||
int size = sticker.width() * sticker.height() * 4;
|
||||
while (!textures.isEmpty()
|
||||
&& (textures.size() >= MAX_TEXTURES || textureBytes + size > TEXTURE_BYTES)) {
|
||||
String oldest = textures.keySet().iterator().next();
|
||||
Texture removed = textures.remove(oldest);
|
||||
Minecraft.getInstance().getTextureManager().release(removed.location());
|
||||
textureBytes -= removed.bytes();
|
||||
}
|
||||
ResourceLocation location = ResourceLocation.fromNamespaceAndPath(
|
||||
"wowmine_stickers", "cache/" + sticker.id());
|
||||
Minecraft.getInstance().getTextureManager().register(location, new DynamicTexture(image));
|
||||
textures.put(sticker.id(), new Texture(location, size));
|
||||
textureBytes += size;
|
||||
return true;
|
||||
} catch (IOException invalid) {
|
||||
failures.put(sticker.id(), Component.translatable("wowmine_stickers.asset.invalid"));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void clear() {
|
||||
for (Texture texture : textures.values()) {
|
||||
Minecraft.getInstance().getTextureManager().release(texture.location());
|
||||
}
|
||||
textures.clear();
|
||||
cache.clear();
|
||||
transfers.clear();
|
||||
failures.clear();
|
||||
queue.clear();
|
||||
textureBytes = 0;
|
||||
cacheBytes = 0;
|
||||
}
|
||||
|
||||
private record Texture(ResourceLocation location, int bytes) {}
|
||||
|
||||
private static final class Transfer {
|
||||
private final StickerCatalog.Sticker sticker;
|
||||
private final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
private final long started = System.nanoTime();
|
||||
private int next;
|
||||
private int total;
|
||||
|
||||
private Transfer(StickerCatalog.Sticker sticker) {
|
||||
this.sticker = sticker;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.AbstractButton;
|
||||
import net.minecraft.client.gui.narration.NarrationElementOutput;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
/** Original ten-pixel folded-sticker glyph; no VoiceMessages artwork. */
|
||||
final class StickerButton extends AbstractButton {
|
||||
private static final String[] PIXELS = {
|
||||
"1111111000", "1000001100", "1000001010", "1010101111", "1000000001",
|
||||
"1000000001", "1010000101", "1001111001", "1000000001", "1111111111"
|
||||
};
|
||||
private final Runnable action;
|
||||
|
||||
StickerButton(int x, int y, Runnable action) {
|
||||
super(x, y, 14, 14, Component.translatable("wowmine_stickers.open"));
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPress() {
|
||||
action.run();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float tick) {
|
||||
int color = active ? (isHoveredOrFocused() ? 0xFFFFFFA0 : 0xFFFFFFFF) : 0xFF777777;
|
||||
if (isFocused()) {
|
||||
graphics.renderOutline(getX(), getY(), 14, 14, color);
|
||||
}
|
||||
for (int y = 0; y < PIXELS.length; y++) {
|
||||
for (int x = 0; x < PIXELS[y].length(); x++) {
|
||||
if (PIXELS[y].charAt(x) == '1') {
|
||||
graphics.fill(getX() + x + 2, getY() + y + 2,
|
||||
getX() + x + 3, getY() + y + 3, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void updateWidgetNarration(NarrationElementOutput output) {
|
||||
defaultButtonNarrationText(output);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.ClientPacketListener;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.neoforged.neoforge.network.PacketDistributor;
|
||||
import net.wowmine.stickers.StickerCatalog;
|
||||
import net.wowmine.stickers.StickerPackets;
|
||||
|
||||
/** Network callbacks are registered by the mod and delivered on the client thread. */
|
||||
public final class StickerClient {
|
||||
static final StickerAssets ASSETS = new StickerAssets();
|
||||
private static final Gson GSON = new Gson();
|
||||
private static StickerCatalog catalog = new StickerCatalog(1, java.util.List.of());
|
||||
private static final ArrayDeque<StickerPackets.StickerMessage> pending = new ArrayDeque<>();
|
||||
private static boolean requested;
|
||||
private static boolean ready;
|
||||
private static boolean importing;
|
||||
private static String importDraft = "";
|
||||
private static Component importStatus = Component.empty();
|
||||
private static Component status = Component.translatable("wowmine_stickers.unavailable");
|
||||
|
||||
private StickerClient() {}
|
||||
|
||||
static boolean channelsAvailable() {
|
||||
ClientPacketListener connection = Minecraft.getInstance().getConnection();
|
||||
return connection != null && connection.hasChannel(StickerPackets.CatalogRequest.TYPE)
|
||||
&& connection.hasChannel(StickerPackets.AssetRequest.TYPE)
|
||||
&& connection.hasChannel(StickerPackets.SendSticker.TYPE);
|
||||
}
|
||||
|
||||
static boolean available() {
|
||||
return ready && channelsAvailable();
|
||||
}
|
||||
|
||||
static void tick() {
|
||||
if (!requested && channelsAvailable()) {
|
||||
requested = true;
|
||||
status = Component.translatable("wowmine_stickers.catalog.loading");
|
||||
PacketDistributor.sendToServer(new StickerPackets.CatalogRequest());
|
||||
}
|
||||
ASSETS.tick();
|
||||
}
|
||||
|
||||
public static void onCatalog(StickerPackets.CatalogReply reply) {
|
||||
StickerCatalog parsed;
|
||||
try {
|
||||
if (reply.json().getBytes(StandardCharsets.UTF_8).length > StickerCatalog.MAX_CATALOG_BYTES) {
|
||||
throw new IllegalArgumentException("Catalog byte limit");
|
||||
}
|
||||
parsed = GSON.fromJson(reply.json(), StickerCatalog.class);
|
||||
Map<String, Integer> frames = new HashMap<>();
|
||||
for (StickerCatalog.Pack pack : parsed.packs()) {
|
||||
for (StickerCatalog.Sticker sticker : pack.stickers()) {
|
||||
Integer previous = frames.putIfAbsent(sticker.id(), sticker.frames());
|
||||
if (previous != null && previous != sticker.frames()) {
|
||||
throw new IllegalArgumentException("Conflicting asset metadata");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException invalid) {
|
||||
// Gson wraps record-constructor failures in RuntimeException.
|
||||
ready = false;
|
||||
status = Component.translatable("wowmine_stickers.catalog.invalid");
|
||||
return;
|
||||
}
|
||||
catalog = parsed;
|
||||
ready = true;
|
||||
status = Component.translatable("wowmine_stickers.open");
|
||||
StickerClientEvents.catalogChanged();
|
||||
while (!pending.isEmpty()) {
|
||||
display(pending.removeFirst());
|
||||
}
|
||||
}
|
||||
|
||||
public static void onAssetChunk(StickerPackets.AssetChunk chunk) {
|
||||
ASSETS.receive(chunk);
|
||||
}
|
||||
|
||||
public static void onAssetProblem(StickerPackets.AssetProblem problem) {
|
||||
ASSETS.problem(problem);
|
||||
}
|
||||
|
||||
public static void onMessage(StickerPackets.StickerMessage message) {
|
||||
if (!ready) {
|
||||
if (pending.size() == 100) {
|
||||
pending.removeFirst();
|
||||
}
|
||||
pending.addLast(message);
|
||||
return;
|
||||
}
|
||||
display(message);
|
||||
}
|
||||
|
||||
private static void display(StickerPackets.StickerMessage message) {
|
||||
catalog.find(message.id()).ifPresentOrElse(sticker -> {
|
||||
var sender = Component.literal(message.name() + ": ");
|
||||
Minecraft.getInstance().gui.getChat().addMessage(
|
||||
sender.append(Component.translatable("wowmine_stickers.message")),
|
||||
null, StickerRows.tag(sticker));
|
||||
}, () -> Minecraft.getInstance().gui.getChat().addMessage(
|
||||
Component.translatable("wowmine_stickers.message.unknown", message.name())));
|
||||
}
|
||||
|
||||
public static void onImportStatus(StickerPackets.ImportStatus reply) {
|
||||
importing = reply.state().equals("queued") || reply.state().equals("importing");
|
||||
String key = switch (reply.state()) {
|
||||
case "queued" -> "wowmine_stickers.import.queued";
|
||||
case "importing" -> "wowmine_stickers.import.importing";
|
||||
case "ready" -> "wowmine_stickers.import.ready";
|
||||
case "error" -> "wowmine_stickers.import.error";
|
||||
default -> "wowmine_stickers.import.error";
|
||||
};
|
||||
var text = Component.translatable(key, reply.pack());
|
||||
if (!reply.detail().isBlank() && !reply.detail().equals(key)) {
|
||||
text.append(" ").append(Component.translatable(reply.detail(), reply.pack()));
|
||||
}
|
||||
importStatus = text;
|
||||
if (reply.state().equals("ready") && channelsAvailable()) {
|
||||
PacketDistributor.sendToServer(new StickerPackets.CatalogRequest());
|
||||
}
|
||||
}
|
||||
|
||||
static boolean canImport() {
|
||||
ClientPacketListener connection = Minecraft.getInstance().getConnection();
|
||||
return available() && connection != null
|
||||
&& connection.hasChannel(StickerPackets.ImportPack.TYPE) && !importing;
|
||||
}
|
||||
|
||||
static void importPack() {
|
||||
if (canImport() && !importDraft.isBlank()) {
|
||||
importing = true;
|
||||
importStatus = Component.translatable("wowmine_stickers.import.queued", "");
|
||||
PacketDistributor.sendToServer(new StickerPackets.ImportPack(importDraft));
|
||||
}
|
||||
}
|
||||
|
||||
static void send(StickerCatalog.Sticker sticker) {
|
||||
if (available()) {
|
||||
PacketDistributor.sendToServer(new StickerPackets.SendSticker(sticker.id()));
|
||||
}
|
||||
}
|
||||
|
||||
static StickerCatalog catalog() { return catalog; }
|
||||
static Component status() { return status; }
|
||||
static Component importStatus() { return importStatus; }
|
||||
static String importDraft() { return importDraft; }
|
||||
static void importDraft(String value) { importDraft = value; }
|
||||
|
||||
static void disconnect() {
|
||||
ASSETS.clear();
|
||||
pending.clear();
|
||||
catalog = new StickerCatalog(1, java.util.List.of());
|
||||
ready = false;
|
||||
requested = false;
|
||||
importing = false;
|
||||
importDraft = "";
|
||||
importStatus = Component.empty();
|
||||
status = Component.translatable("wowmine_stickers.unavailable");
|
||||
StickerClientEvents.disconnect();
|
||||
}
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.client.gui.components.Tooltip;
|
||||
import net.minecraft.client.gui.screens.ChatScreen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.neoforged.api.distmarker.Dist;
|
||||
import net.neoforged.bus.api.EventPriority;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.fml.common.EventBusSubscriber;
|
||||
import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent;
|
||||
import net.neoforged.neoforge.client.event.ClientTickEvent;
|
||||
import net.neoforged.neoforge.client.event.RenderFrameEvent;
|
||||
import net.neoforged.neoforge.client.event.ScreenEvent;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
|
||||
@EventBusSubscriber(modid = "wowmine_stickers", value = Dist.CLIENT)
|
||||
public final class StickerClientEvents {
|
||||
@Nullable private static ChatScreen chat;
|
||||
@Nullable private static StickerButton button;
|
||||
@Nullable private static StickerPicker picker;
|
||||
private static Component buttonStatus = Component.empty();
|
||||
|
||||
private StickerClientEvents() {}
|
||||
|
||||
public interface ChatInput {
|
||||
EditBox wowmine_stickers$input();
|
||||
}
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.LOWEST)
|
||||
public static void init(ScreenEvent.Init.Post event) {
|
||||
if (!(event.getScreen() instanceof ChatScreen screen)) {
|
||||
return;
|
||||
}
|
||||
chat = screen;
|
||||
picker = null;
|
||||
EditBox input = ((ChatInput) screen).wowmine_stickers$input();
|
||||
button = new StickerButton(input.getX() - 3, input.getY() - 3, StickerClientEvents::toggle);
|
||||
input.setX(input.getX() + 14);
|
||||
input.setWidth(Math.max(1, input.getWidth() - 14));
|
||||
event.addListener(button);
|
||||
buttonStatus = Component.empty();
|
||||
updateButton();
|
||||
}
|
||||
|
||||
public static boolean hasButton(ChatScreen screen) {
|
||||
return screen == chat && button != null;
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void tick(ClientTickEvent.Post event) {
|
||||
StickerClient.tick();
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void frame(RenderFrameEvent.Pre event) {
|
||||
StickerImages.beginFrame();
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void logout(ClientPlayerNetworkEvent.LoggingOut event) {
|
||||
StickerClient.disconnect();
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void render(ScreenEvent.Render.Post event) {
|
||||
if (event.getScreen() == chat && button != null) {
|
||||
updateButton();
|
||||
if (picker != null) {
|
||||
picker.render(event.getGuiGraphics(), event.getMouseX(), event.getMouseY(), event.getPartialTick());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void updateButton() {
|
||||
if (button != null) {
|
||||
button.active = StickerClient.available();
|
||||
Component current = StickerClient.channelsAvailable()
|
||||
? StickerClient.status() : Component.translatable("wowmine_stickers.unavailable");
|
||||
if (picker != null) {
|
||||
buttonStatus = Component.empty();
|
||||
button.setTooltip(null);
|
||||
} else if (!current.equals(buttonStatus)) {
|
||||
buttonStatus = current;
|
||||
button.setTooltip(Tooltip.create(current));
|
||||
}
|
||||
if (!button.active) {
|
||||
picker = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void toggle() {
|
||||
if (chat != null && button != null && StickerClient.available()) {
|
||||
if (picker == null) {
|
||||
picker = new StickerPicker(chat, button, StickerClientEvents::close);
|
||||
button.setTooltip(null);
|
||||
buttonStatus = Component.empty();
|
||||
((ChatInput) chat).wowmine_stickers$input().setFocused(false);
|
||||
} else {
|
||||
close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void close() {
|
||||
picker = null;
|
||||
if (chat != null) {
|
||||
chat.setFocused(((ChatInput) chat).wowmine_stickers$input());
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.HIGHEST)
|
||||
public static void mouse(ScreenEvent.MouseButtonPressed.Pre event) {
|
||||
if (event.getScreen() == chat && picker != null && button != null) {
|
||||
if (button.isMouseOver(event.getMouseX(), event.getMouseY())) {
|
||||
return;
|
||||
}
|
||||
if (picker.contains(event.getMouseX(), event.getMouseY())) {
|
||||
picker.click(event.getMouseX(), event.getMouseY(), event.getButton());
|
||||
} else {
|
||||
close();
|
||||
}
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.HIGHEST)
|
||||
public static void scroll(ScreenEvent.MouseScrolled.Pre event) {
|
||||
if (event.getScreen() == chat && picker != null
|
||||
&& picker.scroll(event.getMouseX(), event.getMouseY(), event.getScrollDeltaY())) {
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.HIGHEST)
|
||||
public static void key(ScreenEvent.KeyPressed.Pre event) {
|
||||
if (event.getScreen() != chat) {
|
||||
return;
|
||||
}
|
||||
if (picker != null) {
|
||||
picker.key(event.getKeyCode(), event.getScanCode(), event.getModifiers());
|
||||
event.setCanceled(true);
|
||||
} else if (event.getKeyCode() == GLFW.GLFW_KEY_S
|
||||
&& (event.getModifiers() & GLFW.GLFW_MOD_ALT) != 0 && StickerClient.available()) {
|
||||
toggle();
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.HIGHEST)
|
||||
public static void character(ScreenEvent.CharacterTyped.Pre event) {
|
||||
if (event.getScreen() == chat && picker != null) {
|
||||
picker.character(event.getCodePoint(), event.getModifiers());
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void opening(ScreenEvent.Opening event) {
|
||||
if (event.getCurrentScreen() == chat && event.getNewScreen() != chat) {
|
||||
picker = null;
|
||||
}
|
||||
}
|
||||
|
||||
static void catalogChanged() {
|
||||
if (picker != null) {
|
||||
picker.catalogChanged();
|
||||
}
|
||||
}
|
||||
|
||||
static void disconnect() {
|
||||
picker = null;
|
||||
chat = null;
|
||||
button = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import java.util.List;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.wowmine.stickers.StickerCatalog;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
|
||||
final class StickerGrid {
|
||||
private static final int CELL = 44;
|
||||
private List<StickerCatalog.Sticker> stickers = List.of();
|
||||
private String packId = "";
|
||||
private int x;
|
||||
private int y;
|
||||
private int width;
|
||||
private int columns = 1;
|
||||
private int rows = 1;
|
||||
private int firstRow;
|
||||
private int selected;
|
||||
|
||||
void clear() {
|
||||
stickers = List.of();
|
||||
packId = "";
|
||||
selected = 0;
|
||||
firstRow = 0;
|
||||
}
|
||||
|
||||
void pack(StickerCatalog.Pack pack) {
|
||||
if (!pack.id().equals(packId)) {
|
||||
selected = 0;
|
||||
firstRow = 0;
|
||||
}
|
||||
packId = pack.id();
|
||||
stickers = pack.stickers();
|
||||
selected = Math.min(selected, Math.max(0, stickers.size() - 1));
|
||||
reveal();
|
||||
}
|
||||
|
||||
void bounds(int left, int top, int availableWidth, int availableHeight) {
|
||||
x = left;
|
||||
y = top;
|
||||
width = availableWidth;
|
||||
columns = Math.max(1, availableWidth / CELL);
|
||||
rows = Math.max(1, availableHeight / CELL);
|
||||
reveal();
|
||||
}
|
||||
|
||||
void render(GuiGraphics graphics, int mouseX, int mouseY, boolean focused) {
|
||||
var font = Minecraft.getInstance().font;
|
||||
if (stickers.isEmpty()) {
|
||||
Component empty = Component.translatable(StickerClient.catalog().packs().isEmpty()
|
||||
? "wowmine_stickers.packs.hint" : "wowmine_stickers.pack.empty");
|
||||
graphics.drawWordWrap(font, empty,
|
||||
x + 4, y + 6, width - 8, 0xFFE0E0E0);
|
||||
return;
|
||||
}
|
||||
int start = firstRow * columns;
|
||||
for (int index = start; index < Math.min(stickers.size(), start + rows * columns); index++) {
|
||||
int left = x + ((index - start) % columns) * CELL;
|
||||
int top = y + ((index - start) / columns) * CELL;
|
||||
boolean hovered = mouseX >= left && mouseX < left + CELL - 2
|
||||
&& mouseY >= top && mouseY < top + CELL - 2;
|
||||
if (hovered || (focused && index == selected)) {
|
||||
graphics.fill(left, top, left + CELL - 2, top + CELL - 2, 0xFF414141);
|
||||
}
|
||||
if (focused && index == selected) {
|
||||
graphics.renderOutline(left, top, CELL - 2, CELL - 2, 0xFFFFFFFF);
|
||||
}
|
||||
StickerCatalog.Sticker sticker = stickers.get(index);
|
||||
if (!StickerImages.render(graphics, sticker,
|
||||
new StickerImages.Rectangle(left + 5, top + 5, 32, 0, 32, 255))) {
|
||||
graphics.drawCenteredString(font, StickerClient.ASSETS.failed(sticker.id()) ? "!" : "...",
|
||||
left + 20, top + 17, 0xFFFFFFFF);
|
||||
}
|
||||
}
|
||||
int totalRows = (stickers.size() + columns - 1) / columns;
|
||||
if (totalRows > rows) {
|
||||
int track = rows * CELL - 2;
|
||||
int thumb = Math.max(8, track * rows / totalRows);
|
||||
int offset = (track - thumb) * firstRow / (totalRows - rows);
|
||||
graphics.fill(x + width - 2, y, x + width, y + track, 0xFF444444);
|
||||
graphics.fill(x + width - 2, y + offset, x + width, y + offset + thumb, 0xFFCCCCCC);
|
||||
}
|
||||
}
|
||||
|
||||
void tooltip(GuiGraphics graphics, int mouseX, int mouseY) {
|
||||
int index = indexAt(mouseX, mouseY);
|
||||
if (index >= 0) {
|
||||
StickerCatalog.Sticker sticker = stickers.get(index);
|
||||
Component text = StickerClient.ASSETS.failed(sticker.id())
|
||||
? StickerClient.ASSETS.status(sticker.id())
|
||||
: Component.translatable("wowmine_stickers.sticker", index + 1, sticker.emoji());
|
||||
graphics.renderTooltip(Minecraft.getInstance().font, text, mouseX, mouseY);
|
||||
}
|
||||
}
|
||||
|
||||
boolean contains(double mouseX, double mouseY) {
|
||||
return mouseX >= x && mouseX < x + width && mouseY >= y && mouseY < y + rows * CELL;
|
||||
}
|
||||
|
||||
private int indexAt(double mouseX, double mouseY) {
|
||||
if (!contains(mouseX, mouseY) || mouseX - x >= columns * CELL) {
|
||||
return -1;
|
||||
}
|
||||
int index = (firstRow + (int) (mouseY - y) / CELL) * columns + (int) (mouseX - x) / CELL;
|
||||
return index < stickers.size() ? index : -1;
|
||||
}
|
||||
|
||||
boolean click(double mouseX, double mouseY) {
|
||||
int index = indexAt(mouseX, mouseY);
|
||||
if (index < 0) {
|
||||
return false;
|
||||
}
|
||||
selected = index;
|
||||
return activate();
|
||||
}
|
||||
|
||||
boolean activate() {
|
||||
if (stickers.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
StickerCatalog.Sticker sticker = stickers.get(selected);
|
||||
if (StickerClient.ASSETS.failed(sticker.id())) {
|
||||
StickerClient.ASSETS.retry(sticker);
|
||||
} else if (StickerClient.ASSETS.get(sticker) != null && StickerClient.available()) {
|
||||
StickerClient.send(sticker);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void scroll(double delta) {
|
||||
int totalRows = (stickers.size() + columns - 1) / columns;
|
||||
firstRow = Math.clamp(firstRow - (int) Math.signum(delta), 0, Math.max(0, totalRows - rows));
|
||||
selected = Math.clamp(selected, firstRow * columns,
|
||||
Math.max(firstRow * columns, Math.min(stickers.size(), (firstRow + rows) * columns) - 1));
|
||||
}
|
||||
|
||||
void key(int key) {
|
||||
int before = selected;
|
||||
selected = switch (key) {
|
||||
case GLFW.GLFW_KEY_LEFT -> selected - 1;
|
||||
case GLFW.GLFW_KEY_RIGHT -> selected + 1;
|
||||
case GLFW.GLFW_KEY_UP -> selected - columns;
|
||||
case GLFW.GLFW_KEY_DOWN -> selected + columns;
|
||||
case GLFW.GLFW_KEY_PAGE_UP -> selected - columns * rows;
|
||||
case GLFW.GLFW_KEY_PAGE_DOWN -> selected + columns * rows;
|
||||
case GLFW.GLFW_KEY_HOME -> 0;
|
||||
case GLFW.GLFW_KEY_END -> stickers.size() - 1;
|
||||
default -> selected;
|
||||
};
|
||||
selected = Math.clamp(selected, 0, Math.max(0, stickers.size() - 1));
|
||||
if (key == GLFW.GLFW_KEY_R && !stickers.isEmpty()) {
|
||||
StickerClient.ASSETS.retry(stickers.get(selected));
|
||||
}
|
||||
reveal();
|
||||
if (selected != before) {
|
||||
Minecraft.getInstance().getNarrator().sayNow(selection());
|
||||
}
|
||||
}
|
||||
|
||||
Component selection() {
|
||||
if (stickers.isEmpty()) {
|
||||
return Component.translatable("wowmine_stickers.pack.empty");
|
||||
}
|
||||
StickerCatalog.Sticker sticker = stickers.get(selected);
|
||||
var announcement = Component.translatable("wowmine_stickers.sticker", selected + 1, sticker.emoji());
|
||||
if (StickerClient.ASSETS.failed(sticker.id())) {
|
||||
announcement.append(" ").append(StickerClient.ASSETS.status(sticker.id()));
|
||||
} else if (StickerClient.ASSETS.get(sticker) == null) {
|
||||
announcement.append(" ").append(Component.translatable("wowmine_stickers.asset.loading"));
|
||||
}
|
||||
return announcement;
|
||||
}
|
||||
|
||||
private void reveal() {
|
||||
int selectedRow = selected / columns;
|
||||
if (selectedRow < firstRow) {
|
||||
firstRow = selectedRow;
|
||||
} else if (selectedRow >= firstRow + rows) {
|
||||
firstRow = selectedRow - rows + 1;
|
||||
}
|
||||
firstRow = Math.min(firstRow, Math.max(0, (stickers.size() + columns - 1) / columns - rows));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
import com.mojang.blaze3d.vertex.BufferUploader;
|
||||
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
|
||||
import com.mojang.blaze3d.vertex.Tesselator;
|
||||
import com.mojang.blaze3d.vertex.VertexFormat;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.renderer.GameRenderer;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.wowmine.stickers.StickerCatalog;
|
||||
import org.joml.Matrix4f;
|
||||
|
||||
/** Fractional UVs keep sliced frames seamless at non-default chat spacing. */
|
||||
final class StickerImages {
|
||||
private static long animationFrame;
|
||||
|
||||
private StickerImages() {}
|
||||
|
||||
static void beginFrame() {
|
||||
animationFrame = System.nanoTime() / 50_000_000L;
|
||||
}
|
||||
|
||||
static boolean render(GuiGraphics graphics, StickerCatalog.Sticker sticker, Rectangle rectangle) {
|
||||
ResourceLocation texture = StickerClient.ASSETS.get(sticker);
|
||||
if (texture == null) {
|
||||
return false;
|
||||
}
|
||||
return render(graphics, sticker, rectangle, texture);
|
||||
}
|
||||
|
||||
static boolean render(GuiGraphics graphics, StickerCatalog.Sticker sticker, Rectangle rectangle,
|
||||
ResourceLocation texture) {
|
||||
int frame = (int) (animationFrame % sticker.frames());
|
||||
float u0 = (float) ((frame % sticker.columns()) * 128) / sticker.width();
|
||||
float u1 = u0 + 128.0F / sticker.width();
|
||||
float frameY = (frame / sticker.columns()) * 128.0F;
|
||||
float v0 = (frameY + rectangle.offset() * 128.0F / rectangle.size()) / sticker.height();
|
||||
float v1 = (frameY + (rectangle.offset() + rectangle.height()) * 128.0F / rectangle.size())
|
||||
/ sticker.height();
|
||||
graphics.flush();
|
||||
RenderSystem.enableBlend();
|
||||
RenderSystem.defaultBlendFunc();
|
||||
RenderSystem.setShader(GameRenderer::getPositionTexColorShader);
|
||||
RenderSystem.setShaderTexture(0, texture);
|
||||
Matrix4f pose = graphics.pose().last().pose();
|
||||
var buffer = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR);
|
||||
int x = rectangle.x();
|
||||
int y = rectangle.y();
|
||||
int right = x + rectangle.size();
|
||||
int bottom = y + rectangle.height();
|
||||
buffer.addVertex(pose, x, y, 0).setUv(u0, v0).setColor(255, 255, 255, rectangle.alpha());
|
||||
buffer.addVertex(pose, x, bottom, 0).setUv(u0, v1).setColor(255, 255, 255, rectangle.alpha());
|
||||
buffer.addVertex(pose, right, bottom, 0).setUv(u1, v1).setColor(255, 255, 255, rectangle.alpha());
|
||||
buffer.addVertex(pose, right, y, 0).setUv(u1, v0).setColor(255, 255, 255, rectangle.alpha());
|
||||
BufferUploader.drawWithShader(buffer.buildOrThrow());
|
||||
RenderSystem.disableBlend();
|
||||
return true;
|
||||
}
|
||||
|
||||
record Rectangle(int x, int y, int size, int offset, int height, int alpha) {}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import java.util.List;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.AbstractWidget;
|
||||
import net.minecraft.client.gui.components.Button;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.client.gui.components.Tooltip;
|
||||
import net.minecraft.client.gui.screens.ChatScreen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.wowmine.stickers.StickerCatalog;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
|
||||
/** Inline overlay: the original ChatScreen and its input draft stay alive. */
|
||||
final class StickerPicker {
|
||||
private final Runnable close;
|
||||
private final StickerGrid grid = new StickerGrid();
|
||||
private final EditBox url;
|
||||
private final Button add;
|
||||
private final Button previous;
|
||||
private final Button next;
|
||||
private final List<AbstractWidget> controls;
|
||||
private final int x;
|
||||
private final int y;
|
||||
private final int width;
|
||||
private final int height;
|
||||
private int packIndex;
|
||||
private int focus;
|
||||
|
||||
StickerPicker(ChatScreen screen, StickerButton anchor, Runnable close) {
|
||||
this.close = close;
|
||||
width = Math.min(260, screen.width - 8);
|
||||
height = Math.min(244, anchor.getY() - 6);
|
||||
x = Math.clamp(anchor.getX(), 4, Math.max(4, screen.width - width - 4));
|
||||
y = Math.max(4, anchor.getY() - height - 2);
|
||||
int footer = y + height - 82;
|
||||
url = new EditBox(Minecraft.getInstance().font, x + 6, footer + 12, width - 52, 18,
|
||||
Component.translatable("wowmine_stickers.import.url"));
|
||||
url.setMaxLength(256);
|
||||
url.setHint(Component.translatable("wowmine_stickers.import.hint"));
|
||||
url.setValue(StickerClient.importDraft());
|
||||
url.setResponder(StickerClient::importDraft);
|
||||
url.setTooltip(Tooltip.create(Component.translatable("wowmine_stickers.import.url")));
|
||||
add = Button.builder(Component.translatable("wowmine_stickers.import.add"), button -> StickerClient.importPack())
|
||||
.bounds(x + width - 42, footer + 12, 36, 18).build();
|
||||
previous = Button.builder(Component.literal("<"), button -> changePack(-1))
|
||||
.bounds(x + 5, y + 4, 16, 16).build();
|
||||
previous.setTooltip(Tooltip.create(Component.translatable("wowmine_stickers.pack.previous")));
|
||||
next = Button.builder(Component.literal(">"), button -> changePack(1))
|
||||
.bounds(x + width - 21, y + 4, 16, 16).build();
|
||||
next.setTooltip(Tooltip.create(Component.translatable("wowmine_stickers.pack.next")));
|
||||
controls = List.of(previous, next, url, add);
|
||||
grid.bounds(x + 6, y + 26, width - 12, Math.max(44, footer - y - 30));
|
||||
catalogChanged();
|
||||
setFocus(0);
|
||||
}
|
||||
|
||||
void catalogChanged() {
|
||||
var packs = StickerClient.catalog().packs();
|
||||
packIndex = Math.min(packIndex, Math.max(0, packs.size() - 1));
|
||||
if (!packs.isEmpty()) {
|
||||
grid.pack(packs.get(packIndex));
|
||||
} else {
|
||||
grid.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private void changePack(int delta) {
|
||||
var packs = StickerClient.catalog().packs();
|
||||
if (!packs.isEmpty()) {
|
||||
packIndex = Math.floorMod(packIndex + delta, packs.size());
|
||||
grid.pack(packs.get(packIndex));
|
||||
Minecraft.getInstance().getNarrator().sayNow(
|
||||
Component.literal(packs.get(packIndex).title()).append(" ").append(grid.selection()));
|
||||
}
|
||||
}
|
||||
|
||||
void render(GuiGraphics graphics, int mouseX, int mouseY, float tick) {
|
||||
var font = Minecraft.getInstance().font;
|
||||
graphics.pose().pushPose();
|
||||
// Vanilla tooltip backgrounds use layer 400; keep the panel below them.
|
||||
graphics.pose().translate(0, 0, 200);
|
||||
graphics.fill(x, y, x + width, y + height, 0xFF202020);
|
||||
graphics.renderOutline(x, y, width, height, 0xFFAAAAAA);
|
||||
var packs = StickerClient.catalog().packs();
|
||||
String title = packs.isEmpty()
|
||||
? Component.translatable("wowmine_stickers.packs.empty").getString()
|
||||
: packs.get(packIndex).title();
|
||||
graphics.drawCenteredString(font, font.plainSubstrByWidth(title, width - 50),
|
||||
x + width / 2, y + 8, 0xFFFFFFFF);
|
||||
grid.render(graphics, mouseX, mouseY, focus == 0);
|
||||
int footer = y + height - 82;
|
||||
graphics.drawString(font, Component.translatable("wowmine_stickers.import.url"),
|
||||
x + 6, footer, 0xFFFFFFFF);
|
||||
add.active = StickerClient.canImport() && !url.getValue().isBlank();
|
||||
previous.active = next.active = packs.size() > 1;
|
||||
for (AbstractWidget control : controls) {
|
||||
control.render(graphics, mouseX, mouseY, tick);
|
||||
}
|
||||
var lines = font.split(StickerClient.importStatus(), width - 12);
|
||||
for (int index = 0; index < Math.min(3, lines.size()); index++) {
|
||||
if (index == 2 && lines.size() > 3) {
|
||||
graphics.drawString(font, "...", x + 6, footer + 35 + index * 9, 0xFFE0E0E0);
|
||||
} else {
|
||||
graphics.drawString(font, lines.get(index), x + 6, footer + 35 + index * 9, 0xFFE0E0E0);
|
||||
}
|
||||
}
|
||||
graphics.drawString(font, Component.translatable("wowmine_stickers.picker.help"),
|
||||
x + 6, y + height - 11, 0xFFCCCCCC);
|
||||
grid.tooltip(graphics, mouseX, mouseY);
|
||||
if (mouseX >= x + 6 && mouseX < x + width - 6
|
||||
&& mouseY >= footer + 35 && mouseY < footer + 63 && !lines.isEmpty()) {
|
||||
graphics.renderTooltip(font, StickerClient.importStatus(), mouseX, mouseY);
|
||||
}
|
||||
graphics.pose().popPose();
|
||||
}
|
||||
|
||||
boolean contains(double mouseX, double mouseY) {
|
||||
return mouseX >= x && mouseX < x + width && mouseY >= y && mouseY < y + height;
|
||||
}
|
||||
|
||||
void click(double mouseX, double mouseY, int button) {
|
||||
for (int index = 0; index < controls.size(); index++) {
|
||||
AbstractWidget control = controls.get(index);
|
||||
if (control.isMouseOver(mouseX, mouseY)) {
|
||||
setFocus(index + 1);
|
||||
control.mouseClicked(mouseX, mouseY, button);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setFocus(0);
|
||||
if (button == 0 && grid.click(mouseX, mouseY)) {
|
||||
close.run();
|
||||
}
|
||||
}
|
||||
|
||||
boolean scroll(double mouseX, double mouseY, double delta) {
|
||||
if (grid.contains(mouseX, mouseY)) {
|
||||
grid.scroll(delta);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void key(int key, int scan, int modifiers) {
|
||||
if (key == GLFW.GLFW_KEY_ESCAPE) {
|
||||
close.run();
|
||||
} else if (key == GLFW.GLFW_KEY_TAB) {
|
||||
int direction = (modifiers & GLFW.GLFW_MOD_SHIFT) == 0 ? 1 : -1;
|
||||
int target = focus;
|
||||
do {
|
||||
target = Math.floorMod(target + direction, controls.size() + 1);
|
||||
} while (target != 0 && !controls.get(target - 1).active);
|
||||
setFocus(target);
|
||||
} else if ((modifiers & GLFW.GLFW_MOD_CONTROL) != 0
|
||||
&& (key == GLFW.GLFW_KEY_LEFT || key == GLFW.GLFW_KEY_RIGHT) && focus != 3) {
|
||||
changePack(key == GLFW.GLFW_KEY_LEFT ? -1 : 1);
|
||||
} else if (focus == 0) {
|
||||
if (key == GLFW.GLFW_KEY_ENTER || key == GLFW.GLFW_KEY_KP_ENTER || key == GLFW.GLFW_KEY_SPACE) {
|
||||
if (grid.activate()) {
|
||||
close.run();
|
||||
}
|
||||
} else {
|
||||
grid.key(key);
|
||||
}
|
||||
} else if (focus == 3 && (key == GLFW.GLFW_KEY_ENTER || key == GLFW.GLFW_KEY_KP_ENTER)) {
|
||||
StickerClient.importPack();
|
||||
} else {
|
||||
controls.get(focus - 1).keyPressed(key, scan, modifiers);
|
||||
}
|
||||
}
|
||||
|
||||
void character(char character, int modifiers) {
|
||||
if (focus == 3) {
|
||||
url.charTyped(character, modifiers);
|
||||
}
|
||||
}
|
||||
|
||||
private void setFocus(int index) {
|
||||
focus = index;
|
||||
for (int current = 0; current < controls.size(); current++) {
|
||||
controls.get(current).setFocused(current + 1 == index);
|
||||
}
|
||||
Component announcement = switch (index) {
|
||||
case 0 -> Component.translatable("wowmine_stickers.picker.grid")
|
||||
.append(" ").append(grid.selection());
|
||||
case 1 -> Component.translatable("wowmine_stickers.pack.previous");
|
||||
case 2 -> Component.translatable("wowmine_stickers.pack.next");
|
||||
default -> controls.get(index - 1).getMessage();
|
||||
};
|
||||
Minecraft.getInstance().getNarrator().sayNow(announcement);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import net.wowmine.stickers.StickerCatalog;
|
||||
|
||||
/** Checks the compressed-image boundary before allocating native image memory. */
|
||||
final class StickerPng {
|
||||
private StickerPng() {}
|
||||
|
||||
static void verify(byte[] bytes, StickerCatalog.Sticker sticker) throws IOException {
|
||||
if (bytes.length < 33 || bytes.length > StickerCatalog.MAX_ASSET_BYTES) {
|
||||
throw new IOException("Invalid PNG byte count");
|
||||
}
|
||||
ByteBuffer header = ByteBuffer.wrap(bytes);
|
||||
if (header.getLong() != 0x89504e470d0a1a0aL
|
||||
|| header.getInt() != 13 || header.getInt() != 0x49484452
|
||||
|| header.getInt() != sticker.width() || header.getInt() != sticker.height()) {
|
||||
throw new IOException("PNG dimensions do not match the manifest");
|
||||
}
|
||||
try {
|
||||
String digest = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
if (!digest.equals(sticker.id())) {
|
||||
throw new IOException("PNG content hash does not match the manifest");
|
||||
}
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new AssertionError("Java requires SHA-256", impossible);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package net.wowmine.stickers.client;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.minecraft.client.GuiMessage;
|
||||
import net.minecraft.client.GuiMessageTag;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.util.FormattedCharSequence;
|
||||
import net.wowmine.stickers.StickerCatalog;
|
||||
|
||||
/** Sticker slices participate in vanilla's normal line, history and fade machinery. */
|
||||
public final class StickerRows {
|
||||
private static final String PREFIX = "wowmine_stickers:";
|
||||
|
||||
private StickerRows() {}
|
||||
|
||||
static GuiMessageTag tag(StickerCatalog.Sticker sticker) {
|
||||
return new GuiMessageTag(0xA6C8FF, null, null,
|
||||
PREFIX + sticker.id() + ":" + sticker.frames());
|
||||
}
|
||||
|
||||
public static List<FormattedCharSequence> layout(
|
||||
List<FormattedCharSequence> original, GuiMessage message, int width) {
|
||||
GuiMessageTag tag = message.tag();
|
||||
if (tag == null || tag.logTag() == null || !tag.logTag().startsWith(PREFIX)) {
|
||||
return original;
|
||||
}
|
||||
String[] parts = tag.logTag().substring(PREFIX.length()).split(":", 2);
|
||||
if (parts.length != 2) {
|
||||
return original;
|
||||
}
|
||||
StickerCatalog.Sticker sticker;
|
||||
try {
|
||||
sticker = new StickerCatalog.Sticker(parts[0], "", Integer.parseInt(parts[1]));
|
||||
} catch (IllegalArgumentException invalidTag) {
|
||||
return original;
|
||||
}
|
||||
int size = Math.max(1, Math.min(96, width));
|
||||
int lineHeight = lineHeight();
|
||||
int rows = (size + lineHeight - 1) / lineHeight;
|
||||
List<FormattedCharSequence> result = new ArrayList<>(original);
|
||||
for (int index = 0; index < rows; index++) {
|
||||
result.add(new Row(sticker, size, index * lineHeight, Math.min(lineHeight, size - index * lineHeight)));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void render(GuiGraphics graphics, Row row, int y, int color) {
|
||||
double spacing = Minecraft.getInstance().options.chatLineSpacing().get();
|
||||
int baseline = (int) Math.round(-8.0 * (spacing + 1.0) + 4.0 * spacing);
|
||||
int top = y - baseline - lineHeight();
|
||||
if (!StickerImages.render(graphics, row.sticker(),
|
||||
new StickerImages.Rectangle(0, top, row.size(), row.offset(), row.height(), color >>> 24))) {
|
||||
if (row.offset() == 0) {
|
||||
Component text = StickerClient.ASSETS.status(row.sticker().id());
|
||||
var font = Minecraft.getInstance().font;
|
||||
graphics.drawString(font, font.plainSubstrByWidth(text.getString(), row.size()), 0, y, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static int lineHeight() {
|
||||
return (int) (9.0 * (Minecraft.getInstance().options.chatLineSpacing().get() + 1.0));
|
||||
}
|
||||
|
||||
public record Row(StickerCatalog.Sticker sticker, int size, int offset, int height)
|
||||
implements FormattedCharSequence {
|
||||
@Override
|
||||
public boolean accept(net.minecraft.util.FormattedCharSink sink) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package net.wowmine.stickers.mixin;
|
||||
|
||||
import com.llamalad7.mixinextras.injector.ModifyExpressionValue;
|
||||
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
|
||||
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
|
||||
import com.llamalad7.mixinextras.sugar.Local;
|
||||
import java.util.List;
|
||||
import net.minecraft.client.GuiMessage;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.gui.GuiGraphics;
|
||||
import net.minecraft.client.gui.components.ChatComponent;
|
||||
import net.minecraft.util.FormattedCharSequence;
|
||||
import net.wowmine.stickers.client.StickerRows;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Shadow;
|
||||
import org.spongepowered.asm.mixin.Unique;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ChatComponent.class)
|
||||
abstract class ChatComponentMixin {
|
||||
@Shadow public abstract void rescaleChat();
|
||||
@Unique private int wowmine_stickers$lineHeight;
|
||||
|
||||
@ModifyExpressionValue(
|
||||
method = "addMessageToDisplayQueue",
|
||||
at = @At(value = "INVOKE",
|
||||
target = "Lnet/minecraft/client/gui/components/ComponentRenderUtils;wrapComponents(Lnet/minecraft/network/chat/FormattedText;ILnet/minecraft/client/gui/Font;)Ljava/util/List;"))
|
||||
private List<FormattedCharSequence> wowmine_stickers$rows(
|
||||
List<FormattedCharSequence> original, @Local(argsOnly = true) GuiMessage message,
|
||||
@Local(ordinal = 0) int width) {
|
||||
return StickerRows.layout(original, message, width);
|
||||
}
|
||||
|
||||
@WrapOperation(
|
||||
method = "render",
|
||||
at = @At(value = "INVOKE",
|
||||
target = "Lnet/minecraft/client/gui/GuiGraphics;drawString(Lnet/minecraft/client/gui/Font;Lnet/minecraft/util/FormattedCharSequence;III)I",
|
||||
ordinal = 0))
|
||||
private int wowmine_stickers$draw(GuiGraphics graphics, Font font, FormattedCharSequence text,
|
||||
int x, int y, int color, Operation<Integer> original) {
|
||||
int advance = original.call(graphics, font, text, x, y, color);
|
||||
if (text instanceof StickerRows.Row row) {
|
||||
StickerRows.render(graphics, row, y, color);
|
||||
}
|
||||
return advance;
|
||||
}
|
||||
|
||||
@Inject(method = "render", at = @At("HEAD"))
|
||||
private void wowmine_stickers$spacing(CallbackInfo ci) {
|
||||
int current = StickerRows.lineHeight();
|
||||
if (wowmine_stickers$lineHeight != 0 && current != wowmine_stickers$lineHeight) {
|
||||
rescaleChat();
|
||||
}
|
||||
wowmine_stickers$lineHeight = current;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package net.wowmine.stickers.mixin;
|
||||
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.client.gui.screens.ChatScreen;
|
||||
import net.wowmine.stickers.client.StickerClientEvents;
|
||||
import net.wowmine.stickers.client.HistoryClientEvents;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Shadow;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.ModifyArg;
|
||||
|
||||
@Mixin(ChatScreen.class)
|
||||
abstract class ChatScreenMixin implements StickerClientEvents.ChatInput {
|
||||
@Shadow protected EditBox input;
|
||||
|
||||
@Override
|
||||
public EditBox wowmine_stickers$input() {
|
||||
return input;
|
||||
}
|
||||
|
||||
@ModifyArg(method = "render",
|
||||
at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiGraphics;fill(IIIII)V"),
|
||||
index = 0)
|
||||
private int wowmine_stickers$background(int original) {
|
||||
ChatScreen screen = (ChatScreen) (Object) this;
|
||||
return original + (StickerClientEvents.hasButton(screen) ? 14 : 0)
|
||||
+ (HistoryClientEvents.hasButton(screen) ? 14 : 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
modLoader="javafml"
|
||||
loaderVersion="[4,)"
|
||||
license="All Rights Reserved"
|
||||
|
||||
[[mods]]
|
||||
modId="wowmine_stickers"
|
||||
version="1.1.0"
|
||||
displayName="wowmine Chat"
|
||||
description="Vanilla chat stickers and a persistent, paginated server chat archive."
|
||||
|
||||
[[mixins]]
|
||||
config="wowmine_stickers.mixins.json"
|
||||
|
||||
[[dependencies.wowmine_stickers]]
|
||||
modId="neoforge"
|
||||
type="required"
|
||||
versionRange="[21.1.250,)"
|
||||
ordering="NONE"
|
||||
side="BOTH"
|
||||
|
||||
[[dependencies.wowmine_stickers]]
|
||||
modId="minecraft"
|
||||
type="required"
|
||||
versionRange="[1.21.1,1.21.2)"
|
||||
ordering="NONE"
|
||||
side="BOTH"
|
||||
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"wowmine_stickers.history.open": "Chat archive (Alt+H)",
|
||||
"wowmine_stickers.history.title": "Chat archive",
|
||||
"wowmine_stickers.history.offline": "Chat archive is unavailable on this server.",
|
||||
"wowmine_stickers.history.loading": "Loading archive...",
|
||||
"wowmine_stickers.history.empty": "No messages in this window.",
|
||||
"wowmine_stickers.history.problem": "Archive error: %s",
|
||||
"wowmine_stickers.history.failure.busy": "Server busy",
|
||||
"wowmine_stickers.history.failure.not_found": "Not found",
|
||||
"wowmine_stickers.history.failure.unavailable": "Unavailable",
|
||||
"wowmine_stickers.history.failure.invalid_request": "Invalid request",
|
||||
"wowmine_stickers.history.failure.voice_unavailable": "Voice unavailable",
|
||||
"wowmine_stickers.history.busy": "Another attachment is loading.",
|
||||
"wowmine_stickers.history.media_loading": "Loading attachment...",
|
||||
"wowmine_stickers.history.invalid_media": "Invalid attachment.",
|
||||
"wowmine_stickers.history.timeout": "Archive request timed out.",
|
||||
"wowmine_stickers.history.earliest": "Earliest",
|
||||
"wowmine_stickers.history.older": "Older",
|
||||
"wowmine_stickers.history.newer": "Newer",
|
||||
"wowmine_stickers.history.latest": "Latest",
|
||||
"wowmine_stickers.history.date": "Date (YYYY-MM-DD)",
|
||||
"wowmine_stickers.history.jump": "Go",
|
||||
"wowmine_stickers.history.invalid_date": "Enter a valid date after 1970-01-01.",
|
||||
"wowmine_stickers.history.invalid_message": "[Invalid message]",
|
||||
"wowmine_stickers.history.sticker": "[Sticker loading]",
|
||||
"wowmine_stickers.history.play": "Play",
|
||||
"wowmine_stickers.history.stop": "Stop",
|
||||
"wowmine_stickers.history.voice_unavailable": "Voice playback is unavailable.",
|
||||
"wowmine_stickers.history.selected_voice": "Selected voice from %s",
|
||||
"wowmine_stickers.history.voice_select": "Select voice; use Play",
|
||||
"wowmine_stickers.history.voice_help": "Select a voice by clicking it or using [ and ], then press Play.",
|
||||
"wowmine_stickers.history.voice.unavailable": "Voice playback unavailable.",
|
||||
"wowmine_stickers.history.voice.invalid": "Invalid voice data.",
|
||||
"wowmine_stickers.history.voice.decode_failed": "Could not decode voice.",
|
||||
"wowmine_stickers.history.voice.playback_failed": "Voice playback failed.",
|
||||
"wowmine_stickers.open": "Stickers (Alt+S)",
|
||||
"wowmine_history.error.not_sent": "The message was not sent because the chat archive is unavailable.",
|
||||
"wowmine_history.error.not_saved": "The voice message could not be saved to history.",
|
||||
"wowmine_stickers.history.voice.archive_failed": "The voice message could not be saved to history.",
|
||||
"wowmine_stickers.history.voice.unsupported_target": "This voice target does not support archiving.",
|
||||
"wowmine_stickers.history.voice.public": "Public voice message",
|
||||
"wowmine_stickers.history.voice.team": "Team voice message",
|
||||
"wowmine_stickers.history.voice.to": "Voice message to %s",
|
||||
"wowmine_stickers.unavailable": "This server does not provide stickers.",
|
||||
"wowmine_stickers.catalog.loading": "Loading sticker packs...",
|
||||
"wowmine_stickers.catalog.invalid": "The server sent an invalid sticker catalog.",
|
||||
"wowmine_stickers.message": "[Sticker]",
|
||||
"wowmine_stickers.message.unknown": "%s: [Unknown sticker]",
|
||||
"wowmine_stickers.sticker": "Sticker %s %s",
|
||||
"wowmine_stickers.asset.loading": "Loading sticker...",
|
||||
"wowmine_stickers.asset.timeout": "Download timed out. Click or press R to retry.",
|
||||
"wowmine_stickers.asset.invalid": "Invalid sticker image. Click or press R to retry.",
|
||||
"wowmine_stickers.asset.problem": "%s Click or press R to retry.",
|
||||
"wowmine_stickers.pack.empty": "This pack has no stickers.",
|
||||
"wowmine_stickers.packs.empty": "No packs yet",
|
||||
"wowmine_stickers.packs.hint": "Paste a Telegram pack link below to add stickers.",
|
||||
"wowmine_stickers.pack.previous": "Previous pack",
|
||||
"wowmine_stickers.pack.next": "Next pack",
|
||||
"wowmine_stickers.picker.grid": "Sticker grid. Arrow keys select; Enter sends. R retries a failed download.",
|
||||
"wowmine_stickers.picker.help": "Tab: controls Esc: close R: retry",
|
||||
"wowmine_stickers.import.url": "Telegram sticker set URL",
|
||||
"wowmine_stickers.import.hint": "https://t.me/addstickers/...",
|
||||
"wowmine_stickers.import.add": "Add",
|
||||
"wowmine_stickers.import.queued": "Pack %s queued.",
|
||||
"wowmine_stickers.import.importing": "Importing pack %s...",
|
||||
"wowmine_stickers.import.ready": "Pack %s added.",
|
||||
"wowmine_stickers.import.error": "Could not add pack %s.",
|
||||
"wowmine_stickers.error.asset_busy": "The server is transferring another sticker.",
|
||||
"wowmine_stickers.error.asset_missing": "This sticker is unavailable on the server.",
|
||||
"wowmine_stickers.error.asset_read": "The server could not read this sticker.",
|
||||
"wowmine_stickers.error.send_cooldown": "Wait a moment before sending another sticker.",
|
||||
"wowmine_stickers.import.invalid_link": "Paste a https://t.me/addstickers/NAME link or a pack short name.",
|
||||
"wowmine_stickers.import.already_available": "This pack is already available.",
|
||||
"wowmine_stickers.import.cooldown": "Wait before importing another pack.",
|
||||
"wowmine_stickers.import.rate_limited": "Wait a moment before sending another request.",
|
||||
"wowmine_stickers.import.queue_full": "The import queue is full. Try again later.",
|
||||
"wowmine_stickers.import.not_configured": "Sticker imports are not configured on this server.",
|
||||
"wowmine_stickers.import.timeout": "The import timed out. Try again later.",
|
||||
"wowmine_stickers.import.failed": "The server could not import this pack."
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"wowmine_stickers.history.open": "Архив чата (Alt+H)",
|
||||
"wowmine_stickers.history.title": "Архив чата",
|
||||
"wowmine_stickers.history.offline": "Архив чата на сервере недоступен.",
|
||||
"wowmine_stickers.history.loading": "Загрузка архива...",
|
||||
"wowmine_stickers.history.empty": "Сообщений в этом окне нет.",
|
||||
"wowmine_stickers.history.problem": "Ошибка архива: %s",
|
||||
"wowmine_stickers.history.failure.busy": "Сервер занят",
|
||||
"wowmine_stickers.history.failure.not_found": "Не найдено",
|
||||
"wowmine_stickers.history.failure.unavailable": "Недоступно",
|
||||
"wowmine_stickers.history.failure.invalid_request": "Неверный запрос",
|
||||
"wowmine_stickers.history.failure.voice_unavailable": "Голос недоступен",
|
||||
"wowmine_stickers.history.busy": "Другое вложение уже загружается.",
|
||||
"wowmine_stickers.history.media_loading": "Загрузка вложения...",
|
||||
"wowmine_stickers.history.invalid_media": "Некорректное вложение.",
|
||||
"wowmine_stickers.history.timeout": "Время запроса архива истекло.",
|
||||
"wowmine_stickers.history.earliest": "Первые",
|
||||
"wowmine_stickers.history.older": "Раньше",
|
||||
"wowmine_stickers.history.newer": "Позже",
|
||||
"wowmine_stickers.history.latest": "Последние",
|
||||
"wowmine_stickers.history.date": "Дата (ГГГГ-ММ-ДД)",
|
||||
"wowmine_stickers.history.jump": "Перейти",
|
||||
"wowmine_stickers.history.invalid_date": "Введите дату не раньше 1970-01-01.",
|
||||
"wowmine_stickers.history.invalid_message": "[Некорректное сообщение]",
|
||||
"wowmine_stickers.history.sticker": "[Загрузка стикера]",
|
||||
"wowmine_stickers.history.play": "Слушать",
|
||||
"wowmine_stickers.history.stop": "Стоп",
|
||||
"wowmine_stickers.history.voice_unavailable": "Воспроизведение голоса недоступно.",
|
||||
"wowmine_stickers.history.selected_voice": "Выбрано голосовое от %s",
|
||||
"wowmine_stickers.history.voice_select": "Выберите голосовое и нажмите «Слушать»",
|
||||
"wowmine_stickers.history.voice_help": "Выберите голосовое мышью или клавишами [ и ], затем нажмите «Слушать».",
|
||||
"wowmine_stickers.history.voice.unavailable": "Голос недоступен.",
|
||||
"wowmine_stickers.history.voice.invalid": "Некорректное голосовое.",
|
||||
"wowmine_stickers.history.voice.decode_failed": "Не удалось декодировать голос.",
|
||||
"wowmine_stickers.history.voice.playback_failed": "Ошибка воспроизведения голоса.",
|
||||
"wowmine_stickers.open": "Стикеры (Alt+S)",
|
||||
"wowmine_history.error.not_sent": "Сообщение не отправлено: архив чата недоступен.",
|
||||
"wowmine_history.error.not_saved": "Не удалось сохранить голосовое сообщение в историю.",
|
||||
"wowmine_stickers.history.voice.archive_failed": "Не удалось сохранить голосовое сообщение в историю.",
|
||||
"wowmine_stickers.history.voice.unsupported_target": "Архивирование для этого получателя голосовых не поддерживается.",
|
||||
"wowmine_stickers.history.voice.public": "Общее голосовое сообщение",
|
||||
"wowmine_stickers.history.voice.team": "Командное голосовое сообщение",
|
||||
"wowmine_stickers.history.voice.to": "Голосовое сообщение для %s",
|
||||
"wowmine_stickers.unavailable": "На этом сервере стикеры недоступны.",
|
||||
"wowmine_stickers.catalog.loading": "Загрузка наборов стикеров...",
|
||||
"wowmine_stickers.catalog.invalid": "Сервер прислал некорректный каталог стикеров.",
|
||||
"wowmine_stickers.message": "[Стикер]",
|
||||
"wowmine_stickers.message.unknown": "%s: [Неизвестный стикер]",
|
||||
"wowmine_stickers.sticker": "Стикер %s %s",
|
||||
"wowmine_stickers.asset.loading": "Загрузка стикера...",
|
||||
"wowmine_stickers.asset.timeout": "Время загрузки истекло. Нажмите на стикер или R для повтора.",
|
||||
"wowmine_stickers.asset.invalid": "Некорректное изображение. Нажмите на стикер или R для повтора.",
|
||||
"wowmine_stickers.asset.problem": "%s Нажмите на стикер или R для повтора.",
|
||||
"wowmine_stickers.pack.empty": "В этом наборе нет стикеров.",
|
||||
"wowmine_stickers.packs.empty": "Наборов пока нет",
|
||||
"wowmine_stickers.packs.hint": "Вставьте ссылку на набор Telegram в поле ниже.",
|
||||
"wowmine_stickers.pack.previous": "Предыдущий набор",
|
||||
"wowmine_stickers.pack.next": "Следующий набор",
|
||||
"wowmine_stickers.picker.grid": "Сетка стикеров. Стрелки: выбор, Enter: отправить, R: повторить загрузку.",
|
||||
"wowmine_stickers.picker.help": "Tab: выбор Esc: закрыть R: повтор",
|
||||
"wowmine_stickers.import.url": "Ссылка на набор стикеров Telegram",
|
||||
"wowmine_stickers.import.hint": "https://t.me/addstickers/...",
|
||||
"wowmine_stickers.import.add": "Доб.",
|
||||
"wowmine_stickers.import.queued": "Набор %s в очереди.",
|
||||
"wowmine_stickers.import.importing": "Импорт набора %s...",
|
||||
"wowmine_stickers.import.ready": "Набор %s добавлен.",
|
||||
"wowmine_stickers.import.error": "Не удалось добавить набор %s.",
|
||||
"wowmine_stickers.error.asset_busy": "Сервер уже передаёт другой стикер.",
|
||||
"wowmine_stickers.error.asset_missing": "Этот стикер недоступен на сервере.",
|
||||
"wowmine_stickers.error.asset_read": "Сервер не смог прочитать стикер.",
|
||||
"wowmine_stickers.error.send_cooldown": "Подождите перед отправкой следующего стикера.",
|
||||
"wowmine_stickers.import.invalid_link": "Вставьте ссылку https://t.me/addstickers/NAME или короткое имя набора.",
|
||||
"wowmine_stickers.import.already_available": "Этот набор уже доступен.",
|
||||
"wowmine_stickers.import.cooldown": "Подождите перед импортом следующего набора.",
|
||||
"wowmine_stickers.import.rate_limited": "Подождите немного перед следующим запросом.",
|
||||
"wowmine_stickers.import.queue_full": "Очередь импорта заполнена. Попробуйте позже.",
|
||||
"wowmine_stickers.import.not_configured": "Импорт стикеров на сервере не настроен.",
|
||||
"wowmine_stickers.import.timeout": "Время импорта истекло. Попробуйте позже.",
|
||||
"wowmine_stickers.import.failed": "Сервер не смог импортировать этот набор."
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"required": true,
|
||||
"minVersion": "0.8",
|
||||
"package": "net.wowmine.stickers.mixin",
|
||||
"compatibilityLevel": "JAVA_21",
|
||||
"client": [
|
||||
"ChatScreenMixin",
|
||||
"ChatComponentMixin"
|
||||
],
|
||||
"injectors": {
|
||||
"defaultRequire": 1
|
||||
}
|
||||
}
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import com.google.gson.JsonParser;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFileAttributeView;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import net.wowmine.stickers.ChatHistory.Audience;
|
||||
import net.wowmine.stickers.ChatHistory.Draft;
|
||||
import net.wowmine.stickers.ChatHistory.Entry;
|
||||
import net.wowmine.stickers.ChatHistory.Kind;
|
||||
import net.wowmine.stickers.ChatHistory.Page;
|
||||
import net.wowmine.stickers.ChatHistory.Query;
|
||||
|
||||
/** Real temporary SQLite databases; no server, cache, network, or injected storage implementation. */
|
||||
public final class ChatArchiveTest {
|
||||
private static final UUID ALICE = UUID.fromString("00000000-0000-0000-0000-000000000001");
|
||||
private static final UUID BOB = UUID.fromString("00000000-0000-0000-0000-000000000002");
|
||||
private static final ZoneId ZONE = ZoneId.of("Europe/Moscow");
|
||||
private static final String HEADER = "[25Nov2026 12:34:56.789] [Server thread/INFO] "
|
||||
+ "[net.minecraft.server.MinecraftServer/]: ";
|
||||
|
||||
private ChatArchiveTest() {}
|
||||
|
||||
public static void main(String[] arguments) throws IOException, SQLException {
|
||||
try (var fixture = new Fixture()) {
|
||||
walksUnlimitedHistoryWithCompositeCursors(fixture.root.resolve("walk"));
|
||||
keepsByteLimitedPagesNavigable(fixture.root.resolve("budget"));
|
||||
enforcesAudienceForRowsAndAttachments(fixture.root.resolve("acl"));
|
||||
persistsDeduplicatedMediaWithoutSourceCache(fixture.root.resolve("persist"));
|
||||
rejectsInvalidMediaWithoutPartialWrites(fixture.root.resolve("invalid"));
|
||||
rollsBackMetadataMediaAndAudienceOnSqlFailure(fixture.root.resolve("rollback"));
|
||||
restrictsOnlyArchiveDirectoryPermissions(fixture.root.resolve("permissions"));
|
||||
importsOnlyWhitelistedPublicChatOnce(fixture.root.resolve("logs"));
|
||||
resumesPartialMigrationWithoutDuplicatesOrNewSessions(fixture.root.resolve("resume"));
|
||||
}
|
||||
System.out.println("CHAT_ARCHIVE_PASS");
|
||||
}
|
||||
|
||||
private static void walksUnlimitedHistoryWithCompositeCursors(Path root) throws IOException, SQLException {
|
||||
var expected = new ArrayList<Entry>();
|
||||
var aliceEntries = new ArrayList<Entry>();
|
||||
try (var archive = new ChatArchive(root)) {
|
||||
for (int index = 0; index < 17_013; index++) {
|
||||
// Insertion order differs from chronology; groups of seven exercise cursor ID ties.
|
||||
Draft draft = text(946_684_800_000L + ((17_012 - index) / 7) * 1000L, "row " + index);
|
||||
Audience audience = index % 251 == 0 ? ChatHistory.PUBLIC
|
||||
: new Audience(false, index % 509 == 0 ? Set.of(ALICE, BOB) : Set.of(BOB));
|
||||
Entry entry = new Entry(archive.append(draft, audience, new byte[0]), draft);
|
||||
expected.add(entry);
|
||||
if (audience.publicMessage() || audience.recipients().contains(ALICE)) {
|
||||
aliceEntries.add(entry);
|
||||
}
|
||||
}
|
||||
Draft oldest = text(0, "oldest");
|
||||
Entry first = new Entry(archive.append(oldest, ChatHistory.PUBLIC, new byte[0]), oldest);
|
||||
expected.add(first);
|
||||
aliceEntries.add(first);
|
||||
Comparator<Entry> chronological = Comparator.comparingLong((Entry entry) -> entry.message().time())
|
||||
.thenComparingLong(Entry::id);
|
||||
expected.sort(chronological);
|
||||
aliceEntries.sort(chronological);
|
||||
equal(expected, walk(archive, BOB, true));
|
||||
equal(expected, walk(archive, BOB, false));
|
||||
equal(aliceEntries, walk(archive, ALICE, true));
|
||||
equal(aliceEntries, walk(archive, ALICE, false));
|
||||
equal(expected.subList(0, 50), archive.page(BOB, Query.earliest()).entries());
|
||||
equal(expected.subList(expected.size() - 50, expected.size()), archive.page(BOB, Query.latest()).entries());
|
||||
long time = expected.get(8000).message().time();
|
||||
var atDate = archive.page(BOB, new Query(ChatHistory.Direction.AT_DATE, time, 0));
|
||||
List<Entry> beforeDate = expected.stream().filter(entry -> entry.message().time() <= time).toList();
|
||||
equal(beforeDate.subList(beforeDate.size() - 50, beforeDate.size()), atDate.entries());
|
||||
equal(true, atDate.hasOlder());
|
||||
equal(true, atDate.hasNewer());
|
||||
Page afterEnd = archive.page(ALICE, Query.after(aliceEntries.getLast().cursor()));
|
||||
equal(List.of(), afterEnd.entries());
|
||||
equal(true, afterEnd.hasOlder());
|
||||
equal(false, afterEnd.hasNewer());
|
||||
Page beforeStart = archive.page(ALICE, Query.before(aliceEntries.getFirst().cursor()));
|
||||
equal(List.of(), beforeStart.entries());
|
||||
equal(false, beforeStart.hasOlder());
|
||||
equal(true, beforeStart.hasNewer());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Entry> walk(ChatArchive archive, UUID requester, boolean forward) throws SQLException {
|
||||
var result = new ArrayList<Entry>();
|
||||
Page page = archive.page(requester, forward ? Query.earliest() : Query.latest());
|
||||
while (true) {
|
||||
if (page.entries().isEmpty()) {
|
||||
throw new AssertionError("Nonempty history walk reached empty window");
|
||||
}
|
||||
if (forward) {
|
||||
equal(!result.isEmpty(), page.hasOlder());
|
||||
result.addAll(page.entries());
|
||||
} else {
|
||||
equal(!result.isEmpty(), page.hasNewer());
|
||||
result.addAll(0, page.entries());
|
||||
}
|
||||
boolean more = forward ? page.hasNewer() : page.hasOlder();
|
||||
if (!more) {
|
||||
break;
|
||||
}
|
||||
if (result.size() > 18_000) {
|
||||
throw new AssertionError("Cursor walk repeats entries");
|
||||
}
|
||||
page = archive.page(requester, forward ? Query.after(page.entries().getLast().cursor())
|
||||
: Query.before(page.entries().getFirst().cursor()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void keepsByteLimitedPagesNavigable(Path root) throws IOException, SQLException {
|
||||
try (var archive = new ChatArchive(root)) {
|
||||
var expected = new ArrayList<Entry>();
|
||||
for (int index = 0; index < 11; index++) {
|
||||
Draft draft = text(index, "\u00e9".repeat(32_750));
|
||||
expected.add(new Entry(archive.append(draft, ChatHistory.PUBLIC, new byte[0]), draft));
|
||||
}
|
||||
Page earliest = archive.page(ALICE, Query.earliest());
|
||||
equal(3, earliest.entries().size());
|
||||
equal(false, earliest.hasOlder());
|
||||
equal(true, earliest.hasNewer());
|
||||
Page latest = archive.page(ALICE, Query.latest());
|
||||
equal(3, latest.entries().size());
|
||||
equal(true, latest.hasOlder());
|
||||
equal(false, latest.hasNewer());
|
||||
equal(expected, walk(archive, ALICE, true));
|
||||
equal(expected, walk(archive, ALICE, false));
|
||||
}
|
||||
}
|
||||
|
||||
private static void enforcesAudienceForRowsAndAttachments(Path root) throws IOException, SQLException {
|
||||
byte[] voice = voice();
|
||||
try (var archive = new ChatArchive(root)) {
|
||||
Draft draft = media(10, Kind.VOICE, voice, 2);
|
||||
long privateId = archive.append(draft, new Audience(false, Set.of(ALICE)), voice);
|
||||
for (Query query : List.of(Query.earliest(), Query.latest(),
|
||||
new Query(ChatHistory.Direction.AT_DATE, 10, 0),
|
||||
Query.before(new ChatHistory.Cursor(20, Long.MAX_VALUE)),
|
||||
Query.after(new ChatHistory.Cursor(0, 1)))) {
|
||||
equal(new Page(List.of(), false, false), archive.page(BOB, query));
|
||||
}
|
||||
long publicId = archive.append(text(20, "public"), ChatHistory.PUBLIC, new byte[0]);
|
||||
equal(List.of(publicId), ids(archive.page(BOB, Query.earliest())));
|
||||
equal(List.of(privateId, publicId), ids(archive.page(ALICE, Query.earliest())));
|
||||
equal(false, archive.page(BOB, Query.earliest()).hasOlder());
|
||||
Page unauthorizedDate = archive.page(BOB, new Query(ChatHistory.Direction.AT_DATE, 10, 0));
|
||||
equal(List.of(), unauthorizedDate.entries());
|
||||
equal(false, unauthorizedDate.hasOlder());
|
||||
equal(true, unauthorizedDate.hasNewer());
|
||||
equal(true, archive.attachment(BOB, privateId).isEmpty());
|
||||
equal(true, archive.attachment(BOB, publicId).isEmpty());
|
||||
equal(true, archive.attachment(BOB, Long.MAX_VALUE).isEmpty());
|
||||
equal(Kind.VOICE, archive.attachment(ALICE, privateId).orElseThrow().kind());
|
||||
bytesEqual(voice, archive.attachment(ALICE, privateId).orElseThrow().bytes());
|
||||
}
|
||||
}
|
||||
|
||||
private static void persistsDeduplicatedMediaWithoutSourceCache(Path root) throws IOException, SQLException {
|
||||
byte[] sticker = png(2);
|
||||
Path cache = root.resolve("source-cache.png");
|
||||
Files.createDirectories(root);
|
||||
Files.write(cache, sticker);
|
||||
long id;
|
||||
long restrictedId;
|
||||
long voiceId;
|
||||
byte[] voice = voice();
|
||||
try (var archive = new ChatArchive(root)) {
|
||||
Draft draft = media(100, Kind.STICKER, Files.readAllBytes(cache), 2);
|
||||
id = archive.append(draft, ChatHistory.PUBLIC, sticker);
|
||||
restrictedId = archive.append(draft, new Audience(false, Set.of(ALICE)), sticker);
|
||||
voiceId = archive.append(media(101, Kind.VOICE, voice, 2), new Audience(false, Set.of(ALICE)), voice);
|
||||
equal(2L, count(root, "media"));
|
||||
}
|
||||
Files.delete(cache);
|
||||
try (var archive = new ChatArchive(root)) {
|
||||
var attachment = archive.attachment(BOB, id).orElseThrow();
|
||||
equal(Kind.STICKER, attachment.kind());
|
||||
equal(2, attachment.frames());
|
||||
bytesEqual(sticker, attachment.bytes());
|
||||
byte[] copy = attachment.bytes();
|
||||
copy[0] ^= 1;
|
||||
bytesEqual(sticker, attachment.bytes());
|
||||
equal(List.of(id), ids(archive.page(BOB, Query.latest())));
|
||||
equal(true, archive.attachment(BOB, restrictedId).isEmpty());
|
||||
equal(true, archive.attachment(BOB, voiceId).isEmpty());
|
||||
bytesEqual(voice, archive.attachment(ALICE, voiceId).orElseThrow().bytes());
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejectsInvalidMediaWithoutPartialWrites(Path root) throws IOException, SQLException {
|
||||
try (var archive = new ChatArchive(root)) {
|
||||
byte[] png = png(1);
|
||||
byte[] voice = voice();
|
||||
rejects(IllegalArgumentException.class, () -> archive.append(text(0, "text"),
|
||||
ChatHistory.PUBLIC, new byte[] {1}));
|
||||
rejects(IllegalArgumentException.class, () -> archive.append(
|
||||
new Draft(0, ALICE, "Alice", Kind.STICKER, "{}", "0".repeat(64), 1), ChatHistory.PUBLIC, png));
|
||||
rejects(IOException.class, () -> archive.append(media(0, Kind.STICKER, png, 2), ChatHistory.PUBLIC, png));
|
||||
rejects(IOException.class, () -> archive.append(media(0, Kind.VOICE, voice, 1), ChatHistory.PUBLIC, voice));
|
||||
for (byte[] invalid : List.of(new byte[] {0, 0}, new byte[] {1, 1, 0}, new byte[] {0, 2, 1})) {
|
||||
rejects(IOException.class, () -> archive.append(media(0, Kind.VOICE, invalid, 1), ChatHistory.PUBLIC, invalid));
|
||||
}
|
||||
byte[] tooLarge = new byte[ChatHistory.MEDIA_BYTES + 1];
|
||||
rejects(IllegalArgumentException.class, () -> archive.append(
|
||||
media(0, Kind.VOICE, tooLarge, 1), ChatHistory.PUBLIC, tooLarge));
|
||||
equal(0L, count(root, "entries"));
|
||||
equal(0L, count(root, "media"));
|
||||
equal(0L, count(root, "recipients"));
|
||||
long id = archive.append(media(1, Kind.VOICE, voice, 2), ChatHistory.PUBLIC, voice);
|
||||
equal(List.of(id), ids(archive.page(ALICE, Query.latest())));
|
||||
}
|
||||
var closed = new ChatArchive(root);
|
||||
closed.close();
|
||||
rejects(SQLException.class, () -> closed.page(ALICE, Query.latest()));
|
||||
}
|
||||
|
||||
private static void rollsBackMetadataMediaAndAudienceOnSqlFailure(Path root) throws IOException, SQLException {
|
||||
try (var archive = new ChatArchive(root); Connection db = database(root)) {
|
||||
execute(db, "CREATE TRIGGER fail_acl BEFORE INSERT ON recipients BEGIN SELECT RAISE(ABORT,'fixture ACL failure'); END");
|
||||
byte[] voice = voice();
|
||||
rejects(SQLException.class, () -> archive.append(media(1, Kind.VOICE, voice, 2),
|
||||
new Audience(false, Set.of(ALICE, BOB)), voice));
|
||||
equal(0L, count(root, "entries"));
|
||||
equal(0L, count(root, "media"));
|
||||
equal(0L, count(root, "recipients"));
|
||||
execute(db, "DROP TRIGGER fail_acl");
|
||||
long id = archive.append(media(1, Kind.VOICE, voice, 2), new Audience(false, Set.of(ALICE)), voice);
|
||||
equal(List.of(id), ids(archive.page(ALICE, Query.earliest())));
|
||||
equal(List.of(), ids(archive.page(BOB, Query.earliest())));
|
||||
}
|
||||
}
|
||||
|
||||
private static void importsOnlyWhitelistedPublicChatOnce(Path root) throws IOException, SQLException {
|
||||
Path logs = Files.createDirectories(root.resolve("server-logs"));
|
||||
String message = "quote \" literal {\"clickEvent\":{}} backslash \\\\";
|
||||
List<String> lines = List.of(
|
||||
HEADER + "<Alice> " + message,
|
||||
HEADER + "[Not Secure] <Bob_2> second",
|
||||
HEADER + "Alice whispers to Bob: secret",
|
||||
HEADER + "[Alice -> Bob] secret",
|
||||
HEADER + "[Admin] announcement",
|
||||
HEADER + "<Alice> /say command",
|
||||
HEADER + "<Name-With-Dash> invalid",
|
||||
HEADER.replace("Server thread/INFO", "RCON Listener #1/INFO") + "<Alice> forged",
|
||||
HEADER.replace("Server thread/INFO", "Async Chat Thread/INFO") + "<Alice> forged",
|
||||
HEADER.replace("MinecraftServer/", "dedicated.DedicatedServer/") + "<Alice> forged",
|
||||
HEADER.replace("INFO", "WARN") + "<Alice> forged",
|
||||
HEADER.replace("25Nov", "31Nov") + "<Alice> invalid date",
|
||||
HEADER + "<Alice> " + "x".repeat(100_000),
|
||||
"continuation <Alice> untrusted",
|
||||
HEADER + "<Alice> after oversized");
|
||||
Files.write(logs.resolve("a.log"), lines);
|
||||
gzip(logs.resolve("b.log.gz"), HEADER + "<Carol> compressed\n");
|
||||
Files.writeString(logs.resolve("latest.log"), HEADER + "<Active> current server is still writing\n");
|
||||
Files.writeString(logs.resolve("debug.log"), HEADER + "<Duplicate> verbose copy of public log\n");
|
||||
Files.writeString(logs.resolve("ignore.txt"), HEADER + "<Ignored> ignored\n");
|
||||
try (var archive = new ChatArchive(root.resolve("archive"))) {
|
||||
equal(4, ArchiveLogImport.importOnce(archive, logs, ZONE));
|
||||
var entries = archive.page(BOB, Query.earliest()).entries();
|
||||
equal(List.of("Alice", "Bob_2", "Alice", "Carol"), entries.stream().map(entry -> entry.message().name()).toList());
|
||||
equal(message, JsonParser.parseString(entries.getFirst().message().body())
|
||||
.getAsJsonObject().get("text").getAsString());
|
||||
equal(Set.of("text"), JsonParser.parseString(entries.getFirst().message().body()).getAsJsonObject().keySet());
|
||||
equal(UUID.nameUUIDFromBytes("OfflinePlayer:Alice".getBytes(StandardCharsets.UTF_8)),
|
||||
entries.getFirst().message().author());
|
||||
equal(LocalDateTime.of(2026, 11, 25, 12, 34, 56, 789_000_000).atZone(ZONE).toInstant().toEpochMilli(),
|
||||
entries.getFirst().message().time());
|
||||
}
|
||||
Files.writeString(logs.resolve("a.log"), HEADER + "<NewSession> already live\n");
|
||||
try (var archive = new ChatArchive(root.resolve("archive"))) {
|
||||
equal(0, ArchiveLogImport.importOnce(archive, logs, ZONE));
|
||||
equal(4, archive.page(ALICE, Query.latest()).entries().size());
|
||||
}
|
||||
}
|
||||
|
||||
private static void resumesPartialMigrationWithoutDuplicatesOrNewSessions(Path root) throws IOException, SQLException {
|
||||
Path logs = Files.createDirectories(root.resolve("logs"));
|
||||
Path dbRoot = root.resolve("archive");
|
||||
Files.writeString(logs.resolve("old.log"), HEADER + "<Alice> first\n" + HEADER + "<Bob> second\n");
|
||||
try (var archive = new ChatArchive(dbRoot); Connection db = database(dbRoot)) {
|
||||
execute(db, """
|
||||
CREATE TRIGGER interrupt_import BEFORE INSERT ON entries WHEN NEW.name='Bob'
|
||||
BEGIN SELECT RAISE(ABORT,'fixture migration interruption'); END
|
||||
""");
|
||||
rejects(SQLException.class, () -> ArchiveLogImport.importOnce(archive, logs, ZONE));
|
||||
equal(List.of("Alice"), archive.page(ALICE, Query.latest()).entries().stream()
|
||||
.map(entry -> entry.message().name()).toList());
|
||||
execute(db, "DROP TRIGGER interrupt_import");
|
||||
}
|
||||
// Rotation/recompression preserves decompressed source identity; newly created sessions stay excluded.
|
||||
gzip(logs.resolve("rotated.log.gz"), Files.readString(logs.resolve("old.log")));
|
||||
Files.delete(logs.resolve("old.log"));
|
||||
Files.writeString(logs.resolve("latest.log"), HEADER + "<NewSession> do not import\n");
|
||||
try (var archive = new ChatArchive(dbRoot)) {
|
||||
equal(1, ArchiveLogImport.importOnce(archive, logs, ZONE));
|
||||
equal(List.of("Alice", "Bob"), archive.page(ALICE, Query.earliest()).entries().stream()
|
||||
.map(entry -> entry.message().name()).toList());
|
||||
equal(0, ArchiveLogImport.importOnce(archive, logs, ZONE));
|
||||
}
|
||||
}
|
||||
|
||||
private static Draft text(long time, String body) {
|
||||
var component = new com.google.gson.JsonObject();
|
||||
component.addProperty("text", body);
|
||||
return new Draft(time, ALICE, "Alice", Kind.TEXT, component.toString(), "", 0);
|
||||
}
|
||||
|
||||
private static void restrictsOnlyArchiveDirectoryPermissions(Path root) throws IOException, SQLException {
|
||||
Files.createDirectories(root);
|
||||
var parentPermissions = Files.getFileAttributeView(root, PosixFileAttributeView.class);
|
||||
var before = parentPermissions == null ? Set.of() : parentPermissions.readAttributes().permissions();
|
||||
Path archiveRoot = root.resolve("archive");
|
||||
try (var archive = new ChatArchive(archiveRoot)) {
|
||||
equal(List.of(), archive.page(ALICE, Query.latest()).entries());
|
||||
var permissions = Files.getFileAttributeView(archiveRoot, PosixFileAttributeView.class);
|
||||
if (permissions != null) {
|
||||
equal(PosixFilePermissions.fromString("rwx------"), permissions.readAttributes().permissions());
|
||||
equal(before, parentPermissions.readAttributes().permissions());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Draft media(long time, Kind kind, byte[] bytes, int frames) {
|
||||
return new Draft(time, ALICE, "Alice", kind, "{\"text\":\"media\"}", ChatArchive.sha256(bytes), frames);
|
||||
}
|
||||
|
||||
private static byte[] voice() {
|
||||
return VoiceFrames.encode(List.of(new byte[] {1, 2}, new byte[] {3, 4, 5}));
|
||||
}
|
||||
|
||||
private static byte[] png(int frames) throws IOException {
|
||||
var image = new BufferedImage(Math.min(frames, 8) * 128,
|
||||
((frames + Math.min(frames, 8) - 1) / Math.min(frames, 8)) * 128, BufferedImage.TYPE_INT_ARGB);
|
||||
try (var output = new ByteArrayOutputStream()) {
|
||||
if (!ImageIO.write(image, "png", output)) {
|
||||
throw new IOException("No PNG writer");
|
||||
}
|
||||
return output.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static void gzip(Path path, String text) throws IOException {
|
||||
try (var output = new GZIPOutputStream(Files.newOutputStream(path))) {
|
||||
output.write(text.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
|
||||
private static Connection database(Path root) throws SQLException {
|
||||
return DriverManager.getConnection("jdbc:sqlite:" + root.resolve("chat-archive.sqlite").toAbsolutePath());
|
||||
}
|
||||
|
||||
private static long count(Path root, String table) throws SQLException {
|
||||
try (Connection db = database(root); var sql = db.createStatement();
|
||||
var row = sql.executeQuery("SELECT count(*) FROM " + table)) {
|
||||
if (!row.next()) {
|
||||
throw new SQLException("Missing count row");
|
||||
}
|
||||
return row.getLong(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void execute(Connection db, String statement) throws SQLException {
|
||||
try (var sql = db.createStatement()) {
|
||||
sql.execute(statement);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Long> ids(Page page) {
|
||||
return page.entries().stream().map(Entry::id).toList();
|
||||
}
|
||||
|
||||
private static void equal(Object expected, Object actual) {
|
||||
if (!expected.equals(actual)) {
|
||||
throw new AssertionError("Expected " + expected + ", got " + actual);
|
||||
}
|
||||
}
|
||||
|
||||
private static void bytesEqual(byte[] expected, byte[] actual) {
|
||||
if (!Arrays.equals(expected, actual)) {
|
||||
throw new AssertionError("Archive changed binary media");
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejects(Class<? extends Exception> expected, Action action) throws IOException, SQLException {
|
||||
try {
|
||||
action.run();
|
||||
} catch (IOException | SQLException | IllegalArgumentException error) {
|
||||
if (expected.isInstance(error)) {
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
throw new AssertionError("Expected rejection: " + expected.getSimpleName());
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface Action {
|
||||
void run() throws IOException, SQLException;
|
||||
}
|
||||
|
||||
private static final class Fixture implements AutoCloseable {
|
||||
private final Path root;
|
||||
|
||||
private Fixture() throws IOException {
|
||||
root = Files.createTempDirectory("wowmine-chat-archive-");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
try (var paths = Files.walk(root)) {
|
||||
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
|
||||
Files.delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import io.netty.buffer.Unpooled;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
|
||||
/** Real wire contracts for long cursors, bounded metadata and independent media transfers. */
|
||||
public final class HistoryProtocolTest {
|
||||
private static final UUID AUTHOR = UUID.fromString("bb0c26de-752c-4f0f-b5da-8be7a5d46c91");
|
||||
|
||||
private HistoryProtocolTest() {}
|
||||
|
||||
public static void main(String[] arguments) {
|
||||
cursorsDoNotTruncateAcrossYearsOrIntegerLimits();
|
||||
pagesPreserveAllKindsAndNavigation();
|
||||
rejectsUnboundedMetadataBeforeReadingEntries();
|
||||
attachmentWirePreservesBytesAndLimits();
|
||||
System.out.println("HISTORY_PROTOCOL_PASS");
|
||||
}
|
||||
|
||||
private static void cursorsDoNotTruncateAcrossYearsOrIntegerLimits() {
|
||||
for (var query : List.of(ChatHistory.Query.latest(), ChatHistory.Query.earliest(),
|
||||
new ChatHistory.Query(ChatHistory.Direction.BEFORE, 946_684_800_000L, 4_294_967_299L),
|
||||
new ChatHistory.Query(ChatHistory.Direction.AFTER, 946_684_800_000L, 4_294_967_299L),
|
||||
new ChatHistory.Query(ChatHistory.Direction.AT_DATE, 4_102_444_800_000L, 0))) {
|
||||
var buffer = buffer();
|
||||
try {
|
||||
var original = new HistoryPackets.PageRequest(8_589_934_599L, query);
|
||||
HistoryPackets.PageRequest.CODEC.encode(buffer, original);
|
||||
equal(original, HistoryPackets.PageRequest.CODEC.decode(buffer));
|
||||
equal(0, buffer.readableBytes());
|
||||
} finally {
|
||||
buffer.release();
|
||||
}
|
||||
}
|
||||
rejects(() -> new ChatHistory.Query(ChatHistory.Direction.BEFORE, 1, 0));
|
||||
rejects(() -> new ChatHistory.Query(ChatHistory.Direction.AT_DATE, -1, 0));
|
||||
rejects(() -> new ChatHistory.Query(ChatHistory.Direction.LATEST, 1, 1));
|
||||
}
|
||||
|
||||
private static void pagesPreserveAllKindsAndNavigation() {
|
||||
var entries = List.of(
|
||||
entry(4_294_967_300L, 1, ChatHistory.Kind.TEXT, "{\"text\":\"old text\"}", "", 0),
|
||||
entry(4_294_967_301L, 1, ChatHistory.Kind.STICKER, "{\"text\":\"\"}", "a".repeat(64), 60),
|
||||
entry(4_294_967_302L, 2, ChatHistory.Kind.VOICE, "{\"text\":\"team\"}", "b".repeat(64), 15_000));
|
||||
var original = new HistoryPackets.PageReply(21, new ChatHistory.Page(entries, true, true));
|
||||
var buffer = buffer();
|
||||
try {
|
||||
HistoryPackets.PageReply.CODEC.encode(buffer, original);
|
||||
equal(original, HistoryPackets.PageReply.CODEC.decode(buffer));
|
||||
equal(0, buffer.readableBytes());
|
||||
} finally {
|
||||
buffer.release();
|
||||
}
|
||||
rejects(() -> new ChatHistory.Page(List.of(entries.get(2), entries.get(0)), false, false));
|
||||
}
|
||||
|
||||
private static void rejectsUnboundedMetadataBeforeReadingEntries() {
|
||||
var buffer = buffer();
|
||||
try {
|
||||
buffer.writeLong(1);
|
||||
buffer.writeVarInt(ChatHistory.PAGE_SIZE + 1);
|
||||
rejects(() -> HistoryPackets.PageReply.CODEC.decode(buffer));
|
||||
} finally {
|
||||
buffer.release();
|
||||
}
|
||||
var oversized = buffer();
|
||||
try {
|
||||
oversized.writeLong(1);
|
||||
oversized.writeVarInt(5);
|
||||
String body = "{\"text\":\"" + "\u03bb".repeat(30_000) + "\"}";
|
||||
for (int index = 0; index < 5; index++) {
|
||||
oversized.writeLong(index + 1);
|
||||
oversized.writeLong(index);
|
||||
oversized.writeUUID(AUTHOR);
|
||||
oversized.writeUtf("ArchiveQA", 64);
|
||||
oversized.writeEnum(ChatHistory.Kind.TEXT);
|
||||
oversized.writeUtf(body, ChatHistory.BODY_CHARACTERS);
|
||||
oversized.writeUtf("", 64);
|
||||
oversized.writeVarInt(0);
|
||||
}
|
||||
oversized.writeBoolean(false);
|
||||
oversized.writeBoolean(false);
|
||||
rejects(() -> HistoryPackets.PageReply.CODEC.decode(oversized));
|
||||
} finally {
|
||||
oversized.release();
|
||||
}
|
||||
}
|
||||
|
||||
private static void attachmentWirePreservesBytesAndLimits() {
|
||||
byte[] bytes = new byte[HistoryPackets.CHUNK_BYTES];
|
||||
Arrays.fill(bytes, (byte) 73);
|
||||
var original = new HistoryPackets.AttachmentChunk(91, "c".repeat(64), 0, bytes.length + 3, bytes);
|
||||
bytes[0] = 0;
|
||||
var buffer = buffer();
|
||||
try {
|
||||
HistoryPackets.AttachmentChunk.CODEC.encode(buffer, original);
|
||||
var decoded = HistoryPackets.AttachmentChunk.CODEC.decode(buffer);
|
||||
equal(91L, decoded.request());
|
||||
equal("c".repeat(64), decoded.id());
|
||||
equal(0, decoded.part());
|
||||
equal(HistoryPackets.CHUNK_BYTES + 3, decoded.totalBytes());
|
||||
if (!Arrays.equals(original.bytes(), decoded.bytes()) || decoded.bytes()[0] != 73) {
|
||||
throw new AssertionError("Archive attachment wire changed bytes or retained mutable input");
|
||||
}
|
||||
equal(0, buffer.readableBytes());
|
||||
} finally {
|
||||
buffer.release();
|
||||
}
|
||||
new HistoryPackets.AttachmentChunk(92, "d".repeat(64), 1, HistoryPackets.CHUNK_BYTES + 3, new byte[3]);
|
||||
rejects(() -> new HistoryPackets.AttachmentChunk(0, "a".repeat(64), 0, 1, new byte[1]));
|
||||
rejects(() -> new HistoryPackets.AttachmentChunk(1, "a".repeat(64), -1, 1, new byte[1]));
|
||||
rejects(() -> new HistoryPackets.AttachmentChunk(1, "a".repeat(64), 1, 1, new byte[1]));
|
||||
rejects(() -> new HistoryPackets.AttachmentChunk(1, "a".repeat(64), 0,
|
||||
ChatHistory.MEDIA_BYTES + 1, new byte[1]));
|
||||
rejects(() -> new HistoryPackets.AttachmentChunk(1, "../private", 0, 1, new byte[1]));
|
||||
rejects(() -> new HistoryPackets.AttachmentChunk(1, "a".repeat(64), 0, 10, new byte[9]));
|
||||
}
|
||||
|
||||
private static ChatHistory.Entry entry(long id, long time, ChatHistory.Kind kind,
|
||||
String body, String attachment, int frames) {
|
||||
return new ChatHistory.Entry(id, new ChatHistory.Draft(
|
||||
time, AUTHOR, "ArchiveQA", kind, body, attachment, frames));
|
||||
}
|
||||
|
||||
private static RegistryFriendlyByteBuf buffer() {
|
||||
return new RegistryFriendlyByteBuf(Unpooled.buffer(), RegistryAccess.EMPTY);
|
||||
}
|
||||
|
||||
private static void equal(Object expected, Object actual) {
|
||||
if (!expected.equals(actual)) {
|
||||
throw new AssertionError("Expected " + expected + " but got " + actual);
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejects(Runnable action) {
|
||||
try {
|
||||
action.run();
|
||||
} catch (IllegalArgumentException expected) {
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("Invalid archive protocol input accepted");
|
||||
}
|
||||
}
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import javax.imageio.ImageIO;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
|
||||
/** Runs against real codecs and files without a fake Minecraft server. */
|
||||
public final class StickerProtocolTest {
|
||||
private StickerProtocolTest() {}
|
||||
|
||||
public static void main(String[] arguments) throws IOException {
|
||||
acceptsPublicPackNames();
|
||||
rejectsNonPackNetworkTargets();
|
||||
chunkWirePreservesBytes();
|
||||
messageWirePreservesServerAuthor();
|
||||
rejectsMalformedChunks();
|
||||
servesOnlyCataloguedContentAddressedPngs();
|
||||
rejectsWrongAtlasDimensions();
|
||||
System.out.println("STICKER_PROTOCOL_PASS");
|
||||
}
|
||||
|
||||
private static void acceptsPublicPackNames() {
|
||||
for (String input : List.of("Pack_Name", "https://t.me/addstickers/Pack_Name",
|
||||
" https://t.me/addstickers/Pack_Name ")) {
|
||||
equal("Pack_Name", TelegramPack.fromInput(input).name());
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejectsNonPackNetworkTargets() {
|
||||
for (String input : List.of("https://localhost/addstickers/Pack_Name",
|
||||
"https://t.me.attacker.test/addstickers/Pack_Name",
|
||||
"https://t.me:443/addstickers/Pack_Name",
|
||||
"https://user:secret@t.me/addstickers/Pack_Name",
|
||||
"https://t.me/addstickers/../secret", "https://t.me/addstickers/a%2fb",
|
||||
"https://t.me/addstickers/Pack_Name?redirect=localhost",
|
||||
"https://t.me/addstickers/Pack_Name#extra",
|
||||
"http://t.me/addstickers/Pack_Name", "file:///etc/passwd",
|
||||
"https://t.me/SomeUser", "https://t.me/addstickers/", "")) {
|
||||
rejects(() -> TelegramPack.fromInput(input));
|
||||
}
|
||||
}
|
||||
|
||||
private static void chunkWirePreservesBytes() {
|
||||
byte[] source = new byte[24_576];
|
||||
Arrays.fill(source, (byte) 37);
|
||||
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), RegistryAccess.EMPTY);
|
||||
try {
|
||||
var original = new StickerPackets.AssetChunk("a".repeat(64), 0, 2, source);
|
||||
StickerPackets.AssetChunk.CODEC.encode(buffer, original);
|
||||
var received = StickerPackets.AssetChunk.CODEC.decode(buffer);
|
||||
equal(original.id(), received.id());
|
||||
equal(0, received.part());
|
||||
equal(2, received.total());
|
||||
if (!Arrays.equals(source, received.bytes()) || buffer.readableBytes() != 0) {
|
||||
throw new AssertionError("Chunk codec lost bytes or left an unread payload");
|
||||
}
|
||||
} finally {
|
||||
buffer.release();
|
||||
}
|
||||
}
|
||||
|
||||
private static void messageWirePreservesServerAuthor() {
|
||||
var original = new StickerPackets.StickerMessage(
|
||||
UUID.fromString("12345678-1234-1234-1234-123456789abc"), "StickerQA", "b".repeat(64));
|
||||
RegistryFriendlyByteBuf buffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), RegistryAccess.EMPTY);
|
||||
try {
|
||||
StickerPackets.StickerMessage.CODEC.encode(buffer, original);
|
||||
equal(original, StickerPackets.StickerMessage.CODEC.decode(buffer));
|
||||
} finally {
|
||||
buffer.release();
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejectsMalformedChunks() {
|
||||
String id = "a".repeat(64);
|
||||
rejects(() -> new StickerPackets.AssetChunk(id, -1, 1, new byte[1]));
|
||||
rejects(() -> new StickerPackets.AssetChunk(id, 1, 1, new byte[1]));
|
||||
rejects(() -> new StickerPackets.AssetChunk(id, 0, 87, new byte[24_576]));
|
||||
rejects(() -> new StickerPackets.AssetChunk(id, 0, 1, new byte[0]));
|
||||
rejects(() -> new StickerPackets.AssetChunk(id, 0, 1, new byte[24_577]));
|
||||
rejects(() -> new StickerPackets.AssetChunk(id, 0, 2, new byte[3]));
|
||||
rejects(() -> new StickerPackets.AssetRequest("../secret"));
|
||||
}
|
||||
|
||||
private static void servesOnlyCataloguedContentAddressedPngs() throws IOException {
|
||||
Path root = Files.createTempDirectory("wowmine-sticker-protocol-");
|
||||
try {
|
||||
byte[] png = png(128);
|
||||
String id = hash(png);
|
||||
Files.createDirectory(root.resolve("assets"));
|
||||
Path asset = root.resolve("assets").resolve(id + ".png");
|
||||
Files.write(asset, png);
|
||||
writeCatalog(root, List.of(new StickerCatalog.Sticker(id, "", 1)));
|
||||
if (!Arrays.equals(png, ServerCatalog.load(root).asset(id))) {
|
||||
throw new AssertionError("Server changed validated PNG bytes");
|
||||
}
|
||||
writeCatalog(root, List.of());
|
||||
rejectsIo(() -> ServerCatalog.load(root).asset(id));
|
||||
writeCatalog(root, List.of(new StickerCatalog.Sticker(id, "", 1)));
|
||||
png[png.length - 1] ^= 1;
|
||||
Files.write(asset, png);
|
||||
rejectsIo(() -> ServerCatalog.load(root).asset(id));
|
||||
} finally {
|
||||
removeFixture(root);
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejectsWrongAtlasDimensions() throws IOException {
|
||||
Path root = Files.createTempDirectory("wowmine-sticker-dimensions-");
|
||||
try {
|
||||
byte[] png = png(64);
|
||||
String id = hash(png);
|
||||
Files.createDirectory(root.resolve("assets"));
|
||||
Files.write(root.resolve("assets").resolve(id + ".png"), png);
|
||||
writeCatalog(root, List.of(new StickerCatalog.Sticker(id, "", 1)));
|
||||
rejectsIo(() -> ServerCatalog.load(root).asset(id));
|
||||
} finally {
|
||||
removeFixture(root);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] png(int width) throws IOException {
|
||||
var image = new BufferedImage(width, 128, BufferedImage.TYPE_INT_ARGB);
|
||||
image.setRGB(0, 0, 0xff336699);
|
||||
try (var output = new java.io.ByteArrayOutputStream()) {
|
||||
if (!ImageIO.write(image, "png", output)) {
|
||||
throw new IOException("No PNG writer in test runtime");
|
||||
}
|
||||
return output.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static String hash(byte[] bytes) {
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
} catch (NoSuchAlgorithmException error) {
|
||||
throw new AssertionError(error);
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeCatalog(Path root, List<StickerCatalog.Sticker> stickers) throws IOException {
|
||||
var catalog = new StickerCatalog(1, List.of(new StickerCatalog.Pack("Fixture", "Fixture", stickers)));
|
||||
Files.writeString(root.resolve("catalog.json"), new Gson().toJson(catalog));
|
||||
}
|
||||
|
||||
private static void removeFixture(Path root) throws IOException {
|
||||
try (var paths = Files.walk(root)) {
|
||||
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
|
||||
Files.delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejects(Runnable action) {
|
||||
try {
|
||||
action.run();
|
||||
} catch (IllegalArgumentException expected) {
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("Invalid protocol input was accepted");
|
||||
}
|
||||
|
||||
private static void rejectsIo(IoAction action) throws IOException {
|
||||
try {
|
||||
action.run();
|
||||
} catch (IOException expected) {
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("Invalid catalog asset was served");
|
||||
}
|
||||
|
||||
private static void equal(Object expected, Object actual) {
|
||||
if (!expected.equals(actual)) {
|
||||
throw new AssertionError("Expected " + expected + ", got " + actual);
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface IoAction {
|
||||
void run() throws IOException;
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package net.wowmine.stickers;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/** Main-style protocol tests; exercises the real archive container, without an audio device. */
|
||||
public final class VoiceFramesTest {
|
||||
private VoiceFramesTest() {}
|
||||
|
||||
public static void main(String[] arguments) {
|
||||
preservesExactOpusBytesAndFrameOrder();
|
||||
acceptsMaximumDurationAndFrameSize();
|
||||
rejectsInvalidFrameInputs();
|
||||
rejectsMalformedContainers();
|
||||
snapshotsBothBoundaries();
|
||||
System.out.println("VOICE_FRAMES_PASS");
|
||||
}
|
||||
|
||||
private static void preservesExactOpusBytesAndFrameOrder() {
|
||||
List<byte[]> frames = List.of(new byte[] {(byte) 0xf8, (byte) 0xff, (byte) 0xfe},
|
||||
new byte[] {0, 1, (byte) 0x80});
|
||||
byte[] expected = {0x57, 0x56, 0x4f, 0x31, 0, 0, 0, 2,
|
||||
0, 3, (byte) 0xf8, (byte) 0xff, (byte) 0xfe, 0, 3, 0, 1, (byte) 0x80};
|
||||
equalBytes(expected, VoiceFrames.encode(frames));
|
||||
equalFrames(frames, VoiceFrames.decode(expected));
|
||||
}
|
||||
|
||||
private static void acceptsMaximumDurationAndFrameSize() {
|
||||
byte[] frame = new byte[ChatHistory.VOICE_FRAME_BYTES];
|
||||
for (int index = 0; index < frame.length; index++) {
|
||||
frame[index] = (byte) index;
|
||||
}
|
||||
List<byte[]> frames = Collections.nCopies(ChatHistory.VOICE_FRAMES, frame);
|
||||
byte[] packed = VoiceFrames.encode(frames);
|
||||
if (packed.length != 8 + ChatHistory.VOICE_FRAMES * (2 + frame.length)) {
|
||||
throw new AssertionError("Maximum voice container lost framing or payload bytes");
|
||||
}
|
||||
equalFrames(frames, VoiceFrames.decode(packed));
|
||||
}
|
||||
|
||||
private static void rejectsInvalidFrameInputs() {
|
||||
for (List<byte[]> frames : List.<List<byte[]>>of(
|
||||
List.of(),
|
||||
Collections.nCopies(ChatHistory.VOICE_FRAMES + 1, new byte[] {1}),
|
||||
List.of(new byte[0]),
|
||||
List.of(new byte[ChatHistory.VOICE_FRAME_BYTES + 1]),
|
||||
Arrays.asList(new byte[] {1}, null))) {
|
||||
rejects(() -> VoiceFrames.encode(frames));
|
||||
}
|
||||
rejects(() -> VoiceFrames.encode(null));
|
||||
}
|
||||
|
||||
private static void rejectsMalformedContainers() {
|
||||
byte[] valid = VoiceFrames.encode(List.of(new byte[] {1, 2}, new byte[] {3}));
|
||||
for (int length = 0; length < valid.length; length++) {
|
||||
byte[] truncated = Arrays.copyOf(valid, length);
|
||||
rejects(() -> VoiceFrames.decode(truncated));
|
||||
}
|
||||
for (int count : new int[] {0, -1, ChatHistory.VOICE_FRAMES + 1, Integer.MAX_VALUE}) {
|
||||
byte[] badCount = valid.clone();
|
||||
ByteBuffer.wrap(badCount).putInt(4, count);
|
||||
rejects(() -> VoiceFrames.decode(badCount));
|
||||
}
|
||||
for (int length : new int[] {0, ChatHistory.VOICE_FRAME_BYTES + 1, 65_535}) {
|
||||
byte[] badLength = valid.clone();
|
||||
ByteBuffer.wrap(badLength).putShort(8, (short) length);
|
||||
rejects(() -> VoiceFrames.decode(badLength));
|
||||
}
|
||||
byte[] unknownVersion = valid.clone();
|
||||
unknownVersion[3]++;
|
||||
rejects(() -> VoiceFrames.decode(unknownVersion));
|
||||
rejects(() -> VoiceFrames.decode(Arrays.copyOf(valid, valid.length + 1)));
|
||||
rejects(() -> VoiceFrames.decode(new byte[ChatHistory.MEDIA_BYTES + 1]));
|
||||
rejects(() -> VoiceFrames.decode(null));
|
||||
}
|
||||
|
||||
private static void snapshotsBothBoundaries() {
|
||||
byte[] source = {3, 7, 11};
|
||||
var frames = new ArrayList<byte[]>();
|
||||
frames.add(source);
|
||||
byte[] packed = VoiceFrames.encode(frames);
|
||||
source[0] = 99;
|
||||
frames.clear();
|
||||
List<byte[]> decoded = VoiceFrames.decode(packed);
|
||||
Arrays.fill(packed, (byte) 0);
|
||||
decoded.getFirst()[0] = 42;
|
||||
decoded.iterator().next()[1] = 42;
|
||||
equalFrames(List.of(new byte[] {3, 7, 11}), decoded);
|
||||
try {
|
||||
decoded.set(0, new byte[] {99});
|
||||
} catch (UnsupportedOperationException expected) {
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("Decoded frame list permits structural mutation");
|
||||
}
|
||||
|
||||
private static void equalFrames(List<byte[]> expected, List<byte[]> actual) {
|
||||
if (expected.size() != actual.size()) {
|
||||
throw new AssertionError("Frame count changed");
|
||||
}
|
||||
for (int index = 0; index < expected.size(); index++) {
|
||||
equalBytes(expected.get(index), actual.get(index));
|
||||
}
|
||||
}
|
||||
|
||||
private static void equalBytes(byte[] expected, byte[] actual) {
|
||||
if (!Arrays.equals(expected, actual)) {
|
||||
throw new AssertionError("Voice bytes changed");
|
||||
}
|
||||
}
|
||||
|
||||
private static void rejects(Runnable action) {
|
||||
try {
|
||||
action.run();
|
||||
} catch (IllegalArgumentException expected) {
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("Malformed voice data was accepted");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user