diff --git a/frames/index.json b/frames/index.json index d05832f..f04b38d 100644 --- a/frames/index.json +++ b/frames/index.json @@ -576,6 +576,433 @@ ] } ] + }, + { + "id": "winter", + "name": "Зима", + "version": 1, + "sprites": [ + { + "file": "winter/antler.png", + "sha256": "09e6180856063a86239e3a9aaa3f77490cf70678ea617f3a2e23e7ca556cbb71", + "bytes": 33737, + "w": 220, + "h": 280 + }, + { + "file": "winter/snowflake.png", + "sha256": "966f7cf2aa3b7f17696fedc14ba6c7350a743bce297654803e2f0add0623bc52", + "bytes": 42677, + "w": 160, + "h": 160 + }, + { + "file": "winter/bulb-red.png", + "sha256": "8c11888854b3abc015168b9382d32dcb7262b3e5e797cd2893c2ad3d2a9eab7d", + "bytes": 7116, + "w": 80, + "h": 124 + }, + { + "file": "winter/bulb-yellow.png", + "sha256": "33921a23b771d044c452bc329ff277101afce72f16e11ab38dc5ddad9c09d20d", + "bytes": 7377, + "w": 80, + "h": 124 + }, + { + "file": "winter/bulb-blue.png", + "sha256": "352cc6b0430ce90a9db8b23367a191c4825e50d368a39616df5bf1786f359535", + "bytes": 7278, + "w": 80, + "h": 124 + }, + { + "file": "winter/bulb-green.png", + "sha256": "2cbd576506435145579b64df4c9263f8fc244ddfa8c6d72d307cddff8c8c6e7b", + "bytes": 7207, + "w": 80, + "h": 124 + }, + { + "file": "winter/holly-leaf.png", + "sha256": "994fb074e985366c94158fb5a401daf038389e20ab5683065874922681ae4fc2", + "bytes": 13558, + "w": 190, + "h": 130 + }, + { + "file": "winter/berries.png", + "sha256": "990b73dfae9abae11109d09bbdd066088015d21f7ea6b500d31aec986e35daca", + "bytes": 10046, + "w": 120, + "h": 100 + } + ], + "frames": [ + { + "id": "deer", + "name": "Олень", + "ring": { + "width": 0.045, + "line": 0.014, + "fill": [ + "#c8935a", + "#7a4a22" + ], + "ink": "#3e2210" + }, + "parts": [ + { + "file": "winter/antler.png", + "ax": 0.5, + "ay": 0.93, + "at": -36, + "size": 0.4, + "turn": -10 + }, + { + "file": "winter/antler.png", + "ax": 0.5, + "ay": 0.93, + "at": 36, + "size": 0.4, + "turn": 10, + "flip": true + } + ] + }, + { + "id": "snow", + "name": "Снежинки", + "ring": { + "width": 0.045, + "line": 0.014, + "fill": [ + "#f4fbff", + "#a8d4f5" + ], + "ink": "#46709a" + }, + "parts": [ + { + "file": "winter/snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": -150, + "size": 0.27, + "turn": -30, + "radial": 0.045 + }, + { + "file": "winter/snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": -112, + "size": 0.2, + "turn": -13, + "radial": 0.045 + }, + { + "file": "winter/snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": -74, + "size": 0.27, + "turn": 4, + "radial": 0.045 + }, + { + "file": "winter/snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": -36, + "size": 0.2, + "turn": 21, + "radial": 0.045 + }, + { + "file": "winter/snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": 2, + "size": 0.27, + "turn": -22, + "radial": 0.045 + }, + { + "file": "winter/snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": 40, + "size": 0.2, + "turn": -5, + "radial": 0.045 + }, + { + "file": "winter/snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": 78, + "size": 0.27, + "turn": 12, + "radial": 0.045 + }, + { + "file": "winter/snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": 116, + "size": 0.2, + "turn": 29, + "radial": 0.045 + }, + { + "file": "winter/snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": 154, + "size": 0.27, + "turn": -14, + "radial": 0.045 + }, + { + "file": "winter/snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": 192, + "size": 0.2, + "turn": 3, + "radial": 0.045 + } + ] + }, + { + "id": "garland", + "name": "Гирлянда", + "ring": { + "width": 0.035, + "line": 0.012, + "fill": [ + "#2e8b57", + "#14532d" + ], + "ink": "#0a3320" + }, + "parts": [ + { + "file": "winter/bulb-red.png", + "ax": 0.5, + "ay": 0.1, + "at": -168, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-yellow.png", + "ax": 0.5, + "ay": 0.1, + "at": -144, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-blue.png", + "ax": 0.5, + "ay": 0.1, + "at": -120, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-green.png", + "ax": 0.5, + "ay": 0.1, + "at": -96, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-red.png", + "ax": 0.5, + "ay": 0.1, + "at": -72, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-yellow.png", + "ax": 0.5, + "ay": 0.1, + "at": -48, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-blue.png", + "ax": 0.5, + "ay": 0.1, + "at": -24, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-green.png", + "ax": 0.5, + "ay": 0.1, + "at": 0, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-red.png", + "ax": 0.5, + "ay": 0.1, + "at": 24, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-yellow.png", + "ax": 0.5, + "ay": 0.1, + "at": 48, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-blue.png", + "ax": 0.5, + "ay": 0.1, + "at": 72, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-green.png", + "ax": 0.5, + "ay": 0.1, + "at": 96, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-red.png", + "ax": 0.5, + "ay": 0.1, + "at": 120, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-yellow.png", + "ax": 0.5, + "ay": 0.1, + "at": 144, + "size": 0.12, + "turn": 180 + }, + { + "file": "winter/bulb-blue.png", + "ax": 0.5, + "ay": 0.1, + "at": 168, + "size": 0.12, + "turn": 180 + } + ] + }, + { + "id": "holly", + "name": "Омела", + "ring": { + "width": 0.05, + "line": 0.014, + "fill": [ + "#3cb371", + "#1d6b3e" + ], + "ink": "#0a3c20" + }, + "parts": [ + { + "file": "winter/holly-leaf.png", + "ax": 0.06, + "ay": 0.5, + "at": 35, + "size": 0.36, + "turn": -116 + }, + { + "file": "winter/holly-leaf.png", + "ax": 0.06, + "ay": 0.5, + "at": 35, + "size": 0.36, + "turn": -64 + }, + { + "file": "winter/berries.png", + "ax": 0.5, + "ay": 0.55, + "at": 35, + "size": 0.17, + "radial": 0.015, + "layer": "front" + }, + { + "file": "winter/holly-leaf.png", + "ax": 0.06, + "ay": 0.5, + "at": 155, + "size": 0.36, + "turn": -116 + }, + { + "file": "winter/holly-leaf.png", + "ax": 0.06, + "ay": 0.5, + "at": 155, + "size": 0.36, + "turn": -64 + }, + { + "file": "winter/berries.png", + "ax": 0.5, + "ay": 0.55, + "at": 155, + "size": 0.17, + "radial": 0.015, + "layer": "front" + }, + { + "file": "winter/holly-leaf.png", + "ax": 0.06, + "ay": 0.5, + "at": 275, + "size": 0.36, + "turn": -116 + }, + { + "file": "winter/holly-leaf.png", + "ax": 0.06, + "ay": 0.5, + "at": 275, + "size": 0.36, + "turn": -64 + }, + { + "file": "winter/berries.png", + "ax": 0.5, + "ay": 0.55, + "at": 275, + "size": 0.17, + "radial": 0.015, + "layer": "front" + } + ] + } + ] } ] } diff --git a/frames/winter/antler.png b/frames/winter/antler.png new file mode 100644 index 0000000..8927075 Binary files /dev/null and b/frames/winter/antler.png differ diff --git a/frames/winter/berries.png b/frames/winter/berries.png new file mode 100644 index 0000000..84b357d Binary files /dev/null and b/frames/winter/berries.png differ diff --git a/frames/winter/bulb-blue.png b/frames/winter/bulb-blue.png new file mode 100644 index 0000000..8631b38 Binary files /dev/null and b/frames/winter/bulb-blue.png differ diff --git a/frames/winter/bulb-green.png b/frames/winter/bulb-green.png new file mode 100644 index 0000000..ba7f708 Binary files /dev/null and b/frames/winter/bulb-green.png differ diff --git a/frames/winter/bulb-red.png b/frames/winter/bulb-red.png new file mode 100644 index 0000000..62ac882 Binary files /dev/null and b/frames/winter/bulb-red.png differ diff --git a/frames/winter/bulb-yellow.png b/frames/winter/bulb-yellow.png new file mode 100644 index 0000000..9aab3cf Binary files /dev/null and b/frames/winter/bulb-yellow.png differ diff --git a/frames/winter/holly-leaf.png b/frames/winter/holly-leaf.png new file mode 100644 index 0000000..e94c6ed Binary files /dev/null and b/frames/winter/holly-leaf.png differ diff --git a/frames/winter/pack.json b/frames/winter/pack.json new file mode 100644 index 0000000..94df9b6 --- /dev/null +++ b/frames/winter/pack.json @@ -0,0 +1,402 @@ +{ + "id": "winter", + "name": "Зима", + "version": 1, + "frames": [ + { + "id": "deer", + "name": "Олень", + "ring": { + "width": 0.045, + "line": 0.014, + "fill": [ + "#c8935a", + "#7a4a22" + ], + "ink": "#3e2210" + }, + "parts": [ + { + "sprite": "antler.png", + "ax": 0.5, + "ay": 0.93, + "at": -36, + "size": 0.4, + "turn": -10, + "layer": "back" + }, + { + "sprite": "antler.png", + "ax": 0.5, + "ay": 0.93, + "at": 36, + "size": 0.4, + "turn": 10, + "flip": true, + "layer": "back" + } + ] + }, + { + "id": "snow", + "name": "Снежинки", + "ring": { + "width": 0.045, + "line": 0.014, + "fill": [ + "#f4fbff", + "#a8d4f5" + ], + "ink": "#46709a" + }, + "parts": [ + { + "sprite": "snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": -150, + "size": 0.27, + "turn": -30, + "radial": 0.045, + "layer": "back" + }, + { + "sprite": "snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": -112, + "size": 0.2, + "turn": -13, + "radial": 0.045, + "layer": "back" + }, + { + "sprite": "snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": -74, + "size": 0.27, + "turn": 4, + "radial": 0.045, + "layer": "back" + }, + { + "sprite": "snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": -36, + "size": 0.2, + "turn": 21, + "radial": 0.045, + "layer": "back" + }, + { + "sprite": "snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": 2, + "size": 0.27, + "turn": -22, + "radial": 0.045, + "layer": "back" + }, + { + "sprite": "snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": 40, + "size": 0.2, + "turn": -5, + "radial": 0.045, + "layer": "back" + }, + { + "sprite": "snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": 78, + "size": 0.27, + "turn": 12, + "radial": 0.045, + "layer": "back" + }, + { + "sprite": "snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": 116, + "size": 0.2, + "turn": 29, + "radial": 0.045, + "layer": "back" + }, + { + "sprite": "snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": 154, + "size": 0.27, + "turn": -14, + "radial": 0.045, + "layer": "back" + }, + { + "sprite": "snowflake.png", + "ax": 0.5, + "ay": 0.5, + "at": 192, + "size": 0.2, + "turn": 3, + "radial": 0.045, + "layer": "back" + } + ] + }, + { + "id": "garland", + "name": "Гирлянда", + "ring": { + "width": 0.035, + "line": 0.012, + "fill": [ + "#2e8b57", + "#14532d" + ], + "ink": "#0a3320" + }, + "parts": [ + { + "sprite": "bulb-red.png", + "ax": 0.5, + "ay": 0.1, + "at": -168, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-yellow.png", + "ax": 0.5, + "ay": 0.1, + "at": -144, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-blue.png", + "ax": 0.5, + "ay": 0.1, + "at": -120, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-green.png", + "ax": 0.5, + "ay": 0.1, + "at": -96, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-red.png", + "ax": 0.5, + "ay": 0.1, + "at": -72, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-yellow.png", + "ax": 0.5, + "ay": 0.1, + "at": -48, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-blue.png", + "ax": 0.5, + "ay": 0.1, + "at": -24, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-green.png", + "ax": 0.5, + "ay": 0.1, + "at": 0, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-red.png", + "ax": 0.5, + "ay": 0.1, + "at": 24, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-yellow.png", + "ax": 0.5, + "ay": 0.1, + "at": 48, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-blue.png", + "ax": 0.5, + "ay": 0.1, + "at": 72, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-green.png", + "ax": 0.5, + "ay": 0.1, + "at": 96, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-red.png", + "ax": 0.5, + "ay": 0.1, + "at": 120, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-yellow.png", + "ax": 0.5, + "ay": 0.1, + "at": 144, + "size": 0.12, + "turn": 180, + "layer": "back" + }, + { + "sprite": "bulb-blue.png", + "ax": 0.5, + "ay": 0.1, + "at": 168, + "size": 0.12, + "turn": 180, + "layer": "back" + } + ] + }, + { + "id": "holly", + "name": "Омела", + "ring": { + "width": 0.05, + "line": 0.014, + "fill": [ + "#3cb371", + "#1d6b3e" + ], + "ink": "#0a3c20" + }, + "parts": [ + { + "sprite": "holly-leaf.png", + "ax": 0.06, + "ay": 0.5, + "at": 35, + "size": 0.36, + "turn": -116, + "layer": "back" + }, + { + "sprite": "holly-leaf.png", + "ax": 0.06, + "ay": 0.5, + "at": 35, + "size": 0.36, + "turn": -64, + "layer": "back" + }, + { + "sprite": "berries.png", + "ax": 0.5, + "ay": 0.55, + "at": 35, + "size": 0.17, + "radial": 0.015, + "layer": "front" + }, + { + "sprite": "holly-leaf.png", + "ax": 0.06, + "ay": 0.5, + "at": 155, + "size": 0.36, + "turn": -116, + "layer": "back" + }, + { + "sprite": "holly-leaf.png", + "ax": 0.06, + "ay": 0.5, + "at": 155, + "size": 0.36, + "turn": -64, + "layer": "back" + }, + { + "sprite": "berries.png", + "ax": 0.5, + "ay": 0.55, + "at": 155, + "size": 0.17, + "radial": 0.015, + "layer": "front" + }, + { + "sprite": "holly-leaf.png", + "ax": 0.06, + "ay": 0.5, + "at": 275, + "size": 0.36, + "turn": -116, + "layer": "back" + }, + { + "sprite": "holly-leaf.png", + "ax": 0.06, + "ay": 0.5, + "at": 275, + "size": 0.36, + "turn": -64, + "layer": "back" + }, + { + "sprite": "berries.png", + "ax": 0.5, + "ay": 0.55, + "at": 275, + "size": 0.17, + "radial": 0.015, + "layer": "front" + } + ] + } + ] +} diff --git a/frames/winter/snowflake.png b/frames/winter/snowflake.png new file mode 100644 index 0000000..88c99e2 Binary files /dev/null and b/frames/winter/snowflake.png differ diff --git a/scripts/frame_render.py b/scripts/frame_render.py index 88daa5b..9f2b3ed 100644 --- a/scripts/frame_render.py +++ b/scripts/frame_render.py @@ -24,7 +24,10 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) import make_frame_on_shape as S # noqa: E402 ROOT = Path(__file__).resolve().parents[1] -PACK = ROOT / "frames" / "basic" +import os # noqa: E402 + +PACK_NAME = os.environ.get("LIHONT_PACK", "basic") # another pack: set LIHONT_PACK=winter +PACK = ROOT / "frames" / PACK_NAME OUT = ROOT / "work" / "frames" SS = 2 @@ -158,8 +161,8 @@ def main() -> None: for row, frame in enumerate(frames): for col, shape in enumerate(shapes): sheet.alpha_composite(render(frame, shape, 1000, 520).resize((tile, tile), Image.LANCZOS), (col * tile, row * tile)) - sheet.convert("RGB").save(OUT / "frames_grid.png") - print(OUT / "frames_grid.png") + sheet.convert("RGB").save(OUT / ("frames_grid.png" if PACK_NAME == "basic" else PACK_NAME + "_grid.png")) + print(OUT / ("frames_grid.png" if PACK_NAME == "basic" else PACK_NAME + "_grid.png")) return shape = sys.argv[1] if len(sys.argv) > 1 else "flower" tile = 540 @@ -169,8 +172,8 @@ def main() -> None: x, y = (i % 3) * tile, (i // 3) * tile sheet.alpha_composite(render(frame, shape, 1000, 520).resize((tile, tile), Image.LANCZOS), (x, y)) d.text((x + tile / 2, y + tile - 14), frame["name"], font=font(34), fill=(40, 30, 40, 255), anchor="mm") - sheet.convert("RGB").save(OUT / ("frames_on_" + shape + ".png")) - print(OUT / ("frames_on_" + shape + ".png")) + sheet.convert("RGB").save(OUT / (("frames_on_" if PACK_NAME == "basic" else PACK_NAME + "_on_") + shape + ".png")) + print(OUT / (("frames_on_" if PACK_NAME == "basic" else PACK_NAME + "_on_") + shape + ".png")) if __name__ == "__main__": diff --git a/services/members/server.py b/services/members/server.py index 69430be..e65967b 100644 --- a/services/members/server.py +++ b/services/members/server.py @@ -34,6 +34,9 @@ UNIQUE = re.compile(r"[A-Za-z0-9_.]{2,24}\Z") SHAPES = ("flower", "squircle", "hexagon", "heart", "triangle") # Avatar frames: "pack.frame" ids of the catalog on the site (the catalog itself is not known here, only the shape of the id). FRAME = re.compile(r"[a-z0-9][a-z0-9_-]{0,23}\.[a-z0-9][a-z0-9_-]{0,23}\Z") +# Packs whose frames only the accounts that were given them may use. A grant is one frame ("vip.creator") or a whole pack ("vip.*"). +RESTRICTED_PACKS = ("vip",) +GRANT = re.compile(r"[a-z0-9][a-z0-9_-]{0,23}\.(\*|[a-z0-9][a-z0-9_-]{0,23})\Z") # The niche-mod badge can be claimed until this moment (Moscow time). CLAIM_DEADLINE = 1794735240 # 2026-11-15 12:34:00 +03:00 @@ -56,6 +59,12 @@ def fetch_profile(unique_id): return str(user["id"]), str(user.get("signature") or "") +def frame_permitted(frame, grants): + """True when the frame is open to everyone, or one of `grants` (frame ids and "pack.*") covers it.""" + pack = frame.split(".", 1)[0] + return pack not in RESTRICTED_PACKS or frame in grants or pack + ".*" in grants + + def valid_uid(value): return isinstance(value, str) and UID.fullmatch(value) is not None @@ -75,6 +84,7 @@ class Registry: db.execute("CREATE TABLE IF NOT EXISTS niche (uid TEXT PRIMARY KEY, unique_id TEXT NOT NULL, granted_at INTEGER NOT NULL)") db.execute("CREATE TABLE IF NOT EXISTS shapes (uid TEXT PRIMARY KEY, shape TEXT NOT NULL, updated_at INTEGER NOT NULL)") db.execute("CREATE TABLE IF NOT EXISTS avatar_frames (uid TEXT PRIMARY KEY, frame TEXT NOT NULL, updated_at INTEGER NOT NULL)") + db.execute("CREATE TABLE IF NOT EXISTS frame_grants (uid TEXT NOT NULL, frame TEXT NOT NULL, granted_at INTEGER NOT NULL, PRIMARY KEY(uid, frame))") db.execute("CREATE TABLE IF NOT EXISTS shape_owner (uid TEXT PRIMARY KEY, installation TEXT NOT NULL, unique_id TEXT NOT NULL, verified_at INTEGER NOT NULL)") db.execute("CREATE TABLE IF NOT EXISTS 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),)) @@ -208,6 +218,8 @@ 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): + raise ValueError("This frame is not available for this account") digest = hashlib.sha256(installation.encode("ascii")).hexdigest() with self.connect() as db: if db.execute("SELECT 1 FROM blocked WHERE uid=?", (uid,)).fetchone(): @@ -251,12 +263,37 @@ class Registry: frames_of = {row[0]: row[1] for row in db.execute( "SELECT uid,frame FROM avatar_frames WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM blocked)", uids ).fetchall() if FRAME.fullmatch(row[1])} + grants = {} + for row in db.execute("SELECT uid,frame FROM frame_grants WHERE uid IN (" + placeholders + ")", uids).fetchall(): + grants.setdefault(row[0], []).append(row[1]) + frames_of = {uid: frame for uid, frame in frames_of.items() if frame_permitted(frame, grants.get(uid, []))} 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, "ttl": 300} + "niche": {uid: uid in niche for uid in uids}, "shapes": shapes, "avatar_frames": frames_of, "frame_grants": grants, "ttl": 300} + + def frame_allowed(self, uid, frame): + """May this account use this frame? Open packs: always; closed packs: only with a grant.""" + if frame.split(".", 1)[0] not in RESTRICTED_PACKS: + return True + with self.connect() as db: + rows = db.execute("SELECT frame FROM frame_grants WHERE uid=?", (uid,)).fetchall() + return frame_permitted(frame, [row[0] for row in rows]) + + def set_frame_grant(self, uid, frame, enabled=True): + """Admin-only when invoked from the server CLI; never exposed over HTTP. `frame` is "pack.name" or "pack.*".""" + if not valid_uid(uid): + raise ValueError("Invalid account ID") + if not isinstance(frame, str) or not GRANT.fullmatch(frame): + raise ValueError("Invalid frame") + with self.connect() as db: + if enabled: + db.execute("INSERT OR IGNORE INTO frame_grants(uid,frame,granted_at) VALUES(?,?,?)", (uid, frame, int(self.clock()))) + else: + db.execute("DELETE FROM frame_grants WHERE uid=? AND frame=?", (uid, frame)) + return {"uid": uid, "frame": frame, "granted": bool(enabled)} def set_supporter(self, uid, enabled=True): """Admin-only when invoked from the server CLI; never exposed over HTTP.""" @@ -361,8 +398,15 @@ def main(): parser.add_argument("--port", type=int, default=18746) parser.add_argument("--grant-supporter", metavar="UID", help="Grant the LihonT supporter badge locally") parser.add_argument("--revoke-supporter", metavar="UID", help="Revoke the LihonT supporter badge locally") + parser.add_argument("--grant-frame", nargs=2, metavar=("UID", "FRAME"), help="Give an account a closed frame (vip.name) or a whole pack (vip.*)") + parser.add_argument("--revoke-frame", nargs=2, metavar=("UID", "FRAME"), help="Take a closed frame away from an account") args = parser.parse_args() Path(args.database).resolve().parent.mkdir(parents=True, exist_ok=True) + if args.grant_frame or args.revoke_frame: + registry = Registry(args.database) + uid, frame = args.grant_frame or args.revoke_frame + print(json.dumps(registry.set_frame_grant(uid, frame, enabled=bool(args.grant_frame)))) + return if args.grant_supporter or args.revoke_supporter: registry = Registry(args.database) print(json.dumps(registry.set_supporter(args.grant_supporter or args.revoke_supporter, diff --git a/src/lihont/two/account/CurrentAccount.java b/src/lihont/two/account/CurrentAccount.java index 9b64b47..52e3713 100644 --- a/src/lihont/two/account/CurrentAccount.java +++ b/src/lihont/two/account/CurrentAccount.java @@ -15,6 +15,7 @@ public final class CurrentAccount { private static String uid; private static String uniqueId; private static long refreshAt; + private static boolean refreshing; private CurrentAccount() {} @@ -37,10 +38,18 @@ public final class CurrentAccount { private static void refresh() { long now = SystemClock.uptimeMillis(); - if (refreshAt != 0L && now < refreshAt) return; - NicheClaim.Account account = NicheClaim.account(); - uid = account == null ? null : account.uid; - uniqueId = account == null ? null : account.uniqueId; + if (refreshing || (refreshAt != 0L && now < refreshAt)) return; + // Asking TikTok who is signed in makes it read user names, which pass through the mod's hooks, which ask this class again. The + // next time is therefore set before the question, and a nested question gets the last answer: without this each level of + // the nesting asked TikTok again, thousands of levels deep, and the main thread did nothing else. + refreshing = true; refreshAt = now + REFRESH_MS; + try { + NicheClaim.Account account = NicheClaim.account(); + uid = account == null ? null : account.uid; + uniqueId = account == null ? null : account.uniqueId; + } finally { + refreshing = false; + } } } diff --git a/src/lihont/two/avatar/AvatarShapes.java b/src/lihont/two/avatar/AvatarShapes.java index 7e87771..4261acf 100644 --- a/src/lihont/two/avatar/AvatarShapes.java +++ b/src/lihont/two/avatar/AvatarShapes.java @@ -49,6 +49,15 @@ public final class AvatarShapes { /** Called before the avatar is drawn. Never throws. */ public static void begin(View view, Canvas canvas) { + long perfStart = lihont.two.look.Perf.start(); + try { + beginImpl(view, canvas); + } finally { + lihont.two.look.Perf.end(lihont.two.look.Perf.AVATAR_BEGIN, perfStart); + } + } + + private static void beginImpl(View view, Canvas canvas) { try { int width = view.getWidth(); int height = view.getHeight(); @@ -106,6 +115,15 @@ public final class AvatarShapes { /** Called when the avatar has been drawn: takes off what begin() put on the canvas, then draws the front of the frame. Never throws. */ public static void end(Canvas canvas) { + long perfStart = lihont.two.look.Perf.start(); + try { + endImpl(canvas); + } finally { + lihont.two.look.Perf.end(lihont.two.look.Perf.AVATAR_END, perfStart); + } + } + + private static void endImpl(Canvas canvas) { try { if (openCanvas == canvas) { canvas.restoreToCount(openSave); diff --git a/src/lihont/two/badge/AccountNames.java b/src/lihont/two/badge/AccountNames.java index dddd4a4..85974f7 100644 --- a/src/lihont/two/badge/AccountNames.java +++ b/src/lihont/two/badge/AccountNames.java @@ -45,15 +45,28 @@ final class AccountNames { /** Called by the User getters: records that `name` (a copy is returned) belongs to `user`. */ static String remember(Object user, String name) { if (name == null || name.length() == 0 || user == null) return name; + // What this method calls may read user names again through the same hooks: a nested call only hands the name back. + if (INSIDE.get() == Boolean.TRUE) return name; + INSIDE.set(Boolean.TRUE); + lihont.two.look.Perf.enter(); try { + long t = lihont.two.look.Perf.start(); String uid = (String) user.getClass().getMethod("getUid").invoke(user); + lihont.two.look.Perf.end(lihont.two.look.Perf.REM_UID, t); if (!validUid(uid)) return name; + t = lihont.two.look.Perf.start(); lihont.two.avatar.PictureOwners.learn(user, uid); + lihont.two.look.Perf.end(lihont.two.look.Perf.REM_PICTURES, t); + t = lihont.two.look.Perf.start(); lihont.two.widget.Contacts.learn(user, uid, name); + lihont.two.look.Perf.end(lihont.two.look.Perf.REM_CONTACTS, t); // a plugin may show this account under another name; the badge lookups follow the text that is shown + t = lihont.two.look.Perf.start(); String shown = lihont.two.plugin.PluginEngine.name(uid, name); + lihont.two.look.Perf.end(lihont.two.look.Perf.REM_PLUGIN, t); // The handle is not a display name: TikTok checks it, and a changed one makes it demand a new username. if (!shown.equals(name) && fromHandle()) shown = name; + t = lihont.two.look.Perf.start(); String copy = new String(shown); synchronized (NAMES) { NAMES.put(copy, uid); @@ -67,12 +80,18 @@ final class AccountNames { BY_VALUE.put(shown, ""); } } + lihont.two.look.Perf.end(lihont.two.look.Perf.REM_MAPS, t); return copy; } catch (Exception ignored) { return name; + } finally { + lihont.two.look.Perf.leave(); + INSIDE.set(Boolean.FALSE); } } + private static final ThreadLocal INSIDE = new ThreadLocal(); + 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++) { diff --git a/src/lihont/two/badge/Badges.java b/src/lihont/two/badge/Badges.java index 53d03f4..17bd786 100644 --- a/src/lihont/two/badge/Badges.java +++ b/src/lihont/two/badge/Badges.java @@ -67,6 +67,15 @@ public final class Badges { /** TuxTextView.setText: returns the text to show, with badges when it names an account. */ public static CharSequence prepare(TextView view, CharSequence text) { + long perfStart = lihont.two.look.Perf.start(); + try { + return prepareImpl(view, text); + } finally { + lihont.two.look.Perf.end(lihont.two.look.Perf.BADGE_PREPARE, perfStart); + } + } + + private static CharSequence prepareImpl(TextView view, CharSequence text) { if (view == null || text == null || text.length() == 0) return text; if (Boolean.TRUE.equals(REFRESHING.get())) return text; try { @@ -271,6 +280,15 @@ public final class Badges { /** A comment cell: the author name view and the comment the cell shows. */ public static void bindComment(Object cell, TextView view) { + long perfStart = lihont.two.look.Perf.start(); + try { + bindCommentImpl(cell, view); + } finally { + lihont.two.look.Perf.end(lihont.two.look.Perf.BADGE_COMMENT, perfStart); + } + } + + private static void bindCommentImpl(Object cell, TextView view) { if (cell == null || view == null) return; try { if (commentGetter == null || !commentGetter.getDeclaringClass().isInstance(cell)) { @@ -293,6 +311,15 @@ public final class Badges { /** The profile header: the protocol holds the profile data, the view shows the nickname. */ public static void bindProfile(Object protocol, TextView view) { + long perfStart = lihont.two.look.Perf.start(); + try { + bindProfileImpl(protocol, view); + } finally { + lihont.two.look.Perf.end(lihont.two.look.Perf.BADGE_PROFILE, perfStart); + } + } + + private static void bindProfileImpl(Object protocol, TextView view) { if (protocol == null || view == null) return; try { Object common = protocol.getClass().getMethod("LJLI").invoke(protocol); @@ -312,6 +339,15 @@ public final class Badges { /** Called by the User getters. */ public static String remember(Object user, String name) { + long perfStart = lihont.two.look.Perf.start(); + try { + return rememberImpl(user, name); + } finally { + lihont.two.look.Perf.end(lihont.two.look.Perf.BADGE_REMEMBER, perfStart); + } + } + + private static String rememberImpl(Object user, String name) { return AccountNames.remember(user, name); } diff --git a/src/lihont/two/feed/FeedFilter.java b/src/lihont/two/feed/FeedFilter.java index cb5827c..35dc833 100644 --- a/src/lihont/two/feed/FeedFilter.java +++ b/src/lihont/two/feed/FeedFilter.java @@ -44,6 +44,15 @@ public final class FeedFilter { /** Whether advertisements are to be removed; the early returns of the ad hooks ask this. */ public static boolean ads() { + long perfStart = lihont.two.look.Perf.start(); + try { + return adsImpl(); + } finally { + lihont.two.look.Perf.end(lihont.two.look.Perf.FEED_ADS, perfStart); + } + } + + private static boolean adsImpl() { return SettingsHost.hideAds(); } @@ -100,6 +109,15 @@ public final class FeedFilter { * removed; a list from the server or a cache is never changed in place. */ public static List filter(List input) { + long perfStart = lihont.two.look.Perf.start(); + try { + return filterImpl(input); + } finally { + lihont.two.look.Perf.end(lihont.two.look.Perf.FEED_FILTER, perfStart); + } + } + + private static List filterImpl(List input) { if (input == null || input.isEmpty()) return input; boolean ads = SettingsHost.hideAds(); boolean live = SettingsHost.hideLive(); @@ -174,6 +192,15 @@ public final class FeedFilter { /** Cleans a FeedItemList in place: its items, the advertisements preloaded for it and its ad flag. */ public static void cleanPage(Object page) { + long perfStart = lihont.two.look.Perf.start(); + try { + cleanPageImpl(page); + } finally { + lihont.two.look.Perf.end(lihont.two.look.Perf.FEED_CLEAN, perfStart); + } + } + + private static void cleanPageImpl(Object page) { if (page == null) return; try { if (pageClass != page.getClass()) pageFields(page.getClass()); diff --git a/src/lihont/two/look/Perf.java b/src/lihont/two/look/Perf.java new file mode 100644 index 0000000..5479ac7 --- /dev/null +++ b/src/lihont/two/look/Perf.java @@ -0,0 +1,115 @@ +package lihont.two.look; + +import android.os.Handler; +import android.os.Looper; +import android.util.Log; + +/** + * How much of the main thread the mod's own code takes. Every place where TikTok calls into the mod measures itself with start() and end(); + * the main thread's share (time, number of calls, the worst call) is written to the log under the LIHONT tag every five seconds, and a + * single call of the mod that takes longer than 50 ms on the main thread is logged at once. It is what the diary shows when something feels slow, + * and the answer to "is it the mod or TikTok". + * + * The counters are plain arrays touched by the main thread only (calls from other threads are not counted), so measuring costs two clock reads. + */ +public final class Perf { + public static final int AVATAR_BEGIN = 0; + public static final int AVATAR_END = 1; + public static final int BADGE_PREPARE = 2; + public static final int BADGE_COMMENT = 3; + public static final int BADGE_PROFILE = 4; + public static final int BADGE_REMEMBER = 5; + public static final int THEME_COLORS = 6; + public static final int FEED_ADS = 7; + public static final int FEED_FILTER = 8; + public static final int FEED_CLEAN = 9; + public static final int FLAGS = 10; + public static final int REM_UID = 11; + public static final int REM_PICTURES = 12; + public static final int REM_CONTACTS = 13; + public static final int REM_PLUGIN = 14; + public static final int REM_MAPS = 15; + + private static final String[] NAMES = {"avatar.begin", "avatar.end", "badge.prepare", "badge.comment", "badge.profile", "badge.remember", + "theme.colors", "feed.ads", "feed.filter", "feed.clean", "flags", "rem.uid", "rem.pictures", "rem.contacts", "rem.plugin", "rem.maps"}; + private static final String TAG = "LIHONT"; + private static final long SLOW_NS = 50000000L; + private static final long REPORT_MS = 5000L; + private static final long[] TOTAL = new long[NAMES.length]; + private static final long[] WORST = new long[NAMES.length]; + private static final int[] CALLS = new int[NAMES.length]; + private static final Handler MAIN = new Handler(Looper.getMainLooper()); + private static boolean scheduled; + private static int depth; + private static int deepest; + private static int slowLogged; + private static long slowWindow; + + private Perf() {} + + public static long start() { + return System.nanoTime(); + } + + /** The code between enter() and leave() may call itself again (a getter of TikTok that the mod hooks); the deepest nesting is logged. */ + public static void enter() { + if (Looper.myLooper() == Looper.getMainLooper() && ++depth > deepest) deepest = depth; + } + + public static void leave() { + if (Looper.myLooper() == Looper.getMainLooper() && depth > 0) depth--; + } + + public static void end(int slot, long since) { + try { + if (Looper.myLooper() != Looper.getMainLooper()) return; + long took = System.nanoTime() - since; + TOTAL[slot] += took; + CALLS[slot]++; + if (took > WORST[slot]) WORST[slot] = took; + if (took > SLOW_NS) logSlow(slot, took); + if (!scheduled) { + scheduled = true; + MAIN.postDelayed(REPORT, REPORT_MS); + } + } catch (Throwable ignored) { + // measuring must never break the app + } + } + + private static void logSlow(int slot, long took) { + long now = System.currentTimeMillis(); + if (now - slowWindow > 60000L) { + slowWindow = now; + slowLogged = 0; + } + if (slowLogged++ < 20) Log.i(TAG, "perf: SLOW " + NAMES[slot] + " took " + (took / 1000000L) + " ms on the main thread"); + } + + private static final Runnable REPORT = new Runnable() { + @Override public void run() { + scheduled = false; + try { + StringBuilder out = new StringBuilder(); + long sum = 0L; + for (int i = 0; i < NAMES.length; i++) { + if (CALLS[i] == 0) continue; + sum += TOTAL[i]; + out.append(' ').append(NAMES[i]).append('=').append(TOTAL[i] / 1000000L).append("ms/").append(CALLS[i]) + .append("(worst ").append(WORST[i] / 1000000L).append(')'); + TOTAL[i] = 0L; + WORST[i] = 0L; + CALLS[i] = 0; + } + if (out.length() > 0) { + Runtime runtime = Runtime.getRuntime(); + Log.i(TAG, "perf 5s: mod total " + (sum / 1000000L) + " ms of 5000 |" + out + " | heap " + + ((runtime.totalMemory() - runtime.freeMemory()) / 1048576L) + " MB | deepest nesting " + deepest); + deepest = 0; + } + } catch (Throwable ignored) { + // diagnostics only + } + } + }; +} diff --git a/src/lihont/two/settings/LihonTSettingsActivity.java b/src/lihont/two/settings/LihonTSettingsActivity.java index d38c4f9..c70ca11 100644 --- a/src/lihont/two/settings/LihonTSettingsActivity.java +++ b/src/lihont/two/settings/LihonTSettingsActivity.java @@ -46,13 +46,15 @@ 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"; + private static final String VERSION_LINE = "LihonT 2.0 · Serena beta 2"; 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 = - "• Рамки аватарок: рамка повторяет форму аватарки, наборы рамок приходят сами, без обновления мода. Выбранную рамку видят другие с модом.\n" + "• Исправление (beta 2): приложение больше не зависало при прокрутке ленты и входе в профиль («Не отвечает»). Причина была в моде: при чтении имён он обращался к самому себе по кругу." + + "\n" + + "• Рамки аватарок: рамка повторяет форму аватарки, наборы рамок приходят сами, без обновления мода. Выбранную рамку видят другие с модом.\n" + "• Сохранить аватарку по нику в Галерею (папка LihonT).\n" + "• Дневник мода: записи мода копируются одним нажатием. Полоса перемотки на каждом видео.\n" + "• Темы «Стикеры» и Windows 95, темы и значки кнопок из плагинов, конфетти и вибрация в плагинах.\n" diff --git a/src/lihont/two/theme/NativeTheme.java b/src/lihont/two/theme/NativeTheme.java index 4b50e4e..e5a6647 100644 --- a/src/lihont/two/theme/NativeTheme.java +++ b/src/lihont/two/theme/NativeTheme.java @@ -50,6 +50,15 @@ public final class NativeTheme { /** Called from the patched LX/0LAr;->LIZIZ. Never throws. */ public static Object colors(Object original, Object composer) { + long perfStart = lihont.two.look.Perf.start(); + try { + return colorsImpl(original, composer); + } finally { + lihont.two.look.Perf.end(lihont.two.look.Perf.THEME_COLORS, perfStart); + } + } + + private static Object colorsImpl(Object original, Object composer) { if (original == null || composer == null) return original; try { Activity activity = activityOf(composer); diff --git a/tests/java/lihont/two/frame/FrameTest.java b/tests/java/lihont/two/frame/FrameTest.java index d94c85e..9420376 100644 --- a/tests/java/lihont/two/frame/FrameTest.java +++ b/tests/java/lihont/two/frame/FrameTest.java @@ -46,14 +46,19 @@ public final class FrameTest { private static void real() throws Exception { String text = new String(Files.readAllBytes(Paths.get("frames", "index.json")), StandardCharsets.UTF_8); FrameIndex index = FrameIndex.parse(text); - check(index.packs.size() == 1 && index.packs.get(0).id.equals("basic"), "one pack named basic"); - check(index.allFrames().size() == 5, "five frames"); + check(index.packs.size() == 2 && index.packs.get(0).id.equals("basic") && index.packs.get(1).id.equals("winter"), + "the packs basic and winter"); + check(index.allFrames().size() == 9, "nine frames"); + for (String id : new String[] {"winter.deer", "winter.snow", "winter.garland", "winter.holly"}) { + check(index.frame(id) != null && !index.frame(id).parts.isEmpty(), id); + } + check(index.frame("winter.garland").parts.size() == 15, "fifteen bulbs on the garland"); for (String id : new String[] {"basic.cat", "basic.helmet", "basic.flower", "basic.crown", "basic.flame"}) { FrameIndex.Frame frame = index.frame(id); check(frame != null && !frame.parts.isEmpty(), id); check(FrameIndex.validFrameId(id), "valid id " + id); } - check(index.allSprites().size() == 13, "thirteen sprites, each once: " + index.allSprites().size()); + check(index.allSprites().size() == 21, "21 sprites, each once: " + index.allSprites().size()); FrameIndex.Frame flower = index.frame("basic.flower"); check(flower.parts.size() == 24, "the flower hangs 24 petals on 2 sprites"); check(index.frame("basic.crown").parts.get(0).front, "the crown is drawn in front");