LihonT 2 Serena beta

Avatar frames that follow the outline of the avatar (ring and parts hung on it), packs of frames that arrive from a catalog on the
site by themselves, the frame shown to other members through the members service, save an avatar by user name, the diary of the
mod, the seek bar on every video, the beta version line and its what is new, plus tests, the catalog builder, the sprites and the
scripts that draw them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
cheb0chik
2026-11-03 10:30:22 +03:00
parent 38e7b2551e
commit d40c17b083
55 changed files with 4955 additions and 66 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

BIN
frames/basic/cat-ear.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

BIN
frames/basic/cat-tuft.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

BIN
frames/basic/crown.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

BIN
frames/basic/flame-mid.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
frames/basic/flame-tall.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

BIN
frames/basic/helmet-pod.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

94
frames/basic/pack.json Normal file
View File

@@ -0,0 +1,94 @@
{
"id": "basic",
"name": "Основные",
"version": 1,
"frames": [
{
"id": "cat",
"name": "Ушки",
"ring": {"width": 0.045, "line": 0.014, "fill": ["#fffcfa", "#ece6f0"], "ink": "#16141a"},
"parts": [
{"sprite": "cat-tuft.png", "ax": 0.5, "ay": 0.9, "at": -68, "radial": 0.01, "size": 0.27, "turn": -30, "layer": "back"},
{"sprite": "cat-tuft.png", "ax": 0.5, "ay": 0.9, "at": -92, "size": 0.3, "turn": -38, "layer": "back"},
{"sprite": "cat-tuft.png", "ax": 0.5, "ay": 0.9, "at": -116, "size": 0.27, "turn": -48, "layer": "back"},
{"sprite": "cat-tuft.png", "ax": 0.5, "ay": 0.9, "at": 68, "radial": 0.01, "size": 0.27, "turn": 30, "flip": true, "layer": "back"},
{"sprite": "cat-tuft.png", "ax": 0.5, "ay": 0.9, "at": 92, "size": 0.3, "turn": 38, "flip": true, "layer": "back"},
{"sprite": "cat-tuft.png", "ax": 0.5, "ay": 0.9, "at": 116, "size": 0.27, "turn": 48, "flip": true, "layer": "back"},
{"sprite": "cat-ear.png", "ax": 0.5, "ay": 0.9, "at": -38, "radial": 0.03, "size": 0.44, "turn": -14, "layer": "back"},
{"sprite": "cat-ear.png", "ax": 0.5, "ay": 0.9, "at": 38, "radial": 0.03, "size": 0.44, "turn": 14, "flip": true, "layer": "back"},
{"sprite": "cat-cowlick.png", "ax": 0.5, "ay": 0.92, "at": 0, "size": 0.14, "turn": 4, "layer": "back"}
]
},
{
"id": "helmet",
"name": "Скафандр",
"ring": {"width": 0.075, "line": 0.014, "fill": ["#eef2f8", "#a8b6ce"], "ink": "#16141a"},
"parts": [
{"sprite": "helmet-antenna.png", "ax": 0.5, "ay": 0.95, "at": 42, "size": 0.1, "layer": "back"},
{"sprite": "helmet-pod.png", "ax": 0.5, "ay": 0.55, "at": -90, "size": 0.3, "layer": "back"},
{"sprite": "helmet-pod.png", "ax": 0.5, "ay": 0.55, "at": 90, "size": 0.3, "flip": true, "layer": "back"},
{"sprite": "helmet-collar.png", "ax": 0.5, "ay": 0.05, "at": 180, "radial": 0.0, "size": 1.0, "layer": "back"},
{"sprite": "helmet-glare.png", "ax": 0.5, "ay": 0.5, "at": -40, "radial": -0.3, "size": 0.5, "turn": 40, "layer": "front"}
]
},
{
"id": "flower",
"name": "Цветок",
"ring": {"width": 0.06, "line": 0.014, "fill": ["#fff6d6", "#ffc460"], "ink": "#8a5a10"},
"parts": [
{"sprite": "petal-back.png", "ax": 0.5, "ay": 0.8, "at": 0, "size": 0.34, "layer": "back"},
{"sprite": "petal-back.png", "ax": 0.5, "ay": 0.8, "at": 30, "size": 0.34, "layer": "back"},
{"sprite": "petal-back.png", "ax": 0.5, "ay": 0.8, "at": 60, "size": 0.34, "layer": "back"},
{"sprite": "petal-back.png", "ax": 0.5, "ay": 0.8, "at": 90, "size": 0.34, "layer": "back"},
{"sprite": "petal-back.png", "ax": 0.5, "ay": 0.8, "at": 120, "size": 0.34, "layer": "back"},
{"sprite": "petal-back.png", "ax": 0.5, "ay": 0.8, "at": 150, "size": 0.34, "layer": "back"},
{"sprite": "petal-back.png", "ax": 0.5, "ay": 0.8, "at": 180, "size": 0.34, "layer": "back"},
{"sprite": "petal-back.png", "ax": 0.5, "ay": 0.8, "at": 210, "size": 0.34, "layer": "back"},
{"sprite": "petal-back.png", "ax": 0.5, "ay": 0.8, "at": 240, "size": 0.34, "layer": "back"},
{"sprite": "petal-back.png", "ax": 0.5, "ay": 0.8, "at": 270, "size": 0.34, "layer": "back"},
{"sprite": "petal-back.png", "ax": 0.5, "ay": 0.8, "at": 300, "size": 0.34, "layer": "back"},
{"sprite": "petal-back.png", "ax": 0.5, "ay": 0.8, "at": 330, "size": 0.34, "layer": "back"},
{"sprite": "petal-front.png", "ax": 0.5, "ay": 0.8, "at": 15, "size": 0.27, "layer": "back"},
{"sprite": "petal-front.png", "ax": 0.5, "ay": 0.8, "at": 45, "size": 0.27, "layer": "back"},
{"sprite": "petal-front.png", "ax": 0.5, "ay": 0.8, "at": 75, "size": 0.27, "layer": "back"},
{"sprite": "petal-front.png", "ax": 0.5, "ay": 0.8, "at": 105, "size": 0.27, "layer": "back"},
{"sprite": "petal-front.png", "ax": 0.5, "ay": 0.8, "at": 135, "size": 0.27, "layer": "back"},
{"sprite": "petal-front.png", "ax": 0.5, "ay": 0.8, "at": 165, "size": 0.27, "layer": "back"},
{"sprite": "petal-front.png", "ax": 0.5, "ay": 0.8, "at": 195, "size": 0.27, "layer": "back"},
{"sprite": "petal-front.png", "ax": 0.5, "ay": 0.8, "at": 225, "size": 0.27, "layer": "back"},
{"sprite": "petal-front.png", "ax": 0.5, "ay": 0.8, "at": 255, "size": 0.27, "layer": "back"},
{"sprite": "petal-front.png", "ax": 0.5, "ay": 0.8, "at": 285, "size": 0.27, "layer": "back"},
{"sprite": "petal-front.png", "ax": 0.5, "ay": 0.8, "at": 315, "size": 0.27, "layer": "back"},
{"sprite": "petal-front.png", "ax": 0.5, "ay": 0.8, "at": 345, "size": 0.27, "layer": "back"}
]
},
{
"id": "crown",
"name": "Корона",
"ring": {"width": 0.05, "line": 0.014, "fill": ["#ffeea0", "#e8a018"], "ink": "#96500a"},
"parts": [
{"sprite": "crown.png", "ax": 0.5, "ay": 0.86, "at": 0, "radial": -0.01, "size": 0.62, "layer": "front"}
]
},
{
"id": "flame",
"name": "Пламя",
"ring": {"width": 0.05, "line": 0.014, "fill": ["#ffa046", "#ce2a1c"], "ink": "#821810"},
"parts": [
{"sprite": "flame-mid.png", "ax": 0.5, "ay": 0.9, "at": -120, "size": 0.24, "turn": -6, "layer": "back"},
{"sprite": "flame-short.png", "ax": 0.5, "ay": 0.9, "at": -100, "size": 0.27, "turn": 4, "layer": "back"},
{"sprite": "flame-tall.png", "ax": 0.5, "ay": 0.9, "at": -80, "size": 0.24, "turn": -4, "layer": "back"},
{"sprite": "flame-mid.png", "ax": 0.5, "ay": 0.9, "at": -60, "size": 0.24, "turn": 6, "layer": "back"},
{"sprite": "flame-tall.png", "ax": 0.5, "ay": 0.9, "at": -40, "size": 0.28, "turn": -5, "layer": "back"},
{"sprite": "flame-short.png", "ax": 0.5, "ay": 0.9, "at": -22, "size": 0.27, "turn": 6, "layer": "back"},
{"sprite": "flame-tall.png", "ax": 0.5, "ay": 0.9, "at": 0, "size": 0.3, "turn": 0, "layer": "back"},
{"sprite": "flame-short.png", "ax": 0.5, "ay": 0.9, "at": 22, "size": 0.27, "turn": -6, "layer": "back"},
{"sprite": "flame-tall.png", "ax": 0.5, "ay": 0.9, "at": 40, "size": 0.28, "turn": 5, "layer": "back"},
{"sprite": "flame-mid.png", "ax": 0.5, "ay": 0.9, "at": 60, "size": 0.24, "turn": -6, "layer": "back"},
{"sprite": "flame-tall.png", "ax": 0.5, "ay": 0.9, "at": 80, "size": 0.24, "turn": 4, "layer": "back"},
{"sprite": "flame-short.png", "ax": 0.5, "ay": 0.9, "at": 100, "size": 0.27, "turn": -4, "layer": "back"},
{"sprite": "flame-mid.png", "ax": 0.5, "ay": 0.9, "at": 120, "size": 0.24, "turn": 6, "layer": "back"}
]
}
]
}

BIN
frames/basic/petal-back.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

581
frames/index.json Normal file
View File

@@ -0,0 +1,581 @@
{
"version": 1,
"packs": [
{
"id": "basic",
"name": "Основные",
"version": 1,
"sprites": [
{
"file": "basic/cat-tuft.png",
"sha256": "fd6084ac5b81b3bd071f82bc99efe3b0dfb7f6dd6aef96fb8a4bc7ad0081c71b",
"bytes": 9085,
"w": 150,
"h": 130
},
{
"file": "basic/cat-ear.png",
"sha256": "6051fb23d0bab1ab16b42e3b85ae64783bcbf40778c2da741a14ca35c8fb0920",
"bytes": 15326,
"w": 170,
"h": 160
},
{
"file": "basic/cat-cowlick.png",
"sha256": "b1fb465fec418232ba0362d4087575f11fc3d2c07cd4e264b6cf2f4c8e15afcd",
"bytes": 8573,
"w": 110,
"h": 130
},
{
"file": "basic/helmet-antenna.png",
"sha256": "bfeb63034293909abd55529e00b29b7497dbc6fe5493b21bea02c9625e1143b4",
"bytes": 7707,
"w": 80,
"h": 170
},
{
"file": "basic/helmet-pod.png",
"sha256": "1ba1b10910ce108bbcef2cff281db222a716014c8ac98e90f407e4cd962967b1",
"bytes": 10027,
"w": 110,
"h": 150
},
{
"file": "basic/helmet-collar.png",
"sha256": "9d80aeb85aa0dfa260c2b11b3d8325a57383c69e90ad931b77ceebd0e885a934",
"bytes": 10783,
"w": 300,
"h": 100
},
{
"file": "basic/helmet-glare.png",
"sha256": "2eb7d91a7b0274db997c35e649472b865db09ea435b486c41ffdc1488c50108d",
"bytes": 2804,
"w": 220,
"h": 220
},
{
"file": "basic/petal-back.png",
"sha256": "fb4f2790c036269742aa8d76c32b7c4e510e484350a58c6e1817ebc8f7d8edd9",
"bytes": 20714,
"w": 150,
"h": 190
},
{
"file": "basic/petal-front.png",
"sha256": "0d042a2b2a7225def2606ffd98ee1afabb277271c76f8419c891e7b62db37389",
"bytes": 20058,
"w": 150,
"h": 190
},
{
"file": "basic/crown.png",
"sha256": "437717076c06f1dc2338fb1d22e32cd74e72e62be22d65e014ab03c53a35f881",
"bytes": 34870,
"w": 340,
"h": 230
},
{
"file": "basic/flame-mid.png",
"sha256": "c32020c050cb076cd5d69742d813ffac1f44bca27be18c410107516899ee243c",
"bytes": 14926,
"w": 110,
"h": 160
},
{
"file": "basic/flame-short.png",
"sha256": "caa599c4da4b3564703b819c154f723487c20aeb1f129fe63186a2c0a399aaa8",
"bytes": 11562,
"w": 96,
"h": 110
},
{
"file": "basic/flame-tall.png",
"sha256": "f91d0c94a3963209240b4589be59e23797898730eb2e3e8410ac79dc68d4f5f3",
"bytes": 18982,
"w": 120,
"h": 210
}
],
"frames": [
{
"id": "cat",
"name": "Ушки",
"ring": {
"width": 0.045,
"line": 0.014,
"fill": [
"#fffcfa",
"#ece6f0"
],
"ink": "#16141a"
},
"parts": [
{
"file": "basic/cat-tuft.png",
"ax": 0.5,
"ay": 0.9,
"at": -68,
"size": 0.27,
"turn": -30,
"radial": 0.01
},
{
"file": "basic/cat-tuft.png",
"ax": 0.5,
"ay": 0.9,
"at": -92,
"size": 0.3,
"turn": -38
},
{
"file": "basic/cat-tuft.png",
"ax": 0.5,
"ay": 0.9,
"at": -116,
"size": 0.27,
"turn": -48
},
{
"file": "basic/cat-tuft.png",
"ax": 0.5,
"ay": 0.9,
"at": 68,
"size": 0.27,
"turn": 30,
"radial": 0.01,
"flip": true
},
{
"file": "basic/cat-tuft.png",
"ax": 0.5,
"ay": 0.9,
"at": 92,
"size": 0.3,
"turn": 38,
"flip": true
},
{
"file": "basic/cat-tuft.png",
"ax": 0.5,
"ay": 0.9,
"at": 116,
"size": 0.27,
"turn": 48,
"flip": true
},
{
"file": "basic/cat-ear.png",
"ax": 0.5,
"ay": 0.9,
"at": -38,
"size": 0.44,
"turn": -14,
"radial": 0.03
},
{
"file": "basic/cat-ear.png",
"ax": 0.5,
"ay": 0.9,
"at": 38,
"size": 0.44,
"turn": 14,
"radial": 0.03,
"flip": true
},
{
"file": "basic/cat-cowlick.png",
"ax": 0.5,
"ay": 0.92,
"at": 0,
"size": 0.14,
"turn": 4
}
]
},
{
"id": "helmet",
"name": "Скафандр",
"ring": {
"width": 0.075,
"line": 0.014,
"fill": [
"#eef2f8",
"#a8b6ce"
],
"ink": "#16141a"
},
"parts": [
{
"file": "basic/helmet-antenna.png",
"ax": 0.5,
"ay": 0.95,
"at": 42,
"size": 0.1
},
{
"file": "basic/helmet-pod.png",
"ax": 0.5,
"ay": 0.55,
"at": -90,
"size": 0.3
},
{
"file": "basic/helmet-pod.png",
"ax": 0.5,
"ay": 0.55,
"at": 90,
"size": 0.3,
"flip": true
},
{
"file": "basic/helmet-collar.png",
"ax": 0.5,
"ay": 0.05,
"at": 180,
"size": 1.0,
"radial": 0.0
},
{
"file": "basic/helmet-glare.png",
"ax": 0.5,
"ay": 0.5,
"at": -40,
"size": 0.5,
"turn": 40,
"radial": -0.3,
"layer": "front"
}
]
},
{
"id": "flower",
"name": "Цветок",
"ring": {
"width": 0.06,
"line": 0.014,
"fill": [
"#fff6d6",
"#ffc460"
],
"ink": "#8a5a10"
},
"parts": [
{
"file": "basic/petal-back.png",
"ax": 0.5,
"ay": 0.8,
"at": 0,
"size": 0.34
},
{
"file": "basic/petal-back.png",
"ax": 0.5,
"ay": 0.8,
"at": 30,
"size": 0.34
},
{
"file": "basic/petal-back.png",
"ax": 0.5,
"ay": 0.8,
"at": 60,
"size": 0.34
},
{
"file": "basic/petal-back.png",
"ax": 0.5,
"ay": 0.8,
"at": 90,
"size": 0.34
},
{
"file": "basic/petal-back.png",
"ax": 0.5,
"ay": 0.8,
"at": 120,
"size": 0.34
},
{
"file": "basic/petal-back.png",
"ax": 0.5,
"ay": 0.8,
"at": 150,
"size": 0.34
},
{
"file": "basic/petal-back.png",
"ax": 0.5,
"ay": 0.8,
"at": 180,
"size": 0.34
},
{
"file": "basic/petal-back.png",
"ax": 0.5,
"ay": 0.8,
"at": 210,
"size": 0.34
},
{
"file": "basic/petal-back.png",
"ax": 0.5,
"ay": 0.8,
"at": 240,
"size": 0.34
},
{
"file": "basic/petal-back.png",
"ax": 0.5,
"ay": 0.8,
"at": 270,
"size": 0.34
},
{
"file": "basic/petal-back.png",
"ax": 0.5,
"ay": 0.8,
"at": 300,
"size": 0.34
},
{
"file": "basic/petal-back.png",
"ax": 0.5,
"ay": 0.8,
"at": 330,
"size": 0.34
},
{
"file": "basic/petal-front.png",
"ax": 0.5,
"ay": 0.8,
"at": 15,
"size": 0.27
},
{
"file": "basic/petal-front.png",
"ax": 0.5,
"ay": 0.8,
"at": 45,
"size": 0.27
},
{
"file": "basic/petal-front.png",
"ax": 0.5,
"ay": 0.8,
"at": 75,
"size": 0.27
},
{
"file": "basic/petal-front.png",
"ax": 0.5,
"ay": 0.8,
"at": 105,
"size": 0.27
},
{
"file": "basic/petal-front.png",
"ax": 0.5,
"ay": 0.8,
"at": 135,
"size": 0.27
},
{
"file": "basic/petal-front.png",
"ax": 0.5,
"ay": 0.8,
"at": 165,
"size": 0.27
},
{
"file": "basic/petal-front.png",
"ax": 0.5,
"ay": 0.8,
"at": 195,
"size": 0.27
},
{
"file": "basic/petal-front.png",
"ax": 0.5,
"ay": 0.8,
"at": 225,
"size": 0.27
},
{
"file": "basic/petal-front.png",
"ax": 0.5,
"ay": 0.8,
"at": 255,
"size": 0.27
},
{
"file": "basic/petal-front.png",
"ax": 0.5,
"ay": 0.8,
"at": 285,
"size": 0.27
},
{
"file": "basic/petal-front.png",
"ax": 0.5,
"ay": 0.8,
"at": 315,
"size": 0.27
},
{
"file": "basic/petal-front.png",
"ax": 0.5,
"ay": 0.8,
"at": 345,
"size": 0.27
}
]
},
{
"id": "crown",
"name": "Корона",
"ring": {
"width": 0.05,
"line": 0.014,
"fill": [
"#ffeea0",
"#e8a018"
],
"ink": "#96500a"
},
"parts": [
{
"file": "basic/crown.png",
"ax": 0.5,
"ay": 0.86,
"at": 0,
"size": 0.62,
"radial": -0.01,
"layer": "front"
}
]
},
{
"id": "flame",
"name": "Пламя",
"ring": {
"width": 0.05,
"line": 0.014,
"fill": [
"#ffa046",
"#ce2a1c"
],
"ink": "#821810"
},
"parts": [
{
"file": "basic/flame-mid.png",
"ax": 0.5,
"ay": 0.9,
"at": -120,
"size": 0.24,
"turn": -6
},
{
"file": "basic/flame-short.png",
"ax": 0.5,
"ay": 0.9,
"at": -100,
"size": 0.27,
"turn": 4
},
{
"file": "basic/flame-tall.png",
"ax": 0.5,
"ay": 0.9,
"at": -80,
"size": 0.24,
"turn": -4
},
{
"file": "basic/flame-mid.png",
"ax": 0.5,
"ay": 0.9,
"at": -60,
"size": 0.24,
"turn": 6
},
{
"file": "basic/flame-tall.png",
"ax": 0.5,
"ay": 0.9,
"at": -40,
"size": 0.28,
"turn": -5
},
{
"file": "basic/flame-short.png",
"ax": 0.5,
"ay": 0.9,
"at": -22,
"size": 0.27,
"turn": 6
},
{
"file": "basic/flame-tall.png",
"ax": 0.5,
"ay": 0.9,
"at": 0,
"size": 0.3,
"turn": 0
},
{
"file": "basic/flame-short.png",
"ax": 0.5,
"ay": 0.9,
"at": 22,
"size": 0.27,
"turn": -6
},
{
"file": "basic/flame-tall.png",
"ax": 0.5,
"ay": 0.9,
"at": 40,
"size": 0.28,
"turn": 5
},
{
"file": "basic/flame-mid.png",
"ax": 0.5,
"ay": 0.9,
"at": 60,
"size": 0.24,
"turn": -6
},
{
"file": "basic/flame-tall.png",
"ax": 0.5,
"ay": 0.9,
"at": 80,
"size": 0.24,
"turn": 4
},
{
"file": "basic/flame-short.png",
"ax": 0.5,
"ay": 0.9,
"at": 100,
"size": 0.27,
"turn": -4
},
{
"file": "basic/flame-mid.png",
"ax": 0.5,
"ay": 0.9,
"at": 120,
"size": 0.24,
"turn": 6
}
]
}
]
}
]
}

40
lihont/seekbar_patch.py Normal file
View File

@@ -0,0 +1,40 @@
"""Seek bar on every video: with the switch on, TikTok never hides the scrubbing bar under a video.
TikTok 47.1.3 decides how the bar looks in LX/1Azi;->setSeekBarShowType(I)V: types 0, 1, 2, 4 and 0x64..0x66 show it in
different ways, type 3 hides it (it makes the view gone and stops dragging). With the switch on the type 3 is read as
type 0, the plain visible bar. With it off, or for any other type, TikTok's own code runs untouched.
"""
from __future__ import annotations
import re
SEEKBAR_CLASS = "LX/1Azi;"
HOOK = "Llihont/two/look/Seekbar;->type(I)I"
_METHOD = re.compile(r"^\.method public final setSeekBarShowType\(I\)V\n.*?^\.end method", re.M | re.S)
_FIRST = re.compile(r"^ iget v0, p0, LX/1Azi;->LLJJJJJIL:I\n", re.M)
def runtime_targets():
"""Runtime methods the rewrite calls, as they appear in a method table."""
return [HOOK]
def rewrite_seek_bar(text: str) -> str:
"""Let the runtime change the show type before TikTok looks at it."""
match = _METHOD.search(text)
if match is None:
raise ValueError("LX/1Azi;->setSeekBarShowType(I)V not found")
method = match.group()
if "Seekbar;" in method:
raise ValueError("Seekbar hook already present in LX/1Azi;->setSeekBarShowType")
# The shape that identifies it: it logs the change and hides the bar with visibility 8 for one of the types.
if "seekbar show type change, change to:" not in method or "const/16 v0, 0x8" not in method:
raise ValueError("LX/1Azi;->setSeekBarShowType has an unexpected shape")
first = _FIRST.search(method)
if first is None:
raise ValueError("LX/1Azi;->setSeekBarShowType does not start with the expected type check")
injected = " invoke-static {p1}, %s\n\n move-result p1\n\n" % HOOK
patched = method[:first.start()] + injected + method[first.start():]
return text[:match.start()] + patched + text[match.end():]

View File

@@ -14,7 +14,7 @@ import subprocess
from collections import defaultdict
from pathlib import Path
from . import avatar_patch, badge_patch, bar_patch, comment_photos_patch, dexpatch, feed_patch, ghost_patch, media_patch, region, profile_features, settings_patch, theme_patch
from . import avatar_patch, badge_patch, bar_patch, comment_photos_patch, dexpatch, feed_patch, ghost_patch, media_patch, seekbar_patch, region, profile_features, settings_patch, theme_patch
from . import portmap
from .apkzip import Apk
from .axml import Axml
@@ -340,6 +340,14 @@ def patch_ghost_stories(apk: Apk, tools: Toolchain, room: Path, api: int) -> dic
return report
def patch_seek_bar(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict:
"""Let a switch keep TikTok's scrubbing bar visible on every video."""
report = patch_class(apk, tools, room, api, "classes34.dex", seekbar_patch.SEEKBAR_CLASS,
"seek-bar", seekbar_patch.rewrite_seek_bar, b"Llihont/two/look/Seekbar;")
report["hook"] = seekbar_patch.HOOK
return report
def patch_ghost_messages(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict:
"""Let a switch stop the chat from telling the server that a conversation was read."""
report = patch_class(apk, tools, room, api, "classes31.dex", ghost_patch.MARK_READ_CLASS,
@@ -603,6 +611,7 @@ def build(source: str, output: str, workspace: str = "work/build") -> dict:
report["comment_photos"] = step("comment_photos", patch_comment_photos, apk, tools, room, api)
report["ghost_stories"] = step("ghost_stories", patch_ghost_stories, apk, tools, room, api)
report["ghost_messages"] = step("ghost_messages", patch_ghost_messages, apk, tools, room, api)
report["seek_bar"] = step("seek_bar", patch_seek_bar, apk, tools, room, api)
report["main_activity"] = step("main_activity", patch_main_activity, apk, tools, room, api)
report["downloads"] = step("downloads", patch_downloads, apk, tools, room, api)
report["feed"] = step("feed", patch_feed, apk, tools, room, api)
@@ -628,7 +637,8 @@ def build(source: str, output: str, workspace: str = "work/build") -> dict:
+ theme_patch.card_targets() + bar_patch.runtime_targets()
+ media_patch.runtime_targets() + feed_patch.runtime_targets()
+ badge_patch.runtime_targets() + avatar_patch.runtime_targets()
+ comment_photos_patch.runtime_targets() + ghost_patch.runtime_targets() if t not in merged]
+ comment_photos_patch.runtime_targets() + ghost_patch.runtime_targets()
+ seekbar_patch.runtime_targets() if t not in merged]
if absent:
raise ValueError("Hooks have no runtime target: " + ", ".join(absent))
report["feature_flags"]["runtime"] = profile_features.FLAGS_CLASS

58
scripts/analyze_beats.py Normal file
View File

@@ -0,0 +1,58 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Finds the beats of a song so that a video can cut and move on them: the tempo, the time of every beat, the strong beats (the first of a
bar, guessed from the loudness) and the moments of sharp sounds. The result is written as JSON next to the audio.
usage (from the repository root):
py -X utf8 -B scripts/analyze_beats.py work/music/baka.mp3 # writes work/music/baka.beats.json
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
import librosa
import numpy as np
def main() -> None:
path = Path(sys.argv[1])
y, sr = librosa.load(str(path), sr=22050, mono=True)
duration = float(len(y) / sr)
hop = 512
onset_env = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop)
tempo, beat_frames = librosa.beat.beat_track(onset_envelope=onset_env, sr=sr, hop_length=hop, tightness=120)
tempo = float(np.atleast_1d(tempo)[0])
beats = librosa.frames_to_time(beat_frames, sr=sr, hop_length=hop)
onsets = librosa.frames_to_time(librosa.onset.onset_detect(onset_envelope=onset_env, sr=sr, hop_length=hop, backtrack=False),
sr=sr, hop_length=hop)
# the strong beats: of the four beats of a bar, the group whose beats are louder on average
strength = [float(onset_env[min(int(f), len(onset_env) - 1)]) for f in beat_frames]
bar_start = 0
if len(strength) >= 8:
sums = [sum(strength[i::4]) for i in range(4)]
bar_start = int(np.argmax(sums))
strong = [round(float(t), 3) for i, t in enumerate(beats) if (i - bar_start) % 4 == 0]
loud = librosa.feature.rms(y=y, hop_length=hop)[0]
data = {
"file": path.name,
"duration": round(duration, 3),
"tempo": round(tempo, 2),
"beat_interval": round(60.0 / tempo, 4) if tempo else None,
"beats": [round(float(t), 3) for t in beats],
"strong_beats": strong,
"onsets": [round(float(t), 3) for t in onsets],
"loudness_per_second": [round(float(np.mean(loud[int(s * sr / hop):int((s + 1) * sr / hop)] if int(s * sr / hop) < len(loud) else 0)), 4)
for s in range(int(duration) + 1)],
}
out = path.with_suffix(".beats.json")
out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
print("tempo %.1f BPM, %d beats, %d strong, %d onsets, %.1f s -> %s" % (tempo, len(beats), len(strong), len(onsets), duration, out))
print("beats:", [round(float(t), 2) for t in beats][:40])
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,107 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Builds the catalog of avatar frames that the mod downloads: frames/index.json, from every frames/<pack>/pack.json and the sprites
(PNG files) next to it. The catalog lists each sprite with its checksum, size and picture size, and each frame with its ring and its
parts; the mod refuses anything that does not match, so a pack is only ever what was built here.
To add a pack: make frames/<pack>/ with pack.json (see frames/basic/pack.json) and the sprites, run this script, and put the
frames/ folder on the site (scripts/stage_site.py takes it along). Phones pick the new pack up by themselves.
usage (from the repository root):
py -X utf8 -B scripts/build_frames_catalog.py # writes frames/index.json
py -X utf8 -B scripts/build_frames_catalog.py --check # exits 1 if frames/index.json is out of date
"""
from __future__ import annotations
import hashlib
import json
import re
import struct
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
FRAMES = ROOT / "frames"
INDEX = FRAMES / "index.json"
ID = re.compile(r"[a-z0-9][a-z0-9_-]{0,23}\Z")
SPRITE = re.compile(r"[a-z0-9][a-z0-9_.-]{0,47}\.png\Z")
COLOR = re.compile(r"#[0-9a-f]{6}\Z")
MAX_SPRITE_BYTES = 150 * 1024
MAX_PARTS = 80
def png_size(data: bytes) -> tuple[int, int]:
if data[:8] != b"\x89PNG\r\n\x1a\n" or data[12:16] != b"IHDR":
raise SystemExit("not a PNG")
return struct.unpack(">II", data[16:24])
def build_pack(folder: Path) -> dict:
pack = json.loads((folder / "pack.json").read_text(encoding="utf-8"))
pack_id = pack["id"]
if not ID.match(pack_id) or pack_id != folder.name:
raise SystemExit("%s: the pack id must be the folder name, lower case" % folder)
sprites = {}
frames = []
for frame in pack["frames"]:
if not ID.match(frame["id"]):
raise SystemExit("%s: bad frame id %r" % (pack_id, frame["id"]))
ring = frame["ring"]
if not all(COLOR.match(c) for c in ring["fill"] + [ring["ink"]]):
raise SystemExit("%s.%s: colours must be #rrggbb in lower case" % (pack_id, frame["id"]))
if len(frame["parts"]) > MAX_PARTS:
raise SystemExit("%s.%s: too many parts" % (pack_id, frame["id"]))
parts = []
for part in frame["parts"]:
name = part["sprite"]
if not SPRITE.match(name) or ".." in name:
raise SystemExit("%s.%s: bad sprite name %r" % (pack_id, frame["id"], name))
if name not in sprites:
data = (folder / name).read_bytes()
if len(data) > MAX_SPRITE_BYTES:
raise SystemExit("%s: %s is %d bytes, at most %d" % (pack_id, name, len(data), MAX_SPRITE_BYTES))
width, height = png_size(data)
sprites[name] = {"file": "%s/%s" % (pack_id, name), "sha256": hashlib.sha256(data).hexdigest(),
"bytes": len(data), "w": width, "h": height}
entry = {"file": sprites[name]["file"]}
for key in ("ax", "ay", "at", "size", "turn", "radial"):
if key in part:
entry[key] = part[key]
if part.get("flip"):
entry["flip"] = True
if part.get("layer") == "front":
entry["layer"] = "front"
parts.append(entry)
frames.append({"id": frame["id"], "name": frame["name"], "ring": ring, "parts": parts})
return {"id": pack_id, "name": pack["name"], "version": pack["version"],
"sprites": list(sprites.values()), "frames": frames}
def build() -> str:
packs = [build_pack(folder) for folder in sorted(FRAMES.iterdir()) if (folder / "pack.json").is_file()]
catalog = {"version": 1, "packs": packs}
return json.dumps(catalog, ensure_ascii=False, indent=1) + "\n"
def main() -> None:
text = build()
if len(text.encode("utf-8")) > 262144:
raise SystemExit("the catalog is larger than the 256 KB the mod accepts")
if "--check" in sys.argv:
current = INDEX.read_text(encoding="utf-8") if INDEX.is_file() else ""
if current.replace("\r\n", "\n") != text:
print("frames/index.json is out of date: run scripts/build_frames_catalog.py")
raise SystemExit(1)
print("frames/index.json is up to date")
return
INDEX.write_text(text, encoding="utf-8", newline="\n")
catalog = json.loads(text)
print("frames/index.json: %d packs, %d frames, %d sprites, %d bytes" % (
len(catalog["packs"]), sum(len(p["frames"]) for p in catalog["packs"]),
sum(len(p["sprites"]) for p in catalog["packs"]), len(text.encode("utf-8"))))
if __name__ == "__main__":
main()

View File

@@ -2,6 +2,7 @@
py scripts/deploy_site.py --dry-run show the plan, change nothing
py scripts/deploy_site.py back up the live files, upload, verify
py scripts/deploy_site.py --only frames/ the same, but only the files whose path starts with the prefix
py scripts/deploy_site.py --rollback restore the newest backup (or --stamp <timestamp> for another)
py scripts/deploy_site.py --portal swap the /lihont2 portal's server.py, restart it, roll back on failure
@@ -41,9 +42,12 @@ def text(result: subprocess.CompletedProcess) -> str:
return "\n".join(lines)
def deploy(dry_run: bool) -> int:
def deploy(dry_run: bool, only: str | None = None) -> int:
stage_site.main()
files = [(stage_site.STAGE / target, target) for _source, target in stage_site.PAYLOAD]
files = [(stage_site.STAGE / target, target) for _source, target in stage_site.PAYLOAD if only is None or target.startswith(only)]
if not files:
print("No staged file starts with %r" % only)
return 1
stamp = time.strftime("%Y%m%d-%H%M%S")
backup = "%s/%s" % (BACKUPS, stamp)
print("Backup folder on the server: %s" % backup)
@@ -182,11 +186,12 @@ def main() -> int:
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--rollback", action="store_true")
parser.add_argument("--stamp", help="backup to restore with --rollback (default: the newest)")
parser.add_argument("--only", metavar="PREFIX", help="deploy only the staged files whose server path starts with PREFIX")
parser.add_argument("--portal", action="store_true", help="act on the /lihont2 portal (server.py) instead of the static site")
args = parser.parse_args()
if args.portal:
return rollback_portal(args.stamp) if args.rollback else deploy_portal(args.dry_run)
return rollback(args.stamp) if args.rollback else deploy(args.dry_run)
return rollback(args.stamp) if args.rollback else deploy(args.dry_run, args.only)
if __name__ == "__main__":

177
scripts/frame_render.py Normal file
View File

@@ -0,0 +1,177 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Draws a frame on an avatar of any shape exactly as the application does (FrameDraw.java): the ring follows the outline of the
shape, and every part hangs on a point of that outline given by an angle, turned to look away from the avatar there.
usage (from the repository root):
py -X utf8 -B scripts/frame_render.py [shape] # work/frames/frames_on_<shape>.png: all frames on one shape
py -X utf8 -B scripts/frame_render.py --grid # work/frames/frames_grid.png: every frame on every shape
"""
from __future__ import annotations
import json
import math
import sys
from pathlib import Path
import numpy as np
from PIL import Image, ImageChops, ImageDraw, ImageFont
from scipy import ndimage
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"
OUT = ROOT / "work" / "frames"
SS = 2
def hexcolor(text):
return tuple(int(text[i:i + 2], 16) for i in (1, 3, 5)) + (255,)
def outline_table(mask, d):
"""r(theta) for theta = 0..359 degrees clockwise from the top: how far the shape reaches from its middle."""
px = mask.load()
table = []
for deg in range(360):
a = math.radians(deg)
r = d / 2.0
while r > 0:
x, y = d / 2 + r * math.sin(a), d / 2 - r * math.cos(a)
if 0 <= x < mask.width and 0 <= y < mask.height and px[int(x), int(y)] > 127:
break
r -= 0.5
table.append(r)
return table
def at(table, deg, d):
deg %= 360
i = int(math.floor(deg))
f = deg - i
r = table[i % 360] * (1 - f) + table[(i + 1) % 360] * f
a = math.radians(deg)
return d / 2 + r * math.sin(a), d / 2 - r * math.cos(a)
def normal_degrees(table, deg, d):
"""The direction away from the avatar at that point: the turn (degrees clockwise from up) that points a sprite outwards."""
p0, p1 = at(table, deg - 3, d), at(table, deg + 3, d)
tx, ty = p1[0] - p0[0], p1[1] - p0[1]
nx, ny = ty, -tx
return math.degrees(math.atan2(nx, -ny))
def sprite(name, cache={}): # noqa: B006
if name not in cache:
cache[name] = Image.open(PACK / name).convert("RGBA")
return cache[name]
def draw_part(canvas, part, table, d, cx, cy):
img = sprite(part["sprite"])
deg = part["at"]
px, py = at(table, deg, d)
nx, ny = px - d / 2, py - d / 2
ln = math.hypot(nx, ny) or 1.0
radial = part.get("radial", 0.0) * d
px, py = px + nx / ln * radial, py + ny / ln * radial
turn = normal_degrees(table, deg, d) + part.get("turn", 0)
width = part["size"] * d
scale = width / img.width
sp = img.resize((max(1, int(img.width * scale * SS)), max(1, int(img.height * scale * SS))), Image.LANCZOS)
if part.get("flip"):
sp = sp.transpose(Image.FLIP_LEFT_RIGHT)
ax = part["ax"] if not part.get("flip") else 1 - part["ax"]
pad = int(math.hypot(sp.width, sp.height)) + 2
holder = Image.new("RGBA", (pad * 2, pad * 2), (0, 0, 0, 0))
holder.alpha_composite(sp, (pad - int(ax * sp.width), pad - int(part["ay"] * sp.height)))
holder = holder.rotate(-turn, resample=Image.BICUBIC, center=(pad, pad))
canvas.alpha_composite(holder, (int(cx + (px - d / 2) * SS - pad), int(cy + (py - d / 2) * SS - pad)))
def render(frame, shape, size=1000, d=520):
"""The frame on an avatar of `shape`; the avatar box is d pixels wide, in the middle of a size-by-size picture."""
s = d * SS
cx = cy = size * SS / 2
cy += 40 * SS
canvas = Image.new("RGBA", (size * SS, size * SS), (0, 0, 0, 0))
mask = S.shape_mask(shape, d)
big = mask.resize((s, s), Image.LANCZOS)
table = outline_table(big, s)
table = [r / SS for r in table]
ring = frame["ring"]
rw, lw = ring["width"] * d * SS, ring["line"] * d * SS
holder = Image.new("L", canvas.size, 0)
holder.paste(big, (int(cx - s / 2), int(cy - s / 2)))
for part in frame["parts"]:
if part.get("layer", "back") == "back":
draw_part(canvas, part, table, d, cx, cy)
outer = grow(holder, rw + lw)
mid = grow(holder, rw)
canvas.paste(Image.new("RGBA", canvas.size, hexcolor(ring["ink"])), (0, 0), outer)
top, bottom = hexcolor(ring["fill"][0]), hexcolor(ring["fill"][1])
g = Image.linear_gradient("L").resize(canvas.size)
fill = Image.merge("RGBA", [g.point(lambda v, a=top[i], b=bottom[i]: a + (b - a) * v // 255) for i in range(3)]
+ [Image.new("L", canvas.size, 255)])
canvas.paste(fill, (0, 0), mid)
av = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
avatar = S.avatar(d).resize((s, s), Image.LANCZOS)
av.paste(avatar, (int(cx - s / 2), int(cy - s / 2)), holder.crop((int(cx - s / 2), int(cy - s / 2), int(cx + s / 2), int(cy + s / 2))))
canvas.alpha_composite(av)
edge = ImageChops.subtract(grow(holder, lw), holder)
canvas.paste(Image.new("RGBA", canvas.size, hexcolor(ring["ink"])), (0, 0), edge)
for part in frame["parts"]:
if part.get("layer") == "front":
draw_part(canvas, part, table, d, cx, cy)
return canvas.resize((size, size), Image.LANCZOS)
def grow(mask, radius):
"""The mask grown by `radius` pixels in every direction (a real distance, so the corners are round like a stroke's join)."""
inside = np.asarray(mask) > 127
reach = ndimage.distance_transform_edt(~inside) <= radius
return Image.fromarray((reach * 255).astype("uint8"), "L")
def font(n):
for name in ("C:/Windows/Fonts/arialbd.ttf", "C:/Windows/Fonts/segoeuib.ttf"):
try:
return ImageFont.truetype(name, n)
except OSError:
pass
return None
def main() -> None:
pack = json.loads((PACK / "pack.json").read_text(encoding="utf-8"))
OUT.mkdir(parents=True, exist_ok=True)
frames = pack["frames"]
if "--grid" in sys.argv:
shapes = ("circle", "flower", "squircle", "hexagon", "heart", "triangle")
tile = 300
sheet = S.background(tile * len(shapes), tile * len(frames) + 30)
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")
return
shape = sys.argv[1] if len(sys.argv) > 1 else "flower"
tile = 540
sheet = S.background(tile * 3, tile * 2 + 60)
d = ImageDraw.Draw(sheet)
for i, frame in enumerate(frames):
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"))
if __name__ == "__main__":
main()

246
scripts/frame_sprites.py Normal file
View File

@@ -0,0 +1,246 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The sprites of the frames of the pack "basic": small transparent pictures (an ear, a lock of fur, a crown, a petal, a flame...)
that the application hangs on the outline of an avatar of any shape. Each sprite is drawn here from scratch, shaded, with a dark
outline; its "up" is the direction pointing away from the avatar.
usage (from the repository root):
py -X utf8 -B scripts/frame_sprites.py # frames/basic/*.png
"""
from __future__ import annotations
import math
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw, ImageFilter
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "frames" / "basic"
SS = 4
INK = (22, 20, 26, 255)
LINE = 5 # outline width in sprite pixels
class Sprite:
def __init__(self, w: int, h: int):
self.w, self.h = w, h
self.n = (w * SS, h * SS)
self.img = Image.new("RGBA", self.n, (0, 0, 0, 0))
self.masks = []
def mask(self, *polys, circles=()):
m = Image.new("L", self.n, 0)
d = ImageDraw.Draw(m)
for poly in polys:
d.polygon([(x * SS, y * SS) for x, y in poly], fill=255)
for (x, y, r) in circles:
d.ellipse([(x - r) * SS, (y - r) * SS, (x + r) * SS, (y + r) * SS], fill=255)
return m
def gradient(self, top, bottom):
g = Image.linear_gradient("L").resize(self.n)
chans = [g.point(lambda v, a=top[i], b=bottom[i]: a + (b - a) * v // 255) for i in range(3)]
return Image.merge("RGBA", chans + [Image.new("L", self.n, 255)])
def shade(self, mask, top, bottom, line=None, light=0.55, dark=0.2, reach=4, line_w=2):
self.masks.append(mask)
self.img.paste(self.gradient(top, bottom), (0, 0), mask)
dx = reach * SS
lit = ImageChops.subtract(mask, ImageChops.offset(mask, dx, dx)).filter(ImageFilter.GaussianBlur(SS * 0.6))
shd = ImageChops.subtract(mask, ImageChops.offset(mask, -dx, -dx)).filter(ImageFilter.GaussianBlur(SS * 0.6))
self.img.paste(Image.new("RGBA", self.n, (255, 255, 255, 255)), (0, 0), lit.point(lambda v: int(v * light)))
self.img.paste(Image.new("RGBA", self.n, (60, 30, 50, 255)), (0, 0), shd.point(lambda v: min(255, int(v * dark * 2))))
if line:
k = line_w * SS * 2 + 1
edge = ImageChops.subtract(mask.filter(ImageFilter.MaxFilter(k)), mask)
self.img.paste(Image.new("RGBA", self.n, line), (0, 0), edge.point(lambda v: min(255, v * 2)))
def draw(self):
return ImageDraw.Draw(self.img)
def save(self, name):
"""Adds the dark outline round everything drawn, then saves at the sprite's own size."""
union = self.masks[0]
for m in self.masks[1:]:
union = ImageChops.lighter(union, m)
k = LINE * SS * 2 + 1
out = union.filter(ImageFilter.MaxFilter(k))
base = Image.new("RGBA", self.n, (0, 0, 0, 0))
base.paste(Image.new("RGBA", self.n, INK), (0, 0), out)
base.alpha_composite(self.img)
OUT.mkdir(parents=True, exist_ok=True)
base.resize((self.w, self.h), Image.LANCZOS).save(OUT / name, optimize=True)
def curve(p0, p1, p2, n=16):
return [((1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * p1[0] + t * t * p2[0],
(1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * p1[1] + t * t * p2[1]) for t in (i / n for i in range(n + 1))]
def ellipse(cx, cy, rx, ry, angle=0.0, n=40):
c, s = math.cos(math.radians(angle)), math.sin(math.radians(angle))
return [(cx + rx * math.cos(2 * math.pi * i / n) * c - ry * math.sin(2 * math.pi * i / n) * s,
cy + rx * math.cos(2 * math.pi * i / n) * s + ry * math.sin(2 * math.pi * i / n) * c) for i in range(n)]
def wob(poly, amount=1.2, seed=0.0):
cx = sum(x for x, _ in poly) / len(poly)
cy = sum(y for _, y in poly) / len(poly)
out = []
for i, (x, y) in enumerate(poly):
k = math.sin(i * 0.9 + seed) * amount + math.sin(i * 0.37 + seed * 2) * amount * 0.6
dx, dy = x - cx, y - cy
ln = math.hypot(dx, dy) or 1.0
out.append((x + dx / ln * k, y + dy / ln * k))
return out
# ---------------------------------------------------------------- cat
def cat_ear():
s = Sprite(170, 160)
body = curve((16, 152), (4, 56), (86, 6), 18) + curve((86, 6), (134, 56), (156, 152), 18)[1:]
s.shade(s.mask(wob(body, 0.8, 1)), (255, 253, 250), (232, 226, 236), line=(120, 110, 130, 255), reach=5)
inner = [(86 + (x - 86) * 0.58, 146 + (y - 146) * 0.6) for x, y in body]
s.shade(s.mask(inner), (255, 190, 214), (240, 130, 172), line=(214, 96, 140, 255), light=0.35, reach=3)
s.save("cat-ear.png")
def cat_tuft():
s = Sprite(150, 130)
body = curve((10, 124), (6, 46), (112, 6), 18) + curve((112, 6), (92, 70), (132, 124), 18)[1:]
s.shade(s.mask(wob(body, 0.8, 3)), (255, 253, 250), (232, 226, 236), line=(120, 110, 130, 255), reach=4)
s.save("cat-tuft.png")
def cat_cowlick():
s = Sprite(110, 130)
body = curve((30, 124), (22, 40), (82, 10), 14) + curve((82, 10), (70, 46), (50, 34), 8)[1:] + curve((50, 34), (60, 80), (74, 124), 10)[1:]
s.shade(s.mask(wob(body, 0.6, 5)), (255, 253, 250), (232, 226, 236), line=(120, 110, 130, 255), reach=4)
s.save("cat-cowlick.png")
# ---------------------------------------------------------------- helmet
def helmet_antenna():
s = Sprite(80, 170)
s.shade(s.mask([(34, 160), (46, 160), (44, 50), (36, 50)]), (236, 240, 248), (168, 182, 206), line=(110, 120, 150, 255), reach=3)
s.shade(s.mask(circles=[(40, 36, 26)]), (255, 150, 150), (214, 50, 60), line=(130, 20, 36, 255), reach=5, light=0.7)
s.draw().ellipse([(28 - 5) * SS, (26 - 5) * SS, (28 + 4) * SS, (26 + 4) * SS], fill=(255, 255, 255, 220))
s.save("helmet-antenna.png")
def helmet_pod():
s = Sprite(110, 150)
s.shade(s.mask(), (0, 0, 0), (0, 0, 0)) # placeholder so masks is never empty
s.img = Image.new("RGBA", s.n, (0, 0, 0, 0))
s.masks = []
body = s.mask(circles=[])
d = ImageDraw.Draw(body)
d.rounded_rectangle([14 * SS, 12 * SS, 96 * SS, 140 * SS], radius=30 * SS, fill=255)
s.shade(body, (236, 240, 248), (168, 182, 206), line=(110, 120, 150, 255), reach=5)
orange = s.mask()
ImageDraw.Draw(orange).rounded_rectangle([36 * SS, 38 * SS, 74 * SS, 112 * SS], radius=14 * SS, fill=255)
s.shade(orange, (255, 190, 100), (240, 120, 30), line=(150, 70, 10, 255), reach=3)
s.save("helmet-pod.png")
def helmet_collar():
s = Sprite(300, 100)
s.img = Image.new("RGBA", s.n, (0, 0, 0, 0))
body = Image.new("L", s.n, 0)
ImageDraw.Draw(body).rounded_rectangle([10 * SS, 8 * SS, 290 * SS, 92 * SS], radius=36 * SS, fill=255)
s.shade(body, (236, 240, 248), (168, 182, 206), line=(110, 120, 150, 255), reach=6)
stripe = Image.new("L", s.n, 0)
ImageDraw.Draw(stripe).rounded_rectangle([34 * SS, 52 * SS, 266 * SS, 74 * SS], radius=11 * SS, fill=255)
s.shade(stripe, (255, 190, 100), (240, 120, 30), line=(150, 70, 10, 255), reach=3)
d = s.draw()
for gx in range(60, 250, 46):
d.line([gx * SS, 18 * SS, gx * SS, 40 * SS], fill=(150, 165, 190, 255), width=5 * SS)
s.save("helmet-collar.png")
def helmet_glare():
s = Sprite(220, 220)
g = Image.new("L", s.n, 0)
d = ImageDraw.Draw(g)
d.arc([20 * SS, 20 * SS, 200 * SS, 200 * SS], start=200, end=262, fill=255, width=24 * SS)
d.arc([20 * SS, 20 * SS, 200 * SS, 200 * SS], start=272, end=292, fill=255, width=24 * SS)
s.img.paste(Image.new("RGBA", s.n, (255, 255, 255, 150)), (0, 0), g)
s.img.resize((s.w, s.h), Image.LANCZOS).save(OUT / "helmet-glare.png", optimize=True)
# ---------------------------------------------------------------- crown
def crown():
s = Sprite(340, 230)
body = [(30, 214), (14, 70), (62, 104), (118, 150), (170, 70), (170, 62), (222, 150), (278, 104), (326, 70), (310, 214)]
body = [(30, 214), (20, 70), (70, 112), (118, 150), (170, 40), (222, 150), (270, 112), (320, 70), (310, 214)]
s.shade(s.mask(wob(body, 0.8, 1)), (255, 240, 150), (240, 172, 30), line=(150, 92, 10, 255), reach=6)
inner = [(52, 206), (44, 100), (96, 142), (170, 70), (244, 142), (296, 100), (288, 206)]
s.shade(s.mask(wob(inner, 0.8, 4)), (255, 250, 200), (255, 206, 80), reach=4, light=0.35)
band = s.mask()
ImageDraw.Draw(band).rounded_rectangle([22 * SS, 178 * SS, 318 * SS, 222 * SS], radius=16 * SS, fill=255)
s.shade(band, (255, 226, 110), (214, 128, 16), line=(150, 92, 10, 255), reach=5)
for (x, y, r, a, b) in ((20, 66, 20, (255, 130, 150), (204, 34, 72)), (170, 34, 24, (140, 214, 255), (36, 112, 214)),
(320, 66, 20, (255, 130, 150), (204, 34, 72))):
s.shade(s.mask(circles=[(x, y, r)]), a, b, line=(110, 20, 50, 255), reach=5, light=0.7)
s.draw().ellipse([(x - r * 0.5) * SS, (y - r * 0.55) * SS, (x - r * 0.12) * SS, (y - r * 0.2) * SS], fill=(255, 255, 255, 230))
for gx in (80, 125, 170, 215, 260):
s.shade(s.mask(circles=[(gx, 200, 9)]), (255, 255, 255), (214, 210, 232), line=(120, 100, 130, 255), reach=3, line_w=1)
s.save("crown.png")
# ---------------------------------------------------------------- flower
def petal(name, top, bottom, line, heart_top, heart_bottom):
s = Sprite(150, 190)
body = ellipse(75, 100, 62, 84, 0, 44)
s.shade(s.mask(wob(body, 1.2, 2)), top, bottom, line=line, reach=5)
inner = ellipse(75, 108, 36, 54, 0, 36)
s.shade(s.mask(wob(inner, 0.8, 5)), heart_top, heart_bottom, line=None, reach=4, light=0.3)
d = s.draw()
for off in (-14, 0, 14):
d.line([(75 + off * 0.4) * SS, 150 * SS, (75 + off * 0.1) * SS, 66 * SS], fill=line[:3] + (170,), width=3 * SS)
s.save(name)
# ---------------------------------------------------------------- flame
def flame(name, h, w, lean):
s = Sprite(w, h)
cx = w / 2
def tongue(scale, base_y, k):
width = (w / 2 - 8) * scale
height = (h - 16) * k
a, b = (cx - width, base_y), (cx + width, base_y)
tip = (cx + lean * scale, base_y - height)
return curve(a, (cx - width * 1.35, base_y - height * 0.45), tip, 16) + curve(tip, (cx + width * 1.15, base_y - height * 0.5), b, 16)[1:]
s.shade(s.mask(wob(tongue(1.0, h - 4, 1.0), 1.3, 1)), (255, 150, 60), (214, 44, 28), line=(130, 24, 16, 255), reach=5, light=0.4)
s.shade(s.mask(wob(tongue(0.68, h - 6, 0.7), 1.0, 2)), (255, 214, 90), (255, 130, 32), line=(214, 84, 16, 255), reach=4, light=0.4)
s.shade(s.mask(wob(tongue(0.36, h - 8, 0.4), 0.8, 3)), (255, 252, 214), (255, 214, 96), reach=3, light=0.3)
s.save(name)
def main() -> None:
cat_ear()
cat_tuft()
cat_cowlick()
helmet_antenna()
helmet_pod()
helmet_collar()
helmet_glare()
crown()
petal("petal-back.png", (255, 168, 204), (226, 92, 148), (176, 58, 112, 255), (255, 214, 232), (255, 168, 204))
petal("petal-front.png", (255, 230, 240), (255, 176, 210), (214, 96, 150, 255), (255, 244, 248), (255, 206, 226))
flame("flame-tall.png", 210, 120, 8)
flame("flame-mid.png", 160, 110, -6)
flame("flame-short.png", 110, 96, 4)
for p in sorted(OUT.glob("*.png")):
print(p.name, p.stat().st_size)
if __name__ == "__main__":
main()

448
scripts/make_frame_cat.py Normal file
View File

@@ -0,0 +1,448 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Profile frame "Ушки": a ring round the avatar with two ears, tufts of fur on the cheeks and a cowlick, sticker style
(black outline, white fur, pink inside the ears). The shape is drawn here from scratch.
A second frame, "Скафандр", is drawn the same way: a round helmet with a collar, side pieces, an antenna and rivets, and a glare
on the glass over the avatar.
usage (from the repository root):
py -X utf8 -B scripts/make_frame_cat.py # work/frames/cat.png, helmet.png (transparent) and the two previews
"""
from __future__ import annotations
import math
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "work" / "frames"
SIZE = 1024
SS = 2 # supersampling
CX, CY = 512, 580 # centre of the avatar
HOLE = 290 # radius of the avatar window
RING = 332 # outer radius of the ring
LINE = 9 # outline width at SIZE
def pt(theta: float, r: float):
a = math.radians(theta)
return (CX + r * math.cos(a), CY - r * math.sin(a))
def curve(p0, p1, p2, n=18):
"""A quadratic curve p0 -> p2 bent towards p1."""
return [((1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * p1[0] + t * t * p2[0],
(1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * p1[1] + t * t * p2[1]) for t in (i / n for i in range(n + 1))]
def ear(side: int):
"""side -1 = left ear, +1 = right ear: the outer edge bulges, the inner edge is nearly straight."""
if side < 0:
base_out, base_in, tip = pt(134, 312), pt(100, 312), pt(116, 600)
else:
base_out, base_in, tip = pt(46, 312), pt(80, 312), pt(64, 600)
bend_out = (base_out[0] + side * 22, (base_out[1] + tip[1]) / 2 + 20)
bend_in = ((base_in[0] + tip[0]) / 2 - side * 2, (base_in[1] + tip[1]) / 2 + 6)
return curve(base_out, bend_out, tip) + curve(tip, bend_in, base_in)[1:]
def inner_ear(side: int):
"""The pink inside of the ear: the ear itself shrunk towards the middle of its base, so the white rim is even all round."""
outer = ear(side)
anchor = pt(118 if side < 0 else 62, 322)
k = 0.64
return [(anchor[0] + (x - anchor[0]) * k, anchor[1] + (y - anchor[1]) * k) for x, y in outer]
def tuft(theta: float, length: float, lean: float, width: float = 13):
"""A pointed lock of fur growing out of the ring at theta, leaning by `lean` degrees."""
a = pt(theta - width, RING - 25)
b = pt(theta + width, RING - 25)
tip = pt(theta + lean, RING + length)
return curve(a, ((a[0] + tip[0]) / 2 + 22, (a[1] + tip[1]) / 2 - 14), tip, 10) + curve(tip, ((b[0] + tip[0]) / 2 - 2, (b[1] + tip[1]) / 2 + 12), b, 10)[1:]
def shapes():
out = []
for side in (-1, 1):
out.append(ear(side))
# cheeks: three locks each side, the lower ones lean down
for theta, length, lean in ((162, 70, 10), (184, 78, 4), (206, 66, -4)):
out.append(tuft(theta, length, lean))
out.append(tuft(180 - theta, length, -lean))
# cowlick between the ears
out.append(curve(pt(98, RING - 30), pt(88, 470), pt(70, 402), 12) + curve(pt(70, 402), pt(86, 420), pt(80, RING - 28), 12)[1:])
return out
def build() -> Image.Image:
n = SIZE * SS
scale = lambda poly: [(x * SS, y * SS) for x, y in poly] # noqa: E731
mask = Image.new("L", (n, n), 0)
d = ImageDraw.Draw(mask)
d.ellipse([(CX - RING) * SS, (CY - RING) * SS, (CX + RING) * SS, (CY + RING) * SS], fill=255)
for poly in shapes():
d.polygon(scale(poly), fill=255)
k = LINE * SS * 2 + 1
outline = mask.filter(ImageFilter.MaxFilter(k if k % 2 else k + 1))
img = Image.new("RGBA", (n, n), (0, 0, 0, 0))
img.paste(Image.new("RGBA", (n, n), (22, 20, 26, 255)), (0, 0), outline)
img.paste(Image.new("RGBA", (n, n), (255, 252, 250, 255)), (0, 0), mask)
d = ImageDraw.Draw(img)
for side in (-1, 1): # pink inside the ears, with a thin outline
poly = scale(inner_ear(side))
d.polygon(poly, fill=(255, 176, 204, 255))
d.line(poly + [poly[0]], fill=(214, 110, 150, 255), width=LINE * SS // 3, joint="curve")
# the window of the avatar, with its own outline
hole = Image.new("L", (n, n), 0)
ImageDraw.Draw(hole).ellipse([(CX - HOLE) * SS, (CY - HOLE) * SS, (CX + HOLE) * SS, (CY + HOLE) * SS], fill=255)
ring_line = Image.new("L", (n, n), 0)
ImageDraw.Draw(ring_line).ellipse([(CX - HOLE - LINE) * SS, (CY - HOLE - LINE) * SS,
(CX + HOLE + LINE) * SS, (CY + HOLE + LINE) * SS], fill=255)
img.paste(Image.new("RGBA", (n, n), (22, 20, 26, 255)), (0, 0), ring_line)
clear = Image.new("RGBA", (n, n), (0, 0, 0, 0))
img.paste(clear, (0, 0), hole)
return img.resize((SIZE, SIZE), Image.LANCZOS)
def build_helmet() -> Image.Image:
n = SIZE * SS
ring = 352
sc = lambda v: v * SS # noqa: E731
mask = Image.new("L", (n, n), 0)
d = ImageDraw.Draw(mask)
d.ellipse([sc(CX - ring), sc(CY - ring), sc(CX + ring), sc(CY + ring)], fill=255)
for side in (-1, 1): # side pieces of the helmet
x = CX + side * (ring - 6)
d.rounded_rectangle([sc(x - 34), sc(CY - 74), sc(x + 34), sc(CY + 74)], radius=sc(30), fill=255)
d.rounded_rectangle([sc(CX - 290), sc(CY + ring - 40), sc(CX + 290), sc(CY + ring + 74)], radius=sc(44), fill=255) # collar
ax, ay = pt(52, ring - 10) # antenna
tx, ty = pt(52, ring + 120)
d.line([sc(ax), sc(ay), sc(tx), sc(ty)], fill=255, width=sc(14))
d.ellipse([sc(tx - 24), sc(ty - 24), sc(tx + 24), sc(ty + 24)], fill=255)
k = LINE * SS * 2 + 1
outline = mask.filter(ImageFilter.MaxFilter(k if k % 2 else k + 1))
ink, metal = (22, 20, 26, 255), (226, 233, 242, 255)
img = Image.new("RGBA", (n, n), (0, 0, 0, 0))
img.paste(Image.new("RGBA", (n, n), ink), (0, 0), outline)
img.paste(Image.new("RGBA", (n, n), metal), (0, 0), mask)
d = ImageDraw.Draw(img)
# shading on the lower right of the ring, so it reads as a rounded metal
shade = Image.new("L", (n, n), 0)
sd = ImageDraw.Draw(shade)
sd.ellipse([sc(CX - ring + 26), sc(CY - ring + 26), sc(CX + ring + 40), sc(CY + ring + 40)], fill=255)
sd.ellipse([sc(CX - ring - 10), sc(CY - ring - 10), sc(CX + ring - 26), sc(CY + ring - 26)], fill=0)
img.paste(Image.new("RGBA", (n, n), (160, 176, 200, 255)), (0, 0), Image.composite(shade, Image.new("L", (n, n), 0), mask))
# orange stripe on the collar, grooves, side pieces
d.rounded_rectangle([sc(CX - 250), sc(CY + ring + 8), sc(CX + 250), sc(CY + ring + 34)], radius=sc(12), fill=(255, 150, 60, 255), outline=ink, width=sc(4))
for gx in range(-210, 211, 70):
d.line([sc(CX + gx), sc(CY + ring - 24), sc(CX + gx), sc(CY + ring + 2)], fill=(150, 165, 190, 255), width=sc(6))
for side in (-1, 1):
x = CX + side * (ring - 6)
d.rounded_rectangle([sc(x - 16), sc(CY - 40), sc(x + 16), sc(CY + 40)], radius=sc(12), fill=(255, 150, 60, 255), outline=ink, width=sc(4))
d.ellipse([sc(tx - 14), sc(ty - 14), sc(tx + 14), sc(ty + 14)], fill=(255, 90, 90, 255))
# rivets round the ring
for theta in range(0, 360, 20):
if 218 <= theta <= 322:
continue # hidden behind the collar
x, y = pt(theta, (HOLE + ring) / 2 + 4)
d.ellipse([sc(x - 8), sc(y - 8), sc(x + 8), sc(y + 8)], fill=(150, 165, 190, 255), outline=ink, width=sc(3))
# the window: dark rim round the glass
hole = Image.new("L", (n, n), 0)
ImageDraw.Draw(hole).ellipse([sc(CX - HOLE), sc(CY - HOLE), sc(CX + HOLE), sc(CY + HOLE)], fill=255)
rim = Image.new("L", (n, n), 0)
ImageDraw.Draw(rim).ellipse([sc(CX - HOLE - 22), sc(CY - HOLE - 22), sc(CX + HOLE + 22), sc(CY + HOLE + 22)], fill=255)
img.paste(Image.new("RGBA", (n, n), (48, 56, 84, 255)), (0, 0), rim)
inner = Image.new("L", (n, n), 0)
ImageDraw.Draw(inner).ellipse([sc(CX - HOLE - 12), sc(CY - HOLE - 12), sc(CX + HOLE + 12), sc(CY + HOLE + 12)], fill=255)
img.paste(Image.new("RGBA", (n, n), (48, 56, 84, 255)), (0, 0), inner)
img.paste(Image.new("RGBA", (n, n), (0, 0, 0, 0)), (0, 0), hole)
# glare on the glass: it lies over the avatar, so it is drawn last and kept light
glare = Image.new("RGBA", (n, n), (0, 0, 0, 0))
gd = ImageDraw.Draw(glare)
gd.arc([sc(CX - HOLE + 40), sc(CY - HOLE + 40), sc(CX + HOLE - 40), sc(CY + HOLE - 40)], start=200, end=262, fill=(255, 255, 255, 150), width=sc(26))
gd.arc([sc(CX - HOLE + 40), sc(CY - HOLE + 40), sc(CX + HOLE - 40), sc(CY + HOLE - 40)], start=272, end=290, fill=(255, 255, 255, 150), width=sc(26))
img.alpha_composite(glare)
return img.resize((SIZE, SIZE), Image.LANCZOS)
INK = (22, 20, 26, 255)
def ellipse_poly(cx, cy, rx, ry, angle_deg, n=36):
c, s_ = math.cos(math.radians(angle_deg)), math.sin(math.radians(angle_deg))
out = []
for i in range(n):
t = 2 * math.pi * i / n
x, y = rx * math.cos(t), ry * math.sin(t)
out.append((cx + x * c - y * s_, cy + x * s_ + y * c))
return out
def lock(theta, r0, length, width, lean=0.0):
"""A pointed tongue growing outwards from the ring at theta (flame, leaf): a bulging belly and a tip."""
a, b = pt(theta - width, r0), pt(theta + width, r0)
tip = pt(theta + lean, r0 + length)
mid_l, mid_r = pt(theta - width * 1.5, r0 + length * 0.45), pt(theta + width * 1.2, r0 + length * 0.5)
return curve(a, mid_l, tip, 14) + curve(tip, mid_r, b, 14)[1:]
def make_frame(ring, base, shapes_fn, paint_fn, rim=INK, rim_width=0):
"""Common recipe: shapes -> outline -> base colour -> details -> window cut with its own rim."""
n = SIZE * SS
sc = lambda poly: [(x * SS, y * SS) for x, y in poly] # noqa: E731
mask = Image.new("L", (n, n), 0)
d = ImageDraw.Draw(mask)
d.ellipse([(CX - ring) * SS, (CY - ring) * SS, (CX + ring) * SS, (CY + ring) * SS], fill=255)
for poly in shapes_fn():
d.polygon(sc(poly), fill=255)
k = LINE * SS * 2 + 1
outline = mask.filter(ImageFilter.MaxFilter(k if k % 2 else k + 1))
img = Image.new("RGBA", (n, n), (0, 0, 0, 0))
img.paste(Image.new("RGBA", (n, n), INK), (0, 0), outline)
img.paste(Image.new("RGBA", (n, n), base), (0, 0), mask)
d = ImageDraw.Draw(img)
paint_fn(d, sc)
pad = LINE + rim_width
ring_line = Image.new("L", (n, n), 0)
ImageDraw.Draw(ring_line).ellipse([(CX - HOLE - pad) * SS, (CY - HOLE - pad) * SS, (CX + HOLE + pad) * SS, (CY + HOLE + pad) * SS], fill=255)
img.paste(Image.new("RGBA", (n, n), INK), (0, 0), ring_line)
if rim_width:
inner = Image.new("L", (n, n), 0)
ImageDraw.Draw(inner).ellipse([(CX - HOLE - rim_width) * SS, (CY - HOLE - rim_width) * SS, (CX + HOLE + rim_width) * SS, (CY + HOLE + rim_width) * SS], fill=255)
img.paste(Image.new("RGBA", (n, n), rim), (0, 0), inner)
hole = Image.new("L", (n, n), 0)
ImageDraw.Draw(hole).ellipse([(CX - HOLE) * SS, (CY - HOLE) * SS, (CX + HOLE) * SS, (CY + HOLE) * SS], fill=255)
img.paste(Image.new("RGBA", (n, n), (0, 0, 0, 0)), (0, 0), hole)
return img.resize((SIZE, SIZE), Image.LANCZOS)
# --- the three richer frames: every element is shaded (gradient, light on the upper left, shadow on the lower right) ---
N = SIZE * SS
def wob(poly, amount=3.0, seed=0.0):
"""A hand-drawn feel: the outline is pushed in and out a little by a slow wave."""
cx = sum(x for x, _ in poly) / len(poly)
cy = sum(y for _, y in poly) / len(poly)
out = []
for i, (x, y) in enumerate(poly):
k = math.sin(i * 0.9 + seed) * amount + math.sin(i * 0.37 + seed * 2) * amount * 0.6
dx, dy = x - cx, y - cy
ln = math.hypot(dx, dy) or 1.0
out.append((x + dx / ln * k, y + dy / ln * k))
return out
def mask_of(*polys, circles=()):
m = Image.new("L", (N, N), 0)
d = ImageDraw.Draw(m)
for poly in polys:
d.polygon([(x * SS, y * SS) for x, y in poly], fill=255)
for (x, y, r) in circles:
d.ellipse([(x - r) * SS, (y - r) * SS, (x + r) * SS, (y + r) * SS], fill=255)
return m
def union(masks):
out = masks[0]
for m in masks[1:]:
out = ImageChops.lighter(out, m)
return out
def gradient(top, bottom):
g = Image.linear_gradient("L").resize((N, N))
return Image.merge("RGBA", [g.point(lambda v, a=top[i], b=bottom[i]: a + (b - a) * v // 255) for i in range(3)]
+ [Image.new("L", (N, N), 255)])
def shade(img, mask, top, bottom, line=None, light=0.6, dark=0.22, reach=7, line_w=3):
"""Paint one element: gradient fill, light edge on the upper left, shadow edge on the lower right, a thin darker line."""
img.paste(gradient(top, bottom), (0, 0), mask)
dx = reach * SS
lit = ImageChops.subtract(mask, ImageChops.offset(mask, dx, dx)).filter(ImageFilter.GaussianBlur(SS))
shd = ImageChops.subtract(mask, ImageChops.offset(mask, -dx, -dx)).filter(ImageFilter.GaussianBlur(SS))
img.paste(Image.new("RGBA", (N, N), (255, 255, 255, 255)), (0, 0), lit.point(lambda v: int(v * light)))
img.paste(Image.new("RGBA", (N, N), (60, 20, 40, 255)), (0, 0), shd.point(lambda v: min(255, int(v * dark * 2))))
if line:
k = line_w * SS * 2 + 1
edge = ImageChops.subtract(mask.filter(ImageFilter.MaxFilter(k)), mask)
img.paste(Image.new("RGBA", (N, N), line), (0, 0), edge.point(lambda v: min(255, v * 2)))
def finish_frame(img, silhouette, ring_color=INK):
"""Black outline round the whole silhouette (under everything), then the window cut with a thin rim."""
k = LINE * SS * 2 + 1
out = silhouette.filter(ImageFilter.MaxFilter(k))
base = Image.new("RGBA", (N, N), (0, 0, 0, 0))
base.paste(Image.new("RGBA", (N, N), INK), (0, 0), out)
base.alpha_composite(img)
rim = Image.new("L", (N, N), 0)
ImageDraw.Draw(rim).ellipse([(CX - HOLE - LINE) * SS, (CY - HOLE - LINE) * SS,
(CX + HOLE + LINE) * SS, (CY + HOLE + LINE) * SS], fill=255)
base.paste(Image.new("RGBA", (N, N), ring_color), (0, 0), rim)
hole = Image.new("L", (N, N), 0)
ImageDraw.Draw(hole).ellipse([(CX - HOLE) * SS, (CY - HOLE) * SS, (CX + HOLE) * SS, (CY + HOLE) * SS], fill=255)
base.paste(Image.new("RGBA", (N, N), (0, 0, 0, 0)), (0, 0), hole)
return base.resize((SIZE, SIZE), Image.LANCZOS)
def ring_mask(r):
m = Image.new("L", (N, N), 0)
ImageDraw.Draw(m).ellipse([(CX - r) * SS, (CY - r) * SS, (CX + r) * SS, (CY + r) * SS], fill=255)
return m
def star(x, y, r, spin=0.0):
pts = []
for i in range(8):
a = math.radians(i * 45 + spin)
rr = r if i % 2 == 0 else r * 0.28
pts.append((x + rr * math.cos(a), y + rr * math.sin(a)))
return pts
def build_flower() -> Image.Image:
img = Image.new("RGBA", (N, N), (0, 0, 0, 0))
back, front = [], []
for i in range(12):
th = i * 30
back.append(wob(ellipse_poly(*pt(th, 372), 92, 64, -th, 40), 2.6, i))
front.append(wob(ellipse_poly(*pt(th + 15, 352), 74, 52, -(th + 15), 40), 2.2, i + 5))
silhouette = union([mask_of(*back), mask_of(*front), ring_mask(340)])
for poly in back:
shade(img, mask_of(poly), (255, 168, 204), (226, 92, 148), line=(176, 58, 112, 255))
for poly in front:
shade(img, mask_of(poly), (255, 226, 238), (255, 168, 204), line=(214, 96, 150, 255))
d = ImageDraw.Draw(img)
for i in range(12): # veins
th = i * 30 + 15
for off in (-7, 0, 7):
a, b = pt(th + off * 0.5, 332), pt(th + off * 0.18, 392)
d.line([a[0] * SS, a[1] * SS, b[0] * SS, b[1] * SS], fill=(226, 120, 168, 200), width=3 * SS)
shade(img, ring_mask(340), (255, 246, 214), (255, 196, 96), line=(186, 120, 30, 255), reach=9)
shade(img, ring_mask(312), (255, 228, 120), (240, 160, 40), line=(186, 120, 30, 255), reach=6, light=0.5)
for th in range(0, 360, 15): # pearls on the golden ring
x, y = pt(th, 326)
shade(img, mask_of(circles=[(x, y, 7)]), (255, 255, 255), (220, 214, 230), line=(150, 120, 140, 255), reach=3, line_w=2)
return finish_frame(img, silhouette)
def build_crown() -> Image.Image:
img = Image.new("RGBA", (N, N), (0, 0, 0, 0))
body = wob([(322, 296), (308, 130), (354, 164), (418, 222), (466, 150), (512, 84), (558, 150), (606, 222), (670, 164),
(716, 130), (702, 296)], 2.2, 1)
band = wob([(CX - 196, 268), (CX + 196, 268), (CX + 204, 322), (CX - 204, 322)], 1.6, 3)
gems = [(308, 124, 26, (255, 130, 150), (204, 34, 72)), (512, 80, 30, (140, 214, 255), (36, 112, 214)),
(716, 124, 26, (255, 130, 150), (204, 34, 72))]
silhouette = union([mask_of(body), mask_of(band), ring_mask(340), mask_of(circles=[(x, y, r + 4) for x, y, r, _, _ in gems])])
shade(img, ring_mask(340), (255, 238, 150), (236, 160, 24), line=(150, 92, 10, 255), reach=10)
shade(img, ring_mask(312), (255, 214, 90), (226, 138, 20), line=(150, 92, 10, 255), reach=6, light=0.4)
shade(img, mask_of(body), (255, 240, 150), (240, 172, 30), line=(150, 92, 10, 255), reach=9)
inner = wob([(344, 286), (336, 178), (420, 244), (512, 120), (604, 244), (688, 178), (680, 286)], 1.8, 7)
shade(img, mask_of(inner), (255, 250, 200), (255, 206, 80), line=None, reach=6, light=0.35)
shade(img, mask_of(band), (255, 226, 110), (214, 128, 16), line=(150, 92, 10, 255), reach=7)
for gx in (-132, -66, 0, 66, 132): # pearls on the band
shade(img, mask_of(circles=[(CX + gx, 295, 15)]), (255, 255, 255), (214, 210, 232), line=(120, 100, 130, 255), reach=4, line_w=2)
for (x, y, r, a, b) in gems:
shade(img, mask_of(circles=[(x, y, r)]), a, b, line=(110, 20, 50, 255), reach=7, light=0.7)
d = ImageDraw.Draw(img)
d.ellipse([(x - r * 0.5) * SS, (y - r * 0.55) * SS, (x - r * 0.12) * SS, (y - r * 0.2) * SS], fill=(255, 255, 255, 230))
for th in range(0, 360, 20): # rivets
if 56 <= th <= 124:
continue
x, y = pt(th, 326)
shade(img, mask_of(circles=[(x, y, 8)]), (255, 232, 140), (190, 120, 16), line=(120, 70, 10, 255), reach=3, line_w=2)
d = ImageDraw.Draw(img)
for (x, y, r, spin) in ((250, 190, 30, 0), (790, 220, 24, 20), (610, 60, 20, 10)): # sparkles
poly = [(px * SS, py * SS) for px, py in star(x, y, r, spin)]
d.polygon(poly, fill=(255, 252, 220, 255), outline=(150, 92, 10, 255))
return finish_frame(img, silhouette)
def build_flame() -> Image.Image:
img = Image.new("RGBA", (N, N), (0, 0, 0, 0))
rnd = [0.9, 1.15, 0.8, 1.2, 1.0, 1.25, 0.85, 1.1, 0.95, 1.2, 0.8, 1.05, 0.9, 1.1, 0.85, 1.2, 0.95, 1.0, 0.8, 1.15, 1.0]
spec = []
for i, theta in enumerate(range(-30, 211, 12)):
up = max(0.0, math.sin(math.radians(theta)))
length = (96 + 120 * up) * rnd[i % len(rnd)]
spec.append((theta, length, 9 + 3 * up, (-1) ** i * (5 + 4 * up)))
outer = [wob(lock(t, 300, ln, w, lean), 2.4, t) for t, ln, w, lean in spec]
mid = [wob(lock(t, 306, ln * 0.7, w * 0.72, lean * 0.7), 1.8, t + 3) for t, ln, w, lean in spec]
core = [wob(lock(t, 312, ln * 0.4, w * 0.45, lean * 0.4), 1.4, t + 7) for t, ln, w, lean in spec]
sparks = []
for (x, y, sz, tilt) in ((196, 150, 17, 30), (842, 190, 15, -35), (120, 330, 13, 20), (900, 430, 14, -20), (360, 70, 13, 10)):
sparks.append(wob(ellipse_poly(x, y, sz * 1.6, sz * 0.8, tilt, 24), 0.8, x))
silhouette = union([mask_of(*outer), mask_of(*sparks), ring_mask(340)])
for poly in outer:
shade(img, mask_of(poly), (255, 150, 60), (214, 44, 28), line=(130, 24, 16, 255), reach=7, light=0.4)
for poly in mid:
shade(img, mask_of(poly), (255, 214, 90), (255, 130, 32), line=(214, 84, 16, 255), reach=5, light=0.4, line_w=2)
for poly in core:
shade(img, mask_of(poly), (255, 252, 214), (255, 214, 96), line=None, reach=4, light=0.3)
for poly in sparks:
shade(img, mask_of(poly), (255, 246, 190), (255, 168, 40), line=(214, 84, 16, 255), reach=3, light=0.3, line_w=2)
shade(img, ring_mask(340), (255, 160, 70), (206, 40, 28), line=(130, 24, 16, 255), reach=9)
shade(img, ring_mask(314), (255, 214, 96), (255, 124, 30), line=(214, 84, 16, 255), reach=6, light=0.5)
return finish_frame(img, silhouette)
def preview(frame: Image.Image, title: str, subtitle: str) -> Image.Image:
w, h = 1080, 1350
bg = Image.new("RGBA", (w, h), (255, 236, 196, 255))
d = ImageDraw.Draw(bg)
for gx in range(0, w, 60):
for gy in range(0, h, 60):
d.ellipse([gx, gy, gx + 5, gy + 5], fill=(240, 214, 160, 255))
avatar = Image.new("RGBA", (2 * HOLE, 2 * HOLE), (0, 0, 0, 0))
ad = ImageDraw.Draw(avatar)
for i in range(2 * HOLE): # a soft gradient stands in for a photo
t = i / (2 * HOLE)
ad.line([(0, i), (2 * HOLE, i)], fill=(int(120 + 100 * t), int(150 - 30 * t), int(230 - 80 * t), 255))
ad.ellipse([HOLE - 90, HOLE - 150, HOLE + 90, HOLE + 30], fill=(255, 230, 210, 255))
ad.ellipse([HOLE - 190, HOLE + 70, HOLE + 190, HOLE + 520], fill=(255, 230, 210, 255))
m = Image.new("L", avatar.size, 0)
ImageDraw.Draw(m).ellipse([0, 0, 2 * HOLE - 1, 2 * HOLE - 1], fill=255)
layer = Image.new("RGBA", (SIZE, SIZE), (0, 0, 0, 0))
layer.paste(avatar, (CX - HOLE, CY - HOLE), m)
layer.alpha_composite(frame)
bg.alpha_composite(layer.resize((900, 900), Image.LANCZOS), (90, 90))
font = None
for name in ("C:/Windows/Fonts/arialbd.ttf", "C:/Windows/Fonts/segoeuib.ttf"):
try:
font = ImageFont.truetype(name, 54)
break
except OSError:
pass
d = ImageDraw.Draw(bg)
d.text((w / 2, 1090), title, font=font, fill=(40, 30, 40, 255), anchor="mm")
d.text((w / 2, 1170), subtitle, font=font, fill=(150, 90, 110, 255), anchor="mm")
return bg
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
frame = build()
frame.save(OUT / "cat.png")
preview(frame, "Рамка «Ушки»", "уши, шерсть на щеках и хохолок").convert("RGB").save(OUT / "cat_preview.png")
helmet = build_helmet()
helmet.save(OUT / "helmet.png")
preview(helmet, "Рамка «Скафандр»", "шлем, антенна, блик на стекле").convert("RGB").save(OUT / "helmet_preview.png")
for name, title, sub, fn in (("flower", "Рамка «Цветок»", "двенадцать лепестков, как наш логотип", build_flower),
("crown", "Рамка «Корона»", "золотой обод, три камня", build_crown),
("flame", "Рамка «Пламя»", "под огоньки стрика", build_flame)):
frame_img = fn()
frame_img.save(OUT / (name + ".png"))
preview(frame_img, title, sub).convert("RGB").save(OUT / (name + "_preview.png"))
print(OUT / "cat.png")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,128 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Shows a frame on an avatar of each shape the mod knows (the outlines are those of Shapes.java), as it is drawn in the application:
the avatar keeps the window of the frame, the shape lies inside the circle of that window.
usage (from the repository root):
py -X utf8 -B scripts/make_frame_on_shape.py [frame] # work/frames/<frame>_on_flower.png and <frame>_on_shapes.png
"""
from __future__ import annotations
import math
import sys
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
ROOT = Path(__file__).resolve().parents[1]
FRAMES = ROOT / "work" / "frames"
CX, CY, HOLE = 512, 580, 290
SS = 4
def shape_polys(name, s):
"""Outlines as polygons in a box of side s (the shape sits in the middle square), like Shapes.path."""
pts = []
if name == "flower":
return [("circle", 0.5 * s, 0.5 * s, 0.31 * s)] + [
("circle", s * (0.5 + 0.31 * math.cos(p * math.pi / 3 - math.pi / 2)),
s * (0.5 + 0.31 * math.sin(p * math.pi / 3 - math.pi / 2)), 0.19 * s) for p in range(6)]
if name == "squircle":
return [("round", 0, 0, s, 0.34 * s)]
if name == "hexagon":
pts = [(s * (0.5 + 0.5 * math.cos(math.pi / 6 + c * math.pi / 3 - math.pi / 2 + math.pi / 6)),
s * (0.5 + 0.5 * math.sin(math.pi / 6 + c * math.pi / 3 - math.pi / 2 + math.pi / 6))) for c in range(6)]
elif name == "heart":
def bez(p0, p1, p2, p3, n=24):
return [((1 - t) ** 3 * p0[0] + 3 * (1 - t) ** 2 * t * p1[0] + 3 * (1 - t) * t * t * p2[0] + t ** 3 * p3[0],
(1 - t) ** 3 * p0[1] + 3 * (1 - t) ** 2 * t * p1[1] + 3 * (1 - t) * t * t * p2[1] + t ** 3 * p3[1])
for t in (i / n for i in range(n + 1))]
k = lambda a, b: (a * s, b * s) # noqa: E731
pts = (bez(k(.5, .94), k(.10, .62), k(.02, .40), k(.10, .24)) + bez(k(.10, .24), k(.18, .08), k(.40, .06), k(.5, .27))
+ bez(k(.5, .27), k(.60, .06), k(.82, .08), k(.90, .24)) + bez(k(.90, .24), k(.98, .40), k(.90, .62), k(.5, .94)))
elif name == "triangle":
pts = [(0.5 * s, 0.05 * s), (0.96 * s, 0.86 * s), (0.04 * s, 0.86 * s)]
else:
return [("circle", 0.5 * s, 0.5 * s, 0.5 * s)]
return [("poly", pts)]
def shape_mask(name, s):
m = Image.new("L", (s * SS, s * SS), 0)
d = ImageDraw.Draw(m)
for item in shape_polys(name, s * SS):
if item[0] == "circle":
_, x, y, r = item
d.ellipse([x - r, y - r, x + r, y + r], fill=255)
elif item[0] == "round":
_, x, y, side, rad = item
d.rounded_rectangle([x, y, x + side, y + side], radius=rad, fill=255)
else:
d.polygon(item[1], fill=255)
return m.resize((s, s), Image.LANCZOS)
def avatar(s):
"""A stand-in picture: a gradient with a head and shoulders."""
img = Image.new("RGBA", (s, s))
d = ImageDraw.Draw(img)
for i in range(s):
t = i / s
d.line([(0, i), (s, i)], fill=(int(120 + 100 * t), int(150 - 30 * t), int(230 - 80 * t), 255))
d.ellipse([s * 0.34, s * 0.2, s * 0.66, s * 0.52], fill=(255, 230, 210, 255))
d.ellipse([s * 0.14, s * 0.58, s * 0.86, s * 1.3], fill=(255, 230, 210, 255))
return img
def compose(frame: Image.Image, shape: str) -> Image.Image:
s = HOLE * 2
layer = Image.new("RGBA", frame.size, (0, 0, 0, 0))
layer.paste(avatar(s), (CX - s // 2, CY - s // 2), shape_mask(shape, s))
layer.alpha_composite(frame)
return layer
def font(size):
for name in ("C:/Windows/Fonts/arialbd.ttf", "C:/Windows/Fonts/segoeuib.ttf"):
try:
return ImageFont.truetype(name, size)
except OSError:
pass
return None
def background(w, h):
bg = Image.new("RGBA", (w, h), (255, 236, 196, 255))
d = ImageDraw.Draw(bg)
for gx in range(0, w, 60):
for gy in range(0, h, 60):
d.ellipse([gx, gy, gx + 5, gy + 5], fill=(240, 214, 160, 255))
return bg
def main() -> None:
name = sys.argv[1] if len(sys.argv) > 1 else "cat"
frame = Image.open(FRAMES / (name + ".png")).convert("RGBA")
big = background(1080, 1350)
big.alpha_composite(compose(frame, "flower").resize((900, 900), Image.LANCZOS), (90, 90))
d = ImageDraw.Draw(big)
d.text((540, 1090), "Рамка на форме «Цветочек»", font=font(54), fill=(40, 30, 40, 255), anchor="mm")
d.text((540, 1170), "аватарка встаёт в окно рамки", font=font(46), fill=(150, 90, 110, 255), anchor="mm")
big.convert("RGB").save(FRAMES / (name + "_on_flower.png"))
shapes = ("circle", "flower", "squircle", "hexagon", "heart", "triangle")
labels = ("Круг", "Цветочек", "Квадрат", "Шестиугольник", "Сердечко", "Треугольник")
tile = 560
sheet = background(tile * 3, tile * 2 + 40)
d = ImageDraw.Draw(sheet)
for i, (shape, label) in enumerate(zip(shapes, labels)):
x, y = (i % 3) * tile, (i // 3) * tile
sheet.alpha_composite(compose(frame, shape).resize((tile, tile), Image.LANCZOS), (x, y))
d.text((x + tile / 2, y + tile - 8), label, font=font(34), fill=(40, 30, 40, 255), anchor="mm")
sheet.convert("RGB").save(FRAMES / (name + "_on_shapes.png"))
print(FRAMES / (name + "_on_flower.png"))
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,139 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
LihonT 2 «Serena alpha»: one video from the scenes of the two alpha videos (make_serena_promo.py and make_serena_promo2.py),
1080x1920, 30 fps, one intro and one outro, the sticker style of make_luna_promo2.py.
usage (from the repository root):
py -X utf8 -B scripts/make_serena_alpha_video.py # work/serena-promo/serena_alpha.mp4
py -X utf8 -B scripts/make_serena_alpha_video.py --still 20.0 # one frame
"""
from __future__ import annotations
import argparse
import math
import shutil
import subprocess
import sys
from multiprocessing import Pool
from pathlib import Path
from PIL import Image, ImageDraw
sys.path.insert(0, str(Path(__file__).resolve().parent))
import make_luna_promo2 as V # noqa: E402
import make_serena_promo as A # noqa: E402
import make_serena_promo2 as B # noqa: E402
W, H, FPS = V.W, V.H, V.FPS
ROOT = V.ROOT
UT = ROOT / "work" / "serena-promo" / "serena_alpha.mp4"
AUDIO = ROOT / "work" / "serena-promo" / "serena_alpha_audio.wav"
clamp, ease_out_cubic, ease_out_back, pop = V.clamp, V.ease_out_cubic, V.ease_out_back, V.pop
YELLOW, WHITE, PINK, CREAM = V.YELLOW, V.WHITE, V.PINK, V.CREAM
def scene_intro(layer, lt):
k = ease_out_back(lt / 0.9)
V.place(layer, V.ASSETS["logo"], W / 2, 760, 0.5 * k * (1 + 0.04 * math.sin(lt * 5)), math.sin(lt * 2.4) * 8 + (1 - k) * 360)
V.burst(layer, W / 2, 760, lt, 0.6, seed=34)
V.title(layer, max(0.0, lt - 0.9), "LihonT 2", "Serena alpha", y=1230)
V.label(layer, W / 2, 1480, "темы · значки · плагины · приколы", pop(lt, 1.8), size=42, fill=YELLOW)
def scene_outro(layer, lt):
k = ease_out_back(lt / 0.8)
V.place(layer, V.ASSETS["logo"], W / 2, 620, 0.46 * k * (1 + 0.04 * math.sin(lt * 5)), math.sin(lt * 2.4) * 8 + (1 - k) * 300)
V.burst(layer, W / 2, 620, lt, 0.5, seed=39, count=60, power=1000)
V.title(layer, max(0.0, lt - 0.5), "Serena alpha", "Открытый код · лицензия VCBFU v2", y=1000)
bounce = lambda t0: abs(math.sin((lt - t0) * 3)) * 14 if lt > t0 else 0 # noqa: E731
V.label(layer, W / 2, 1290 - bounce(1.2), "git.lihont.space", pop(lt, 1.2), size=60, fill=YELLOW)
V.label(layer, W / 2, 1440 - bounce(1.5), "Telegram · @lihont", pop(lt, 1.5), size=60, fill=WHITE)
V.label(layer, W / 2, 1580, "Это альфа: может быть шероховато", pop(lt, 2.2), size=34, fill=PINK)
# name, length in seconds, background colour, the function that draws the scene (its own time starts at 0)
PARTS = [
("intro", 3.2, CREAM, scene_intro),
("themes", 6.0, (255, 226, 200), A.scene_themes),
("win95", 4.8, (0, 128, 128), A.scene_win95),
("plugin", 6.0, (255, 236, 150), A.scene_plugin),
("icons", 6.2, (190, 240, 220), B.scene_icons),
("cards", 6.2, (215, 200, 255), B.scene_cards),
("fun", 5.2, (215, 200, 255), A.scene_fun),
("debug", 5.4, (190, 240, 220), A.scene_debug),
("safe", 4.4, (255, 205, 225), B.scene_safe),
("outro", 4.2, (255, 196, 176), scene_outro),
]
SCENES = []
_t = 0.0
for _name, _length, _color, _draw in PARTS:
SCENES.append((_name, _t, _t + _length, _color, _draw))
_t += _length
DURATION = SCENES[-1][2]
FRAMES = int(round(DURATION * FPS))
WIPE = V.WIPE
def frame_at(t: float) -> Image.Image:
V.init_assets()
index = 0
for n, (name, start, end, color, draw) in enumerate(SCENES):
if t >= start:
index = n
name, start, end, color, draw = SCENES[index]
img = Image.new("RGBA", (W, H), color + (255,))
if index > 0 and t - start < WIPE:
prev = SCENES[index - 1][3]
img = Image.new("RGBA", (W, H), prev + (255,))
r = 1700 * ease_out_cubic((t - start) / WIPE)
mask = Image.new("L", (W, H), 0)
ImageDraw.Draw(mask).ellipse([W / 2 - r, H / 2 - r, W / 2 + r, H / 2 + r], fill=255)
img.paste(Image.new("RGBA", (W, H), color + (255,)), (0, 0), mask)
if name != "win95": # the teal desktop of Windows 95 has no dot grid
ox, oy = int(t * 30) % 80, int(t * 18) % 80
img.alpha_composite(V.ASSETS["dots"], (-ox, -oy))
layer = Image.new("RGBA", (W, H), (0, 0, 0, 0))
draw(layer, t - start)
out = clamp((end - t) / 0.25) if index < len(SCENES) - 1 else 1.0
if out < 1.0:
layer.putalpha(layer.getchannel("A").point(lambda v, a=out: int(v * a)))
img.alpha_composite(layer)
return img
def render_frame(index: int) -> bytes:
return frame_at(index / FPS).convert("RGB").tobytes()
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--still", type=float)
parser.add_argument("--out", default=str(OUT))
parser.add_argument("--jobs", type=int, default=6)
args = parser.parse_args()
OUT.parent.mkdir(parents=True, exist_ok=True)
if args.still is not None:
path = OUT.parent / ("still_alpha_%.2f.png" % args.still)
frame_at(args.still).convert("RGB").save(path)
print(path)
return
import make_lihont_music
make_lihont_music.generate(AUDIO, DURATION, tuple(s[1] for s in SCENES[1:]))
command = [shutil.which("ffmpeg") or "ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
"-s", "%dx%d" % (W, H), "-r", str(FPS), "-i", "-", "-i", str(AUDIO), "-c:v", "libx264", "-preset", "medium",
"-crf", "18", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k", "-shortest", args.out]
proc = subprocess.Popen(command, stdin=subprocess.PIPE)
with Pool(args.jobs, initializer=V.init_assets) as pool:
for n, data in enumerate(pool.imap(render_frame, range(FRAMES), chunksize=4)):
proc.stdin.write(data)
if n % 60 == 0:
print("frame %d/%d" % (n, FRAMES), flush=True)
proc.stdin.close()
proc.wait()
print("done:", args.out)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,332 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
LihonT 2 «Serena beta»: a video that moves on the beats of a song. Every scene starts on a strong beat, every beat makes the picture
jump and a new thing pop in. The beats come from scripts/analyze_beats.py (work/music/<song>.beats.json). Only our own material is
shown: the avatar frames drawn by scripts/frame_render.py, their sprites, the sticker labels of the earlier videos.
1080x1920, 30 fps, the sticker style of make_luna_promo2.py.
The song is chosen by name (work/music/<name>.mp3 and <name>.beats.json); PLANS says how the scenes are laid on its strong beats.
usage (from the repository root):
py -X utf8 -B scripts/make_serena_beat_video.py [--song baka|long] # work/serena-promo/serena_beat_<song>.mp4
py -X utf8 -B scripts/make_serena_beat_video.py --song long --still 3.0 # one frame as a picture
"""
from __future__ import annotations
import argparse
import json
import math
import shutil
import subprocess
import sys
from multiprocessing import Pool
from pathlib import Path
from PIL import Image, ImageDraw
sys.path.insert(0, str(Path(__file__).resolve().parent))
import make_luna_promo2 as V # noqa: E402
ROOT = V.ROOT
W, H, FPS = V.W, V.H, V.FPS
INK, CREAM, CORAL, YELLOW, MINT, VIOLET, SKY, PINK, WHITE = (V.INK, V.CREAM, V.CORAL, V.YELLOW, V.MINT, V.VIOLET, V.SKY, V.PINK, V.WHITE)
clamp, ease_out_cubic, ease_out_back = V.clamp, V.ease_out_cubic, V.ease_out_back
CACHE = ROOT / "work" / "serena-promo" / "beat-cache"
CAT_ORDER = ["none", "basic.cat", "basic.helmet", "basic.flower", "basic.crown", "basic.flame", "basic.cat", "basic.crown",
"basic.flower", "basic.helmet", "basic.flame", "basic.cat"]
NAMES = {"basic.cat": "Ушки", "basic.helmet": "Скафандр", "basic.flower": "Цветок", "basic.crown": "Корона", "basic.flame": "Пламя"}
SHAPES = ["circle", "flower", "squircle", "hexagon", "heart", "triangle", "flower", "heart"]
SHAPE_NAMES = {"circle": "Круг", "flower": "Цветочек", "squircle": "Квадрат", "hexagon": "Шестиугольник", "heart": "Сердечко",
"triangle": "Треугольник"}
# scene, the strong beat it starts on (None = the very start), the strong beat it ends on (None = the end), background colour
PLANS = {
"baka": [("intro", None, 0, CREAM), ("frames", 0, 2, (255, 226, 200)), ("grid", 2, 3, (215, 200, 255)),
("packs", 3, 5, (190, 240, 220)), ("list", 5, 7, (255, 236, 150)), ("more", 7, 9, (255, 205, 225)),
("outro", 9, None, (255, 196, 176))],
"long": [("intro", None, 0, CREAM), ("frames", 0, 3, (255, 226, 200)), ("grid", 3, 4, (215, 200, 255)),
("packs", 4, 6, (190, 240, 220)), ("list", 6, 9, (255, 236, 150)), ("more", 9, 12, (255, 205, 225)),
("shapes", 12, 14, (215, 200, 255)), ("outro", 14, None, (255, 196, 176))],
}
# filled by configure()
SONG = None
B: list = []
STRONG: list = []
DURATION = 0.0
FRAMES = 0
SCENES: list = []
_IMAGES: dict = {}
def configure(name: str) -> None:
global SONG, B, STRONG, DURATION, FRAMES, SCENES
SONG = ROOT / "work" / "music" / (name + ".mp3")
data = json.loads(SONG.with_suffix(".beats.json").read_text(encoding="utf-8"))
B, STRONG = data["beats"], data["strong_beats"]
DURATION = round(data["duration"], 2)
FRAMES = int(round(DURATION * FPS))
SCENES = []
for scene, a, b, color in PLANS[name]:
SCENES.append((scene, 0.0 if a is None else STRONG[a], DURATION if b is None else STRONG[b], color))
def beat_index(t: float) -> int:
"""The number of the last beat that has happened by time t (-1 before the first one)."""
n = -1
for i, b in enumerate(B):
if t >= b:
n = i
return n
def since_beat(t: float) -> float:
n = beat_index(t)
return t - B[n] if n >= 0 else 9.0
def jump(t: float) -> float:
"""1 right on a beat, falling to 0 in about a fifth of a second."""
return max(0.0, 1.0 - since_beat(t) / 0.2) ** 2
def pop_at(t: float, t0: float, speed: float = 0.32) -> float:
return ease_out_back((t - t0) / speed) if t >= t0 else 0.0
def prepare_images() -> None:
"""Draws every frame on a round avatar (and one frame on every shape) once, it takes a while, and keeps the pictures."""
CACHE.mkdir(parents=True, exist_ok=True)
import frame_render as FR
import make_frame_on_shape as S
pack = json.loads((ROOT / "frames" / "basic" / "pack.json").read_text(encoding="utf-8"))
for frame in pack["frames"]:
path = CACHE / ("basic.%s.png" % frame["id"])
if not path.exists():
FR.render(frame, "circle", 1000, 520).save(path)
if frame["id"] == "cat":
for shape in set(SHAPES):
path = CACHE / ("cat-on-%s.png" % shape)
if not path.exists():
FR.render(frame, shape, 1000, 520).save(path)
plain = CACHE / "none.png"
if not plain.exists():
img = Image.new("RGBA", (1000, 1000), (0, 0, 0, 0))
img.paste(S.avatar(520), (240, 320), S.shape_mask("circle", 520))
ImageDraw.Draw(img).ellipse([240, 320, 760, 840], outline=INK + (255,), width=8)
img.save(plain)
def image(name: str) -> Image.Image:
if name not in _IMAGES:
if name.startswith("sprite:"):
_IMAGES[name] = Image.open(ROOT / "frames" / "basic" / name[7:]).convert("RGBA")
elif name == "grid":
_IMAGES[name] = Image.open(ROOT / "work" / "frames" / "frames_grid.png").convert("RGBA")
else:
_IMAGES[name] = Image.open(CACHE / (name + ".png")).convert("RGBA")
return _IMAGES[name]
def small_burst(layer, cx, cy, t, t0, seed):
V.burst(layer, cx, cy, t, t0, seed=seed, count=22, power=620)
# ---------------------------------------------------------------- scenes (t is the time of the whole video, t0 the start of the scene)
def scene_intro(layer, t, t0):
k = pop_at(t, B[0], 0.5)
V.place(layer, V.ASSETS["logo"], W / 2, 860, 0.5 * k * (1 + 0.05 * jump(t)), math.sin(t * 2.4) * 6 + (1 - k) * 300)
V.burst(layer, W / 2, 860, t, B[0], seed=11, count=50, power=900)
if len(B) > 1 and t >= B[1]:
V.title(layer, max(0.0, t - B[1]), "LihonT 2", "Serena beta", y=1300)
def scene_frames(layer, t, t0):
first = beat_index(t0 + 0.01)
index = max(0, min(beat_index(t) - first, len(CAT_ORDER) - 1))
name = CAT_ORDER[index]
born = B[first + index]
k = 0.8 + 0.2 * ease_out_back((t - born) / 0.28) if t >= born else 1.0
V.place(layer, image(name), W / 2, 880, 1.0 * k * (1 + 0.025 * jump(t)), math.sin(t * 3) * 2.5)
small_burst(layer, W / 2, 1420, t, born, seed=20 + index)
V.label(layer, W / 2, 230, "Рамки для аватарок", pop_at(t, t0, 0.3), size=64, fill=YELLOW)
V.label(layer, W / 2, 1520, NAMES.get(name, "Без рамки"), pop_at(t, born, 0.22), size=76, fill=WHITE)
V.label(layer, W / 2, 1680, "и её видят все с модом", pop_at(t, B[first + 4], 0.3), size=44, fill=MINT)
def scene_grid(layer, t, t0):
grid = image("grid")
card = grid.resize((960, int(grid.height * 960 / grid.width)), Image.Resampling.LANCZOS)
k = pop_at(t, t0, 0.35) * (1 + 0.03 * jump(t))
V.sticker(layer, (W / 2 - card.width / 2 - 20, 540, W / 2 + card.width / 2 + 20, 560 + card.height + 20), V.WHITE, radius=36, shadow=12)
layer.alpha_composite(card, (int(W / 2 - card.width / 2), 560))
V.label(layer, W / 2, 260, "на любой форме", pop_at(t, t0, 0.3), size=76, fill=WHITE)
V.label(layer, W / 2, 420, "круг · цветок · сердце · шестиугольник", pop_at(t, t0 + 0.4, 0.3), size=40, fill=YELLOW)
V.label(layer, W / 2, 1600, "ободок повторяет контур", pop_at(t, t0 + 0.8, 0.3) * k, size=52, fill=MINT)
def scene_packs(layer, t, t0):
sprites = ["cat-ear.png", "crown.png", "helmet-antenna.png", "flame-tall.png", "cat-tuft.png", "helmet-collar.png", "flame-mid.png",
"cat-cowlick.png"]
first = beat_index(t0 + 0.01)
V.label(layer, W / 2, 250, "Новые паки", pop_at(t, t0, 0.3), size=84, fill=WHITE)
V.label(layer, W / 2, 400, "приходят сами", pop_at(t, t0 + 0.4, 0.3), size=64, fill=YELLOW)
for n, name in enumerate(sprites):
born = B[first + n]
k = pop_at(t, born, 0.3)
if k <= 0:
continue
col, row = n % 4, n // 4
cx, cy = 190 + col * 233, 760 + row * 330
V.sticker(layer, (cx - 105, cy - 125, cx + 105, cy + 125), WHITE if (col + row) % 2 == 0 else CREAM, radius=34, shadow=8)
sp = image("sprite:" + name)
V.place(layer, sp, cx, cy, min(190 / sp.width, 220 / sp.height) * k, (n % 3 - 1) * 4)
small_burst(layer, cx, cy, t, born, seed=40 + n)
V.label(layer, W / 2, 1500, "без обновления мода", pop_at(t, B[first + 8] if first + 8 < len(B) else t0 + 3.0, 0.3), size=56, fill=MINT)
V.label(layer, W / 2, 1650, "NEW", pop_at(t, B[first + 10] if first + 10 < len(B) else t0 + 3.4, 0.3), size=70, fill=CORAL)
def scene_list(layer, t, t0):
items = [("Дневник мода", MINT), ("Полоса перемотки", SKY), ("Аватарка по нику", YELLOW), ("Призрак", PINK),
("Темы и Windows 95", VIOLET), ("Плагины со значками", MINT), ("Режим DEBUG", CORAL), ("Рамки в паках", YELLOW),
("Свои стили", SKY), ("Открытый код", PINK), ("Без рекламы", MINT), ("Плагины без кода", VIOLET)]
first = beat_index(t0 + 0.01)
V.label(layer, W / 2, 230, "и ещё", pop_at(t, t0, 0.3), size=84, fill=WHITE)
last = [s for s in SCENES if s[0] == "list"][0][2]
shown = [n for n in range(len(items)) if first + n < len(B) and B[first + n] < last - 0.05]
step = min(160, 1250 // max(1, len(shown)))
for n in shown:
text, color = items[n]
born = B[first + n]
k = pop_at(t, born, 0.3)
if k <= 0:
continue
x = W / 2 + (-1) ** n * 40
y = 400 + n * step
V.label(layer, x, y, text, k, size=58, fill=color)
small_burst(layer, x, y, t, born, seed=60 + n)
def scene_more(layer, t, t0):
first = beat_index(t0 + 0.01)
k = pop_at(t, B[first], 0.32)
V.place(layer, V.ghost(380), W / 2 - 250, 620 + math.sin(t * 5) * 14, k * (1 + 0.04 * jump(t)), math.sin(t * 3) * 6)
V.label(layer, W / 2 - 250, 840, "Призрак", pop_at(t, B[first] + 0.1, 0.3), size=56, fill=WHITE)
k = pop_at(t, B[first + 2], 0.32)
V.place(layer, V.ASSETS["flame_lit"][int(t * 8) % 4], W / 2 + 250, 640, 0.7 * k * (1 + 0.04 * jump(t)), math.sin(t * 4) * 5)
V.label(layer, W / 2 + 250, 840, "Огоньки", pop_at(t, B[first + 2] + 0.1, 0.3), size=56, fill=YELLOW)
k = pop_at(t, B[first + 4], 0.32)
if k > 0:
d = ImageDraw.Draw(layer, "RGBA")
cx, cy, w, h = W / 2, 1180, 700 * k, 330 * k
d.rectangle([cx - w / 2 + 12, cy - h / 2 + 12, cx + w / 2 + 12, cy + h / 2 + 12], fill=INK + (255,))
d.rectangle([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], fill=(192, 192, 192, 255), outline=INK + (255,), width=5)
d.rectangle([cx - w / 2 + 8, cy - h / 2 + 8, cx + w / 2 - 8, cy - h / 2 + 8 + 56 * k], fill=(0, 0, 128, 255))
d.text((cx - w / 2 + 24, cy - h / 2 + 8 + 28 * k), "LihonT", font=V.P.font(max(8, int(34 * k)), True), fill=WHITE + (255,), anchor="lm")
d.rectangle([cx + w / 2 - 70 * k, cy - h / 2 + 14 * k, cx + w / 2 - 14 * k, cy - h / 2 + 52 * k], fill=(192, 192, 192, 255),
outline=INK + (255,), width=3)
d.text((cx, cy + 40 * k), "Windows 95", font=V.P.font(max(8, int(60 * k)), True), fill=INK + (255,), anchor="mm")
V.label(layer, W / 2, 1560, "Сброс как «Очистить кэш»", pop_at(t, B[first + 6], 0.32), size=50, fill=MINT)
V.label(layer, W / 2, 1700, "режим DEBUG", pop_at(t, B[first + 8] if first + 8 < len(B) else B[first + 7], 0.3), size=60, fill=CORAL)
def scene_shapes(layer, t, t0):
"""One frame (the ears) moving over the shapes of the avatar, one shape on every beat."""
first = beat_index(t0 + 0.01)
index = max(0, min(beat_index(t) - first, len(SHAPES) - 1))
shape = SHAPES[index]
born = B[first + index]
k = 0.8 + 0.2 * ease_out_back((t - born) / 0.28) if t >= born else 1.0
V.place(layer, image("cat-on-" + shape), W / 2, 900, 1.0 * k * (1 + 0.025 * jump(t)), math.sin(t * 3) * 2.5)
small_burst(layer, W / 2, 1420, t, born, seed=90 + index)
V.label(layer, W / 2, 230, "рамка сама ложится", pop_at(t, t0, 0.3), size=64, fill=YELLOW)
V.label(layer, W / 2, 1520, SHAPE_NAMES[shape], pop_at(t, born, 0.22), size=76, fill=WHITE)
def scene_outro(layer, t, t0):
k = pop_at(t, t0, 0.5)
V.place(layer, V.ASSETS["logo"], W / 2, 640, 0.46 * k * (1 + 0.05 * jump(t)), math.sin(t * 2.4) * 6 + (1 - k) * 280)
V.burst(layer, W / 2, 640, t, t0, seed=77, count=60, power=1000)
V.burst(layer, W / 2, 640, t, STRONG[-1], seed=78, count=60, power=1000)
V.title(layer, max(0.0, t - t0), "Serena beta", "Открытый код · лицензия VCBFU v2", y=1020)
V.label(layer, W / 2, 1300, "git.lihont.space", pop_at(t, t0 + 0.4, 0.3), size=60, fill=YELLOW)
V.label(layer, W / 2, 1450, "Telegram · @lihont", pop_at(t, t0 + 0.8, 0.3), size=60, fill=WHITE)
SCENE_DRAW = {"intro": scene_intro, "frames": scene_frames, "grid": scene_grid, "packs": scene_packs, "list": scene_list,
"more": scene_more, "shapes": scene_shapes, "outro": scene_outro}
def frame_at(t: float) -> Image.Image:
V.init_assets()
index = 0
for n, scene in enumerate(SCENES):
if t >= scene[1]:
index = n
name, start, end, color = SCENES[index]
img = Image.new("RGBA", (W, H), color + (255,))
if index > 0 and t - start < 0.3: # a circle of the new colour opens on the strong beat
img = Image.new("RGBA", (W, H), SCENES[index - 1][3] + (255,))
r = 1800 * ease_out_cubic((t - start) / 0.3)
mask = Image.new("L", (W, H), 0)
ImageDraw.Draw(mask).ellipse([W / 2 - r, H / 2 - r, W / 2 + r, H / 2 + r], fill=255)
img.paste(Image.new("RGBA", (W, H), color + (255,)), (0, 0), mask)
ox, oy = int(t * 30) % 80, int(t * 18) % 80
img.alpha_composite(V.ASSETS["dots"], (-ox, -oy))
layer = Image.new("RGBA", (W, H), (0, 0, 0, 0))
SCENE_DRAW[name](layer, t, start)
zoom = 1.0 + 0.03 * jump(t) # the whole picture jumps a little on every beat
if zoom > 1.001:
big = layer.resize((int(W * zoom), int(H * zoom)), Image.Resampling.BILINEAR)
layer = big.crop(((big.width - W) // 2, (big.height - H) // 2, (big.width - W) // 2 + W, (big.height - H) // 2 + H))
img.alpha_composite(layer)
for s in STRONG: # a white flash on the strong beats
d = t - s
if 0 <= d < 0.16:
img.alpha_composite(Image.new("RGBA", (W, H), (255, 255, 255, int(110 * (1 - d / 0.16)))))
return img
def render_frame(index: int) -> bytes:
return frame_at(index / FPS).convert("RGB").tobytes()
def _init(song: str) -> None:
configure(song)
V.init_assets()
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--song", default="baka", choices=sorted(PLANS))
parser.add_argument("--still", type=float)
parser.add_argument("--jobs", type=int, default=6)
args = parser.parse_args()
configure(args.song)
out = ROOT / "work" / "serena-promo" / ("serena_beat_%s.mp4" % args.song)
out.parent.mkdir(parents=True, exist_ok=True)
prepare_images()
if args.still is not None:
path = out.parent / ("still_beat_%s_%.2f.png" % (args.song, args.still))
frame_at(args.still).convert("RGB").save(path)
print(path)
return
command = [shutil.which("ffmpeg") or "ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
"-s", "%dx%d" % (W, H), "-r", str(FPS), "-i", "-", "-i", str(SONG), "-c:v", "libx264", "-preset", "medium",
"-crf", "18", "-pix_fmt", "yuv420p", "-af", "afade=t=out:st=%.2f:d=0.5" % (DURATION - 0.5), "-c:a", "aac", "-b:a", "192k",
"-t", "%.2f" % DURATION, str(out)]
proc = subprocess.Popen(command, stdin=subprocess.PIPE)
with Pool(args.jobs, initializer=_init, initargs=(args.song,)) as pool:
for n, data in enumerate(pool.imap(render_frame, range(FRAMES), chunksize=4)):
proc.stdin.write(data)
if n % 60 == 0:
print("frame %d/%d" % (n, FRAMES), flush=True)
proc.stdin.close()
proc.wait()
print("done:", out)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,30 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Cards for the Telegram post about Serena alpha: the settled frames of the two sticker-style promo videos
(make_serena_promo.py and make_serena_promo2.py), 1080x1920, no screenshots.
usage: py -X utf8 -B scripts/make_serena_cards.py # writes work/serena-cards/card_01.png ...
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import make_serena_promo as A # noqa: E402
import make_serena_promo2 as B # noqa: E402
OUT = A.ROOT / "work" / "serena-cards"
# (module, name, time): the moment of a scene when everything has landed and nothing is half-way
MOMENTS = [(B, "intro", 2.9), (A, "themes", 8.2), (A, "win95", 13.0), (A, "plugin", 19.2), (B, "icons", 8.6),
(B, "cards", 14.6), (A, "fun", 24.4), (A, "debug", 29.6), (B, "safe", 24.4), (B, "outro", 29.0)]
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
for n, (module, name, t) in enumerate(MOMENTS, 1):
path = OUT / ("card_%02d_%s.png" % (n, name))
module.frame_at(t).convert("RGB").save(path)
print(path.name)
if __name__ == "__main__":
main()

View File

@@ -30,6 +30,14 @@ PAYLOAD = [
("src/web/assets/site/plugin_howto.svg", "assets/site/plugin_howto.svg"),
]
# The avatar frames the mod downloads (see scripts/build_frames_catalog.py): the catalog and every sprite of every pack, at
# /frames/ on the site. A new pack is only the files of its folder: build the catalog, deploy, and phones pick it up by themselves.
_FRAMES = ROOT / "frames"
if (_FRAMES / "index.json").is_file():
PAYLOAD.append(("frames/index.json", "frames/index.json"))
for _sprite in sorted(_FRAMES.glob("*/*.png")):
PAYLOAD.append((_sprite.relative_to(ROOT).as_posix(), _sprite.relative_to(ROOT).as_posix()))
def main() -> int:
missing = [source for source, _ in PAYLOAD if not (ROOT / source).is_file()]

View File

@@ -32,6 +32,8 @@ LIFETIME = 30 * 86400
UNIQUE = re.compile(r"[A-Za-z0-9_.]{2,24}\Z")
# Avatar outlines a member can publish; the round one is TikTok's own and is never stored.
SHAPES = ("flower", "squircle", "hexagon", "heart", "triangle")
# Avatar frames: "pack.frame" ids of the catalog on the site (the catalog itself is not known here, only the shape of the id).
FRAME = re.compile(r"[a-z0-9][a-z0-9_-]{0,23}\.[a-z0-9][a-z0-9_-]{0,23}\Z")
# The niche-mod badge can be claimed until this moment (Moscow time).
CLAIM_DEADLINE = 1794735240 # 2026-11-15 12:34:00 +03:00
@@ -72,6 +74,7 @@ class Registry:
db.execute("CREATE TABLE IF NOT EXISTS supporters (uid TEXT PRIMARY KEY, granted_at INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS niche (uid TEXT PRIMARY KEY, unique_id TEXT NOT NULL, granted_at INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS shapes (uid TEXT PRIMARY KEY, shape TEXT NOT NULL, updated_at INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS avatar_frames (uid TEXT PRIMARY KEY, frame TEXT NOT NULL, updated_at INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS 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),))
@@ -162,24 +165,9 @@ class Registry:
if not proven and shape == "circle" and not has_shape:
return {"ok": True, "published": True, "shape": "circle"} # nothing to withdraw
if not proven:
if not isinstance(unique_id, str) or not UNIQUE.fullmatch(unique_id):
return {"ok": True, "published": False, "reason": "proof_needed", "code": self.code(uid)}
try:
profile = self.fetcher(unique_id)
except Exception:
raise ValueError("Could not read the TikTok profile, try again later")
if profile is None:
raise ValueError("Profile not found")
found_uid, bio = profile
if found_uid != uid:
raise ValueError("That profile belongs to another account")
if self.code(uid) not in bio:
return {"ok": True, "published": False, "reason": "code_missing", "code": self.code(uid)}
with self.connect() as db:
db.execute("INSERT INTO shape_owner(uid,installation,unique_id,verified_at) VALUES(?,?,?,?) "
"ON CONFLICT(uid) DO UPDATE SET installation=excluded.installation,"
"unique_id=excluded.unique_id,verified_at=excluded.verified_at",
(uid, digest, unique_id, int(self.clock())))
reply = self._prove(uid, digest, unique_id)
if reply is not None:
return reply
with self.connect() as db:
if shape == "circle":
db.execute("DELETE FROM shapes WHERE uid=?", (uid,))
@@ -189,6 +177,59 @@ class Registry:
(uid, shape, int(self.clock())))
return {"ok": True, "published": True, "shape": shape}
def _prove(self, uid, digest, unique_id):
"""The account proves itself with the code in its public bio; the installation is then bound to it.
Returns None once the installation is bound, else the reply that tells the client what is missing."""
if not isinstance(unique_id, str) or not UNIQUE.fullmatch(unique_id):
return {"ok": True, "published": False, "reason": "proof_needed", "code": self.code(uid)}
try:
profile = self.fetcher(unique_id)
except Exception:
raise ValueError("Could not read the TikTok profile, try again later")
if profile is None:
raise ValueError("Profile not found")
found_uid, bio = profile
if found_uid != uid:
raise ValueError("That profile belongs to another account")
if self.code(uid) not in bio:
return {"ok": True, "published": False, "reason": "code_missing", "code": self.code(uid)}
with self.connect() as db:
db.execute("INSERT INTO shape_owner(uid,installation,unique_id,verified_at) VALUES(?,?,?,?) "
"ON CONFLICT(uid) DO UPDATE SET installation=excluded.installation,"
"unique_id=excluded.unique_id,verified_at=excluded.verified_at",
(uid, digest, unique_id, int(self.clock())))
return None
def avatar_frame(self, uid, installation, frame, unique_id=None):
"""Publishes (or, for "none", withdraws) the avatar frame of `uid`, on the same terms as the avatar outline:
the account is proven once by the code in its bio, and the proving installation keeps the right to change it."""
if not valid_uid(uid) or not isinstance(installation, str) or not INSTALL.fullmatch(installation):
raise ValueError("Invalid account ID or installation code")
if frame != "none" and not (isinstance(frame, str) and FRAME.fullmatch(frame)):
raise ValueError("Unknown frame")
digest = hashlib.sha256(installation.encode("ascii")).hexdigest()
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()
has_frame = db.execute("SELECT 1 FROM avatar_frames WHERE uid=?", (uid,)).fetchone()
proven = owner is not None and hmac.compare_digest(owner[0], digest)
if not proven and frame == "none" and not has_frame:
return {"ok": True, "published": True, "frame": "none"} # nothing to withdraw
if not proven:
reply = self._prove(uid, digest, unique_id)
if reply is not None:
return reply
with self.connect() as db:
if frame == "none":
db.execute("DELETE FROM avatar_frames WHERE uid=?", (uid,))
else:
db.execute("INSERT INTO avatar_frames(uid,frame,updated_at) VALUES(?,?,?) "
"ON CONFLICT(uid) DO UPDATE SET frame=excluded.frame,updated_at=excluded.updated_at",
(uid, frame, int(self.clock())))
return {"ok": True, "published": True, "frame": frame}
def lookup(self, uids):
if not isinstance(uids, list) or len(uids) > 100 or any(not valid_uid(uid) for uid in uids):
raise ValueError("Request at most 100 account IDs")
@@ -207,12 +248,15 @@ class Registry:
shapes = {row[0]: row[1] for row in db.execute(
"SELECT uid,shape FROM shapes WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM blocked)", uids
).fetchall() if row[1] in SHAPES}
frames_of = {row[0]: row[1] for row in db.execute(
"SELECT uid,frame FROM avatar_frames WHERE uid IN (" + placeholders + ") AND uid NOT IN (SELECT uid FROM blocked)", uids
).fetchall() if FRAME.fullmatch(row[1])}
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, "ttl": 300}
"niche": {uid: uid in niche for uid in uids}, "shapes": shapes, "avatar_frames": frames_of, "ttl": 300}
def set_supporter(self, uid, enabled=True):
"""Admin-only when invoked from the server CLI; never exposed over HTTP."""
@@ -235,7 +279,7 @@ 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 == "shape" else (3600, 40))
else (3600, 30) if operation in ("shape", "avatar_frame") else (3600, 40))
now = time.monotonic()
with self.lock:
if len(self.events) > 10000:
@@ -275,11 +319,11 @@ class Handler(BaseHTTPRequestHandler):
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"):
if self.path != "/members/v1/" + operation or operation not in ("presence", "lookup", "withdraw", "code", "claim", "shape", "avatar_frame"):
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") else "presence"):
if not self.server.limits.allow(ip, operation if operation in ("lookup", "claim", "shape", "avatar_frame") else "presence"):
return self.send_json(429, {"error": "Try again later"})
try:
length = int(self.headers.get("Content-Length", "0"))
@@ -299,6 +343,9 @@ 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 == "avatar_frame":
result = self.server.registry.avatar_frame(payload.get("uid"), payload.get("installation"),
payload.get("frame"), payload.get("unique_id"))
else:
result = self.server.registry.presence(payload.get("uid"), payload.get("installation"), operation == "withdraw", payload.get("frame_color", "green"))
self.send_json(200, result)

View File

@@ -0,0 +1,94 @@
package lihont.two.account;
import android.content.Context;
import android.content.SharedPreferences;
import org.json.JSONObject;
import lihont.two.frame.FrameIndex;
import lihont.two.widget.AppContext;
/**
* The avatar frame of every account on this phone: each account has its own, and the signed-in one decides how its own pictures
* are framed. Kept as one small JSON object (account id -> frame id) in a private file; an account without an entry has no frame.
*/
public final class AccountFrames {
private static final String FILE = "lihont_account_frames";
private static final String KEY = "book";
private static JSONObject book;
private static Context application;
private static String current;
private static long checkedAt;
private AccountFrames() {}
/** The frame id of the signed-in account's pictures, or null for none. Asked on every avatar draw, so cached for a moment. */
public static synchronized String current() {
try {
long now = android.os.SystemClock.uptimeMillis();
if (checkedAt != 0L && now - checkedAt < 1500L) return current;
checkedAt = now;
String uid = CurrentAccount.uid();
Context context = context();
if (uid == null || context == null || !load(context)) {
current = null;
return null;
}
current = valid(book.optString(uid, null));
return current;
} catch (Throwable unavailable) {
return null;
}
}
/** The frame one of the accounts of this phone chose, or null (a stranger's picture, or an account without a frame). */
public static synchronized String localFor(String uid) {
try {
Context context = context();
if (context == null || uid == null || !load(context)) return null;
return valid(book.optString(uid, null));
} catch (Throwable unavailable) {
return null;
}
}
/** Remembers the frame of one account (null or "" for none) and shows it at once if that account is signed in. */
public static synchronized void set(Context context, String uid, String frameId) {
if (uid == null || !load(context)) return;
try {
if (frameId == null || frameId.length() == 0) book.remove(uid);
else if (FrameIndex.validFrameId(frameId)) book.put(uid, frameId);
else return;
prefs(context).edit().putString(KEY, book.toString()).apply();
} catch (Exception ignored) {
return;
}
checkedAt = 0L;
}
private static String valid(String id) {
return FrameIndex.validFrameId(id) ? id : null;
}
private static Context context() {
if (application == null) application = AppContext.get();
return application;
}
private static boolean load(Context context) {
if (book != null) return true;
if (context == null) return false;
try {
String text = prefs(context).getString(KEY, null);
book = text == null ? new JSONObject() : new JSONObject(text);
} catch (Exception unreadable) {
book = new JSONObject();
}
return true;
}
private static SharedPreferences prefs(Context context) {
return context.getSharedPreferences(FILE, Context.MODE_PRIVATE);
}
}

View File

@@ -1,67 +1,143 @@
package lihont.two.avatar;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import java.util.WeakHashMap;
import lihont.two.frame.FrameDraw;
import lihont.two.frame.FrameIndex;
import lihont.two.frame.FrameStore;
import lihont.two.settings.ModSettings;
/**
* What TikTok's avatar view asks the mod around its drawing (see lihont/avatar_patch.py).
*
* With a shape other than the round one, begin() clips the canvas to that shape, sized to the view, and zooms
* the picture when the shape reaches out of the circle TikTok already cut the picture to; end() takes it off.
* Every shape is drawn inside the circle (see Shapes), so the picture, which is round, always covers it.
* Only the account's own picture and those of members who published a shape take one (see Owner); every other
* avatar stays round.
*
* With a frame, begin() draws what lies behind the avatar (the frame's ring, which follows the outline of the shape, and the parts
* hung behind it) and shrinks the avatar to leave room for the decoration; end() draws what lies in front. The smaller the view,
* the larger the part of it the avatar keeps. Only the account's own picture and those of members who published a shape or a frame are changed
* (see Owner); every other avatar stays as TikTok draws it.
*/
public final class AvatarShapes {
private static final java.util.Set<String> SEEN = new java.util.HashSet<String>();
private static Canvas openCanvas;
private static int openSave;
private static View openView;
private static FrameDraw.Prepared openFrame;
private static final java.util.Map<Long, Path> PATHS = new java.util.HashMap<Long, Path>();
private static final WeakHashMap<View, Boolean> UNCLIPPED = new WeakHashMap<View, Boolean>();
private static boolean refreshed;
private AvatarShapes() {}
/** The part of the view the avatar keeps inside a frame: a big avatar gives up more room for the frame's decoration. */
public static float keep(float sizePx, float density) {
float dp = sizePx / density;
if (dp >= 80f) return 0.72f;
if (dp >= 56f) return 0.8f;
return 0.9f; // a small avatar (a feed button, a comment) keeps nearly all of its room
}
/** Called before the avatar is drawn. Never throws. */
public static void begin(View view, Canvas canvas) {
try {
int width = view.getWidth();
int height = view.getHeight();
if (width <= 0 || height <= 0 || Math.abs(width - height) > 2) return;
ModSettings.AvatarShape shape = Owner.shapeFor(view);
if (shape == null || shape == ModSettings.AvatarShape.CIRCLE) return;
String name = view.getClass().getName();
if (SEEN.size() < 40 && SEEN.add(shape + " " + name + " " + width + "x" + height)) {
android.util.Log.i("LIHONT", "avatar-shape: " + shape + " on " + name + " " + width + "x" + height);
Owner.Look look = Owner.lookFor(view);
if (look == null) return;
ModSettings.AvatarShape shape = look.shape == null ? ModSettings.AvatarShape.CIRCLE : look.shape;
FrameDraw.Prepared frame = null;
float size = Math.min(width, height);
float diameter = size;
if (look.frame != null) {
Context context = view.getContext();
if (!refreshed) {
refreshed = true;
FrameStore.refresh(context, false);
}
FrameIndex.Frame known = FrameStore.index(context).frame(look.frame);
if (known != null) {
diameter = size * keep(size, view.getResources().getDisplayMetrics().density);
frame = FrameDraw.prepare(context, known, shape, diameter, view);
}
}
long key = ((long) shape.ordinal() << 40) | ((long) width << 20) | height;
Path path = PATHS.get(key);
if (path == null) {
if (PATHS.size() > 64) PATHS.clear();
path = Shapes.path(shape, width, height);
PATHS.put(key, path);
if (shape == ModSettings.AvatarShape.CIRCLE && frame == null) return;
String name = view.getClass().getName();
if (SEEN.size() < 40 && SEEN.add(shape + "+" + (frame == null ? "-" : look.frame) + " " + name + " " + width + "x" + height)) {
android.util.Log.i("LIHONT", "avatar-look: " + shape + (frame == null ? "" : " frame " + look.frame)
+ " on " + name + " " + width + "x" + height);
}
int save = canvas.save();
canvas.clipPath(path);
float zoom = Shapes.zoom(shape);
if (zoom != 1f) canvas.scale(zoom, zoom, width / 2f, height / 2f);
if (frame != null) {
FrameDraw.drawBack(canvas, frame, width / 2f, height / 2f);
float scale = diameter / size;
canvas.scale(scale, scale, width / 2f, height / 2f);
}
if (shape != ModSettings.AvatarShape.CIRCLE) {
long key = ((long) shape.ordinal() << 40) | ((long) width << 20) | height;
Path path = PATHS.get(key);
if (path == null) {
if (PATHS.size() > 64) PATHS.clear();
path = Shapes.path(shape, width, height);
PATHS.put(key, path);
}
canvas.clipPath(path);
float zoom = Shapes.zoom(shape);
if (zoom != 1f) canvas.scale(zoom, zoom, width / 2f, height / 2f);
}
openCanvas = canvas;
openSave = save;
openView = view;
openFrame = frame;
} catch (Throwable ignored) {
// Decoration: the avatar is drawn as TikTok draws it.
}
}
/** Called when the avatar has been drawn: takes off what begin() put on the canvas. Never throws. */
/** 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) {
try {
if (openCanvas == canvas) {
canvas.restoreToCount(openSave);
View view = openView;
FrameDraw.Prepared frame = openFrame;
openCanvas = null;
openView = null;
openFrame = null;
if (frame != null && view != null) {
unclip(view);
FrameDraw.drawFront(canvas, frame, view.getWidth() / 2f, view.getHeight() / 2f);
}
}
} catch (Throwable ignored) {
openCanvas = null;
openView = null;
openFrame = null;
}
}
/**
* A frame reaches out of the avatar's own rectangle (ears, a crown). The few parents above the avatar are told not to cut their
* children at their edges, once per view, so that the decoration is not clipped.
*/
public static void unclip(View view) {
if (UNCLIPPED.put(view, Boolean.TRUE) != null) return;
ViewParent parent = view.getParent();
for (int level = 0; level < 3 && parent instanceof ViewGroup; level++) {
ViewGroup group = (ViewGroup) parent;
group.setClipChildren(false);
group.setClipToPadding(false);
parent = group.getParent();
}
}
}

View File

@@ -0,0 +1,58 @@
package lihont.two.avatar;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import org.json.JSONObject;
import lihont.two.badge.NicheClaim;
/**
* Puts the account's own avatar frame on the members service, where other members' phones read it; the same proof as for the shape
* (the account's code in its public bio, once; then this installation changes the frame alone). Only the numeric account id, the
* public username, the frame id and this installation's secret are sent. A null frame withdraws the published one.
*/
public final class FramePublisher {
private static final Handler MAIN = new Handler(Looper.getMainLooper());
private FramePublisher() {}
public static void publish(final Context context, final String frameId, 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("avatar_frame", new JSONObject()
.put("uid", account.uid)
.put("installation", Installation.secret(context.getApplicationContext() != null
? context.getApplicationContext() : context))
.put("frame", frameId == null ? "none" : frameId)
.put("unique_id", account.uniqueId));
if (reply.optBoolean("published", false)) {
result = new ShapePublisher.Result(true, null, frameId == null
? "Рамка снята у всех" : "Рамка опубликована: её видят все с модом");
} 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").start();
}
}

View File

@@ -9,6 +9,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import lihont.two.account.AccountFrames;
import lihont.two.account.AccountShapes;
import lihont.two.bar.UserAvatar;
import lihont.two.settings.ModSettings;
@@ -37,22 +38,56 @@ final class Owner {
private Owner() {}
/** The shape this view is drawn in, or null for TikTok's round one. Never throws. */
static ModSettings.AvatarShape shapeFor(View view) {
/** How an avatar is dressed: its shape (null = round) and its frame id (null = none). */
static final class Look {
final ModSettings.AvatarShape shape;
final String frame;
Look(ModSettings.AvatarShape shape, String frame) {
this.shape = shape;
this.frame = frame;
}
}
private static final Map<String, Look> LOOKS = new HashMap<String, Look>();
private static Look look(ModSettings.AvatarShape shape, String frame) {
if ((shape == null || shape == ModSettings.AvatarShape.CIRCLE) && frame == null) return null;
String key = (shape == null ? "-" : shape.value()) + "|" + frame;
Look found = LOOKS.get(key);
if (found == null) {
if (LOOKS.size() > 128) LOOKS.clear();
found = new Look(shape, frame);
LOOKS.put(key, found);
}
return found;
}
/** The shape and the frame this view is drawn with, or null for TikTok's plain round avatar. Never throws. */
static Look lookFor(View view) {
try {
String id = Pictures.id(addressOf(view));
if (id == null) return null;
if (isMine(id)) return AccountShapes.current();
if (isMine(id)) return look(AccountShapes.current(), AccountFrames.current());
String uid = PictureOwners.uidOf(id);
if (uid == null) return null;
// another account of this phone (the account switcher shows them all) wears its own choice
ModSettings.AvatarShape own = AccountShapes.localFor(uid);
return own != null ? own : ShapeCatalog.shapeOf(uid, view);
ModSettings.AvatarShape shape = own != null ? own : ShapeCatalog.shapeOf(uid, view);
String frame = AccountFrames.localFor(uid);
if (frame == null) frame = ShapeCatalog.frameOf(uid);
return look(shape, frame);
} catch (Throwable unreadable) {
return null;
}
}
/** The shape this view is drawn in, or null for TikTok's round one. Never throws. */
static ModSettings.AvatarShape shapeFor(View view) {
Look look = lookFor(view);
return look == null ? null : look.shape;
}
private static boolean isMine(String id) {
long now = SystemClock.uptimeMillis();
if (mine == null || now >= refreshAt) {

View File

@@ -46,10 +46,12 @@ public final class ShapeCatalog {
private static final class Entry {
final ModSettings.AvatarShape shape;
final String frame;
final long until;
Entry(ModSettings.AvatarShape shape, long until) {
Entry(ModSettings.AvatarShape shape, String frame, long until) {
this.shape = shape;
this.frame = frame;
this.until = until;
}
}
@@ -76,6 +78,12 @@ public final class ShapeCatalog {
return entry == null ? null : entry.shape;
}
/** The frame id published for `uid` (asked after shapeOf, which fetches the answer), or null for none or not known yet. */
static String frameOf(String uid) {
Entry entry = KNOWN.get(uid);
return entry == null || SystemClock.uptimeMillis() >= entry.until ? null : entry.frame;
}
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++) {
@@ -96,29 +104,32 @@ public final class ShapeCatalog {
NETWORK.execute(new Runnable() {
@Override public void run() {
JSONObject shapes = null;
JSONObject frames = 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");
} catch (Exception ignored) {
// A failed lookup leaves everyone round for a minute.
}
final JSONObject found = shapes;
final JSONObject framed = frames;
MAIN.post(new Runnable() {
@Override public void run() {
record(ids, found);
record(ids, found, framed);
}
});
}
});
}
private static void record(List<String> ids, JSONObject shapes) {
private static void record(List<String> ids, JSONObject shapes, JSONObject frames) {
long now = SystemClock.uptimeMillis();
if (KNOWN.size() > MAX_KNOWN) KNOWN.clear();
for (String uid : ids) {
if (shapes == null) {
KNOWN.put(uid, new Entry(null, now + FAILED_MS));
KNOWN.put(uid, new Entry(null, null, now + FAILED_MS));
continue;
}
ModSettings.AvatarShape shape = null;
@@ -127,7 +138,9 @@ public final class ShapeCatalog {
} catch (Exception unknown) {
shape = null; // a shape this version does not know stays round
}
KNOWN.put(uid, new Entry(shape, now + KEEP_MS));
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));
}
if (shapes != null) redraw();
if (!PENDING.isEmpty() && !scheduled) {

View File

@@ -21,6 +21,30 @@ public final class Shapes {
}
}
/**
* The shape as one outline, for a ring drawn along it: the flower is made of overlapping circles, whose union is its true outline
* (the circles alone would show their inner arcs). Falls back to the plain path where the union cannot be made.
*/
public static Path outline(ModSettings.AvatarShape shape, float width, float height) {
Path plain = path(shape, width, height);
if (shape != ModSettings.AvatarShape.FLOWER) return plain;
float s = Math.min(width, height);
float x = (width - s) / 2f;
float y = (height - s) / 2f;
Path union = new Path();
union.addCircle(x + s * 0.5f, y + s * 0.5f, s * 0.31f, Path.Direction.CW);
for (int petal = 0; petal < 6; petal++) {
double angle = petal * Math.PI / 3.0 - Math.PI / 2.0;
Path one = new Path();
one.addCircle(x + s * (0.5f + 0.31f * (float) Math.cos(angle)), y + s * (0.5f + 0.31f * (float) Math.sin(angle)),
s * 0.19f, Path.Direction.CW);
Path next = new Path();
if (!next.op(union, one, Path.Op.UNION)) return plain;
union = next;
}
return union;
}
public static Path path(ModSettings.AvatarShape shape, float width, float height) {
float s = Math.min(width, height);
float x = (width - s) / 2f;

View File

@@ -20,12 +20,16 @@ import lihont.two.settings.SettingsHost;
* The user's avatar in the shape chosen in the settings (a circle unless another is chosen), drawn over the
* profile tab's icon, with a ring of the same shape while the tab is selected.
*
* It lives in the tab's view overlay: above the icon, outside the layout, never taking a touch.
* With an avatar frame chosen (see lihont.two.frame) the avatar shrinks a little and the frame is drawn round it, the selection
* ring going outside the frame's own ring. It lives in the tab's view overlay: above the icon, outside the layout, never
* taking a touch.
*/
final class AvatarBadge extends Drawable {
private static final float DIAMETER_DP = 26f;
private static final float RING_GAP_DP = 2.5f;
private static final float RING_WIDTH_DP = 2f;
/** The avatar's size when a frame is drawn round it: the decoration needs room inside the tab. */
private static final float FRAMED_DIAMETER_DP = 23f;
private final View item;
private final View icon;
@@ -70,11 +74,23 @@ final class AvatarBadge extends Drawable {
if (bitmap == null || shader == null) return;
float cx = (icon.getLeft() + icon.getRight()) / 2f;
float cy = (icon.getTop() + icon.getBottom()) / 2f;
float radius = DIAMETER_DP * density / 2f;
ModSettings.AvatarShape shape = lihont.two.account.AccountShapes.current();
lihont.two.frame.FrameDraw.Prepared frame = frameFor(shape);
float radius = (frame != null ? FRAMED_DIAMETER_DP : DIAMETER_DP) * density / 2f;
matrix.setScale(2f * radius / bitmap.getWidth(), 2f * radius / bitmap.getHeight());
matrix.postTranslate(cx - radius, cy - radius);
shader.setLocalMatrix(matrix);
ModSettings.AvatarShape shape = lihont.two.account.AccountShapes.current();
if (frame != null) {
lihont.two.avatar.AvatarShapes.unclip(item);
lihont.two.frame.FrameDraw.drawBack(canvas, frame, cx, cy);
canvas.drawPath(outline(shape, cx, cy, radius), fill);
if (item.isSelected()) {
float reach = radius + frame.ringWidthPx() + (RING_GAP_DP + RING_WIDTH_DP) * density / 2f;
canvas.drawPath(outline(shape, cx, cy, reach), ring);
}
lihont.two.frame.FrameDraw.drawFront(canvas, frame, cx, cy);
return;
}
if (shape == ModSettings.AvatarShape.CIRCLE) {
canvas.drawCircle(cx, cy, radius, fill);
if (item.isSelected()) {
@@ -92,6 +108,21 @@ final class AvatarBadge extends Drawable {
}
}
/** The frame of the signed-in account, prepared for this shape at the framed size; null when there is none or it is not ready. */
private lihont.two.frame.FrameDraw.Prepared frameFor(ModSettings.AvatarShape shape) {
try {
String id = lihont.two.account.AccountFrames.current();
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);
if (known == null) return null;
return lihont.two.frame.FrameDraw.prepare(context, known, shape, FRAMED_DIAMETER_DP * density, item);
} catch (Throwable ignored) {
return null; // decoration: the avatar is drawn without it
}
}
/** The shape as a path around (cx, cy) that fits a circle of this radius. */
private Path outline(ModSettings.AvatarShape shape, float cx, float cy, float radius) {
Path path = Shapes.path(shape, 2f * radius, 2f * radius);

View File

@@ -0,0 +1,113 @@
package lihont.two.frame;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.util.LruCache;
import android.view.View;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* The pictures of frames as bitmaps, decoded off the main thread and kept in a small cache.
*
* An avatar is drawn many times a second, so the drawing only ever asks: a picture that is ready is returned at once, one that is
* not is decoded in the background and the views that asked are redrawn when it is. A picture is decoded at the size it will be
* drawn at (a power-of-two reduction), so a small avatar in a list does not hold a large bitmap.
*/
public final class FrameArt {
private static final Handler MAIN = new Handler(Looper.getMainLooper());
private static final ExecutorService DECODER = Executors.newSingleThreadExecutor();
private static final LruCache<String, Bitmap> CACHE = new LruCache<String, Bitmap>(8 * 1024 * 1024) {
@Override protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
private static final Set<String> PENDING = new HashSet<String>();
private static final Set<String> BROKEN = new HashSet<String>();
private static final List<WeakReference<View>> WAITING = new ArrayList<WeakReference<View>>();
private static int seenVersion = -1;
private FrameArt() {}
/**
* The bitmap of `sprite` reduced for being drawn about `wantedPx` wide, or null while it is not on the phone or not decoded yet
* (then `asking` is redrawn when it is). Never throws.
*/
public static Bitmap get(Context context, FrameIndex.Sprite sprite, int wantedPx, View asking) {
try {
int version = FrameStore.version();
if (version != seenVersion) {
seenVersion = version;
CACHE.evictAll();
BROKEN.clear();
}
int sample = 1;
while (sample < 8 && sprite.width / (sample * 2) >= wantedPx) sample *= 2;
String key = sprite.sha256 + ":" + sample;
Bitmap ready = CACHE.get(key);
if (ready != null) return ready;
if (BROKEN.contains(key)) return null;
if (asking != null && WAITING.size() < 200) WAITING.add(new WeakReference<View>(asking));
File file = FrameStore.file(context, sprite);
if (file != null && PENDING.add(key)) decode(key, file, sample);
} catch (Throwable ignored) {
// Decoration: the avatar is drawn without it.
}
return null;
}
/** A bitmap for the picker screen, decoded on the calling thread; null if the picture is not there. */
public static Bitmap load(Context context, FrameIndex.Sprite sprite, int sample) {
try {
File file = FrameStore.file(context, sprite);
if (file == null) return null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sample;
return BitmapFactory.decodeFile(file.getPath(), options);
} catch (Throwable unreadable) {
return null;
}
}
private static void decode(final String key, final File file, final int sample) {
DECODER.execute(new Runnable() {
@Override public void run() {
Bitmap bitmap = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sample;
bitmap = BitmapFactory.decodeFile(file.getPath(), options);
} catch (Throwable unreadable) {
bitmap = null;
}
final Bitmap decoded = bitmap;
MAIN.post(new Runnable() {
@Override public void run() {
PENDING.remove(key);
if (decoded == null) {
BROKEN.add(key);
return;
}
CACHE.put(key, decoded);
List<WeakReference<View>> views = new ArrayList<WeakReference<View>>(WAITING);
WAITING.clear();
for (WeakReference<View> reference : views) {
View view = reference.get();
if (view != null && view.isAttachedToWindow()) view.invalidate();
}
}
});
}
});
}
}

View File

@@ -0,0 +1,161 @@
package lihont.two.frame;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.RectF;
import android.graphics.Shader;
import android.view.View;
import java.util.HashMap;
import java.util.Map;
import lihont.two.avatar.Shapes;
import lihont.two.settings.ModSettings;
/**
* Draws a frame round an avatar of any shape (see FrameIndex for what a frame is): a ring that follows the shape's outline, with the
* parts hung on points of that outline. The ring and the parts that belong behind the avatar are drawn before it, the rest after.
*
* Everything that depends only on the frame, the shape and the size (the outline, the ring's paints, the decoded pictures) is made
* once and kept, so drawing an avatar costs a few canvas calls. A frame whose pictures are not all decoded yet is not drawn at all,
* and the views that asked are redrawn when the pictures are ready.
*/
public final class FrameDraw {
/** A frame ready to be drawn for one shape at one size. */
public static final class Prepared {
final FrameIndex.Frame frame;
final Bitmap[] bitmaps;
final Outline outline;
final Path path;
final float size;
final Paint ink = new Paint(Paint.ANTI_ALIAS_FLAG);
final Paint fill = new Paint(Paint.ANTI_ALIAS_FLAG);
final Paint edge = new Paint(Paint.ANTI_ALIAS_FLAG);
/** The ring's width and dark line in pixels: how far the frame reaches out of the avatar's edge. */
public float ringWidthPx() {
return (frame.ring.width + frame.ring.line) * size;
}
Prepared(FrameIndex.Frame frame, Bitmap[] bitmaps, Outline outline, Path path, float size) {
this.frame = frame;
this.bitmaps = bitmaps;
this.outline = outline;
this.path = path;
this.size = size;
FrameIndex.Ring ring = frame.ring;
float ringWidth = ring.width * size;
float lineWidth = ring.line * size;
ink.setStyle(Paint.Style.STROKE);
ink.setStrokeJoin(Paint.Join.ROUND);
ink.setColor(ring.ink);
ink.setStrokeWidth(2f * (ringWidth + lineWidth));
fill.setStyle(Paint.Style.STROKE);
fill.setStrokeJoin(Paint.Join.ROUND);
fill.setStrokeWidth(2f * ringWidth);
fill.setShader(new LinearGradient(0f, 0f, 0f, size, ring.top, ring.bottom, Shader.TileMode.CLAMP));
edge.setStyle(Paint.Style.STROKE);
edge.setStrokeJoin(Paint.Join.ROUND);
edge.setColor(ring.ink);
edge.setStrokeWidth(Math.max(1f, lineWidth));
}
}
private static final Map<String, Prepared> CACHE = new HashMap<String, Prepared>();
private static final Paint SPRITE_PAINT = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
private static final RectF DESTINATION = new RectF();
private FrameDraw() {}
/** The frame prepared for `shape` at `size` pixels, or null while some of its pictures are not ready (`asking` is redrawn then). */
public static Prepared prepare(Context context, FrameIndex.Frame frame, ModSettings.AvatarShape shape, float size, View asking) {
String key = frame.id + "|" + shape.value() + "|" + Math.round(size) + "|" + FrameStore.version();
Prepared found = CACHE.get(key);
if (found != null) return found;
Bitmap[] bitmaps = new Bitmap[frame.parts.size()];
boolean ready = true;
for (int i = 0; i < bitmaps.length; i++) {
FrameIndex.Part part = frame.parts.get(i);
bitmaps[i] = FrameArt.get(context, part.sprite, Math.round(part.size * size), asking);
if (bitmaps[i] == null) ready = false;
}
if (!ready) return null;
Path path = Shapes.outline(shape, size, size);
Prepared made = new Prepared(frame, bitmaps, outlineOf(path, size), path, size);
if (CACHE.size() > 32) CACHE.clear();
CACHE.put(key, made);
return made;
}
private static Outline outlineOf(Path path, float size) {
PathMeasure measure = new PathMeasure(path, false);
float[] xs = new float[4096];
float[] ys = new float[4096];
int count = 0;
float[] at = new float[2];
do {
float length = measure.getLength();
float step = Math.max(0.5f, length / 1500f);
for (float distance = 0f; distance < length && count < xs.length; distance += step) {
if (measure.getPosTan(distance, at, null)) {
xs[count] = at[0];
ys[count] = at[1];
count++;
}
}
} while (measure.nextContour());
return Outline.of(xs, ys, count, size / 2f, size / 2f);
}
/** Before the avatar: the parts that sit behind it, then the ring. (cx, cy) is the middle of the avatar in the canvas. */
public static void drawBack(Canvas canvas, Prepared prepared, float cx, float cy) {
int save = canvas.save();
canvas.translate(cx - prepared.size / 2f, cy - prepared.size / 2f);
for (int i = 0; i < prepared.bitmaps.length; i++) {
if (!prepared.frame.parts.get(i).front) drawPart(canvas, prepared, i);
}
canvas.drawPath(prepared.path, prepared.ink);
canvas.drawPath(prepared.path, prepared.fill);
canvas.restoreToCount(save);
}
/** After the avatar: a thin line along its edge, then the parts that sit in front of it. */
public static void drawFront(Canvas canvas, Prepared prepared, float cx, float cy) {
int save = canvas.save();
canvas.translate(cx - prepared.size / 2f, cy - prepared.size / 2f);
canvas.drawPath(prepared.path, prepared.edge);
for (int i = 0; i < prepared.bitmaps.length; i++) {
if (prepared.frame.parts.get(i).front) drawPart(canvas, prepared, i);
}
canvas.restoreToCount(save);
}
private static void drawPart(Canvas canvas, Prepared prepared, int index) {
FrameIndex.Part part = prepared.frame.parts.get(index);
float[] point = prepared.outline.point(part.at);
float half = prepared.size / 2f;
float dx = point[0] - half;
float dy = point[1] - half;
float length = (float) Math.sqrt(dx * dx + dy * dy);
float x = point[0];
float y = point[1];
if (length > 0.001f && part.radial != 0f) {
x += dx / length * part.radial * prepared.size;
y += dy / length * part.radial * prepared.size;
}
float width = part.size * prepared.size;
float height = width * part.sprite.height / part.sprite.width;
int save = canvas.save();
canvas.translate(x, y);
canvas.rotate(prepared.outline.normalDegrees(part.at) + part.turn);
if (part.flip) canvas.scale(-1f, 1f);
DESTINATION.set(-part.ax * width, -part.ay * height, (1f - part.ax) * width, (1f - part.ay) * height);
canvas.drawBitmap(prepared.bitmaps[index], null, DESTINATION, SPRITE_PAINT);
canvas.restoreToCount(save);
}
}

View File

@@ -0,0 +1,335 @@
package lihont.two.frame;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import lihont.two.plugin.Json;
import lihont.two.plugin.LtpException;
/**
* The catalog of avatar frames, read from index.json.
*
* A frame is made of a ring that follows the outline of the avatar, whatever its shape, and parts (an ear, a lock of fur, a crown, a
* petal...) that hang on points of that outline: each part is a small transparent picture (a sprite), the angle of the outline point
* where it hangs (degrees clockwise from the top), its size as a part of the avatar, and how it is turned. Sprites are shared: one
* petal picture serves twelve places.
*
* The catalog comes from the network, so everything in it is checked: ids, file names (the files are fetched by name from the
* catalog's own folder, never from a path that climbs out of it), sizes, numbers and colours. A bad entry is left out, a bad
* catalog is refused as a whole.
*/
public final class FrameIndex {
public static final int MAX_PACKS = 40;
public static final int MAX_FRAMES_PER_PACK = 120;
public static final int MAX_SPRITES_PER_PACK = 80;
public static final int MAX_PARTS = 80;
public static final int MAX_SPRITE_BYTES = 150 * 1024;
public static final int MAX_MIRRORS = 6;
private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9_-]{0,23}");
private static final Pattern FILE = Pattern.compile("[a-z0-9][a-z0-9_-]{0,23}/[a-z0-9][a-z0-9_.-]{0,47}\\.png");
private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}");
private static final Pattern COLOR = Pattern.compile("#[0-9a-f]{6}");
private static final Pattern MIRROR = Pattern.compile("https://[a-z0-9.-]{3,80}(:[0-9]{2,5})?/[A-Za-z0-9._/-]{0,100}/");
/** One picture, kept under its checksum. `width` and `height` are its size in pixels. */
public static final class Sprite {
public final String file;
public final String sha256;
public final int bytes;
public final int width;
public final int height;
Sprite(String file, String sha256, int bytes, int width, int height) {
this.file = file;
this.sha256 = sha256;
this.bytes = bytes;
this.width = width;
this.height = height;
}
}
/** The ring round the avatar: widths as parts of the avatar's width, a gradient from `top` to `bottom`, and the dark line. */
public static final class Ring {
public final float width;
public final float line;
public final int top;
public final int bottom;
public final int ink;
Ring(float width, float line, int top, int bottom, int ink) {
this.width = width;
this.line = line;
this.top = top;
this.bottom = bottom;
this.ink = ink;
}
}
/**
* 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.
*/
public static final class Part {
public final Sprite sprite;
public final float ax;
public final float ay;
public final float at;
public final float size;
public final float turn;
public final float radial;
public final boolean flip;
public final boolean front;
Part(Sprite sprite, float ax, float ay, float at, float size, float turn, float radial, boolean flip, boolean front) {
this.sprite = sprite;
this.ax = ax;
this.ay = ay;
this.at = at;
this.size = size;
this.turn = turn;
this.radial = radial;
this.flip = flip;
this.front = front;
}
}
/** One frame: the global id is "pack.frame", e.g. "basic.cat". */
public static final class Frame {
public final String id;
public final String name;
public final Ring ring;
public final List<Part> parts;
Frame(String id, String name, Ring ring, List<Part> parts) {
this.id = id;
this.name = name;
this.ring = ring;
this.parts = parts;
}
}
public static final class Pack {
public final String id;
public final String name;
public final int version;
public final List<Frame> frames;
Pack(String id, String name, int version, List<Frame> frames) {
this.id = id;
this.name = name;
this.version = version;
this.frames = frames;
}
}
public final List<Pack> packs;
public final List<String> mirrors;
private final Map<String, Frame> byId = new LinkedHashMap<String, Frame>();
private FrameIndex(List<Pack> packs, List<String> mirrors) {
this.packs = packs;
this.mirrors = mirrors;
for (Pack pack : packs) for (Frame frame : pack.frames) byId.put(frame.id, frame);
}
public static FrameIndex empty() {
return new FrameIndex(new ArrayList<Pack>(), new ArrayList<String>());
}
/** The frame with this global id, or null (an id from a newer catalog that this phone has not got). */
public Frame frame(String id) {
return id == null ? null : byId.get(id);
}
public List<Frame> allFrames() {
return new ArrayList<Frame>(byId.values());
}
/** Every distinct picture the catalog uses, each once. */
public List<Sprite> allSprites() {
Map<String, Sprite> out = new LinkedHashMap<String, Sprite>();
for (Frame frame : byId.values()) for (Part part : frame.parts) out.put(part.sprite.sha256, part.sprite);
return new ArrayList<Sprite>(out.values());
}
public static boolean validFrameId(String id) {
if (id == null || id.length() > 49) return false;
int dot = id.indexOf('.');
return dot > 0 && dot == id.lastIndexOf('.') && ID.matcher(id.substring(0, dot)).matches()
&& ID.matcher(id.substring(dot + 1)).matches();
}
/** Parses and checks a catalog; throws IllegalArgumentException for one that is not a usable catalog at all. */
public static FrameIndex parse(String text) {
try {
return read(text);
} catch (LtpException bad) {
throw new IllegalArgumentException(bad.getMessage());
} catch (ClassCastException bad) {
throw new IllegalArgumentException("catalog shape");
}
}
@SuppressWarnings("unchecked")
private static FrameIndex read(String text) throws LtpException {
if (text == null || text.length() > 262144) throw new LtpException("catalog size");
Object tree = Json.parse(text);
if (!(tree instanceof Map)) throw new LtpException("catalog is not an object");
Map<String, Object> root = (Map<String, Object>) tree;
if (!(root.get("version") instanceof Double) || ((Double) root.get("version")).intValue() != 1) {
throw new LtpException("catalog version");
}
List<String> mirrors = new ArrayList<String>();
if (root.get("mirrors") instanceof List) {
for (Object item : (List<Object>) root.get("mirrors")) {
if (mirrors.size() < MAX_MIRRORS && item instanceof String && MIRROR.matcher((String) item).matches()
&& ((String) item).indexOf("..") < 0) {
mirrors.add((String) item);
}
}
}
if (!(root.get("packs") instanceof List)) throw new LtpException("packs");
List<Pack> packs = new ArrayList<Pack>();
Map<String, Boolean> seen = new LinkedHashMap<String, Boolean>();
for (Object rawPack : (List<Object>) root.get("packs")) {
if (packs.size() >= MAX_PACKS) break;
if (!(rawPack instanceof Map)) continue;
Map<String, Object> raw = (Map<String, Object>) rawPack;
String packId = string(raw, "id");
if (packId == null || !ID.matcher(packId).matches() || seen.containsKey(packId)) continue;
Map<String, Sprite> sprites = sprites(raw.get("sprites"), packId);
if (sprites.isEmpty() || !(raw.get("frames") instanceof List)) continue;
List<Frame> frames = new ArrayList<Frame>();
for (Object rawFrame : (List<Object>) raw.get("frames")) {
if (frames.size() >= MAX_FRAMES_PER_PACK) break;
Frame frame = frame(packId, rawFrame, sprites);
if (frame != null && !seen.containsKey(frame.id)) {
seen.put(frame.id, Boolean.TRUE);
frames.add(frame);
}
}
seen.put(packId, Boolean.TRUE);
if (frames.isEmpty()) continue;
String name = string(raw, "name");
Double version = raw.get("version") instanceof Double ? (Double) raw.get("version") : Double.valueOf(1);
packs.add(new Pack(packId, clean(name == null ? packId : name, 40), Math.max(1, version.intValue()), frames));
}
return new FrameIndex(packs, mirrors);
}
@SuppressWarnings("unchecked")
private static Map<String, Sprite> sprites(Object node, String packId) {
Map<String, Sprite> out = new LinkedHashMap<String, Sprite>();
if (!(node instanceof List)) return out;
for (Object item : (List<Object>) node) {
if (out.size() >= MAX_SPRITES_PER_PACK) break;
if (!(item instanceof Map)) continue;
Map<String, Object> raw = (Map<String, Object>) item;
String file = string(raw, "file");
String sha = string(raw, "sha256");
Integer bytes = whole(raw.get("bytes"), 1, MAX_SPRITE_BYTES);
Integer width = whole(raw.get("w"), 8, 1024);
Integer height = whole(raw.get("h"), 8, 1024);
if (file == null || sha == null || bytes == null || width == null || height == null
|| !FILE.matcher(file).matches() || file.indexOf("..") >= 0 || !file.startsWith(packId + "/")
|| !SHA256.matcher(sha).matches()) {
continue;
}
out.put(file, new Sprite(file, sha, bytes.intValue(), width.intValue(), height.intValue()));
}
return out;
}
@SuppressWarnings("unchecked")
private static Frame frame(String packId, Object node, Map<String, Sprite> sprites) {
if (!(node instanceof Map)) return null;
Map<String, Object> raw = (Map<String, Object>) node;
String frameId = string(raw, "id");
if (frameId == null || !ID.matcher(frameId).matches()) return null;
Ring ring = ring(raw.get("ring"));
if (ring == null || !(raw.get("parts") instanceof List)) return null;
List<Part> parts = new ArrayList<Part>();
for (Object item : (List<Object>) raw.get("parts")) {
if (parts.size() >= MAX_PARTS) return null; // a frame with too many parts is refused whole, not half drawn
Part part = part(item, sprites);
if (part == null) return null;
parts.add(part);
}
String name = string(raw, "name");
return new Frame(packId + "." + frameId, clean(name == null ? frameId : name, 40), ring, parts);
}
@SuppressWarnings("unchecked")
private static Ring ring(Object node) {
if (!(node instanceof Map)) return null;
Map<String, Object> raw = (Map<String, Object>) node;
Double width = number(raw.get("width"), 0, 0.15);
Double line = number(raw.get("line"), 0, 0.04);
String ink = string(raw, "ink");
if (width == null || line == null || ink == null || !COLOR.matcher(ink).matches()
|| !(raw.get("fill") instanceof List) || ((List<Object>) raw.get("fill")).size() != 2) {
return null;
}
List<Object> fill = (List<Object>) raw.get("fill");
if (!(fill.get(0) instanceof String) || !(fill.get(1) instanceof String)
|| !COLOR.matcher((String) fill.get(0)).matches() || !COLOR.matcher((String) fill.get(1)).matches()) {
return null;
}
return new Ring(width.floatValue(), line.floatValue(), rgb((String) fill.get(0)), rgb((String) fill.get(1)), rgb(ink));
}
@SuppressWarnings("unchecked")
private static Part part(Object node, Map<String, Sprite> sprites) {
if (!(node instanceof Map)) return null;
Map<String, Object> raw = (Map<String, Object>) node;
Sprite sprite = sprites.get(string(raw, "file"));
Double ax = number(raw.get("ax"), -0.5, 1.5);
Double ay = number(raw.get("ay"), -0.5, 1.5);
Double at = number(raw.get("at"), -360, 360);
Double size = number(raw.get("size"), 0.02, 1.2);
Double turn = raw.get("turn") == null ? Double.valueOf(0) : number(raw.get("turn"), -180, 180);
Double radial = raw.get("radial") == null ? Double.valueOf(0) : number(raw.get("radial"), -0.6, 0.6);
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"));
return new Part(sprite, ax.floatValue(), ay.floatValue(), at.floatValue(), size.floatValue(), turn.floatValue(),
radial.floatValue(), flip, front);
}
private static String string(Map<String, Object> from, String key) {
Object value = from.get(key);
return value instanceof String ? (String) value : null;
}
private static Double number(Object value, double min, double max) {
if (!(value instanceof Double)) return null;
double number = ((Double) value).doubleValue();
return number >= min && number <= max ? (Double) value : null;
}
private static Integer whole(Object value, int min, int max) {
Double number = number(value, min, max);
return number == null || number.doubleValue() != Math.rint(number.doubleValue()) ? null : Integer.valueOf(number.intValue());
}
private static int rgb(String color) {
return 0xFF000000 | Integer.parseInt(color.substring(1), 16);
}
/** A name for the screen: no control characters, no line breaks, at most `max` characters. */
static String clean(String name, int max) {
StringBuilder out = new StringBuilder();
for (int i = 0; i < name.length() && out.length() < max; i++) {
char c = name.charAt(i);
if (c >= 32 && c != 127) out.append(c);
}
String text = out.toString().trim();
return text.length() == 0 ? "?" : text;
}
}

View File

@@ -0,0 +1,54 @@
package lihont.two.frame;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
import lihont.two.settings.ModSettings;
/**
* A frame on a plain round avatar, for the picker in the settings (a null frame shows the avatar alone). It draws with the very code
* that draws frames in the application, so what the person sees here is what the feed will show. The frame reaches out of the square
* of the view, so the parent should not clip its children.
*/
public final class FramePreviewView extends View {
private final String frameId;
private final Paint avatar = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint glyph = new Paint(Paint.ANTI_ALIAS_FLAG);
public FramePreviewView(Context context, String frameId, int avatarColor, int glyphColor) {
super(context);
this.frameId = frameId;
avatar.setColor(avatarColor);
glyph.setColor(glyphColor);
setClipToOutline(false);
}
@Override protected void onDraw(Canvas canvas) {
float w = getWidth();
float h = getHeight();
float d = Math.min(w, h) * 0.52f;
float cx = w / 2f;
float cy = h / 2f + d * 0.06f;
FrameDraw.Prepared prepared = null;
if (frameId != null) {
FrameIndex.Frame frame = FrameStore.index(getContext()).frame(frameId);
if (frame != null) prepared = FrameDraw.prepare(getContext(), frame, ModSettings.AvatarShape.CIRCLE, d, this);
}
if (prepared != null) FrameDraw.drawBack(canvas, prepared, cx, cy);
canvas.drawCircle(cx, cy, d / 2f, avatar);
canvas.drawCircle(cx, cy - d * 0.12f, d * 0.17f, glyph);
int save = canvas.save();
canvas.clipPath(circle(cx, cy, d / 2f));
canvas.drawCircle(cx, cy + d * 0.5f, d * 0.34f, glyph);
canvas.restoreToCount(save);
if (prepared != null) FrameDraw.drawFront(canvas, prepared, cx, cy);
}
private static android.graphics.Path circle(float cx, float cy, float r) {
android.graphics.Path path = new android.graphics.Path();
path.addCircle(cx, cy, r, android.graphics.Path.Direction.CW);
return path;
}
}

View File

@@ -0,0 +1,251 @@
package lihont.two.frame;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
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.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* The frames this phone has, and how new ones arrive.
*
* The catalog (index.json) and the pictures live in one private folder; every picture is stored under its own checksum, so a
* file is either exactly what the catalog promised or is not there. A refresh asks the mirrors in turn (the built-in list, then
* those the catalog names itself), takes the first catalog that is valid and fetches only the pictures that are missing. New
* packs therefore appear by themselves, without a new version of the mod, and a mirror that is blocked costs one failed request.
* Nothing but this catalog and its pictures is fetched, and nothing about the person is sent.
*/
public final class FrameStore {
private static final String TAG = "LIHONT";
private static final String PREFS = "lihont_frames";
private static final String[] MIRRORS = {
"https://lihont.space/frames/",
"https://lihont.lihon.online/frames/",
"https://git.lihont.space/lihont/LihonT/raw/branch/main/frames/",
};
private static final long FRESH_MS = 6L * 3600L * 1000L;
private static final long RETRY_MS = 15L * 60L * 1000L;
private static final int INDEX_LIMIT = 262144;
private static final Handler MAIN = new Handler(Looper.getMainLooper());
private static FrameIndex index;
private static volatile int version;
private static boolean running;
private static final List<Runnable> LISTENERS = new ArrayList<Runnable>();
private FrameStore() {}
/** The catalog this phone has (empty until the first refresh has brought one). Never null, never throws. */
public static synchronized FrameIndex index(Context context) {
if (index == null) {
index = FrameIndex.empty();
try {
File file = new File(folder(context), "index.json");
if (file.isFile() && file.length() <= INDEX_LIMIT) {
index = FrameIndex.parse(new String(readAll(file), StandardCharsets.UTF_8));
}
} catch (Exception unreadable) {
index = FrameIndex.empty();
}
}
return index;
}
/** Counts the times the set of frames changed; the pictures held in memory are dropped when it moves. */
public static int version() {
return version;
}
/** The stored picture of a sprite, or null when it has not been fetched (yet). */
public static File file(Context context, FrameIndex.Sprite sprite) {
File file = new File(folder(context), sprite.sha256 + ".png");
return file.isFile() ? file : null;
}
/** Called (on the main thread) when new frames have arrived. */
public static void onChanged(Runnable listener) {
synchronized (LISTENERS) {
if (!LISTENERS.contains(listener)) LISTENERS.add(listener);
}
}
public static void removeListener(Runnable listener) {
synchronized (LISTENERS) {
LISTENERS.remove(listener);
}
}
/** Asks the mirrors for a newer catalog, at most every few hours unless `force`. Returns at once; never throws. */
public static void refresh(Context context, boolean force) {
final Context app = context.getApplicationContext() != null ? context.getApplicationContext() : context;
synchronized (FrameStore.class) {
if (running) return;
SharedPreferences prefs = app.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
long now = System.currentTimeMillis();
if (!force && (now - prefs.getLong("ok", 0L) < FRESH_MS || now - prefs.getLong("try", 0L) < RETRY_MS)) return;
prefs.edit().putLong("try", now).apply();
running = true;
}
Thread worker = new Thread(new Runnable() {
@Override public void run() {
boolean changed = false;
try {
changed = fetch(app);
} catch (Throwable failed) {
try {
Log.i(TAG, "frames: refresh failed: " + failed.getClass().getSimpleName());
} catch (Throwable noLogger) {
// diagnostic only
}
} finally {
synchronized (FrameStore.class) {
running = false;
}
}
if (changed) {
version++;
MAIN.post(new Runnable() {
@Override public void run() {
List<Runnable> copy;
synchronized (LISTENERS) {
copy = new ArrayList<Runnable>(LISTENERS);
}
for (Runnable listener : copy) listener.run();
}
});
}
}
}, "lihont-frames");
worker.setDaemon(true);
worker.start();
}
/** True when something changed (a new catalog or new pictures). */
private static boolean fetch(Context context) throws Exception {
List<String> bases = new ArrayList<String>();
for (String mirror : MIRRORS) bases.add(mirror);
File folder = folder(context);
String stored = null;
File current = new File(folder, "index.json");
if (current.isFile()) stored = new String(readAll(current), StandardCharsets.UTF_8);
for (int turn = 0; turn < bases.size(); turn++) {
String base = bases.get(turn);
try {
String text = new String(get(base + "index.json", INDEX_LIMIT), StandardCharsets.UTF_8);
FrameIndex fresh = FrameIndex.parse(text);
for (String extra : fresh.mirrors) if (!bases.contains(extra)) bases.add(extra);
boolean changed = false;
Set<String> wanted = new HashSet<String>();
for (FrameIndex.Sprite sprite : fresh.allSprites()) {
wanted.add(sprite.sha256 + ".png");
File target = new File(folder, sprite.sha256 + ".png");
if (target.isFile()) continue;
byte[] data = get(base + sprite.file, sprite.bytes);
if (data.length != sprite.bytes || !sprite.sha256.equals(sha256(data))) {
throw new IOException("checksum of " + sprite.file);
}
File part = new File(folder, sprite.sha256 + ".part");
try (FileOutputStream out = new FileOutputStream(part)) {
out.write(data);
}
if (!part.renameTo(target)) throw new IOException("rename");
changed = true;
}
if (!text.equals(stored)) {
File part = new File(folder, "index.part");
try (FileOutputStream out = new FileOutputStream(part)) {
out.write(text.getBytes(StandardCharsets.UTF_8));
}
if (!part.renameTo(current) && !(current.delete() && part.renameTo(current))) throw new IOException("index");
synchronized (FrameStore.class) {
index = fresh;
}
changed = true;
}
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
String name = file.getName();
if ((name.endsWith(".png") && !wanted.contains(name)) || name.endsWith(".part")) file.delete();
}
}
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putLong("ok", System.currentTimeMillis()).apply();
try {
Log.i(TAG, "frames: " + fresh.allFrames().size() + " frames in " + fresh.packs.size()
+ " packs from " + base + (changed ? " (new)" : " (same)"));
} catch (Throwable noLogger) {
// diagnostic only
}
return changed;
} catch (Exception failed) {
// this mirror is down or sends rubbish: the next one
}
}
return false;
}
private 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 {
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);
connection.setRequestProperty("User-Agent", "LihonT-Frames/1");
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() > limit) throw new IOException("too large");
}
return out.toByteArray();
}
} finally {
connection.disconnect();
}
}
private static byte[] readAll(File file) throws IOException {
try (java.io.FileInputStream in = new java.io.FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) >= 0) out.write(buffer, 0, count);
return out.toByteArray();
}
}
static String sha256(byte[] data) throws IOException {
try {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(data);
StringBuilder hex = new StringBuilder(64);
for (byte b : digest) hex.append(Character.forDigit((b >> 4) & 15, 16)).append(Character.forDigit(b & 15, 16));
return hex.toString();
} catch (java.security.NoSuchAlgorithmException missing) {
throw new IOException(missing);
}
}
}

View File

@@ -0,0 +1,77 @@
package lihont.two.frame;
/**
* How far an avatar's outline reaches from its middle, in every direction, so that a part of a frame can be hung on "the point of
* the outline at 40 degrees" whatever the shape is. Angles are degrees clockwise from the top. Every shape of the mod is star-shaped
* round its middle (a ray from the middle meets the outline once), so a table of 360 distances describes it.
*/
public final class Outline {
private final float[] reach = new float[360];
private final float cx;
private final float cy;
private Outline(float cx, float cy) {
this.cx = cx;
this.cy = cy;
}
/** Builds the table from points taken along the outline (any order, about a pixel apart); the middle is (cx, cy). */
public static Outline of(float[] xs, float[] ys, int count, float cx, float cy) {
Outline outline = new Outline(cx, cy);
boolean[] known = new boolean[360];
for (int i = 0; i < count; i++) {
float dx = xs[i] - cx;
float dy = ys[i] - cy;
float r = (float) Math.sqrt(dx * dx + dy * dy);
if (r < 0.001f) continue;
int bin = (int) Math.floor(Math.toDegrees(Math.atan2(dx, -dy)));
bin = ((bin % 360) + 360) % 360;
if (!known[bin] || r > outline.reach[bin]) {
outline.reach[bin] = r;
known[bin] = true;
}
}
outline.fill(known);
return outline;
}
/** Directions no point fell on take the distance of their nearest known neighbours (a straight stretch between them). */
private void fill(boolean[] known) {
int any = -1;
for (int i = 0; i < 360; i++) if (known[i]) { any = i; break; }
if (any < 0) return;
for (int i = 0; i < 360; i++) {
if (known[i]) continue;
int before = i;
int after = i;
int back = 0;
int ahead = 0;
while (!known[((before % 360) + 360) % 360] && back < 360) { before--; back++; }
while (!known[after % 360] && ahead < 360) { after++; ahead++; }
float low = reach[((before % 360) + 360) % 360];
float high = reach[after % 360];
reach[i] = low + (high - low) * back / (float) (back + ahead);
}
}
/** The point of the outline in direction `degrees`, as {x, y}. */
public float[] point(float degrees) {
float d = degrees % 360f;
if (d < 0) d += 360f;
int i = (int) Math.floor(d);
float f = d - i;
float r = reach[i % 360] * (1f - f) + reach[(i + 1) % 360] * f;
double a = Math.toRadians(d);
return new float[] {cx + r * (float) Math.sin(a), cy - r * (float) Math.cos(a)};
}
/** The direction pointing away from the avatar at that point, as a turn (degrees clockwise from "up") for a sprite. */
public float normalDegrees(float degrees) {
float[] before = point(degrees - 3f);
float[] after = point(degrees + 3f);
float tx = after[0] - before[0];
float ty = after[1] - before[1];
// the outward normal of the tangent (tx, ty) is (ty, -tx); as a turn from "up" that is atan2(ty, tx)
return (float) Math.toDegrees(Math.atan2(ty, tx));
}
}

View File

@@ -0,0 +1,82 @@
package lihont.two.look;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* The diary of the mod: what it noticed and did, copied out in one tap so that it can be sent to whoever helps.
*
* The mod writes every note to the system log under the tag LIHONT; the app may read its own lines of that log, so nothing
* has to be stored apart. The last few hundred lines are put on the clipboard. They hold the mod's own notes (which hooks
* worked, which screens were skinned, what the plugins did), never the text of a message.
*/
public final class Diary {
private static final int MAX_LINES = 400;
private static final long MAX_WAIT_MS = 8000L;
private Diary() {}
/** Reads the diary on a background thread and puts it on the clipboard; tells the person how many lines went there. */
public static void copy(final Activity activity) {
final Context app = activity.getApplicationContext();
final Handler ui = new Handler(Looper.getMainLooper());
new Thread(new Runnable() {
@Override public void run() {
final String text = read();
ui.post(new Runnable() {
@Override public void run() {
if (activity.isFinishing()) return;
try {
ClipboardManager board = (ClipboardManager) app.getSystemService(Context.CLIPBOARD_SERVICE);
if (text.length() == 0 || board == null) {
Toast.makeText(app, "Дневник пуст: записей мода пока нет", Toast.LENGTH_LONG).show();
return;
}
board.setPrimaryClip(ClipData.newPlainText("Дневник LihonT", text));
int lines = text.split("\n").length;
Toast.makeText(app, "Дневник скопирован: " + lines + " строк. Сообщений в нём нет.",
Toast.LENGTH_LONG).show();
} catch (RuntimeException failure) {
Toast.makeText(app, "Не удалось скопировать дневник", Toast.LENGTH_LONG).show();
}
}
});
}
}, "lihont-diary").start();
}
/** The last lines of the mod's own notes, oldest first; empty when the log cannot be read. */
static String read() {
Process process = null;
try {
process = new ProcessBuilder("logcat", "-d", "-v", "time", "-s", "LIHONT:I").redirectErrorStream(true).start();
Deque<String> last = new ArrayDeque<String>();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
long until = System.currentTimeMillis() + MAX_WAIT_MS;
String line;
while ((line = in.readLine()) != null && System.currentTimeMillis() < until) {
if (line.startsWith("---------")) continue;
last.addLast(line);
if (last.size() > MAX_LINES) last.removeFirst();
}
StringBuilder out = new StringBuilder();
for (String kept : last) out.append(kept).append('\n');
return out.toString();
} catch (IOException unreadable) {
return "";
} finally {
if (process != null) process.destroy();
}
}
}

View File

@@ -0,0 +1,42 @@
package lihont.two.look;
import android.content.Context;
import android.content.SharedPreferences;
import lihont.two.widget.AppContext;
/**
* The scrubbing bar under every video. TikTok hides it on some videos (type 3 of its show-type switch); with this switch on
* the hidden type is read as the plain visible one (see lihont/seekbar_patch.py), so the bar can be dragged everywhere.
*/
public final class Seekbar {
private static final String PREFS = "lihont_look";
private static final String KEY = "seekbar";
private static final int HIDDEN = 3;
private static final int SHOWN = 0;
private Seekbar() {}
/** Asked by TikTok before it applies a show type: returns the type to apply. */
public static int type(int asked) {
if (asked != HIDDEN) return asked;
return on(AppContext.get()) ? SHOWN : asked;
}
public static boolean on(Context context) {
if (context == null) return false;
try {
return prefs(context).getBoolean(KEY, false);
} catch (RuntimeException unreadable) {
return false;
}
}
public static void set(Context context, boolean on) {
prefs(context).edit().putBoolean(KEY, on).apply();
}
private static SharedPreferences prefs(Context context) {
return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE);
}
}

View File

@@ -0,0 +1,101 @@
package lihont.two.media;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Reads what is needed to save someone's profile picture out of the public profile page of TikTok: the user name is checked, and the
* addresses of the picture (largest first) are taken from the page's data. Plain Java, so it is tested on a plain JVM.
*/
public final class ProfileAddresses {
private static final Pattern NAME = Pattern.compile("[A-Za-z0-9_.]{2,24}");
private static final Pattern FIELD = Pattern.compile("\"(avatarLarger|avatarMedium|avatarThumb)\":\"((?:[^\"\\\\]|\\\\.)*)\"");
private static final String MARKER = "\"webapp.user-detail\"";
private ProfileAddresses() {}
/** The user name without "@" and spaces, or null when it cannot be a TikTok name. */
public static String cleanName(String typed) {
if (typed == null) return null;
String name = typed.trim();
if (name.startsWith("@")) name = name.substring(1);
return NAME.matcher(name).matches() && !name.endsWith(".") ? name : null;
}
/** The public profile page to read for this (already cleaned) name. */
public static String pageOf(String name) {
return "https://www.tiktok.com/@" + name;
}
/** The picture's addresses, the largest first, of the account whose data begins at the profile marker; empty if there are none. */
public static List<String> addresses(String page) {
List<String> out = new ArrayList<String>();
if (page == null) return out;
int from = page.indexOf(MARKER);
if (from < 0) return out;
String large = null;
String medium = null;
String thumb = null;
Matcher matcher = FIELD.matcher(page);
matcher.region(from, Math.min(page.length(), from + 60000));
while (matcher.find() && (large == null || medium == null || thumb == null)) {
String url = unescape(matcher.group(2));
if (!allowed(url)) continue;
String field = matcher.group(1);
if (field.equals("avatarLarger") && large == null) large = url;
else if (field.equals("avatarMedium") && medium == null) medium = url;
else if (field.equals("avatarThumb") && thumb == null) thumb = url;
}
if (large != null) out.add(large);
if (medium != null) out.add(medium);
if (thumb != null) out.add(thumb);
return out;
}
/** Only https addresses on TikTok's own picture hosts: whatever the page says, nothing else is fetched. */
static boolean allowed(String url) {
if (url == null || !url.startsWith("https://") || url.length() > 800) return false;
int end = url.indexOf('/', 8);
if (end < 0) return false;
String host = url.substring(8, end).toLowerCase(java.util.Locale.ROOT);
if (host.indexOf('@') >= 0 || host.indexOf(':') >= 0) return false;
return host.endsWith(".tiktokcdn.com") || host.endsWith(".tiktokcdn-eu.com") || host.endsWith(".tiktokcdn-us.com")
|| host.endsWith(".tiktokv.com") || host.endsWith(".byteoversea.com") || host.endsWith(".ibytedtos.com");
}
/** A JSON string without its quotes: \\uXXXX, \\/, \\\\ and \\" are undone. */
static String unescape(String text) {
StringBuilder out = new StringBuilder(text.length());
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c != '\\' || i + 1 >= text.length()) {
out.append(c);
continue;
}
char next = text.charAt(++i);
switch (next) {
case 'u':
if (i + 4 < text.length()) {
try {
out.append((char) Integer.parseInt(text.substring(i + 1, i + 5), 16));
i += 4;
break;
} catch (NumberFormatException bad) {
out.append("\\u");
break;
}
}
out.append("\\u");
break;
case '/': out.append('/'); break;
case '\\': out.append('\\'); break;
case '"': out.append('"'); break;
case 'n': out.append('\n'); break;
default: out.append('\\').append(next);
}
}
return out.toString();
}
}

View File

@@ -0,0 +1,91 @@
package lihont.two.media;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* Saves a profile picture of any public account by its user name: the public profile page is read, the address of the largest
* picture is taken from it, and the picture goes to the gallery (Pictures/LihonT) through the same job as every other download.
* Only the name that was typed goes out, to tiktok.com; nothing about the person using the mod.
*/
public final class ProfilePictures {
private static final String TAG = "LIHONT";
private static final String AGENT = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/124.0 Mobile Safari/537.36";
private static final int PAGE_LIMIT = 4 * 1024 * 1024;
private static final Handler MAIN = new Handler(Looper.getMainLooper());
private ProfilePictures() {}
/** Starts saving; reports with toasts; never throws. Returns false at once when the typed text cannot be a user name. */
public static boolean save(final Context context, String typed) {
final String name = ProfileAddresses.cleanName(typed);
if (name == null) return false;
final Context app = context.getApplicationContext() != null ? context.getApplicationContext() : context;
say(app, "Ищу аватарку @" + name + "…");
Thread worker = new Thread(new Runnable() {
@Override public void run() {
try {
List<String> addresses = ProfileAddresses.addresses(readPage(ProfileAddresses.pageOf(name)));
if (addresses.isEmpty()) {
say(app, "У @" + name + " аватарку не нашли: аккаунта нет или он закрыт");
return;
}
new DownloadJob(app, DownloadJob.Kind.IMAGE, addresses, "avatar-" + name).start("аватарка @" + name);
} catch (Throwable failure) {
Log.i(TAG, "profile-picture: failed " + failure);
say(app, "Не удалось получить страницу: " + (failure.getMessage() == null
? failure.getClass().getSimpleName() : failure.getMessage()));
}
}
}, "lihont-profile-picture");
worker.setDaemon(true);
worker.start();
return true;
}
private static String readPage(String address) throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(address).openConnection();
connection.setConnectTimeout(8000);
connection.setReadTimeout(15000);
connection.setInstanceFollowRedirects(false);
connection.setRequestProperty("User-Agent", AGENT);
try {
if (connection.getResponseCode() != 200) throw new IOException("страница ответила " + connection.getResponseCode());
try (InputStream in = connection.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
byte[] buffer = new byte[16384];
int count;
while ((count = in.read(buffer)) >= 0) {
out.write(buffer, 0, count);
if (out.size() > PAGE_LIMIT) break; // the data we need is near the start; a huge page is read only in part
}
return new String(out.toByteArray(), StandardCharsets.UTF_8);
}
} finally {
connection.disconnect();
}
}
private static void say(final Context context, final String message) {
MAIN.post(new Runnable() {
@Override public void run() {
try {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
} catch (Throwable noToast) {
// reporting only
}
}
});
}
}

View File

@@ -11,7 +11,7 @@ import java.util.Map;
* org.json so that the same code runs in the unit tests on a plain JVM, and so that a hostile file cannot make
* the parser do anything but fail.
*/
final class Json {
public final class Json {
static final int MAX_DEPTH = 24;
static final int MAX_CHARS = 256 * 1024;
@@ -25,7 +25,7 @@ final class Json {
this.text = text;
}
static Object parse(String text) throws LtpException {
public static Object parse(String text) throws LtpException {
if (text == null || text.length() > MAX_CHARS) throw new LtpException("Файл плагина слишком большой");
Json reader = new Json(text.length() > 0 && text.charAt(0) == '' ? text.substring(1) : text);
Object value = reader.value(0);

View File

@@ -46,13 +46,18 @@ 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 alpha";
private static final String VERSION_LINE = "LihonT 2.0 · Serena beta";
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 =
"• Serena alpha: оформление на выбор (Material 3, Стикеры или обычный TikTok) в настройках мода.\n"
"• Рамки аватарок: рамка повторяет форму аватарки, наборы рамок приходят сами, без обновления мода. Выбранную рамку видят другие с модом.\n"
+ "• Сохранить аватарку по нику в Галерею (папка LihonT).\n"
+ "• Дневник мода: записи мода копируются одним нажатием. Полоса перемотки на каждом видео.\n"
+ "• Темы «Стикеры» и Windows 95, темы и значки кнопок из плагинов, конфетти и вибрация в плагинах.\n"
+ "• Режим DEBUG: «Очистить кэш» в сведениях о приложении сбрасывает оформление и плагины.\n"
+ "• Оформление на выбор (Material 3, Стикеры или обычный TikTok) в настройках мода.\n"
+ "• Призрак (раздел «Приватность»): истории без отметки о просмотре и чаты без «прочитано». Переключатели выключены, пока вы их не включите.\n"
+ "• Несколько фото в одном комментарии (до 9), если это даёт сервер для вашего аккаунта.\n"
+ "• Плагины .ltp: правила для ленты, имён и картинок без кода. Права вы одобряете сами, плагины включаются на каждый аккаунт отдельно, есть журнал, откат версии и защитник, который говорит простыми словами, что делает плагин.\n"
@@ -197,9 +202,13 @@ public final class LihonTSettingsActivity extends Activity {
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DOWNLOAD, palette.onPrimaryContainer, 8),
settings.noWatermark(), TOGGLE_NO_WATERMARK));
cardFunc.addView(Md3.cardDivider(this, palette));
cardFunc.addView(seekbarRow());
cardFunc.addView(Md3.cardDivider(this, palette));
cardFunc.addView(switchRow("Меню сохранения", "Качество от меньшего к большему, только звук, фото карусели",
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DOWNLOAD, palette.onPrimaryContainer, 8),
settings.downloadMenu(), TOGGLE_MENU));
cardFunc.addView(Md3.cardDivider(this, palette));
cardFunc.addView(saveAvatarRow());
addSection("Функции", cardFunc, true);
LinearLayout cardPrivacy = Md3.card(this, palette);
@@ -210,6 +219,8 @@ public final class LihonTSettingsActivity extends Activity {
LinearLayout cardDebug = Md3.card(this, palette);
cardDebug.addView(debugRow());
cardDebug.addView(Md3.cardDivider(this, palette));
cardDebug.addView(diaryRow());
addSection("Восстановление", cardDebug, false);
LinearLayout cardChat = Md3.card(this, palette);
@@ -262,6 +273,8 @@ public final class LihonTSettingsActivity extends Activity {
cardParams.addView(Md3.cardDivider(this, palette));
cardParams.addView(shapeRow());
cardParams.addView(Md3.cardDivider(this, palette));
cardParams.addView(frameRow());
cardParams.addView(Md3.cardDivider(this, palette));
cardParams.addView(switchRow("AMOLED: чёрный фон", "Чистый чёрный в тёмной теме",
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.MOON, palette.onPrimaryContainer, 8),
settings.amoled(), TOGGLE_AMOLED));
@@ -417,6 +430,16 @@ public final class LihonTSettingsActivity extends Activity {
return row;
}
/** The diary of the mod: its own notes, copied in one tap to be sent to whoever helps. */
private View diaryRow() {
LinearLayout row = Md3.listItem(this, palette,
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.INFO, palette.onPrimaryContainer, 8),
"Дневник мода", "Что мод заметил и сделал: последние строки копируются в один тап. Сообщений там нет",
Md3.chevron(this, palette), true);
row.setOnClickListener(v -> lihont.two.look.Diary.copy(this));
return row;
}
private String styleName() {
if (!settings.md3()) return "Обычный TikTok";
ThemeSpec theme = ThemeEngine.active(this);
@@ -548,6 +571,71 @@ public final class LihonTSettingsActivity extends Activity {
return row;
}
/** Saves the profile picture of any public account, by its user name, into the gallery. */
private View saveAvatarRow() {
LinearLayout row = Md3.listItem(this, palette,
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DOWNLOAD, palette.onPrimaryContainer, 8),
"Сохранить аватарку по нику", "Введите @ник: большая аватарка сохранится в Галерею, в папку LihonT",
Md3.chevron(this, palette), true);
row.setOnClickListener(v -> openSaveAvatarDialog());
return row;
}
private void openSaveAvatarDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
LinearLayout box = new LinearLayout(this);
box.setOrientation(LinearLayout.VERTICAL);
box.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16));
box.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this));
box.addView(Md3.text(this, "Сохранить аватарку", Md3.HEADLINE_SMALL, false, palette.onSurface));
TextView info = Md3.text(this, "Ник аккаунта, как в его профиле: @ник. Аккаунт должен быть открытым.",
Md3.BODY_MEDIUM, false, palette.onSurfaceVariant);
info.setPadding(0, Md3.dp(this, 12), 0, Md3.dp(this, 12));
box.addView(info);
final EditText input = new EditText(this);
input.setSingleLine(true);
input.setHint("@ник");
input.setTextColor(palette.onSurface);
input.setHintTextColor(palette.onSurfaceVariant);
input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(26)});
box.addView(input);
LinearLayout buttons = new LinearLayout(this);
buttons.setGravity(Gravity.END);
buttons.setPadding(0, Md3.dp(this, 16), 0, 0);
TextView cancel = Md3.textButton(this, palette, "Отмена");
TextView save = Md3.filledButton(this, palette, "Сохранить");
buttons.addView(cancel);
buttons.addView(save);
box.addView(buttons);
cancel.setOnClickListener(v -> dialog.dismiss());
save.setOnClickListener(v -> {
if (lihont.two.media.ProfilePictures.save(this, input.getText().toString())) {
dialog.dismiss();
} else {
Toast.makeText(this, "Это не похоже на ник TikTok: буквы, цифры, точка и подчёркивание", Toast.LENGTH_LONG).show();
}
});
dialog.setContentView(box);
styleDialog(dialog);
dialog.show();
sizeDialog(dialog, 0.92f);
}
/** The scrubbing bar under every video, also where TikTok hides it. */
private View seekbarRow() {
Md3Switch toggle = new Md3Switch(this, palette);
toggle.setContentDescription("Полоса перемотки");
toggle.setChecked(lihont.two.look.Seekbar.on(this), false);
toggle.setOnCheckedChangeListener((view, value) -> lihont.two.look.Seekbar.set(this, value));
LinearLayout row = Md3.listItem(this, palette,
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DOWNLOAD, palette.onPrimaryContainer, 8),
"Полоса перемотки", "Всегда показывать полосу перемотки под видео, даже там, где TikTok её прячет",
toggle, true);
row.setOnClickListener(v -> toggle.toggle());
return row;
}
/** Ghost mode for stories: the view is not reported, so the author does not see the person among the viewers. */
private View ghostStoriesRow() {
Md3Switch toggle = new Md3Switch(this, palette);
@@ -878,25 +966,25 @@ public final class LihonTSettingsActivity extends Activity {
if (result.published) {
Toast.makeText(this, result.message, Toast.LENGTH_LONG).show();
} else if (result.code != null) {
openShapeProofDialog(option, result.code);
openProofDialog("форму", result.code, retry -> lihont.two.avatar.ShapePublisher.publish(this, option, retry));
} else {
Toast.makeText(this, result.message, Toast.LENGTH_LONG).show();
}
});
}
private void openShapeProofDialog(final ModSettings.AvatarShape option, final String proof) {
private void openProofDialog(final String what, final String proof, final java.util.function.Consumer<lihont.two.avatar.ShapePublisher.Callback> publish) {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
LinearLayout box = new LinearLayout(this);
box.setOrientation(LinearLayout.VERTICAL);
box.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16));
box.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this));
box.addView(Md3.text(this, "Показать форму другим", Md3.HEADLINE_SMALL, false, palette.onSurface));
box.addView(Md3.text(this, "Показать " + what + " другим", Md3.HEADLINE_SMALL, false, palette.onSurface));
final TextView info = Md3.text(this,
"У вас форма уже стоит. Чтобы её видели и другие с модом, сервер должен убедиться, что аккаунт ваш.\n"
"У вас выбор уже сохранён. Чтобы его видели и другие с модом, сервер должен убедиться, что аккаунт ваш.\n"
+ "1. Скопируйте код.\n2. Вставьте его в описание профиля TikTok.\n"
+ "3. Нажмите «Проверить»: после этого форму можно менять без кода.",
+ "3. Нажмите «Проверить»: после этого менять можно без кода.",
Md3.BODY_MEDIUM, false, palette.onSurfaceVariant);
info.setPadding(0, Md3.dp(this, 12), 0, Md3.dp(this, 12));
box.addView(info);
@@ -923,7 +1011,7 @@ public final class LihonTSettingsActivity extends Activity {
});
check.setOnClickListener(v -> {
result.setText("Проверяем…");
lihont.two.avatar.ShapePublisher.publish(this, option, outcome -> {
publish.accept(outcome -> {
result.setText(outcome.message);
if (outcome.published) Toast.makeText(this, outcome.message, Toast.LENGTH_LONG).show();
});
@@ -934,6 +1022,144 @@ public final class LihonTSettingsActivity extends Activity {
sizeDialog(dialog, 0.92f);
}
/** The frame belongs to the account that is signed in, like the shape: every account on the phone has its own. */
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.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)));
String subtitle = account == null ? "Войдите в TikTok, чтобы выбрать рамку"
: (frame == null ? "Без рамки" : frame.name) + " · @" + account;
LinearLayout row = Md3.listItem(this, palette, preview, "Рамка аватарки", subtitle, Md3.chevron(this, palette), true);
row.setOnClickListener(v -> openFramePicker());
lihont.two.frame.FrameStore.refresh(this, false);
return row;
}
/** A grid of the frames the catalog holds, a new pack appearing in it by itself once the phone has fetched it. */
private void openFramePicker() {
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);
final 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, 12), Md3.dp(this, 16), Md3.dp(this, 12), Md3.dp(this, 12));
final Runnable fill = new Runnable() {
@Override public void run() {
fillFramePicker(root, dialog, uid);
}
};
fill.run();
lihont.two.frame.FrameStore.onChanged(fill);
dialog.setOnDismissListener(d -> lihont.two.frame.FrameStore.removeListener(fill));
lihont.two.frame.FrameStore.refresh(this, false);
ScrollView scroll = new ScrollView(this);
scroll.setClipChildren(false);
scroll.addView(root);
dialog.setContentView(scroll);
styleDialog(dialog);
dialog.show();
sizeDialog(dialog, 0.94f);
}
private void fillFramePicker(final LinearLayout root, final Dialog dialog, final String uid) {
root.removeAllViews();
root.addView(Md3.text(this, "Рамка аватарки", Md3.HEADLINE_SMALL, false, palette.onSurface));
lihont.two.frame.FrameIndex index = lihont.two.frame.FrameStore.index(this);
int total = index.allFrames().size();
TextView info = Md3.text(this, total == 0
? "Рамки ещё не загружены: нужен интернет. Они подгрузятся сами."
: "Рамка повторяет форму аватарки. Новые наборы появляются здесь сами, без обновления мода.",
Md3.BODY_MEDIUM, false, palette.onSurfaceVariant);
info.setPadding(0, Md3.dp(this, 8), 0, Md3.dp(this, 8));
root.addView(info);
String chosen = lihont.two.account.AccountFrames.current();
List<String[]> tiles = new ArrayList<String[]>();
tiles.add(new String[] {null, "Без рамки"});
addFrameTiles(root, tiles, 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<String[]> rowTiles = new ArrayList<String[]>();
for (lihont.two.frame.FrameIndex.Frame frame : pack.frames) rowTiles.add(new String[] {frame.id, frame.name});
addFrameTiles(root, rowTiles, chosen, dialog, uid);
}
LinearLayout buttons = new LinearLayout(this);
buttons.setGravity(Gravity.END);
buttons.setPadding(0, Md3.dp(this, 8), 0, 0);
final TextView refresh = Md3.textButton(this, palette, "Обновить наборы");
refresh.setOnClickListener(v -> {
refresh.setText("Ищем…");
lihont.two.frame.FrameStore.refresh(this, true);
new Handler(Looper.getMainLooper()).postDelayed(() -> refresh.setText("Обновить наборы"), 4000L);
});
TextView close = Md3.textButton(this, palette, "Закрыть");
close.setOnClickListener(v -> dialog.dismiss());
buttons.addView(refresh);
buttons.addView(close);
root.addView(buttons);
}
private void addFrameTiles(LinearLayout root, List<String[]> tiles, String chosen, final Dialog dialog, final String uid) {
final int perRow = 3;
LinearLayout line = null;
for (int i = 0; i < tiles.size(); i++) {
if (i % perRow == 0) {
line = new LinearLayout(this);
line.setOrientation(LinearLayout.HORIZONTAL);
line.setClipChildren(false);
root.addView(line);
}
final String id = tiles.get(i)[0];
boolean selected = id == null ? chosen == null : id.equals(chosen);
LinearLayout tile = new LinearLayout(this);
tile.setOrientation(LinearLayout.VERTICAL);
tile.setGravity(Gravity.CENTER_HORIZONTAL);
tile.setClipChildren(false);
tile.setPadding(Md3.dp(this, 4), Md3.dp(this, 6), Md3.dp(this, 4), Md3.dp(this, 6));
tile.setBackground(Md3.shape(selected ? palette.primaryContainer : Color.TRANSPARENT, Md3.dp(this, 16), this));
lihont.two.frame.FramePreviewView preview = new lihont.two.frame.FramePreviewView(this, id,
palette.secondaryContainer, palette.onSecondaryContainer);
preview.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(this, 92), Md3.dp(this, 92)));
tile.addView(preview);
tile.addView(Md3.text(this, tiles.get(i)[1], Md3.LABEL_MEDIUM, selected, selected ? palette.onPrimaryContainer : palette.onSurface));
tile.setOnClickListener(v -> {
dialog.dismiss();
lihont.two.account.AccountFrames.set(this, uid, id);
buildScreen();
shareFrame(id);
});
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f);
params.setMargins(Md3.dp(this, 2), Md3.dp(this, 2), Md3.dp(this, 2), Md3.dp(this, 2));
line.addView(tile, params);
}
if (line != null) {
for (int pad = tiles.size() % perRow; pad != 0 && pad < perRow; pad++) {
line.addView(new View(this), new LinearLayout.LayoutParams(0, 1, 1f));
}
}
}
/** 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 -> {
if (result.published) {
Toast.makeText(this, result.message, Toast.LENGTH_LONG).show();
} else if (result.code != null) {
openProofDialog("рамку", result.code, retry -> lihont.two.avatar.FramePublisher.publish(this, frameId, retry));
} else {
Toast.makeText(this, result.message, Toast.LENGTH_LONG).show();
}
});
}
private String shapeLabel(ModSettings.AvatarShape shape) {
switch (shape) {
case FLOWER: return "Цветочек";

49
src/web/mirror_index.html Normal file
View File

@@ -0,0 +1,49 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LihonT: зеркало</title>
<meta name="description" content="Запасная копия сайта LihonT. Работает, пока основной сервер недоступен.">
<style>
:root{--bg:#fff3d6;--card:#ffffff;--ink:#1c1820;--muted:#6b5f6e;--accent:#ff6f9c;--line:#1c1820}
@media (prefers-color-scheme:dark){:root{--bg:#1d1822;--card:#2a2330;--ink:#f6eef7;--muted:#b9a9bd;--accent:#ff8fb3;--line:#f6eef7}}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
main{max-width:640px;margin:0 auto;padding:32px 16px 56px}
h1{font-size:28px;margin:0 0 4px}
.sub{color:var(--muted);margin:0 0 24px}
.card{background:var(--card);border:3px solid var(--line);border-radius:20px;padding:20px;margin:0 0 16px;box-shadow:5px 5px 0 var(--line)}
.btn{display:inline-block;background:var(--accent);color:#1c1820;font-weight:700;text-decoration:none;border:3px solid var(--line);border-radius:14px;padding:12px 18px;box-shadow:3px 3px 0 var(--line)}
code{word-break:break-all;font-size:12px}
a{color:inherit}
small{color:var(--muted)}
</style>
</head>
<body>
<main>
<h1>LihonT: зеркало</h1>
<p class="sub">Запасная копия. Её включают, когда основной сайт недоступен.</p>
<div class="card">
<strong>LihonT 2.0 Luna</strong>
<p>Мод для TikTok 47.1.3. Ставится поверх установленного TikTok той же версии.</p>
<p><a class="btn" href="/LihonT-2.0-luna.apk">Скачать APK (350 МБ)</a></p>
<small>SHA-256, чтобы проверить файл:</small><br>
<code>1a5753888ac80feea64ec0be8b75e1680294e32810f4adae2d46ebaef3c6e712</code>
</div>
<div class="card">
<strong>Новости и свежие сборки</strong>
<p>Канал в Telegram: <a href="https://t.me/lihont">@lihont</a>. Там же выходят все обновления, даже когда сайты недоступны.</p>
</div>
<div class="card">
<strong>Если страница не открывается</strong>
<p>Из некоторых российских сетей зарубежные адреса блокируют. Помогает VPN. Основной адрес: <a href="https://lihont.space">lihont.space</a>.</p>
</div>
<small>Открытый код, лицензия VCBFU v2. Это копия: рамки аватарок и каталоги лежат в <code>/frames/</code>.</small>
</main>
</body>
</html>

View File

@@ -0,0 +1,209 @@
package lihont.two.frame;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
/** The frame catalog and the outline geometry on a plain JVM. Usage: FrameTest scenario; prints "PASS scenario". */
public final class FrameTest {
private static final String SHA = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
private FrameTest() {}
public static void main(String[] args) throws Exception {
String scenario = args[0];
switch (scenario) {
case "real": real(); break;
case "refusals": refusals(); break;
case "dropped": dropped(); break;
case "ids": ids(); break;
case "outline": outline(); break;
default: throw new IllegalArgumentException(scenario);
}
System.out.println("PASS " + scenario);
}
private static void check(boolean ok, String what) {
if (!ok) throw new AssertionError(what);
}
private static String catalog(String sprite, String frame) {
return "{\"version\":1,\"packs\":[{\"id\":\"p\",\"name\":\"Pack\",\"version\":1,\"sprites\":[" + sprite
+ "],\"frames\":[" + frame + "]}]}";
}
private static String sprite(String file, String sha, int bytes) {
return "{\"file\":\"" + file + "\",\"sha256\":\"" + sha + "\",\"bytes\":" + bytes + ",\"w\":100,\"h\":80}";
}
private static String frame(String id, String ring, String part) {
return "{\"id\":\"" + id + "\",\"name\":\"F\",\"ring\":" + ring + ",\"parts\":[" + part + "]}";
}
private static final String RING = "{\"width\":0.05,\"line\":0.01,\"fill\":[\"#ffffff\",\"#000000\"],\"ink\":\"#112233\"}";
private static final String PART = "{\"file\":\"p/a.png\",\"ax\":0.5,\"ay\":0.9,\"at\":-30,\"size\":0.3}";
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");
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());
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");
check(index.frame("basic.cat").parts.get(7).flip && !index.frame("basic.cat").parts.get(6).flip, "the right ear is mirrored");
check(index.frame("nope.cat") == null && index.frame(null) == null, "unknown ids give null");
}
private static void refusals() {
String[] bad = {
"", "[]", "{}", "{\"version\":2,\"packs\":[]}", "{\"version\":1}", "{\"version\":1,\"packs\":5}", "not json",
"{\"version\":1,\"packs\":[]} trailing",
};
for (String text : bad) {
try {
FrameIndex.parse(text);
throw new AssertionError("should be refused: " + text);
} catch (IllegalArgumentException expected) {
// refused
}
}
StringBuilder big = new StringBuilder("{\"version\":1,\"packs\":[],\"pad\":\"");
for (int i = 0; i < 270000; i++) big.append('x');
big.append("\"}");
try {
FrameIndex.parse(big.toString());
throw new AssertionError("a catalog over 256 KB is refused");
} catch (IllegalArgumentException expected) {
// refused
}
check(FrameIndex.parse("{\"version\":1,\"packs\":[]}").allFrames().isEmpty(), "an empty catalog is fine");
}
private static void dropped() {
String good = sprite("p/a.png", SHA, 1000);
FrameIndex ok = FrameIndex.parse(catalog(good, frame("f", RING, PART)));
check(ok.frame("p.f") != null, "the good frame is kept");
// each of these loses the frame (or the sprite) and nothing else: the catalog still parses
String[] sprites = {
sprite("p/../a.png", SHA, 1000), sprite("../p/a.png", SHA, 1000), sprite("/etc/a.png", SHA, 1000),
sprite("other/a.png", SHA, 1000), sprite("p/a.exe", SHA, 1000), sprite("p/A.png", SHA, 1000),
sprite("p/a.png", "xyz", 1000), sprite("p/a.png", SHA.toUpperCase(), 1000), sprite("p/a.png", SHA, 0),
sprite("p/a.png", SHA, FrameIndex.MAX_SPRITE_BYTES + 1), sprite("p/a.png", SHA, -5),
sprite("p/sub/a.png", SHA, 1000), sprite("p/a.png\\u0000", SHA, 1000),
};
for (String bad : sprites) {
FrameIndex index = FrameIndex.parse("{\"version\":1,\"packs\":[{\"id\":\"p\",\"name\":\"P\",\"version\":1,\"sprites\":[" + bad
+ "],\"frames\":[" + frame("f", RING, PART) + "]}]}");
check(index.allFrames().isEmpty(), "a bad sprite leaves no frame: " + bad);
}
String[] rings = {
"{\"width\":0.5,\"line\":0.01,\"fill\":[\"#ffffff\",\"#000000\"],\"ink\":\"#112233\"}",
"{\"width\":0.05,\"line\":0.5,\"fill\":[\"#ffffff\",\"#000000\"],\"ink\":\"#112233\"}",
"{\"width\":0.05,\"line\":0.01,\"fill\":[\"#FFFFFF\",\"#000000\"],\"ink\":\"#112233\"}",
"{\"width\":0.05,\"line\":0.01,\"fill\":[\"#ffffff\"],\"ink\":\"#112233\"}",
"{\"width\":0.05,\"line\":0.01,\"fill\":[\"#ffffff\",\"#000000\"],\"ink\":\"red\"}",
"{\"line\":0.01,\"fill\":[\"#ffffff\",\"#000000\"],\"ink\":\"#112233\"}",
};
for (String ring : rings) {
check(FrameIndex.parse(catalog(good, frame("f", ring, PART))).allFrames().isEmpty(), "bad ring: " + ring);
}
String[] parts = {
"{\"file\":\"p/missing.png\",\"ax\":0.5,\"ay\":0.9,\"at\":0,\"size\":0.3}",
"{\"file\":\"p/a.png\",\"ax\":0.5,\"ay\":0.9,\"at\":0,\"size\":5}",
"{\"file\":\"p/a.png\",\"ax\":0.5,\"ay\":0.9,\"at\":0,\"size\":0}",
"{\"file\":\"p/a.png\",\"ax\":0.5,\"ay\":0.9,\"at\":999,\"size\":0.3}",
"{\"file\":\"p/a.png\",\"ax\":9,\"ay\":0.9,\"at\":0,\"size\":0.3}",
"{\"file\":\"p/a.png\",\"ax\":0.5,\"ay\":0.9,\"at\":0,\"size\":0.3,\"turn\":500}",
"{\"file\":\"p/a.png\",\"ax\":0.5,\"ay\":0.9,\"at\":0,\"size\":0.3,\"radial\":3}",
"{\"file\":\"p/a.png\",\"ay\":0.9,\"at\":0,\"size\":0.3}",
"5",
};
for (String part : parts) {
check(FrameIndex.parse(catalog(good, frame("f", RING, part))).allFrames().isEmpty(), "bad part: " + part);
}
// too many parts: the frame is refused whole, not half drawn
StringBuilder many = new StringBuilder();
for (int i = 0; i <= FrameIndex.MAX_PARTS; i++) many.append(i == 0 ? "" : ",").append(PART);
check(FrameIndex.parse(catalog(good, frame("f", RING, many.toString()))).allFrames().isEmpty(), "81 parts");
// a good frame beside a bad one survives
FrameIndex mixed = FrameIndex.parse(catalog(good, frame("bad", RING, "5") + "," + frame("good", RING, PART)));
check(mixed.allFrames().size() == 1 && mixed.frame("p.good") != null, "the good one survives");
}
private static void ids() {
String[] good = {"basic.cat", "a.b", "pack-1.frame_2", "x9.y9"};
String[] bad = {"", "cat", "basic.", ".cat", "Basic.cat", "basic.cat.x", "a/b.c", "a b.c", "basic.cat\n",
"aaaaaaaaaaaaaaaaaaaaaaaaa.b", "a.bbbbbbbbbbbbbbbbbbbbbbbbb", "-a.b", "a._b"};
for (String id : good) check(FrameIndex.validFrameId(id), "valid " + id);
for (String id : bad) check(!FrameIndex.validFrameId(id), "invalid " + id);
check(!FrameIndex.validFrameId(null), "null");
String twice = "{\"version\":1,\"packs\":[{\"id\":\"p\",\"name\":\"P\",\"version\":1,\"sprites\":[" + sprite("p/a.png", SHA, 10)
+ "],\"frames\":[" + frame("f", RING, PART) + "," + frame("f", RING, PART) + "]}]}";
check(FrameIndex.parse(twice).allFrames().size() == 1, "a repeated id is kept once");
String names = FrameIndex.parse(catalog(sprite("p/a.png", SHA, 10), "{\"id\":\"f\",\"name\":\"A\\nB\\u0001C\",\"ring\":" + RING
+ ",\"parts\":[" + PART + "]}")).frame("p.f").name;
check(names.equals("ABC"), "control characters are dropped from names: " + names);
String mirrors = "{\"version\":1,\"packs\":[],\"mirrors\":[\"https://a.example.org/frames/\",\"http://a.example.org/frames/\","
+ "\"https://x/\",\"https://a.example.org/../x/\",5]}";
check(FrameIndex.parse(mirrors).mirrors.size() == 1, "only the https mirror with a sane address stays");
}
private static void outline() {
int n = 720;
float[] xs = new float[n];
float[] ys = new float[n];
float r = 100f;
for (int i = 0; i < n; i++) {
double a = 2 * Math.PI * i / n;
xs[i] = 150f + r * (float) Math.cos(a);
ys[i] = 150f + r * (float) Math.sin(a);
}
Outline circle = Outline.of(xs, ys, n, 150f, 150f);
float[] top = circle.point(0f);
check(Math.abs(top[0] - 150f) < 1f && Math.abs(top[1] - 50f) < 1f, "0 degrees is the top");
float[] right = circle.point(90f);
check(Math.abs(right[0] - 250f) < 1f && Math.abs(right[1] - 150f) < 1f, "90 degrees is the right");
float[] bottom = circle.point(180f);
check(Math.abs(bottom[1] - 250f) < 1f, "180 degrees is the bottom");
float[] left = circle.point(-90f);
check(Math.abs(left[0] - 50f) < 1f, "-90 degrees is the left");
check(Math.abs(circle.point(450f)[0] - 250f) < 1f, "angles wrap");
for (int degrees : new int[] {0, 45, 90, 135, 180, -90, -45}) {
float normal = circle.normalDegrees(degrees);
float diff = Math.abs(((normal - degrees + 540f) % 360f) - 180f);
check(diff < 2f, "on a circle the way out at " + degrees + " is " + degrees + " but was " + normal);
}
// a square: the top edge is flat, so its way out is straight up at the middle and the corners reach further
float s = 100f;
int per = 400;
float[] sx = new float[4 * per];
float[] sy = new float[4 * per];
for (int i = 0; i < per; i++) {
float t = s * i / per;
sx[i] = 100f + t; sy[i] = 100f;
sx[per + i] = 200f; sy[per + i] = 100f + t;
sx[2 * per + i] = 200f - t; sy[2 * per + i] = 200f;
sx[3 * per + i] = 100f; sy[3 * per + i] = 200f - t;
}
Outline square = Outline.of(sx, sy, 4 * per, 150f, 150f);
check(Math.abs(square.point(0f)[1] - 100f) < 1f, "the middle of the top edge");
check(Math.abs(square.normalDegrees(0f)) < 1f, "straight up from a flat top");
float[] corner = square.point(45f);
check(Math.abs(corner[0] - 200f) < 2f && Math.abs(corner[1] - 100f) < 2f, "the corner reaches further than the edge");
// gaps are filled from the neighbours: only a few points, still a closed table
Outline sparse = Outline.of(new float[] {250f, 150f, 50f, 150f}, new float[] {150f, 250f, 150f, 50f}, 4, 150f, 150f);
check(Math.abs(sparse.point(0f)[1] - 50f) < 1f && Math.abs(sparse.point(90f)[0] - 250f) < 1f, "known directions are exact");
float[] between = sparse.point(45f);
check(between[0] > 150f && between[1] < 150f, "unknown directions stay on the right side: " + between[0] + "," + between[1]);
// no points at all gives a point in the middle, not a crash
Outline none = Outline.of(new float[0], new float[0], 0, 10f, 10f);
check(Math.abs(none.point(30f)[0] - 10f) < 0.01f, "an empty outline is the middle");
}
}

View File

@@ -0,0 +1,56 @@
package lihont.two.media;
import java.util.List;
/** Reading a profile picture's address out of a profile page, on a plain JVM. Prints "PASS" on success. */
public final class ProfileAddressesTest {
private ProfileAddressesTest() {}
private static void check(boolean ok, String what) {
if (!ok) throw new AssertionError(what);
}
public static void main(String[] args) {
// names
check("abc".equals(ProfileAddresses.cleanName("abc")), "plain");
check("name".equals(ProfileAddresses.cleanName("name\n")), "a line break at the edge is trimmed");
check("my_name.x".equals(ProfileAddresses.cleanName(" @my_name.x ")), "at sign and spaces");
String[] bad = {null, "", "@", "a", "a b", "иван", "a/b", "a?b", "x".repeat(25), "name.", "@@name", "na\nme", "<script>", ".."};
for (String name : bad) check(ProfileAddresses.cleanName(name) == null, "refused: " + name);
check("https://www.tiktok.com/@abc".equals(ProfileAddresses.pageOf("abc")), "page address");
// a page: the data of the profile, three sizes, escaped as in the real page
String data = "{\"__DEFAULT_SCOPE__\":{\"webapp.user-detail\":{\"userInfo\":{\"user\":{\"id\":\"1\","
+ "\"avatarLarger\":\"https:\\u002F\\u002Fp16-common-sign.tiktokcdn-eu.com\\u002Ftos\\u002Fabc~tplv-1080x1080.jpeg?x=1\\u0026y=2\","
+ "\"avatarMedium\":\"https:\\/\\/p19-common-sign.tiktokcdn-eu.com\\/tos\\/abc~tplv-720x720.jpeg?x=1\","
+ "\"avatarThumb\":\"https://p16-common-sign.tiktokcdn-eu.com/tos/abc~tplv-100x100.jpeg\"}}}}}";
String page = "<html><script>noise \"avatarLarger\":\"https://evil.example/x.jpg\"</script><script id=\"x\">" + data + "</script></html>";
List<String> found = ProfileAddresses.addresses(page);
check(found.size() == 3, "three sizes: " + found);
check(found.get(0).equals("https://p16-common-sign.tiktokcdn-eu.com/tos/abc~tplv-1080x1080.jpeg?x=1&y=2"), "largest first, unescaped: " + found.get(0));
check(found.get(1).equals("https://p19-common-sign.tiktokcdn-eu.com/tos/abc~tplv-720x720.jpeg?x=1"), "slashes: " + found.get(1));
check(found.get(2).endsWith("100x100.jpeg"), "thumb last");
// the address before the profile marker (noise) is never used; no marker: nothing
check(ProfileAddresses.addresses("\"avatarLarger\":\"https://p16.tiktokcdn.com/a.jpg\"").isEmpty(), "no marker");
check(ProfileAddresses.addresses(null).isEmpty() && ProfileAddresses.addresses("").isEmpty(), "empty");
// only TikTok's own https hosts
String[] hosts = {"http://p16.tiktokcdn.com/a.jpg", "https://evil.example/a.jpg", "https://tiktokcdn.com.evil.example/a.jpg",
"https://user@p16.tiktokcdn.com/a.jpg", "https://p16.tiktokcdn.com:8443/a.jpg", "ftp://p16.tiktokcdn.com/a.jpg",
"https://p16.tiktokcdn.com", "file:///sdcard/a.jpg", ""};
for (String url : hosts) check(!ProfileAddresses.allowed(url), "refused host: " + url);
check(ProfileAddresses.allowed("https://p16-common-sign.tiktokcdn-eu.com/tos/a.jpg"), "eu cdn");
check(ProfileAddresses.allowed("https://p77.tiktokcdn-us.com/a.jpg"), "us cdn");
String evil = "{\"webapp.user-detail\":{\"avatarLarger\":\"https://evil.example/x.jpg\",\"avatarMedium\":\"http://p16.tiktokcdn.com/m.jpg\","
+ "\"avatarThumb\":\"https://p16.tiktokcdn.com/t.jpg\"}}";
List<String> only = ProfileAddresses.addresses(evil);
check(only.size() == 1 && only.get(0).endsWith("/t.jpg"), "a foreign host and plain http are skipped: " + only);
// broken escapes do not crash
check(ProfileAddresses.unescape("a\\u12").equals("a\\u12"), "short unicode escape stays");
check(ProfileAddresses.unescape("a\\").equals("a\\"), "trailing backslash");
check(ProfileAddresses.unescape("\\uZZZZ").startsWith("\\u"), "bad hex stays");
System.out.println("PASS");
}
}

93
tests/test_frames.py Normal file
View File

@@ -0,0 +1,93 @@
"""Avatar frames: the catalog the mod downloads and the outline geometry, on a real JVM, and the catalog builder.
The catalog reader (FrameIndex) and the outline table (Outline) are plain Java, so they are compiled with javac and each scenario
runs in its own process. The parts that draw or download need a device; the runtime compile test covers that they build.
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
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" / "plugin" / "Json.java",
ROOT / "src" / "lihont" / "two" / "plugin" / "LtpException.java"]
HARNESS = ROOT / "tests" / "java" / "lihont" / "two" / "frame" / "FrameTest.java"
class FrameJavaTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
javac, cls.java = shutil.which("javac"), shutil.which("java")
if not javac or not cls.java:
raise RuntimeError("Frame tests require a JDK with java and javac")
cls.temporary = tempfile.TemporaryDirectory(prefix="lihont-frame-tests-")
cls.addClassCleanup(cls.temporary.cleanup)
cls.classes = Path(cls.temporary.name)
env = dict(os.environ)
env.pop("JAVA_TOOL_OPTIONS", None)
cls.env = env
result = subprocess.run([javac, "--release", "17", "-encoding", "UTF-8", "-Xlint:all", "-Werror", "-d", str(cls.classes)]
+ [str(s) for s in SOURCES] + [str(HARNESS)],
capture_output=True, text=True, encoding="utf-8", env=env, timeout=120)
if result.returncode:
raise AssertionError(result.stdout + result.stderr)
def scenario(self, name):
result = subprocess.run([self.java, "-Dfile.encoding=UTF-8", "-cp", str(self.classes), "lihont.two.frame.FrameTest", name],
capture_output=True, text=True, encoding="utf-8", env=self.env, timeout=60, cwd=str(ROOT))
self.assertEqual(result.stdout.strip(), "PASS " + name, result.stdout + result.stderr)
def test_the_real_catalog_is_read(self):
self.scenario("real")
def test_bad_catalogs_are_refused(self):
self.scenario("refusals")
def test_bad_entries_are_dropped_and_good_ones_kept(self):
self.scenario("dropped")
def test_ids_names_and_mirrors(self):
self.scenario("ids")
def test_the_outline_geometry(self):
self.scenario("outline")
class CatalogBuilderTest(unittest.TestCase):
def test_the_catalog_is_up_to_date(self):
result = subprocess.run([sys.executable, "-X", "utf8", "-B", str(ROOT / "scripts" / "build_frames_catalog.py"), "--check"],
capture_output=True, text=True, encoding="utf-8", timeout=60)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_every_sprite_matches_its_checksum_and_stays_small(self):
import hashlib
catalog = json.loads((ROOT / "frames" / "index.json").read_text(encoding="utf-8"))
total = 0
for pack in catalog["packs"]:
for sprite in pack["sprites"]:
data = (ROOT / "frames" / sprite["file"]).read_bytes()
self.assertEqual(hashlib.sha256(data).hexdigest(), sprite["sha256"], sprite["file"])
self.assertEqual(len(data), sprite["bytes"], sprite["file"])
self.assertLessEqual(len(data), 150 * 1024)
total += len(data)
self.assertLess(total, 400 * 1024, "the whole basic pack should stay a small download")
def test_every_frame_uses_sprites_of_its_pack_only(self):
catalog = json.loads((ROOT / "frames" / "index.json").read_text(encoding="utf-8"))
for pack in catalog["packs"]:
known = {s["file"] for s in pack["sprites"]}
for frame in pack["frames"]:
for part in frame["parts"]:
self.assertIn(part["file"], known)
self.assertTrue(part["file"].startswith(pack["id"] + "/"))
if __name__ == "__main__":
unittest.main()

View File

@@ -161,5 +161,81 @@ class ShapeTest(unittest.TestCase):
self.assertEqual("proof_needed", self.registry.shape(UID, INSTALLATION, "flower", "bad name!")["reason"])
class AvatarFrameTest(unittest.TestCase):
"""Frames are published like outlines: the account is proven once, the proving installation changes the frame alone."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.now = 1_790_000_000
self.bio = ""
self.found = UID
self.fetches = 0
self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now, fetcher=self.fetch)
def fetch(self, unique_id):
self.fetches += 1
return (self.found, self.bio)
def publish(self, frame, installation=INSTALLATION, unique_id="someone", uid=UID):
return self.registry.avatar_frame(uid, installation, frame, unique_id)
def test_nothing_is_published_without_the_code_in_the_bio(self):
self.assertEqual("code_missing", self.publish("basic.cat")["reason"])
self.assertEqual({}, self.registry.lookup([UID])["avatar_frames"])
self.assertEqual("proof_needed", self.registry.avatar_frame(UID, INSTALLATION, "basic.cat")["reason"])
def test_the_code_in_the_bio_publishes_the_frame(self):
self.bio = "me " + self.registry.code(UID)
self.assertTrue(self.publish("basic.cat")["published"])
self.assertEqual({UID: "basic.cat"}, self.registry.lookup([UID])["avatar_frames"])
def test_the_shape_proof_also_covers_frames(self):
self.bio = self.registry.code(UID)
self.registry.shape(UID, INSTALLATION, "flower", "someone")
fetched = self.fetches
self.bio = ""
self.assertTrue(self.registry.avatar_frame(UID, INSTALLATION, "basic.crown")["published"])
self.assertEqual(fetched, self.fetches)
both = self.registry.lookup([UID])
self.assertEqual({UID: "flower"}, both["shapes"])
self.assertEqual({UID: "basic.crown"}, both["avatar_frames"])
def test_another_installation_must_prove_the_account_itself(self):
self.bio = self.registry.code(UID)
self.publish("basic.cat")
self.bio = ""
self.assertFalse(self.publish("basic.flame", OTHER_INSTALLATION)["published"])
self.assertEqual({UID: "basic.cat"}, self.registry.lookup([UID])["avatar_frames"])
def test_none_withdraws_the_frame(self):
self.bio = self.registry.code(UID)
self.publish("basic.helmet")
self.assertTrue(self.registry.avatar_frame(UID, INSTALLATION, "none")["published"])
self.assertEqual({}, self.registry.lookup([UID])["avatar_frames"])
def test_none_for_an_account_without_a_frame_needs_nothing(self):
self.assertTrue(self.publish("none")["published"])
self.assertEqual(0, self.fetches)
def test_blocked_accounts_are_refused_and_vanish_from_lookups(self):
self.bio = self.registry.code(UID)
self.publish("basic.cat")
with self.registry.connect() as db:
db.execute("INSERT INTO blocked(uid) VALUES(?)", (UID,))
self.assertEqual({}, self.registry.lookup([UID])["avatar_frames"])
with self.assertRaises(ValueError):
self.publish("basic.crown")
def test_bad_input(self):
for frame in ("cat", "basic.", ".cat", "Basic.cat", "basic.cat.x", "a/b.c", "", None, 5, "basic.cat" + "x" * 30):
with self.assertRaises(ValueError):
self.publish(frame)
with self.assertRaises(ValueError):
self.registry.avatar_frame("abc", INSTALLATION, "basic.cat", "someone")
with self.assertRaises(ValueError):
self.registry.avatar_frame(UID, "short", "basic.cat", "someone")
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,29 @@
"""ProfileAddresses (the user name check and the picture addresses of a profile page) on a real JVM."""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / "src" / "lihont" / "two" / "media" / "ProfileAddresses.java"
HARNESS = ROOT / "tests" / "java" / "lihont" / "two" / "media" / "ProfileAddressesTest.java"
class ProfileAddressesTest(unittest.TestCase):
def test_names_pages_and_hosts(self):
javac, java = shutil.which("javac"), shutil.which("java")
if not javac or not java:
raise RuntimeError("This test requires a JDK with java and javac")
with tempfile.TemporaryDirectory(prefix="lihont-profile-addresses-") as out:
subprocess.run([javac, "--release", "17", "-encoding", "UTF-8", "-Xlint:all", "-Werror", "-d", out, str(SOURCE), str(HARNESS)],
check=True, capture_output=True)
result = subprocess.run([java, "-cp", out, "lihont.two.media.ProfileAddressesTest"],
capture_output=True, text=True, encoding="utf-8", timeout=60)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertEqual(result.stdout.strip(), "PASS")
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,63 @@
import unittest
from pathlib import Path
from lihont import seekbar_patch
ROOT = Path(__file__).resolve().parents[1]
# LX/1Azi;->setSeekBarShowType of TikTok 47.1.3 (shortened to the parts the patch looks at).
SAMPLE = """.class public LX/1Azi;
.super Landroid/widget/LinearLayout;
.method public final setSeekBarShowType(I)V
.registers 9
iget v0, p0, LX/1Azi;->LLJJJJJIL:I
if-eq v0, p1, :cond_30
iput p1, p0, LX/1Azi;->LLJJJJJIL:I
const-string v0, "seekbar show type change, change to:"
const/4 v0, 0x3
if-eq p1, v0, :cond_86
:cond_30
return-void
:cond_86
const/16 v0, 0x8
return-void
.end method
"""
class SeekbarPatchTest(unittest.TestCase):
def test_type_is_changed_before_anything_else(self):
text = seekbar_patch.rewrite_seek_bar(SAMPLE)
self.assertIn("invoke-static {p1}, " + seekbar_patch.HOOK, text)
self.assertLess(text.index("move-result p1"), text.index("iget v0, p0, LX/1Azi;->LLJJJJJIL:I"))
def test_twice_is_refused(self):
with self.assertRaises(ValueError):
seekbar_patch.rewrite_seek_bar(seekbar_patch.rewrite_seek_bar(SAMPLE))
def test_other_shape_is_refused(self):
with self.assertRaises(ValueError):
seekbar_patch.rewrite_seek_bar(SAMPLE.replace("const/16 v0, 0x8", "const/16 v0, 0x4"))
def test_missing_method_is_refused(self):
with self.assertRaises(ValueError):
seekbar_patch.rewrite_seek_bar(".class public LX/1Azi;\n")
def test_runtime_hook_exists(self):
source = (ROOT / "src/lihont/two/look/Seekbar.java").read_text(encoding="utf-8")
self.assertIn("public static int type(int asked)", source)
self.assertEqual(seekbar_patch.runtime_targets(), [seekbar_patch.HOOK])
if __name__ == "__main__":
unittest.main()