Files
LihonT/services/members/catalog.py
cheb0chik 9de69113b5 LihonT 2 Serena
LihonT Store: a separate app with a catalog of avatar frames and chat bubbles made by members (browse, add with "+", author
profiles, publishing), signed in through the TikTok that carries the mod (an exported no-window activity that answers only the
store, checked by package name and signing key). The mod gets frames made from any picture (a photo is cut into a ring), the
library of the store in the frame picker and for bubbles, other members' published bubbles and one picture per chat for both
people. The members service gets the catalog, the account library, uploads that are re-made with Pillow, an AI first pass
(Groq) and the owner's Telegram bot with accept and reject buttons. The build tools pass long file lists through an argument
file. Nothing a member sends is shown to others before it is approved.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 15:56:00 +03:00

252 lines
14 KiB
Python

"""The public catalog of member-made frames and chat bubbles (the data behind the LihonT Store app).
An item is a row of the `art` table that its author has listed and the owner has approved. Listing is by time, newest first, with a
cursor; an author's profile is the same list for one account. Pictures are served by the members service itself (GET /art/<id>.png).
Everything the author sends is judged first by the AI and then by the owner (see modbot); only approved items are ever listed.
"""
from __future__ import annotations
import hashlib
import hmac
import re
import community
from community import INSTALL, valid_uid
KINDS = ("frame", "bubble")
SIZES = {"frame": (community.FRAME_SIDE, True), "bubble": (community.BUBBLE_SIDE, False)}
PAGE = 30
ART_ID = re.compile(r"[0-9a-f]{24}\Z")
CURSOR = re.compile(r"(\d{1,12}):([0-9a-f]{24})\Z")
COLUMNS = "a.id, a.kind, a.name, a.description, a.uid, a.listed_at, a.installs, " \
"(SELECT unique_id FROM shape_owner o WHERE o.uid = a.uid)"
def _item(row):
return {"id": row[0], "kind": row[1], "name": row[2], "description": row[3],
"author": {"uid": row[4], "name": row[7]}, "at": row[5], "installs": row[6]}
class Catalog:
def __init__(self, registry):
self.r = registry
self.operations = {
"publish": self.publish, "catalog": self.listing, "item": self.item, "profile": self.profile,
"mine": self.mine, "unpublish": self.unpublish, "install": self.install, "bubble_choose": self.choose_bubble,
"prove": self.prove, "library_add": self.library_add, "library_remove": self.library_remove, "library": self.library,
}
def call(self, operation, payload):
return self.operations[operation](payload)
# ---- reading ---------------------------------------------------------------------------------------------
def _page(self, where, args, cursor, limit):
limit = limit if isinstance(limit, int) and 1 <= limit <= PAGE else PAGE
sql = ("SELECT " + COLUMNS + " FROM art a WHERE a.status='approved' AND a.listed=1 "
"AND a.uid NOT IN (SELECT uid FROM blocked)" + where)
if cursor:
match = CURSOR.fullmatch(cursor) if isinstance(cursor, str) else None
if match is None:
raise ValueError("Bad cursor")
sql += " AND (a.listed_at < ? OR (a.listed_at = ? AND a.id < ?))"
args = args + [int(match.group(1)), int(match.group(1)), match.group(2)]
sql += " ORDER BY a.listed_at DESC, a.id DESC LIMIT ?"
with self.r.connect() as db:
rows = db.execute(sql, args + [limit]).fetchall()
items = [_item(row) for row in rows]
more = "%d:%s" % (rows[-1][5], rows[-1][0]) if len(rows) == limit else None
return items, more
def listing(self, p):
kind = p.get("kind")
if kind is not None and kind not in KINDS:
raise ValueError("Unknown kind")
items, more = self._page(" AND a.kind=?" if kind else "", [kind] if kind else [], p.get("cursor"), p.get("limit"))
return {"items": items, "next": more}
def item(self, p):
art_id = p.get("id")
if not isinstance(art_id, str) or not ART_ID.fullmatch(art_id):
raise ValueError("Unknown item")
items, _ = self._page(" AND a.id=?", [art_id], None, 1)
if not items:
raise ValueError("Unknown item")
return {"item": items[0]}
def profile(self, p):
uid = p.get("uid")
if not valid_uid(uid):
raise ValueError("Invalid account ID")
items, more = self._page(" AND a.uid=?", [uid], p.get("cursor"), p.get("limit"))
with self.r.connect() as db:
name = db.execute("SELECT unique_id FROM shape_owner WHERE uid=?", (uid,)).fetchone()
totals = db.execute("SELECT kind, COUNT(*), COALESCE(SUM(installs),0) FROM art WHERE uid=? AND status='approved' "
"AND listed=1 GROUP BY kind", (uid,)).fetchall()
return {"uid": uid, "name": name[0] if name else None, "items": items, "next": more,
"totals": {row[0]: {"count": row[1], "installs": row[2]} for row in totals}}
# ---- the author's own side (the installation must have proven the account) -----------------------------
def _owner(self, uid, installation):
if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation):
raise ValueError("Invalid account ID or installation code")
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
with self.r.connect() as db:
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
if owner is None or not hmac.compare_digest(owner[0], digest):
raise ValueError("Prove the account first")
return digest
def mine(self, p):
"""Everything this account has sent, in any state, with the reason when something was not accepted."""
uid = p.get("uid")
self._owner(uid, p.get("installation"))
with self.r.connect() as db:
rows = db.execute("SELECT id, kind, name, description, status, reason, listed, created_at, installs FROM art "
"WHERE uid=? ORDER BY created_at DESC LIMIT 100", (uid,)).fetchall()
return {"items": [{"id": r[0], "kind": r[1], "name": r[2], "description": r[3], "status": r[4],
"reason": r[5] if r[4] == "rejected" else "", "listed": bool(r[6]), "at": r[7], "installs": r[8]}
for r in rows]}
def publish(self, p):
"""Lists a picture in the catalog. It goes to the AI and then to the owner; until approved it is not shown to anyone."""
kind = p.get("kind")
if kind not in KINDS:
raise ValueError("Unknown kind")
side, square = SIZES[kind]
name = community.clean_name(p.get("name"), "Без названия")
description = community.clean_name(p.get("description"), "", 200)
got = self.r._receive(kind, p.get("uid"), p.get("installation"), p.get("unique_id"), name, p.get("png"),
side, square, listed=True, description=description)
if "art" not in got:
return got
return {"ok": True, "published": True, "id": got["art"]["id"], "status": got["art"]["status"]}
def unpublish(self, p):
uid = p.get("uid")
self._owner(uid, p.get("installation"))
art_id = p.get("id")
if not isinstance(art_id, str) or not ART_ID.fullmatch(art_id):
raise ValueError("Unknown item")
with self.r.connect() as db:
changed = db.execute("UPDATE art SET listed=0 WHERE id=? AND uid=?", (art_id, uid)).rowcount
if not changed:
raise ValueError("Not your item")
return {"ok": True}
def install(self, p):
"""The "+" of the store: counts one installation once per item, never more."""
installation, art_id = p.get("installation"), p.get("id")
if not isinstance(installation, str) or not INSTALL.fullmatch(installation):
raise ValueError("Invalid installation code")
if not isinstance(art_id, str) or not ART_ID.fullmatch(art_id):
raise ValueError("Unknown item")
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
with self.r.connect() as db:
if not db.execute("SELECT 1 FROM art WHERE id=? AND status='approved' AND listed=1", (art_id,)).fetchone():
raise ValueError("Unknown item")
db.execute("INSERT OR IGNORE INTO art_installs(art_id, installation) VALUES(?,?)", (art_id, digest))
count = db.execute("SELECT COUNT(*) FROM art_installs WHERE art_id=?", (art_id,)).fetchone()[0]
db.execute("UPDATE art SET installs=? WHERE id=?", (count, art_id))
return {"ok": True, "installs": count}
# ---- the account's library: what it added with "+" in the store; the mod offers these in its pickers ---------
def prove(self, p):
"""Binds the calling installation to the account (the code in the bio, once) so it may use the account's rights."""
uid, installation = p.get("uid"), p.get("installation")
if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation):
raise ValueError("Invalid account ID or installation code")
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
with self.r.connect() as db:
if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone():
raise ValueError("Account excluded")
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
if owner is not None and hmac.compare_digest(owner[0], digest):
return {"ok": True, "published": True}
reply = self.r._prove(uid, digest, p.get("unique_id"))
return reply if reply is not None else {"ok": True, "published": True}
def library_add(self, p):
"""The "+" of the store: puts an approved catalog item into the account's library and counts the installation once."""
uid = p.get("uid")
digest = self._owner(uid, p.get("installation"))
art_id = p.get("id")
if not isinstance(art_id, str) or not ART_ID.fullmatch(art_id):
raise ValueError("Unknown item")
with self.r.connect() as db:
if not db.execute("SELECT 1 FROM art WHERE id=? AND status='approved' AND listed=1", (art_id,)).fetchone():
raise ValueError("Unknown item")
db.execute("INSERT OR IGNORE INTO account_library(uid, art_id, added_at) VALUES(?,?,?)", (uid, art_id, int(self.r.clock())))
db.execute("INSERT OR IGNORE INTO art_installs(art_id, installation) VALUES(?,?)", (art_id, digest))
count = db.execute("SELECT COUNT(*) FROM art_installs WHERE art_id=?", (art_id,)).fetchone()[0]
db.execute("UPDATE art SET installs=? WHERE id=?", (count, art_id))
return {"ok": True, "installs": count}
def library_remove(self, p):
uid = p.get("uid")
self._owner(uid, p.get("installation"))
art_id = p.get("id")
if not isinstance(art_id, str) or not ART_ID.fullmatch(art_id):
raise ValueError("Unknown item")
with self.r.connect() as db:
db.execute("DELETE FROM account_library WHERE uid=? AND art_id=?", (uid, art_id))
return {"ok": True}
def library(self, p):
"""What this account has added, newest first (only what is still approved and listed)."""
uid = p.get("uid")
self._owner(uid, p.get("installation"))
with self.r.connect() as db:
rows = db.execute("SELECT " + COLUMNS + " FROM account_library l JOIN art a ON a.id = l.art_id "
"WHERE l.uid=? AND a.status='approved' AND a.listed=1 ORDER BY l.added_at DESC LIMIT 200", (uid,)).fetchall()
return {"items": [_item(row) for row in rows]}
# ---- the bubble an account shows to other members ------------------------------------------------------
def choose_bubble(self, p):
"""Publishes (or, for "none", withdraws) the bubble this account wants others to see on its messages, on the same terms as a
frame: the account is proven once. The bubble is the account's own picture or an approved one from the catalog."""
uid, installation, art_id = p.get("uid"), p.get("installation"), p.get("id")
if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation):
raise ValueError("Invalid account ID or installation code")
if art_id != "none" and not (isinstance(art_id, str) and ART_ID.fullmatch(art_id)):
raise ValueError("Unknown bubble")
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
with self.r.connect() as db:
if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone():
raise ValueError("Account excluded")
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
has = db.execute("SELECT 1 FROM account_bubbles WHERE uid=?", (uid,)).fetchone()
proven = owner is not None and hmac.compare_digest(owner[0], digest)
if not proven and art_id == "none" and not has:
return {"ok": True, "published": True, "id": "none"}
if not proven:
reply = self.r._prove(uid, digest, p.get("unique_id"))
if reply is not None:
return reply
with self.r.connect() as db:
if art_id == "none":
db.execute("DELETE FROM account_bubbles WHERE uid=?", (uid,))
else:
art = db.execute("SELECT kind, uid, status, listed FROM art WHERE id=?", (art_id,)).fetchone()
ok = art is not None and art[0] == "bubble" and ((art[1] == uid and art[2] != "rejected") or (art[3] and art[2] == "approved"))
if not ok:
raise ValueError("This bubble is not available for this account")
db.execute("INSERT INTO account_bubbles(uid, art_id, updated_at) VALUES(?,?,?) "
"ON CONFLICT(uid) DO UPDATE SET art_id=excluded.art_id, updated_at=excluded.updated_at",
(uid, art_id, int(self.r.clock())))
return {"ok": True, "published": True, "id": art_id}
def bubbles_of(self, uids):
"""{uid: art id} of the approved bubbles these accounts show to others."""
if not uids:
return {}
marks = ",".join("?" for _ in uids)
with self.r.connect() as db:
rows = db.execute("SELECT b.uid, b.art_id FROM account_bubbles b JOIN art a ON a.id = b.art_id "
"WHERE b.uid IN (" + marks + ") AND a.status='approved' AND a.kind='bubble' "
"AND b.uid NOT IN (SELECT uid FROM blocked)", list(uids)).fetchall()
return {uid: art_id for uid, art_id in rows}