A pair of people can have a kitten, a puppy or a lion cub in place of TikTok's streak creature: it grows with the days of the streak (cub, teen, adult, elder), goes grey while the streak is about to burn out, can be dragged in the chat and is also shown on the big streak screen. An animal is given by a link (lihont.space/pet) that the friend accepts. The drawings are made by scripts/make_pet_designs.py and served as strips of frames. Also here: the promo video scripts (make_pet_video.py on top of make_store_video.py), a retry pause for strips that failed to load, stricter checks in the answer to a gift. Work in progress: the gift service is not switched on for everyone yet and there is no public build with the animals. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
275 lines
15 KiB
Python
275 lines
15 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 base64
|
|
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, "report": self.report, "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 active_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:
|
|
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone():
|
|
raise ValueError("Account excluded")
|
|
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 report(self, p):
|
|
"""The detailed rejection report (PDF, base64) of one of this account's own pictures. Made now when it was not made at the time."""
|
|
uid, art_id = p.get("uid"), str(p.get("id") or "")
|
|
self._owner(uid, p.get("installation"))
|
|
with self.r.connect() as db:
|
|
row = db.execute("SELECT status FROM art WHERE id=? AND uid=?", (art_id, uid)).fetchone()
|
|
if row is None or row[0] != "rejected":
|
|
raise ValueError("No report for this picture")
|
|
pdf = self.r.art_report(art_id)
|
|
if pdf is None:
|
|
import report
|
|
data = self.r.art_bytes(art_id, approved_only=False)
|
|
art = self.r.art(art_id)
|
|
detail = report.detail_check(data) if data else {"ok": None}
|
|
if detail["ok"] is None:
|
|
raise ValueError("The report is not ready, try later")
|
|
pdf = report.build_pdf(data, detail, name=art["name"], kind=art["kind"], art_id=art_id)
|
|
self.r.art_report_save(art_id, pdf)
|
|
return {"ok": True, "pdf": base64.b64encode(pdf).decode("ascii")}
|
|
|
|
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 active_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 active_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 active_blocked)", list(uids)).fetchall()
|
|
return {uid: art_id for uid, art_id in rows}
|