From 9de69113b5010e80d6522bd68f1b4451676a21e9 Mon Sep 17 00:00:00 2001 From: cheb0chik Date: Thu, 5 Nov 2026 15:56:00 +0300 Subject: [PATCH] LihonT 2 Serena LihonT Store: a separate app with a catalog of avatar frames and chat bubbles made by members (browse, add with "+", author profiles, publishing), signed in through the TikTok that carries the mod (an exported no-window activity that answers only the store, checked by package name and signing key). The mod gets frames made from any picture (a photo is cut into a ring), the library of the store in the frame picker and for bubbles, other members' published bubbles and one picture per chat for both people. The members service gets the catalog, the account library, uploads that are re-made with Pillow, an AI first pass (Groq) and the owner's Telegram bot with accept and reject buttons. The build tools pass long file lists through an argument file. Nothing a member sends is shown to others before it is approved. Co-Authored-By: Claude Sonnet 5.5 --- lihont/toolchain.py | 27 +- lihont/upgrade.py | 8 + scripts/deploy_members.py | 110 +++--- services/members/catalog.py | 251 +++++++++++++ services/members/community.py | 61 ++++ services/members/server.py | 241 ++++++++++++- src/lihont/two/avatar/AvatarShapes.java | 2 +- src/lihont/two/avatar/FramePublisher.java | 43 +++ src/lihont/two/avatar/Installation.java | 4 +- src/lihont/two/avatar/PairPictures.java | 300 ++++++++++++++++ src/lihont/two/avatar/ShapeCatalog.java | 24 +- src/lihont/two/badge/Badges.java | 5 + src/lihont/two/bar/AvatarBadge.java | 2 +- src/lihont/two/chat/BubbleStore.java | 13 + src/lihont/two/chat/Bubbles.java | 20 +- src/lihont/two/frame/CustomFrames.java | 185 ++++++++++ src/lihont/two/frame/FrameCut.java | 53 +++ src/lihont/two/frame/FrameDraw.java | 7 + src/lihont/two/frame/FrameIndex.java | 11 +- src/lihont/two/frame/FramePreviewView.java | 2 +- src/lihont/two/frame/FrameStore.java | 40 ++- .../two/settings/LihonTSettingsActivity.java | 330 +++++++++++++++++- src/lihont/two/store/LoginActivity.java | 46 +++ src/lihont/two/store/StoreClient.java | 150 ++++++++ tests/java/lihont/two/frame/FrameTest.java | 26 ++ tests/test_catalog.py | 245 +++++++++++++ tests/test_community_frames.py | 231 ++++++++++++ tests/test_frames.py | 7 + tests/test_manifest_activity.py | 9 + 29 files changed, 2356 insertions(+), 97 deletions(-) create mode 100644 services/members/catalog.py create mode 100644 services/members/community.py create mode 100644 src/lihont/two/avatar/PairPictures.java create mode 100644 src/lihont/two/frame/CustomFrames.java create mode 100644 src/lihont/two/frame/FrameCut.java create mode 100644 src/lihont/two/store/LoginActivity.java create mode 100644 src/lihont/two/store/StoreClient.java create mode 100644 tests/test_catalog.py create mode 100644 tests/test_community_frames.py diff --git a/lihont/toolchain.py b/lihont/toolchain.py index ef021a9..249a89c 100644 --- a/lihont/toolchain.py +++ b/lihont/toolchain.py @@ -154,8 +154,7 @@ class Toolchain: stub_sources = _java_under(stubs_dir) if stub_sources: _run(["javac", "-nowarn", "-Xlint:-options", "-encoding", "UTF-8", - "-cp", self.android_jar, "--release", "17", "-d", stubs] - + stub_sources) + "-cp", self.android_jar, "--release", "17", "-d", stubs], bulk=stub_sources) classpath = self.android_jar + os.pathsep + stubs sources = _java_under(sources_dir) @@ -164,14 +163,14 @@ class Toolchain: _run( ["javac", "-nowarn", "-Xlint:-options", "-encoding", "UTF-8", - "-cp", classpath, "--release", "17", "-d", classes] + sources + "-cp", classpath, "--release", "17", "-d", classes], bulk=sources ) class_files = _classes_under(classes) command = ["java", "-cp", self.r8, "com.android.tools.r8.D8", "--release", "--min-api", str(min_api), "--lib", self.android_jar] if stubs_dir and _classes_under(stubs): command += ["--classpath", stubs] - _run(command + ["--output", dex] + class_files) + _run(command + ["--output", dex], bulk=class_files) return os.path.join(dex, "classes.dex") def _zipalign_path(self) -> Optional[str]: @@ -226,11 +225,27 @@ def _classes_under(root: str) -> list: return sorted(out) -def _run(command: list) -> None: +def _run(command: list, bulk: Optional[list] = None) -> None: + """Runs a tool. `bulk` is the long tail of file names (every source or class of the mod): when the whole line would be too long + for the system (Windows stops at about 32 000 characters) it goes through an argument file, which javac and D8 both read.""" environment = dict(os.environ) # the wrapper's own JVM options print a banner into every tool's output environment.pop("JAVA_TOOL_OPTIONS", None) - result = subprocess.run(command, capture_output=True, text=True, env=environment) + holder = None + if bulk: + if sum(len(part) + 1 for part in command + bulk) < 24000: + command = command + bulk + else: + import tempfile + holder = tempfile.NamedTemporaryFile("w", suffix=".args", delete=False, encoding="utf-8") + holder.write(chr(10).join(part.replace(chr(92), "/") for part in bulk)) + holder.close() + command = command + ["@" + holder.name.replace(chr(92), "/")] + try: + result = subprocess.run(command, capture_output=True, text=True, env=environment) + finally: + if holder is not None: + os.unlink(holder.name) if result.returncode != 0: sys.stderr.write(result.stdout + result.stderr) raise RuntimeError("%s failed" % os.path.basename(command[0])) diff --git a/lihont/upgrade.py b/lihont/upgrade.py index 8088f1d..abf52b9 100644 --- a/lihont/upgrade.py +++ b/lihont/upgrade.py @@ -25,6 +25,8 @@ SETTINGS_ACTIVITY = "lihont.two.settings.LihonTSettingsActivity" # Existing app theme keeps system bars/insets compatible with TikTok; the # activity draws its own Nothing-inspired surface. SETTINGS_THEME = 0x7F120364 +STORE_LOGIN_ACTIVITY = "lihont.two.store.LoginActivity" +NO_DISPLAY_THEME = 0x01030055 # android:style/Theme.NoDisplay: the login screen has no window, it only answers # dex -> list of class descriptors patched for the region feature REGION_TARGETS = { @@ -592,6 +594,12 @@ def build(source: str, output: str, workspace: str = "work/build") -> dict: report["manifest"] = {"settings_activity": SETTINGS_ACTIVITY, "exported": False} else: report["manifest"] = {"settings_activity": SETTINGS_ACTIVITY, "exported": False, "already_present": True} + # The door of LihonT Store: it asks which account is signed in. It is exported, so that another app can start it, and + # answers only a caller named lihonstore.app that is signed with the same key as this app (checked in the activity). + if not manifest_module.has_activity(xml, STORE_LOGIN_ACTIVITY): + manifest_module.add_activity(xml, STORE_LOGIN_ACTIVITY, "LihonT Store", NO_DISPLAY_THEME, exported=True) + apk.replace("AndroidManifest.xml", xml.build()) + report["manifest"]["store_login_activity"] = STORE_LOGIN_ACTIVITY # The launcher icons the settings screen offers: one disabled alias per catalog icon. from . import app_icons report["app_icons"] = step("app_icons", app_icons.apply, apk, xml, app_icons.load_catalog(Path("src/icons"))) diff --git a/scripts/deploy_members.py b/scripts/deploy_members.py index 567dfdc..238bb2b 100644 --- a/scripts/deploy_members.py +++ b/scripts/deploy_members.py @@ -1,13 +1,17 @@ -"""Swap the LihonT members service (badges and avatar shapes) on the Helsinki server and roll it back. +"""Swap the LihonT members service (badges, avatar shapes, frames, the community catalog and its moderation bot) on the Helsinki +server and roll it back. - py scripts/deploy_members.py --dry-run compare the live server.py with the local one, change nothing + py scripts/deploy_members.py --dry-run compare the live files with the local ones, change nothing py scripts/deploy_members.py back up, upload, restart lihont-members, roll back on failure py scripts/deploy_members.py --rollback restore the newest backup (or --stamp ) -Only /opt/lihont-members/server.py is replaced; its database is never touched (new tables are created by the -service itself when it starts, so an older server.py keeps working on the same file). The live file is copied to -server.py.bak- first, the new one is compiled on the server before it goes live, and the service is -asked for its health after the restart; a failed check puts the backup back. +The python files of services/members are replaced in /opt/lihont-members; the database is never touched (new tables and columns +are created by the service itself when it starts, so an older server.py keeps working on the same file). Every live file that is +replaced is copied to .bak- first, the new ones are compiled on the server before anything goes live, and the +service is asked for its health after the restart; a failed check puts the backups back. + +Not done here, by design: the service's environment file (/etc/lihont-members.env: MOD_BOT_TOKEN, MOD_OWNER_ID, GROQ_KEY) and the +nginx rules for uploads are server configuration, set up once by hand. """ from __future__ import annotations @@ -22,10 +26,11 @@ from pathlib import Path HOST = "hels" FOLDER = "/opt/lihont-members" -LIVE = FOLDER + "/server.py" SERVICE = "lihont-members" HEALTH = "http://127.0.0.1:18746/members/v1/health" -SOURCE = Path(__file__).resolve().parents[1] / "services" / "members" / "server.py" +SOURCE = Path(__file__).resolve().parents[1] / "services" / "members" +# every python file of the service that exists here (the moderation bot is not part of the public source, so it is simply absent there) +FILES = tuple(name for name in ("server.py", "community.py", "moderation.py", "modbot.py", "catalog.py") if (SOURCE / name).is_file()) SSH = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", HOST] @@ -39,9 +44,16 @@ def text(result: subprocess.CompletedProcess) -> str: return "\n".join(lines) -def digest_of_live() -> str: - result = remote("sha256sum %s" % shlex.quote(LIVE)) - return result.stdout.decode().split()[0] if result.returncode == 0 and result.stdout else "?" +def live_digests() -> dict[str, str]: + """sha256 of every file on the server, "?" for one that is not there.""" + names = " ".join(shlex.quote(FOLDER + "/" + name) for name in FILES) + result = remote("sha256sum %s 2>/dev/null" % names) + found = {} + for line in result.stdout.decode().splitlines(): + parts = line.split() + if len(parts) == 2: + found[parts[1].rsplit("/", 1)[-1]] = parts[0] + return {name: found.get(name, "?") for name in FILES} def healthy() -> bool: @@ -49,53 +61,69 @@ def healthy() -> bool: def deploy(dry_run: bool) -> int: - data = SOURCE.read_bytes() - local = hashlib.sha256(data).hexdigest() - live = digest_of_live() - print("local %s\nlive %s" % (local, live)) + local = {name: (SOURCE / name).read_bytes() for name in FILES} + live = live_digests() + changed = [name for name in FILES if hashlib.sha256(local[name]).hexdigest() != live[name]] + for name in FILES: + print("%-14s %s" % (name, "changed" if name in changed else "same")) if dry_run: - print("Dry run: nothing was changed." if local != live else "Already deployed.") + print("Dry run: nothing was changed." if changed else "Already deployed.") return 0 - if local == live: - print("The server already runs this file.") + if not changed: + print("The server already runs these files.") return 0 + for name in changed: # compile every new file on the server before anything goes live + result = remote("python3 -c 'import sys; compile(sys.stdin.read(), \"new\", \"exec\")'", local[name]) + if result.returncode: + print("%s does not compile on the server, nothing was changed:\n%s" % (name, text(result))) + return 1 stamp = time.strftime("%Y%m%d-%H%M%S") - backup = "%s.bak-%s" % (LIVE, stamp) - result = remote("set -e; cat > /tmp/members-server.new && python3 -m py_compile /tmp/members-server.new " - "&& cp -p %s %s && install -m 644 /tmp/members-server.new %s && rm -f /tmp/members-server.new" - % (shlex.quote(LIVE), shlex.quote(backup), shlex.quote(LIVE)), data) + for name in changed: + result = remote("set -e; cat > /tmp/members-%s.new" % shlex.quote(name), local[name]) + if result.returncode: + print("Upload of %s failed, nothing is live yet:\n%s" % (name, text(result))) + return 1 + steps = [] + for name in changed: + live_path = FOLDER + "/" + name + steps.append("([ -f %s ] && cp -p %s %s.bak-%s || true)" % (shlex.quote(live_path), shlex.quote(live_path), shlex.quote(live_path), stamp)) + steps.append("install -m 644 /tmp/members-%s.new %s" % (shlex.quote(name), shlex.quote(live_path))) + steps.append("rm -f /tmp/members-%s.new" % shlex.quote(name)) + result = remote("set -e; " + "; ".join(steps)) if result.returncode: - print("Upload failed, the live file is untouched:\n" + text(result)) - return 1 - print("backup: %s" % backup) + print("Installing failed:\n" + text(result)) + return restore(stamp) + print("backups: *.bak-%s" % stamp) remote("systemctl restart %s" % SERVICE) time.sleep(2) if healthy(): print("The service answers; deployed.") return 0 - print("The service did not answer: putting the backup back.") - remote("cp -p %s %s && systemctl restart %s" % (shlex.quote(backup), shlex.quote(LIVE), SERVICE)) + print("The service did not answer: putting the backups back.") + return restore(stamp) + + +def restore(stamp: str) -> int: + """Puts back every file that has a backup with this stamp (files that did not exist before stay; the old server.py ignores them).""" + steps = ["([ -f %s/%s.bak-%s ] && cp -p %s/%s.bak-%s %s/%s || true)" % ((FOLDER, name, stamp) * 2 + (FOLDER, name)) for name in FILES] + result = remote("; ".join(steps) + "; systemctl restart %s" % SERVICE) + if result.returncode: + print("Restoring failed:\n" + text(result)) + return 1 time.sleep(2) - print("Rolled back; the service answers: %s" % healthy()) - return 1 + ok = healthy() + print("Restored backup %s; the service answers: %s" % (stamp, ok)) + return 0 if ok else 1 def rollback(stamp: str | None) -> int: - if stamp: - backup = "%s.bak-%s" % (LIVE, stamp) - else: - listing = remote("ls -1 %s.bak-2* 2>/dev/null | tail -1" % shlex.quote(LIVE)).stdout.decode().strip() + if not stamp: + listing = remote("ls -1 %s/server.py.bak-2* 2>/dev/null | tail -1" % shlex.quote(FOLDER)).stdout.decode().strip() if not listing: print("No dated backup found.") return 1 - backup = listing - result = remote("cp -p %s %s && systemctl restart %s" % (shlex.quote(backup), shlex.quote(LIVE), SERVICE)) - if result.returncode: - print("Rollback failed:\n" + text(result)) - return 1 - time.sleep(2) - print("Restored %s; the service answers: %s" % (backup, healthy())) - return 0 if healthy() else 1 + stamp = listing.rsplit(".bak-", 1)[-1] + return restore(stamp) def main() -> int: diff --git a/services/members/catalog.py b/services/members/catalog.py new file mode 100644 index 0000000..96d39db --- /dev/null +++ b/services/members/catalog.py @@ -0,0 +1,251 @@ +"""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/.png). +Everything the author sends is judged first by the AI and then by the owner (see modbot); only approved items are ever listed. +""" +from __future__ import annotations + +import hashlib +import hmac +import re + +import community +from community import INSTALL, valid_uid + +KINDS = ("frame", "bubble") +SIZES = {"frame": (community.FRAME_SIDE, True), "bubble": (community.BUBBLE_SIDE, False)} +PAGE = 30 +ART_ID = re.compile(r"[0-9a-f]{24}\Z") +CURSOR = re.compile(r"(\d{1,12}):([0-9a-f]{24})\Z") +COLUMNS = "a.id, a.kind, a.name, a.description, a.uid, a.listed_at, a.installs, " \ + "(SELECT unique_id FROM shape_owner o WHERE o.uid = a.uid)" + + +def _item(row): + return {"id": row[0], "kind": row[1], "name": row[2], "description": row[3], + "author": {"uid": row[4], "name": row[7]}, "at": row[5], "installs": row[6]} + + +class Catalog: + def __init__(self, registry): + self.r = registry + self.operations = { + "publish": self.publish, "catalog": self.listing, "item": self.item, "profile": self.profile, + "mine": self.mine, "unpublish": self.unpublish, "install": self.install, "bubble_choose": self.choose_bubble, + "prove": self.prove, "library_add": self.library_add, "library_remove": self.library_remove, "library": self.library, + } + + def call(self, operation, payload): + return self.operations[operation](payload) + + # ---- reading --------------------------------------------------------------------------------------------- + + def _page(self, where, args, cursor, limit): + limit = limit if isinstance(limit, int) and 1 <= limit <= PAGE else PAGE + sql = ("SELECT " + COLUMNS + " FROM art a WHERE a.status='approved' AND a.listed=1 " + "AND a.uid NOT IN (SELECT uid FROM blocked)" + where) + if cursor: + match = CURSOR.fullmatch(cursor) if isinstance(cursor, str) else None + if match is None: + raise ValueError("Bad cursor") + sql += " AND (a.listed_at < ? OR (a.listed_at = ? AND a.id < ?))" + args = args + [int(match.group(1)), int(match.group(1)), match.group(2)] + sql += " ORDER BY a.listed_at DESC, a.id DESC LIMIT ?" + with self.r.connect() as db: + rows = db.execute(sql, args + [limit]).fetchall() + items = [_item(row) for row in rows] + more = "%d:%s" % (rows[-1][5], rows[-1][0]) if len(rows) == limit else None + return items, more + + def listing(self, p): + kind = p.get("kind") + if kind is not None and kind not in KINDS: + raise ValueError("Unknown kind") + items, more = self._page(" AND a.kind=?" if kind else "", [kind] if kind else [], p.get("cursor"), p.get("limit")) + return {"items": items, "next": more} + + def item(self, p): + art_id = p.get("id") + if not isinstance(art_id, str) or not ART_ID.fullmatch(art_id): + raise ValueError("Unknown item") + items, _ = self._page(" AND a.id=?", [art_id], None, 1) + if not items: + raise ValueError("Unknown item") + return {"item": items[0]} + + def profile(self, p): + uid = p.get("uid") + if not valid_uid(uid): + raise ValueError("Invalid account ID") + items, more = self._page(" AND a.uid=?", [uid], p.get("cursor"), p.get("limit")) + with self.r.connect() as db: + name = db.execute("SELECT unique_id FROM shape_owner WHERE uid=?", (uid,)).fetchone() + totals = db.execute("SELECT kind, COUNT(*), COALESCE(SUM(installs),0) FROM art WHERE uid=? AND status='approved' " + "AND listed=1 GROUP BY kind", (uid,)).fetchall() + return {"uid": uid, "name": name[0] if name else None, "items": items, "next": more, + "totals": {row[0]: {"count": row[1], "installs": row[2]} for row in totals}} + + # ---- the author's own side (the installation must have proven the account) ----------------------------- + + def _owner(self, uid, installation): + if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation): + raise ValueError("Invalid account ID or installation code") + digest = hashlib.sha256(installation.encode("ascii")).hexdigest() + with self.r.connect() as db: + owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone() + if owner is None or not hmac.compare_digest(owner[0], digest): + raise ValueError("Prove the account first") + return digest + + def mine(self, p): + """Everything this account has sent, in any state, with the reason when something was not accepted.""" + uid = p.get("uid") + self._owner(uid, p.get("installation")) + with self.r.connect() as db: + rows = db.execute("SELECT id, kind, name, description, status, reason, listed, created_at, installs FROM art " + "WHERE uid=? ORDER BY created_at DESC LIMIT 100", (uid,)).fetchall() + return {"items": [{"id": r[0], "kind": r[1], "name": r[2], "description": r[3], "status": r[4], + "reason": r[5] if r[4] == "rejected" else "", "listed": bool(r[6]), "at": r[7], "installs": r[8]} + for r in rows]} + + def publish(self, p): + """Lists a picture in the catalog. It goes to the AI and then to the owner; until approved it is not shown to anyone.""" + kind = p.get("kind") + if kind not in KINDS: + raise ValueError("Unknown kind") + side, square = SIZES[kind] + name = community.clean_name(p.get("name"), "Без названия") + description = community.clean_name(p.get("description"), "", 200) + got = self.r._receive(kind, p.get("uid"), p.get("installation"), p.get("unique_id"), name, p.get("png"), + side, square, listed=True, description=description) + if "art" not in got: + return got + return {"ok": True, "published": True, "id": got["art"]["id"], "status": got["art"]["status"]} + + def unpublish(self, p): + uid = p.get("uid") + self._owner(uid, p.get("installation")) + art_id = p.get("id") + if not isinstance(art_id, str) or not ART_ID.fullmatch(art_id): + raise ValueError("Unknown item") + with self.r.connect() as db: + changed = db.execute("UPDATE art SET listed=0 WHERE id=? AND uid=?", (art_id, uid)).rowcount + if not changed: + raise ValueError("Not your item") + return {"ok": True} + + def install(self, p): + """The "+" of the store: counts one installation once per item, never more.""" + installation, art_id = p.get("installation"), p.get("id") + if not isinstance(installation, str) or not INSTALL.fullmatch(installation): + raise ValueError("Invalid installation code") + if not isinstance(art_id, str) or not ART_ID.fullmatch(art_id): + raise ValueError("Unknown item") + digest = hashlib.sha256(installation.encode("ascii")).hexdigest() + with self.r.connect() as db: + if not db.execute("SELECT 1 FROM art WHERE id=? AND status='approved' AND listed=1", (art_id,)).fetchone(): + raise ValueError("Unknown item") + db.execute("INSERT OR IGNORE INTO art_installs(art_id, installation) VALUES(?,?)", (art_id, digest)) + count = db.execute("SELECT COUNT(*) FROM art_installs WHERE art_id=?", (art_id,)).fetchone()[0] + db.execute("UPDATE art SET installs=? WHERE id=?", (count, art_id)) + return {"ok": True, "installs": count} + + # ---- the account's library: what it added with "+" in the store; the mod offers these in its pickers --------- + + def prove(self, p): + """Binds the calling installation to the account (the code in the bio, once) so it may use the account's rights.""" + uid, installation = p.get("uid"), p.get("installation") + if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation): + raise ValueError("Invalid account ID or installation code") + digest = hashlib.sha256(installation.encode("ascii")).hexdigest() + with self.r.connect() as db: + if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone(): + raise ValueError("Account excluded") + owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone() + if owner is not None and hmac.compare_digest(owner[0], digest): + return {"ok": True, "published": True} + reply = self.r._prove(uid, digest, p.get("unique_id")) + return reply if reply is not None else {"ok": True, "published": True} + + def library_add(self, p): + """The "+" of the store: puts an approved catalog item into the account's library and counts the installation once.""" + uid = p.get("uid") + digest = self._owner(uid, p.get("installation")) + art_id = p.get("id") + if not isinstance(art_id, str) or not ART_ID.fullmatch(art_id): + raise ValueError("Unknown item") + with self.r.connect() as db: + if not db.execute("SELECT 1 FROM art WHERE id=? AND status='approved' AND listed=1", (art_id,)).fetchone(): + raise ValueError("Unknown item") + db.execute("INSERT OR IGNORE INTO account_library(uid, art_id, added_at) VALUES(?,?,?)", (uid, art_id, int(self.r.clock()))) + db.execute("INSERT OR IGNORE INTO art_installs(art_id, installation) VALUES(?,?)", (art_id, digest)) + count = db.execute("SELECT COUNT(*) FROM art_installs WHERE art_id=?", (art_id,)).fetchone()[0] + db.execute("UPDATE art SET installs=? WHERE id=?", (count, art_id)) + return {"ok": True, "installs": count} + + def library_remove(self, p): + uid = p.get("uid") + self._owner(uid, p.get("installation")) + art_id = p.get("id") + if not isinstance(art_id, str) or not ART_ID.fullmatch(art_id): + raise ValueError("Unknown item") + with self.r.connect() as db: + db.execute("DELETE FROM account_library WHERE uid=? AND art_id=?", (uid, art_id)) + return {"ok": True} + + def library(self, p): + """What this account has added, newest first (only what is still approved and listed).""" + uid = p.get("uid") + self._owner(uid, p.get("installation")) + with self.r.connect() as db: + rows = db.execute("SELECT " + COLUMNS + " FROM account_library l JOIN art a ON a.id = l.art_id " + "WHERE l.uid=? AND a.status='approved' AND a.listed=1 ORDER BY l.added_at DESC LIMIT 200", (uid,)).fetchall() + return {"items": [_item(row) for row in rows]} + + # ---- the bubble an account shows to other members ------------------------------------------------------ + + def choose_bubble(self, p): + """Publishes (or, for "none", withdraws) the bubble this account wants others to see on its messages, on the same terms as a + frame: the account is proven once. The bubble is the account's own picture or an approved one from the catalog.""" + uid, installation, art_id = p.get("uid"), p.get("installation"), p.get("id") + if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation): + raise ValueError("Invalid account ID or installation code") + if art_id != "none" and not (isinstance(art_id, str) and ART_ID.fullmatch(art_id)): + raise ValueError("Unknown bubble") + digest = hashlib.sha256(installation.encode("ascii")).hexdigest() + with self.r.connect() as db: + if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone(): + raise ValueError("Account excluded") + owner = db.execute("SELECT installation FROM shape_owner WHERE uid=?", (uid,)).fetchone() + has = db.execute("SELECT 1 FROM account_bubbles WHERE uid=?", (uid,)).fetchone() + proven = owner is not None and hmac.compare_digest(owner[0], digest) + if not proven and art_id == "none" and not has: + return {"ok": True, "published": True, "id": "none"} + if not proven: + reply = self.r._prove(uid, digest, p.get("unique_id")) + if reply is not None: + return reply + with self.r.connect() as db: + if art_id == "none": + db.execute("DELETE FROM account_bubbles WHERE uid=?", (uid,)) + else: + art = db.execute("SELECT kind, uid, status, listed FROM art WHERE id=?", (art_id,)).fetchone() + ok = art is not None and art[0] == "bubble" and ((art[1] == uid and art[2] != "rejected") or (art[3] and art[2] == "approved")) + if not ok: + raise ValueError("This bubble is not available for this account") + db.execute("INSERT INTO account_bubbles(uid, art_id, updated_at) VALUES(?,?,?) " + "ON CONFLICT(uid) DO UPDATE SET art_id=excluded.art_id, updated_at=excluded.updated_at", + (uid, art_id, int(self.r.clock()))) + return {"ok": True, "published": True, "id": art_id} + + def bubbles_of(self, uids): + """{uid: art id} of the approved bubbles these accounts show to others.""" + if not uids: + return {} + marks = ",".join("?" for _ in uids) + with self.r.connect() as db: + rows = db.execute("SELECT b.uid, b.art_id FROM account_bubbles b JOIN art a ON a.id = b.art_id " + "WHERE b.uid IN (" + marks + ") AND a.status='approved' AND a.kind='bubble' " + "AND b.uid NOT IN (SELECT uid FROM blocked)", list(uids)).fetchall() + return {uid: art_id for uid, art_id in rows} diff --git a/services/members/community.py b/services/members/community.py new file mode 100644 index 0000000..21f8417 --- /dev/null +++ b/services/members/community.py @@ -0,0 +1,61 @@ +"""Pictures that members make themselves (avatar frames, chat pictures): the safe handling of the bytes. + +Nothing a member sends is kept as it came: the picture is decoded, cropped, scaled and written again as a fresh PNG, so +metadata, odd chunks and anything that is not pixels is gone. What is left is judged by the AI and by the owner. +""" +from __future__ import annotations + +import io +import re + +UID = re.compile(r"[1-9][0-9]{4,24}\Z") +INSTALL = re.compile(r"[a-f0-9]{64}\Z") + + +def valid_uid(value): + return isinstance(value, str) and UID.fullmatch(value) is not None + + +MAX_UPLOAD = 400_000 +MAX_PIXELS = 16_000_000 +FRAME_SIDE = 256 +BUBBLE_SIDE = 512 +MAX_PNG = 150 * 1024 + + +def normalize_png(data: bytes, side: int, square: bool, limit: int = MAX_PNG) -> bytes: + """A fresh PNG of at most `side` pixels (exactly side x side when `square`, cropped in the middle), at most `limit` bytes.""" + from PIL import Image + + if not isinstance(data, (bytes, bytearray)) or not 0 < len(data) <= MAX_UPLOAD: + raise ValueError("The picture is too large") + try: + image = Image.open(io.BytesIO(data)) + if image.width * image.height > MAX_PIXELS: + raise ValueError("The picture is too large") + image.load() + except ValueError: + raise + except Exception: + raise ValueError("Not a picture") + image = image.convert("RGBA") + if square: + edge = min(image.width, image.height) + left, top = (image.width - edge) // 2, (image.height - edge) // 2 + image = image.crop((left, top, left + edge, top + edge)).resize((side, side), Image.LANCZOS) + else: + image.thumbnail((side, side), Image.LANCZOS) + for colors in (0, 256, 128, 64): + shown = image if colors == 0 else image.quantize(colors=colors, method=Image.FASTOCTREE) + out = io.BytesIO() + shown.save(out, "PNG", optimize=True) + if out.tell() <= limit: + return out.getvalue() + raise ValueError("The picture is too complicated") + + +def clean_name(name, default="Без названия", limit=30) -> str: + """A name for the screen: no control characters, no line breaks, at most `limit` characters.""" + text = "".join(ch for ch in (name if isinstance(name, str) else "") if ch >= " " and ch != "\x7f") + text = " ".join(text.split())[:limit].strip() + return text or default diff --git a/services/members/server.py b/services/members/server.py index e65967b..f1a63ff 100644 --- a/services/members/server.py +++ b/services/members/server.py @@ -13,7 +13,9 @@ from __future__ import annotations import argparse import base64 import hmac +import os import secrets +import sys import urllib.request import hashlib import json @@ -26,8 +28,11 @@ from contextlib import contextmanager from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -UID = re.compile(r"[1-9][0-9]{4,24}\Z") -INSTALL = re.compile(r"[a-f0-9]{64}\Z") +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import catalog +import community +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. @@ -37,6 +42,18 @@ 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") +UPLOAD_BODY = 300_000 +# Operations by how often one address may call them: reads, the account's own small writes, installs, uploads. +READS = ("lookup", "pair_lookup", "catalog", "item", "profile", "library") +WRITES = ("shape", "avatar_frame", "mine", "unpublish", "bubble_choose", "prove", "library_add", "library_remove") +UPLOADS = ("frame_upload", "bubble_upload", "publish") +CATALOG = ("publish", "catalog", "item", "profile", "mine", "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") + CATALOG # The niche-mod badge can be claimed until this moment (Moscow time). CLAIM_DEADLINE = 1794735240 # 2026-11-15 12:34:00 +03:00 @@ -65,13 +82,11 @@ def frame_permitted(frame, grants): return pack not in RESTRICTED_PACKS or frame in grants or pack + ".*" in grants -def valid_uid(value): - return isinstance(value, str) and UID.fullmatch(value) is not None - - class Registry: - def __init__(self, path, clock=time.time, fetcher=fetch_profile): + 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))") @@ -86,6 +101,20 @@ class Registry: 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)") + 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),)) @@ -218,7 +247,13 @@ class Registry: 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 not self.frame_allowed(uid, 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: @@ -267,12 +302,158 @@ class Registry: 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, "ttl": 300} + "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_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 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 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} def frame_allowed(self, uid, frame): """May this account use this frame? Open packs: always; closed packs: only with a grant.""" @@ -315,8 +496,9 @@ class Limits: def allow(self, ip, operation): key = ip, operation - window, count = ((60, 120) if operation == "lookup" else (3600, 10) if operation == "claim" - else (3600, 30) if operation in ("shape", "avatar_frame") else (3600, 40)) + window, count = ((60, 120) if operation in READS else (3600, 10) if operation == "claim" + 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: @@ -351,26 +533,40 @@ class Handler(BaseHTTPRequestHandler): self.wfile.write(raw) 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 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 ("presence", "lookup", "withdraw", "code", "claim", "shape", "avatar_frame"): + 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 ("lookup", "claim", "shape", "avatar_frame") else "presence"): + 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 <= 8192: + if not 0 < length <= (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 == "lookup": + if operation in CATALOG: + result = self.server.registry.catalog.call(operation, payload) + elif operation == "lookup": result = self.server.registry.lookup(payload.get("uids")) elif operation == "code": result = {"code": self.server.registry.code(payload.get("uid")), @@ -380,6 +576,16 @@ class Handler(BaseHTTPRequestHandler): 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 == "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")) @@ -415,6 +621,11 @@ def main(): 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 + modbot.start(server.registry, token, owner) server.serve_forever() diff --git a/src/lihont/two/avatar/AvatarShapes.java b/src/lihont/two/avatar/AvatarShapes.java index 4261acf..df45a90 100644 --- a/src/lihont/two/avatar/AvatarShapes.java +++ b/src/lihont/two/avatar/AvatarShapes.java @@ -74,7 +74,7 @@ public final class AvatarShapes { refreshed = true; FrameStore.refresh(context, false); } - FrameIndex.Frame known = FrameStore.index(context).frame(look.frame); + FrameIndex.Frame known = FrameStore.frame(context, look.frame); if (known != null) { diameter = size * keep(size, view.getResources().getDisplayMetrics().density); frame = FrameDraw.prepare(context, known, shape, diameter, view); diff --git a/src/lihont/two/avatar/FramePublisher.java b/src/lihont/two/avatar/FramePublisher.java index aac56ef..0b53723 100644 --- a/src/lihont/two/avatar/FramePublisher.java +++ b/src/lihont/two/avatar/FramePublisher.java @@ -18,6 +18,49 @@ public final class FramePublisher { private FramePublisher() {} + /** Sends the member's own picture to be checked; others see it as a frame only after it is approved. The same proof as publishing. */ + public static void upload(final Context context, final byte[] png, final String name, final ShapePublisher.Callback callback) { + final NicheClaim.Account account = NicheClaim.account(); + if (account == null) { + callback.done(new ShapePublisher.Result(false, null, "Войдите в TikTok, чтобы отправить рамку")); + return; + } + new Thread(new Runnable() { + @Override public void run() { + ShapePublisher.Result result; + try { + JSONObject reply = lihont.two.badge.MemberClient.post("frame_upload", new JSONObject() + .put("uid", account.uid) + .put("installation", Installation.secret(context.getApplicationContext() != null + ? context.getApplicationContext() : context)) + .put("unique_id", account.uniqueId) + .put("name", name) + .put("png", android.util.Base64.encodeToString(png, android.util.Base64.NO_WRAP))); + if (reply.optBoolean("published", false)) { + String status = reply.optString("status", "new"); + result = new ShapePublisher.Result(!"rejected".equals(status), null, + "rejected".equals(status) ? "Эту картинку не приняли" + : "approved".equals(status) ? "Рамка уже принята: её видят все с модом" + : "Отправлено на проверку. Когда её примут, рамку увидят все с модом"); + } else { + String code = reply.optString("code", ""); + result = new ShapePublisher.Result(false, code.length() == 0 ? null : code, + "Кода в описании профиля не нашли. Вставьте его и подождите минуту."); + } + } catch (Exception error) { + result = new ShapePublisher.Result(false, null, + error.getMessage() == null ? "Нет связи с сервером" : error.getMessage()); + } + final ShapePublisher.Result outcome = result; + MAIN.post(new Runnable() { + @Override public void run() { + callback.done(outcome); + } + }); + } + }, "lihont-frame-upload").start(); + } + public static void publish(final Context context, final String frameId, final ShapePublisher.Callback callback) { final NicheClaim.Account account = NicheClaim.account(); if (account == null) { diff --git a/src/lihont/two/avatar/Installation.java b/src/lihont/two/avatar/Installation.java index b32234f..0dbfd60 100644 --- a/src/lihont/two/avatar/Installation.java +++ b/src/lihont/two/avatar/Installation.java @@ -13,13 +13,13 @@ import java.security.SecureRandom; * binds an account to the installation that proved it, so only this installation may change its published shape * without proving the account again. It never leaves the phone except in requests to that service. */ -final class Installation { +public final class Installation { private static final String FILE = "lihont-installation"; private static String secret; private Installation() {} - static synchronized String secret(Context context) throws IOException { + public static synchronized String secret(Context context) throws IOException { if (secret != null) return secret; File file = new File(context.getFilesDir(), FILE); if (file.isFile()) { diff --git a/src/lihont/two/avatar/PairPictures.java b/src/lihont/two/avatar/PairPictures.java new file mode 100644 index 0000000..dbe7ad7 --- /dev/null +++ b/src/lihont/two/avatar/PairPictures.java @@ -0,0 +1,300 @@ +package lihont.two.avatar; + +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; + +import org.json.JSONObject; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import lihont.two.account.CurrentAccount; +import lihont.two.badge.NicheClaim; +import lihont.two.frame.FrameStore; + +/** + * One picture for the chat between two accounts, the same on both phones: whichever of the two chose it, both see it behind the + * bubbles once it has been approved. The picture lives on the members service (asked about at most every few minutes, and only by + * one of the two accounts); the phone keeps the pictures it has seen under their checksums and the answer, so a chat dresses + * itself at once and without a network. + * + * A picture the member has just sent is shown to them straight away, before it is approved, for a few days. + */ +public final class PairPictures { + private static final String ART = "https://lihont.space/members/v1/art/"; + private static final String PREFS = "lihont_pair_pictures"; + private static final long CHECK_MS = 10L * 60L * 1000L; + private static final long PENDING_MS = 3L * 24L * 3600L * 1000L; + private static final int MAX_BYTES = 150 * 1024; + private static final Handler MAIN = new Handler(Looper.getMainLooper()); + + private static final Map IDS = new HashMap(); + private static final Map CHECKED = new HashMap(); + private static final Set FETCHING = new HashSet(); + private static final Map BITMAPS = new LinkedHashMap(4, 0.75f, true) { + @Override protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > 4; + } + }; + + private PairPictures() {} + + /** The picture of the chat with `peerUid` for the signed-in account, or null (none chosen, not approved, or not fetched yet). */ + public static synchronized Bitmap forPartner(Context context, String peerUid) { + String mine = CurrentAccount.uid(); + if (mine == null || peerUid == null || mine.equals(peerUid)) return null; + String key = key(mine, peerUid); + SharedPreferences prefs = prefs(context); + long now = SystemClock.uptimeMillis(); + Long checked = CHECKED.get(key); + if (checked == null || now - checked.longValue() > CHECK_MS) { + CHECKED.put(key, Long.valueOf(now)); + ask(context.getApplicationContext() != null ? context.getApplicationContext() : context, mine, peerUid, key); + } + String hex = IDS.get(key); + if (hex == null) { + hex = prefs.getString("id_" + key, ""); + IDS.put(key, hex); + } + if (hex.length() == 0) { + hex = pending(prefs, key); + if (hex == null) return null; + } + Bitmap cached = BITMAPS.get(hex); + if (cached != null) return cached; + File file = new File(folder(context), hex + ".png"); + if (file.isFile()) { + Bitmap decoded = BitmapFactory.decodeFile(file.getPath()); + if (decoded != null) BITMAPS.put(hex, decoded); + return decoded; + } + fetch(context.getApplicationContext() != null ? context.getApplicationContext() : context, hex); + return null; + } + + /** The picture with this id (24 hex digits) when it is on the phone, else null and it is fetched in the background. */ + public static synchronized Bitmap artBitmap(Context context, String hex) { + if (hex == null || !hex.matches("[0-9a-f]{24}")) return null; + Bitmap cached = BITMAPS.get(hex); + if (cached != null) return cached; + File file = new File(folder(context), hex + ".png"); + if (file.isFile()) { + Bitmap decoded = BitmapFactory.decodeFile(file.getPath()); + if (decoded != null) BITMAPS.put(hex, decoded); + return decoded; + } + fetch(context.getApplicationContext() != null ? context.getApplicationContext() : context, hex); + return null; + } + + /** The same, but fetched now on the calling thread (which must not be the main one); null when it cannot be had. */ + public static Bitmap fetchNow(Context context, String hex) { + try { + File file = new File(folder(context), hex + ".png"); + if (!file.isFile()) { + byte[] data = get(ART + hex + ".png"); + if (data.length == 0 || !FrameStore.sha256(data).startsWith(hex)) return null; + save(context, hex, data); + } + return BitmapFactory.decodeFile(file.getPath()); + } catch (Exception unreachable) { + return null; + } + } + + private static String pending(SharedPreferences prefs, String key) { + long at = prefs.getLong("pending_at_" + key, 0L); + String hex = prefs.getString("pending_" + key, ""); + return hex.length() == 0 || System.currentTimeMillis() - at > PENDING_MS ? null : hex; + } + + private static String key(String mine, String peer) { + return mine.compareTo(peer) < 0 ? mine + ":" + peer : peer + ":" + mine; + } + + private static SharedPreferences prefs(Context context) { + return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } + + private static File folder(Context context) { + File folder = new File(context.getFilesDir(), "lihont-pair-pictures"); + if (!folder.isDirectory()) folder.mkdirs(); + return folder; + } + + private static void ask(final Context context, final String mine, final String peer, final String key) { + new Thread(new Runnable() { + @Override public void run() { + try { + JSONObject reply = lihont.two.badge.MemberClient.post("pair_lookup", new JSONObject() + .put("uid", mine).put("peer", peer).put("installation", Installation.secret(context))); + String id = reply.isNull("id") ? "" : reply.optString("id", ""); + if (!id.matches("[0-9a-f]{24}")) id = ""; + synchronized (PairPictures.class) { + IDS.put(key, id); + SharedPreferences.Editor edit = prefs(context).edit().putString("id_" + key, id); + if (id.length() > 0) edit.remove("pending_" + key); + edit.apply(); + } + } catch (Exception unreachable) { + // the last answer stays + } + } + }, "lihont-pair-lookup").start(); + } + + private static void fetch(final Context context, final String hex) { + if (!FETCHING.add(hex)) return; + new Thread(new Runnable() { + @Override public void run() { + try { + byte[] data = get(ART + hex + ".png"); + if (data.length > 0 && FrameStore.sha256(data).startsWith(hex)) save(context, hex, data); + } catch (Exception unreachable) { + // not approved yet, or no network: asked again on a later frame of the chat + } finally { + synchronized (PairPictures.class) { + FETCHING.remove(hex); + } + } + } + }, "lihont-pair-art").start(); + } + + private static void save(Context context, String hex, byte[] data) throws IOException { + File folder = folder(context); + File part = new File(folder, hex + ".part"); + try (FileOutputStream out = new FileOutputStream(part)) { + out.write(data); + } + if (!part.renameTo(new File(folder, hex + ".png"))) throw new IOException("rename"); + File[] files = folder.listFiles(); + if (files != null && files.length > 40) { + java.util.Arrays.sort(files, new java.util.Comparator() { + @Override public int compare(File a, File b) { + return Long.compare(a.lastModified(), b.lastModified()); + } + }); + for (int i = 0; i < files.length - 40; i++) if (!files[i].getName().equals(hex + ".png")) files[i].delete(); + } + } + + private static byte[] get(String address) throws IOException { + URL url = new URL(address); + if (!"https".equals(url.getProtocol())) throw new IOException("not https"); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setConnectTimeout(6000); + connection.setReadTimeout(15000); + connection.setInstanceFollowRedirects(false); + try { + if (connection.getResponseCode() != 200) throw new IOException("status " + connection.getResponseCode()); + try (InputStream in = connection.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream()) { + byte[] buffer = new byte[8192]; + int count; + while ((count = in.read(buffer)) >= 0) { + out.write(buffer, 0, count); + if (out.size() > MAX_BYTES) throw new IOException("too large"); + } + return out.toByteArray(); + } + } finally { + connection.disconnect(); + } + } + + /** Sends the picture for the chat with `peerUid` to be checked; it is shown on this phone at once and on the other one once approved. */ + public static void upload(final Context context, final String peerUid, final byte[] png, final ShapePublisher.Callback callback) { + final NicheClaim.Account account = NicheClaim.account(); + if (account == null) { + callback.done(new ShapePublisher.Result(false, null, "Войдите в TikTok, чтобы отправить картинку")); + return; + } + final Context app = context.getApplicationContext() != null ? context.getApplicationContext() : context; + new Thread(new Runnable() { + @Override public void run() { + ShapePublisher.Result result; + try { + JSONObject reply = lihont.two.badge.MemberClient.post("bubble_upload", new JSONObject() + .put("uid", account.uid).put("peer", peerUid) + .put("installation", Installation.secret(app)).put("unique_id", account.uniqueId) + .put("name", "Картинка чата") + .put("png", android.util.Base64.encodeToString(png, android.util.Base64.NO_WRAP))); + if (reply.optBoolean("published", false)) { + String status = reply.optString("status", "new"); + String id = reply.optString("id", ""); + if (!"rejected".equals(status) && id.matches("[0-9a-f]{24}")) { + String key = key(account.uid, peerUid); + synchronized (PairPictures.class) { + save(app, id, png); + BITMAPS.remove(id); + prefs(app).edit().putString("pending_" + key, id).putLong("pending_at_" + key, System.currentTimeMillis()).apply(); + CHECKED.remove(key); + } + } + result = new ShapePublisher.Result(!"rejected".equals(status), null, + "rejected".equals(status) ? "Эту картинку не приняли" + : "approved".equals(status) ? "Картинка принята: её видите вы оба" + : "Отправлено на проверку. Вы видите её уже сейчас, собеседник увидит после проверки"); + } else { + String code = reply.optString("code", ""); + result = new ShapePublisher.Result(false, code.length() == 0 ? null : code, + "Кода в описании профиля не нашли. Вставьте его и подождите минуту."); + } + } catch (Exception error) { + result = new ShapePublisher.Result(false, null, error.getMessage() == null ? "Нет связи с сервером" : error.getMessage()); + } + final ShapePublisher.Result outcome = result; + MAIN.post(new Runnable() { + @Override public void run() { + callback.done(outcome); + } + }); + } + }, "lihont-pair-upload").start(); + } + + /** Takes the shared picture of the chat away, for both. */ + public static void clear(final Context context, final String peerUid, final ShapePublisher.Callback callback) { + final String mine = CurrentAccount.uid(); + final Context app = context.getApplicationContext() != null ? context.getApplicationContext() : context; + new Thread(new Runnable() { + @Override public void run() { + ShapePublisher.Result result; + try { + if (mine == null) throw new IOException("Войдите в TikTok"); + lihont.two.badge.MemberClient.post("pair_clear", new JSONObject() + .put("uid", mine).put("peer", peerUid).put("installation", Installation.secret(app))); + String key = key(mine, peerUid); + synchronized (PairPictures.class) { + IDS.put(key, ""); + prefs(app).edit().remove("id_" + key).remove("pending_" + key).apply(); + } + result = new ShapePublisher.Result(true, null, "Общая картинка убрана"); + } catch (Exception error) { + result = new ShapePublisher.Result(false, null, error.getMessage() == null ? "Нет связи с сервером" : error.getMessage()); + } + final ShapePublisher.Result outcome = result; + MAIN.post(new Runnable() { + @Override public void run() { + callback.done(outcome); + } + }); + } + }, "lihont-pair-clear").start(); + } +} diff --git a/src/lihont/two/avatar/ShapeCatalog.java b/src/lihont/two/avatar/ShapeCatalog.java index 0054d0a..a3deb18 100644 --- a/src/lihont/two/avatar/ShapeCatalog.java +++ b/src/lihont/two/avatar/ShapeCatalog.java @@ -47,11 +47,13 @@ public final class ShapeCatalog { private static final class Entry { final ModSettings.AvatarShape shape; final String frame; + final String bubble; final long until; - Entry(ModSettings.AvatarShape shape, String frame, long until) { + Entry(ModSettings.AvatarShape shape, String frame, String bubble, long until) { this.shape = shape; this.frame = frame; + this.bubble = bubble; this.until = until; } } @@ -84,6 +86,13 @@ public final class ShapeCatalog { return entry == null || SystemClock.uptimeMillis() >= entry.until ? null : entry.frame; } + /** The chat picture `uid` published for its messages (asks the service when it is not known yet), or null. */ + public static String bubbleOf(String uid) { + shapeOf(uid, null); + Entry entry = KNOWN.get(uid); + return entry == null || SystemClock.uptimeMillis() >= entry.until ? null : entry.bubble; + } + private static boolean validUid(String uid) { if (uid == null || uid.length() < 5 || uid.length() > 25 || uid.charAt(0) == '0') return false; for (int i = 0; i < uid.length(); i++) { @@ -105,31 +114,34 @@ public final class ShapeCatalog { @Override public void run() { JSONObject shapes = null; JSONObject frames = null; + JSONObject bubbled = null; try { JSONObject reply = MemberClient.post("lookup", new JSONObject().put("uids", new JSONArray(ids))); shapes = reply.optJSONObject("shapes"); if (shapes == null) shapes = new JSONObject(); frames = reply.optJSONObject("avatar_frames"); + bubbled = reply.optJSONObject("bubbles"); } catch (Exception ignored) { // A failed lookup leaves everyone round for a minute. } final JSONObject found = shapes; final JSONObject framed = frames; + final JSONObject bubbles = bubbled; MAIN.post(new Runnable() { @Override public void run() { - record(ids, found, framed); + record(ids, found, framed, bubbles); } }); } }); } - private static void record(List ids, JSONObject shapes, JSONObject frames) { + private static void record(List ids, JSONObject shapes, JSONObject frames, JSONObject bubbles) { long now = SystemClock.uptimeMillis(); if (KNOWN.size() > MAX_KNOWN) KNOWN.clear(); for (String uid : ids) { if (shapes == null) { - KNOWN.put(uid, new Entry(null, null, now + FAILED_MS)); + KNOWN.put(uid, new Entry(null, null, null, now + FAILED_MS)); continue; } ModSettings.AvatarShape shape = null; @@ -140,7 +152,9 @@ public final class ShapeCatalog { } String frame = frames == null ? null : frames.optString(uid, null); if (!lihont.two.frame.FrameIndex.validFrameId(frame)) frame = null; - KNOWN.put(uid, new Entry(shape, frame, now + KEEP_MS)); + String bubble = bubbles == null ? null : bubbles.optString(uid, null); + if (bubble != null && !bubble.matches("[0-9a-f]{24}")) bubble = null; + KNOWN.put(uid, new Entry(shape, frame, bubble, now + KEEP_MS)); } if (shapes != null) redraw(); if (!PENDING.isEmpty() && !scheduled) { diff --git a/src/lihont/two/badge/Badges.java b/src/lihont/two/badge/Badges.java index 17bd786..b89aa50 100644 --- a/src/lihont/two/badge/Badges.java +++ b/src/lihont/two/badge/Badges.java @@ -351,6 +351,11 @@ public final class Badges { return AccountNames.remember(user, name); } + /** The account whose name is spelled like this, when only one account has been seen with it, else null. */ + public static String uidForName(CharSequence name) { + return AccountNames.uidByValue(name); + } + /** Whether the other mods' badges are wanted: used by the hook that must not run when they are off. */ public static boolean enabled() { return SettingsHost.foreignBadges(); diff --git a/src/lihont/two/bar/AvatarBadge.java b/src/lihont/two/bar/AvatarBadge.java index f12cd8a..5896fb8 100644 --- a/src/lihont/two/bar/AvatarBadge.java +++ b/src/lihont/two/bar/AvatarBadge.java @@ -115,7 +115,7 @@ final class AvatarBadge extends Drawable { if (id == null) return null; android.content.Context context = item.getContext(); lihont.two.frame.FrameStore.refresh(context, false); - lihont.two.frame.FrameIndex.Frame known = lihont.two.frame.FrameStore.index(context).frame(id); + lihont.two.frame.FrameIndex.Frame known = lihont.two.frame.FrameStore.frame(context, id); if (known == null) return null; return lihont.two.frame.FrameDraw.prepare(context, known, shape, FRAMED_DIAMETER_DP * density, item); } catch (Throwable ignored) { diff --git a/src/lihont/two/chat/BubbleStore.java b/src/lihont/two/chat/BubbleStore.java index 5fe675a..9d86192 100644 --- a/src/lihont/two/chat/BubbleStore.java +++ b/src/lihont/two/chat/BubbleStore.java @@ -72,6 +72,19 @@ public final class BubbleStore { prefs.edit().putStringSet(PEOPLE, known).apply(); } + /** Remembers which account a name in a chat header belongs to, so a picture can be shared with that account later. */ + public static void rememberAccount(Context context, String person, String uid) { + if (!plausible(person) || uid == null) return; + SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + String key = "uid_" + person; + if (!uid.equals(prefs.getString(key, null))) prefs.edit().putString(key, uid).apply(); + } + + /** The account remembered for a name, or null. */ + public static String accountOf(Context context, String person) { + return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("uid_" + person, null); + } + public static java.util.List people(Context context) { SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); java.util.List list = new java.util.ArrayList(); diff --git a/src/lihont/two/chat/Bubbles.java b/src/lihont/two/chat/Bubbles.java index 3793c40..20c2de8 100644 --- a/src/lihont/two/chat/Bubbles.java +++ b/src/lihont/two/chat/Bubbles.java @@ -29,6 +29,7 @@ public final class Bubbles { private static final WeakHashMap WATCHED = new WeakHashMap(); private static final WeakHashMap TEXT = new WeakHashMap(); private static String name; + private static String partnerUid; private static long nameAt; private Bubbles() {} @@ -75,6 +76,15 @@ public final class Bubbles { ViewGroup list = (ViewGroup) found; String partner = null; Bitmap own = BubbleStore.forSlot(activity, BubbleStore.OWN, false); + // one picture for the chat, chosen by either of the two, is the same on both phones and replaces the personal ones + partner = cachedName(activity, decor, list); + BubbleStore.seen(activity, partner); + Bitmap shared = partnerUid == null ? null : lihont.two.avatar.PairPictures.forPartner(activity, partnerUid); + String publishedId = partnerUid == null ? null : lihont.two.avatar.ShapeCatalog.bubbleOf(partnerUid); + Bitmap published = publishedId == null ? null : lihont.two.avatar.PairPictures.artBitmap(activity, publishedId); + if (shared != null) { + own = shared; + } Bitmap theirs = null; boolean theirsLoaded = false; int corner = Math.round(CORNER_DP * activity.getResources().getDisplayMetrics().density); @@ -92,11 +102,11 @@ public final class Bubbles { Bitmap picture; if (mine) { picture = own; + } else if (shared != null) { + picture = shared; } else { if (!theirsLoaded) { - partner = partner == null ? cachedName(decor, list) : partner; - BubbleStore.seen(activity, partner); - theirs = partner == null ? BubbleStore.forSlot(activity, BubbleStore.GENERAL, false) + theirs = published != null ? published : partner == null ? BubbleStore.forSlot(activity, BubbleStore.GENERAL, false) : BubbleStore.forSlot(activity, "p:" + partner, true); theirsLoaded = true; } @@ -114,11 +124,13 @@ public final class Bubbles { } /** The header name is looked up at most every few seconds: walking the whole screen for each frame would be wasteful. */ - private static String cachedName(View decor, ViewGroup list) { + private static String cachedName(Activity activity, View decor, ViewGroup list) { long now = android.os.SystemClock.uptimeMillis(); if (now - nameAt > NAME_MS) { name = headerName(decor, list); nameAt = now; + partnerUid = name == null ? null : lihont.two.badge.Badges.uidForName(name); + if (partnerUid != null) BubbleStore.rememberAccount(activity, name, partnerUid); } return name; } diff --git a/src/lihont/two/frame/CustomFrames.java b/src/lihont/two/frame/CustomFrames.java new file mode 100644 index 0000000..65afe17 --- /dev/null +++ b/src/lihont/two/frame/CustomFrames.java @@ -0,0 +1,185 @@ +package lihont.two.frame; + +import android.content.Context; +import android.graphics.Bitmap; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Frames that members made from their own pictures. A frame is one square picture drawn over the avatar, 1.3 times as wide as the + * avatar, so it can reach out of the avatar's edge. Its id is "u." and the first 24 hex digits of the picture's SHA-256: the picture is + * fetched from the members service by that name (only once the owner has approved it there) and checked against its own name, so a + * file is either exactly the picture the id promises or is not kept. + * + * A picture that is not a frame (a photo, a drawing with a solid middle) is turned into one on the phone: cut square, and cut into a + * ring, with the round hole left where the avatar will be. + */ +public final class CustomFrames { + public static final int SIDE = FrameCut.SIDE; + /** The picture's width as a part of the avatar's width: the avatar fills the middle 1/1.3 of it. */ + public static final float OVERLAY = FrameCut.OVERLAY; + private static final String ART = "https://lihont.space/members/v1/art/"; + private static final int MAX_BYTES = 150 * 1024; + private static final int MAX_FILES = 80; + private static final long RETRY_MS = 10L * 60L * 1000L; + private static final Pattern ID = Pattern.compile("u\\.[0-9a-f]{24}"); + private static final Map FRAMES = new HashMap(); + private static final Map FAILED = new HashMap(); + private static final java.util.Set FETCHING = new java.util.HashSet(); + + private CustomFrames() {} + + public static boolean isCustom(String id) { + return id != null && ID.matcher(id).matches(); + } + + static boolean isCustom(FrameIndex.Sprite sprite) { + return sprite.file.startsWith("u/"); + } + + private static File folder(Context context) { + File folder = new File(context.getFilesDir(), "lihont-frames-u"); + if (!folder.isDirectory()) folder.mkdirs(); + return folder; + } + + /** The stored picture of a custom sprite, or null. */ + static File file(Context context, FrameIndex.Sprite sprite) { + File file = new File(folder(context), sprite.sha256 + ".png"); + return file.isFile() ? file : null; + } + + /** + * The frame for a custom id, or null while its picture is not on the phone (it is then fetched in the background and the views + * that show frames are redrawn when it has arrived). + */ + public static synchronized FrameIndex.Frame frame(Context context, String id) { + FrameIndex.Frame known = FRAMES.get(id); + if (known != null) return known; + String hex = id.substring(2); + if (new File(folder(context), hex + ".png").isFile()) { + FrameIndex.Sprite sprite = new FrameIndex.Sprite("u/" + hex + ".png", hex, MAX_BYTES, SIDE, SIDE); + FrameIndex.Ring none = new FrameIndex.Ring(0f, 0f, 0, 0, 0); + List parts = new ArrayList(); + parts.add(new FrameIndex.Part(sprite, 0.5f, 0.5f, 0f, OVERLAY, 0f, 0f, false, true, true)); + known = new FrameIndex.Frame(id, "Своя рамка", none, parts); + if (FRAMES.size() > 64) FRAMES.clear(); + FRAMES.put(id, known); + return known; + } + fetch(context.getApplicationContext() != null ? context.getApplicationContext() : context, hex); + return null; + } + + private static void fetch(final Context context, final String hex) { + Long failedAt = FAILED.get(hex); + if (failedAt != null && android.os.SystemClock.uptimeMillis() - failedAt.longValue() < RETRY_MS) return; + if (!FETCHING.add(hex)) return; + Thread worker = new Thread(new Runnable() { + @Override public void run() { + boolean ok = false; + try { + byte[] data = FrameStore.get(ART + hex + ".png", MAX_BYTES); + if (data.length > 0 && FrameStore.sha256(data).startsWith(hex)) { + store(context, hex, data); + ok = true; + } + } catch (Throwable unreachable) { + // not approved yet, or no network: tried again later + } + synchronized (CustomFrames.class) { + FETCHING.remove(hex); + if (!ok) FAILED.put(hex, Long.valueOf(android.os.SystemClock.uptimeMillis())); + } + if (ok) FrameStore.changed(); + } + }, "lihont-frame-art"); + worker.setDaemon(true); + worker.start(); + } + + private static void store(Context context, String hex, byte[] data) throws IOException { + File folder = folder(context); + File part = new File(folder, hex + ".part"); + try (FileOutputStream out = new FileOutputStream(part)) { + out.write(data); + } + if (!part.renameTo(new File(folder, hex + ".png"))) throw new IOException("rename"); + File[] files = folder.listFiles(); + if (files != null && files.length > MAX_FILES) { + Arrays.sort(files, new Comparator() { + @Override public int compare(File a, File b) { + return Long.compare(a.lastModified(), b.lastModified()); + } + }); + for (int i = 0; i < files.length - MAX_FILES; i++) if (!files[i].getName().equals(hex + ".png")) files[i].delete(); + } + } + + /** The member's own frames, newest first, per account: they are listed in the picker beside the catalog's. */ + public static synchronized java.util.List mine(Context context, String uid) { + java.util.List out = new ArrayList(); + if (uid == null) return out; + String text = context.getSharedPreferences("lihont_frames_mine", Context.MODE_PRIVATE).getString(uid, ""); + for (String id : text.split(",")) { + if (isCustom(id) && !out.contains(id) && new File(folder(context), id.substring(2) + ".png").isFile()) out.add(id); + } + return out; + } + + /** Adds a frame to the account's own list (kept at most 12, the oldest leaves first). */ + public static synchronized void remember(Context context, String uid, String id) { + if (uid == null || !isCustom(id)) return; + java.util.List list = mine(context, uid); + list.remove(id); + list.add(0, id); + StringBuilder text = new StringBuilder(); + for (int i = 0; i < list.size() && i < 12; i++) text.append(i == 0 ? "" : ",").append(list.get(i)); + context.getSharedPreferences("lihont_frames_mine", Context.MODE_PRIVATE).edit().putString(uid, text.toString()).apply(); + } + + /** Keeps the member's own picture on the phone at once and returns its frame id ("u." and the checksum), or null. */ + public static synchronized String save(Context context, byte[] png) { + try { + String hex = FrameStore.sha256(png).substring(0, 24); + store(context, hex, png); + FRAMES.remove("u." + hex); + FrameStore.changed(); + return "u." + hex; + } catch (Throwable failed) { + return null; + } + } + + /** + * Turns any picture into the PNG of a frame: cut square in the middle, scaled to SIDE, and, unless its middle is already see-through, + * cut into a ring (outer edge round, a round hole for the avatar). Returns null for a picture that cannot be used. + */ + public static byte[] make(Bitmap source) { + try { + int edge = Math.min(source.getWidth(), source.getHeight()); + if (edge < 16) return null; + Bitmap square = Bitmap.createBitmap(source, (source.getWidth() - edge) / 2, (source.getHeight() - edge) / 2, edge, edge); + Bitmap scaled = Bitmap.createScaledBitmap(square, SIDE, SIDE, true); + int[] pixels = new int[SIDE * SIDE]; + scaled.getPixels(pixels, 0, SIDE, 0, 0, SIDE, SIDE); + if (!FrameCut.seeThroughMiddle(pixels)) FrameCut.ring(pixels); + Bitmap result = Bitmap.createBitmap(pixels, SIDE, SIDE, Bitmap.Config.ARGB_8888); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + result.compress(Bitmap.CompressFormat.PNG, 100, out); + return out.toByteArray(); + } catch (Throwable unusable) { + return null; + } + } +} diff --git a/src/lihont/two/frame/FrameCut.java b/src/lihont/two/frame/FrameCut.java new file mode 100644 index 0000000..9e36347 --- /dev/null +++ b/src/lihont/two/frame/FrameCut.java @@ -0,0 +1,53 @@ +package lihont.two.frame; + +/** + * The pixel maths that turns a picture into a frame, on plain ARGB arrays (so it runs and is tested without a phone). + * + * A frame is a square picture drawn over the avatar, OVERLAY times as wide as the avatar: the avatar fills the middle 1/OVERLAY of it. + */ +final class FrameCut { + static final int SIDE = 256; + static final float OVERLAY = 1.3f; + + private FrameCut() {} + + /** True when most of the middle disc is see-through: the picture is a frame already and is kept as it is. */ + static boolean seeThroughMiddle(int[] pixels) { + float middle = SIDE / 2f; + float reach = SIDE * 0.3f; + int total = 0; + int solid = 0; + for (int y = 0; y < SIDE; y++) { + for (int x = 0; x < SIDE; x++) { + float dx = x + 0.5f - middle; + float dy = y + 0.5f - middle; + if (dx * dx + dy * dy > reach * reach) continue; + total++; + if ((pixels[y * SIDE + x] >>> 24) > 128) solid++; + } + } + return total > 0 && solid < total / 2; + } + + /** Keeps only the ring between the hole (1/OVERLAY of the width, a little less so the ring overlaps the avatar's edge) and the circle. */ + static void ring(int[] pixels) { + float middle = SIDE / 2f; + float inner = SIDE / OVERLAY / 2f * 0.96f; + float outer = SIDE / 2f - 1f; + for (int y = 0; y < SIDE; y++) { + for (int x = 0; x < SIDE; x++) { + float dx = x + 0.5f - middle; + float dy = y + 0.5f - middle; + float distance = (float) Math.sqrt(dx * dx + dy * dy); + float keep = Math.min(clamp(distance - inner + 1f), clamp(outer - distance + 1f)); + int color = pixels[y * SIDE + x]; + int alpha = Math.round(((color >>> 24) & 0xFF) * keep); + pixels[y * SIDE + x] = (alpha << 24) | (color & 0x00FFFFFF); + } + } + } + + private static float clamp(float value) { + return value < 0f ? 0f : (value > 1f ? 1f : value); + } +} diff --git a/src/lihont/two/frame/FrameDraw.java b/src/lihont/two/frame/FrameDraw.java index 92c2900..414955a 100644 --- a/src/lihont/two/frame/FrameDraw.java +++ b/src/lihont/two/frame/FrameDraw.java @@ -137,6 +137,13 @@ public final class FrameDraw { private static void drawPart(Canvas canvas, Prepared prepared, int index) { FrameIndex.Part part = prepared.frame.parts.get(index); + if (part.center) { + float side = part.size * prepared.size; + float half = prepared.size / 2f; + DESTINATION.set(half - side / 2f, half - side / 2f, half + side / 2f, half + side / 2f); + canvas.drawBitmap(prepared.bitmaps[index], null, DESTINATION, SPRITE_PAINT); + return; + } float[] point = prepared.outline.point(part.at); float half = prepared.size / 2f; float dx = point[0] - half; diff --git a/src/lihont/two/frame/FrameIndex.java b/src/lihont/two/frame/FrameIndex.java index d197642..d85b8e1 100644 --- a/src/lihont/two/frame/FrameIndex.java +++ b/src/lihont/two/frame/FrameIndex.java @@ -73,7 +73,9 @@ public final class FrameIndex { * One part. `at`: the angle of the outline point (degrees clockwise from the top); `size`: the sprite's width as a part of the * avatar's width; (`ax`, `ay`): the point of the sprite that sits on the outline point, as parts of its width and height; * `turn`: extra turn in degrees, clockwise, on top of "pointing away from the avatar"; `radial`: a shift along that direction - * (positive = outwards) as a part of the avatar's width; `flip`: mirrored; `front`: drawn over the avatar, not behind it. + * (positive = outwards) as a part of the avatar's width; `flip`: mirrored; `front`: drawn over the avatar, not behind it; + * `center`: the sprite sits on the middle of the avatar, upright (`at`, `ax`, `ay`, `turn`, `radial` are then ignored): a picture + * that is a whole frame in itself, such as one a member made. */ public static final class Part { public final Sprite sprite; @@ -85,8 +87,9 @@ public final class FrameIndex { public final float radial; public final boolean flip; public final boolean front; + public final boolean center; - Part(Sprite sprite, float ax, float ay, float at, float size, float turn, float radial, boolean flip, boolean front) { + Part(Sprite sprite, float ax, float ay, float at, float size, float turn, float radial, boolean flip, boolean front, boolean center) { this.sprite = sprite; this.ax = ax; this.ay = ay; @@ -96,6 +99,7 @@ public final class FrameIndex { this.radial = radial; this.flip = flip; this.front = front; + this.center = center; } } @@ -298,8 +302,9 @@ public final class FrameIndex { if (sprite == null || ax == null || ay == null || at == null || size == null || turn == null || radial == null) return null; boolean flip = Boolean.TRUE.equals(raw.get("flip")); boolean front = "front".equals(raw.get("layer")); + boolean center = Boolean.TRUE.equals(raw.get("center")); return new Part(sprite, ax.floatValue(), ay.floatValue(), at.floatValue(), size.floatValue(), turn.floatValue(), - radial.floatValue(), flip, front); + radial.floatValue(), flip, front, center); } private static String string(Map from, String key) { diff --git a/src/lihont/two/frame/FramePreviewView.java b/src/lihont/two/frame/FramePreviewView.java index 71108ca..bea6bcf 100644 --- a/src/lihont/two/frame/FramePreviewView.java +++ b/src/lihont/two/frame/FramePreviewView.java @@ -33,7 +33,7 @@ public final class FramePreviewView extends View { float cy = h / 2f + d * 0.06f; FrameDraw.Prepared prepared = null; if (frameId != null) { - FrameIndex.Frame frame = FrameStore.index(getContext()).frame(frameId); + FrameIndex.Frame frame = FrameStore.frame(getContext(), frameId); if (frame != null) prepared = FrameDraw.prepare(getContext(), frame, ModSettings.AvatarShape.CIRCLE, d, this); } if (prepared != null) FrameDraw.drawBack(canvas, prepared, cx, cy); diff --git a/src/lihont/two/frame/FrameStore.java b/src/lihont/two/frame/FrameStore.java index 0e7cc3a..e7db51b 100644 --- a/src/lihont/two/frame/FrameStore.java +++ b/src/lihont/two/frame/FrameStore.java @@ -70,8 +70,15 @@ public final class FrameStore { return version; } + /** The frame with this id: one of the catalog's, or a picture a member made ("u." and its checksum), or null while it is not on the phone. */ + public static FrameIndex.Frame frame(Context context, String id) { + if (id == null) return null; + return CustomFrames.isCustom(id) ? CustomFrames.frame(context, id) : index(context).frame(id); + } + /** The stored picture of a sprite, or null when it has not been fetched (yet). */ public static File file(Context context, FrameIndex.Sprite sprite) { + if (CustomFrames.isCustom(sprite)) return CustomFrames.file(context, sprite); File file = new File(folder(context), sprite.sha256 + ".png"); return file.isFile() ? file : null; } @@ -116,24 +123,27 @@ public final class FrameStore { running = false; } } - if (changed) { - version++; - MAIN.post(new Runnable() { - @Override public void run() { - List copy; - synchronized (LISTENERS) { - copy = new ArrayList(LISTENERS); - } - for (Runnable listener : copy) listener.run(); - } - }); - } + if (changed) changed(); } }, "lihont-frames"); worker.setDaemon(true); worker.start(); } + /** Something about the frames changed: the pictures held in memory are dropped and the screens that show frames are redrawn. */ + static void changed() { + version++; + MAIN.post(new Runnable() { + @Override public void run() { + List copy; + synchronized (LISTENERS) { + copy = new ArrayList(LISTENERS); + } + for (Runnable listener : copy) listener.run(); + } + }); + } + /** True when something changed (a new catalog or new pictures). */ private static boolean fetch(Context context) throws Exception { List bases = new ArrayList(); @@ -199,13 +209,13 @@ public final class FrameStore { return false; } - private static File folder(Context context) { + static File folder(Context context) { File folder = new File(context.getFilesDir(), "lihont-frames"); if (!folder.isDirectory()) folder.mkdirs(); return folder; } - private static byte[] get(String address, int limit) throws IOException { + static byte[] get(String address, int limit) throws IOException { URL url = new URL(address); if (!"https".equals(url.getProtocol())) throw new IOException("not https"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); @@ -238,7 +248,7 @@ public final class FrameStore { } } - static String sha256(byte[] data) throws IOException { + public static String sha256(byte[] data) throws IOException { try { byte[] digest = MessageDigest.getInstance("SHA-256").digest(data); StringBuilder hex = new StringBuilder(64); diff --git a/src/lihont/two/settings/LihonTSettingsActivity.java b/src/lihont/two/settings/LihonTSettingsActivity.java index c70ca11..b44de7f 100644 --- a/src/lihont/two/settings/LihonTSettingsActivity.java +++ b/src/lihont/two/settings/LihonTSettingsActivity.java @@ -46,13 +46,19 @@ import java.util.Locale; /** Material 3 settings screen for LihonT 2. */ public final class LihonTSettingsActivity extends Activity { - private static final String VERSION_LINE = "LihonT 2.0 · Serena beta 2"; + private static final String VERSION_LINE = "LihonT 2.0 · Serena"; private static final String BASE_LINE = "База TikTok 47.1.3"; private static final String CHANNEL_URL = "https://t.me/lihont"; private static final String SOURCE_URL = "https://git.lihont.space/lihont/LihonT"; private static final String LICENSE_URL = SOURCE_URL + "/src/branch/main/LICENSE"; private static final String CHANGES = - "• Исправление (beta 2): приложение больше не зависало при прокрутке ленты и входе в профиль («Не отвечает»). Причина была в моде: при чтении имён он обращался к самому себе по кругу." + "• LihonT Store: отдельное приложение с каталогом рамок и пузырей чата от людей. Добавляете вещь кнопкой «+», и она появляется в моде (рамка в выборе рамок, пузырь в настройках чата). Свои работы публикуются там же, сначала их проверяют." + + "\n" + + "• Своя рамка из любой картинки (кнопка «Своя рамка» в выборе рамок): фото вырезается в кольцо само. Её видят все с этой версией после проверки." + + "\n" + + "• Пузыри из магазина видят другие с модом на ваших сообщениях. Картинка на двоих: одна на чат, её видите вы оба (Пузыри чата → «Картинка на двоих»)." + + "\n" + + "• Исправлено зависание при прокрутке ленты и входе в профиль («Не отвечает»)." + "\n" + "• Рамки аватарок: рамка повторяет форму аватарки, наборы рамок приходят сами, без обновления мода. Выбранную рамку видят другие с модом.\n" + "• Сохранить аватарку по нику в Галерею (папка LihonT).\n" @@ -233,6 +239,18 @@ public final class LihonTSettingsActivity extends Activity { cardChat.addView(bubbleSlotRow("Общая картинка", "Для всех, у кого нет своей: и для тех, кто написал вам впервые", lihont.two.chat.BubbleStore.GENERAL)); cardChat.addView(Md3.cardDivider(this, palette)); + LinearLayout storeRow = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.ADD_PHOTO, palette.onPrimaryContainer, 8), + "Пузырь из магазина", "То, что вы добавили в LihonT Store. Его увидят другие с модом", Md3.chevron(this, palette), true); + storeRow.setOnClickListener(v -> askStoreBubble()); + cardChat.addView(storeRow); + cardChat.addView(Md3.cardDivider(this, palette)); + LinearLayout pairRow = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.ADD_PHOTO, palette.onPrimaryContainer, 8), + "Картинка на двоих", "Одна на чат, её видите вы оба. Собеседнику нужен мод", Md3.chevron(this, palette), true); + pairRow.setOnClickListener(v -> askPairPerson()); + cardChat.addView(pairRow); + cardChat.addView(Md3.cardDivider(this, palette)); cardChat.addView(bubbleColorRow("Цвет текста: мой", true)); cardChat.addView(Md3.cardDivider(this, palette)); cardChat.addView(bubbleColorRow("Цвет текста: собеседника", false)); @@ -667,6 +685,11 @@ public final class LihonTSettingsActivity extends Activity { } private static final int REQUEST_BUBBLE = 4102; + private static final int REQUEST_FRAME = 4103; + private static final int REQUEST_PAIR = 4104; + private String pairPeer; + private java.util.List libraryPieces = new java.util.ArrayList(); + private String pairPeerName; private String bubbleSlot; private View bubblesSwitchRow() { @@ -1028,7 +1051,7 @@ public final class LihonTSettingsActivity extends Activity { private View frameRow() { String account = lihont.two.account.CurrentAccount.uniqueId(); String id = lihont.two.account.AccountFrames.current(); - lihont.two.frame.FrameIndex.Frame frame = id == null ? null : lihont.two.frame.FrameStore.index(this).frame(id); + lihont.two.frame.FrameIndex.Frame frame = id == null ? null : lihont.two.frame.FrameStore.frame(this, id); lihont.two.frame.FramePreviewView preview = new lihont.two.frame.FramePreviewView(this, frame == null ? null : id, palette.primaryContainer, palette.onPrimaryContainer); preview.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(this, 40), Md3.dp(this, 40))); @@ -1060,6 +1083,10 @@ public final class LihonTSettingsActivity extends Activity { } }; fill.run(); + lihont.two.store.StoreClient.library(this, (pieces, problem) -> { + libraryPieces = pieces; + if (dialog.isShowing()) fill.run(); + }); lihont.two.frame.FrameStore.onChanged(fill); dialog.setOnDismissListener(d -> lihont.two.frame.FrameStore.removeListener(fill)); lihont.two.frame.FrameStore.refresh(this, false); @@ -1087,6 +1114,20 @@ public final class LihonTSettingsActivity extends Activity { List tiles = new ArrayList(); tiles.add(new String[] {null, "Без рамки"}); addFrameTiles(root, tiles, chosen, dialog, uid); + if (chosen != null) lihont.two.frame.CustomFrames.remember(this, uid, chosen); // a frame made before the list existed + java.util.List fromStore = new ArrayList(); + for (lihont.two.store.StoreClient.Piece piece : libraryPieces) if (piece.frame) fromStore.add(new String[] {piece.frameId(), piece.name}); + if (!fromStore.isEmpty()) { + root.addView(Md3.text(this, "Из магазина", Md3.TITLE_MEDIUM, true, palette.primary)); + addFrameTiles(root, fromStore, chosen, dialog, uid); + } + java.util.List own = lihont.two.frame.CustomFrames.mine(this, uid); + if (!own.isEmpty()) { + root.addView(Md3.text(this, "Мои рамки", Md3.TITLE_MEDIUM, true, palette.primary)); + List ownTiles = new ArrayList(); + for (int i = 0; i < own.size(); i++) ownTiles.add(new String[] {own.get(i), "Моя рамка " + (own.size() - i)}); + addFrameTiles(root, ownTiles, chosen, dialog, uid); + } for (lihont.two.frame.FrameIndex.Pack pack : index.packs) { root.addView(Md3.text(this, pack.name, Md3.TITLE_MEDIUM, true, palette.primary)); List rowTiles = new ArrayList(); @@ -1102,8 +1143,19 @@ public final class LihonTSettingsActivity extends Activity { lihont.two.frame.FrameStore.refresh(this, true); new Handler(Looper.getMainLooper()).postDelayed(() -> refresh.setText("Обновить наборы"), 4000L); }); + TextView mine = Md3.textButton(this, palette, "Своя рамка"); + mine.setOnClickListener(v -> { + dialog.dismiss(); + pickFrameImage(); + }); TextView close = Md3.textButton(this, palette, "Закрыть"); close.setOnClickListener(v -> dialog.dismiss()); + // "Своя рамка" is the main action of this screen: it gets a row of its own, so the other two never run out of width + LinearLayout mineRow = new LinearLayout(this); + mineRow.setGravity(Gravity.START); + mineRow.setPadding(0, Md3.dp(this, 8), 0, 0); + mineRow.addView(mine); + root.addView(mineRow); buttons.addView(refresh); buttons.addView(close); root.addView(buttons); @@ -1149,6 +1201,270 @@ public final class LihonTSettingsActivity extends Activity { } } + /** Lists the bubbles of the account's library (LihonT Store) and makes the chosen one the account's bubble. */ + private void askStoreBubble() { + final LinearLayout list = new LinearLayout(this); + list.setOrientation(LinearLayout.VERTICAL); + final TextView wait = Md3.text(this, "Загружаем…", Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + list.addView(wait); + final Dialog[] shown = new Dialog[1]; + ScrollView scroll = new ScrollView(this); + scroll.addView(list, new ScrollView.LayoutParams(-1, -2)); + shown[0] = bubbleDialog("Пузырь из магазина", scroll, "Убрать мой пузырь", () -> { + lihont.two.store.StoreClient.clearBubble(this); + Toast.makeText(this, "Ваш пузырь больше не показывается другим", Toast.LENGTH_LONG).show(); + }); + lihont.two.store.StoreClient.library(this, (pieces, problem) -> { + list.removeAllViews(); + int count = 0; + for (final lihont.two.store.StoreClient.Piece piece : pieces) { + if (piece.frame) continue; + count++; + TextView item = Md3.text(this, piece.name, Md3.BODY_LARGE, false, palette.onSurface); + item.setPadding(Md3.dp(this, 8), Md3.dp(this, 14), Md3.dp(this, 8), Md3.dp(this, 14)); + item.setBackground(Md3.stateLayer(this, Md3.SHAPE_EXTRA_SMALL, Md3.stateLayerColor(palette.onSurface))); + item.setClickable(true); + item.setOnClickListener(v -> { + shown[0].dismiss(); + lihont.two.store.StoreClient.chooseBubble(this, piece, (ok, message) -> Toast.makeText(this, message, Toast.LENGTH_LONG).show()); + }); + list.addView(item); + } + if (count == 0) list.addView(Md3.text(this, problem != null ? problem : "В библиотеке пока нет пузырей. Добавьте их в LihonT Store кнопкой «+».", + Md3.BODY_MEDIUM, false, palette.onSurfaceVariant)); + }); + } + + /** The people whose chats the mod has seen with their account known: a picture can be shared with them. */ + private void askPairPerson() { + LinearLayout list = new LinearLayout(this); + list.setOrientation(LinearLayout.VERTICAL); + final Dialog[] shown = new Dialog[1]; + int count = 0; + for (final String person : lihont.two.chat.BubbleStore.people(this)) { + final String uid = lihont.two.chat.BubbleStore.accountOf(this, person); + if (uid == null) continue; + count++; + TextView item = Md3.text(this, person, Md3.BODY_LARGE, false, palette.onSurface); + item.setPadding(Md3.dp(this, 8), Md3.dp(this, 14), Md3.dp(this, 8), Md3.dp(this, 14)); + item.setBackground(Md3.stateLayer(this, Md3.SHAPE_EXTRA_SMALL, Md3.stateLayerColor(palette.onSurface))); + item.setClickable(true); + item.setOnClickListener(v -> { + shown[0].dismiss(); + pairPeer = uid; + pairPeerName = person; + askPairAction(); + }); + list.addView(item); + } + if (count == 0) { + list.addView(Md3.text(this, "Пока никого. Откройте чат с человеком, и он появится здесь.", Md3.BODY_MEDIUM, + false, palette.onSurfaceVariant)); + } + ScrollView scroll = new ScrollView(this); + scroll.addView(list, new ScrollView.LayoutParams(-1, -2)); + shown[0] = bubbleDialog("Картинка на двоих: с кем чат", scroll, null, null); + } + + private void askPairAction() { + final String peer = pairPeer; + LinearLayout body = new LinearLayout(this); + body.setOrientation(LinearLayout.VERTICAL); + body.addView(Md3.text(this, "Чат с " + pairPeerName + ". Картинку проверят, потом её увидите вы оба.", Md3.BODY_MEDIUM, + false, palette.onSurfaceVariant)); + TextView clear = Md3.textButton(this, palette, "Убрать общую картинку"); + clear.setOnClickListener(v -> lihont.two.avatar.PairPictures.clear(this, peer, + result -> Toast.makeText(this, result.message, Toast.LENGTH_LONG).show())); + body.addView(clear); + bubbleDialog("Картинка на двоих", body, "Выбрать картинку", this::pickPair); + } + + private void pickPair() { + try { + startActivityForResult(IconShortcuts.pickIntent(), REQUEST_PAIR); + } catch (ActivityNotFoundException | SecurityException none) { + Toast.makeText(this, "Не нашлось приложения для выбора фото", Toast.LENGTH_SHORT).show(); + } + } + + /** The chosen picture is made small enough for the service (at most 150 KB as a PNG) and shown before it is sent. */ + private void pairPicked(final Uri uri) { + final String peer = pairPeer; + if (peer == null) return; + new Thread(() -> { + Bitmap picture = null; + byte[] png = null; + try { + picture = decodeScaled(uri, 1024); + for (int side = 512; picture != null && side >= 160 && png == null; side = side * 3 / 4) { + float scale = Math.min(1f, side / (float) Math.max(picture.getWidth(), picture.getHeight())); + Bitmap small = scale >= 1f ? picture : Bitmap.createScaledBitmap(picture, Math.max(3, Math.round(picture.getWidth() * scale)), + Math.max(3, Math.round(picture.getHeight() * scale)), true); + java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + small.compress(Bitmap.CompressFormat.PNG, 100, out); + if (out.size() <= 140 * 1024) { + png = out.toByteArray(); + picture = small; + } + } + } catch (IOException | RuntimeException | OutOfMemoryError unreadable) { + png = null; + } + final byte[] made = png; + final Bitmap shownPicture = picture; + handler.post(() -> { + if (isFinishing()) return; + if (made == null) Toast.makeText(this, "Не удалось подготовить эту картинку", Toast.LENGTH_LONG).show(); + else confirmPair(peer, made, shownPicture); + }); + }, "lihont-pair-make").start(); + } + + private void confirmPair(final String peer, final byte[] png, Bitmap picture) { + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + root.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16)); + root.addView(Md3.text(this, "Картинка на двоих", Md3.HEADLINE_SMALL, false, palette.onSurface)); + ImageView preview = new ImageView(this); + preview.setImageBitmap(picture); + preview.setAdjustViewBounds(true); + LinearLayout.LayoutParams previewParams = new LinearLayout.LayoutParams(-1, Md3.dp(this, 160)); + previewParams.topMargin = Md3.dp(this, 16); + preview.setScaleType(ImageView.ScaleType.FIT_CENTER); + root.addView(preview, previewParams); + TextView note = Md3.text(this, "Вы увидите её сразу. Собеседнику её покажут после проверки, ему нужен мод.", + Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + note.setPadding(0, Md3.dp(this, 12), 0, Md3.dp(this, 8)); + root.addView(note); + LinearLayout buttons = new LinearLayout(this); + buttons.setGravity(Gravity.END); + TextView cancel = Md3.textButton(this, palette, "Отмена"); + cancel.setOnClickListener(v -> dialog.dismiss()); + TextView send = Md3.textButton(this, palette, "Отправить"); + send.setOnClickListener(v -> { + dialog.dismiss(); + lihont.two.avatar.PairPictures.upload(this, peer, png, result -> { + if (result.published || result.code == null) { + Toast.makeText(this, result.message, Toast.LENGTH_LONG).show(); + } else { + openProofDialog("картинку", result.code, retry -> lihont.two.avatar.PairPictures.upload(this, peer, png, retry)); + } + }); + }); + buttons.addView(cancel); + buttons.addView(send); + root.addView(buttons); + dialog.setContentView(root); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.9f); + } + + private void pickFrameImage() { + try { + startActivityForResult(IconShortcuts.pickIntent(), REQUEST_FRAME); + } catch (ActivityNotFoundException | SecurityException none) { + Toast.makeText(this, "Не нашлось приложения для выбора фото", Toast.LENGTH_SHORT).show(); + } + } + + /** A picture was chosen: it becomes a frame (a photo is cut into a ring), and the person sees it before it is sent anywhere. */ + private void framePicked(final Uri uri) { + new Thread(() -> { + byte[] png = null; + String id = null; + try { + Bitmap bitmap = decodeScaled(uri, 1024); + if (bitmap != null) png = lihont.two.frame.CustomFrames.make(bitmap); + if (png != null) id = lihont.two.frame.CustomFrames.save(this, png); + } catch (IOException | RuntimeException | OutOfMemoryError unreadable) { + png = null; + } + final byte[] made = png; + final String frameId = id; + handler.post(() -> { + if (isFinishing()) return; + if (made == null || frameId == null) Toast.makeText(this, "Не удалось сделать рамку из этой картинки", Toast.LENGTH_LONG).show(); + else confirmCustomFrame(made, frameId); + }); + }, "lihont-frame-make").start(); + } + + private Bitmap decodeScaled(Uri uri, int limit) throws IOException { + BitmapFactory.Options bounds = new BitmapFactory.Options(); + bounds.inJustDecodeBounds = true; + try (java.io.InputStream in = getContentResolver().openInputStream(uri)) { + BitmapFactory.decodeStream(in, null, bounds); + } + int sample = 1; + while (bounds.outWidth / (sample * 2) >= limit || bounds.outHeight / (sample * 2) >= limit) sample *= 2; + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inSampleSize = sample; + try (java.io.InputStream in = getContentResolver().openInputStream(uri)) { + return BitmapFactory.decodeStream(in, null, options); + } + } + + private void confirmCustomFrame(final byte[] png, final String frameId) { + final String uid = lihont.two.account.CurrentAccount.uid(); + if (uid == null) { + Toast.makeText(this, "Войдите в TikTok, чтобы сделать рамку", Toast.LENGTH_LONG).show(); + return; + } + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setClipChildren(false); + root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + root.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16)); + root.addView(Md3.text(this, "Своя рамка", Md3.HEADLINE_SMALL, false, palette.onSurface)); + lihont.two.frame.FramePreviewView preview = new lihont.two.frame.FramePreviewView(this, frameId, + palette.secondaryContainer, palette.onSecondaryContainer); + LinearLayout.LayoutParams previewParams = new LinearLayout.LayoutParams(Md3.dp(this, 140), Md3.dp(this, 140)); + previewParams.gravity = Gravity.CENTER_HORIZONTAL; + previewParams.topMargin = Md3.dp(this, 16); + root.addView(preview, previewParams); + TextView note = Md3.text(this, "Картинка станет рамкой, фото вырежется в кольцо. Рамка сразу видна вам, а остальным её покажут после проверки.", + Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + note.setPadding(0, Md3.dp(this, 12), 0, Md3.dp(this, 8)); + root.addView(note); + LinearLayout buttons = new LinearLayout(this); + buttons.setGravity(Gravity.END); + TextView cancel = Md3.textButton(this, palette, "Отмена"); + cancel.setOnClickListener(v -> dialog.dismiss()); + TextView send = Md3.textButton(this, palette, "Использовать"); + send.setOnClickListener(v -> { + dialog.dismiss(); + lihont.two.frame.CustomFrames.remember(this, uid, frameId); + lihont.two.account.AccountFrames.set(this, uid, frameId); + buildScreen(); + lihont.two.avatar.FramePublisher.upload(this, png, "Своя рамка", result -> { + if (result.published) { + Toast.makeText(this, result.message, Toast.LENGTH_LONG).show(); + shareFrame(frameId); + } else if (result.code != null) { + openProofDialog("рамку", result.code, retry -> lihont.two.avatar.FramePublisher.upload(this, png, "Своя рамка", sent -> { + retry.done(sent); + if (sent.published) shareFrame(frameId); + })); + } else { + Toast.makeText(this, result.message, Toast.LENGTH_LONG).show(); + } + }); + }); + buttons.addView(cancel); + buttons.addView(send); + root.addView(buttons); + dialog.setContentView(root); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.9f); + } + /** Publishes the chosen frame for other members; asks for the code in the bio when the account is not proven yet. */ private void shareFrame(final String frameId) { lihont.two.avatar.FramePublisher.publish(this, frameId, result -> { @@ -1607,6 +1923,14 @@ public final class LihonTSettingsActivity extends Activity { @Override protected void onActivityResult(int request, int result, Intent data) { super.onActivityResult(request, result, data); + if (request == REQUEST_PAIR) { + if (result == RESULT_OK && data != null && data.getData() != null) pairPicked(data.getData()); + return; + } + if (request == REQUEST_FRAME) { + if (result == RESULT_OK && data != null && data.getData() != null) framePicked(data.getData()); + return; + } if (request == REQUEST_BUBBLE) { if (result == RESULT_OK && data != null && data.getData() != null) bubblePicked(data.getData()); return; diff --git a/src/lihont/two/store/LoginActivity.java b/src/lihont/two/store/LoginActivity.java new file mode 100644 index 0000000..0afc0a8 --- /dev/null +++ b/src/lihont/two/store/LoginActivity.java @@ -0,0 +1,46 @@ +package lihont.two.store; + +import android.app.Activity; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Bundle; + +import lihont.two.avatar.Installation; +import lihont.two.badge.NicheClaim; + +/** + * The door LihonT Store knocks on: it asks which account is signed in and gets back the public id and username, and the secret of this + * installation (the members service knows the installation as the holder of the account, so the store may act for it). + * + * Nothing is shown. The answer goes only to an app that asked with startActivityForResult, is called "lihonstore.app" and is signed with + * the very key this TikTok is signed with; every other caller gets "cancelled" and learns nothing. + */ +public final class LoginActivity extends Activity { + static final String STORE = "lihonstore.app"; + + @Override protected void onCreate(Bundle state) { + super.onCreate(state); + Intent answer = null; + try { + if (allowed()) answer = reply(); + } catch (Throwable refused) { + answer = null; + } + if (answer != null) setResult(RESULT_OK, answer); + else setResult(RESULT_CANCELED); + finish(); + } + + private boolean allowed() { + String caller = getCallingPackage(); + if (!STORE.equals(caller)) return false; + return getPackageManager().checkSignatures(caller, getPackageName()) == PackageManager.SIGNATURE_MATCH; + } + + private Intent reply() throws Exception { + NicheClaim.Account account = NicheClaim.account(); + if (account == null || account.uid == null || account.uniqueId == null) return null; + return new Intent().putExtra("uid", account.uid).putExtra("unique_id", account.uniqueId) + .putExtra("installation", Installation.secret(getApplicationContext())); + } +} diff --git a/src/lihont/two/store/StoreClient.java b/src/lihont/two/store/StoreClient.java new file mode 100644 index 0000000..7b9de29 --- /dev/null +++ b/src/lihont/two/store/StoreClient.java @@ -0,0 +1,150 @@ +package lihont.two.store; + +import android.content.Context; +import android.graphics.Bitmap; +import android.os.Handler; +import android.os.Looper; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; + +import lihont.two.avatar.Installation; +import lihont.two.badge.MemberClient; +import lihont.two.badge.NicheClaim; +import lihont.two.chat.BubbleStore; + +/** + * What the mod takes from the store's side: the account's library (what it added with "+" in LihonT Store), offered in the frame picker and + * for the chat bubbles. Only the account's own installation may read it; nothing is sent but the numeric id, the public username and + * this installation's secret. + */ +public final class StoreClient { + /** One thing from the library. */ + public static final class Piece { + public final String id; + public final String name; + public final boolean frame; + + Piece(String id, String name, boolean frame) { + this.id = id; + this.name = name; + this.frame = frame; + } + + /** The frame id the avatar hook understands ("u." and the picture's checksum digits). */ + public String frameId() { + return "u." + id; + } + } + + public interface Listener { + void done(List pieces, String problem); + } + + public interface Result { + void done(boolean ok, String message); + } + + private static final Handler MAIN = new Handler(Looper.getMainLooper()); + + private StoreClient() {} + + /** Reads the library in the background; `listener` is called on the main thread (an empty list and a note when it cannot be read). */ + public static void library(final Context context, final Listener listener) { + final NicheClaim.Account account = NicheClaim.account(); + if (account == null) { + listener.done(new ArrayList(), "Войдите в TikTok"); + return; + } + final Context app = context.getApplicationContext() != null ? context.getApplicationContext() : context; + new Thread(new Runnable() { + @Override public void run() { + final List pieces = new ArrayList(); + String problem = null; + try { + JSONObject reply = MemberClient.post("library", new JSONObject().put("uid", account.uid) + .put("installation", Installation.secret(app)).put("unique_id", account.uniqueId)); + JSONArray items = reply.optJSONArray("items"); + for (int i = 0; items != null && i < items.length(); i++) { + JSONObject item = items.optJSONObject(i); + if (item == null || !item.optString("id", "").matches("[0-9a-f]{24}")) continue; + pieces.add(new Piece(item.getString("id"), item.optString("name", "?"), "frame".equals(item.optString("kind")))); + } + } catch (Exception failed) { + String message = failed.getMessage(); + problem = message != null && message.contains("Prove the account") + ? "Откройте LihonT Store и войдите: аккаунт ещё не подтверждён" : "Не удалось прочитать библиотеку"; + } + final String note = problem; + MAIN.post(new Runnable() { + @Override public void run() { + listener.done(pieces, note); + } + }); + } + }, "lihont-store-library").start(); + } + + /** + * Makes a bubble from the library the account's own: its picture becomes "Мои пузыри" on this phone and the choice is published so that + * members with the mod see it on the account's messages. + */ + public static void chooseBubble(final Context context, final Piece piece, final Result result) { + final NicheClaim.Account account = NicheClaim.account(); + if (account == null) { + result.done(false, "Войдите в TikTok"); + return; + } + final Context app = context.getApplicationContext() != null ? context.getApplicationContext() : context; + new Thread(new Runnable() { + @Override public void run() { + boolean ok = false; + String message; + try { + Bitmap picture = lihont.two.avatar.PairPictures.fetchNow(app, piece.id); + if (picture == null) throw new IllegalStateException("picture"); + BubbleStore.put(app, BubbleStore.OWN, picture); + BubbleStore.setEnabled(app, true); + JSONObject reply = MemberClient.post("bubble_choose", new JSONObject().put("uid", account.uid) + .put("installation", Installation.secret(app)).put("unique_id", account.uniqueId).put("id", piece.id)); + if (reply.optBoolean("published", false)) { + ok = true; + message = "Пузырь выбран: его видите вы, а люди с модом увидят его на ваших сообщениях"; + } else { + ok = true; + message = "Пузырь выбран у вас. Чтобы его увидели другие, откройте LihonT Store и войдите (подтверждение аккаунта)"; + } + } catch (Exception failed) { + message = "Не удалось выбрать пузырь"; + } + final boolean done = ok; + final String text = message; + MAIN.post(new Runnable() { + @Override public void run() { + result.done(done, text); + } + }); + } + }, "lihont-store-bubble").start(); + } + + /** Takes the published bubble back (the local picture stays as it is). */ + public static void clearBubble(final Context context) { + final NicheClaim.Account account = NicheClaim.account(); + if (account == null) return; + final Context app = context.getApplicationContext() != null ? context.getApplicationContext() : context; + new Thread(new Runnable() { + @Override public void run() { + try { + MemberClient.post("bubble_choose", new JSONObject().put("uid", account.uid) + .put("installation", Installation.secret(app)).put("unique_id", account.uniqueId).put("id", "none")); + } catch (Exception ignored) { + // nothing was published, or the service is away + } + } + }, "lihont-store-clear").start(); + } +} diff --git a/tests/java/lihont/two/frame/FrameTest.java b/tests/java/lihont/two/frame/FrameTest.java index 9420376..1bc7e11 100644 --- a/tests/java/lihont/two/frame/FrameTest.java +++ b/tests/java/lihont/two/frame/FrameTest.java @@ -18,6 +18,8 @@ public final class FrameTest { case "dropped": dropped(); break; case "ids": ids(); break; case "outline": outline(); break; + case "center": center(); break; + case "cut": cut(); break; default: throw new IllegalArgumentException(scenario); } System.out.println("PASS " + scenario); @@ -160,6 +162,30 @@ public final class FrameTest { check(FrameIndex.parse(mirrors).mirrors.size() == 1, "only the https mirror with a sane address stays"); } + private static void center() { + String part = "{\"file\":\"p/a.png\",\"ax\":0.5,\"ay\":0.5,\"at\":0,\"size\":1.2,\"layer\":\"front\",\"center\":true}"; + FrameIndex.Part read = FrameIndex.parse(catalog(sprite("p/a.png", SHA, 10), frame("f", RING, part))).frame("p.f").parts.get(0); + check(read.center && read.front, "a middle part is read"); + check(!FrameIndex.parse(catalog(sprite("p/a.png", SHA, 10), frame("f", RING, PART))).frame("p.f").parts.get(0).center, "ordinary parts are not centred"); + } + + private static void cut() { + int side = FrameCut.SIDE; + int[] solid = new int[side * side]; + java.util.Arrays.fill(solid, 0xFFCC3322); + check(!FrameCut.seeThroughMiddle(solid), "a solid picture is not a frame yet"); + FrameCut.ring(solid); + check((solid[(side / 2) * side + side / 2] >>> 24) == 0, "the middle is a hole"); + check((solid[0] >>> 24) == 0, "the corner is cut off"); + int edge = Math.round(side / FrameCut.OVERLAY / 2f); + check((solid[(side / 2) * side + (side - 12)] >>> 24) == 255, "the ring itself is kept"); + check((solid[(side / 2) * side + (side / 2 + edge - 8)] >>> 24) == 0, "inside the avatar is clear"); + check(FrameCut.seeThroughMiddle(solid), "a ring is a frame"); + int[] before = solid.clone(); + if (!FrameCut.seeThroughMiddle(solid)) FrameCut.ring(solid); + check(java.util.Arrays.equals(before, solid), "a frame is left as it is"); + } + private static void outline() { int n = 720; float[] xs = new float[n]; diff --git a/tests/test_catalog.py b/tests/test_catalog.py new file mode 100644 index 0000000..bf874c6 --- /dev/null +++ b/tests/test_catalog.py @@ -0,0 +1,245 @@ +import base64 +import importlib.util +import io +import tempfile +import unittest +from pathlib import Path + +from PIL import Image + +ROOT = Path(__file__).resolve().parents[1] / "services" / "members" +SPEC = importlib.util.spec_from_file_location("members_server", ROOT / "server.py") +server = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(server) + +UID = "6812345678901234" +OTHER = "6899999999999999" +INSTALL_A = "a" * 64 +INSTALL_B = "b" * 64 + + +def picture(shade, size=(120, 80)): + out = io.BytesIO() + Image.new("RGBA", size, (shade, 40, 90, 255)).save(out, "PNG") + return base64.b64encode(out.getvalue()).decode("ascii") + + +class CatalogTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.now = 1_790_000_000 + self.who = UID + self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now, + fetcher=lambda unique_id: (self.who, self.registry.code(self.who))) + self.cat = self.registry.catalog + + def publish(self, kind="frame", shade=10, name="Венок", description="Из веток", uid=UID, installation=INSTALL_A): + self.who = uid + return self.cat.call("publish", {"uid": uid, "installation": installation, "unique_id": "someone", "kind": kind, + "name": name, "description": description, "png": picture(shade)}) + + def approve(self, art_id): + self.registry.art_decide(art_id, "approved") + + def listing(self, **payload): + return self.cat.call("catalog", payload) + + def test_a_published_item_is_not_listed_until_approved(self): + reply = self.publish() + self.assertEqual("new", reply["status"]) + self.assertEqual([], self.listing()["items"]) + self.approve(reply["id"]) + items = self.listing()["items"] + self.assertEqual(1, len(items)) + self.assertEqual(("frame", "Венок", "Из веток", UID), (items[0]["kind"], items[0]["name"], items[0]["description"], items[0]["author"]["uid"])) + self.assertEqual("someone", items[0]["author"]["name"]) + + def test_the_picture_is_remade_by_kind(self): + frame = self.registry.art_bytes(self.publish("frame", 1)["id"], approved_only=False) + self.who = UID + wide = self.cat.call("publish", {"uid": UID, "installation": INSTALL_A, "unique_id": "someone", "kind": "bubble", + "name": "B", "png": picture(2, (1024, 683))}) + bubble = self.registry.art_bytes(wide["id"], approved_only=False) + small = self.registry.art_bytes(self.publish("bubble", 3)["id"], approved_only=False) + self.assertEqual((256, 256), Image.open(io.BytesIO(frame)).size) + self.assertEqual((512, 342), Image.open(io.BytesIO(bubble)).size) + self.assertEqual((120, 80), Image.open(io.BytesIO(small)).size) # never enlarged + + def test_newest_first_with_a_cursor_and_kind_filter(self): + ids = [] + for shade in range(5): + self.now += 10 + self.registry.art_decide(self.publish("frame" if shade % 2 == 0 else "bubble", shade * 20)["id"], "approved") + ids.append(self.registry.catalog.listing({"limit": 1})["items"][0]["id"]) + everything = self.listing(limit=2) + self.assertEqual([ids[4], ids[3]], [i["id"] for i in everything["items"]]) + rest = self.listing(limit=30, cursor=everything["next"]) + self.assertEqual([ids[2], ids[1], ids[0]], [i["id"] for i in rest["items"]]) + self.assertIsNone(rest["next"]) + self.assertEqual({"frame"}, {i["kind"] for i in self.listing(kind="frame")["items"]}) + with self.assertRaises(ValueError): + self.listing(kind="sticker") + with self.assertRaises(ValueError): + self.listing(cursor="nonsense") + + def test_item_and_profile(self): + first = self.publish("frame", 5)["id"] + self.approve(first) + self.now += 5 + second = self.publish("bubble", 90, name="Облако")["id"] + self.approve(second) + self.assertEqual("Венок", self.cat.call("item", {"id": first})["item"]["name"]) + profile = self.cat.call("profile", {"uid": UID}) + self.assertEqual([second, first], [i["id"] for i in profile["items"]]) + self.assertEqual("someone", profile["name"]) + self.assertEqual(1, profile["totals"]["frame"]["count"]) + with self.assertRaises(ValueError): + self.cat.call("item", {"id": "0" * 24}) + with self.assertRaises(ValueError): + self.cat.call("profile", {"uid": "12"}) + + def test_a_rejected_or_pending_item_is_never_shown_or_installed(self): + art = self.publish()["id"] + with self.assertRaises(ValueError): + self.cat.call("install", {"installation": INSTALL_B, "id": art}) + self.registry.art_decide(art, "rejected", "ai: nudity") + self.assertEqual([], self.listing()["items"]) + self.assertEqual({"items": []}, {"items": self.cat.call("profile", {"uid": UID})["items"]}) + + def test_install_counts_once_per_installation(self): + art = self.publish()["id"] + self.approve(art) + self.assertEqual(1, self.cat.call("install", {"installation": INSTALL_A, "id": art})["installs"]) + self.assertEqual(1, self.cat.call("install", {"installation": INSTALL_A, "id": art})["installs"]) + self.assertEqual(2, self.cat.call("install", {"installation": INSTALL_B, "id": art})["installs"]) + self.assertEqual(2, self.listing()["items"][0]["installs"]) + with self.assertRaises(ValueError): + self.cat.call("install", {"installation": "short", "id": art}) + + def test_mine_shows_every_state_and_the_reason_of_a_refusal(self): + art = self.publish()["id"] + self.registry.art_decide(art, "rejected", "ai: nudity") + mine = self.cat.call("mine", {"uid": UID, "installation": INSTALL_A})["items"] + self.assertEqual(("rejected", "ai: nudity", True), (mine[0]["status"], mine[0]["reason"], mine[0]["listed"])) + with self.assertRaises(ValueError): + self.cat.call("mine", {"uid": UID, "installation": INSTALL_B}) + with self.assertRaises(ValueError): + self.cat.call("mine", {"uid": OTHER, "installation": INSTALL_A}) + + def test_unpublish_is_the_authors_alone(self): + art = self.publish()["id"] + self.approve(art) + self.who = OTHER + self.registry.shape(OTHER, INSTALL_B, "flower", "peer") + with self.assertRaises(ValueError): + self.cat.call("unpublish", {"uid": OTHER, "installation": INSTALL_B, "id": art}) + self.assertEqual(1, len(self.listing()["items"])) + self.cat.call("unpublish", {"uid": UID, "installation": INSTALL_A, "id": art}) + self.assertEqual([], self.listing()["items"]) + + def test_a_blocked_author_vanishes(self): + self.approve(self.publish()["id"]) + with self.registry.connect() as db: + db.execute("INSERT INTO blocked(uid) VALUES(?)", (UID,)) + self.assertEqual([], self.listing()["items"]) + + def test_listing_an_old_private_picture_judges_it_again(self): + private = self.registry.frame_upload(UID, INSTALL_A, "someone", "Своя", picture(33)) + art = private["id"][2:] + self.approve(art) + self.who = UID + again = self.cat.call("publish", {"uid": UID, "installation": INSTALL_A, "kind": "frame", "name": "Новое", + "description": "d", "png": picture(33)}) + self.assertEqual(art, again["id"]) + self.assertEqual("new", again["status"]) + self.assertEqual([], self.listing()["items"]) + + def test_bad_publish_requests(self): + self.who = UID + for payload in ({"kind": "sticker"}, {"kind": "frame", "png": "###"}, {"kind": "frame", "uid": "1"}): + with self.assertRaises(ValueError): + self.cat.call("publish", dict({"uid": UID, "installation": INSTALL_A, "unique_id": "someone", "name": "x"}, **payload)) + + def test_anyone_may_wear_a_catalog_frame_but_not_a_pending_one(self): + art = self.publish("frame", 3)["id"] + self.who = OTHER + self.registry.shape(OTHER, INSTALL_B, "flower", "peer") + with self.assertRaises(ValueError): + self.registry.avatar_frame(OTHER, INSTALL_B, "u." + art) + self.approve(art) + self.assertTrue(self.registry.avatar_frame(OTHER, INSTALL_B, "u." + art)["published"]) + self.assertEqual({OTHER: "u." + art}, self.registry.lookup([OTHER])["avatar_frames"]) + + def test_bubbles_are_chosen_and_seen_by_others_once_approved(self): + art = self.publish("bubble", 77)["id"] + self.cat.call("bubble_choose", {"uid": UID, "installation": INSTALL_A, "id": art, "unique_id": "someone"}) + self.assertEqual({}, self.registry.lookup([UID])["bubbles"]) + self.approve(art) + self.assertEqual({UID: art}, self.registry.lookup([UID, OTHER])["bubbles"]) + self.who = OTHER + self.registry.shape(OTHER, INSTALL_B, "flower", "peer") + self.assertTrue(self.cat.call("bubble_choose", {"uid": OTHER, "installation": INSTALL_B, "id": art})["published"]) + self.assertEqual({UID: art, OTHER: art}, self.registry.lookup([UID, OTHER])["bubbles"]) + self.cat.call("bubble_choose", {"uid": OTHER, "installation": INSTALL_B, "id": "none"}) + self.assertEqual({UID: art}, self.registry.lookup([UID, OTHER])["bubbles"]) + + def test_a_frame_cannot_be_chosen_as_a_bubble_or_the_reverse(self): + frame = self.publish("frame", 8)["id"] + with self.assertRaises(ValueError): + self.cat.call("bubble_choose", {"uid": UID, "installation": INSTALL_A, "id": frame, "unique_id": "someone"}) + bubble = self.publish("bubble", 9)["id"] + with self.assertRaises(ValueError): + self.registry.avatar_frame(UID, INSTALL_A, "u." + bubble) + + +class LibraryTest(unittest.TestCase): + """The "+" of the store: a library per account, filled by the store and read by the mod.""" + + setUp = CatalogTest.setUp + publish = CatalogTest.publish + approve = CatalogTest.approve + + def test_prove_binds_an_installation_once(self): + self.who = UID + self.registry.fetcher = lambda unique_id: (UID, "") + self.assertEqual("code_missing", self.cat.call("prove", {"uid": UID, "installation": INSTALL_A, "unique_id": "someone"})["reason"]) + self.registry.fetcher = lambda unique_id: (UID, self.registry.code(UID)) + self.assertTrue(self.cat.call("prove", {"uid": UID, "installation": INSTALL_A, "unique_id": "someone"})["published"]) + self.registry.fetcher = lambda unique_id: (_ for _ in ()).throw(AssertionError("the profile is read only once")) + self.assertTrue(self.cat.call("prove", {"uid": UID, "installation": INSTALL_A})["published"]) + + def test_add_list_remove(self): + art = self.publish("frame", 12)["id"] + self.approve(art) + self.who = OTHER + self.registry.fetcher = lambda unique_id: (OTHER, self.registry.code(OTHER)) + self.cat.call("prove", {"uid": OTHER, "installation": INSTALL_B, "unique_id": "peer"}) + self.assertEqual({"items": []}, self.cat.call("library", {"uid": OTHER, "installation": INSTALL_B})) + self.assertEqual(1, self.cat.call("library_add", {"uid": OTHER, "installation": INSTALL_B, "id": art})["installs"]) + self.assertEqual(1, self.cat.call("library_add", {"uid": OTHER, "installation": INSTALL_B, "id": art})["installs"]) + items = self.cat.call("library", {"uid": OTHER, "installation": INSTALL_B})["items"] + self.assertEqual([art], [i["id"] for i in items]) + self.cat.call("library_remove", {"uid": OTHER, "installation": INSTALL_B, "id": art}) + self.assertEqual([], self.cat.call("library", {"uid": OTHER, "installation": INSTALL_B})["items"]) + + def test_the_library_needs_the_proven_installation_and_an_approved_item(self): + art = self.publish("frame", 13)["id"] + with self.assertRaises(ValueError): + self.cat.call("library_add", {"uid": UID, "installation": INSTALL_A, "id": art}) # not approved yet + self.approve(art) + with self.assertRaises(ValueError): + self.cat.call("library_add", {"uid": UID, "installation": INSTALL_B, "id": art}) # another installation + with self.assertRaises(ValueError): + self.cat.call("library", {"uid": UID, "installation": INSTALL_B}) + + def test_an_item_taken_off_the_catalog_leaves_the_library(self): + art = self.publish("bubble", 14)["id"] + self.approve(art) + self.cat.call("library_add", {"uid": UID, "installation": INSTALL_A, "id": art}) + self.cat.call("unpublish", {"uid": UID, "installation": INSTALL_A, "id": art}) + self.assertEqual([], self.cat.call("library", {"uid": UID, "installation": INSTALL_A})["items"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_community_frames.py b/tests/test_community_frames.py new file mode 100644 index 0000000..5826605 --- /dev/null +++ b/tests/test_community_frames.py @@ -0,0 +1,231 @@ +import base64 +import importlib.util +import io +import tempfile +import unittest +from pathlib import Path + +from PIL import Image + +ROOT = Path(__file__).resolve().parents[1] / "services" / "members" +SPEC = importlib.util.spec_from_file_location("members_server", ROOT / "server.py") +server = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(server) +community = server.community + +UID = "6812345678901234" +OTHER = "6899999999999999" +INSTALLATION = "a" * 64 + + +def picture(width=300, height=200, color=(200, 30, 30, 255), fmt="PNG"): + out = io.BytesIO() + Image.new("RGBA" if fmt == "PNG" else "RGB", (width, height), color if fmt == "PNG" else color[:3]).save(out, fmt) + return out.getvalue() + + +def encoded(data): + return base64.b64encode(data).decode("ascii") + + +class NormalizeTest(unittest.TestCase): + def test_square_crop_and_size(self): + png = community.normalize_png(picture(300, 200), 256, square=True) + image = Image.open(io.BytesIO(png)) + self.assertEqual((256, 256), image.size) + self.assertEqual("PNG", image.format) + + def test_a_jpeg_is_remade_as_png(self): + png = community.normalize_png(picture(100, 100, fmt="JPEG"), 256, square=True) + self.assertTrue(png.startswith(b"\x89PNG")) + + def test_metadata_does_not_survive(self): + source = io.BytesIO() + info = Image.new("RGBA", (64, 64), (1, 2, 3, 255)) + from PIL.PngImagePlugin import PngInfo + + meta = PngInfo() + meta.add_text("secret", "location 55.7,37.6") + info.save(source, "PNG", pnginfo=meta) + self.assertIn(b"secret", source.getvalue()) + self.assertNotIn(b"secret", community.normalize_png(source.getvalue(), 256, square=True)) + + def test_rubbish_and_oversize_are_refused(self): + for bad in (b"", b"not a picture", b"\x89PNG\r\n\x1a\n" + b"\x00" * 50, b"x" * (community.MAX_UPLOAD + 1)): + with self.assertRaises(ValueError): + community.normalize_png(bad, 256, square=True) + + def test_a_picture_with_too_many_pixels_is_refused(self): + huge = io.BytesIO() + Image.new("L", (5000, 5000), 0).save(huge, "PNG") + with self.assertRaises(ValueError): + community.normalize_png(huge.getvalue(), 256, square=True) + + def test_names_are_cleaned(self): + self.assertEqual("Моя рамка", community.clean_name("\n\t ", "Моя рамка")) + self.assertEqual("a b", community.clean_name("a\n b\x00")) + self.assertEqual(30, len(community.clean_name("x" * 100))) + + +class UploadTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.now = 1_790_000_000 + self.bio = "" + self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now, + fetcher=lambda unique_id: (UID, self.bio)) + + def upload(self, data=None, name="Моя", uid=UID, installation=INSTALLATION): + return self.registry.frame_upload(uid, installation, "someone", name, encoded(data or picture())) + + def prove(self): + self.bio = self.registry.code(UID) + + def test_needs_the_code_in_the_bio_first(self): + self.assertEqual("code_missing", self.upload()["reason"]) + self.assertEqual({}, self.registry.art_counts()) + + def test_upload_waits_for_review_and_is_not_shown(self): + self.prove() + reply = self.upload() + self.assertTrue(reply["published"]) + self.assertEqual("new", reply["status"]) + art_id = reply["id"][2:] + self.assertTrue(reply["id"].startswith("u.")) + self.assertIsNone(self.registry.art_bytes(art_id)) + self.assertTrue(self.registry.avatar_frame(UID, INSTALLATION, reply["id"])["published"]) + self.assertEqual({}, self.registry.lookup([UID])["avatar_frames"]) + + def test_approval_shows_the_frame_to_others(self): + self.prove() + frame = self.upload()["id"] + self.registry.avatar_frame(UID, INSTALLATION, frame) + self.registry.art_decide(frame[2:], "approved") + self.assertEqual({UID: frame}, self.registry.lookup([OTHER, UID])["avatar_frames"]) + data = self.registry.art_bytes(frame[2:]) + self.assertEqual((256, 256), Image.open(io.BytesIO(data)).size) + + def test_rejection_hides_and_blocks_choosing(self): + self.prove() + frame = self.upload()["id"] + self.registry.avatar_frame(UID, INSTALLATION, frame) + self.registry.art_decide(frame[2:], "rejected", "no") + self.assertEqual({}, self.registry.lookup([UID])["avatar_frames"]) + self.assertIsNone(self.registry.art_bytes(frame[2:])) + with self.assertRaises(ValueError): + self.registry.avatar_frame(UID, INSTALLATION, frame) + + def test_someone_elses_or_invented_frames_cannot_be_chosen(self): + self.prove() + frame = self.upload()["id"] + self.registry.art_decide(frame[2:], "approved") + self.registry.avatar_frame(UID, INSTALLATION, "none") + other = "b" * 64 + self.registry.fetcher = lambda unique_id: (OTHER, self.registry.code(OTHER)) + with self.assertRaises(ValueError): + self.registry.avatar_frame(OTHER, other, frame, "someone") + with self.assertRaises(ValueError): + self.registry.avatar_frame(UID, INSTALLATION, "u." + "0" * 24) + + def test_same_picture_twice_is_one_row_and_another_account_cannot_claim_it(self): + self.prove() + first = self.upload() + again = self.upload() + self.assertEqual(first["id"], again["id"]) + self.assertEqual({"new": 1}, self.registry.art_counts()) + self.registry.fetcher = lambda unique_id: (OTHER, self.registry.code(OTHER)) + with self.assertRaises(ValueError): + self.upload(uid=OTHER, installation="b" * 64) + + def test_limits_per_account(self): + self.prove() + for shade in range(3): + self.upload(picture(color=(shade * 40, 0, 0, 255))) + with self.assertRaises(ValueError): + self.upload(picture(color=(0, 200, 0, 255))) + + def test_bad_payloads(self): + self.prove() + with self.assertRaises(ValueError): + self.registry.frame_upload(UID, INSTALLATION, "someone", "x", "***not base64***") + with self.assertRaises(ValueError): + self.registry.frame_upload(UID, INSTALLATION, "someone", "x", encoded(b"hello")) + with self.assertRaises(ValueError): + self.registry.frame_upload("12", INSTALLATION, "someone", "x", encoded(picture())) + + def test_pending_review_order(self): + self.prove() + first = self.upload(picture(color=(1, 1, 1, 255)))["id"][2:] + self.now += 5 + second = self.upload(picture(color=(9, 9, 9, 255)))["id"][2:] + self.assertEqual([first, second], [a["id"] for a in self.registry.art_in_state("new")]) + + +class ChatPictureTest(unittest.TestCase): + """One picture for the chat between two accounts: set by either, shown to both once approved, to nobody else.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.now = 1_790_000_000 + self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now, + fetcher=lambda unique_id: (self.who, self.registry.code(self.who))) + self.who = UID + self.peer_install = "b" * 64 + + def prove_peer(self): + self.who = OTHER + self.registry.shape(OTHER, self.peer_install, "flower", "peer") + self.who = UID + + def test_the_picture_keeps_its_shape_and_size(self): + reply = self.registry.bubble_upload(UID, INSTALLATION, "someone", OTHER, "Мы", encoded(picture(900, 300))) + self.assertEqual("new", reply["status"]) + data = self.registry.art_bytes(reply["id"], approved_only=False) + self.assertEqual((512, 171), Image.open(io.BytesIO(data)).size) + + def test_it_waits_for_approval_then_both_see_it(self): + art = self.registry.bubble_upload(UID, INSTALLATION, "someone", OTHER, "Мы", encoded(picture()))["id"] + self.prove_peer() + self.assertEqual({"id": None}, self.registry.pair_lookup(UID, INSTALLATION, OTHER)) + self.registry.art_decide(art, "approved") + self.assertEqual({"id": art}, self.registry.pair_lookup(UID, INSTALLATION, OTHER)) + self.assertEqual({"id": art}, self.registry.pair_lookup(OTHER, self.peer_install, UID)) + + def test_a_stranger_and_an_unproven_caller_see_nothing(self): + art = self.registry.bubble_upload(UID, INSTALLATION, "someone", OTHER, "Мы", encoded(picture()))["id"] + self.registry.art_decide(art, "approved") + self.assertEqual({"id": None}, self.registry.pair_lookup(OTHER, self.peer_install, UID)) + stranger = "6877777777777777" + self.registry.shape(UID, INSTALLATION, "flower", "someone") + self.assertEqual({"id": None}, self.registry.pair_lookup(UID, INSTALLATION, stranger)) + self.assertEqual({"id": None}, self.registry.pair_lookup(UID, "c" * 64, OTHER)) + + def test_the_proof_is_needed_to_set_it(self): + self.registry.fetcher = lambda unique_id: (UID, "") + self.assertEqual("code_missing", self.registry.bubble_upload(UID, INSTALLATION, "someone", OTHER, "Мы", encoded(picture()))["reason"]) + + def test_you_cannot_pair_with_yourself_or_a_junk_id(self): + for peer in (UID, "12", None): + with self.assertRaises(ValueError): + self.registry.bubble_upload(UID, INSTALLATION, "someone", peer, "Мы", encoded(picture())) + + def test_either_side_can_clear_and_a_rejected_picture_is_not_served(self): + art = self.registry.bubble_upload(UID, INSTALLATION, "someone", OTHER, "Мы", encoded(picture()))["id"] + self.registry.art_decide(art, "approved") + self.prove_peer() + self.registry.pair_clear(OTHER, self.peer_install, UID) + self.assertEqual({"id": None}, self.registry.pair_lookup(UID, INSTALLATION, OTHER)) + again = self.registry.bubble_upload(UID, INSTALLATION, "someone", OTHER, "Мы", encoded(picture(color=(9, 9, 200, 255))))["id"] + self.registry.art_decide(again, "rejected") + self.assertEqual({"id": None}, self.registry.pair_lookup(UID, INSTALLATION, OTHER)) + + def test_a_frame_and_a_chat_picture_are_not_interchangeable(self): + art = self.registry.bubble_upload(UID, INSTALLATION, "someone", OTHER, "Мы", encoded(picture()))["id"] + with self.assertRaises(ValueError): + self.registry.avatar_frame(UID, INSTALLATION, "u." + art) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_frames.py b/tests/test_frames.py index 50ae161..e15feac 100644 --- a/tests/test_frames.py +++ b/tests/test_frames.py @@ -16,6 +16,7 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SOURCES = [ROOT / "src" / "lihont" / "two" / "frame" / "FrameIndex.java", ROOT / "src" / "lihont" / "two" / "frame" / "Outline.java", + ROOT / "src" / "lihont" / "two" / "frame" / "FrameCut.java", ROOT / "src" / "lihont" / "two" / "plugin" / "Json.java", ROOT / "src" / "lihont" / "two" / "plugin" / "LtpException.java"] HARNESS = ROOT / "tests" / "java" / "lihont" / "two" / "frame" / "FrameTest.java" @@ -59,6 +60,12 @@ class FrameJavaTest(unittest.TestCase): def test_the_outline_geometry(self): self.scenario("outline") + def test_a_part_can_sit_on_the_middle(self): + self.scenario("center") + + def test_pictures_become_frames(self): + self.scenario("cut") + class CatalogBuilderTest(unittest.TestCase): def test_the_catalog_is_up_to_date(self): diff --git a/tests/test_manifest_activity.py b/tests/test_manifest_activity.py index 7887990..a2e0ef0 100644 --- a/tests/test_manifest_activity.py +++ b/tests/test_manifest_activity.py @@ -35,6 +35,15 @@ class ManifestActivityTest(unittest.TestCase): reparsed = Axml.parse(xml.build()) self.assertTrue(has_activity(reparsed, name)) + def test_the_store_login_activity_is_exported_without_a_window(self): + xml = self._manifest() + name = 'lihont.two.store.LoginActivity' + add_activity(xml, name, 'LihonT Store', 0x01030055, exported=True) + reparsed = Axml.parse(xml.build()) + node = next(n for n in reparsed.elements('activity') if reparsed.attr_string(n, 'name') == name) + self.assertNotEqual(0, reparsed.attr(node, 'exported').data) + self.assertEqual(0x01030055, reparsed.attr(node, 'theme').data) + def test_launcher_activity_must_explicitly_be_exported(self): xml = self._manifest() with self.assertRaises(ManifestError):