- Shared moderated MP3 profile music (with floating mini-player and MediaSession controls, zero bubble when absent) - AI video dubbing into Russian with burned-in ASS subtitles inside AgentChat (`services/members/dub.py`) - Picture-in-Picture 9:16 and background audio playback (`PlayControl` + `play_patch.py`) - System/custom .ttf fonts & emoji packs (`FontsAndEmoji`), account cleaner (`AccountCleaner`) - Feed blacklist, muted sound restoration, OLED burn-in shift, A/B flag editor, presets, long comments - Updated site homepage (`src/web/index.html`) for LihonT 2.3.0 Serena
1025 lines
60 KiB
Python
1025 lines
60 KiB
Python
"""Self-reported LihonT presence registry. Standard library only; bind to localhost.
|
|
|
|
This is a community marker, not proof of TikTok account ownership or official
|
|
verification. A modified client can claim another UID. No TikTok credentials
|
|
are accepted. Installation secrets permit withdrawing only that installation's
|
|
contribution. Public lookup responses expose only requested membership bits.
|
|
|
|
Avatar outlines are different: one is published for an account only after that
|
|
account's public bio held its code (the same proof as the niche badge), and the
|
|
installation that proved it keeps the right to change it.
|
|
"""
|
|
from __future__ import annotations
|
|
import argparse
|
|
import base64
|
|
import hmac
|
|
import os
|
|
import secrets
|
|
import sys
|
|
import urllib.request
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
from collections import defaultdict, deque
|
|
from contextlib import contextmanager
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
import accounts
|
|
import ai
|
|
import catalog
|
|
import codegate
|
|
import community
|
|
import dub
|
|
import music
|
|
from community import INSTALL, UID, valid_uid
|
|
|
|
LIFETIME = 30 * 86400
|
|
UNIQUE = re.compile(r"[A-Za-z0-9_.]{2,24}\Z")
|
|
# Avatar outlines a member can publish; the round one is TikTok's own and is never stored.
|
|
SHAPES = ("flower", "squircle", "hexagon", "heart", "triangle")
|
|
# Avatar frames: "pack.frame" ids of the catalog on the site (the catalog itself is not known here, only the shape of the id).
|
|
FRAME = re.compile(r"[a-z0-9][a-z0-9_-]{0,23}\.[a-z0-9][a-z0-9_-]{0,23}\Z")
|
|
# Packs whose frames only the accounts that were given them may use. A grant is one frame ("vip.creator") or a whole pack ("vip.*").
|
|
RESTRICTED_PACKS = ("vip",)
|
|
GRANT = re.compile(r"[a-z0-9][a-z0-9_-]{0,23}\.(\*|[a-z0-9][a-z0-9_-]{0,23})\Z")
|
|
# A frame a member made: "u." and the first 24 hex digits of the picture's SHA-256.
|
|
CUSTOM = re.compile(r"u\.[0-9a-f]{24}\Z")
|
|
ART_STATES = ("new", "review", "approved", "rejected")
|
|
SPECIES = ("cat", "dog", "lion") # the animals known when the site's catalog cannot be read
|
|
# The animals are listed in the site's catalog (assets/pets/index.json, made by scripts/build_pets_catalog.py); the service reads the same
|
|
# file where the site keeps it, so a new animal needs no change here and no restart.
|
|
PETS_INDEX = Path(os.environ.get("LIHONT_PETS_INDEX", "/var/www/lihont/assets/pets/index.json"))
|
|
SPECIES_ID = re.compile(r"[a-z][a-z0-9]{1,15}\Z")
|
|
_species_seen = [None, SPECIES] # the catalog file's modification time and the animals read from it
|
|
|
|
|
|
def species_list():
|
|
"""The animals a pair can be given: the catalog file when it can be read, else the last good list, else the three first ones."""
|
|
try:
|
|
stamp = PETS_INDEX.stat().st_mtime
|
|
if _species_seen[0] != stamp:
|
|
data = json.loads(PETS_INDEX.read_text(encoding="utf-8"))
|
|
ids = tuple(a["id"] for a in data["animals"][:60] if isinstance(a, dict) and SPECIES_ID.match(str(a.get("id", ""))))
|
|
_species_seen[0], _species_seen[1] = stamp, (ids or SPECIES)
|
|
except (OSError, ValueError, KeyError, TypeError):
|
|
pass # a half-written or missing file: keep what was read last
|
|
return _species_seen[1]
|
|
UPLOAD_BODY = 300_000
|
|
CHAT_BODY = 400_000 # a talk with the model: the last turns and up to two small pictures
|
|
# Operations by how often one address may call them: reads, the account's own small writes, installs, uploads.
|
|
ACCOUNTS = ("tg_start", "tg_poll", "tg_register", "tg_me", "tg_link_tiktok", "tg_logout", "tg_delete", "tg_notify", "follow", "unfollow",
|
|
"following", "followers", "follow_info", "inbox", "inbox_seen")
|
|
AI = ("ai_status", "ai_chat")
|
|
DUB = ("dub_start", "dub_status")
|
|
CODE = ("code_status", "code_chat", "code_consent") # LihonC, the coding agent
|
|
READS = ("ai_status", "dub_status", "code_status", "lookup", "pair_lookup", "pet_lookup", "species_lookup", "catalog", "item", "profile", "library", "tg_poll", "tg_me", "following", "followers", "follow_info", "inbox", "music_lookup", "music_mine")
|
|
WRITES = ("ai_chat", "dub_start", "code_chat", "code_consent", "species_offer", "species_answer", "pet_revert", "pet_clear", "tg_start", "tg_register", "tg_link_tiktok", "tg_logout", "tg_delete", "tg_notify", "follow", "unfollow", "inbox_seen",
|
|
"shape", "avatar_frame", "mine", "report", "unpublish", "bubble_choose", "prove", "library_add", "library_remove", "music_select", "music_clear")
|
|
UPLOADS = ("frame_upload", "bubble_upload", "pet_upload", "publish", "music_upload")
|
|
CATALOG = ("publish", "catalog", "item", "profile", "mine", "report", "unpublish", "install", "bubble_choose", "prove", "library_add",
|
|
"library_remove", "library")
|
|
OPERATIONS = ("presence", "lookup", "withdraw", "code", "claim", "shape", "avatar_frame", "frame_upload", "bubble_upload",
|
|
"pair_lookup", "pair_clear", "pet_upload", "pet_lookup", "pet_revert", "pet_clear",
|
|
"species_offer", "species_lookup", "species_answer",
|
|
"music_upload", "music_lookup", "music_mine", "music_select", "music_clear") + CATALOG + ACCOUNTS + AI + DUB + CODE
|
|
# The niche-mod badge can be claimed until this moment (Moscow time).
|
|
CLAIM_DEADLINE = 1794735240 # 2026-11-15 12:34:00 +03:00
|
|
|
|
|
|
def fetch_profile(unique_id):
|
|
"""Public TikTok profile page of @unique_id as (account id, bio), or None. Anonymous GET only."""
|
|
request = urllib.request.Request(
|
|
"https://www.tiktok.com/@" + unique_id,
|
|
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
|
"(KHTML, like Gecko) Chrome/124.0 Safari/537.36"})
|
|
with urllib.request.urlopen(request, timeout=20) as response:
|
|
page = response.read(3_000_000).decode("utf-8", "replace")
|
|
match = re.search(r'<script id="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>(.*?)</script>', page, re.S)
|
|
if not match:
|
|
return None
|
|
user = (json.loads(match.group(1)).get("__DEFAULT_SCOPE__", {})
|
|
.get("webapp.user-detail", {}).get("userInfo", {}).get("user", {}))
|
|
if not user.get("id"):
|
|
return None
|
|
return str(user["id"]), str(user.get("signature") or "")
|
|
|
|
|
|
def frame_permitted(frame, grants):
|
|
"""True when the frame is open to everyone, or one of `grants` (frame ids and "pack.*") covers it."""
|
|
pack = frame.split(".", 1)[0]
|
|
return pack not in RESTRICTED_PACKS or frame in grants or pack + ".*" in grants
|
|
|
|
|
|
class Registry:
|
|
def __init__(self, path, clock=time.time, fetcher=fetch_profile, art_dir=None):
|
|
self.path, self.clock, self.fetcher = str(path), clock, fetcher
|
|
self.art_dir = Path(art_dir) if art_dir else Path(path).resolve().parent / "art"
|
|
self.catalog = catalog.Catalog(self)
|
|
with self.connect() as db:
|
|
db.execute("PRAGMA journal_mode=WAL")
|
|
db.execute("CREATE TABLE IF NOT EXISTS presence (installation TEXT NOT NULL, uid TEXT NOT NULL, last_seen INTEGER NOT NULL, frame_color TEXT NOT NULL DEFAULT 'green', PRIMARY KEY(installation, uid))")
|
|
columns = {row[1] for row in db.execute("PRAGMA table_info(presence)")}
|
|
if "frame_color" not in columns:
|
|
db.execute("ALTER TABLE presence ADD COLUMN frame_color TEXT NOT NULL DEFAULT 'green'")
|
|
db.execute("CREATE INDEX IF NOT EXISTS presence_uid ON presence(uid, last_seen)")
|
|
db.execute("CREATE TABLE IF NOT EXISTS blocked (uid TEXT PRIMARY KEY)")
|
|
if "until" not in {row[1] for row in db.execute("PRAGMA table_info(blocked)")}:
|
|
db.execute("ALTER TABLE blocked ADD COLUMN until INTEGER NOT NULL DEFAULT 0") # 0 = for ever
|
|
# what every check reads: the rows whose ban has not run out
|
|
db.execute("CREATE VIEW IF NOT EXISTS active_blocked AS SELECT uid FROM blocked "
|
|
"WHERE until = 0 OR until > CAST(strftime('%s','now') AS INTEGER)")
|
|
db.execute("CREATE TABLE IF NOT EXISTS supporters (uid TEXT PRIMARY KEY, granted_at INTEGER NOT NULL)")
|
|
db.execute("CREATE TABLE IF NOT EXISTS niche (uid TEXT PRIMARY KEY, unique_id TEXT NOT NULL, granted_at INTEGER NOT NULL)")
|
|
db.execute("CREATE TABLE IF NOT EXISTS shapes (uid TEXT PRIMARY KEY, shape TEXT NOT NULL, updated_at INTEGER NOT NULL)")
|
|
db.execute("CREATE TABLE IF NOT EXISTS avatar_frames (uid TEXT PRIMARY KEY, frame TEXT NOT NULL, updated_at INTEGER NOT NULL)")
|
|
db.execute("CREATE TABLE IF NOT EXISTS frame_grants (uid TEXT NOT NULL, frame TEXT NOT NULL, granted_at INTEGER NOT NULL, PRIMARY KEY(uid, frame))")
|
|
db.execute("CREATE TABLE IF NOT EXISTS shape_owner (uid TEXT PRIMARY KEY, installation TEXT NOT NULL, unique_id TEXT NOT NULL, verified_at INTEGER NOT NULL)")
|
|
db.execute("CREATE TABLE IF NOT EXISTS art (id TEXT PRIMARY KEY, kind TEXT NOT NULL, uid TEXT NOT NULL, name TEXT NOT NULL, "
|
|
"sha256 TEXT NOT NULL, status TEXT NOT NULL, reason TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, "
|
|
"decided_at INTEGER, review_message INTEGER)")
|
|
db.execute("CREATE TABLE IF NOT EXISTS pair_art (pair TEXT PRIMARY KEY, art_id TEXT NOT NULL, set_by TEXT NOT NULL, updated_at INTEGER NOT NULL)")
|
|
# the "Серийчик" of a pair: every change is a row, the newest approved one is shown, the older ones can be brought back
|
|
db.execute("CREATE TABLE IF NOT EXISTS pair_pet (id INTEGER PRIMARY KEY AUTOINCREMENT, pair TEXT NOT NULL, art_id TEXT NOT NULL, "
|
|
"set_by TEXT NOT NULL, at INTEGER NOT NULL)")
|
|
db.execute("CREATE INDEX IF NOT EXISTS pair_pet_pair ON pair_pet(pair, id)")
|
|
# the animal of a pair: one word, no picture. `kind` is what both see; an offer waits until the other one accepts it
|
|
db.execute("CREATE TABLE IF NOT EXISTS pair_species (pair TEXT PRIMARY KEY, kind TEXT NOT NULL DEFAULT '', "
|
|
"offer TEXT NOT NULL DEFAULT '', offer_by TEXT NOT NULL DEFAULT '', at INTEGER NOT NULL)")
|
|
for column, ddl in (("description", "TEXT NOT NULL DEFAULT ''"), ("listed", "INTEGER NOT NULL DEFAULT 0"),
|
|
("listed_at", "INTEGER NOT NULL DEFAULT 0"), ("installs", "INTEGER NOT NULL DEFAULT 0")):
|
|
if column not in {row[1] for row in db.execute("PRAGMA table_info(art)")}:
|
|
db.execute("ALTER TABLE art ADD COLUMN %s %s" % (column, ddl))
|
|
db.execute("CREATE TABLE IF NOT EXISTS art_installs (art_id TEXT NOT NULL, installation TEXT NOT NULL, PRIMARY KEY(art_id, installation))")
|
|
db.execute("CREATE TABLE IF NOT EXISTS account_library (uid TEXT NOT NULL, art_id TEXT NOT NULL, added_at INTEGER NOT NULL, PRIMARY KEY(uid, art_id))")
|
|
db.execute("CREATE TABLE IF NOT EXISTS account_bubbles (uid TEXT PRIMARY KEY, art_id TEXT NOT NULL, updated_at INTEGER NOT NULL)")
|
|
db.execute("CREATE INDEX IF NOT EXISTS art_listing ON art(status, listed, listed_at)")
|
|
db.execute("CREATE INDEX IF NOT EXISTS art_status ON art(status, created_at)")
|
|
db.execute("CREATE INDEX IF NOT EXISTS art_uid ON art(uid, created_at)")
|
|
db.execute("CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
|
|
db.execute("INSERT OR IGNORE INTO meta(key,value) VALUES('code_secret',?)", (secrets.token_hex(32),))
|
|
self.accounts = accounts.Accounts(self)
|
|
self.ai = ai.AiGate(self)
|
|
self.dub = dub.DubManager(self)
|
|
self.codegate = codegate.CodeGate(self)
|
|
self.music = music.MusicStore(self)
|
|
|
|
@contextmanager
|
|
def connect(self):
|
|
db = sqlite3.connect(self.path, timeout=10)
|
|
try:
|
|
with db:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
def presence(self, uid, installation, withdraw=False, frame_color="green"):
|
|
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()
|
|
if frame_color not in ("none", "green", "red", "yellow"):
|
|
frame_color = "green"
|
|
now = int(self.clock())
|
|
with self.connect() as db:
|
|
db.execute("DELETE FROM presence WHERE last_seen < ?", (now - LIFETIME,))
|
|
if withdraw:
|
|
db.execute("DELETE FROM presence WHERE installation=? AND uid=?", (digest, uid))
|
|
else:
|
|
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone():
|
|
raise ValueError("Account excluded from the registry")
|
|
existing = db.execute("SELECT 1 FROM presence WHERE installation=? AND uid=?", (digest, uid)).fetchone()
|
|
if not existing and db.execute("SELECT COUNT(*) FROM presence WHERE installation=?", (digest,)).fetchone()[0] >= 20:
|
|
raise ValueError("Too many accounts for one installation")
|
|
db.execute("INSERT INTO presence(installation,uid,last_seen,frame_color) VALUES(?,?,?,?) ON CONFLICT(installation,uid) DO UPDATE SET last_seen=excluded.last_seen,frame_color=excluded.frame_color", (digest, uid, now, frame_color))
|
|
return {"ok": True}
|
|
|
|
def code(self, uid, installation_digest=None):
|
|
"""The proof string for an account: it only ever goes into that account's own bio.
|
|
|
|
With `installation_digest` (the SHA-256 of the installation secret) the code belongs to that one installation as well: a code
|
|
that stays visible in someone's bio proves nothing to any other installation, so it cannot be replayed to take the account over.
|
|
Without it the code is the old one that only knows the account; the niche-mod badge still uses that."""
|
|
if not valid_uid(uid):
|
|
raise ValueError("Invalid account ID")
|
|
with self.connect() as db:
|
|
secret = db.execute("SELECT value FROM meta WHERE key='code_secret'").fetchone()[0]
|
|
message = uid if installation_digest is None else uid + ":" + installation_digest
|
|
digest = hmac.new(bytes.fromhex(secret), message.encode("ascii"), "sha256").digest()
|
|
length = 8 if installation_digest is None else 9 # the code of an installation is nine letters and digits after "LT-"
|
|
return "LT-" + base64.b32encode(digest)[:length].decode("ascii")
|
|
|
|
FETCH_PER_HOUR = 60 # profile reads of every kind, all accounts together: the server is a polite visitor of tiktok.com
|
|
|
|
def _fetch_budget(self):
|
|
"""Keeps the number of TikTok profile reads low so the server's address is not taken for a bot."""
|
|
now = self.clock()
|
|
window = getattr(self, "_fetches", None)
|
|
if window is None:
|
|
window = self._fetches = []
|
|
while window and window[0] < now - 3600:
|
|
window.pop(0)
|
|
if len(window) >= self.FETCH_PER_HOUR:
|
|
raise ValueError("Too many proofs right now, try again in a while")
|
|
window.append(now)
|
|
|
|
def claim(self, uid, unique_id):
|
|
"""Gives the niche-mod badge to `uid` when its public bio holds the account's code."""
|
|
if not valid_uid(uid) or not isinstance(unique_id, str) or not UNIQUE.fullmatch(unique_id):
|
|
raise ValueError("Invalid account")
|
|
with self.connect() as db:
|
|
if db.execute("SELECT 1 FROM niche WHERE uid=?", (uid,)).fetchone():
|
|
return {"ok": True, "granted": True}
|
|
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone():
|
|
raise ValueError("Account excluded")
|
|
if self.clock() > CLAIM_DEADLINE:
|
|
raise ValueError("The badge can no longer be claimed")
|
|
self._fetch_budget()
|
|
try:
|
|
profile = self.fetcher(unique_id)
|
|
except Exception:
|
|
raise ValueError("Could not read the TikTok profile, try again later")
|
|
if profile is None:
|
|
raise ValueError("Profile not found")
|
|
found_uid, bio = profile
|
|
if found_uid != uid:
|
|
raise ValueError("That profile belongs to another account")
|
|
if self.code(uid) not in bio:
|
|
return {"ok": True, "granted": False, "reason": "code_missing"}
|
|
with self.connect() as db:
|
|
db.execute("INSERT OR IGNORE INTO niche(uid,unique_id,granted_at) VALUES(?,?,?)",
|
|
(uid, unique_id, int(self.clock())))
|
|
return {"ok": True, "granted": True}
|
|
|
|
def shape(self, uid, installation, shape, unique_id=None):
|
|
"""Publishes (or, for "circle", withdraws) the avatar outline of `uid`.
|
|
|
|
The installation that proved the account stays bound to it, so that installation changes the outline
|
|
again without another proof. Any other installation has to prove the account first: its public bio
|
|
must hold the account's code, exactly as for the niche badge.
|
|
"""
|
|
if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation):
|
|
raise ValueError("Invalid account ID or installation code")
|
|
if shape != "circle" and shape not in SHAPES:
|
|
raise ValueError("Unknown shape")
|
|
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
|
|
with self.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_shape = db.execute("SELECT 1 FROM shapes WHERE uid=?", (uid,)).fetchone()
|
|
proven = owner is not None and hmac.compare_digest(owner[0], digest)
|
|
if not proven and shape == "circle" and not has_shape:
|
|
return {"ok": True, "published": True, "shape": "circle"} # nothing to withdraw
|
|
if not proven:
|
|
reply = self._prove(uid, digest, unique_id)
|
|
if reply is not None:
|
|
return reply
|
|
with self.connect() as db:
|
|
if shape == "circle":
|
|
db.execute("DELETE FROM shapes WHERE uid=?", (uid,))
|
|
else:
|
|
db.execute("INSERT INTO shapes(uid,shape,updated_at) VALUES(?,?,?) "
|
|
"ON CONFLICT(uid) DO UPDATE SET shape=excluded.shape,updated_at=excluded.updated_at",
|
|
(uid, shape, int(self.clock())))
|
|
return {"ok": True, "published": True, "shape": shape}
|
|
|
|
def _prove(self, uid, digest, unique_id):
|
|
"""The account proves itself with the code in its public bio; the installation is then bound to it.
|
|
|
|
Returns None once the installation is bound, else the reply that tells the client what is missing."""
|
|
if not isinstance(unique_id, str) or not UNIQUE.fullmatch(unique_id):
|
|
return {"ok": True, "published": False, "reason": "proof_needed", "code": self.code(uid, digest)}
|
|
self._fetch_budget()
|
|
try:
|
|
profile = self.fetcher(unique_id)
|
|
except Exception:
|
|
raise ValueError("Could not read the TikTok profile, try again later")
|
|
if profile is None:
|
|
raise ValueError("Profile not found")
|
|
found_uid, bio = profile
|
|
if found_uid != uid:
|
|
raise ValueError("That profile belongs to another account")
|
|
if self.code(uid, digest) not in bio:
|
|
return {"ok": True, "published": False, "reason": "code_missing", "code": self.code(uid, digest)}
|
|
with self.connect() as db:
|
|
db.execute("INSERT INTO shape_owner(uid,installation,unique_id,verified_at) VALUES(?,?,?,?) "
|
|
"ON CONFLICT(uid) DO UPDATE SET installation=excluded.installation,"
|
|
"unique_id=excluded.unique_id,verified_at=excluded.verified_at",
|
|
(uid, digest, unique_id, int(self.clock())))
|
|
return None
|
|
|
|
def avatar_frame(self, uid, installation, frame, unique_id=None):
|
|
"""Publishes (or, for "none", withdraws) the avatar frame of `uid`, on the same terms as the avatar outline:
|
|
the account is proven once by the code in its bio, and the proving installation keeps the right to change it."""
|
|
if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation):
|
|
raise ValueError("Invalid account ID or installation code")
|
|
if frame != "none" and not (isinstance(frame, str) and FRAME.fullmatch(frame)):
|
|
raise ValueError("Unknown frame")
|
|
if frame != "none" and CUSTOM.fullmatch(frame):
|
|
art = self.art(frame[2:])
|
|
mine = art is not None and art["uid"] == uid and art["status"] != "rejected"
|
|
from_catalog = art is not None and art["listed"] and art["status"] == "approved"
|
|
if art is None or art["kind"] != "frame" or not (mine or from_catalog):
|
|
raise ValueError("This frame is not available for this account")
|
|
elif frame != "none" and not self.frame_allowed(uid, frame):
|
|
raise ValueError("This frame is not available for this account")
|
|
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
|
|
with self.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_frame = db.execute("SELECT 1 FROM avatar_frames WHERE uid=?", (uid,)).fetchone()
|
|
proven = owner is not None and hmac.compare_digest(owner[0], digest)
|
|
if not proven and frame == "none" and not has_frame:
|
|
return {"ok": True, "published": True, "frame": "none"} # nothing to withdraw
|
|
if not proven:
|
|
reply = self._prove(uid, digest, unique_id)
|
|
if reply is not None:
|
|
return reply
|
|
with self.connect() as db:
|
|
if frame == "none":
|
|
db.execute("DELETE FROM avatar_frames WHERE uid=?", (uid,))
|
|
else:
|
|
db.execute("INSERT INTO avatar_frames(uid,frame,updated_at) VALUES(?,?,?) "
|
|
"ON CONFLICT(uid) DO UPDATE SET frame=excluded.frame,updated_at=excluded.updated_at",
|
|
(uid, frame, int(self.clock())))
|
|
return {"ok": True, "published": True, "frame": frame}
|
|
|
|
def lookup(self, uids):
|
|
if not isinstance(uids, list) or len(uids) > 100 or any(not valid_uid(uid) for uid in uids):
|
|
raise ValueError("Request at most 100 account IDs")
|
|
uids = list(dict.fromkeys(uids))
|
|
if not uids:
|
|
return {"members": {}}
|
|
placeholders = ",".join("?" for _ in uids)
|
|
with self.connect() as db:
|
|
rows = db.execute("SELECT uid,frame_color FROM presence WHERE uid IN (" + placeholders + ") AND last_seen >= ? AND uid NOT IN (SELECT uid FROM active_blocked)", uids + [int(self.clock()) - LIFETIME]).fetchall()
|
|
niche = {row[0] for row in db.execute(
|
|
"SELECT uid FROM niche WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM active_blocked)", uids
|
|
).fetchall()}
|
|
supporters = {row[0] for row in db.execute(
|
|
"SELECT uid FROM supporters WHERE uid IN (" + placeholders + ")", uids
|
|
).fetchall()}
|
|
shapes = {row[0]: row[1] for row in db.execute(
|
|
"SELECT uid,shape FROM shapes WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM active_blocked)", uids
|
|
).fetchall() if row[1] in SHAPES}
|
|
frames_of = {row[0]: row[1] for row in db.execute(
|
|
"SELECT uid,frame FROM avatar_frames WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM active_blocked)", uids
|
|
).fetchall() if FRAME.fullmatch(row[1])}
|
|
grants = {}
|
|
for row in db.execute("SELECT uid,frame FROM frame_grants WHERE uid IN (" + placeholders + ")", uids).fetchall():
|
|
grants.setdefault(row[0], []).append(row[1])
|
|
frames_of = {uid: frame for uid, frame in frames_of.items() if frame_permitted(frame, grants.get(uid, []))}
|
|
shown = self.approved_ids([frame[2:] for frame in frames_of.values() if CUSTOM.fullmatch(frame)])
|
|
frames_of = {uid: frame for uid, frame in frames_of.items() if not CUSTOM.fullmatch(frame) or frame[2:] in shown}
|
|
colors = {}
|
|
for uid, color in rows:
|
|
colors.setdefault(uid, color if color in ("none", "green", "red", "yellow") else "green")
|
|
return {"members": {uid: uid in colors for uid in uids}, "frames": colors,
|
|
"supporters": {uid: uid in supporters for uid in uids},
|
|
"niche": {uid: uid in niche for uid in uids}, "shapes": shapes, "avatar_frames": frames_of, "frame_grants": grants,
|
|
"bubbles": self.catalog.bubbles_of(uids), "ttl": 300}
|
|
|
|
# ---- pictures made by members: kept as art rows, shown to others only after the owner approved them
|
|
|
|
def art(self, art_id):
|
|
if not isinstance(art_id, str) or not re.fullmatch(r"[0-9a-f]{24}", art_id):
|
|
return None
|
|
with self.connect() as db:
|
|
row = db.execute("SELECT id,kind,uid,name,sha256,status,reason,review_message,description,listed FROM art WHERE id=?", (art_id,)).fetchone()
|
|
return None if row is None else dict(zip(("id", "kind", "uid", "name", "sha256", "status", "reason", "review_message", "description", "listed"), row))
|
|
|
|
def approved_ids(self, ids):
|
|
ids = [i for i in dict.fromkeys(ids) if re.fullmatch(r"[0-9a-f]{24}", i)]
|
|
if not ids:
|
|
return set()
|
|
with self.connect() as db:
|
|
return {row[0] for row in db.execute(
|
|
"SELECT id FROM art WHERE status='approved' AND id IN (" + ",".join("?" for _ in ids) + ")", ids)}
|
|
|
|
def art_bytes(self, art_id, approved_only=True):
|
|
art = self.art(art_id)
|
|
if art is None or (approved_only and art["status"] != "approved"):
|
|
return None
|
|
try:
|
|
return (self.art_dir / (art["sha256"] + ".png")).read_bytes()
|
|
except OSError:
|
|
return None
|
|
|
|
def art_report_save(self, art_id, pdf: bytes):
|
|
"""The detailed rejection report of one picture (PDF), kept beside the pictures."""
|
|
self.art_dir.mkdir(parents=True, exist_ok=True)
|
|
target = self.art_dir / (art_id + ".report.pdf")
|
|
part = self.art_dir / (art_id + ".report.part")
|
|
part.write_bytes(pdf)
|
|
os.replace(part, target)
|
|
|
|
def art_report(self, art_id):
|
|
try:
|
|
return (self.art_dir / (art_id + ".report.pdf")).read_bytes()
|
|
except OSError:
|
|
return None
|
|
|
|
def art_in_state(self, status, limit=5):
|
|
with self.connect() as db:
|
|
rows = db.execute("SELECT id FROM art WHERE status=? ORDER BY created_at LIMIT ?", (status, limit)).fetchall()
|
|
return [self.art(row[0]) for row in rows]
|
|
|
|
def art_decide(self, art_id, status, reason="", review_message=None):
|
|
if status not in ART_STATES:
|
|
raise ValueError("Unknown state")
|
|
with self.connect() as db:
|
|
db.execute("UPDATE art SET status=?, reason=?, decided_at=?, review_message=COALESCE(?, review_message) WHERE id=?",
|
|
(status, str(reason)[:120], int(self.clock()), review_message, art_id))
|
|
|
|
def art_counts(self):
|
|
with self.connect() as db:
|
|
return dict(db.execute("SELECT status, COUNT(*) FROM art GROUP BY status").fetchall())
|
|
|
|
def _receive(self, kind, uid, installation, unique_id, name, data, side, square, listed=False, description=""):
|
|
"""The shared part of taking a member's picture: the account is proven (the same code in the bio as for the outline and the
|
|
frame choice), the picture is re-made here and kept, and it waits for the AI and the owner. Returns a proof request or
|
|
{"art": row}."""
|
|
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()
|
|
now = int(self.clock())
|
|
with self.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()
|
|
waiting = db.execute("SELECT COUNT(*) FROM art WHERE uid=? AND status IN ('new','review')", (uid,)).fetchone()[0]
|
|
today = db.execute("SELECT COUNT(*) FROM art WHERE uid=? AND created_at>?", (uid, now - 86400)).fetchone()[0]
|
|
if not (owner is not None and hmac.compare_digest(owner[0], digest)):
|
|
reply = self._prove(uid, digest, unique_id)
|
|
if reply is not None:
|
|
return reply
|
|
try:
|
|
raw = base64.b64decode(data, validate=True) if isinstance(data, str) else b""
|
|
except (ValueError, TypeError):
|
|
raise ValueError("Not a picture")
|
|
png = community.normalize_png(raw, side, square=square)
|
|
sha = hashlib.sha256(png).hexdigest()
|
|
art_id = sha[:24]
|
|
known = self.art(art_id)
|
|
if known is not None:
|
|
if known["uid"] != uid or known["kind"] != kind:
|
|
raise ValueError("This picture is already taken")
|
|
if listed and not known["listed"]:
|
|
# the picture was moderated as a private one; its name and description are new, so it is judged again
|
|
with self.connect() as db:
|
|
db.execute("UPDATE art SET listed=1, listed_at=?, name=?, description=?, status='new', reason='' WHERE id=?",
|
|
(now, community.clean_name(name, "Без названия"), description, art_id))
|
|
return {"art": self.art(art_id)}
|
|
return {"art": known}
|
|
if waiting >= 3 or today >= 10:
|
|
raise ValueError("Too many pictures waiting, try again later")
|
|
self.art_dir.mkdir(parents=True, exist_ok=True)
|
|
target = self.art_dir / (sha + ".png")
|
|
part = self.art_dir / (sha + ".part")
|
|
part.write_bytes(png)
|
|
part.replace(target)
|
|
with self.connect() as db:
|
|
db.execute("INSERT INTO art(id,kind,uid,name,sha256,status,created_at,description,listed,listed_at) VALUES(?,?,?,?,?,?,?,?,?,?)",
|
|
(art_id, kind, uid, community.clean_name(name, "Без названия"), sha, "new", now, description, 1 if listed else 0, now if listed else 0))
|
|
return {"art": self.art(art_id)}
|
|
|
|
def frame_upload(self, uid, installation, unique_id, name, data):
|
|
"""A member sends a picture to be their avatar frame. Others see it only once approved."""
|
|
got = self._receive("frame", uid, installation, unique_id, name or "Моя рамка", data, community.FRAME_SIDE, True)
|
|
if "art" not in got:
|
|
return got
|
|
return {"ok": True, "published": True, "id": "u." + got["art"]["id"], "status": got["art"]["status"]}
|
|
|
|
@staticmethod
|
|
def pair_key(uid, peer):
|
|
if not valid_uid(uid) or not valid_uid(peer) or uid == peer:
|
|
raise ValueError("Invalid account ID")
|
|
return ":".join(sorted((uid, peer)))
|
|
|
|
def bubble_upload(self, uid, installation, unique_id, peer, name, data):
|
|
"""A member sends one picture for the chat with `peer`; both of them see it (once it is approved) instead of their own bubbles."""
|
|
key = self.pair_key(uid, peer)
|
|
got = self._receive("bubble", uid, installation, unique_id, name or "Картинка чата", data, community.BUBBLE_SIDE, False)
|
|
if "art" not in got:
|
|
return got
|
|
art = got["art"]
|
|
with self.connect() as db:
|
|
db.execute("INSERT INTO pair_art(pair,art_id,set_by,updated_at) VALUES(?,?,?,?) "
|
|
"ON CONFLICT(pair) DO UPDATE SET art_id=excluded.art_id,set_by=excluded.set_by,updated_at=excluded.updated_at",
|
|
(key, art["id"], uid, int(self.clock())))
|
|
return {"ok": True, "published": True, "id": art["id"], "status": art["status"]}
|
|
|
|
def pair_lookup(self, uid, installation, peer):
|
|
"""The approved picture of the chat between `uid` and `peer`, for one of the two only (the installation must have proven `uid`)."""
|
|
key = self.pair_key(uid, peer)
|
|
if 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.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):
|
|
return {"id": None}
|
|
row = db.execute("SELECT art_id FROM pair_art WHERE pair=?", (key,)).fetchone()
|
|
blocked = db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone()
|
|
if row is None or blocked or row[0] not in self.approved_ids([row[0]]):
|
|
return {"id": None}
|
|
return {"id": row[0]}
|
|
|
|
def pair_clear(self, uid, installation, peer):
|
|
"""Either side takes the shared picture of the chat away."""
|
|
key = self.pair_key(uid, peer)
|
|
digest = hashlib.sha256(str(installation).encode("ascii", "replace")).hexdigest()
|
|
with self.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")
|
|
db.execute("DELETE FROM pair_art WHERE pair=?", (key,))
|
|
return {"ok": True}
|
|
|
|
# ---- the "Серийчик" of a pair: one picture for the two, either of them may change it ----------------------------------
|
|
|
|
PET_COOLDOWN = 3600 # a pair changes its picture once an hour
|
|
PET_HISTORY = 5 # how many earlier pictures can be brought back
|
|
|
|
def _proven(self, uid, installation) -> bool:
|
|
if 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.connect() as db:
|
|
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
|
|
return owner is not None and hmac.compare_digest(owner[0], digest)
|
|
|
|
def _pet_cooldown(self, key):
|
|
with self.connect() as db:
|
|
last = db.execute("SELECT at FROM pair_pet WHERE pair=? ORDER BY id DESC LIMIT 1", (key,)).fetchone()
|
|
if last and int(self.clock()) - last[0] < self.PET_COOLDOWN:
|
|
raise ValueError("The picture of the pair can be changed once an hour")
|
|
|
|
def pet_upload(self, uid, installation, unique_id, peer, name, data):
|
|
"""Either of the two sends a new picture for their "Серийчик". It waits for the AI and the owner; until it is approved the
|
|
earlier one stays."""
|
|
key = self.pair_key(uid, peer)
|
|
if valid_uid(uid) and self._proven(uid, installation):
|
|
try:
|
|
raw = base64.b64decode(data, validate=True) if isinstance(data, str) else b""
|
|
same = hashlib.sha256(community.normalize_png(raw, community.PET_SIDE, square=False)).hexdigest()[:24]
|
|
except (ValueError, TypeError):
|
|
same = None # the real check of the picture comes in _receive and says what is wrong
|
|
with self.connect() as db:
|
|
last = db.execute("SELECT art_id FROM pair_pet WHERE pair=? ORDER BY id DESC LIMIT 1", (key,)).fetchone()
|
|
if same is not None and last and last[0] == same and self.art(same):
|
|
return {"ok": True, "published": True, "id": same, "status": self.art(same)["status"]} # the picture it already is
|
|
self._pet_cooldown(key) # checked before the picture is taken, so a refused change costs nobody a review
|
|
got = self._receive("pet", uid, installation, unique_id, name or "Серийчик", data, community.PET_SIDE, False)
|
|
if "art" not in got:
|
|
return got
|
|
art = got["art"]
|
|
now = int(self.clock())
|
|
with self.connect() as db:
|
|
last = db.execute("SELECT art_id FROM pair_pet WHERE pair=? ORDER BY id DESC LIMIT 1", (key,)).fetchone()
|
|
if not last or last[0] != art["id"]:
|
|
db.execute("INSERT INTO pair_pet(pair, art_id, set_by, at) VALUES(?,?,?,?)", (key, art["id"], uid, now))
|
|
return {"ok": True, "published": True, "id": art["id"], "status": art["status"]}
|
|
|
|
def pet_lookup(self, uid, installation, peer):
|
|
"""What the two see: the newest approved picture, whether a newer one waits, and the earlier approved ones (to bring back)."""
|
|
key = self.pair_key(uid, peer)
|
|
if not self._proven(uid, installation):
|
|
return {"id": None, "pending": False, "history": []}
|
|
with self.connect() as db:
|
|
rows = db.execute("SELECT art_id FROM pair_pet WHERE pair=? ORDER BY id DESC LIMIT ?", (key, self.PET_HISTORY + 8)).fetchall()
|
|
blocked = db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone()
|
|
ids = []
|
|
for row in rows:
|
|
if row[0] not in ids:
|
|
ids.append(row[0])
|
|
approved = self.approved_ids(ids) if ids else set()
|
|
if blocked or not ids:
|
|
return {"id": None, "pending": False, "history": []}
|
|
shown = [i for i in ids if i in approved]
|
|
current = shown[0] if shown else None
|
|
return {"id": current, "pending": ids[0] not in approved, "history": shown[1:1 + self.PET_HISTORY]}
|
|
|
|
def pet_revert(self, uid, installation, peer, art_id):
|
|
"""Brings back one of the earlier approved pictures of the pair (it counts as a change: once an hour)."""
|
|
key = self.pair_key(uid, peer)
|
|
if not self._proven(uid, installation):
|
|
raise ValueError("Prove the account first")
|
|
if not isinstance(art_id, str) or not re.fullmatch(r"[0-9a-f]{24}", art_id):
|
|
raise ValueError("Unknown picture")
|
|
with self.connect() as db:
|
|
if db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone():
|
|
raise ValueError("Account excluded")
|
|
known = db.execute("SELECT 1 FROM pair_pet WHERE pair=? AND art_id=?", (key, art_id)).fetchone()
|
|
if not known or art_id not in self.approved_ids([art_id]):
|
|
raise ValueError("Unknown picture")
|
|
self._pet_cooldown(key)
|
|
with self.connect() as db:
|
|
db.execute("INSERT INTO pair_pet(pair, art_id, set_by, at) VALUES(?,?,?,?)", (key, art_id, uid, int(self.clock())))
|
|
return {"ok": True, "id": art_id}
|
|
|
|
def pet_clear(self, uid, installation, peer):
|
|
"""Either side takes the picture away (the history goes with it)."""
|
|
key = self.pair_key(uid, peer)
|
|
if not self._proven(uid, installation):
|
|
raise ValueError("Prove the account first")
|
|
with self.connect() as db:
|
|
db.execute("DELETE FROM pair_pet WHERE pair=?", (key,))
|
|
return {"ok": True}
|
|
|
|
# ---- the animal of a pair: "kitten", "puppy", "lion cub" ... offered by link, accepted by the other one ---------------------
|
|
|
|
SPECIES_OFFER_LIFE = 7 * 86400 # an offer that nobody answered goes stale after a week
|
|
|
|
def _species_row(self, key):
|
|
with self.connect() as db:
|
|
row = db.execute("SELECT kind, offer, offer_by, at FROM pair_species WHERE pair=?", (key,)).fetchone()
|
|
return row or ("", "", "", 0)
|
|
|
|
def species_offer(self, uid, installation, peer, kind):
|
|
"""One of the two gives the pair an animal. It becomes theirs when the other accepts; their own animal does not change before."""
|
|
key = self.pair_key(uid, peer)
|
|
if not self._proven(uid, installation):
|
|
raise ValueError("Prove the account first")
|
|
if kind not in species_list():
|
|
raise ValueError("Unknown animal")
|
|
with self.connect() as db:
|
|
if db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone():
|
|
raise ValueError("Account excluded")
|
|
current, _, _, _ = self._species_row(key)
|
|
db.execute("INSERT INTO pair_species(pair, kind, offer, offer_by, at) VALUES(?,?,?,?,?) "
|
|
"ON CONFLICT(pair) DO UPDATE SET offer=excluded.offer, offer_by=excluded.offer_by, at=excluded.at",
|
|
(key, current, kind, uid, int(self.clock())))
|
|
return {"ok": True, "kind": kind}
|
|
|
|
def species_lookup(self, uid, installation, peer):
|
|
"""What the two see: the animal they have, and an offer from the other one that waits for an answer."""
|
|
key = self.pair_key(uid, peer)
|
|
if not self._proven(uid, installation):
|
|
return {"kind": "", "offer": ""}
|
|
kind, offer, offer_by, at = self._species_row(key)
|
|
with self.connect() as db:
|
|
if db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone():
|
|
return {"kind": "", "offer": ""}
|
|
waiting = offer if offer and offer_by == peer and int(self.clock()) - at < self.SPECIES_OFFER_LIFE else ""
|
|
return {"kind": kind, "offer": waiting}
|
|
|
|
def species_answer(self, uid, installation, peer, accept):
|
|
"""The other one says yes (the animal is now the pair's) or no (the offer goes away)."""
|
|
key = self.pair_key(uid, peer)
|
|
if not self._proven(uid, installation):
|
|
raise ValueError("Prove the account first")
|
|
if not isinstance(accept, bool):
|
|
raise ValueError("Say yes or no")
|
|
kind, offer, offer_by, at = self._species_row(key)
|
|
if not offer or offer_by != peer or int(self.clock()) - at >= self.SPECIES_OFFER_LIFE:
|
|
raise ValueError("There is no offer to answer")
|
|
with self.connect() as db:
|
|
if accept and db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone():
|
|
raise ValueError("Account excluded")
|
|
if accept:
|
|
db.execute("UPDATE pair_species SET kind=?, offer='', offer_by='', at=? WHERE pair=?", (offer, int(self.clock()), key))
|
|
else:
|
|
db.execute("UPDATE pair_species SET offer='', offer_by='', at=? WHERE pair=?", (int(self.clock()), key))
|
|
return {"ok": True, "kind": offer if accept else kind}
|
|
|
|
def frame_allowed(self, uid, frame):
|
|
"""May this account use this frame? Open packs: always; closed packs: only with a grant."""
|
|
if frame.split(".", 1)[0] not in RESTRICTED_PACKS:
|
|
return True
|
|
with self.connect() as db:
|
|
rows = db.execute("SELECT frame FROM frame_grants WHERE uid=?", (uid,)).fetchall()
|
|
return frame_permitted(frame, [row[0] for row in rows])
|
|
|
|
def set_frame_grant(self, uid, frame, enabled=True):
|
|
"""Admin-only when invoked from the server CLI; never exposed over HTTP. `frame` is "pack.name" or "pack.*"."""
|
|
if not valid_uid(uid):
|
|
raise ValueError("Invalid account ID")
|
|
if not isinstance(frame, str) or not GRANT.fullmatch(frame):
|
|
raise ValueError("Invalid frame")
|
|
with self.connect() as db:
|
|
if enabled:
|
|
db.execute("INSERT OR IGNORE INTO frame_grants(uid,frame,granted_at) VALUES(?,?,?)", (uid, frame, int(self.clock())))
|
|
else:
|
|
db.execute("DELETE FROM frame_grants WHERE uid=? AND frame=?", (uid, frame))
|
|
return {"uid": uid, "frame": frame, "granted": bool(enabled)}
|
|
|
|
def set_supporter(self, uid, enabled=True):
|
|
"""Admin-only when invoked from the server CLI; never exposed over HTTP."""
|
|
if not valid_uid(uid):
|
|
raise ValueError("Invalid account ID")
|
|
with self.connect() as db:
|
|
if enabled:
|
|
db.execute("INSERT OR IGNORE INTO supporters(uid,granted_at) VALUES(?,?)",
|
|
(uid, int(self.clock())))
|
|
else:
|
|
db.execute("DELETE FROM supporters WHERE uid=?", (uid,))
|
|
return {"uid": uid, "supporter": bool(enabled)}
|
|
|
|
|
|
class Limits:
|
|
def __init__(self):
|
|
self.events = defaultdict(deque)
|
|
self.lock = threading.Lock()
|
|
|
|
def allow(self, ip, operation):
|
|
key = ip, operation
|
|
window, count = ((60, 120) if operation in READS else (3600, 10) if operation == "claim"
|
|
else (3600, 90) if operation == "ai_chat"
|
|
else (3600, 1200) if operation == "code_chat"
|
|
else (3600, 30) if operation in WRITES else (3600, 12) if operation in UPLOADS
|
|
else (3600, 60) if operation == "install" else (3600, 40))
|
|
now = time.monotonic()
|
|
with self.lock:
|
|
if len(self.events) > 10000:
|
|
for old in list(self.events):
|
|
if not self.events[old] or self.events[old][-1] < now - 3600:
|
|
del self.events[old]
|
|
if len(self.events) > 10000 and key not in self.events:
|
|
return False
|
|
queue = self.events[key]
|
|
while queue and queue[0] < now - window:
|
|
queue.popleft()
|
|
if len(queue) >= count:
|
|
return False
|
|
queue.append(now)
|
|
return True
|
|
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
server_version = "LihonT-Members/1"
|
|
|
|
def log_message(self, fmt, *args):
|
|
# Do not log payloads, installation codes or account IDs.
|
|
pass
|
|
|
|
def send_json(self, status, payload):
|
|
raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
self.send_header("Cache-Control", "no-store")
|
|
self.send_header("Content-Length", str(len(raw)))
|
|
self.end_headers()
|
|
self.wfile.write(raw)
|
|
|
|
def send_events(self, stream):
|
|
"""A streamed answer of LihonC: one server-sent event per piece, then the connection closes."""
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/event-stream; charset=utf-8")
|
|
self.send_header("Cache-Control", "no-store")
|
|
self.send_header("X-Accel-Buffering", "no") # nginx must pass the pieces on at once
|
|
self.send_header("Connection", "close")
|
|
self.end_headers()
|
|
try:
|
|
self.connection.settimeout(60)
|
|
for event in stream:
|
|
self.wfile.write(b"data: " + json.dumps(event, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n\n")
|
|
self.wfile.flush()
|
|
except (BrokenPipeError, ConnectionResetError, OSError):
|
|
pass # the person stopped or went away; the gate still charges what was written
|
|
finally:
|
|
stream.close()
|
|
self.close_connection = True
|
|
|
|
def _send_range_bytes(self, data: bytes, content_type: str, cache_control: str = "public, max-age=86400, immutable"):
|
|
total = len(data)
|
|
rng = self.headers.get("Range")
|
|
if rng and rng.startswith("bytes="):
|
|
spec = rng[6:].split(",", 1)[0].strip()
|
|
if "-" in spec:
|
|
start_s, end_s = spec.split("-", 1)
|
|
try:
|
|
if start_s == "":
|
|
suffix = int(end_s)
|
|
start = max(0, total - suffix)
|
|
end = total - 1
|
|
else:
|
|
start = int(start_s)
|
|
end = int(end_s) if end_s else total - 1
|
|
if 0 <= start <= end < total:
|
|
chunk = data[start:end + 1]
|
|
self.send_response(206)
|
|
self.send_header("Content-Type", content_type)
|
|
self.send_header("Accept-Ranges", "bytes")
|
|
self.send_header("Content-Range", "bytes %d-%d/%d" % (start, end, total))
|
|
self.send_header("Cache-Control", cache_control)
|
|
self.send_header("Content-Length", str(len(chunk)))
|
|
self.end_headers()
|
|
self.wfile.write(chunk)
|
|
return
|
|
except ValueError:
|
|
pass
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", content_type)
|
|
self.send_header("Accept-Ranges", "bytes")
|
|
self.send_header("Cache-Control", cache_control)
|
|
self.send_header("Content-Length", str(total))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
def _send_range_file(self, file_path: Path, content_type: str, cache_control: str = "private, max-age=3600"):
|
|
total = file_path.stat().st_size
|
|
start, end, partial = 0, total - 1, False
|
|
rng = self.headers.get("Range")
|
|
if rng and rng.startswith("bytes="):
|
|
spec = rng[6:].split(",", 1)[0].strip()
|
|
if "-" in spec:
|
|
start_s, end_s = spec.split("-", 1)
|
|
try:
|
|
if start_s == "":
|
|
suffix = int(end_s)
|
|
start = max(0, total - suffix)
|
|
else:
|
|
start = int(start_s)
|
|
end = int(end_s) if end_s else total - 1
|
|
if 0 <= start <= end < total:
|
|
partial = True
|
|
except ValueError:
|
|
start, end, partial = 0, total - 1, False
|
|
length = end - start + 1
|
|
self.send_response(206 if partial else 200)
|
|
self.send_header("Content-Type", content_type)
|
|
self.send_header("Accept-Ranges", "bytes")
|
|
if partial:
|
|
self.send_header("Content-Range", "bytes %d-%d/%d" % (start, end, total))
|
|
self.send_header("Cache-Control", cache_control)
|
|
self.send_header("Content-Length", str(length))
|
|
self.end_headers()
|
|
with file_path.open("rb") as fh:
|
|
fh.seek(start)
|
|
remaining = length
|
|
while remaining > 0:
|
|
chunk = fh.read(min(65536, remaining))
|
|
if not chunk:
|
|
break
|
|
self.wfile.write(chunk)
|
|
remaining -= len(chunk)
|
|
|
|
def do_GET(self):
|
|
match = re.fullmatch(r"/members/v1/art/([0-9a-f]{24})\.png", self.path)
|
|
if match:
|
|
data = self.server.registry.art_bytes(match.group(1))
|
|
if data is None:
|
|
return self.send_json(404, {"error": "Not found"})
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "image/png")
|
|
self.send_header("Cache-Control", "public, max-age=86400, immutable")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
return
|
|
music_match = re.fullmatch(r"/members/v1/music/([0-9a-f]{24})\.mp3", self.path)
|
|
if music_match:
|
|
data = self.server.registry.music.bytes(music_match.group(1))
|
|
if data is None:
|
|
return self.send_json(404, {"error": "Not found"})
|
|
self._send_range_bytes(data, "audio/mpeg")
|
|
return
|
|
dub_match = re.fullmatch(r"/members/v1/dub/([0-9a-f]{24})\.mp4", self.path)
|
|
if dub_match:
|
|
fp = self.server.registry.dub.file_path(dub_match.group(1))
|
|
if fp is None:
|
|
return self.send_json(404, {"error": "Not found"})
|
|
self._send_range_file(fp, "video/mp4")
|
|
return
|
|
self.send_json(200 if self.path == "/members/v1/health" else 404,
|
|
{"ok": True} if self.path == "/members/v1/health" else {"error": "Not found"})
|
|
|
|
def do_POST(self):
|
|
operation = self.path.removeprefix("/members/v1/")
|
|
if self.path != "/members/v1/" + operation or operation not in OPERATIONS:
|
|
return self.send_json(404, {"error": "Not found"})
|
|
# This server binds to localhost; nginx overwrites this header.
|
|
ip = self.headers.get("X-Real-IP", self.client_address[0])
|
|
if not self.server.limits.allow(ip, operation if operation in READS + WRITES + UPLOADS + ("claim", "install", "pair_clear") else "presence"):
|
|
return self.send_json(429, {"error": "Try again later"})
|
|
try:
|
|
length = int(self.headers.get("Content-Length", "0"))
|
|
if not 0 < length <= (CHAT_BODY if operation == "ai_chat" else codegate.BODY if operation == "code_chat" else music.UPLOAD_BODY if operation == "music_upload" else UPLOAD_BODY if operation in UPLOADS else 8192):
|
|
return self.send_json(413, {"error": "Invalid payload size"})
|
|
self.connection.settimeout(10)
|
|
payload = json.loads(self.rfile.read(length))
|
|
if not isinstance(payload, dict):
|
|
raise ValueError("Expected an object")
|
|
if operation in CATALOG:
|
|
result = self.server.registry.catalog.call(operation, payload)
|
|
elif operation in ACCOUNTS:
|
|
result = self.server.registry.accounts.call(operation, payload)
|
|
elif operation in AI:
|
|
result = self.server.registry.ai.call(operation, payload)
|
|
elif operation in DUB:
|
|
result = self.server.registry.dub.call(operation, payload)
|
|
elif operation in CODE:
|
|
payload["_ip"] = ip # the gate keeps only a salted hash of it; a "_ip" sent by the client is overwritten here
|
|
result = self.server.registry.codegate.call(operation, payload)
|
|
if isinstance(result, codegate.Stream):
|
|
return self.send_events(result)
|
|
elif operation == "lookup":
|
|
result = self.server.registry.lookup(payload.get("uids"))
|
|
elif operation == "code":
|
|
result = {"code": self.server.registry.code(payload.get("uid")),
|
|
"deadline": CLAIM_DEADLINE, "open": time.time() <= CLAIM_DEADLINE}
|
|
elif operation == "claim":
|
|
result = self.server.registry.claim(payload.get("uid"), payload.get("unique_id"))
|
|
elif operation == "shape":
|
|
result = self.server.registry.shape(payload.get("uid"), payload.get("installation"),
|
|
payload.get("shape"), payload.get("unique_id"))
|
|
elif operation == "frame_upload":
|
|
result = self.server.registry.frame_upload(payload.get("uid"), payload.get("installation"),
|
|
payload.get("unique_id"), payload.get("name"), payload.get("png"))
|
|
elif operation == "bubble_upload":
|
|
result = self.server.registry.bubble_upload(payload.get("uid"), payload.get("installation"), payload.get("unique_id"),
|
|
payload.get("peer"), payload.get("name"), payload.get("png"))
|
|
elif operation == "pet_upload":
|
|
result = self.server.registry.pet_upload(payload.get("uid"), payload.get("installation"), payload.get("unique_id"),
|
|
payload.get("peer"), payload.get("name"), payload.get("png"))
|
|
elif operation == "pet_lookup":
|
|
result = self.server.registry.pet_lookup(payload.get("uid"), payload.get("installation"), payload.get("peer"))
|
|
elif operation == "pet_revert":
|
|
result = self.server.registry.pet_revert(payload.get("uid"), payload.get("installation"), payload.get("peer"), payload.get("id"))
|
|
elif operation == "pet_clear":
|
|
result = self.server.registry.pet_clear(payload.get("uid"), payload.get("installation"), payload.get("peer"))
|
|
elif operation == "species_offer":
|
|
result = self.server.registry.species_offer(payload.get("uid"), payload.get("installation"), payload.get("peer"), payload.get("kind"))
|
|
elif operation == "species_lookup":
|
|
result = self.server.registry.species_lookup(payload.get("uid"), payload.get("installation"), payload.get("peer"))
|
|
elif operation == "species_answer":
|
|
result = self.server.registry.species_answer(payload.get("uid"), payload.get("installation"), payload.get("peer"),
|
|
payload.get("accept") is True)
|
|
elif operation == "pair_lookup":
|
|
result = self.server.registry.pair_lookup(payload.get("uid"), payload.get("installation"), payload.get("peer"))
|
|
elif operation == "pair_clear":
|
|
result = self.server.registry.pair_clear(payload.get("uid"), payload.get("installation"), payload.get("peer"))
|
|
elif operation == "avatar_frame":
|
|
result = self.server.registry.avatar_frame(payload.get("uid"), payload.get("installation"),
|
|
payload.get("frame"), payload.get("unique_id"))
|
|
elif operation == "music_upload":
|
|
result = self.server.registry.music.upload(payload.get("uid"), payload.get("installation"),
|
|
payload.get("unique_id"), payload.get("title"),
|
|
payload.get("artist"), payload.get("mp3"))
|
|
elif operation == "music_lookup":
|
|
result = self.server.registry.music.lookup(payload.get("uid"), payload.get("unique_id"))
|
|
elif operation == "music_mine":
|
|
result = self.server.registry.music.mine(payload.get("uid"), payload.get("installation"))
|
|
elif operation == "music_select":
|
|
result = self.server.registry.music.select(payload.get("uid"), payload.get("installation"), payload.get("id"))
|
|
elif operation == "music_clear":
|
|
result = self.server.registry.music.clear(payload.get("uid"), payload.get("installation"))
|
|
else:
|
|
result = self.server.registry.presence(payload.get("uid"), payload.get("installation"), operation == "withdraw", payload.get("frame_color", "green"))
|
|
self.send_json(200, result)
|
|
except (ValueError, TypeError, UnicodeError) as exc:
|
|
self.send_json(400, {"error": str(exc)})
|
|
except Exception:
|
|
self.send_json(503, {"error": "Service temporarily unavailable"})
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--database", required=True)
|
|
parser.add_argument("--port", type=int, default=18746)
|
|
parser.add_argument("--grant-supporter", metavar="UID", help="Grant the LihonT supporter badge locally")
|
|
parser.add_argument("--revoke-supporter", metavar="UID", help="Revoke the LihonT supporter badge locally")
|
|
parser.add_argument("--grant-frame", nargs=2, metavar=("UID", "FRAME"), help="Give an account a closed frame (vip.name) or a whole pack (vip.*)")
|
|
parser.add_argument("--revoke-frame", nargs=2, metavar=("UID", "FRAME"), help="Take a closed frame away from an account")
|
|
parser.add_argument("--code-unban", metavar="DEVICE", help="Let a device back into LihonC (the code from its ban message)")
|
|
args = parser.parse_args()
|
|
Path(args.database).resolve().parent.mkdir(parents=True, exist_ok=True)
|
|
if args.code_unban:
|
|
print(json.dumps({"devices": Registry(args.database).codegate.unban(args.code_unban.strip().lower())}))
|
|
return
|
|
if args.grant_frame or args.revoke_frame:
|
|
registry = Registry(args.database)
|
|
uid, frame = args.grant_frame or args.revoke_frame
|
|
print(json.dumps(registry.set_frame_grant(uid, frame, enabled=bool(args.grant_frame))))
|
|
return
|
|
if args.grant_supporter or args.revoke_supporter:
|
|
registry = Registry(args.database)
|
|
print(json.dumps(registry.set_supporter(args.grant_supporter or args.revoke_supporter,
|
|
enabled=bool(args.grant_supporter))))
|
|
return
|
|
server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler)
|
|
server.registry = Registry(args.database)
|
|
server.limits = Limits()
|
|
# The owner's moderation bot runs only where its token is set (the service's environment file); without it uploads simply wait.
|
|
token, owner = os.environ.get("MOD_BOT_TOKEN"), os.environ.get("MOD_OWNER_ID")
|
|
if token and owner:
|
|
import modbot
|
|
auth_token = os.environ.get("AUTH_BOT_TOKEN")
|
|
hook = None
|
|
if auth_token:
|
|
import authbot
|
|
auth, _ = authbot.start(server.registry, auth_token, owner)
|
|
hook = auth.notify_new
|
|
modbot.start(server.registry, token, owner, on_approved=hook)
|
|
server.serve_forever()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|