Files
LihonT/services/members/accounts.py
cheb0chik 5df4cddf7d LihonT 3 Luna pre-alpha: the streak pet becomes an animal
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>
2026-11-10 15:14:48 +03:00

447 lines
25 KiB
Python

"""Telegram accounts of the store: sign-in through the bot, nicknames, follows, the inbox, hidden ids of people and timed bans.
Three levels (see the plan of 2026-11-07):
guest looks at the catalog and profiles, nothing else;
member has signed in through the Telegram bot and chosen a nickname: follows authors, reads the inbox, gets notifications;
author a member who also proved a TikTok account (the code in the bio, bound to the installation: see Registry._prove): only
authors may publish, and only the TikTok account decides whose avatar a frame is shown on.
An installation (the secret that the mod and the store hold) is what stands for a signed-in person, exactly as for the TikTok proof; only
its SHA-256 is kept. A "hidden id" (pid, like A7K-3Q2) is the short opaque name of a person that the owner uses: it is shown to nobody but
the owner (review messages, /who) and the owner bans by it: `/ban A7K-3Q2 7 reason` for seven days.
"""
from __future__ import annotations
import hashlib
import re
import secrets
import time
from community import INSTALL, valid_uid
BOT_NAME = "lihonTauthbot"
TOKEN = re.compile(r"[a-f0-9]{24}\Z")
HANDLE = re.compile(r"[a-z0-9_]{3,20}\Z")
RESERVED = {"admin", "administrator", "lihont", "lihon", "lihonts", "moderator", "mod", "support", "owner", "root", "system", "bot",
"telegram", "tiktok", "store", "staff", "official", "cheb0chik", "null", "none", "me", "all"}
PID_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
PID = re.compile(r"[A-HJKMNP-Z2-9]{3}-[A-HJKMNP-Z2-9]{3}\Z")
TOKEN_LIFETIME = 900 # a sign-in link works for 15 minutes
PENDING_LIMIT = 5 # open links per installation
FOLLOW_LIMIT = 200
HANDLE_COOLDOWN = 30 * 86400 # a nickname may be changed once in 30 days
MAX_BAN_DAYS = 3650
def digest_of(installation) -> str:
if not isinstance(installation, str) or not INSTALL.fullmatch(installation):
raise ValueError("Invalid installation code")
return hashlib.sha256(installation.encode("ascii")).hexdigest()
class Accounts:
def __init__(self, registry):
self.r = registry
self.operations = {
"tg_start": self.start, "tg_poll": self.poll, "tg_register": self.register, "tg_me": self.me,
"tg_link_tiktok": self.link_tiktok, "tg_logout": self.logout, "tg_delete": self.delete, "tg_notify": self.set_notify,
"follow": self.follow, "unfollow": self.unfollow, "following": self.following, "followers": self.followers,
"follow_info": self.follow_info, "inbox": self.inbox, "inbox_seen": self.inbox_seen,
}
with self.r.connect() as db:
db.execute("CREATE TABLE IF NOT EXISTS tg_accounts (tg_id INTEGER PRIMARY KEY, handle TEXT UNIQUE COLLATE NOCASE, "
"pid TEXT NOT NULL UNIQUE, created_at INTEGER NOT NULL, notify INTEGER NOT NULL DEFAULT 1, "
"inbox_seen INTEGER NOT NULL DEFAULT 0, handle_changed_at INTEGER NOT NULL DEFAULT 0, "
"banned_until INTEGER NOT NULL DEFAULT 0, ban_reason TEXT NOT NULL DEFAULT '')")
db.execute("CREATE TABLE IF NOT EXISTS tg_logins (token_hash TEXT PRIMARY KEY, installation TEXT NOT NULL, "
"created_at INTEGER NOT NULL, tg_id INTEGER)")
db.execute("CREATE TABLE IF NOT EXISTS tg_sessions (installation TEXT PRIMARY KEY, tg_id INTEGER NOT NULL, created_at INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS tg_tiktok (tg_id INTEGER PRIMARY KEY, uid TEXT NOT NULL UNIQUE, linked_at INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS follows (follower INTEGER NOT NULL, author_uid TEXT NOT NULL, created_at INTEGER NOT NULL, "
"PRIMARY KEY(follower, author_uid))")
db.execute("CREATE INDEX IF NOT EXISTS follows_author ON follows(author_uid)")
db.execute("CREATE TABLE IF NOT EXISTS pids (pid TEXT PRIMARY KEY, tg_id INTEGER UNIQUE, uid TEXT UNIQUE)")
db.execute("CREATE TABLE IF NOT EXISTS ban_log (id INTEGER PRIMARY KEY AUTOINCREMENT, pid TEXT NOT NULL, until INTEGER NOT NULL, "
"reason TEXT NOT NULL, at INTEGER NOT NULL)")
def call(self, operation, payload):
return self.operations[operation](payload)
def _now(self) -> int:
return int(self.r.clock())
# ---- hidden ids ------------------------------------------------------------------------------------------
def _new_pid(self, db) -> str:
while True:
raw = "".join(secrets.choice(PID_ALPHABET) for _ in range(6))
pid = raw[:3] + "-" + raw[3:]
if not db.execute("SELECT 1 FROM pids WHERE pid=?", (pid,)).fetchone():
return pid
def pid_for_tg(self, tg_id: int, db=None) -> str:
def work(db):
row = db.execute("SELECT pid FROM pids WHERE tg_id=?", (tg_id,)).fetchone()
if row:
return row[0]
pid = self._new_pid(db)
db.execute("INSERT INTO pids(pid, tg_id) VALUES(?,?)", (pid, tg_id))
return pid
if db is not None:
return work(db)
with self.r.connect() as own:
return work(own)
def pid_for_uid(self, uid: str) -> str:
"""The hidden id of a TikTok account; made when it is first needed (the owner sees it in the review messages)."""
with self.r.connect() as db:
row = db.execute("SELECT pid FROM pids WHERE uid=?", (uid,)).fetchone()
if row:
return row[0]
tg = db.execute("SELECT tg_id FROM tg_tiktok WHERE uid=?", (uid,)).fetchone()
if tg:
own = db.execute("SELECT pid FROM pids WHERE tg_id=?", (tg[0],)).fetchone()
if own:
db.execute("UPDATE pids SET uid=? WHERE pid=?", (uid, own[0]))
return own[0]
pid = self._new_pid(db)
db.execute("INSERT INTO pids(pid, uid) VALUES(?,?)", (pid, uid))
return pid
# ---- signing in through the bot ----------------------------------------------------------------------------
def start(self, p):
"""The app asks for a sign-in link; the person opens it in Telegram and the bot ties them to the token."""
digest = digest_of(p.get("installation"))
now = self._now()
token = secrets.token_hex(12)
with self.r.connect() as db:
db.execute("DELETE FROM tg_logins WHERE created_at < ?", (now - TOKEN_LIFETIME,))
if db.execute("SELECT COUNT(*) FROM tg_logins WHERE installation=?", (digest,)).fetchone()[0] >= PENDING_LIMIT:
raise ValueError("Too many open sign-in links, wait a few minutes")
db.execute("INSERT INTO tg_logins(token_hash, installation, created_at) VALUES(?,?,?)",
(hashlib.sha256(token.encode("ascii")).hexdigest(), digest, now))
return {"ok": True, "token": token, "link": "https://t.me/%s?start=%s" % (BOT_NAME, token), "expires_in": TOKEN_LIFETIME}
def bot_link(self, token, tg_id: int):
"""Called by the bot on /start <token>. Returns {"ok", "banned_until"?, "registered"}."""
if not isinstance(token, str) or not TOKEN.fullmatch(token) or not isinstance(tg_id, int):
return {"ok": False, "reason": "bad_token"}
now = self._now()
key = hashlib.sha256(token.encode("ascii")).hexdigest()
with self.r.connect() as db:
row = db.execute("SELECT created_at, tg_id FROM tg_logins WHERE token_hash=?", (key,)).fetchone()
if row is None or row[0] < now - TOKEN_LIFETIME:
return {"ok": False, "reason": "expired"}
if row[1] is not None and row[1] != tg_id:
return {"ok": False, "reason": "expired"} # the first person to open the link has it: a copy of the link takes nothing
account = db.execute("SELECT banned_until, ban_reason, handle FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()
if account and account[0] and account[0] > now:
return {"ok": False, "reason": "banned", "banned_until": account[0], "ban_reason": account[1]}
if account is None:
self.pid_for_tg(tg_id, db)
db.execute("INSERT INTO tg_accounts(tg_id, pid, created_at) VALUES(?,?,?)", (tg_id, self.pid_for_tg(tg_id, db), now))
db.execute("UPDATE tg_logins SET tg_id=? WHERE token_hash=?", (tg_id, key))
return {"ok": True, "registered": bool(account and account[2])}
def poll(self, p):
digest = digest_of(p.get("installation"))
token = p.get("token")
if not isinstance(token, str) or not TOKEN.fullmatch(token):
raise ValueError("Bad token")
now = self._now()
key = hashlib.sha256(token.encode("ascii")).hexdigest()
with self.r.connect() as db:
row = db.execute("SELECT installation, created_at, tg_id FROM tg_logins WHERE token_hash=?", (key,)).fetchone()
if row is None or row[0] != digest:
session = db.execute("SELECT tg_id FROM tg_sessions WHERE installation=?", (digest,)).fetchone()
if session:
return self._summary(db, session[0], "linked")
return {"status": "expired"}
if row[1] < now - TOKEN_LIFETIME:
db.execute("DELETE FROM tg_logins WHERE token_hash=?", (key,))
return {"status": "expired"}
if row[2] is None:
return {"status": "waiting"}
ban = db.execute("SELECT banned_until, ban_reason FROM tg_accounts WHERE tg_id=?", (row[2],)).fetchone()
if ban and ban[0] and ban[0] > now:
raise ValueError("Account banned until %d: %s" % (ban[0], ban[1] or "rules"))
db.execute("INSERT INTO tg_sessions(installation, tg_id, created_at) VALUES(?,?,?) "
"ON CONFLICT(installation) DO UPDATE SET tg_id=excluded.tg_id, created_at=excluded.created_at", (digest, row[2], now))
db.execute("DELETE FROM tg_logins WHERE token_hash=?", (key,))
return self._summary(db, row[2], "linked")
def _summary(self, db, tg_id, status):
row = db.execute("SELECT handle FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()
return {"status": status, "registered": bool(row and row[0]), "handle": (row[0] if row else None)}
def _member(self, p, db=None):
"""(tg_id, installation digest) of a signed-in, not banned member; the nickname is not required here."""
digest = digest_of(p.get("installation"))
with self.r.connect() as own:
row = own.execute("SELECT s.tg_id, a.banned_until, a.ban_reason FROM tg_sessions s JOIN tg_accounts a ON a.tg_id = s.tg_id "
"WHERE s.installation=?", (digest,)).fetchone()
if row is None:
raise ValueError("Sign in with Telegram first")
if row[1] and row[1] > self._now():
raise ValueError("Account banned until %d: %s" % (row[1], row[2] or "rules"))
return row[0], digest
def _registered(self, p):
tg_id, digest = self._member(p)
with self.r.connect() as db:
row = db.execute("SELECT handle FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()
if not row or not row[0]:
raise ValueError("Choose a nickname first")
return tg_id, digest
def register(self, p):
"""Chooses (or, after the cooldown, changes) the public nickname."""
tg_id, _ = self._member(p)
handle = str(p.get("handle") or "").strip().lower().lstrip("@")
if not HANDLE.fullmatch(handle):
raise ValueError("A nickname is 3 to 20 letters a-z, digits or _")
if handle in RESERVED or handle.startswith("lihont"):
raise ValueError("This nickname is reserved")
if any(word in handle for word in ("admin", "moder")):
raise ValueError("This nickname is reserved")
now = self._now()
with self.r.connect() as db:
row = db.execute("SELECT handle, handle_changed_at FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()
if row[0] == handle:
return {"ok": True, "handle": handle}
if row[0] and row[1] > now - HANDLE_COOLDOWN:
raise ValueError("A nickname can be changed once in 30 days")
if db.execute("SELECT 1 FROM tg_accounts WHERE handle=? AND tg_id<>?", (handle, tg_id)).fetchone():
raise ValueError("This nickname is taken")
db.execute("UPDATE tg_accounts SET handle=?, handle_changed_at=? WHERE tg_id=?", (handle, now, tg_id))
return {"ok": True, "handle": handle}
def logout(self, p):
digest = digest_of(p.get("installation"))
with self.r.connect() as db:
db.execute("DELETE FROM tg_sessions WHERE installation=?", (digest,))
return {"ok": True}
def delete(self, p):
tg_id, _ = self._member(p)
return self.delete_tg(tg_id)
def delete_tg(self, tg_id: int):
"""Takes the Telegram account away with everything that was only about it (follows, sessions, the link to TikTok)."""
with self.r.connect() as db:
db.execute("DELETE FROM tg_sessions WHERE tg_id=?", (tg_id,))
db.execute("DELETE FROM follows WHERE follower=?", (tg_id,))
db.execute("DELETE FROM tg_tiktok WHERE tg_id=?", (tg_id,))
db.execute("DELETE FROM tg_logins WHERE tg_id=?", (tg_id,))
pid = db.execute("SELECT pid FROM pids WHERE tg_id=?", (tg_id,)).fetchone()
if pid:
db.execute("UPDATE pids SET tg_id=NULL WHERE pid=?", (pid[0],)) # a ban of that person keeps its id
db.execute("DELETE FROM tg_accounts WHERE tg_id=? AND banned_until<=?", (tg_id, self._now()))
return {"ok": True}
def set_notify(self, p):
tg_id, _ = self._member(p)
with self.r.connect() as db:
db.execute("UPDATE tg_accounts SET notify=? WHERE tg_id=?", (1 if p.get("on") else 0, tg_id))
return {"ok": True, "notify": bool(p.get("on"))}
# ---- the author level --------------------------------------------------------------------------------------
def link_tiktok(self, p):
"""Links the member to a TikTok account that this very installation proved with the code in the bio (the author level)."""
tg_id, digest = self._registered(p)
uid = p.get("uid")
if not valid_uid(uid):
raise ValueError("Invalid account ID")
with self.r.connect() as db:
owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone()
if owner is None or owner[0] != digest:
raise ValueError("Prove the TikTok account first")
db.execute("DELETE FROM tg_tiktok WHERE uid=? OR tg_id=?", (uid, tg_id)) # a new proof takes the account over
db.execute("INSERT INTO tg_tiktok(tg_id, uid, linked_at) VALUES(?,?,?)", (tg_id, uid, self._now()))
self.pid_for_uid(uid) # joins the two hidden ids into one
return {"ok": True, "uid": uid}
def tiktok_uid(self, tg_id: int):
with self.r.connect() as db:
row = db.execute("SELECT uid FROM tg_tiktok WHERE tg_id=?", (tg_id,)).fetchone()
return row[0] if row else None
# ---- follows -----------------------------------------------------------------------------------------------
def _author_exists(self, db, uid) -> bool:
return bool(db.execute("SELECT 1 FROM art WHERE uid=? AND status='approved' AND listed=1", (uid,)).fetchone())
def follow(self, p):
tg_id, _ = self._registered(p)
uid = p.get("uid")
if not valid_uid(uid):
raise ValueError("Invalid account ID")
if uid == self.tiktok_uid(tg_id):
raise ValueError("You cannot follow yourself")
with self.r.connect() as db:
if db.execute("SELECT 1 FROM active_blocked WHERE uid=?", (uid,)).fetchone() or not self._author_exists(db, uid):
raise ValueError("No such author")
if not db.execute("SELECT 1 FROM follows WHERE follower=? AND author_uid=?", (tg_id, uid)).fetchone():
if db.execute("SELECT COUNT(*) FROM follows WHERE follower=?", (tg_id,)).fetchone()[0] >= FOLLOW_LIMIT:
raise ValueError("You follow too many authors")
db.execute("INSERT INTO follows(follower, author_uid, created_at) VALUES(?,?,?)", (tg_id, uid, self._now()))
count = db.execute("SELECT COUNT(*) FROM follows WHERE author_uid=?", (uid,)).fetchone()[0]
return {"ok": True, "following": True, "followers": count}
def unfollow(self, p):
tg_id, _ = self._registered(p)
uid = p.get("uid")
if not valid_uid(uid):
raise ValueError("Invalid account ID")
with self.r.connect() as db:
db.execute("DELETE FROM follows WHERE follower=? AND author_uid=?", (tg_id, uid))
count = db.execute("SELECT COUNT(*) FROM follows WHERE author_uid=?", (uid,)).fetchone()[0]
return {"ok": True, "following": False, "followers": count}
def following(self, p):
"""Whom this member follows (only they see it)."""
tg_id, _ = self._registered(p)
with self.r.connect() as db:
rows = db.execute("SELECT f.author_uid, (SELECT unique_id FROM shape_owner o WHERE o.uid = f.author_uid), "
"(SELECT COUNT(*) FROM art a WHERE a.uid = f.author_uid AND a.status='approved' AND a.listed=1) "
"FROM follows f WHERE f.follower=? ORDER BY f.created_at DESC LIMIT ?", (tg_id, FOLLOW_LIMIT)).fetchall()
return {"items": [{"uid": r[0], "name": r[1], "works": r[2]} for r in rows]}
def followers(self, p):
"""Who follows this member's TikTok account: the owner of the account alone sees the list, the others see a number."""
tg_id, _ = self._registered(p)
uid = self.tiktok_uid(tg_id)
if uid is None:
return {"items": [], "count": 0}
with self.r.connect() as db:
rows = db.execute("SELECT a.handle FROM follows f JOIN tg_accounts a ON a.tg_id = f.follower "
"WHERE f.author_uid=? AND a.handle IS NOT NULL ORDER BY f.created_at DESC LIMIT 500", (uid,)).fetchall()
count = db.execute("SELECT COUNT(*) FROM follows WHERE author_uid=?", (uid,)).fetchone()[0]
return {"items": [{"handle": r[0]} for r in rows], "count": count}
def follow_info(self, p):
"""Public: how many follow an author (a number, never names) and, for a signed-in caller, whether they do."""
uid = p.get("uid")
if not valid_uid(uid):
raise ValueError("Invalid account ID")
with self.r.connect() as db:
count = db.execute("SELECT COUNT(*) FROM follows WHERE author_uid=?", (uid,)).fetchone()[0]
reply = {"followers": count}
if p.get("installation"):
try:
tg_id, _ = self._registered(p)
except ValueError:
return reply
with self.r.connect() as db:
reply["following"] = bool(db.execute("SELECT 1 FROM follows WHERE follower=? AND author_uid=?", (tg_id, uid)).fetchone())
return reply
# ---- the inbox -----------------------------------------------------------------------------------------------
def inbox(self, p):
"""New approved and listed works of the authors this member follows, newest first; `unread` counts those after the last look."""
tg_id, _ = self._registered(p)
items, more = self.r.catalog._page(" AND a.uid IN (SELECT author_uid FROM follows WHERE follower=?)", [tg_id], p.get("cursor"), p.get("limit"))
with self.r.connect() as db:
seen = db.execute("SELECT inbox_seen FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()[0]
unread = db.execute("SELECT COUNT(*) FROM art a WHERE a.status='approved' AND a.listed=1 AND a.listed_at > ? "
"AND a.uid IN (SELECT author_uid FROM follows WHERE follower=?) "
"AND a.uid NOT IN (SELECT uid FROM active_blocked)", (seen, tg_id)).fetchone()[0]
return {"items": items, "next": more, "unread": unread}
def inbox_seen(self, p):
tg_id, _ = self._registered(p)
with self.r.connect() as db:
db.execute("UPDATE tg_accounts SET inbox_seen=? WHERE tg_id=?", (self._now(), tg_id))
return {"ok": True}
def me(self, p):
tg_id, _ = self._member(p)
with self.r.connect() as db:
handle, notify, seen = db.execute("SELECT handle, notify, inbox_seen FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()
following = db.execute("SELECT COUNT(*) FROM follows WHERE follower=?", (tg_id,)).fetchone()[0]
uid = self.tiktok_uid(tg_id)
followers = 0
if uid:
with self.r.connect() as db:
followers = db.execute("SELECT COUNT(*) FROM follows WHERE author_uid=?", (uid,)).fetchone()[0]
return {"handle": handle, "registered": bool(handle), "level": "author" if uid else "member", "tiktok": uid,
"notify": bool(notify), "following": following, "followers": followers}
# ---- notifications -------------------------------------------------------------------------------------------
def followers_to_notify(self, uid: str, limit: int = 300) -> list:
"""Telegram ids of the followers of an author who want notifications and are not banned."""
with self.r.connect() as db:
rows = db.execute("SELECT a.tg_id FROM follows f JOIN tg_accounts a ON a.tg_id = f.follower "
"WHERE f.author_uid=? AND a.notify=1 AND a.handle IS NOT NULL AND a.banned_until<=? LIMIT ?",
(uid, self._now(), limit)).fetchall()
return [r[0] for r in rows]
def handle_of_uid(self, uid: str):
with self.r.connect() as db:
row = db.execute("SELECT a.handle FROM tg_tiktok t JOIN tg_accounts a ON a.tg_id = t.tg_id WHERE t.uid=?", (uid,)).fetchone()
return row[0] if row else None
def mute(self, tg_id: int):
with self.r.connect() as db:
db.execute("UPDATE tg_accounts SET notify=0 WHERE tg_id=?", (tg_id,))
# ---- bans, by the hidden id -------------------------------------------------------------------------------------
def _person(self, db, pid):
if not isinstance(pid, str) or not PID.fullmatch(pid.upper()):
raise ValueError("Bad id")
row = db.execute("SELECT pid, tg_id, uid FROM pids WHERE pid=?", (pid.upper(),)).fetchone()
if row is None:
raise ValueError("Unknown id")
return row
def ban(self, pid: str, days: int, reason: str = ""):
"""Bans a person for `days` days (0 = for ever): their Telegram account and their TikTok account together."""
if not isinstance(days, int) or not 0 <= days <= MAX_BAN_DAYS:
raise ValueError("Days must be 0 to %d" % MAX_BAN_DAYS)
now = self._now()
until = 0 if days == 0 else now + days * 86400
reason = str(reason or "")[:120]
with self.r.connect() as db:
pid, tg_id, uid = self._person(db, pid)
if tg_id is not None:
db.execute("UPDATE tg_accounts SET banned_until=?, ban_reason=? WHERE tg_id=?", (until if until else 4102444800, reason, tg_id))
db.execute("DELETE FROM tg_sessions WHERE tg_id=?", (tg_id,))
if uid is not None:
db.execute("INSERT INTO blocked(uid, until) VALUES(?,?) ON CONFLICT(uid) DO UPDATE SET until=excluded.until", (uid, until))
db.execute("INSERT INTO ban_log(pid, until, reason, at) VALUES(?,?,?,?)", (pid, until, reason, now))
return {"ok": True, "pid": pid, "until": until or None, "tg": tg_id is not None, "tiktok": uid is not None}
def unban(self, pid: str):
with self.r.connect() as db:
pid, tg_id, uid = self._person(db, pid)
if tg_id is not None:
db.execute("UPDATE tg_accounts SET banned_until=0, ban_reason='' WHERE tg_id=?", (tg_id,))
if uid is not None:
db.execute("DELETE FROM blocked WHERE uid=?", (uid,))
return {"ok": True, "pid": pid}
def who(self, pid: str):
"""What the owner may see about a person: the nickname, the TikTok account, the counts, the ban."""
now = self._now()
with self.r.connect() as db:
pid, tg_id, uid = self._person(db, pid)
handle = banned = None
if tg_id is not None:
row = db.execute("SELECT handle, banned_until FROM tg_accounts WHERE tg_id=?", (tg_id,)).fetchone()
handle, banned = (row[0], row[1]) if row else (None, 0)
if uid is not None:
unique = db.execute("SELECT unique_id FROM shape_owner WHERE uid=?", (uid,)).fetchone()
blocked = db.execute("SELECT until FROM blocked WHERE uid=?", (uid,)).fetchone()
works = db.execute("SELECT status, COUNT(*) FROM art WHERE uid=? GROUP BY status", (uid,)).fetchall()
else:
unique, blocked, works = None, None, []
followers = db.execute("SELECT COUNT(*) FROM follows WHERE author_uid=?", (uid,)).fetchone()[0] if uid else 0
return {"pid": pid, "handle": handle, "tiktok_uid": uid, "tiktok": unique[0] if unique else None,
"works": dict(works), "followers": followers,
"banned": bool((banned and banned > now) or (blocked and (blocked[0] == 0 or blocked[0] > now)))}