LihonT 2 Luna
Ghost mode for stories and chats, several photos in one comment, .ltp plugins (rights, defender, rollback, downloads only with consent), custom chat bubbles with a text colour of your choice, the lihont-ltp SDK and the plugin docs, streak flames as widgets with a keeper, avatar shapes, Material 3 surfaces. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
45
LICENSE
45
LICENSE
@@ -1,24 +1,45 @@
|
||||
EVHNMKHU licence
|
||||
VCBFU v2 licence (Vibe Code But Free Use)
|
||||
|
||||
Copyright (c) 2026 intcatsite
|
||||
|
||||
ПРАВИЛА ЛИЦЕНЗИИ
|
||||
ПРАВИЛА / RULES
|
||||
|
||||
• (по желанию) Люби маму, папу, бабушек и дедушек.
|
||||
1. СВОБОДНОЕ ИСПОЛЬЗОВАНИЕ / FREE USE
|
||||
Используй, копируй, изменяй, объединяй, публикуй, распространяй и продавай
|
||||
программу и её производные для любой цели, бесплатно. Указывать автора
|
||||
не нужно.
|
||||
You may use, copy, modify, merge, publish, distribute and sell the software
|
||||
and derivative works for any purpose, free of charge. Crediting the author
|
||||
is not required.
|
||||
|
||||
• (обязательно) На деловых встречах и переговорах разговаривай так,
|
||||
как будто тебя на клапан придавило.
|
||||
2. УВЕДОМЛЕНИЕ / THE NOTICE (единственная обязанность / the only duty)
|
||||
Если любая часть того, что ты распространяешь, написана с помощью ИИ
|
||||
(вайбкод), укажи, какой моделью ты пользовался, в файле create_by.md рядом
|
||||
с кодом. Достаточно честно и примерно: «Claude Sonnet 5.5 через Claude Code».
|
||||
If any part of what you distribute was written with the help of an AI model
|
||||
(vibe coding), name the model(s) in a file called create_by.md next to the
|
||||
code. Honest and approximate is enough.
|
||||
|
||||
• (обязательно) Если это вайбкод, указывай, какой моделью ты
|
||||
пользовался, в create_by.md.
|
||||
3. ЭТОТ ФАЙЛ / THIS FILE
|
||||
Передавая код дальше, передавай этот файл вместе с ним, правила 1-3
|
||||
без изменений.
|
||||
When you pass the code on, pass this file with it, rules 1-3 unchanged.
|
||||
|
||||
РАЗРЕШЕНО
|
||||
4. ЧУЖОЕ / THIRD PARTIES
|
||||
Лицензия относится только к собственному коду автора. Код TikTok и
|
||||
материалы других авторов (например, значки других модов) в неё не входят
|
||||
и принадлежат своим владельцам.
|
||||
This licence covers the author's own code only. TikTok's code and other
|
||||
people's materials (for example the badge art of other mods) are not
|
||||
included and belong to their owners.
|
||||
|
||||
• Использовать как хочешь.
|
||||
ДУХ ЛИЦЕНЗИИ / THE SPIRIT
|
||||
|
||||
• Можно не указывать автора.
|
||||
• (по желанию / if you like) Люби маму, папу, бабушек и дедушек.
|
||||
• (добровольно-принудительно / voluntary-compulsory) На деловых встречах и
|
||||
переговорах разговаривай так, как будто тебя на клапан придавило.
|
||||
|
||||
БЕЗ ГАРАНТИЙ
|
||||
БЕЗ ГАРАНТИЙ / NO WARRANTY
|
||||
|
||||
Программа предоставляется «КАК ЕСТЬ» (AS IS), без каких-либо гарантий,
|
||||
явных или подразумеваемых, включая гарантии пригодности для какой-либо
|
||||
@@ -29,4 +50,4 @@ Copyright (c) 2026 intcatsite
|
||||
IMPLIED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
OTHER LIABILITY ARISING FROM THE USE OF THE SOFTWARE.
|
||||
|
||||
(Первые два правила созданы на базе ООСД)
|
||||
(Шуточные правила из «духа лицензии» созданы на базе ООСД)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Мод для TikTok 47.1.3 (arm64) в стиле Material 3. Telegram: [@lihont](https://t.me/lihont).
|
||||
Готовую сборку берите на странице [релизов](https://git.lihont.space/lihont/LihonT/releases).
|
||||
|
||||
Лицензия: EVHNMKHU, см. [LICENSE](LICENSE). Код написан с помощью ИИ, подробности в [create_by.md](create_by.md).
|
||||
Лицензия: VCBFU v2 (Vibe Code But Free Use), см. [LICENSE](LICENSE). Код написан с помощью ИИ, подробности в [create_by.md](create_by.md).
|
||||
|
||||
## Что умеет
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# create_by
|
||||
|
||||
LihonT 2.0 («Luna», пре-релиз) написан с помощью ИИ. По правилу лицензии EVHNMKHU вот модели.
|
||||
LihonT 2.0 («Luna», пре-релиз) написан с помощью ИИ. По правилу лицензии VCBFU вот модели.
|
||||
|
||||
- Claude Sonnet 5.5 (Anthropic), через Claude Code: этот и ряд предыдущих сеансов.
|
||||
- Более ранние сеансы шли в Claude Code на других моделях Claude; точный список не сохранился.
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
"""LihonT build tools.
|
||||
|
||||
LIHONT_PORT_MAP=<json> builds against another TikTok version: see lihont/portmap.py.
|
||||
"""
|
||||
import os as _os
|
||||
|
||||
if _os.environ.get("LIHONT_PORT_MAP"):
|
||||
from . import portmap as _portmap
|
||||
_portmap.install(_portmap.load_map(_os.environ["LIHONT_PORT_MAP"]),
|
||||
_portmap.load_literals(_os.environ["LIHONT_PORT_MAP"]),
|
||||
_portmap.load_version(_os.environ["LIHONT_PORT_MAP"]))
|
||||
|
||||
@@ -44,7 +44,21 @@ SLOTS = (
|
||||
(0x7F040DB3, "res/a/ar9.png"), # icon_bottom_shop_light_unselected_uk_summer_sale
|
||||
)
|
||||
|
||||
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
# dead drawables of TikTok 47.5.15, found by scripts/port_dead_slots.py (nothing in the dex, the binary XML or the
|
||||
# table reads their ids). A file there is a PNG under a .webp name: Android decodes a drawable by its content.
|
||||
SLOTS_47_5_15 = (
|
||||
(0x7F0400AE, "res/c/a02.png"), # an empty file
|
||||
(0x7F0400E9, "res/c/a0d.png"), # an empty file
|
||||
(0x7F040205, "res/c/a2o.png"), # an empty file
|
||||
(0x7F040D91, "res/a/arn.webp"),
|
||||
(0x7F040D92, "res/a/aro.webp"),
|
||||
(0x7F040D93, "res/a/arp.webp"),
|
||||
(0x7F040D94, "res/a/arq.webp"),
|
||||
(0x7F040D95, "res/a/arr.webp"),
|
||||
)
|
||||
SLOTS_BY_VERSION = {"47.1.3": SLOTS, "47.5.15": SLOTS_47_5_15}
|
||||
|
||||
PNG_SIGNATURE =b"\x89PNG\r\n\x1a\n"
|
||||
# no density qualifier on these files: the system reads them as 160 dpi and scales them up by the
|
||||
# screen density, so a big picture turns into a huge bitmap in the launcher
|
||||
MIN_SIDE, MAX_SIDE = 192, 512
|
||||
@@ -149,13 +163,17 @@ def apply(apk: Apk, xml: Axml, icons: Sequence[Icon]) -> dict:
|
||||
manifest_module.add_icon_alias(
|
||||
xml, alias_name(STOCK_SLUG), target, stock_icon, LAUNCHER_LABEL, True, title=STOCK_TITLE)
|
||||
arsc = Arsc(apk.read("resources.arsc"))
|
||||
version = manifest_module.version_name(xml)
|
||||
slots = SLOTS_BY_VERSION.get(version)
|
||||
if slots is None:
|
||||
raise IconError("no dead slots are pinned for TikTok %s (run scripts/port_dead_slots.py)" % version)
|
||||
report = {
|
||||
"icons": len(icons), "original_entry": entry, "target": target,
|
||||
"stock": {"alias": alias_name(STOCK_SLUG), "resource": "0x%08x" % stock_icon},
|
||||
"aliases": {},
|
||||
}
|
||||
for index, icon in enumerate(icons):
|
||||
res_id, old_path = SLOTS[index]
|
||||
res_id, old_path = slots[index]
|
||||
pool_index = verify_slot(arsc, res_id, old_path)
|
||||
new_path = slot_path(old_path, index)
|
||||
if apk.has(new_path):
|
||||
|
||||
@@ -85,15 +85,18 @@ def rewrite_text_view(text: str):
|
||||
|
||||
def rewrite_comment(text: str):
|
||||
def change(header, body, hits):
|
||||
if not header.endswith(" U7(Ljava/lang/CharSequence;)V"):
|
||||
# the setter of the comment author: the only method of the cell that takes a CharSequence (its name is
|
||||
# obfuscated and changes between TikTok versions: U7 in 47.1.3, D7 in 47.5.15)
|
||||
if re.search(r" \w+\(Ljava/lang/CharSequence;\)V$", header) is None:
|
||||
return None
|
||||
field = re.search(r"iget-object v3, p0, " + re.escape(CELL) + r"->(\w+):Lcom/bytedance/tux/input/TuxTextView;", body)
|
||||
field = re.search(r"iget-object (v\d+), p0, " + re.escape(CELL) + r"->(\w+):Lcom/bytedance/tux/input/TuxTextView;", body)
|
||||
if field is None or body.count(" return-void") != 2:
|
||||
raise ValueError("Comment author setter changed")
|
||||
# the author view is v3 from the first read until the end; bind after the last statement
|
||||
# the author view stays in its register (v3 in 47.1.3, v4 in 47.5.15) from the first read until the end;
|
||||
# bind after the last statement
|
||||
head, tail = body.rsplit(" return-void", 1)
|
||||
hits["comment"] = 1
|
||||
return head + " %s\n invoke-static {p0, v3}, %s\n\n return-void" % (MARKER, COMMENT) + tail
|
||||
return head + " %s\n invoke-static {p0, %s}, %s\n\n return-void" % (MARKER, field.group(1), COMMENT) + tail
|
||||
|
||||
result, hits = _rewrite(text, CELL, change)
|
||||
if hits != {"comment": 1}:
|
||||
@@ -103,9 +106,10 @@ def rewrite_comment(text: str):
|
||||
|
||||
def rewrite_profile(text: str):
|
||||
def change(header, body, hits):
|
||||
if not header.endswith(" LLI(Landroid/text/SpannableStringBuilder;Lcom/bytedance/tux/input/TuxTextView;)V"):
|
||||
if re.search(r" \w+\(Landroid/text/SpannableStringBuilder;Lcom/bytedance/tux/input/TuxTextView;\)V$", header) is None:
|
||||
return None
|
||||
if body.count(" return-void") != 1 or "->LJL()" not in body:
|
||||
# the binder reads the user through a getter of its own class (LJL() in 47.1.3, LJJLJLI() in 47.5.15)
|
||||
if body.count(" return-void") != 1 or re.search(re.escape(NICKNAME) + r"->\w+\(\)LX/", body) is None:
|
||||
raise ValueError("Profile nickname binder changed")
|
||||
hits["profile"] = 1
|
||||
head, tail = body.rsplit(" return-void", 1)
|
||||
|
||||
41
lihont/comment_photos_patch.py
Normal file
41
lihont/comment_photos_patch.py
Normal file
@@ -0,0 +1,41 @@
|
||||
"""Let the person turn on TikTok's own multi-photo comments (up to 9 photos in one comment) with a switch.
|
||||
|
||||
TikTok 47.1.3 ships the picker (scene "comment_multi_photo", at most nine photos) but offers it only to accounts whose
|
||||
experiment value is 2. That decision is one static method, LX/09Pr;->LIZ()Z, read by the comment keyboard, the publish
|
||||
view model and the launcher alike, so it is the only place that has to change: its result passes through
|
||||
lihont.two.comments.CommentPhotos.gate(Z)Z, which returns the account's own answer unless the switch is on. The server
|
||||
still decides whether a comment with several photos is accepted; nothing here sends or claims anything.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
GATE_CLASS = "LX/09Pr;"
|
||||
HOOK = "Llihont/two/comments/CommentPhotos;->gate(Z)Z"
|
||||
|
||||
_METHOD = re.compile(r"^\.method public static LIZ\(\)Z\n.*?^\.end method", re.M | re.S)
|
||||
_RETURN = re.compile(r"^ return v1\n", re.M)
|
||||
|
||||
|
||||
def runtime_targets():
|
||||
"""Runtime methods the rewrite calls, as they appear in a method table."""
|
||||
return [HOOK]
|
||||
|
||||
|
||||
def rewrite_gate(text: str) -> str:
|
||||
"""Pass the experiment's answer through CommentPhotos.gate just before it is returned."""
|
||||
match = _METHOD.search(text)
|
||||
if match is None:
|
||||
raise ValueError("LX/09Pr;->LIZ()Z not found")
|
||||
method = match.group()
|
||||
if "CommentPhotos" in method:
|
||||
raise ValueError("Comment photo hook already present in LX/09Pr;->LIZ")
|
||||
# The shape that identifies the gate: an int read from a lazy value, compared with 2, answered in v1.
|
||||
if "Ljava/lang/Number;->intValue()I" not in method or ".registers 3" not in method or "0x2" not in method:
|
||||
raise ValueError("LX/09Pr;->LIZ()Z has an unexpected shape")
|
||||
if len(_RETURN.findall(method)) != 1:
|
||||
raise ValueError("LX/09Pr;->LIZ()Z must return v1 exactly once")
|
||||
patched = _RETURN.sub(
|
||||
" invoke-static {v1}, %s\n\n move-result v1\n\n return v1\n" % HOOK, method, count=1)
|
||||
return text[:match.start()] + patched + text[match.end():]
|
||||
79
lihont/ghost_patch.py
Normal file
79
lihont/ghost_patch.py
Normal file
@@ -0,0 +1,79 @@
|
||||
"""Ghost mode for stories: with the switch on, TikTok does not tell the server that a story was viewed.
|
||||
|
||||
When a story is watched, TikTok 47.1.3 calls LX/0RDS;->LIZJ(Boolean unlocked, String storyId, String authorId)V, which posts
|
||||
/tiktok/story/view/report/v1 (the call that makes the viewer show up in the author's list of viewers) and then marks the story
|
||||
as viewed locally. With the switch on that method returns before doing either, so the story is watched and nothing is sent.
|
||||
With it off TikTok's own code runs untouched.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
STORY_VIEW_CLASS = "LX/0RDS;"
|
||||
HOOK = "Llihont/two/ghost/Ghost;->stories()Z"
|
||||
|
||||
# Chat read receipts. The suspend function LX/13pM;->LIZIZ(Long readIndex, String conversationId, Continuation) builds and
|
||||
# sends "MarkConversationRead" (v3/conversation/mark_read); its only caller (LX/0c4W) ignores the result and just goes on. With
|
||||
# the switch on it returns Unit at once on the first call, so nothing is built or sent and the conversation stays unread
|
||||
# on the server (and here); a call that resumes from a suspension (its own continuation LX/0c58) is never cut short.
|
||||
MARK_READ_CLASS = "LX/13pM;"
|
||||
MARK_READ_HOOK = "Llihont/two/ghost/Ghost;->messages()Z"
|
||||
|
||||
_MARK_READ = re.compile(
|
||||
r"^\.method public final LIZIZ\(Ljava/lang/Long;Ljava/lang/String;LX/01h3;\)Ljava/lang/Object;\n.*?^\.end method",
|
||||
re.M | re.S)
|
||||
_MARK_FIRST = re.compile(r"^ instance-of v0, p3, (LX/\w+;)\n", re.M)
|
||||
_MARK_LABEL = "lihont_mark_read"
|
||||
|
||||
_METHOD = re.compile(
|
||||
r"^\.method public final LIZJ\(Ljava/lang/Boolean;Ljava/lang/String;Ljava/lang/String;\)V\n.*?^\.end method",
|
||||
re.M | re.S)
|
||||
_FIRST = re.compile(r"^ if-eqz p1, :(\w+)\n", re.M)
|
||||
_LABEL = "lihont_story_view"
|
||||
|
||||
|
||||
def runtime_targets():
|
||||
"""Runtime methods the rewrites call, as they appear in a method table."""
|
||||
return [HOOK, MARK_READ_HOOK]
|
||||
|
||||
|
||||
def rewrite_mark_read(text: str) -> str:
|
||||
"""Return Unit from the mark-conversation-read suspend function before it builds or sends anything, while the switch is on."""
|
||||
match = _MARK_READ.search(text)
|
||||
if match is None:
|
||||
raise ValueError("LX/13pM;->LIZIZ(Long,String,Continuation) not found")
|
||||
method = match.group()
|
||||
if "Ghost;" in method:
|
||||
raise ValueError("Ghost hook already present in LX/13pM;->LIZIZ")
|
||||
first = _MARK_FIRST.search(method)
|
||||
# The shape that identifies it: the continuation check comes first, and it is the state machine of a suspend function.
|
||||
if first is None or ".registers 10" not in method or "LX/0NPd;->LJFF()" not in method:
|
||||
raise ValueError("LX/13pM;->LIZIZ has an unexpected shape")
|
||||
own = first.group(1)
|
||||
injected = (" invoke-static {}, %s\n\n move-result v0\n\n if-eqz v0, :%s\n\n"
|
||||
" instance-of v0, p3, %s\n\n if-nez v0, :%s\n\n"
|
||||
" sget-object v0, Lkotlin/Unit;->LIZ:Lkotlin/Unit;\n\n return-object v0\n\n :%s\n\n"
|
||||
% (MARK_READ_HOOK, _MARK_LABEL, own, _MARK_LABEL, _MARK_LABEL))
|
||||
patched = method[:first.start()] + injected + method[first.start():]
|
||||
return text[:match.start()] + patched + text[match.end():]
|
||||
|
||||
|
||||
def rewrite_story_view(text: str) -> str:
|
||||
"""Return from the story-viewed method before anything is sent, while the switch is on."""
|
||||
match = _METHOD.search(text)
|
||||
if match is None:
|
||||
raise ValueError("LX/0RDS;->LIZJ(Boolean,String,String)V not found")
|
||||
method = match.group()
|
||||
if "Ghost;" in method:
|
||||
raise ValueError("Ghost hook already present in LX/0RDS;->LIZJ")
|
||||
# The shape that identifies it: it posts the view through StoryApi.reportStoryViewed and nothing else of ours.
|
||||
if "StoryApi;->reportStoryViewed(" not in method or ".registers 8" not in method:
|
||||
raise ValueError("LX/0RDS;->LIZJ has an unexpected shape")
|
||||
first = _FIRST.search(method)
|
||||
if first is None:
|
||||
raise ValueError("LX/0RDS;->LIZJ does not start with the expected null check")
|
||||
injected = (" invoke-static {}, %s\n\n move-result v0\n\n if-eqz v0, :%s\n\n return-void\n\n :%s\n\n"
|
||||
% (HOOK, _LABEL, _LABEL))
|
||||
patched = method[:first.start()] + injected + method[first.start():]
|
||||
return text[:match.start()] + patched + text[match.end():]
|
||||
194
lihont/portmap.py
Normal file
194
lihont/portmap.py
Normal file
@@ -0,0 +1,194 @@
|
||||
"""Building the mod on another TikTok version.
|
||||
|
||||
Helpers that are off by default, so the build for 47.1.3 stays exactly as it was:
|
||||
|
||||
* `install(classes, literals)` renames obfuscated classes (old name -> name in the new TikTok) and swaps version
|
||||
specific literals (resource ids, file paths) in the source of every `lihont` module while it is imported, so the
|
||||
patches look for the right things without being rewritten by hand. Switched on with the environment variable
|
||||
LIHONT_PORT_MAP=<json>, see lihont/portmaps/ and scripts/port_audit.py.
|
||||
* `translate(text)` does the same for text read at build time (smali templates).
|
||||
* `stage_java(source, target)` copies the Java runtime with the same renaming ("X.0Uiz" in strings included), so the
|
||||
runtime that is compiled into the APK names the classes of the TikTok it is built for.
|
||||
* `ClassIndex` finds which dex of an APK defines a class, so patches do not depend on a fixed `classesN.dex`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.abc
|
||||
import importlib.machinery
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def load_map(path) -> dict:
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
return dict(data.get("classes", {}))
|
||||
|
||||
|
||||
def load_version(path) -> str:
|
||||
return str(json.loads(Path(path).read_text(encoding="utf-8")).get("to", ""))
|
||||
|
||||
|
||||
def load_literals(path) -> dict:
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
return dict(data.get("literals", {}))
|
||||
|
||||
|
||||
def _pattern(mapping: dict):
|
||||
# "LX/1DvK;" and its inner classes "LX/1DvK$0;" share the name before the ; or $
|
||||
names = sorted((old[1:-1] for old in mapping), key=len, reverse=True)
|
||||
if not names:
|
||||
return None
|
||||
# "LX/1DvK;" may follow a primitive letter in a descriptor ("ZZLX/1DvK;"), so a leading L needs no look-behind;
|
||||
# without the L the name must not be the tail of a longer word or path.
|
||||
return re.compile(r"(?:(L)|(?<![A-Za-z0-9_$/]))(" + "|".join(re.escape(n) for n in names) + r")(?=[;$.\"' )\\\n]|$)")
|
||||
|
||||
|
||||
def rename(source: str, mapping: dict, literals: dict | None = None) -> str:
|
||||
pattern = _pattern(mapping)
|
||||
if pattern is not None:
|
||||
table = {old[1:-1]: new[1:-1] for old, new in mapping.items()}
|
||||
|
||||
def swap(match):
|
||||
return (match.group(1) or "") + table[match.group(2)]
|
||||
source = pattern.sub(swap, source)
|
||||
return swap_literals(source, literals) if literals else source
|
||||
|
||||
|
||||
def swap_literals(source: str, literals: dict) -> str:
|
||||
"""Whole-word replacement of literals such as 0x7F0D0178 or res/b/pr.xml, all in one pass (no chains)."""
|
||||
keys = sorted(literals, key=len, reverse=True)
|
||||
pattern = re.compile(r"(?<![A-Za-z0-9_])(" + "|".join(re.escape(k) for k in keys) + r")(?![A-Za-z0-9_])", re.I)
|
||||
lower = {k.lower(): v for k, v in literals.items()}
|
||||
return pattern.sub(lambda m: lower[m.group(1).lower()], source)
|
||||
|
||||
|
||||
def rename_dotted(source: str, mapping: dict) -> str:
|
||||
"""Java spells a class of the app's root package "X.0Uiz" (Class.forName), not "LX/0Uiz;"."""
|
||||
names = sorted((old[3:-1] for old in mapping if old.startswith("LX/")), key=len, reverse=True)
|
||||
if not names:
|
||||
return source
|
||||
table = {old[3:-1]: new[3:-1] for old, new in mapping.items() if old.startswith("LX/") and new.startswith("LX/")}
|
||||
pattern = re.compile(r"(?<![A-Za-z0-9_$.])X\.(" + "|".join(re.escape(n) for n in names) + r")(?![A-Za-z0-9_])")
|
||||
return pattern.sub(lambda m: "X." + table[m.group(1)], source)
|
||||
|
||||
|
||||
class _Renaming(importlib.machinery.SourceFileLoader):
|
||||
def __init__(self, fullname, path, mapping, literals):
|
||||
super().__init__(fullname, path)
|
||||
self._mapping = mapping
|
||||
self._literals = literals
|
||||
|
||||
def get_code(self, fullname):
|
||||
source = self.get_data(self.path).decode("utf-8")
|
||||
return compile(rename(source, self._mapping, self._literals), self.path, "exec", dont_inherit=True)
|
||||
|
||||
|
||||
class _Finder(importlib.abc.MetaPathFinder):
|
||||
def __init__(self, mapping, literals):
|
||||
self._mapping = mapping
|
||||
self._literals = literals
|
||||
|
||||
def find_spec(self, fullname, path, target=None):
|
||||
if not fullname.startswith("lihont.") or fullname == "lihont.portmap":
|
||||
return None
|
||||
spec = importlib.machinery.PathFinder.find_spec(fullname, path)
|
||||
if spec is not None and isinstance(spec.loader, importlib.machinery.SourceFileLoader):
|
||||
spec.loader = _Renaming(spec.loader.name, spec.loader.path, self._mapping, self._literals)
|
||||
return spec
|
||||
|
||||
|
||||
_ACTIVE: dict = {}
|
||||
_LITERALS: dict = {}
|
||||
_TARGET: list = []
|
||||
|
||||
|
||||
def target_version() -> str:
|
||||
"""The TikTok version the active map was made for ("" without a map)."""
|
||||
return _TARGET[0] if _TARGET else ""
|
||||
|
||||
|
||||
def install(mapping: dict, literals: dict | None = None, version: str = "") -> None:
|
||||
sys.dont_write_bytecode = True
|
||||
if version:
|
||||
_TARGET[:] = [version]
|
||||
_ACTIVE.update(mapping)
|
||||
_LITERALS.update(literals or {})
|
||||
sys.meta_path.insert(0, _Finder(mapping, dict(literals or {})))
|
||||
|
||||
|
||||
def active() -> bool:
|
||||
return bool(_ACTIVE or _LITERALS)
|
||||
|
||||
|
||||
def translate(text: str) -> str:
|
||||
"""The same renaming for text that is read at build time (smali templates); a no-op without a map."""
|
||||
return rename(text, _ACTIVE, _LITERALS) if active() else text
|
||||
|
||||
|
||||
def stage_java(source, target) -> str:
|
||||
"""A copy of the Java runtime for the TikTok that is being built for; the same folder when there is no map."""
|
||||
if not active():
|
||||
return str(source)
|
||||
source, target = Path(source), Path(target)
|
||||
if target.exists():
|
||||
shutil.rmtree(target)
|
||||
for path in source.rglob("*"):
|
||||
if not path.is_file():
|
||||
continue
|
||||
destination = target / path.relative_to(source)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path.suffix == ".java":
|
||||
text = path.read_text(encoding="utf-8")
|
||||
text = rename_dotted(rename(text, _ACTIVE, _LITERALS), _ACTIVE)
|
||||
destination.write_text(text, encoding="utf-8", newline="\n")
|
||||
else:
|
||||
shutil.copyfile(path, destination)
|
||||
return str(target)
|
||||
|
||||
|
||||
# ---- which dex defines a class --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _uleb(data: bytes, at: int):
|
||||
value = shift = 0
|
||||
while True:
|
||||
byte = data[at]
|
||||
at += 1
|
||||
value |= (byte & 0x7F) << shift
|
||||
shift += 7
|
||||
if not byte & 0x80:
|
||||
return value, at
|
||||
|
||||
|
||||
def defined_classes(dex: bytes):
|
||||
"""Descriptors of the classes a dex defines."""
|
||||
string_ids_off = struct.unpack_from("<I", dex, 60)[0]
|
||||
type_ids_off = struct.unpack_from("<I", dex, 68)[0]
|
||||
class_defs_size, class_defs_off = struct.unpack_from("<2I", dex, 96)
|
||||
names = []
|
||||
for i in range(class_defs_size):
|
||||
class_idx = struct.unpack_from("<I", dex, class_defs_off + 32 * i)[0]
|
||||
string_idx = struct.unpack_from("<I", dex, type_ids_off + 4 * class_idx)[0]
|
||||
at = struct.unpack_from("<I", dex, string_ids_off + 4 * string_idx)[0]
|
||||
length, at = _uleb(dex, at)
|
||||
names.append(dex[at:at + length].decode("utf-8", "replace"))
|
||||
return names
|
||||
|
||||
|
||||
class ClassIndex:
|
||||
"""class descriptor -> dex name, built once for an APK."""
|
||||
|
||||
def __init__(self, apk):
|
||||
self._where = {}
|
||||
for name in sorted(apk.names()):
|
||||
if re.fullmatch(r"classes\d*\.dex", name):
|
||||
for descriptor in defined_classes(apk.read(name)):
|
||||
self._where.setdefault(descriptor, name)
|
||||
|
||||
def dex_for(self, owner: str, fallback: str) -> str:
|
||||
return self._where.get(owner, fallback)
|
||||
871
lihont/portmaps/47.5.15.json
Normal file
871
lihont/portmaps/47.5.15.json
Normal file
@@ -0,0 +1,871 @@
|
||||
{
|
||||
"from": "47.1.3",
|
||||
"to": "47.5.15",
|
||||
"classes": {
|
||||
"LX/01h3;": "LX/00vE;",
|
||||
"LX/0Kzn;": "LX/03kn;",
|
||||
"LX/0LAr;": "LX/0frf;",
|
||||
"LX/0LDf;": "LX/0g7W;",
|
||||
"LX/0LDm;": "LX/0g7e;",
|
||||
"LX/0LQf;": "LX/03kq;",
|
||||
"LX/0LRh;": "LX/0g9g;",
|
||||
"LX/0LYA;": "LX/0gSD;",
|
||||
"LX/0Lis;": "LX/0olL;",
|
||||
"LX/0Lk9;": "LX/0p15;",
|
||||
"LX/0M1d;": "LX/03Vq;",
|
||||
"LX/0M8m;": "LX/055y;",
|
||||
"LX/0MIo;": "LX/0gUr;",
|
||||
"LX/0qrm;": "LX/0GAg;",
|
||||
"LX/0qv6;": "LX/124W;",
|
||||
"LX/0qvH;": "LX/124L;",
|
||||
"LX/0qvL;": "LX/0GE8;",
|
||||
"LX/0qvu;": "LX/12AE;",
|
||||
"LX/0qwE;": "LX/02mV;",
|
||||
"LX/1Bem;": "LX/08Mi;",
|
||||
"LX/1DHB;": "LX/00Nr;",
|
||||
"LX/1DHU;": "LX/03dK;",
|
||||
"LX/1DuR;": "LX/1QjC;",
|
||||
"LX/1MiX;": "LX/03im;",
|
||||
"LX/0KwU;": "LX/0fo1;",
|
||||
"LX/0L5k;": "LX/0fpu;",
|
||||
"LX/1DvK;": "LX/1Qia;",
|
||||
"LX/1Dvf;": "LX/1QjJ;",
|
||||
"LX/0kmX;": "LX/00PS;",
|
||||
"LX/0LFj;": "LX/0gWm;",
|
||||
"LX/0LAb;": "LX/0gee;",
|
||||
"LX/0FL9;": "LX/1AW5;",
|
||||
"LX/0yw4;": "LX/00No;",
|
||||
"LX/0rdj;": "LX/0cdf;",
|
||||
"LX/14x0;": "LX/1NVu;",
|
||||
"LX/14wU;": "LX/0ceI;",
|
||||
"LX/1552;": "LX/1AM4;",
|
||||
"LX/0FKH;": "LX/1AW2;",
|
||||
"LX/0rZQ;": "LX/1QEa;",
|
||||
"LX/0FKI;": "LX/1AnY;",
|
||||
"LX/14g9;": "LX/1B02;",
|
||||
"LX/1EjA;": "LX/00V4;",
|
||||
"LX/1A6P;": "LX/0YtN;",
|
||||
"LX/0wWx;": "LX/1TnZ;",
|
||||
"LX/1BCf;": "LX/00g6;",
|
||||
"LX/1B41;": "LX/04Gz;",
|
||||
"LX/11LV;": "LX/0pMd;",
|
||||
"LX/11OD;": "LX/1CaE;",
|
||||
"LX/11Li;": "LX/1CaD;",
|
||||
"LX/0fU0;": "LX/1QEv;",
|
||||
"LX/15or;": "LX/0Kvg;",
|
||||
"LX/0fTx;": "LX/1A9W;",
|
||||
"LX/0H5D;": "LX/0doV;",
|
||||
"LX/15nZ;": "LX/0dnz;",
|
||||
"LX/0fTy;": "LX/1A9V;",
|
||||
"LX/0Y23;": "LX/008B;",
|
||||
"LX/1aei;": "LX/1rsU;",
|
||||
"LX/1CCz;": "LX/1UIQ;",
|
||||
"LX/1CvC;": "LX/01j3;",
|
||||
"LX/18Wg;": "LX/1DRd;",
|
||||
"LX/0HtY;": "LX/1GEj;",
|
||||
"LX/0Hsy;": "LX/05Nz;",
|
||||
"LX/0ugf;": "LX/0FQo;",
|
||||
"LX/0zyI;": "LX/1C71;",
|
||||
"LX/17f5;": "LX/06zm;",
|
||||
"LX/0WBa;": "LX/11OS;",
|
||||
"LX/17Yf;": "LX/1CC0;",
|
||||
"LX/17YC;": "LX/1CBr;",
|
||||
"LX/17Yy;": "LX/1CCg;",
|
||||
"LX/17Yn;": "LX/1CCH;",
|
||||
"LX/17Yz;": "LX/1C3V;",
|
||||
"LX/0dLQ;": "LX/1OsI;",
|
||||
"LX/0dLZ;": "LX/1Osd;",
|
||||
"LX/0dLO;": "LX/1OsH;",
|
||||
"LX/1CCw;": "LX/1UIO;",
|
||||
"LX/1BCM;": "LX/1FiA;",
|
||||
"LX/1RNP;": "LX/1iHx;",
|
||||
"LX/1RGW;": "LX/1iBu;",
|
||||
"LX/1R5f;": "LX/1hx9;",
|
||||
"LX/1Qdi;": "LX/1hRJ;",
|
||||
"LX/0rZe;": "LX/0FQn;",
|
||||
"LX/0ra6;": "LX/1QEc;",
|
||||
"LX/1Ef1;": "LX/1ThU;",
|
||||
"LX/1Cd0;": "LX/1As8;",
|
||||
"LX/1YOU;": "LX/1pXw;",
|
||||
"LX/13Zf;": "LX/1HM6;",
|
||||
"LX/13Zh;": "LX/1HOK;",
|
||||
"LX/0rZF;": "LX/0GKx;",
|
||||
"LX/1TGx;": "LX/1kCz;",
|
||||
"LX/1Cfj;": "LX/1MPk;",
|
||||
"LX/0FLG;": "LX/0cdg;",
|
||||
"LX/1Ccy;": "LX/1AsB;",
|
||||
"LX/0rZX;": "LX/1QEe;",
|
||||
"LX/0F5x;": "LX/0iu3;",
|
||||
"LX/0FL7;": "LX/1AWO;",
|
||||
"LX/1CPb;": "LX/1Hnp;",
|
||||
"LX/0uge;": "LX/1GEi;",
|
||||
"LX/0rZU;": "LX/1QEq;",
|
||||
"LX/0rZq;": "LX/1QEk;",
|
||||
"LX/153I;": "LX/1NMw;",
|
||||
"LX/18xT;": "LX/1WIC;",
|
||||
"LX/1CpQ;": "LX/05Yw;",
|
||||
"LX/17hK;": "LX/05Z3;",
|
||||
"LX/1Cr6;": "LX/02sc;",
|
||||
"LX/1Csk;": "LX/03Oi;",
|
||||
"LX/1Csj;": "LX/03Oq;",
|
||||
"LX/1Cpo;": "LX/01jm;",
|
||||
"LX/1Cpa;": "LX/03lj;",
|
||||
"LX/1DGK;": "LX/1ULQ;",
|
||||
"LX/1DGL;": "LX/1ULN;",
|
||||
"LX/0H4I;": "LX/10Uh;",
|
||||
"LX/0HrT;": "LX/007L;",
|
||||
"LX/0fUX;": "LX/1A9U;",
|
||||
"LX/0FL8;": "LX/1AWP;",
|
||||
"LX/0H4b;": "LX/0eXZ;",
|
||||
"LX/1CE4;": "LX/1UJO;",
|
||||
"LX/0Syf;": "LX/02fG;",
|
||||
"LX/0qvX;": "LX/12AM;",
|
||||
"LX/0Bl3;": "LX/0xZJ;",
|
||||
"LX/0MIq;": "LX/0g94;",
|
||||
"LX/0LR4;": "LX/03zd;",
|
||||
"LX/0LQM;": "LX/03kk;",
|
||||
"LX/0L2A;": "LX/03wi;",
|
||||
"LX/0LQl;": "LX/055G;",
|
||||
"LX/0CX2;": "LX/0p1E;",
|
||||
"LX/0CWi;": "LX/0q5t;",
|
||||
"LX/0LLI;": "LX/0fyn;",
|
||||
"LX/0MN8;": "LX/0gj6;",
|
||||
"LX/0MNM;": "LX/05V6;",
|
||||
"LX/0MNz;": "LX/05VD;",
|
||||
"LX/0MNJ;": "LX/1Yn1;",
|
||||
"LX/0MOB;": "LX/03eK;",
|
||||
"LX/0LYD;": "LX/0gSF;",
|
||||
"LX/0MOb;": "LX/1GKH;",
|
||||
"LX/0MNv;": "LX/03ic;",
|
||||
"LX/0DMR;": "LX/0og7;",
|
||||
"LX/0LGU;": "LX/03lK;",
|
||||
"LX/0CWm;": "LX/0q5w;",
|
||||
"LX/1Dit;": "LX/1UVO;",
|
||||
"LX/0L9u;": "LX/0gHR;",
|
||||
"LX/0LQx;": "LX/03km;",
|
||||
"LX/1BeU;": "LX/09lB;",
|
||||
"LX/1Baf;": "LX/0AxR;",
|
||||
"LX/1Dfo;": "LX/1VDu;",
|
||||
"LX/17JA;": "LX/1G59;",
|
||||
"LX/1Dfq;": "LX/1VDw;",
|
||||
"LX/1Dgp;": "LX/1VDs;",
|
||||
"LX/0poF;": "LX/1G5E;",
|
||||
"LX/17DO;": "LX/1G50;",
|
||||
"LX/1Dfp;": "LX/1VDv;",
|
||||
"LX/1Dgo;": "LX/1VDt;",
|
||||
"LX/0LDi;": "LX/0g7Z;",
|
||||
"LX/01sS;": "LX/03gP;",
|
||||
"LX/0LDj;": "LX/0g7a;",
|
||||
"LX/1Dw4;": "LX/05R6;",
|
||||
"LX/0Lqw;": "LX/03eN;",
|
||||
"LX/0LDk;": "LX/0g7q;",
|
||||
"LX/0LDv;": "LX/0g7c;",
|
||||
"LX/0LBx;": "LX/0fzH;",
|
||||
"LX/0LBu;": "LX/0fzD;",
|
||||
"LX/0LwC;": "LX/03k8;",
|
||||
"LX/0MNu;": "LX/1YmE;",
|
||||
"LX/0MOd;": "LX/03if;",
|
||||
"LX/0rZV;": "LX/1QEt;",
|
||||
"LX/1Cr5;": "LX/07mD;",
|
||||
"LX/1Agh;": "LX/01gL;",
|
||||
"LX/1Aey;": "LX/01gu;",
|
||||
"LX/0Aam;": "LX/00bx;",
|
||||
"LX/0kRg;": "LX/0pFz;",
|
||||
"LX/1BCe;": "LX/00ln;",
|
||||
"LX/1BAW;": "LX/0Ii6;",
|
||||
"LX/1BAJ;": "LX/0Ii7;",
|
||||
"LX/0Vsn;": "LX/0Ii8;",
|
||||
"LX/0WbC;": "LX/04Bf;",
|
||||
"LX/1B6a;": "LX/0Ii9;",
|
||||
"LX/1B6g;": "LX/0IiA;",
|
||||
"LX/1B5P;": "LX/0IiB;",
|
||||
"LX/0FKX;": "LX/1AWE;",
|
||||
"LX/0WPj;": "LX/02nl;",
|
||||
"LX/0LSJ;": "LX/03Xa;",
|
||||
"LX/1J87;": "LX/1DP0;",
|
||||
"LX/17Yx;": "LX/1CCf;",
|
||||
"LX/0Why;": "LX/0025;",
|
||||
"LX/1BaE;": "LX/05d5;",
|
||||
"LX/180M;": "LX/06yS;",
|
||||
"LX/0sVI;": "LX/06yR;",
|
||||
"LX/1CE0;": "LX/1UJM;",
|
||||
"LX/0MN7;": "LX/05V0;",
|
||||
"LX/0MNE;": "LX/05V1;",
|
||||
"LX/0MLr;": "LX/059n;",
|
||||
"LX/0a5O;": "LX/05Am;",
|
||||
"LX/0MNi;": "LX/1Ynh;",
|
||||
"LX/0MNS;": "LX/1YnV;",
|
||||
"LX/0dKh;": "LX/0S3i;",
|
||||
"LX/0M0Y;": "LX/03hJ;",
|
||||
"LX/17f4;": "LX/06zl;",
|
||||
"LX/132Q;": "LX/1LDM;",
|
||||
"LX/0FOj;": "LX/1ARB;",
|
||||
"LX/0rZS;": "LX/1QEd;",
|
||||
"LX/0U8H;": "LX/0xUv;",
|
||||
"LX/0U82;": "LX/0GL5;",
|
||||
"LX/0dzr;": "LX/1OsL;",
|
||||
"LX/0dKe;": "LX/1OsN;",
|
||||
"LX/0vYf;": "LX/035D;",
|
||||
"LX/1Csb;": "LX/03Pw;",
|
||||
"LX/0XEt;": "LX/03Po;",
|
||||
"LX/1Cse;": "LX/03Oo;",
|
||||
"LX/1Ct9;": "LX/03Q7;",
|
||||
"LX/1Csh;": "LX/03Ph;",
|
||||
"LX/1Ct0;": "LX/03Pn;",
|
||||
"LX/1Crz;": "LX/03Rx;",
|
||||
"LX/1Csd;": "LX/05Yv;",
|
||||
"LX/1Cue;": "LX/1DWL;",
|
||||
"LX/1Cms;": "LX/03lX;",
|
||||
"LX/1BCO;": "LX/1Fhy;",
|
||||
"LX/17YB;": "LX/1CBe;",
|
||||
"LX/17YD;": "LX/1CCR;",
|
||||
"LX/17YE;": "LX/1CCS;",
|
||||
"LX/0FIu;": "LX/1Ane;",
|
||||
"LX/0LLm;": "LX/0gKV;",
|
||||
"LX/0HrX;": "LX/0M4i;",
|
||||
"LX/0Hqj;": "LX/0M4p;",
|
||||
"LX/0Lr6;": "LX/03jo;",
|
||||
"LX/0M0P;": "LX/03jt;",
|
||||
"LX/0MEu;": "LX/03k4;",
|
||||
"LX/0Lu4;": "LX/03js;",
|
||||
"LX/0Lu0;": "LX/03jr;",
|
||||
"LX/0LwD;": "LX/03kJ;",
|
||||
"LX/0LwH;": "LX/03kT;",
|
||||
"LX/0LwN;": "LX/03kA;",
|
||||
"LX/0LzF;": "LX/03kH;",
|
||||
"LX/0M5A;": "LX/03k2;",
|
||||
"LX/0bCj;": "LX/0Kvl;",
|
||||
"LX/05ay;": "LX/02gw;",
|
||||
"LX/18xW;": "LX/1WI8;",
|
||||
"LX/10RX;": "LX/05hb;",
|
||||
"LX/0M8J;": "LX/0562;",
|
||||
"LX/0MNI;": "LX/03Xh;",
|
||||
"LX/0MNR;": "LX/05V9;",
|
||||
"LX/0MO9;": "LX/05V3;",
|
||||
"LX/0qvZ;": "LX/12AN;",
|
||||
"LX/0QGv;": "LX/1L53;",
|
||||
"LX/153O;": "LX/1NMv;",
|
||||
"LX/1EfC;": "LX/1ThM;",
|
||||
"LX/1EfG;": "LX/1ThO;",
|
||||
"LX/0Eqn;": "LX/0iLH;",
|
||||
"LX/0rZs;": "LX/1QEl;",
|
||||
"LX/0rZp;": "LX/1QEj;",
|
||||
"LX/0Xc8;": "LX/0VLx;",
|
||||
"LX/0XaB;": "LX/0UFw;",
|
||||
"LX/0XZ2;": "LX/0UE6;",
|
||||
"LX/1CDH;": "LX/1UJJ;",
|
||||
"LX/1Bxp;": "LX/1U6z;",
|
||||
"LX/1CCt;": "LX/1UIS;",
|
||||
"LX/1CD6;": "LX/1UJK;",
|
||||
"LX/1CD0;": "LX/1UIR;",
|
||||
"LX/1CpV;": "LX/03Os;",
|
||||
"LX/1Bwn;": "LX/02xN;",
|
||||
"LX/1Cpt;": "LX/05Y3;",
|
||||
"LX/1CpX;": "LX/05Wo;",
|
||||
"LX/1Cmv;": "LX/05X2;",
|
||||
"LX/0rZm;": "LX/1dI6;",
|
||||
"LX/0rZl;": "LX/1A5o;",
|
||||
"LX/0raW;": "LX/0Faz;",
|
||||
"LX/0rZh;": "LX/0y81;",
|
||||
"LX/0rZd;": "LX/1A8K;",
|
||||
"LX/1Cd3;": "LX/1AsA;",
|
||||
"LX/17fJ;": "LX/00yB;",
|
||||
"LX/17fL;": "LX/0G6G;",
|
||||
"LX/17Zq;": "LX/0Fke;",
|
||||
"LX/17dg;": "LX/07iH;",
|
||||
"LX/17dl;": "LX/0701;",
|
||||
"LX/0WT5;": "LX/11N8;",
|
||||
"LX/0WT1;": "LX/11Lw;",
|
||||
"LX/0Loy;": "LX/03xc;",
|
||||
"LX/0A3H;": "LX/0ceh;",
|
||||
"LX/11Mu;": "LX/1CaH;",
|
||||
"LX/1BeV;": "LX/09kc;",
|
||||
"LX/1CCv;": "LX/1UIP;",
|
||||
"LX/1B4c;": "LX/0Wf4;",
|
||||
"LX/1BE7;": "LX/1YKX;",
|
||||
"LX/1DGS;": "LX/1Rw5;",
|
||||
"LX/0Xb3;": "LX/0UJv;",
|
||||
"LX/0LRy;": "LX/0frl;",
|
||||
"LX/1BAG;": "LX/1UA4;",
|
||||
"LX/17oY;": "LX/1CBW;",
|
||||
"LX/180P;": "LX/030l;",
|
||||
"LX/0U8B;": "LX/0xdl;",
|
||||
"LX/0WbD;": "LX/04Bn;",
|
||||
"LX/0Lwf;": "LX/03kB;",
|
||||
"LX/0LwM;": "LX/03kD;",
|
||||
"LX/1Aiu;": "LX/02ro;",
|
||||
"LX/1Bwl;": "LX/02xP;",
|
||||
"LX/0dLN;": "LX/1OsQ;",
|
||||
"LX/0dMA;": "LX/1OsK;",
|
||||
"LX/0dKg;": "LX/0Uix;",
|
||||
"LX/03TB;": "LX/08eM;",
|
||||
"LX/0sY0;": "LX/0ILy;",
|
||||
"LX/1Bb8;": "LX/0Lfi;",
|
||||
"LX/0Gqm;": "LX/06H4;",
|
||||
"LX/01mA;": "LX/0B3x;",
|
||||
"LX/0Cat;": "LX/0cbC;",
|
||||
"LX/0KoL;": "LX/0GaH;",
|
||||
"LX/1BeS;": "LX/02wr;",
|
||||
"LX/0hZq;": "LX/0B3M;",
|
||||
"LX/0sTs;": "LX/1S8J;",
|
||||
"LX/1BE2;": "LX/1YKe;",
|
||||
"LX/1BAU;": "LX/0czi;",
|
||||
"LX/0MNN;": "LX/05VA;",
|
||||
"LX/0MIR;": "LX/1UKw;",
|
||||
"LX/01rr;": "LX/002A;",
|
||||
"LX/0MOD;": "LX/05V5;",
|
||||
"LX/0MNO;": "LX/05V7;",
|
||||
"LX/0MIk;": "LX/0597;",
|
||||
"LX/0HrG;": "LX/0M4q;",
|
||||
"LX/1B5b;": "LX/05WS;",
|
||||
"LX/0MO6;": "LX/03id;",
|
||||
"LX/0MMs;": "LX/03h2;",
|
||||
"LX/1Cri;": "LX/05jy;",
|
||||
"LX/17Vq;": "LX/1CAX;",
|
||||
"LX/0MHx;": "LX/058z;",
|
||||
"LX/0MI9;": "LX/03dV;",
|
||||
"LX/1Crm;": "LX/03Ow;",
|
||||
"LX/1Cs0;": "LX/05k3;",
|
||||
"LX/1Crl;": "LX/075X;",
|
||||
"LX/1Cpe;": "LX/05Y9;",
|
||||
"LX/1CuR;": "LX/1DWB;",
|
||||
"LX/0vhC;": "LX/031v;",
|
||||
"LX/0vyE;": "LX/02sS;",
|
||||
"LX/17YH;": "LX/1CBt;",
|
||||
"LX/1Atg;": "LX/05xE;",
|
||||
"LX/1B68;": "LX/02Tc;",
|
||||
"LX/1B6b;": "LX/05xM;",
|
||||
"LX/1B6S;": "LX/1UAQ;",
|
||||
"LX/0MNA;": "LX/0jhV;",
|
||||
"LX/0LwK;": "LX/03kC;",
|
||||
"LX/0Lwa;": "LX/03kG;",
|
||||
"LX/1CpL;": "LX/05YF;",
|
||||
"LX/0Hrd;": "LX/0M4j;",
|
||||
"LX/0M1U;": "LX/03kI;",
|
||||
"LX/0LwT;": "LX/03kF;",
|
||||
"LX/0LwO;": "LX/03kE;",
|
||||
"LX/0Lxc;": "LX/03by;",
|
||||
"LX/0Low;": "LX/03k9;",
|
||||
"LX/0LwV;": "LX/03kO;",
|
||||
"LX/1BGl;": "LX/05dk;",
|
||||
"LX/0MBa;": "LX/03t9;",
|
||||
"LX/0vYe;": "LX/05bC;",
|
||||
"LX/0hSJ;": "LX/02sa;",
|
||||
"LX/1J86;": "LX/03eJ;",
|
||||
"LX/1J84;": "LX/03Y7;",
|
||||
"LX/0MOv;": "LX/03YA;",
|
||||
"LX/0dKy;": "LX/1Osc;",
|
||||
"LX/0dM9;": "LX/1OsS;",
|
||||
"LX/0dLJ;": "LX/1OrX;",
|
||||
"LX/0dLF;": "LX/1OrW;",
|
||||
"LX/0dLr;": "LX/1OsT;",
|
||||
"LX/12k8;": "LX/02D6;",
|
||||
"LX/1B5a;": "LX/1U9C;",
|
||||
"LX/1B5l;": "LX/1UAD;",
|
||||
"LX/17Pp;": "LX/03PP;",
|
||||
"LX/1Crr;": "LX/03P2;",
|
||||
"LX/0MOu;": "LX/1DP9;",
|
||||
"LX/0vyD;": "LX/02se;",
|
||||
"LX/0MDS;": "LX/057z;",
|
||||
"LX/0MCI;": "LX/03sx;",
|
||||
"LX/0Le8;": "LX/03ty;",
|
||||
"LX/0MBf;": "LX/057U;",
|
||||
"LX/0MBG;": "LX/056Q;",
|
||||
"LX/0MI3;": "LX/03hg;",
|
||||
"LX/1Bb7;": "LX/0Lfg;",
|
||||
"LX/1Crn;": "LX/05jr;",
|
||||
"LX/1Cs5;": "LX/075n;",
|
||||
"LX/1Cs3;": "LX/078C;",
|
||||
"LX/1Crk;": "LX/05k9;",
|
||||
"LX/1Crj;": "LX/05dj;",
|
||||
"LX/1Cr8;": "LX/05bB;",
|
||||
"LX/1Csc;": "LX/05di;",
|
||||
"LX/1Cr7;": "LX/0784;",
|
||||
"LX/1Csv;": "LX/1DVx;",
|
||||
"LX/1CpM;": "LX/05X9;",
|
||||
"LX/1J88;": "LX/03YD;",
|
||||
"LX/1J82;": "LX/1DOz;",
|
||||
"LX/1J8F;": "LX/1CWx;",
|
||||
"LX/0MI6;": "LX/03hd;",
|
||||
"LX/0vYg;": "LX/05XD;",
|
||||
"LX/1Cq7;": "LX/05Xg;",
|
||||
"LX/0USX;": "LX/02xG;",
|
||||
"LX/0Cax;": "LX/0chK;",
|
||||
"LX/0MO5;": "LX/1UW8;",
|
||||
"LX/1BAP;": "LX/1UAF;",
|
||||
"LX/0uo6;": "LX/05x8;",
|
||||
"LX/0MIT;": "LX/03tD;",
|
||||
"LX/0MOe;": "LX/1UKy;",
|
||||
"LX/0L1b;": "LX/03lJ;",
|
||||
"LX/0LB7;": "LX/055A;",
|
||||
"LX/1MiY;": "LX/03iY;",
|
||||
"LX/0kmK;": "LX/03ju;",
|
||||
"LX/0kmL;": "LX/0AXQ;"
|
||||
},
|
||||
"provisional": {
|
||||
"LX/0KwU;": "LX/0fo1;",
|
||||
"LX/0L5k;": "LX/0fpu;",
|
||||
"LX/1DvK;": "LX/1Qia;",
|
||||
"LX/1Dvf;": "LX/1QjJ;"
|
||||
},
|
||||
"ambiguous": {
|
||||
"LX/0LB8;": [
|
||||
"LX/10mc;",
|
||||
"LX/06Yl;"
|
||||
]
|
||||
},
|
||||
"inferred": {
|
||||
"LX/0kmX;": "LX/00PS;",
|
||||
"LX/0LFj;": "LX/0gWm;",
|
||||
"LX/0LAb;": "LX/0gee;",
|
||||
"LX/0FL9;": "LX/1AW5;",
|
||||
"LX/0yw4;": "LX/00No;",
|
||||
"LX/0rdj;": "LX/0cdf;",
|
||||
"LX/14x0;": "LX/1NVu;",
|
||||
"LX/14wU;": "LX/0ceI;",
|
||||
"LX/1552;": "LX/1AM4;",
|
||||
"LX/0FKH;": "LX/1AW2;",
|
||||
"LX/0rZQ;": "LX/1QEa;",
|
||||
"LX/0FKI;": "LX/1AnY;",
|
||||
"LX/14g9;": "LX/1B02;",
|
||||
"LX/1EjA;": "LX/00V4;",
|
||||
"LX/1A6P;": "LX/0YtN;",
|
||||
"LX/0wWx;": "LX/1TnZ;",
|
||||
"LX/1BCf;": "LX/00g6;",
|
||||
"LX/1B41;": "LX/04Gz;",
|
||||
"LX/11LV;": "LX/0pMd;",
|
||||
"LX/11OD;": "LX/1CaE;",
|
||||
"LX/11Li;": "LX/1CaD;",
|
||||
"LX/0fU0;": "LX/1QEv;",
|
||||
"LX/15or;": "LX/0Kvg;",
|
||||
"LX/0fTx;": "LX/1A9W;",
|
||||
"LX/0H5D;": "LX/0doV;",
|
||||
"LX/15nZ;": "LX/0dnz;",
|
||||
"LX/0fTy;": "LX/1A9V;",
|
||||
"LX/0Y23;": "LX/008B;",
|
||||
"LX/1aei;": "LX/1rsU;",
|
||||
"LX/1CCz;": "LX/1UIQ;",
|
||||
"LX/1CvC;": "LX/01j3;",
|
||||
"LX/18Wg;": "LX/1DRd;",
|
||||
"LX/0HtY;": "LX/1GEj;",
|
||||
"LX/0Hsy;": "LX/05Nz;",
|
||||
"LX/0ugf;": "LX/0FQo;",
|
||||
"LX/0zyI;": "LX/1C71;",
|
||||
"LX/17f5;": "LX/06zm;",
|
||||
"LX/0WBa;": "LX/11OS;",
|
||||
"LX/17Yf;": "LX/1CC0;",
|
||||
"LX/17YC;": "LX/1CBr;",
|
||||
"LX/17Yy;": "LX/1CCg;",
|
||||
"LX/17Yn;": "LX/1CCH;",
|
||||
"LX/17Yz;": "LX/1C3V;",
|
||||
"LX/0dLQ;": "LX/1OsI;",
|
||||
"LX/0dLZ;": "LX/1Osd;",
|
||||
"LX/0dLO;": "LX/1OsH;",
|
||||
"LX/1CCw;": "LX/1UIO;",
|
||||
"LX/1BCM;": "LX/1FiA;",
|
||||
"LX/1RNP;": "LX/1iHx;",
|
||||
"LX/1RGW;": "LX/1iBu;",
|
||||
"LX/1R5f;": "LX/1hx9;",
|
||||
"LX/1Qdi;": "LX/1hRJ;",
|
||||
"LX/0rZe;": "LX/0FQn;",
|
||||
"LX/0ra6;": "LX/1QEc;",
|
||||
"LX/1Ef1;": "LX/1ThU;",
|
||||
"LX/1Cd0;": "LX/1As8;",
|
||||
"LX/1YOU;": "LX/1pXw;",
|
||||
"LX/13Zf;": "LX/1HM6;",
|
||||
"LX/13Zh;": "LX/1HOK;",
|
||||
"LX/0rZF;": "LX/0GKx;",
|
||||
"LX/1TGx;": "LX/1kCz;",
|
||||
"LX/1Cfj;": "LX/1MPk;",
|
||||
"LX/0FLG;": "LX/0cdg;",
|
||||
"LX/1Ccy;": "LX/1AsB;",
|
||||
"LX/0rZX;": "LX/1QEe;",
|
||||
"LX/0F5x;": "LX/0iu3;",
|
||||
"LX/0FL7;": "LX/1AWO;",
|
||||
"LX/1CPb;": "LX/1Hnp;",
|
||||
"LX/0uge;": "LX/1GEi;",
|
||||
"LX/0rZU;": "LX/1QEq;",
|
||||
"LX/0rZq;": "LX/1QEk;",
|
||||
"LX/153I;": "LX/1NMw;",
|
||||
"LX/18xT;": "LX/1WIC;",
|
||||
"LX/1CpQ;": "LX/05Yw;",
|
||||
"LX/17hK;": "LX/05Z3;",
|
||||
"LX/1Cr6;": "LX/02sc;",
|
||||
"LX/1Csk;": "LX/03Oi;",
|
||||
"LX/1Csj;": "LX/03Oq;",
|
||||
"LX/1Cpo;": "LX/01jm;",
|
||||
"LX/1Cpa;": "LX/03lj;",
|
||||
"LX/1DGK;": "LX/1ULQ;",
|
||||
"LX/1DGL;": "LX/1ULN;",
|
||||
"LX/0H4I;": "LX/10Uh;",
|
||||
"LX/0HrT;": "LX/007L;",
|
||||
"LX/0fUX;": "LX/1A9U;",
|
||||
"LX/0FL8;": "LX/1AWP;",
|
||||
"LX/0H4b;": "LX/0eXZ;",
|
||||
"LX/1CE4;": "LX/1UJO;",
|
||||
"LX/0Syf;": "LX/02fG;",
|
||||
"LX/0qvX;": "LX/12AM;",
|
||||
"LX/0Bl3;": "LX/0xZJ;",
|
||||
"LX/0MIq;": "LX/0g94;",
|
||||
"LX/0LR4;": "LX/03zd;",
|
||||
"LX/0LQM;": "LX/03kk;",
|
||||
"LX/0L2A;": "LX/03wi;",
|
||||
"LX/0LQl;": "LX/055G;",
|
||||
"LX/0CX2;": "LX/0p1E;",
|
||||
"LX/0CWi;": "LX/0q5t;",
|
||||
"LX/0LLI;": "LX/0fyn;",
|
||||
"LX/0MN8;": "LX/0gj6;",
|
||||
"LX/0MNM;": "LX/05V6;",
|
||||
"LX/0MNz;": "LX/05VD;",
|
||||
"LX/0MNJ;": "LX/1Yn1;",
|
||||
"LX/0MOB;": "LX/03eK;",
|
||||
"LX/0LYD;": "LX/0gSF;",
|
||||
"LX/0MOb;": "LX/1GKH;",
|
||||
"LX/0MNv;": "LX/03ic;",
|
||||
"LX/0DMR;": "LX/0og7;",
|
||||
"LX/0LGU;": "LX/03lK;",
|
||||
"LX/0CWm;": "LX/0q5w;",
|
||||
"LX/1Dit;": "LX/1UVO;",
|
||||
"LX/0L9u;": "LX/0gHR;",
|
||||
"LX/0LQx;": "LX/03km;",
|
||||
"LX/1BeU;": "LX/09lB;",
|
||||
"LX/1Baf;": "LX/0AxR;",
|
||||
"LX/1Dfo;": "LX/1VDu;",
|
||||
"LX/17JA;": "LX/1G59;",
|
||||
"LX/1Dfq;": "LX/1VDw;",
|
||||
"LX/1Dgp;": "LX/1VDs;",
|
||||
"LX/0poF;": "LX/1G5E;",
|
||||
"LX/17DO;": "LX/1G50;",
|
||||
"LX/1Dfp;": "LX/1VDv;",
|
||||
"LX/1Dgo;": "LX/1VDt;",
|
||||
"LX/0LDi;": "LX/0g7Z;",
|
||||
"LX/01sS;": "LX/03gP;",
|
||||
"LX/0LDj;": "LX/0g7a;",
|
||||
"LX/1Dw4;": "LX/05R6;",
|
||||
"LX/0Lqw;": "LX/03eN;",
|
||||
"LX/0LDk;": "LX/0g7q;",
|
||||
"LX/0LDv;": "LX/0g7c;",
|
||||
"LX/0LBx;": "LX/0fzH;",
|
||||
"LX/0LBu;": "LX/0fzD;",
|
||||
"LX/0LwC;": "LX/03k8;",
|
||||
"LX/0MNu;": "LX/1YmE;",
|
||||
"LX/0MOd;": "LX/03if;",
|
||||
"LX/0rZV;": "LX/1QEt;",
|
||||
"LX/1Cr5;": "LX/07mD;",
|
||||
"LX/1Agh;": "LX/01gL;",
|
||||
"LX/1Aey;": "LX/01gu;",
|
||||
"LX/0Aam;": "LX/00bx;",
|
||||
"LX/0kRg;": "LX/0pFz;",
|
||||
"LX/1BCe;": "LX/00ln;",
|
||||
"LX/1BAW;": "LX/0Ii6;",
|
||||
"LX/1BAJ;": "LX/0Ii7;",
|
||||
"LX/0Vsn;": "LX/0Ii8;",
|
||||
"LX/0WbC;": "LX/04Bf;",
|
||||
"LX/1B6a;": "LX/0Ii9;",
|
||||
"LX/1B6g;": "LX/0IiA;",
|
||||
"LX/1B5P;": "LX/0IiB;",
|
||||
"LX/0FKX;": "LX/1AWE;",
|
||||
"LX/0WPj;": "LX/02nl;",
|
||||
"LX/0LSJ;": "LX/03Xa;",
|
||||
"LX/1J87;": "LX/1DP0;",
|
||||
"LX/17Yx;": "LX/1CCf;",
|
||||
"LX/0Why;": "LX/0025;",
|
||||
"LX/1BaE;": "LX/05d5;",
|
||||
"LX/180M;": "LX/06yS;",
|
||||
"LX/0sVI;": "LX/06yR;",
|
||||
"LX/1CE0;": "LX/1UJM;",
|
||||
"LX/0MN7;": "LX/05V0;",
|
||||
"LX/0MNE;": "LX/05V1;",
|
||||
"LX/0MLr;": "LX/059n;",
|
||||
"LX/0a5O;": "LX/05Am;",
|
||||
"LX/0MNi;": "LX/1Ynh;",
|
||||
"LX/0MNS;": "LX/1YnV;",
|
||||
"LX/0dKh;": "LX/0S3i;",
|
||||
"LX/0M0Y;": "LX/03hJ;",
|
||||
"LX/17f4;": "LX/06zl;",
|
||||
"LX/132Q;": "LX/1LDM;",
|
||||
"LX/0FOj;": "LX/1ARB;",
|
||||
"LX/0rZS;": "LX/1QEd;",
|
||||
"LX/0U8H;": "LX/0xUv;",
|
||||
"LX/0U82;": "LX/0GL5;",
|
||||
"LX/0dzr;": "LX/1OsL;",
|
||||
"LX/0dKe;": "LX/1OsN;",
|
||||
"LX/0vYf;": "LX/035D;",
|
||||
"LX/1Csb;": "LX/03Pw;",
|
||||
"LX/0XEt;": "LX/03Po;",
|
||||
"LX/1Cse;": "LX/03Oo;",
|
||||
"LX/1Ct9;": "LX/03Q7;",
|
||||
"LX/1Csh;": "LX/03Ph;",
|
||||
"LX/1Ct0;": "LX/03Pn;",
|
||||
"LX/1Crz;": "LX/03Rx;",
|
||||
"LX/1Csd;": "LX/05Yv;",
|
||||
"LX/1Cue;": "LX/1DWL;",
|
||||
"LX/1Cms;": "LX/03lX;",
|
||||
"LX/1BCO;": "LX/1Fhy;",
|
||||
"LX/17YB;": "LX/1CBe;",
|
||||
"LX/17YD;": "LX/1CCR;",
|
||||
"LX/17YE;": "LX/1CCS;",
|
||||
"LX/0FIu;": "LX/1Ane;",
|
||||
"LX/0LLm;": "LX/0gKV;",
|
||||
"LX/0HrX;": "LX/0M4i;",
|
||||
"LX/0Hqj;": "LX/0M4p;",
|
||||
"LX/0Lr6;": "LX/03jo;",
|
||||
"LX/0M0P;": "LX/03jt;",
|
||||
"LX/0MEu;": "LX/03k4;",
|
||||
"LX/0Lu4;": "LX/03js;",
|
||||
"LX/0Lu0;": "LX/03jr;",
|
||||
"LX/0LwD;": "LX/03kJ;",
|
||||
"LX/0LwH;": "LX/03kT;",
|
||||
"LX/0LwN;": "LX/03kA;",
|
||||
"LX/0LzF;": "LX/03kH;",
|
||||
"LX/0M5A;": "LX/03k2;",
|
||||
"LX/0bCj;": "LX/0Kvl;",
|
||||
"LX/05ay;": "LX/02gw;",
|
||||
"LX/18xW;": "LX/1WI8;",
|
||||
"LX/10RX;": "LX/05hb;",
|
||||
"LX/0M8J;": "LX/0562;",
|
||||
"LX/0MNI;": "LX/03Xh;",
|
||||
"LX/0MNR;": "LX/05V9;",
|
||||
"LX/0MO9;": "LX/05V3;",
|
||||
"LX/0qvZ;": "LX/12AN;",
|
||||
"LX/0QGv;": "LX/1L53;",
|
||||
"LX/153O;": "LX/1NMv;",
|
||||
"LX/1EfC;": "LX/1ThM;",
|
||||
"LX/1EfG;": "LX/1ThO;",
|
||||
"LX/0Eqn;": "LX/0iLH;",
|
||||
"LX/0rZs;": "LX/1QEl;",
|
||||
"LX/0rZp;": "LX/1QEj;",
|
||||
"LX/0Xc8;": "LX/0VLx;",
|
||||
"LX/0XaB;": "LX/0UFw;",
|
||||
"LX/0XZ2;": "LX/0UE6;",
|
||||
"LX/1CDH;": "LX/1UJJ;",
|
||||
"LX/1Bxp;": "LX/1U6z;",
|
||||
"LX/1CCt;": "LX/1UIS;",
|
||||
"LX/1CD6;": "LX/1UJK;",
|
||||
"LX/1CD0;": "LX/1UIR;",
|
||||
"LX/1CpV;": "LX/03Os;",
|
||||
"LX/1Bwn;": "LX/02xN;",
|
||||
"LX/1Cpt;": "LX/05Y3;",
|
||||
"LX/1CpX;": "LX/05Wo;",
|
||||
"LX/1Cmv;": "LX/05X2;",
|
||||
"LX/0rZm;": "LX/1dI6;",
|
||||
"LX/0rZl;": "LX/1A5o;",
|
||||
"LX/0raW;": "LX/0Faz;",
|
||||
"LX/0rZh;": "LX/0y81;",
|
||||
"LX/0rZd;": "LX/1A8K;",
|
||||
"LX/1Cd3;": "LX/1AsA;",
|
||||
"LX/17fJ;": "LX/00yB;",
|
||||
"LX/17fL;": "LX/0G6G;",
|
||||
"LX/17Zq;": "LX/0Fke;",
|
||||
"LX/17dg;": "LX/07iH;",
|
||||
"LX/17dl;": "LX/0701;",
|
||||
"LX/0WT5;": "LX/11N8;",
|
||||
"LX/0WT1;": "LX/11Lw;",
|
||||
"LX/0Loy;": "LX/03xc;",
|
||||
"LX/0A3H;": "LX/0ceh;",
|
||||
"LX/11Mu;": "LX/1CaH;",
|
||||
"LX/1BeV;": "LX/09kc;",
|
||||
"LX/1CCv;": "LX/1UIP;",
|
||||
"LX/1B4c;": "LX/0Wf4;",
|
||||
"LX/1BE7;": "LX/1YKX;",
|
||||
"LX/1DGS;": "LX/1Rw5;",
|
||||
"LX/0Xb3;": "LX/0UJv;",
|
||||
"LX/0LRy;": "LX/0frl;",
|
||||
"LX/1BAG;": "LX/1UA4;",
|
||||
"LX/17oY;": "LX/1CBW;",
|
||||
"LX/180P;": "LX/030l;",
|
||||
"LX/0U8B;": "LX/0xdl;",
|
||||
"LX/0WbD;": "LX/04Bn;",
|
||||
"LX/0Lwf;": "LX/03kB;",
|
||||
"LX/0LwM;": "LX/03kD;",
|
||||
"LX/1Aiu;": "LX/02ro;",
|
||||
"LX/1Bwl;": "LX/02xP;",
|
||||
"LX/0dLN;": "LX/1OsQ;",
|
||||
"LX/0dMA;": "LX/1OsK;",
|
||||
"LX/0dKg;": "LX/0Uix;",
|
||||
"LX/03TB;": "LX/08eM;",
|
||||
"LX/0sY0;": "LX/0ILy;",
|
||||
"LX/1Bb8;": "LX/0Lfi;",
|
||||
"LX/0Gqm;": "LX/06H4;",
|
||||
"LX/01mA;": "LX/0B3x;",
|
||||
"LX/0Cat;": "LX/0cbC;",
|
||||
"LX/0KoL;": "LX/0GaH;",
|
||||
"LX/1BeS;": "LX/02wr;",
|
||||
"LX/0hZq;": "LX/0B3M;",
|
||||
"LX/0sTs;": "LX/1S8J;",
|
||||
"LX/1BE2;": "LX/1YKe;",
|
||||
"LX/1BAU;": "LX/0czi;",
|
||||
"LX/0MNN;": "LX/05VA;",
|
||||
"LX/0MIR;": "LX/1UKw;",
|
||||
"LX/01rr;": "LX/002A;",
|
||||
"LX/0MOD;": "LX/05V5;",
|
||||
"LX/0MNO;": "LX/05V7;",
|
||||
"LX/0MIk;": "LX/0597;",
|
||||
"LX/0HrG;": "LX/0M4q;",
|
||||
"LX/1B5b;": "LX/05WS;",
|
||||
"LX/0MO6;": "LX/03id;",
|
||||
"LX/0MMs;": "LX/03h2;",
|
||||
"LX/1Cri;": "LX/05jy;",
|
||||
"LX/17Vq;": "LX/1CAX;",
|
||||
"LX/0MHx;": "LX/058z;",
|
||||
"LX/0MI9;": "LX/03dV;",
|
||||
"LX/1Crm;": "LX/03Ow;",
|
||||
"LX/1Cs0;": "LX/05k3;",
|
||||
"LX/1Crl;": "LX/075X;",
|
||||
"LX/1Cpe;": "LX/05Y9;",
|
||||
"LX/1CuR;": "LX/1DWB;",
|
||||
"LX/0vhC;": "LX/031v;",
|
||||
"LX/0vyE;": "LX/02sS;",
|
||||
"LX/17YH;": "LX/1CBt;",
|
||||
"LX/1Atg;": "LX/05xE;",
|
||||
"LX/1B68;": "LX/02Tc;",
|
||||
"LX/1B6b;": "LX/05xM;",
|
||||
"LX/1B6S;": "LX/1UAQ;",
|
||||
"LX/0MNA;": "LX/0jhV;",
|
||||
"LX/0LwK;": "LX/03kC;",
|
||||
"LX/0Lwa;": "LX/03kG;",
|
||||
"LX/1CpL;": "LX/05YF;",
|
||||
"LX/0Hrd;": "LX/0M4j;",
|
||||
"LX/0M1U;": "LX/03kI;",
|
||||
"LX/0LwT;": "LX/03kF;",
|
||||
"LX/0LwO;": "LX/03kE;",
|
||||
"LX/0Lxc;": "LX/03by;",
|
||||
"LX/0Low;": "LX/03k9;",
|
||||
"LX/0LwV;": "LX/03kO;",
|
||||
"LX/1BGl;": "LX/05dk;",
|
||||
"LX/0MBa;": "LX/03t9;",
|
||||
"LX/0vYe;": "LX/05bC;",
|
||||
"LX/0hSJ;": "LX/02sa;",
|
||||
"LX/1J86;": "LX/03eJ;",
|
||||
"LX/1J84;": "LX/03Y7;",
|
||||
"LX/0MOv;": "LX/03YA;",
|
||||
"LX/0dKy;": "LX/1Osc;",
|
||||
"LX/0dM9;": "LX/1OsS;",
|
||||
"LX/0dLJ;": "LX/1OrX;",
|
||||
"LX/0dLF;": "LX/1OrW;",
|
||||
"LX/0dLr;": "LX/1OsT;",
|
||||
"LX/12k8;": "LX/02D6;",
|
||||
"LX/1B5a;": "LX/1U9C;",
|
||||
"LX/1B5l;": "LX/1UAD;",
|
||||
"LX/17Pp;": "LX/03PP;",
|
||||
"LX/1Crr;": "LX/03P2;",
|
||||
"LX/0MOu;": "LX/1DP9;",
|
||||
"LX/0vyD;": "LX/02se;",
|
||||
"LX/0MDS;": "LX/057z;",
|
||||
"LX/0MCI;": "LX/03sx;",
|
||||
"LX/0Le8;": "LX/03ty;",
|
||||
"LX/0MBf;": "LX/057U;",
|
||||
"LX/0MBG;": "LX/056Q;",
|
||||
"LX/0MI3;": "LX/03hg;",
|
||||
"LX/1Bb7;": "LX/0Lfg;",
|
||||
"LX/1Crn;": "LX/05jr;",
|
||||
"LX/1Cs5;": "LX/075n;",
|
||||
"LX/1Cs3;": "LX/078C;",
|
||||
"LX/1Crk;": "LX/05k9;",
|
||||
"LX/1Crj;": "LX/05dj;",
|
||||
"LX/1Cr8;": "LX/05bB;",
|
||||
"LX/1Csc;": "LX/05di;",
|
||||
"LX/1Cr7;": "LX/0784;",
|
||||
"LX/1Csv;": "LX/1DVx;",
|
||||
"LX/1CpM;": "LX/05X9;",
|
||||
"LX/1J88;": "LX/03YD;",
|
||||
"LX/1J82;": "LX/1DOz;",
|
||||
"LX/1J8F;": "LX/1CWx;",
|
||||
"LX/0MI6;": "LX/03hd;",
|
||||
"LX/0vYg;": "LX/05XD;",
|
||||
"LX/1Cq7;": "LX/05Xg;",
|
||||
"LX/0USX;": "LX/02xG;",
|
||||
"LX/0Cax;": "LX/0chK;",
|
||||
"LX/0MO5;": "LX/1UW8;",
|
||||
"LX/1BAP;": "LX/1UAF;",
|
||||
"LX/0uo6;": "LX/05x8;",
|
||||
"LX/0MIT;": "LX/03tD;",
|
||||
"LX/0MOe;": "LX/1UKy;"
|
||||
},
|
||||
"disagree": {},
|
||||
"manual": {
|
||||
"LX/0L1b;": "LX/03lJ;",
|
||||
"LX/0LAr;": "LX/0frf;",
|
||||
"LX/0LB7;": "LX/055A;",
|
||||
"LX/1MiY;": "LX/03iY;",
|
||||
"LX/1MiX;": "LX/03im;",
|
||||
"LX/0kmK;": "LX/03ju;",
|
||||
"LX/0kmL;": "LX/0AXQ;"
|
||||
},
|
||||
"literals": {
|
||||
"0x7F0D0178": "0x7F0D0179",
|
||||
"res/b/pr.xml": "res/b/pv.xml",
|
||||
"0x7F0A1DAB": "0x7F0A1D94",
|
||||
"0x7F0A1DAA": "0x7F0A1D93",
|
||||
"0x7F0A1DAC": "0x7F0A1D95",
|
||||
"0x7F0A1DAD": "0x7F0A1D96",
|
||||
"0x7F0A1DAE": "0x7F0A1D97",
|
||||
"0x7F0A881C": "0x7F0A87FA",
|
||||
"0x7F0A8829": "0x7F0A8807",
|
||||
"\"opq\"": "\"op9\"",
|
||||
"\"gsa\"": "\"gt6\"",
|
||||
"\"v29\"": "\"v0z\"",
|
||||
"\"t91\"": "\"t8q\"",
|
||||
"\"dui\"": "\"du2\"",
|
||||
"\"klg\"": "\"kkx\"",
|
||||
"\"zkj\"": "\"zjs\"",
|
||||
"\"t_h\"": "\"lt_off_t_h\"",
|
||||
"\"t_4\"": "\"lt_off_t_4\"",
|
||||
"\"t_k\"": "\"lt_off_t_k\"",
|
||||
"\"t_s\"": "\"lt_off_t_s\"",
|
||||
"\"t_r\"": "\"lt_off_t_r\"",
|
||||
"\"t6g\"": "\"lt_off_t6g\"",
|
||||
"\"bnr\"": "\"lt_off_bnr\"",
|
||||
"\"iaw\"": "\"lt_off_iaw\"",
|
||||
"\"m1s\"": "\"lt_off_m1s\"",
|
||||
"\"m36\"": "\"lt_off_m36\"",
|
||||
"\"pyg\"": "\"lt_off_pyg\"",
|
||||
"\"u8p\"": "\"lt_off_u8p\"",
|
||||
"\"eko\"": "\"lt_off_eko\"",
|
||||
"\"wnz\"": "\"lt_off_wnz\"",
|
||||
"\"l7j\"": "\"lt_off_l7j\"",
|
||||
"\"bsd\"": "\"lt_off_bsd\"",
|
||||
"\"k2b\"": "\"lt_off_k2b\"",
|
||||
"\"mu6\"": "\"lt_off_mu6\"",
|
||||
"\"kgv\"": "\"lt_off_kgv\"",
|
||||
"\"n2b\"": "\"lt_off_n2b\"",
|
||||
"\"kl3\"": "\"lt_off_kl3\"",
|
||||
"\"f36\"": "\"lt_off_f36\"",
|
||||
"\"f67\"": "\"lt_off_f67\"",
|
||||
"\"ep_\"": "\"lt_off_ep_\"",
|
||||
"\"eo1\"": "\"lt_off_eo1\"",
|
||||
"\"l8_\"": "\"lt_off_l8_\"",
|
||||
"\"ejn\"": "\"lt_off_ejn\""
|
||||
},
|
||||
"parked": {
|
||||
"ids": [
|
||||
"\"bnr\"",
|
||||
"\"bsd\"",
|
||||
"\"ejn\"",
|
||||
"\"eko\"",
|
||||
"\"eo1\"",
|
||||
"\"ep_\"",
|
||||
"\"f36\"",
|
||||
"\"f67\"",
|
||||
"\"iaw\"",
|
||||
"\"k2b\"",
|
||||
"\"kgv\"",
|
||||
"\"kl3\"",
|
||||
"\"l7j\"",
|
||||
"\"l8_\"",
|
||||
"\"m1s\"",
|
||||
"\"m36\"",
|
||||
"\"mu6\"",
|
||||
"\"n2b\"",
|
||||
"\"pyg\"",
|
||||
"\"t6g\"",
|
||||
"\"t_4\"",
|
||||
"\"t_h\"",
|
||||
"\"t_k\"",
|
||||
"\"t_r\"",
|
||||
"\"t_s\"",
|
||||
"\"u8p\"",
|
||||
"\"wnz\""
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,25 @@
|
||||
"""Patch TikTok 47.1.3 settings composables to inject native mod settings row and MD3 icons."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
RENDERER_CLASS = "LX/1DvK;"
|
||||
GROUP_CLASS = "LX/1DuR;"
|
||||
DRAW_HOOK = "Llihont/two/settings/SettingsCell;->draw(ZLjava/lang/Object;)Z"
|
||||
CELL_CLASS = "LX/0LDm;"
|
||||
# The icon the settings cell shows before the Material 3 painter takes over. The 47.1.3 build used a fixed constant of
|
||||
# LX/0LB8;; on another TikTok version (LIHONT_PORT_MAP set) that class is not known, so the cell keeps its default icon.
|
||||
SETTINGS_ICON = "" if os.environ.get("LIHONT_PORT_MAP") else "LX/0LB8;->LLLLIIL:LX/0LGU;"
|
||||
PAINTER_CLASS = "Llihont/two/settings/Md3BadgePainter;"
|
||||
|
||||
|
||||
def rewrite_1dvk(text: str) -> str:
|
||||
"""Inject lihont(...) composable into LX/1DvK that renders 'Настройки мода' cell."""
|
||||
"""Inject lihont(...) composable into LX/1DvK that renders 'Настройки мода' cell.
|
||||
|
||||
The anchors are patterns that ignore register numbers, label names, `.line` numbers and the names of TikTok's
|
||||
synthetic lambda classes, so they hold on other TikTok versions as well (see lihont/portmap.py).
|
||||
"""
|
||||
if "lihont(" in text:
|
||||
raise ValueError("lihont method already present in LX/1DvK")
|
||||
|
||||
@@ -23,93 +31,70 @@ def rewrite_1dvk(text: str) -> str:
|
||||
raise ValueError("LX/1DvK;->LIZ method not found")
|
||||
|
||||
body = m_match.group(1)
|
||||
noise = r"(?:[ \t]*\.line [0-9]+\n|[ \t]*\n)*"
|
||||
|
||||
old_recomp = (
|
||||
" new-instance v0, Lkotlin/jvm/internal/AwS2S0121000_35;\n\n"
|
||||
" .line 83886157\n"
|
||||
" .line 83886158\n"
|
||||
" const/16 v11, 0x23\n\n"
|
||||
" .line 83886159\n"
|
||||
" .line 83886160\n"
|
||||
" move-object v6, v0\n\n"
|
||||
" .line 83886161\n"
|
||||
" move-object v7, v5\n\n"
|
||||
" .line 83886162\n"
|
||||
" move v8, v4\n\n"
|
||||
" .line 83886163\n"
|
||||
" move v9, v3\n\n"
|
||||
" .line 83886164\n"
|
||||
" move v10, v2\n\n"
|
||||
" .line 83886165\n"
|
||||
" invoke-direct/range {v6 .. v11}, Lkotlin/jvm/internal/AwS2S0121000_35;-><init>(LX/0CWi;ZZII)V"
|
||||
# the recomposition callback: new Lambda(this, ...) is replaced by SettingsCell.again(...)
|
||||
recomposition = re.compile(
|
||||
r"[ \t]*new-instance v0, (L[\w/$]+;)\n" + noise +
|
||||
r"[ \t]*const/16 v11, 0x[0-9a-f]+\n" + noise +
|
||||
r"[ \t]*move-object v6, v0\n" + noise +
|
||||
r"[ \t]*move-object v7, (v\d+)\n" + noise +
|
||||
r"[ \t]*move v8, (v\d+)\n" + noise +
|
||||
r"[ \t]*move v9, (v\d+)\n" + noise +
|
||||
r"[ \t]*move v10, (v\d+)\n" + noise +
|
||||
r"[ \t]*invoke-direct/range \{v6 \.\. v11\}, \1-><init>\(LX/0CWi;ZZII\)V"
|
||||
)
|
||||
new_recomp = (
|
||||
" invoke-static {v5, v4, v3, v2}, Llihont/two/settings/SettingsCell;->again(Ljava/lang/Object;ZZI)Ljava/lang/Object;\n\n"
|
||||
found = recomposition.search(body)
|
||||
if found is None:
|
||||
raise ValueError("LX/1DvK;->LIZ recomposition callback pattern not found")
|
||||
body = body[:found.start()] + (
|
||||
" invoke-static {%s, %s, %s, %s}, Llihont/two/settings/SettingsCell;->again(Ljava/lang/Object;ZZI)Ljava/lang/Object;\n\n"
|
||||
" move-result-object v0\n\n"
|
||||
" check-cast v0, Lkotlin/jvm/functions/Function2;"
|
||||
)
|
||||
if old_recomp not in body:
|
||||
raise ValueError("LX/1DvK;->LIZ recomposition callback pattern not found")
|
||||
body = body.replace(old_recomp, new_recomp, 1)
|
||||
) % found.group(2, 3, 4, 5) + body[found.end():]
|
||||
|
||||
old_title_icon = (
|
||||
" iget-object v0, v5, LX/0CWi;->LLJJIJIIJIL:Ljava/lang/Integer;\n\n"
|
||||
" .line 83886180\n"
|
||||
" .line 83886181\n"
|
||||
" const/4 v12, 0x0\n\n"
|
||||
" .line 83886182\n"
|
||||
" if-eqz v0, :cond_e5\n\n"
|
||||
" .line 83886183\n"
|
||||
" .line 83886184\n"
|
||||
" invoke-virtual {v0}, Ljava/lang/Integer;->intValue()I\n\n"
|
||||
" .line 83886185\n"
|
||||
" .line 83886186\n"
|
||||
" .line 83886187\n"
|
||||
" move-result v0\n\n"
|
||||
" .line 83886188\n"
|
||||
" :goto_6c\n"
|
||||
" invoke-static {v0, v6}, LX/0KwU;->LIZIZ(ILX/0LYA;)Ljava/lang/String;\n\n"
|
||||
" .line 83886189\n"
|
||||
" .line 83886190\n"
|
||||
" .line 83886191\n"
|
||||
" move-result-object v11\n\n"
|
||||
" .line 83886192\n"
|
||||
" const/4 v10, 0x0\n\n"
|
||||
" .line 83886193\n"
|
||||
" iget-object v0, v5, LX/0CWi;->LLJJIJI:LX/0LGU;\n\n"
|
||||
" .line 83886194\n"
|
||||
" .line 83886195\n"
|
||||
" if-nez v0, :cond_77\n\n"
|
||||
" .line 83886196\n"
|
||||
" .line 83886197\n"
|
||||
" sget-object v0, LX/0L1b;->LIZ:LX/0LGU;\n\n"
|
||||
" .line 83886198\n"
|
||||
" .line 83886199\n"
|
||||
" :cond_77\n"
|
||||
" invoke-static {v0, v6}, LX/0Lis;->LJFF(LX/0LGU;LX/0LYA;)LX/0MIo;"
|
||||
# the title and the icon of the cell
|
||||
title_icon = re.compile(
|
||||
r"[ \t]*iget-object v0, v5, LX/0CWi;->\w+:Ljava/lang/Integer;\n" + noise +
|
||||
r"[ \t]*const/4 v12, 0x0\n" + noise +
|
||||
r"[ \t]*if-eqz v0, :(cond_\w+)\n" + noise +
|
||||
r"[ \t]*invoke-virtual \{v0\}, Ljava/lang/Integer;->intValue\(\)I\n" + noise +
|
||||
r"[ \t]*move-result v0\n" + noise +
|
||||
r"[ \t]*:(goto_\w+)\n"
|
||||
r"[ \t]*invoke-static \{v0, v6\}, LX/0KwU;->LIZIZ\(ILX/0LYA;\)Ljava/lang/String;\n" + noise +
|
||||
r"[ \t]*move-result-object v11\n" + noise +
|
||||
r"[ \t]*const/4 v10, 0x0\n" + noise +
|
||||
r"[ \t]*iget-object v0, v5, LX/0CWi;->\w+:LX/0LGU;\n" + noise +
|
||||
r"[ \t]*if-nez v0, :(cond_\w+)\n" + noise +
|
||||
r"[ \t]*sget-object v0, LX/0L1b;->LIZ:LX/0LGU;\n" + noise +
|
||||
r"[ \t]*:\3\n"
|
||||
r"[ \t]*invoke-static \{v0, v6\}, LX/0Lis;->LJFF\(LX/0LGU;LX/0LYA;\)LX/0MIo;"
|
||||
)
|
||||
new_title_icon = (
|
||||
found = title_icon.search(body)
|
||||
if found is None:
|
||||
raise ValueError("LX/1DvK;->LIZ title/icon pattern not found")
|
||||
miss_label, goto_label = found.group(1), found.group(2)
|
||||
icon = SETTINGS_ICON or "LX/0L1b;->LIZ:LX/0LGU;"
|
||||
body = body[:found.start()] + (
|
||||
" invoke-static {}, Llihont/two/settings/SettingsCell;->title()Ljava/lang/String;\n\n"
|
||||
" move-result-object v11\n\n"
|
||||
" const/4 v12, 0x0\n\n"
|
||||
" const/4 v10, 0x0\n\n"
|
||||
" sget-object v0, LX/0LB8;->LLLLIIL:LX/0LGU;\n\n"
|
||||
" sget-object v0, " + icon + "\n\n"
|
||||
" invoke-static {v0, v6}, LX/0Lis;->LJFF(LX/0LGU;LX/0LYA;)LX/0MIo;"
|
||||
)
|
||||
if old_title_icon not in body:
|
||||
raise ValueError("LX/1DvK;->LIZ title/icon pattern not found")
|
||||
body = body.replace(old_title_icon, new_title_icon, 1)
|
||||
) + body[found.end():]
|
||||
|
||||
cond_e5_pattern = re.compile(
|
||||
r"(?m)^\s*:cond_e5\s*\n\s*const/4 v0, 0x0\s*\n(?:\s*\.line [0-9]+\s*\n)?\s*goto :goto_6c\s*\n?"
|
||||
# the branch that used to supply a missing icon number is gone together with the code that jumped to it
|
||||
miss_block = re.compile(
|
||||
r"(?m)^\s*:" + miss_label + r"\s*\n\s*const/4 v0, 0x0\s*\n(?:\s*\.line [0-9]+\s*\n)*\s*goto :" + goto_label + r"\s*\n?"
|
||||
)
|
||||
if not cond_e5_pattern.search(body):
|
||||
raise ValueError("LX/1DvK;->LIZ cond_e5 block not found")
|
||||
body = cond_e5_pattern.sub("", body)
|
||||
if not miss_block.search(body):
|
||||
raise ValueError("LX/1DvK;->LIZ %s block not found" % miss_label)
|
||||
body = miss_block.sub("", body)
|
||||
|
||||
click_pattern = re.compile(
|
||||
r"(?ms)new-instance v9, Lkotlin/jvm/internal/AwS499S0200000_4;.*?"
|
||||
r"invoke-direct \{v9, v5, v1, v0\}, Lkotlin/jvm/internal/AwS499S0200000_4;-><init>\(LX/0CWi;Landroid/content/Context;I\)V"
|
||||
r"(?ms)new-instance v9, (L[\w/$]+;)(?:(?!new-instance).)*?"
|
||||
r"invoke-direct \{v9, v5, v1, v0\}, \1-><init>\(LX/0CWi;Landroid/content/Context;I\)V"
|
||||
)
|
||||
if click_pattern.search(body):
|
||||
body = click_pattern.sub(
|
||||
@@ -117,9 +102,12 @@ def rewrite_1dvk(text: str) -> str:
|
||||
body,
|
||||
)
|
||||
|
||||
old_ll = " iget-object v7, v5, LX/0CWi;->LL:Lkotlin/jvm/functions/Function1;"
|
||||
if old_ll in body:
|
||||
body = body.replace(old_ll, " const/4 v7, 0x0", 1)
|
||||
body = re.sub(
|
||||
r" iget-object (v\d+), v5, LX/0CWi;->LL:Lkotlin/jvm/functions/Function1;",
|
||||
r" const/4 \1, 0x0",
|
||||
body,
|
||||
count=1,
|
||||
)
|
||||
|
||||
lihont_method = (
|
||||
"\n.method public static final lihont(LX/0CWi;ZZLX/0LYA;I)V\n"
|
||||
@@ -134,27 +122,22 @@ def rewrite_1dur(text: str) -> str:
|
||||
if DRAW_HOOK in text:
|
||||
raise ValueError("SettingsCell.draw already present in LX/1DuR")
|
||||
|
||||
anchor = (
|
||||
" const/4 v14, 0x4\n\n"
|
||||
" .line 83886338\n"
|
||||
" move-object v12, v6\n\n"
|
||||
" .line 83886339\n"
|
||||
" invoke-static/range {v9 .. v14}, LX/1Dvf;->LIZIZ(ZZLcom/ss/android/ugc/aweme/setting/ui/rvmpcompose/group/top/cell/ManagePostsVM;LX/0LYA;II)V"
|
||||
# The call that draws the ManagePostsVM cell; the numbers after `.line` differ between TikTok versions.
|
||||
anchor = re.compile(
|
||||
r"([ \t]*const/4 v14, 0x4\n\n(?:[ \t]*\.line [0-9]+\n)*[ \t]*move-object v12, v6\n\n)"
|
||||
r"((?:[ \t]*\.line [0-9]+\n)*[ \t]*invoke-static/range \{v9 \.\. v14\}, LX/1Dvf;->LIZIZ\("
|
||||
r"ZZLcom/ss/android/ugc/aweme/setting/ui/rvmpcompose/group/top/cell/ManagePostsVM;LX/0LYA;II\)V)"
|
||||
)
|
||||
if anchor not in text:
|
||||
found = anchor.search(text)
|
||||
if found is None:
|
||||
raise ValueError("LX/1DuR ManagePostsVM anchor not found")
|
||||
|
||||
injection = (
|
||||
" const/4 v14, 0x4\n\n"
|
||||
" .line 83886338\n"
|
||||
" move-object v12, v6\n\n"
|
||||
" # LihonT 2.0 native settings cell injection: 47.1.3\n"
|
||||
f" invoke-static {{v9, v6}}, {DRAW_HOOK}\n\n"
|
||||
" move-result v9\n\n"
|
||||
" .line 83886339\n"
|
||||
" invoke-static/range {v9 .. v14}, LX/1Dvf;->LIZIZ(ZZLcom/ss/android/ugc/aweme/setting/ui/rvmpcompose/group/top/cell/ManagePostsVM;LX/0LYA;II)V"
|
||||
)
|
||||
return text.replace(anchor, injection, 1)
|
||||
return text[:found.start()] + found.group(1) + injection + found.group(2) + text[found.end():]
|
||||
|
||||
|
||||
def rewrite_0ldm(text: str) -> str:
|
||||
@@ -175,7 +158,7 @@ def rewrite_0ldm(text: str) -> str:
|
||||
)
|
||||
|
||||
pattern = re.compile(
|
||||
r"(\.method public static final LIZ\(LX/0M1d;[^\n]+\n.*?\.prologue\n(?:\s*\.line [0-9]+\n)?)(\s*move-object/from16 p20, p20)",
|
||||
r"(\.method public static final LIZ\(LX/0M1d;[^\n]+\n.*?\.prologue\n(?:\s*\.line [0-9]+\n)?)(\s*move-object/from16 [vp]\d+, p20)",
|
||||
re.DOTALL
|
||||
)
|
||||
m = pattern.search(text)
|
||||
@@ -187,7 +170,7 @@ def rewrite_0ldm(text: str) -> str:
|
||||
" move-object/from16 v0, p8\n"
|
||||
" move-object/from16 v1, p1\n"
|
||||
" move-object/from16 v2, p25\n"
|
||||
" invoke-static {v0, v1, v2}, Llihont/two/settings/SettingsCell;->transformIcon(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;\n"
|
||||
" invoke-static {v0, v1, v2}, Llihont/two/settings/SettingsCell;->transformIcon(Ljava/lang/Object;Ljava/lang/CharSequence;Ljava/lang/Object;)Ljava/lang/Object;\n"
|
||||
" move-result-object v0\n"
|
||||
" check-cast v0, LX/0LRh;\n"
|
||||
" move-object/from16 p8, v0\n\n"
|
||||
|
||||
@@ -128,7 +128,7 @@ CARD_HOOK = ("Llihont/two/theme/NativeTheme;->cardBackground"
|
||||
"(Ljava/lang/Object;JLjava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;")
|
||||
|
||||
_CARD = re.compile(
|
||||
r" invoke-static \{v11, v0, v1, v15\}, LX/0L5k;->LIZIZ\(LX/0M1d;JLX/0LQx;\)LX/0M1d;\n("
|
||||
r" invoke-static \{(v\d+), v0, v1, v15\}, LX/0L5k;->LIZIZ\(LX/0M1d;JLX/0LQx;\)LX/0M1d;\n("
|
||||
+ _BETWEEN + r" move-result-object v0\n)")
|
||||
|
||||
|
||||
@@ -149,5 +149,5 @@ def rewrite_language_card(text: str) -> str:
|
||||
if len(_CARD.findall(text)) != 1:
|
||||
raise ValueError("LX/0Lk9 must draw its card background exactly once")
|
||||
return _CARD.sub(
|
||||
lambda m: " invoke-static {v11, v0, v1, v15, v3}, %s\n" % CARD_HOOK + m.group(1)
|
||||
lambda m: " invoke-static {%s, v0, v1, v15, v3}, %s\n" % (m.group(1), CARD_HOOK) + m.group(2)
|
||||
+ "\n check-cast v0, LX/0M1d;\n", text, count=1)
|
||||
|
||||
@@ -14,7 +14,8 @@ import subprocess
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
from . import avatar_patch, badge_patch, bar_patch, dexpatch, feed_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, region, profile_features, settings_patch, theme_patch
|
||||
from . import portmap
|
||||
from .apkzip import Apk
|
||||
from .axml import Axml
|
||||
from .toolchain import Toolchain
|
||||
@@ -38,13 +39,24 @@ SETTINGS_TARGET_CLASSES = [settings_patch.RENDERER_CLASS, settings_patch.GROUP_C
|
||||
|
||||
|
||||
|
||||
_INDEXES: dict = {}
|
||||
|
||||
|
||||
def dex_for(apk: Apk, owner: str, fallback: str) -> str:
|
||||
"""The dex that defines `owner` in this APK (the old fixed name when the class is still where it was)."""
|
||||
index = _INDEXES.get(id(apk))
|
||||
if index is None:
|
||||
index = _INDEXES[id(apk)] = portmap.ClassIndex(apk)
|
||||
return index.dex_for(owner, fallback)
|
||||
|
||||
|
||||
def patch_classes(apk: Apk, targets: dict, tools: Toolchain, room: Path, api: int) -> dict:
|
||||
compiler = room / "compiler"
|
||||
compiler.mkdir(parents=True, exist_ok=True)
|
||||
grouped: dict = defaultdict(list)
|
||||
for name, owners in targets.items():
|
||||
for owner in owners:
|
||||
grouped[name].append(owner)
|
||||
grouped[dex_for(apk, owner, name)].append(owner)
|
||||
reports: dict = {}
|
||||
smali = dexpatch.Smali(tools.smali, api, jobs=2, heap="1g")
|
||||
subprocess.run(
|
||||
@@ -100,7 +112,7 @@ def patch_classes(apk: Apk, targets: dict, tools: Toolchain, room: Path, api: in
|
||||
|
||||
def patch_settings_entry(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict:
|
||||
"""Inject the native Jetpack Compose settings row into TikTok's settings card."""
|
||||
name = SETTINGS_TARGET_DEX
|
||||
name = dex_for(apk, SETTINGS_TARGET_CLASSES[0], SETTINGS_TARGET_DEX)
|
||||
before = apk.read(name)
|
||||
folder = room / "settings-entry"
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
@@ -168,7 +180,7 @@ def patch_settings_entry(apk: Apk, tools: Toolchain, room: Path, api: int) -> di
|
||||
|
||||
def patch_md3_settings_icons(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict:
|
||||
"""Inject Material 3 flower badge transformer into TikTok's settings cell renderer in classes9.dex."""
|
||||
name = "classes9.dex"
|
||||
name = dex_for(apk, settings_patch.CELL_CLASS, "classes9.dex")
|
||||
before = apk.read(name)
|
||||
folder = room / "settings-md3-icons"
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
@@ -196,7 +208,7 @@ def patch_md3_settings_icons(apk: Apk, tools: Toolchain, room: Path, api: int) -
|
||||
raise ValueError(f"{painter_src} missing")
|
||||
painter_dst = decoded / "lihont" / "two" / "settings" / "Md3BadgePainter.smali"
|
||||
painter_dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
painter_dst.write_text(painter_src.read_text(encoding="utf-8"), encoding="utf-8", newline="\n")
|
||||
painter_dst.write_text(portmap.translate(painter_src.read_text(encoding="utf-8")), encoding="utf-8", newline="\n")
|
||||
|
||||
replacement = folder / "replacement.dex"
|
||||
dexpatch.Smali(tools.smali, api, jobs=2, heap="1g").assemble(str(decoded), str(replacement))
|
||||
@@ -229,7 +241,7 @@ def patch_md3_settings_icons(apk: Apk, tools: Toolchain, room: Path, api: int) -
|
||||
return {
|
||||
"dex": name,
|
||||
"classes": [settings_patch.CELL_CLASS, settings_patch.PAINTER_CLASS],
|
||||
"hook": "Llihont/two/settings/SettingsCell;->transformIcon(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;",
|
||||
"hook": "Llihont/two/settings/SettingsCell;->transformIcon(Ljava/lang/Object;Ljava/lang/CharSequence;Ljava/lang/Object;)Ljava/lang/Object;",
|
||||
"sha256": hashlib.sha256(patched).hexdigest(),
|
||||
}
|
||||
|
||||
@@ -237,6 +249,7 @@ def patch_md3_settings_icons(apk: Apk, tools: Toolchain, room: Path, api: int) -
|
||||
def patch_class(apk: Apk, tools: Toolchain, room: Path, api: int, dex_name: str, owner: str,
|
||||
label: str, rewrite, marker: bytes) -> dict:
|
||||
"""Disassemble one class, rewrite its smali, and put the reassembled class back in its dex."""
|
||||
dex_name = dex_for(apk, owner, dex_name)
|
||||
before = apk.read(dex_name)
|
||||
folder = room / label
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
@@ -310,6 +323,31 @@ def patch_section_labels(apk: Apk, tools: Toolchain, room: Path, api: int) -> di
|
||||
return report
|
||||
|
||||
|
||||
def patch_comment_photos(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict:
|
||||
"""Let a switch turn on TikTok's multi-photo comments (the experiment gate every part of the comment UI asks)."""
|
||||
report = patch_class(apk, tools, room, api, "classes4.dex", comment_photos_patch.GATE_CLASS,
|
||||
"comment-photos", comment_photos_patch.rewrite_gate,
|
||||
b"Llihont/two/comments/CommentPhotos;")
|
||||
report["hook"] = comment_photos_patch.HOOK
|
||||
return report
|
||||
|
||||
|
||||
def patch_ghost_stories(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict:
|
||||
"""Let a switch stop TikTok from reporting that a story was viewed."""
|
||||
report = patch_class(apk, tools, room, api, "classes12.dex", ghost_patch.STORY_VIEW_CLASS,
|
||||
"ghost-stories", ghost_patch.rewrite_story_view, b"Llihont/two/ghost/Ghost;")
|
||||
report["hook"] = ghost_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,
|
||||
"ghost-messages", ghost_patch.rewrite_mark_read, b"Llihont/two/ghost/Ghost;")
|
||||
report["hook"] = ghost_patch.MARK_READ_HOOK
|
||||
return report
|
||||
|
||||
|
||||
def patch_language_card(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict:
|
||||
"""Let NativeTheme drop the language row's own card inside TikTok settings."""
|
||||
report = patch_class(apk, tools, room, api, "classes9.dex", theme_patch.LANGUAGE_CLASS,
|
||||
@@ -507,6 +545,19 @@ def build(source: str, output: str, workspace: str = "work/build") -> dict:
|
||||
room.mkdir(parents=True, exist_ok=True)
|
||||
tools = Toolchain("tools")
|
||||
apk = Apk(str(source_path))
|
||||
# LIHONT_PORT_SURVEY=1: try every patch against another TikTok version and list which ones fail (no APK is written).
|
||||
survey = os.environ.get("LIHONT_PORT_SURVEY") == "1"
|
||||
failures = {}
|
||||
|
||||
def step(key, function, *arguments):
|
||||
if not survey:
|
||||
return function(*arguments)
|
||||
try:
|
||||
return function(*arguments)
|
||||
except Exception as error: # noqa: BLE001 - the survey reports every kind of failure
|
||||
failures[key] = "%s: %s" % (type(error).__name__, str(error)[:300])
|
||||
return {"failed": failures[key]}
|
||||
|
||||
report = {
|
||||
"edition": "lihont", "mod_version": "2.0-test",
|
||||
"source": source_path.name, "source_sha256": digest,
|
||||
@@ -516,7 +567,7 @@ def build(source: str, output: str, workspace: str = "work/build") -> dict:
|
||||
from . import manifest as manifest_module
|
||||
package = manifest_module.package_name(xml)
|
||||
version = manifest_module.version_name(xml)
|
||||
if package != "com.zhiliaoapp.musically" or version != SOURCE_VERSION:
|
||||
if package != "com.zhiliaoapp.musically" or (version not in (SOURCE_VERSION, portmap.target_version()) and not survey):
|
||||
raise ValueError("Expected TikTok " + SOURCE_VERSION + ", got " + version)
|
||||
api = manifest_module.min_sdk(xml)
|
||||
report["source_version"] = version
|
||||
@@ -535,27 +586,31 @@ def build(source: str, output: str, workspace: str = "work/build") -> dict:
|
||||
report["manifest"] = {"settings_activity": SETTINGS_ACTIVITY, "exported": False, "already_present": True}
|
||||
# The launcher icons the settings screen offers: one disabled alias per catalog icon.
|
||||
from . import app_icons
|
||||
report["app_icons"] = app_icons.apply(apk, xml, app_icons.load_catalog(Path("src/icons")))
|
||||
report["app_icons"] = step("app_icons", app_icons.apply, apk, xml, app_icons.load_catalog(Path("src/icons")))
|
||||
# TikTok's small Stories widget becomes the streak widget (its picture view is all the widget needs).
|
||||
from . import widget_patch
|
||||
report["widget"] = widget_patch.apply(apk, xml, SETTINGS_THEME)
|
||||
report["widget"] = step("widget", widget_patch.apply, apk, xml, SETTINGS_THEME)
|
||||
# The alarm of the streak keeper needs a receiver of its own (the manifest is written again with it).
|
||||
from . import streak_patch
|
||||
report["streak"] = streak_patch.apply(apk, xml)
|
||||
report["changed_dex"] = patch_classes(apk, REGION_TARGETS, tools, room, api)
|
||||
report["settings_entry"] = patch_settings_entry(apk, tools, room, api)
|
||||
report["settings_icons"] = patch_md3_settings_icons(apk, tools, room, api)
|
||||
report["native_theme"] = patch_native_theme(apk, tools, room, api)
|
||||
report["native_rows"] = patch_settings_rows(apk, tools, room, api)
|
||||
report["section_labels"] = patch_section_labels(apk, tools, room, api)
|
||||
report["language_card"] = patch_language_card(apk, tools, room, api)
|
||||
report["main_activity"] = patch_main_activity(apk, tools, room, api)
|
||||
report["downloads"] = patch_downloads(apk, tools, room, api)
|
||||
report["feed"] = patch_feed(apk, tools, room, api)
|
||||
report["badges"] = patch_badges(apk, tools, room, api)
|
||||
report["avatars"] = patch_avatars(apk, tools, room, api)
|
||||
report["feature_flags"] = patch_feature_flags(apk, tools, room, api)
|
||||
runtime_path = tools.compile_dex("src/lihont/two", str(room / "runtime"), api)
|
||||
report["streak"] = step("streak", streak_patch.apply, apk, xml)
|
||||
report["changed_dex"] = step("changed_dex", patch_classes, apk, REGION_TARGETS, tools, room, api)
|
||||
report["settings_entry"] = step("settings_entry", patch_settings_entry, apk, tools, room, api)
|
||||
report["settings_icons"] = step("settings_icons", patch_md3_settings_icons, apk, tools, room, api)
|
||||
report["native_theme"] = step("native_theme", patch_native_theme, apk, tools, room, api)
|
||||
report["native_rows"] = step("native_rows", patch_settings_rows, apk, tools, room, api)
|
||||
report["section_labels"] = step("section_labels", patch_section_labels, apk, tools, room, api)
|
||||
report["language_card"] = step("language_card", patch_language_card, apk, tools, room, api)
|
||||
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["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)
|
||||
report["badges"] = step("badges", patch_badges, apk, tools, room, api)
|
||||
report["avatars"] = step("avatars", patch_avatars, apk, tools, room, api)
|
||||
report["feature_flags"] = step("feature_flags", patch_feature_flags, apk, tools, room, api)
|
||||
runtime_path = tools.compile_dex(portmap.stage_java("src/lihont/two", str(room / "java-src")),
|
||||
str(room / "runtime"), api)
|
||||
runtime = Path(runtime_path).read_bytes()
|
||||
if b"Llihont/two/LihonTRegion;" not in runtime:
|
||||
raise ValueError("Runtime class missing")
|
||||
@@ -572,7 +627,8 @@ def build(source: str, output: str, workspace: str = "work/build") -> dict:
|
||||
+ theme_patch.section_targets() + theme_patch.row_targets()
|
||||
+ theme_patch.card_targets() + bar_patch.runtime_targets()
|
||||
+ media_patch.runtime_targets() + feed_patch.runtime_targets()
|
||||
+ badge_patch.runtime_targets() + avatar_patch.runtime_targets() if t not in merged]
|
||||
+ badge_patch.runtime_targets() + avatar_patch.runtime_targets()
|
||||
+ comment_photos_patch.runtime_targets() + ghost_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
|
||||
@@ -580,6 +636,10 @@ def build(source: str, output: str, workspace: str = "work/build") -> dict:
|
||||
"country": "by", "operator": "25701", "carrier": "A1 BY",
|
||||
"expected_hooks": region.expected_hits(),
|
||||
}
|
||||
if survey:
|
||||
report["survey_failures"] = failures
|
||||
print(json.dumps({"survey_failures": failures}, ensure_ascii=False, indent=2))
|
||||
return report
|
||||
apk.drop_signature()
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
apk.write(str(output_path))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
LihonT 2 «Luna pre-release» promo video: 1080x1920, 30 fps, about 37 seconds, with a synthesised soundtrack (make_lihont_music.py).
|
||||
LihonT 2 «Luna pre-release» promo video: 1080x1920, 30 fps, about 46 seconds, with a synthesised soundtrack (make_lihont_music.py).
|
||||
|
||||
The screens are real screenshots of the mod on a phone, taken to work/promo/shots/ (the status bar and the
|
||||
gesture strip are cut off). Frames are drawn with Pillow in worker processes and piped to ffmpeg.
|
||||
@@ -42,8 +42,10 @@ SCENES = [
|
||||
("save", 17.2, 21.8),
|
||||
("badges", 21.8, 25.8),
|
||||
("settings", 25.8, 30.6),
|
||||
("icons", 30.6, 33.8),
|
||||
("outro", 33.8, 37.8),
|
||||
("flame", 30.6, 34.6),
|
||||
("keeper", 34.6, 38.8),
|
||||
("icons", 38.8, 42.0),
|
||||
("outro", 42.0, 46.0),
|
||||
]
|
||||
DURATION = SCENES[-1][2]
|
||||
FRAMES = int(round(DURATION * FPS))
|
||||
@@ -203,6 +205,11 @@ def init_assets() -> None:
|
||||
ASSETS["shots"] = cache
|
||||
ASSETS["phones"] = {key: build_phone(cache[key]) for key in ("comments", "menu", "native", "shapes", "save")}
|
||||
ASSETS["mod_screens"] = [screen_for(cache["mod1"]), screen_for(cache["mod2"])]
|
||||
import make_widget_preview as WP
|
||||
ASSETS["flame_lit"] = [WP.render(True, n) for n in range(4)]
|
||||
ASSETS["flame_grey"] = WP.render(False)
|
||||
keeper = load_shot("luna/keeper.png") # a toast covers the rows below the chats, so only the top is shown
|
||||
ASSETS["keeper_phone"] = build_phone(keeper.crop((0, 0, keeper.width, 1800)))
|
||||
ASSETS["mod_shell"] = phone_shell(*ASSETS["mod_screens"][0].size)
|
||||
ASSETS["icons"] = {slug: rounded(Image.open(ROOT / "src" / "icons" / (slug + ".png")).convert("RGB").resize((320, 320), Image.Resampling.LANCZOS), 72)
|
||||
for slug, _ in ICONS}
|
||||
@@ -378,6 +385,27 @@ def scene_settings(layer: Image.Image, lt: float) -> None:
|
||||
chip(layer, 890, 1500, "Форма и цвет аватарок", pop(lt, 2.4), size=36)
|
||||
|
||||
|
||||
def scene_flame(layer: Image.Image, lt: float) -> None:
|
||||
headline(layer, lt, "Живой огонёк", "Виджет от 1×1 до 4×4")
|
||||
rise = ease_out_cubic((lt - 0.2) / 0.8)
|
||||
phase = int(lt / 0.22) % 4 # the launcher flips the four pictures by itself, about this fast
|
||||
place(layer, ASSETS["flame_lit"][phase], 280, 1010 + (1 - rise) * 700, 0.82)
|
||||
place(layer, ASSETS["flame_grey"], 800, 1010 + (1 - rise) * 700, 0.82)
|
||||
chip(layer, 280, 1380, "Горит: оранжевый", pop(lt, 0.9), size=38)
|
||||
chip(layer, 800, 1380, "Пора писать: серый", pop(lt, 1.3), size=38)
|
||||
chip(layer, W / 2, 1560, "1×1 · 2×2 · 3×3 · 4×4", pop(lt, 1.8), size=40)
|
||||
|
||||
|
||||
def scene_keeper(layer: Image.Image, lt: float) -> None:
|
||||
headline(layer, lt, "Автопродление", "Раз в день, в нужное время")
|
||||
rise = ease_out_cubic((lt - 0.15) / 0.9)
|
||||
place(layer, ASSETS["keeper_phone"], 755, 1250 + (1 - rise) * 900 + math.sin(lt * 2) * 6, 0.9)
|
||||
chip(layer, 215, 700, "По умолчанию 12:00", pop(lt, 0.9), size=34)
|
||||
chip(layer, 215, 940, "Огонёк или свой текст", pop(lt, 1.3), size=30)
|
||||
chip(layer, 215, 1180, "Свои чаты", pop(lt, 1.7), size=34)
|
||||
chip(layer, 215, 1420, "Свой набор у аккаунта", pop(lt, 2.1), size=30)
|
||||
|
||||
|
||||
def scene_icons(layer: Image.Image, lt: float) -> None:
|
||||
headline(layer, lt, "Иконки приложения", "Выбери свою или добавь свою")
|
||||
spots = [(350, 800), (730, 800), (350, 1220), (730, 1220)]
|
||||
@@ -400,12 +428,13 @@ def scene_outro(layer: Image.Image, lt: float) -> None:
|
||||
chip(layer, W / 2, 1290, "git.lihont.space", pop(lt, 1.0), size=54, fill=PRIMARY, fg=BG)
|
||||
chip(layer, W / 2, 1430, "Telegram · @lihont", pop(lt, 1.3), size=54)
|
||||
c = ease_out_cubic((lt - 1.8) / 0.5)
|
||||
draw_text(layer, (W / 2, 1700), "Открытый код · лицензия EVHNMKHU", 38, MUTED + (int(255 * c),), bold=False)
|
||||
draw_text(layer, (W / 2, 1700), "Открытый код · лицензия VCBFU v2", 38, MUTED + (int(255 * c),), bold=False)
|
||||
|
||||
|
||||
SCENE_DRAW = {
|
||||
"intro": scene_intro, "system": scene_system, "comments": scene_comments, "shapes": scene_shapes,
|
||||
"save": scene_save, "badges": scene_badges, "settings": scene_settings, "icons": scene_icons,
|
||||
"save": scene_save, "badges": scene_badges, "settings": scene_settings, "flame": scene_flame,
|
||||
"keeper": scene_keeper, "icons": scene_icons,
|
||||
"outro": scene_outro,
|
||||
}
|
||||
|
||||
|
||||
91
scripts/make_ltp.py
Normal file
91
scripts/make_ltp.py
Normal file
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Packs plugin folders (plugins/<id>/plugin.json, an optional icon.png, optional files in assets/) into .ltp files.
|
||||
|
||||
An .ltp is a plain zip with plugin.json, optionally icon.png, and optionally files of assets/ (pictures and sounds
|
||||
the plugin's rules point at); the runtime refuses anything else. This script does the same light checks the runtime
|
||||
does (so a mistake shows up here and not on the phone) and writes a file named after the plugin id.
|
||||
|
||||
python scripts/make_ltp.py packs every folder of plugins/ into ComplectAPK/plugins/
|
||||
python scripts/make_ltp.py plugins/my.plugin packs one folder
|
||||
python scripts/make_ltp.py -o some/folder ... writes elsewhere
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
ID = re.compile(r"[a-z0-9][a-z0-9._-]{2,63}")
|
||||
PNG = b"\x89PNG\r\n\x1a\n"
|
||||
MAX_FILE = 1024 * 1024
|
||||
MAX_ICON = 64 * 1024
|
||||
MAX_ASSET = 400 * 1024
|
||||
MAX_ASSETS = 8
|
||||
ASSET = re.compile(r"[a-z0-9][a-z0-9._-]{0,39}")
|
||||
MAGIC = {
|
||||
".png": lambda d: d.startswith(PNG),
|
||||
".gif": lambda d: d.startswith(b"GIF8"),
|
||||
".webp": lambda d: d[:4] == b"RIFF" and d[8:12] == b"WEBP",
|
||||
".ogg": lambda d: d.startswith(b"OggS"),
|
||||
".mp3": lambda d: d.startswith(b"ID3") or (len(d) > 2 and d[0] == 0xFF and d[1] & 0xE0 == 0xE0),
|
||||
}
|
||||
|
||||
|
||||
def pack(folder: Path, out_dir: Path) -> Path:
|
||||
manifest = folder / "plugin.json"
|
||||
if not manifest.is_file():
|
||||
raise SystemExit("%s: no plugin.json" % folder)
|
||||
raw = manifest.read_bytes()
|
||||
try:
|
||||
data = json.loads(raw.decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError) as error:
|
||||
raise SystemExit("%s: plugin.json is not valid UTF-8 JSON: %s" % (folder, error))
|
||||
plugin_id = data.get("id", "")
|
||||
if not isinstance(plugin_id, str) or not ID.fullmatch(plugin_id):
|
||||
raise SystemExit("%s: bad id %r" % (folder, plugin_id))
|
||||
if folder.name != plugin_id:
|
||||
raise SystemExit("%s: the folder name must be the plugin id (%s)" % (folder, plugin_id))
|
||||
icon = folder / "icon.png"
|
||||
out = out_dir / (plugin_id + ".ltp")
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
assets = sorted(p for p in (folder / "assets").glob("*") if p.is_file()) if (folder / "assets").is_dir() else []
|
||||
if len(assets) > MAX_ASSETS:
|
||||
raise SystemExit("%s: at most %d files in assets/" % (folder, MAX_ASSETS))
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
archive.writestr("plugin.json", raw)
|
||||
for asset in assets:
|
||||
body = asset.read_bytes()
|
||||
check = MAGIC.get(asset.suffix.lower())
|
||||
if not ASSET.fullmatch(asset.name) or check is None or not check(body) or len(body) > MAX_ASSET:
|
||||
raise SystemExit("%s: assets/%s is not an allowed file (png, gif, webp, ogg, mp3; up to 400 KB; "
|
||||
"lower-case name)" % (folder, asset.name))
|
||||
archive.writestr("assets/" + asset.name, body)
|
||||
if icon.is_file():
|
||||
picture = icon.read_bytes()
|
||||
if not picture.startswith(PNG) or len(picture) > MAX_ICON:
|
||||
raise SystemExit("%s: icon.png must be a PNG of at most 64 KB" % folder)
|
||||
archive.writestr("icon.png", picture)
|
||||
if out.stat().st_size > MAX_FILE:
|
||||
raise SystemExit("%s: the file is over 1 MB" % out)
|
||||
return out
|
||||
|
||||
|
||||
def main(argv) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("folders", nargs="*", help="plugin folders (default: every folder of plugins/)")
|
||||
parser.add_argument("-o", "--out", default=str(ROOT / "ComplectAPK" / "plugins"))
|
||||
args = parser.parse_args(argv)
|
||||
folders = [Path(f) for f in args.folders] or sorted(p for p in (ROOT / "plugins").iterdir() if p.is_dir())
|
||||
for folder in folders:
|
||||
out = pack(folder, Path(args.out))
|
||||
print("%s %d bytes" % (out, out.stat().st_size))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
377
scripts/make_luna_promo.py
Normal file
377
scripts/make_luna_promo.py
Normal file
@@ -0,0 +1,377 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
LihonT 2 «Luna» promo video: 1080x1920, 30 fps, about 44 seconds, with the synthesised soundtrack of make_lihont_music.py.
|
||||
|
||||
Nothing in it is a screenshot: every scene is drawn here with Pillow (the bubbles, the settings rows, the ghost, the
|
||||
plugin card, the avatar shapes) and the streak flames come from make_widget_preview.py, the same drawing the widget
|
||||
shows on the phone. The earlier pre-release promo (make_lihont_promo.py) is only imported for its helpers and is not
|
||||
changed.
|
||||
|
||||
usage (from the repository root):
|
||||
py -X utf8 -B scripts/make_luna_promo.py # renders work/luna-promo/luna_promo.mp4
|
||||
py -X utf8 -B scripts/make_luna_promo.py --still 14.0 # one frame at 14 s as work/luna-promo/still_14.00.png
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import math
|
||||
import random
|
||||
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_lihont_promo as P # noqa: E402 (helpers only: fonts, easing, chips, shapes)
|
||||
import make_widget_preview as WP # noqa: E402
|
||||
|
||||
W, H, FPS = P.W, P.H, P.FPS
|
||||
ROOT = P.ROOT
|
||||
OUT = ROOT / "work" / "luna-promo" / "luna_promo.mp4"
|
||||
AUDIO = ROOT / "work" / "luna-promo" / "luna_audio.wav"
|
||||
LOGO = P.LOGO
|
||||
|
||||
SCENES = [
|
||||
("intro", 0.0, 3.4),
|
||||
("flame", 3.4, 8.2),
|
||||
("keeper", 8.2, 12.6),
|
||||
("bubbles", 12.6, 17.8),
|
||||
("ghost", 17.8, 22.2),
|
||||
("photos", 22.2, 26.2),
|
||||
("plugins", 26.2, 31.2),
|
||||
("shapes", 31.2, 35.2),
|
||||
("settings", 35.2, 39.6),
|
||||
("outro", 39.6, 43.8),
|
||||
]
|
||||
DURATION = SCENES[-1][2]
|
||||
FRAMES = int(round(DURATION * FPS))
|
||||
FADE = P.FADE
|
||||
|
||||
BG, PRIMARY, ON, MUTED, CHIP, PINK, CORAL = P.BG, P.PRIMARY, P.ON, P.MUTED, P.CHIP, P.PINK, P.CORAL
|
||||
SURFACE = (43, 39, 52)
|
||||
clamp, ease_out_cubic, ease_out_back, pop = P.clamp, P.ease_out_cubic, P.ease_out_back, P.pop
|
||||
draw_text, chip, headline, place = P.draw_text, P.chip, P.headline, P.place
|
||||
|
||||
ASSETS: dict = {}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- small drawings
|
||||
|
||||
def gradient(w: int, h: int, c1, c2, vertical: bool = False) -> Image.Image:
|
||||
img = Image.new("RGB", (w, h))
|
||||
d = ImageDraw.Draw(img)
|
||||
span = h if vertical else w
|
||||
for i in range(span):
|
||||
k = i / max(1, span - 1)
|
||||
color = tuple(int(c1[n] + (c2[n] - c1[n]) * k) for n in range(3))
|
||||
d.line([(0, i), (w, i)] if vertical else [(i, 0), (i, h)], fill=color)
|
||||
return img
|
||||
|
||||
|
||||
def rounded_mask(w: int, h: int, radius: int) -> Image.Image:
|
||||
mask = Image.new("L", (w * 2, h * 2), 0)
|
||||
ImageDraw.Draw(mask).rounded_rectangle([0, 0, w * 2 - 1, h * 2 - 1], radius=radius * 2, fill=255)
|
||||
return mask.resize((w, h), Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def pictured(w: int, h: int, c1, c2, radius: int = 44, motif: tuple = (255, 255, 255, 70)) -> Image.Image:
|
||||
"""A bubble with a picture of its own: a gradient with a flower pattern, like a photo a person would pick."""
|
||||
img = gradient(w, h, c1, c2).convert("RGBA")
|
||||
flower = P.flower(90, motif)
|
||||
for x in range(-20, w, 130):
|
||||
for y in range(-20 + (x // 130 % 2) * 60, h, 120):
|
||||
img.alpha_composite(flower, (x, y)) if 0 <= x < w - 90 and 0 <= y < h - 90 else None
|
||||
img.putalpha(rounded_mask(w, h, radius))
|
||||
return img
|
||||
|
||||
|
||||
def card(layer: Image.Image, box, fill=SURFACE, radius: int = 48, alpha: int = 255) -> None:
|
||||
ImageDraw.Draw(layer, "RGBA").rounded_rectangle(box, radius=radius, fill=fill + (alpha,))
|
||||
|
||||
|
||||
def switch(layer: Image.Image, cx: float, cy: float, on: float) -> None:
|
||||
"""A Material 3 switch; on runs 0..1."""
|
||||
d = ImageDraw.Draw(layer, "RGBA")
|
||||
track = tuple(int(CHIP[n] + (PRIMARY[n] - CHIP[n]) * on) for n in range(3))
|
||||
d.rounded_rectangle([cx - 62, cy - 36, cx + 62, cy + 36], radius=36, fill=track + (255,))
|
||||
r = 22 + 8 * on
|
||||
kx = cx - 26 + 52 * on
|
||||
d.ellipse([kx - r, cy - r, kx + r, cy + r], fill=(BG if on > 0.5 else (150, 144, 160)) + (255,))
|
||||
|
||||
|
||||
def ghost(size: int, bob: float) -> Image.Image:
|
||||
s = size * 3
|
||||
layer = Image.new("RGBA", (s, s), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(layer)
|
||||
white = (240, 236, 248, 255)
|
||||
d.ellipse([s * 0.2, s * 0.1, s * 0.8, s * 0.7], fill=white)
|
||||
d.rectangle([s * 0.2, s * 0.4, s * 0.8, s * 0.82], fill=white)
|
||||
for k in range(4):
|
||||
cx = s * (0.275 + k * 0.15)
|
||||
d.ellipse([cx - s * 0.075, s * 0.74, cx + s * 0.075, s * 0.9 + math.sin(bob * 3 + k) * s * 0.02], fill=white)
|
||||
for ex in (0.38, 0.62):
|
||||
d.ellipse([s * ex - s * 0.04, s * 0.36, s * ex + s * 0.04, s * 0.46], fill=(40, 34, 56, 255))
|
||||
d.ellipse([s * 0.46, s * 0.5, s * 0.54, s * 0.58], fill=(40, 34, 56, 255))
|
||||
return layer.resize((size, size), Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def init_assets() -> None:
|
||||
if ASSETS:
|
||||
return
|
||||
ASSETS["bg"] = Image.new("RGBA", (W, H), BG + (255,))
|
||||
ASSETS["blobs"] = [P.blob(360, (208, 188, 255, 62)), P.blob(300, (239, 184, 200, 52)), P.blob(260, (120, 200, 190, 36))]
|
||||
ASSETS["flower"] = P.flower(70, (255, 255, 255, 26))
|
||||
rnd = random.Random(3)
|
||||
ASSETS["motes"] = [(rnd.random() * W, rnd.random() * H, 0.4 + rnd.random() * 0.9, rnd.random() * 6.28) for _ in range(16)]
|
||||
ASSETS["logo"] = Image.open(LOGO).convert("RGBA")
|
||||
ASSETS["flame_lit"] = [WP.render(True, n) for n in range(4)]
|
||||
ASSETS["flame_grey"] = WP.render(False)
|
||||
ASSETS["incoming"] = pictured(560, 150, (62, 60, 190), (28, 20, 110))
|
||||
ASSETS["incoming_long"] = pictured(640, 150, (62, 60, 190), (28, 20, 110))
|
||||
ASSETS["light"] = pictured(560, 150, (255, 226, 176), (255, 190, 200), motif=(255, 255, 255, 120))
|
||||
ASSETS["mine"] = pictured(520, 150, (150, 60, 190), (90, 30, 140))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- scenes
|
||||
|
||||
def scene_intro(layer, lt):
|
||||
k = ease_out_back(lt / 0.9)
|
||||
place(layer, ASSETS["blobs"][0], W / 2, 800, 1.2 * k)
|
||||
place(layer, ASSETS["logo"], W / 2, 800, 0.46 * k * (1 + 0.03 * math.sin(lt * 4)), math.sin(lt * 2) * 3)
|
||||
a = ease_out_cubic((lt - 0.5) / 0.5)
|
||||
draw_text(layer, (W / 2, 1230 + (1 - a) * 40), "LihonT 2", 130, ON + (int(255 * a),))
|
||||
b = ease_out_cubic((lt - 0.8) / 0.5)
|
||||
draw_text(layer, (W / 2, 1360 + (1 - b) * 30), "Luna", 90, PRIMARY + (int(255 * b),))
|
||||
c = ease_out_cubic((lt - 1.5) / 0.5)
|
||||
draw_text(layer, (W / 2, 1500), "Что нового в релизе", 48, MUTED + (int(255 * c),), bold=False)
|
||||
|
||||
|
||||
def scene_flame(layer, lt):
|
||||
headline(layer, lt, "Живой огонёк", "Виджет серии, от 1×1 до 4×4")
|
||||
rise = ease_out_cubic((lt - 0.2) / 0.8)
|
||||
phase = int(lt / 0.22) % 4
|
||||
lit = ASSETS["flame_lit"][phase]
|
||||
place(layer, lit, 330, 960 + (1 - rise) * 700, 0.95)
|
||||
place(layer, ASSETS["flame_grey"], 790, 800 + (1 - rise) * 700, 0.52)
|
||||
place(layer, lit, 790, 1130 + (1 - rise) * 700, 0.34)
|
||||
place(layer, lit, 610, 1130 + (1 - rise) * 700, 0.26)
|
||||
chip(layer, 330, 1360, "Горит: оранжевый", pop(lt, 0.9), size=38)
|
||||
chip(layer, 790, 1330, "Пора писать: серый", pop(lt, 1.3), size=34)
|
||||
chip(layer, W / 2, 1560, "1×1 · 2×2 · 3×3 · 4×4", pop(lt, 1.8), size=40)
|
||||
|
||||
|
||||
def scene_keeper(layer, lt):
|
||||
headline(layer, lt, "Автопродление", "Огонёк сам, в нужное время")
|
||||
k = ease_out_cubic((lt - 0.2) / 0.6)
|
||||
card(layer, (110, 520 + (1 - k) * 300, 970, 1420 + (1 - k) * 300), radius=56)
|
||||
names = ["Мама", "Друг", "Класс", "Сестра"]
|
||||
t_flip = 2.0
|
||||
for n, name in enumerate(names):
|
||||
y = 640 + n * 190 + (1 - k) * 300
|
||||
P.ImageDraw.Draw(layer, "RGBA").ellipse([160, y - 55, 270, y + 55], fill=(110 + n * 25, 90, 190 - n * 20, 255))
|
||||
draw_text(layer, (310, y - 18), name, 46, ON + (255,), anchor="lm")
|
||||
ImageDraw.Draw(layer, "RGBA").rounded_rectangle([310, y + 18, 310 + 260 - n * 30, y + 38], radius=10, fill=CHIP + (255,))
|
||||
flipped = lt > t_flip + n * 0.35
|
||||
flame = ASSETS["flame_lit"][int(lt / 0.2 + n) % 4] if flipped else ASSETS["flame_grey"]
|
||||
place(layer, flame, 840, y, 0.2 * (1 + (0.25 * max(0.0, 1 - (lt - t_flip - n * 0.35) * 4) if flipped else 0)))
|
||||
chip(layer, W / 2, 1530, "12:00", pop(lt, 0.8), size=70, fill=PRIMARY, fg=BG)
|
||||
chip(layer, W / 2, 1660, "Сам пишет огонёк или ваш текст", pop(lt, 1.3), size=34)
|
||||
|
||||
|
||||
def scene_bubbles(layer, lt):
|
||||
headline(layer, lt, "Свои пузыри", "Любая картинка вместо фона")
|
||||
items = [
|
||||
(ASSETS["incoming"], 120, 560, "Привет! Это моя картинка", (255, 255, 255), 0.6),
|
||||
(ASSETS["mine"], 440, 760, "Видно всё", (255, 255, 255), 1.1),
|
||||
(ASSETS["light"], 120, 960, "На светлой чёрный", (35, 30, 45), 1.6),
|
||||
(ASSETS["incoming_long"], 120, 1160, "На тёмной белый, сам", (255, 255, 255), 2.1),
|
||||
]
|
||||
for img, x, y, text, ink, t0 in items:
|
||||
k = pop(lt, t0, 0.5)
|
||||
if k <= 0.02:
|
||||
continue
|
||||
scaled = img.resize((max(1, int(img.width * k)), max(1, int(img.height * k))), Image.Resampling.BILINEAR)
|
||||
cx = x + img.width / 2
|
||||
layer.alpha_composite(scaled, (int(cx - scaled.width / 2), int(y + 75 - scaled.height / 2)))
|
||||
if k > 0.7:
|
||||
draw_text(layer, (x + 46, y + 75), text, 46, ink + (255,), anchor="lm")
|
||||
chip(layer, 270, 1420, "Для каждого человека", pop(lt, 2.8), size=36)
|
||||
chip(layer, 790, 1500, "Общая для незнакомцев", pop(lt, 3.2), size=36)
|
||||
chip(layer, 540, 1640, "Картинки только на телефоне", pop(lt, 3.6), size=34, fill=PRIMARY, fg=BG)
|
||||
|
||||
|
||||
def scene_ghost(layer, lt):
|
||||
headline(layer, lt, "Режим призрака", "Смотрите и читайте незаметно")
|
||||
bob = math.sin(lt * 2.2) * 18
|
||||
place(layer, ASSETS["blobs"][1], W / 2, 760, 1.0)
|
||||
place(layer, ghost(380, lt), W / 2, 760 + bob, ease_out_back(lt / 0.8))
|
||||
card(layer, (110, 1070, 970, 1290), radius=48)
|
||||
draw_text(layer, (170, 1135), "Истории", 50, ON + (255,), anchor="lm")
|
||||
draw_text(layer, (170, 1215), "Автор не увидит вас в зрителях", 34, MUTED + (255,), bold=False, anchor="lm")
|
||||
card(layer, (110, 1330, 970, 1550), radius=48)
|
||||
draw_text(layer, (170, 1395), "Чаты", 50, ON + (255,), anchor="lm")
|
||||
draw_text(layer, (170, 1475), "«Прочитано» не отправляется", 34, MUTED + (255,), bold=False, anchor="lm")
|
||||
for y, t0 in ((1180, 1.2), (1440, 1.8)):
|
||||
switch(layer, 850, y, ease_out_cubic((lt - t0) / 0.4))
|
||||
chip(layer, W / 2, 1690, "Включается в «Приватность»", pop(lt, 2.4), size=36)
|
||||
|
||||
|
||||
def scene_photos(layer, lt):
|
||||
headline(layer, lt, "До 9 фото", "в одном комментарии")
|
||||
colors = [((255, 160, 120), (220, 90, 140)), ((120, 200, 255), (70, 90, 200)), ((180, 255, 170), (60, 160, 130))]
|
||||
for n in range(9):
|
||||
k = pop(lt, 0.5 + n * 0.16, 0.5)
|
||||
if k <= 0.02:
|
||||
continue
|
||||
row, col = divmod(n, 3)
|
||||
c1, c2 = colors[(row + col) % 3]
|
||||
tile = pictured(250, 250, c1, c2, radius=40, motif=(255, 255, 255, 90))
|
||||
place(layer, tile, 240 + col * 300, 640 + row * 300, k)
|
||||
card(layer, (90, 1620, 990, 1760), radius=70)
|
||||
draw_text(layer, (160, 1690), "Написать комментарий…", 40, MUTED + (255,), bold=False, anchor="lm")
|
||||
count = min(9, int(max(0.0, lt - 0.5) / 0.16) + 1)
|
||||
chip(layer, 870, 1690, "%d/9" % count, 1.0, size=36, fill=PRIMARY, fg=BG)
|
||||
|
||||
|
||||
def scene_plugins(layer, lt):
|
||||
headline(layer, lt, "Плагины .ltp", "Свои дополнения без кода")
|
||||
k = ease_out_back((lt - 0.2) / 0.8)
|
||||
place(layer, ASSETS["blobs"][0], W / 2, 860, 1.1)
|
||||
d = ImageDraw.Draw(layer, "RGBA")
|
||||
s = 1.0 * k
|
||||
x0, y0, x1, y1 = W / 2 - 190 * s, 860 - 250 * s, W / 2 + 190 * s, 860 + 250 * s
|
||||
d.rounded_rectangle([x0, y0, x1, y1], radius=int(54 * s), fill=SURFACE + (255,), outline=PRIMARY + (255,), width=6)
|
||||
draw_text(layer, (W / 2, 830), ".ltp", int(120 * s) + 1, PRIMARY + (255,))
|
||||
draw_text(layer, (W / 2, 950), "plugin.json", int(40 * s) + 1, MUTED + (255,), bold=False)
|
||||
chips = [
|
||||
(260, 560, "Права", 0.9), (820, 600, "LihonT Guard", 1.2), (230, 1180, "Откат", 1.5),
|
||||
(830, 1190, "Журнал", 1.8),
|
||||
]
|
||||
for x, y, text, t0 in chips:
|
||||
chip(layer, x, y + math.sin(lt * 2 + x) * 8, text, pop(lt, t0), size=42)
|
||||
chip(layer, W / 2, 1420, "Интернет только с вашего согласия", pop(lt, 2.4), size=36)
|
||||
chip(layer, W / 2, 1540, "Лицензия и ИИ-метки на виду", pop(lt, 2.8), size=36)
|
||||
chip(layer, W / 2, 1660, "Проверка перед установкой", pop(lt, 3.2), size=36, fill=PRIMARY, fg=BG)
|
||||
|
||||
|
||||
def scene_shapes(layer, lt):
|
||||
headline(layer, lt, "Форма аватарок", "Выбираете сами, видят все с модом")
|
||||
kinds = P.SHAPE_KINDS
|
||||
colors = [PRIMARY, PINK, (120, 200, 190), (255, 200, 120), CORAL, (160, 190, 255)]
|
||||
for n, kind in enumerate(kinds):
|
||||
row, col = divmod(n, 3)
|
||||
k = pop(lt, 0.4 + n * 0.2)
|
||||
wob = math.sin(lt * 2.4 + n) * 8
|
||||
place(layer, P.shape_silhouette(kind, 260, colors[n]), 220 + col * 320, 700 + row * 340 + wob, k)
|
||||
chip(layer, W / 2, 1480, "Круг · цветок · скруглённый", pop(lt, 1.8), size=36)
|
||||
chip(layer, W / 2, 1600, "Шестиугольник · сердце · треугольник", pop(lt, 2.2), size=34)
|
||||
chip(layer, W / 2, 1720, "Без мода — круг", pop(lt, 2.6), size=34, fill=PRIMARY, fg=BG)
|
||||
|
||||
|
||||
def scene_settings(layer, lt):
|
||||
headline(layer, lt, "Material 3", "Все настройки в одном стиле")
|
||||
rows = [
|
||||
("Призрак: истории", "Без отметки о просмотре"),
|
||||
("Призрак: сообщения", "Без «прочитано»"),
|
||||
("Свои пузыри", "Картинка и цвет текста"),
|
||||
("Несколько фото", "До 9 в комментарии"),
|
||||
("Меню сохранения", "Качество и только звук"),
|
||||
]
|
||||
card(layer, (80, 470, 1000, 470 + 5 * 220 + 40), radius=56)
|
||||
for n, (title, sub) in enumerate(rows):
|
||||
a = ease_out_cubic((lt - 0.3 - n * 0.15) / 0.4)
|
||||
y = 590 + n * 220
|
||||
dy = (1 - a) * 40
|
||||
P.ImageDraw.Draw(layer, "RGBA").ellipse([130, y - 40 + dy, 210, y + 40 + dy], fill=(110, 60, 20, int(255 * a)))
|
||||
draw_text(layer, (250, y - 24 + dy), title, 46, ON + (int(255 * a),), anchor="lm")
|
||||
draw_text(layer, (250, y + 34 + dy), sub, 32, MUTED + (int(255 * a),), bold=False, anchor="lm")
|
||||
if a > 0.6:
|
||||
switch(layer, 880, y, ease_out_cubic((lt - 1.4 - n * 0.35) / 0.35))
|
||||
chip(layer, W / 2, 1760, "И палитра, и окна, и значки", pop(lt, 2.4), size=36)
|
||||
|
||||
|
||||
def scene_outro(layer, lt):
|
||||
k = ease_out_back(lt / 0.8)
|
||||
place(layer, ASSETS["blobs"][0], W / 2, 640, 1.3 * k)
|
||||
place(layer, ASSETS["logo"], W / 2, 640, 0.40 * k * (1 + 0.03 * math.sin(lt * 4)), math.sin(lt * 2) * 3)
|
||||
a = ease_out_cubic((lt - 0.4) / 0.5)
|
||||
draw_text(layer, (W / 2, 960 + (1 - a) * 40), "LihonT 2 · Luna", 100, ON + (int(255 * a),))
|
||||
b = ease_out_cubic((lt - 0.7) / 0.5)
|
||||
draw_text(layer, (W / 2, 1075 + (1 - b) * 30), "Открытый код · лицензия VCBFU v2", 44, PRIMARY + (int(255 * b),), bold=False)
|
||||
chip(layer, W / 2, 1290, "git.lihont.space", pop(lt, 1.0), size=54, fill=PRIMARY, fg=BG)
|
||||
chip(layer, W / 2, 1430, "Telegram · @lihont", pop(lt, 1.3), size=54)
|
||||
|
||||
|
||||
SCENE_DRAW = {name: globals()["scene_" + name] for name, _, _ in SCENES}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- frames
|
||||
|
||||
def frame_at(t: float) -> Image.Image:
|
||||
init_assets()
|
||||
img = ASSETS["bg"].copy()
|
||||
for n, blob_img in enumerate(ASSETS["blobs"]):
|
||||
x = W * (0.2 + 0.6 * (0.5 + 0.5 * math.sin(t * (0.5 + n * 0.2) + n * 2)))
|
||||
y = H * (0.25 + 0.5 * (0.5 + 0.5 * math.cos(t * (0.4 + n * 0.15) + n)))
|
||||
img.alpha_composite(blob_img, (int(x - blob_img.width / 2), int(y - blob_img.height / 2)))
|
||||
for x, y, speed, phase in ASSETS["motes"]:
|
||||
yy = (y - t * 40 * speed) % (H + 100) - 50
|
||||
img.alpha_composite(ASSETS["flower"], (int(x + math.sin(t * speed + phase) * 30), int(yy)))
|
||||
for name, start, end in SCENES:
|
||||
alpha = clamp((t - (start - FADE)) / (2 * FADE)) * clamp(((end + FADE) - t) / (2 * FADE))
|
||||
if name == "intro":
|
||||
alpha = clamp(((end + FADE) - t) / (2 * FADE))
|
||||
if name == "outro":
|
||||
alpha = clamp((t - (start - FADE)) / (2 * FADE))
|
||||
if alpha <= 0.0:
|
||||
continue
|
||||
layer = Image.new("RGBA", (W, H), (0, 0, 0, 0))
|
||||
SCENE_DRAW[name](layer, max(0.0, t - start))
|
||||
if alpha < 1.0:
|
||||
layer.putalpha(layer.getchannel("A").point(lambda v, a=alpha: 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, help="render one frame at this time (seconds) and stop")
|
||||
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_%.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:]))
|
||||
ffmpeg = shutil.which("ffmpeg") or "ffmpeg"
|
||||
command = [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=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()
|
||||
532
scripts/make_luna_promo2.py
Normal file
532
scripts/make_luna_promo2.py
Normal file
@@ -0,0 +1,532 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
LihonT 2 «Luna» promo, second design: bright "sticker" style, more motion. 1080x1920, 30 fps, about 44 seconds.
|
||||
|
||||
A cream background with a drifting dot grid, thick ink outlines, hard shadows and saturated colours; scenes change with
|
||||
a circle of the next colour opening over the last one. Nothing is a screenshot: the clock, the chat, the ghost, the
|
||||
photos, the plugin pieces and the avatar shapes are all drawn here. The flames come from make_widget_preview.py (the
|
||||
drawing the widget shows). The first promo (make_luna_promo.py) is not touched.
|
||||
|
||||
usage (from the repository root):
|
||||
py -X utf8 -B scripts/make_luna_promo2.py # work/luna-promo/luna_promo_v2.mp4
|
||||
py -X utf8 -B scripts/make_luna_promo2.py --still 14.0 # one frame
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import math
|
||||
import random
|
||||
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_lihont_promo as P # noqa: E402 (fonts, easing, shape outlines)
|
||||
import make_widget_preview as WP # noqa: E402
|
||||
|
||||
W, H, FPS = P.W, P.H, P.FPS
|
||||
ROOT = P.ROOT
|
||||
OUT = ROOT / "work" / "luna-promo" / "luna_promo_v2.mp4"
|
||||
AUDIO = ROOT / "work" / "luna-promo" / "luna_audio_v2.wav"
|
||||
|
||||
INK = (34, 28, 46)
|
||||
CREAM = (255, 244, 224)
|
||||
CORAL = (255, 107, 107)
|
||||
YELLOW = (255, 205, 60)
|
||||
MINT = (94, 214, 170)
|
||||
VIOLET = (150, 110, 255)
|
||||
SKY = (90, 180, 255)
|
||||
PINK = (255, 150, 200)
|
||||
WHITE = (255, 255, 255)
|
||||
CONFETTI = [CORAL, YELLOW, MINT, VIOLET, SKY, PINK]
|
||||
|
||||
SCENES = [
|
||||
("intro", 0.0, 3.6, CREAM),
|
||||
("flame", 3.6, 8.4, (255, 214, 150)),
|
||||
("keeper", 8.4, 13.0, (190, 240, 220)),
|
||||
("bubbles", 13.0, 18.2, (215, 200, 255)),
|
||||
("ghost", 18.2, 22.8, (190, 225, 255)),
|
||||
("photos", 22.8, 27.0, (255, 205, 225)),
|
||||
("plugins", 27.0, 32.0, (255, 236, 150)),
|
||||
("shapes", 32.0, 36.2, (200, 235, 255)),
|
||||
("settings", 36.2, 40.6, (255, 226, 200)),
|
||||
("outro", 40.6, 44.8, (255, 196, 176)),
|
||||
]
|
||||
DURATION = SCENES[-1][2]
|
||||
FRAMES = int(round(DURATION * FPS))
|
||||
WIPE = 0.55
|
||||
|
||||
clamp, ease_out_cubic, ease_out_back, pop = P.clamp, P.ease_out_cubic, P.ease_out_back, P.pop
|
||||
ASSETS: dict = {}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- drawing helpers
|
||||
|
||||
def stroke_text(layer, xy, s, size, fill=INK, outline=None, anchor="mm", bold=True, width=0):
|
||||
d = ImageDraw.Draw(layer, "RGBA")
|
||||
if outline is not None and width:
|
||||
d.text(xy, s, font=P.font(size, bold), fill=fill, anchor=anchor, stroke_width=width, stroke_fill=outline)
|
||||
else:
|
||||
d.text(xy, s, font=P.font(size, bold), fill=fill, anchor=anchor)
|
||||
|
||||
|
||||
def sticker(layer, box, fill, radius=40, shadow=10, line=6):
|
||||
d = ImageDraw.Draw(layer, "RGBA")
|
||||
x0, y0, x1, y1 = box
|
||||
if shadow:
|
||||
d.rounded_rectangle([x0 + shadow, y0 + shadow, x1 + shadow, y1 + shadow], radius=radius, fill=INK + (255,))
|
||||
d.rounded_rectangle(box, radius=radius, fill=fill + (255,), outline=INK + (255,), width=line)
|
||||
|
||||
|
||||
def label(layer, cx, cy, s, k=1.0, size=44, fill=WHITE, ink=INK):
|
||||
"""A bouncy sticker with a word in it."""
|
||||
if k <= 0.02:
|
||||
return
|
||||
f = P.font(max(8, size * k))
|
||||
d = ImageDraw.Draw(layer, "RGBA")
|
||||
box = d.textbbox((0, 0), s, font=f, anchor="lt")
|
||||
w, h = box[2] + 56 * k, box[3] + 36 * k
|
||||
cx = max(w / 2 + 20, min(W - w / 2 - 20, cx))
|
||||
sticker(layer, (cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2), fill, radius=int(h / 2), shadow=int(8 * k), line=max(2, int(5 * k)))
|
||||
d.text((cx, cy + 2), s, font=f, fill=ink + (255,), anchor="mm")
|
||||
|
||||
|
||||
def title(layer, lt, text, sub, color=INK, y=190):
|
||||
"""Letters drop in one after another and settle with a bounce."""
|
||||
f = P.font(110)
|
||||
d = ImageDraw.Draw(layer, "RGBA")
|
||||
total = d.textlength(text, font=f)
|
||||
x = W / 2 - total / 2
|
||||
for n, ch in enumerate(text):
|
||||
w = d.textlength(ch, font=f)
|
||||
k = ease_out_back((lt - n * 0.035) / 0.45)
|
||||
if k > 0.02 and ch != " ":
|
||||
dy = (1 - k) * -160
|
||||
d.text((x + w / 2, y + dy), ch, font=f, fill=color + (255,), anchor="mm", stroke_width=0)
|
||||
x += w
|
||||
b = ease_out_cubic((lt - 0.4) / 0.5)
|
||||
d.text((W / 2, y + 100 + (1 - b) * 30), sub, font=P.font(46, False), fill=INK + (int(220 * b),), anchor="mm")
|
||||
|
||||
|
||||
def burst(layer, cx, cy, lt, t0, seed=1, count=46, power=900):
|
||||
"""Confetti thrown up from a point at time t0."""
|
||||
dt = lt - t0
|
||||
if dt < 0 or dt > 2.4:
|
||||
return
|
||||
rnd = random.Random(seed)
|
||||
d = ImageDraw.Draw(layer, "RGBA")
|
||||
for _ in range(count):
|
||||
a = rnd.uniform(-math.pi * 0.95, -math.pi * 0.05)
|
||||
v = rnd.uniform(0.35, 1.0) * power
|
||||
color = rnd.choice(CONFETTI)
|
||||
spin = rnd.uniform(-8, 8)
|
||||
size = rnd.uniform(10, 22)
|
||||
x = cx + math.cos(a) * v * dt
|
||||
y = cy + math.sin(a) * v * dt + 900 * dt * dt
|
||||
alpha = int(255 * clamp(1.6 - dt / 1.5))
|
||||
if rnd.random() < 0.5:
|
||||
d.ellipse([x - size / 2, y - size / 2, x + size / 2, y + size / 2], fill=color + (alpha,))
|
||||
else:
|
||||
ang = spin * dt
|
||||
pts = [(x + math.cos(ang + k * math.pi / 2) * size, y + math.sin(ang + k * math.pi / 2) * size * 0.5) for k in range(4)]
|
||||
d.polygon(pts, fill=color + (alpha,))
|
||||
|
||||
|
||||
def ring(layer, cx, cy, lt, t0, color=INK, size=300):
|
||||
dt = (lt - t0) / 0.7
|
||||
if 0 <= dt <= 1:
|
||||
r = size * ease_out_cubic(dt)
|
||||
ImageDraw.Draw(layer, "RGBA").ellipse([cx - r, cy - r, cx + r, cy + r], outline=color + (int(255 * (1 - dt)),), width=10)
|
||||
|
||||
|
||||
def ghost(size, alpha=1.0, blink=False):
|
||||
s = size * 3
|
||||
layer = Image.new("RGBA", (s, s), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(layer)
|
||||
body = WHITE + (255,)
|
||||
d.ellipse([s * 0.2, s * 0.1, s * 0.8, s * 0.7], fill=body, outline=INK + (255,), width=14)
|
||||
d.rectangle([s * 0.2, s * 0.4, s * 0.8, s * 0.82], fill=body)
|
||||
d.line([(s * 0.2, s * 0.4), (s * 0.2, s * 0.82)], fill=INK + (255,), width=14)
|
||||
d.line([(s * 0.8, s * 0.4), (s * 0.8, s * 0.82)], fill=INK + (255,), width=14)
|
||||
for k in range(4):
|
||||
cx = s * (0.275 + k * 0.15)
|
||||
d.ellipse([cx - s * 0.075, s * 0.74, cx + s * 0.075, s * 0.9], fill=body, outline=INK + (255,), width=14)
|
||||
d.rectangle([s * 0.215, s * 0.74, s * 0.785, s * 0.82], fill=body)
|
||||
for ex in (0.38, 0.62):
|
||||
if blink:
|
||||
d.line([(s * ex - s * 0.05, s * 0.41), (s * ex + s * 0.05, s * 0.41)], fill=INK + (255,), width=14)
|
||||
else:
|
||||
d.ellipse([s * ex - s * 0.045, s * 0.35, s * ex + s * 0.045, s * 0.47], fill=INK + (255,))
|
||||
d.ellipse([s * 0.46, s * 0.52, s * 0.54, s * 0.6], fill=INK + (255,))
|
||||
img = layer.resize((size, size), Image.Resampling.LANCZOS)
|
||||
if alpha < 1.0:
|
||||
img.putalpha(img.getchannel("A").point(lambda v: int(v * alpha)))
|
||||
return img
|
||||
|
||||
|
||||
def switch(layer, cx, cy, on):
|
||||
d = ImageDraw.Draw(layer, "RGBA")
|
||||
track = tuple(int(WHITE[n] * (1 - on) + MINT[n] * on) for n in range(3))
|
||||
d.rounded_rectangle([cx - 70, cy - 40, cx + 70, cy + 40], radius=40, fill=track + (255,), outline=INK + (255,), width=6)
|
||||
kx = cx - 30 + 60 * on
|
||||
d.ellipse([kx - 28, cy - 28, kx + 28, cy + 28], fill=INK + (255,))
|
||||
|
||||
|
||||
def picture(w, h, c1, c2, radius=40):
|
||||
img = P.Image.new("RGB", (w, h))
|
||||
d = ImageDraw.Draw(img)
|
||||
for i in range(w):
|
||||
k = i / max(1, w - 1)
|
||||
d.line([(i, 0), (i, h)], fill=tuple(int(c1[n] + (c2[n] - c1[n]) * k) for n in range(3)))
|
||||
img = img.convert("RGBA")
|
||||
flower = P.flower(80, (255, 255, 255, 110))
|
||||
for x in range(-10, w - 70, 120):
|
||||
for y in range(-10 + (x // 120 % 2) * 55, h - 70, 110):
|
||||
img.alpha_composite(flower, (x, y))
|
||||
mask = Image.new("L", (w * 2, h * 2), 0)
|
||||
ImageDraw.Draw(mask).rounded_rectangle([0, 0, w * 2 - 1, h * 2 - 1], radius=radius * 2, fill=255)
|
||||
img.putalpha(mask.resize((w, h), Image.Resampling.LANCZOS))
|
||||
d = ImageDraw.Draw(img)
|
||||
d.rounded_rectangle([1, 1, w - 2, h - 2], radius=radius, outline=INK + (255,), width=5)
|
||||
return img
|
||||
|
||||
|
||||
def place(layer, img, cx, cy, scale=1.0, angle=0.0):
|
||||
P.place(layer, img, cx, cy, scale, angle)
|
||||
|
||||
|
||||
def init_assets():
|
||||
if ASSETS:
|
||||
return
|
||||
ASSETS["dots"] = Image.new("RGBA", (W + 160, H + 160), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(ASSETS["dots"])
|
||||
for x in range(0, W + 160, 80):
|
||||
for y in range(0, H + 160, 80):
|
||||
d.ellipse([x - 5, y - 5, x + 5, y + 5], fill=INK + (34,))
|
||||
ASSETS["logo"] = Image.open(P.LOGO).convert("RGBA")
|
||||
ASSETS["flame_lit"] = [WP.render(True, n) for n in range(4)]
|
||||
ASSETS["flame_grey"] = WP.render(False)
|
||||
ASSETS["dark"] = picture(560, 150, (80, 70, 220), (30, 20, 120))
|
||||
ASSETS["light"] = picture(560, 150, (255, 230, 170), (255, 170, 190))
|
||||
ASSETS["mine"] = picture(520, 150, (170, 80, 220), (110, 40, 170))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- scenes
|
||||
|
||||
def scene_intro(layer, lt):
|
||||
k = ease_out_back(lt / 0.9)
|
||||
place(layer, ASSETS["logo"], W / 2, 760, 0.5 * k * (1 + 0.04 * math.sin(lt * 5)), math.sin(lt * 2.4) * 8 + (1 - k) * 360)
|
||||
burst(layer, W / 2, 760, lt, 0.6, seed=4)
|
||||
title(layer, max(0.0, lt - 0.9), "LihonT 2", "Что нового в Luna", y=1230)
|
||||
label(layer, W / 2, 1480, "релиз", pop(lt, 1.8), size=64, fill=YELLOW)
|
||||
|
||||
|
||||
def scene_flame(layer, lt):
|
||||
title(layer, lt, "Живой огонёк", "Виджет серии")
|
||||
phase = int(lt / 0.2) % 4
|
||||
lit = ASSETS["flame_lit"][phase]
|
||||
# four sizes, each popping in and breathing
|
||||
spots = [(250, 800, 0.46, "1×1"), (700, 780, 0.62, "2×2"), (320, 1240, 0.9, "3×3"), (820, 1260, 0.66, "4×4")]
|
||||
for n, (x, y, s, name) in enumerate(spots):
|
||||
k = pop(lt, 0.5 + n * 0.3, 0.6)
|
||||
breathe = 1 + 0.04 * math.sin(lt * 5 + n)
|
||||
flame = lit if n != 1 or lt < 3.0 else ASSETS["flame_grey"]
|
||||
place(layer, flame, x, y + math.sin(lt * 2 + n) * 10, s * k * breathe, math.sin(lt * 3 + n) * 4)
|
||||
label(layer, x, y + 200 * s + 70, name, pop(lt, 0.8 + n * 0.3), size=40, fill=YELLOW if n % 2 else WHITE)
|
||||
ring(layer, x, y, lt, 0.5 + n * 0.3, size=210 * s + 60)
|
||||
rnd = random.Random(8)
|
||||
d = ImageDraw.Draw(layer, "RGBA")
|
||||
for _ in range(26): # sparks drifting up
|
||||
x0, ph, sp = rnd.uniform(80, 1000), rnd.uniform(0, 6), rnd.uniform(0.6, 1.4)
|
||||
y = H - ((lt * 220 * sp + ph * 200) % (H + 100))
|
||||
r = 6 + 6 * math.sin(lt * 4 + ph) ** 2
|
||||
d.ellipse([x0 + math.sin(lt * sp + ph) * 30 - r, y - r, x0 + math.sin(lt * sp + ph) * 30 + r, y + r], fill=CORAL + (170,))
|
||||
label(layer, W / 2, 1620, "Горит оранжевый, пора писать серый", pop(lt, 2.2), size=36, fill=WHITE)
|
||||
|
||||
|
||||
def clock(layer, cx, cy, r, t):
|
||||
d = ImageDraw.Draw(layer, "RGBA")
|
||||
d.ellipse([cx - r + 10, cy - r + 10, cx + r + 10, cy + r + 10], fill=INK + (255,))
|
||||
d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=WHITE + (255,), outline=INK + (255,), width=8)
|
||||
for k in range(12):
|
||||
a = k * math.pi / 6
|
||||
d.line([(cx + math.cos(a) * r * 0.82, cy + math.sin(a) * r * 0.82), (cx + math.cos(a) * r * 0.93, cy + math.sin(a) * r * 0.93)], fill=INK + (255,), width=6)
|
||||
minute = (1 - ease_out_cubic(t / 2.0)) * math.pi * 6 + 0.0 # spins down to 12:00
|
||||
hour = -math.pi / 2 + (1 - ease_out_cubic(t / 2.0)) * math.pi * 1.0
|
||||
d.line([(cx, cy), (cx + math.cos(hour) * r * 0.5, cy + math.sin(hour) * r * 0.5)], fill=INK + (255,), width=14)
|
||||
d.line([(cx, cy), (cx + math.cos(minute - math.pi / 2) * r * 0.76, cy + math.sin(minute - math.pi / 2) * r * 0.76)], fill=CORAL + (255,), width=10)
|
||||
d.ellipse([cx - 14, cy - 14, cx + 14, cy + 14], fill=INK + (255,))
|
||||
|
||||
|
||||
def scene_keeper(layer, lt):
|
||||
title(layer, lt, "Автопродление", "Сам, в нужное время")
|
||||
clock(layer, 540, 640, 170, max(0.0, lt - 0.3))
|
||||
label(layer, 540, 880, "12:00", pop(lt, 1.8), size=72, fill=YELLOW)
|
||||
names = [("Мама", CORAL), ("Друг", SKY), ("Класс", VIOLET), ("Сестра", MINT)]
|
||||
t_flip = 2.4
|
||||
for n, (name, color) in enumerate(names):
|
||||
k = ease_out_back((lt - 0.5 - n * 0.18) / 0.55)
|
||||
side = -1 if n % 2 == 0 else 1
|
||||
x_off = (1 - k) * 900 * side
|
||||
y = 1060 + n * 170
|
||||
sticker(layer, (90 + x_off, y - 70, 990 + x_off, y + 70), WHITE, radius=44)
|
||||
ImageDraw.Draw(layer, "RGBA").ellipse([120 + x_off, y - 50, 220 + x_off, y + 50], fill=color + (255,), outline=INK + (255,), width=6)
|
||||
stroke_text(layer, (250 + x_off, y), name, 46, INK, anchor="lm")
|
||||
t_n = t_flip + n * 0.35
|
||||
flipped = lt > t_n
|
||||
flame = ASSETS["flame_lit"][int(lt / 0.2 + n) % 4] if flipped else ASSETS["flame_grey"]
|
||||
pulse = 1 + (0.5 * max(0.0, 1 - (lt - t_n) * 3) if flipped else 0)
|
||||
place(layer, flame, 880 + x_off, y, 0.22 * pulse)
|
||||
if flipped:
|
||||
ring(layer, 880, y, lt, t_n, color=CORAL, size=120)
|
||||
burst(layer, 540, 640, lt, t_flip, seed=6, count=30, power=700)
|
||||
|
||||
|
||||
def scene_bubbles(layer, lt):
|
||||
title(layer, lt, "Свои пузыри", "Любая картинка вместо фона")
|
||||
items = [
|
||||
(ASSETS["dark"], 100, 560, "Привет! Картинка", WHITE, 0.6, -1),
|
||||
(ASSETS["mine"], 460, 760, "Видно всё", WHITE, 1.3, 1),
|
||||
(ASSETS["light"], 100, 960, "На светлой чёрный", INK, 2.0, -1),
|
||||
(ASSETS["dark"], 100, 1160, "На тёмной белый", WHITE, 2.7, -1),
|
||||
]
|
||||
for img, x, y, text, ink, t0, side in items:
|
||||
k = ease_out_back((lt - t0) / 0.5)
|
||||
if k <= 0.02:
|
||||
if t0 - 0.5 < lt < t0: # three typing dots before the message arrives
|
||||
for i in range(3):
|
||||
r = 12 + 8 * max(0.0, math.sin(lt * 10 - i * 0.9))
|
||||
cx = (x + 60 if side < 0 else 960 - 60) + i * 40 * (1 if side < 0 else -1)
|
||||
ImageDraw.Draw(layer, "RGBA").ellipse([cx - r, y + 75 - r, cx + r, y + 75 + r], fill=INK + (255,))
|
||||
continue
|
||||
scaled = img.resize((max(1, int(img.width * k)), max(1, int(img.height * k))), Image.Resampling.BILINEAR)
|
||||
cx = x + img.width / 2
|
||||
layer.alpha_composite(scaled, (int(cx - scaled.width / 2), int(y + 75 - scaled.height / 2 + (1 - k) * 80)))
|
||||
if k > 0.8:
|
||||
stroke_text(layer, (x + 44, y + 75), text, 46, ink, anchor="lm")
|
||||
# a colour palette that recolours the last message's text
|
||||
colors = [WHITE, YELLOW, MINT, PINK, SKY]
|
||||
for i, c in enumerate(colors):
|
||||
k = pop(lt, 3.4 + i * 0.12)
|
||||
cx = 220 + i * 150
|
||||
r = 46 * clamp(k, 0, 1.2)
|
||||
d = ImageDraw.Draw(layer, "RGBA")
|
||||
d.ellipse([cx - r, 1420 - r, cx + r, 1420 + r], fill=c + (255,), outline=INK + (255,), width=6)
|
||||
pick = int(max(0.0, lt - 4.0) / 0.35) % len(colors) if lt > 4.0 else 0
|
||||
if lt > 3.4:
|
||||
ring(layer, 220 + pick * 150, 1420, lt, 4.0 + int(max(0.0, lt - 4.0) / 0.35) * 0.35, color=INK, size=90)
|
||||
label(layer, 540, 1590, "Цвет текста выбираете сами", pop(lt, 3.6), size=36, fill=YELLOW)
|
||||
label(layer, 540, 1700, "Для каждого человека и для незнакомцев", pop(lt, 4.0), size=32)
|
||||
|
||||
|
||||
def scene_ghost(layer, lt):
|
||||
title(layer, lt, "Режим призрака", "Смотрите и читайте незаметно")
|
||||
fade = 0.55 + 0.45 * math.sin(lt * 2.0) # fades in and out like a real ghost
|
||||
bob = math.sin(lt * 2.2) * 22
|
||||
blink = (lt % 2.4) > 2.25
|
||||
for i in range(3): # trail
|
||||
place(layer, ghost(300, alpha=0.18 * fade, blink=blink), W / 2 - 60 * (i + 1) * math.sin(lt), 760 + bob + 40 * (i + 1), 1.0)
|
||||
place(layer, ghost(360, alpha=fade, blink=blink), W / 2, 760 + bob, ease_out_back(lt / 0.8))
|
||||
sticker(layer, (90, 1060, 990, 1260), WHITE, radius=48)
|
||||
stroke_text(layer, (150, 1120), "Истории", 50, INK, anchor="lm")
|
||||
stroke_text(layer, (150, 1200), "Автор не увидит вас в зрителях", 32, INK, bold=False, anchor="lm")
|
||||
sticker(layer, (90, 1300, 990, 1500), WHITE, radius=48)
|
||||
stroke_text(layer, (150, 1360), "Чаты", 50, INK, anchor="lm")
|
||||
stroke_text(layer, (150, 1440), "«Прочитано» не отправляется", 32, INK, bold=False, anchor="lm")
|
||||
for y, t0 in ((1160, 1.2), (1400, 1.9)):
|
||||
on = ease_out_cubic((lt - t0) / 0.4)
|
||||
switch(layer, 860, y, on)
|
||||
if on > 0.9:
|
||||
ring(layer, 860, y, lt, t0 + 0.35, color=MINT, size=110)
|
||||
label(layer, W / 2, 1650, "Включается в «Приватность»", pop(lt, 2.6), size=36, fill=YELLOW)
|
||||
|
||||
|
||||
def scene_photos(layer, lt):
|
||||
title(layer, lt, "До 9 фото", "в одном комментарии")
|
||||
palette = [(CORAL, YELLOW), (SKY, VIOLET), (MINT, SKY)]
|
||||
rnd = random.Random(2)
|
||||
for n in range(9):
|
||||
row, col = divmod(n, 3)
|
||||
t0 = 0.5 + n * 0.22
|
||||
k = clamp((lt - t0) / 0.7)
|
||||
if k <= 0:
|
||||
continue
|
||||
c1, c2 = palette[(row + col) % 3]
|
||||
tile = picture(250, 250, c1, c2, radius=40)
|
||||
tx, ty = 240 + col * 300, 660 + row * 300
|
||||
edge = rnd.choice([(-300, -300), (W + 300, -200), (-300, H - 400), (W + 300, H - 300)])
|
||||
e = ease_out_cubic(k)
|
||||
x = edge[0] + (tx - edge[0]) * e
|
||||
y = edge[1] + (ty - edge[1]) * e - math.sin(k * math.pi) * 200
|
||||
place(layer, tile, x, y, 0.6 + 0.4 * e, (1 - e) * 360 * (1 if n % 2 else -1))
|
||||
if k >= 1 and lt - t0 - 0.7 < 0.5:
|
||||
ring(layer, tx, ty, lt, t0 + 0.7, color=INK, size=160)
|
||||
sticker(layer, (80, 1600, 1000, 1760), WHITE, radius=80)
|
||||
stroke_text(layer, (150, 1680), "Написать комментарий…", 40, INK, bold=False, anchor="lm")
|
||||
count = min(9, int(max(0.0, lt - 0.5) / 0.22) + 1)
|
||||
label(layer, 860, 1680, "%d/9" % count, 1.0, size=40, fill=YELLOW)
|
||||
|
||||
|
||||
def scene_plugins(layer, lt):
|
||||
title(layer, lt, "Плагины .ltp", "Свои дополнения без кода")
|
||||
k = ease_out_back((lt - 0.2) / 0.8)
|
||||
place(layer, ASSETS["logo"], 540, 760, 0.0001)
|
||||
# the file card
|
||||
x0, y0, x1, y1 = 540 - 190 * k, 760 - 240 * k, 540 + 190 * k, 760 + 240 * k
|
||||
sticker(layer, (x0, y0, x1, y1), WHITE, radius=50)
|
||||
stroke_text(layer, (540, 740), ".ltp", int(120 * k) + 1, VIOLET, outline=INK, width=6)
|
||||
stroke_text(layer, (540, 860), "plugin.json", int(38 * k) + 1, INK, bold=False)
|
||||
# rule blocks fly in and snap to the card
|
||||
blocks = [("Права", CORAL, (180, 480), 1.0), ("Защитник", MINT, (900, 520), 1.4), ("Откат", SKY, (170, 1060), 1.8), ("Журнал", PINK, (910, 1040), 2.2)]
|
||||
for text, color, (bx, by), t0 in blocks:
|
||||
e = ease_out_cubic((lt - t0) / 0.6)
|
||||
if e <= 0:
|
||||
continue
|
||||
sx, sy = (bx - 600 if bx < 540 else bx + 600), by - 300
|
||||
x = sx + (bx - sx) * e + math.sin(lt * 2 + bx) * 6 * e
|
||||
y = sy + (by - sy) * e
|
||||
label(layer, x, y, text, 1.0, size=46, fill=color)
|
||||
if lt - t0 > 0.6 and lt - t0 < 0.9:
|
||||
ring(layer, bx, by, lt, t0 + 0.6, color=INK, size=120)
|
||||
# shield with a check that draws itself
|
||||
sh = pop(lt, 2.6)
|
||||
if sh > 0.02:
|
||||
cx, cy = 540, 1280
|
||||
d = ImageDraw.Draw(layer, "RGBA")
|
||||
pts = [(cx - 90 * sh, cy - 100 * sh), (cx + 90 * sh, cy - 100 * sh), (cx + 90 * sh, cy + 10 * sh), (cx, cy + 110 * sh), (cx - 90 * sh, cy + 10 * sh)]
|
||||
d.polygon([(x + 8, y + 8) for x, y in pts], fill=INK + (255,))
|
||||
d.polygon(pts, fill=MINT + (255,), outline=INK + (255,))
|
||||
d.line(pts + [pts[0]], fill=INK + (255,), width=8, joint="curve")
|
||||
prog = clamp((lt - 3.0) / 0.5)
|
||||
tick = [(cx - 40, cy - 5), (cx - 10, cy + 30), (cx + 45, cy - 40)]
|
||||
if prog > 0:
|
||||
seg = prog * 2
|
||||
d.line(tick[:2] if seg < 1 else tick[:2], fill=INK + (255,), width=14)
|
||||
if seg > 1:
|
||||
d.line([tick[1], (tick[1][0] + (tick[2][0] - tick[1][0]) * (seg - 1), tick[1][1] + (tick[2][1] - tick[1][1]) * (seg - 1))], fill=INK + (255,), width=14)
|
||||
label(layer, 540, 1490, "Интернет только с вашего согласия", pop(lt, 3.2), size=36, fill=WHITE)
|
||||
label(layer, 540, 1600, "Проверка перед установкой", pop(lt, 3.6), size=36, fill=YELLOW)
|
||||
label(layer, 540, 1710, "Лицензия и метки ИИ на виду", pop(lt, 4.0), size=34, fill=WHITE)
|
||||
|
||||
|
||||
def scene_shapes(layer, lt):
|
||||
title(layer, lt, "Форма аватарок", "Выбираете сами")
|
||||
kinds = P.SHAPE_KINDS
|
||||
colors = [VIOLET, PINK, MINT, YELLOW, CORAL, SKY]
|
||||
# the big avatar morphs through all the shapes
|
||||
idx = int(lt / 0.7) % len(kinds)
|
||||
part = (lt / 0.7) % 1.0
|
||||
squash = 1 + 0.12 * math.sin(part * math.pi)
|
||||
big = P.shape_silhouette(kinds[idx], 380, colors[idx])
|
||||
outline = P.shape_silhouette(kinds[idx], 400, INK)
|
||||
place(layer, outline, 540 + 8, 720 + 8, squash)
|
||||
place(layer, big, 540, 720, squash * 0.98, math.sin(lt * 2) * 5)
|
||||
for n, kind in enumerate(kinds):
|
||||
k = pop(lt, 0.6 + n * 0.18)
|
||||
place(layer, P.shape_silhouette(kind, 150, colors[n]), 140 + n * 160, 1130 + math.sin(lt * 4 + n) * 12, k * (1.15 if n == idx else 1.0))
|
||||
label(layer, W / 2, 1330, "Круг · цветок · сердце · треугольник", pop(lt, 1.8), size=34)
|
||||
label(layer, W / 2, 1450, "Её видят все, у кого есть мод", pop(lt, 2.3), size=36, fill=YELLOW)
|
||||
label(layer, W / 2, 1570, "Без мода — обычный круг", pop(lt, 2.8), size=34)
|
||||
|
||||
|
||||
def scene_settings(layer, lt):
|
||||
title(layer, lt, "Material 3", "Все настройки в одном стиле")
|
||||
rows = [("Призрак: истории", CORAL), ("Призрак: сообщения", SKY), ("Свои пузыри", VIOLET), ("Несколько фото", MINT), ("Меню сохранения", YELLOW)]
|
||||
for n, (name, color) in enumerate(rows):
|
||||
k = ease_out_back((lt - 0.4 - n * 0.16) / 0.5)
|
||||
x_off = (1 - k) * (900 if n % 2 else -900)
|
||||
y = 560 + n * 215
|
||||
sticker(layer, (80 + x_off, y - 85, 1000 + x_off, y + 85), WHITE, radius=48)
|
||||
ImageDraw.Draw(layer, "RGBA").ellipse([120 + x_off, y - 45, 210 + x_off, y + 45], fill=color + (255,), outline=INK + (255,), width=6)
|
||||
stroke_text(layer, (250 + x_off, y), name, 46, INK, anchor="lm")
|
||||
on = ease_out_cubic((lt - 1.6 - n * 0.4) / 0.35)
|
||||
switch(layer, 880 + x_off, y, on)
|
||||
if on > 0.95 and lt - (1.6 + n * 0.4 + 0.35) < 0.5:
|
||||
ring(layer, 880, y, lt, 1.6 + n * 0.4 + 0.3, color=MINT, size=100)
|
||||
label(layer, W / 2, 1750, "И палитра, и окна, и значки", pop(lt, 3.6), size=36, fill=YELLOW)
|
||||
|
||||
|
||||
def scene_outro(layer, lt):
|
||||
k = ease_out_back(lt / 0.8)
|
||||
place(layer, ASSETS["logo"], W / 2, 620, 0.46 * k * (1 + 0.04 * math.sin(lt * 5)), math.sin(lt * 2.4) * 8 + (1 - k) * 300)
|
||||
burst(layer, W / 2, 620, lt, 0.5, seed=9, count=60, power=1000)
|
||||
title(layer, max(0.0, lt - 0.5), "LihonT 2 · Luna", "Открытый код · лицензия VCBFU v2", y=1000)
|
||||
bounce = lambda t0: abs(math.sin((lt - t0) * 3)) * 14 if lt > t0 else 0 # noqa: E731
|
||||
label(layer, W / 2, 1290 - bounce(1.2), "git.lihont.space", pop(lt, 1.2), size=60, fill=YELLOW)
|
||||
label(layer, W / 2, 1440 - bounce(1.5), "Telegram · @lihont", pop(lt, 1.5), size=60, fill=WHITE)
|
||||
|
||||
|
||||
SCENE_DRAW = {name: globals()["scene_" + name] for name, _, _, _ in SCENES}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- frames
|
||||
|
||||
def frame_at(t: float) -> Image.Image:
|
||||
init_assets()
|
||||
index = 0
|
||||
for n, (name, start, end, color) in enumerate(SCENES):
|
||||
if t >= start:
|
||||
index = n
|
||||
name, start, end, color = SCENES[index]
|
||||
img = Image.new("RGBA", (W, H), color + (255,))
|
||||
if index > 0 and t - start < WIPE: # the previous colour is still there; the new one opens as a circle
|
||||
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)
|
||||
ox, oy = int(t * 30) % 80, int(t * 18) % 80
|
||||
img.alpha_composite(ASSETS["dots"], (-ox, -oy))
|
||||
layer = Image.new("RGBA", (W, H), (0, 0, 0, 0))
|
||||
SCENE_DRAW[name](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, help="render one frame at this time (seconds) and stop")
|
||||
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 / ("still2_%.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:]))
|
||||
ffmpeg = shutil.which("ffmpeg") or "ffmpeg"
|
||||
command = [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=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()
|
||||
178
scripts/make_plugin_howto.py
Normal file
178
scripts/make_plugin_howto.py
Normal file
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Draws src/brand/plugin_howto.svg: a light looping animation "your own plugin in four steps" (SMIL, no scripts).
|
||||
|
||||
python scripts/make_plugin_howto.py [out.svg]
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / "src" / "brand" / "plugin_howto.svg"
|
||||
|
||||
W, H = 800, 450
|
||||
SCENE = 4.0 # seconds per step
|
||||
STEPS = 4
|
||||
TOTAL = SCENE * STEPS
|
||||
|
||||
BG, CARD, EDGE, TEXT, DIM = "#1E1B16", "#2B2620", "#4E4840", "#EAE1D9", "#9A9084"
|
||||
GOLD, ORANGE, GREEN = "#F0BF6D", "#FFB27A", "#9ED69A"
|
||||
MONO = "ui-monospace, Consolas, 'Courier New', monospace"
|
||||
SANS = "system-ui, 'Segoe UI', Roboto, sans-serif"
|
||||
|
||||
|
||||
def frac(t: float) -> str:
|
||||
return "%.4f" % min(max(t / TOTAL, 0.0), 1.0)
|
||||
|
||||
|
||||
def window(i: int):
|
||||
"""Opacity of scene i: fades in, stays, fades out, then sleeps until the loop restarts."""
|
||||
a, b = i * SCENE, (i + 1) * SCENE
|
||||
times = [0, a, a + 0.4, b - 0.4, b, TOTAL]
|
||||
values = [0, 0, 1, 1, 0, 0]
|
||||
pairs = []
|
||||
for t, v in zip(times, values):
|
||||
pairs.append((frac(t), v))
|
||||
# key times must not decrease; equal neighbours are fine
|
||||
return ";".join(p[0] for p in pairs), ";".join(str(p[1]) for p in pairs)
|
||||
|
||||
|
||||
def appear(start: float, duration: float = 0.01) -> str:
|
||||
"""Opacity 0 until `start` seconds into the step, then 1 until the step ends (scene fade hides the rest)."""
|
||||
return ('<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;%s;%s;1" dur="%gs" repeatCount="indefinite"/>'
|
||||
% (frac(start), frac(start + duration), TOTAL))
|
||||
|
||||
|
||||
def type_line(x: float, y: float, width: float, start: float, seconds: float, content: str, fill: str, size: int = 17,
|
||||
font: str = MONO, uid: str = "") -> str:
|
||||
"""A line that is typed: a clip rectangle grows over it."""
|
||||
cid = "c" + uid
|
||||
return (
|
||||
'<clipPath id="%s"><rect x="%g" y="%g" width="0" height="30">'
|
||||
'<animate attributeName="width" values="0;0;%g;%g;0" keyTimes="0;%s;%s;%s;1" dur="%gs" repeatCount="indefinite"/>'
|
||||
'</rect></clipPath>'
|
||||
'<text x="%g" y="%g" font-family="%s" font-size="%d" fill="%s" clip-path="url(#%s)" xml:space="preserve">%s</text>'
|
||||
% (cid, x - 2, y - 22, width, width, frac(start), frac(start + seconds), frac(TOTAL - 0.2), TOTAL,
|
||||
x, y, font, size, fill, cid, content))
|
||||
|
||||
|
||||
def scene(i: int, body: str) -> str:
|
||||
kt, vals = window(i)
|
||||
return ('<g opacity="0"><animate attributeName="opacity" values="%s" keyTimes="%s" dur="%gs" repeatCount="indefinite"/>%s</g>'
|
||||
% (vals, kt, TOTAL, body))
|
||||
|
||||
|
||||
def caption(text: str, sub: str) -> str:
|
||||
return ('<text x="400" y="395" text-anchor="middle" font-family="%s" font-size="26" font-weight="600" fill="%s">%s</text>'
|
||||
'<text x="400" y="423" text-anchor="middle" font-family="%s" font-size="16" fill="%s">%s</text>'
|
||||
% (SANS, TEXT, text, SANS, DIM, sub))
|
||||
|
||||
|
||||
def editor_scene() -> str:
|
||||
s = SCENE * 0
|
||||
body = ['<rect x="80" y="86" width="640" height="236" rx="18" fill="%s" stroke="%s" stroke-width="2"/>' % (CARD, EDGE)]
|
||||
for k, color in enumerate(("#FF6B6B", GOLD, GREEN)):
|
||||
body.append('<circle cx="%d" cy="108" r="6" fill="%s"/>' % (108 + 22 * k, color))
|
||||
body.append('<text x="400" y="113" text-anchor="middle" font-family="%s" font-size="14" fill="%s">night.py</text>' % (SANS, DIM))
|
||||
lines = [
|
||||
(150, 'from lihont_ltp import *', 0.5, ORANGE),
|
||||
(186, 'plugin = Plugin("Тихая ночь", author="Вася")', 1.2, TEXT),
|
||||
(222, 'plugin.video(night & hashtag("fyp"), hide)', 2.2, TEXT),
|
||||
(258, 'plugin.save()', 3.0, GREEN),
|
||||
]
|
||||
for n, (y, text, start, fill) in enumerate(lines):
|
||||
body.append(type_line(112, y + 14, 560, s + start, 0.7 if n != 2 else 0.8, text, fill, uid="a%d" % n))
|
||||
body.append(caption("1. Напиши правило, как предложение", "Видео с #fyp ночью скрыть: три строки на Python"))
|
||||
return scene(0, "".join(body))
|
||||
|
||||
|
||||
def terminal_scene() -> str:
|
||||
s = SCENE * 1
|
||||
body = ['<rect x="80" y="86" width="640" height="236" rx="18" fill="#17140F" stroke="%s" stroke-width="2"/>' % EDGE]
|
||||
body.append(type_line(110, 130, 400, s + 0.4, 0.8, "$ python night.py", TEXT, uid="b0"))
|
||||
rows = [
|
||||
(170, "Защитник: Обратите внимание", GOLD, 1.5),
|
||||
(200, "• Скрывает видео из ленты по условиям правил", DIM, 1.9),
|
||||
(230, "Плагин не может: читать сообщения и пароли, запускать код.", DIM, 2.3),
|
||||
(272, "Готово: vasya.tihaya-noch.ltp", GREEN, 2.8),
|
||||
]
|
||||
for y, text, fill, start in rows:
|
||||
body.append('<text x="110" y="%d" font-family="%s" font-size="16" fill="%s" opacity="0" xml:space="preserve">%s%s</text>'
|
||||
% (y, MONO, fill, text, appear(s + start)))
|
||||
# the finished file pops up
|
||||
body.append('<g transform="translate(640 250)" opacity="0">%s'
|
||||
'<rect x="-26" y="-34" width="52" height="68" rx="8" fill="%s"/><text x="0" y="8" text-anchor="middle" '
|
||||
'font-family="%s" font-size="16" font-weight="700" fill="#2B2620">.ltp</text></g>'
|
||||
% (appear(s + 3.0, 0.2), GOLD, SANS))
|
||||
body.append(caption("2. Запусти: защитник покажет всё", "Что делает каждое правило и насколько ему можно доверять"))
|
||||
return scene(1, "".join(body))
|
||||
|
||||
|
||||
def phone_scene() -> str:
|
||||
s = SCENE * 2
|
||||
body = []
|
||||
# laptop
|
||||
body.append('<rect x="90" y="150" width="230" height="140" rx="12" fill="%s" stroke="%s" stroke-width="2"/>' % (CARD, EDGE))
|
||||
body.append('<rect x="70" y="296" width="270" height="12" rx="6" fill="%s"/>' % EDGE)
|
||||
body.append('<text x="205" y="212" text-anchor="middle" font-family="%s" font-size="15" fill="%s">ltp phone</text>' % (MONO, TEXT))
|
||||
body.append('<text x="205" y="238" text-anchor="middle" font-family="%s" font-size="13" fill="%s">vasya.tihaya-noch.ltp</text>' % (MONO, GOLD))
|
||||
# cable
|
||||
body.append('<path d="M320 220 C 400 220 430 220 500 220" stroke="%s" stroke-width="4" fill="none" stroke-dasharray="6 6"/>' % EDGE)
|
||||
# phone
|
||||
body.append('<rect x="500" y="110" width="130" height="236" rx="22" fill="%s" stroke="%s" stroke-width="3"/>' % (CARD, EDGE))
|
||||
body.append('<rect x="515" y="130" width="100" height="196" rx="10" fill="#17140F"/>')
|
||||
body.append('<text x="565" y="236" text-anchor="middle" font-family="%s" font-size="13" fill="%s">Download/ltp</text>' % (SANS, DIM))
|
||||
# the file travels along the cable, twice
|
||||
body.append('<g><rect x="-14" y="-18" width="28" height="36" rx="5" fill="%s"/>'
|
||||
'<animateMotion dur="%gs" repeatCount="indefinite" keyPoints="0;0;1;1" keyTimes="0;%s;%s;1" calcMode="linear" '
|
||||
'path="M330 220 L 540 220"/></g>' % (GOLD, TOTAL, frac(s + 0.6), frac(s + 2.4)))
|
||||
body.append(caption("3. Отправь на телефон по проводу", "Команда ltp phone кладёт файл в Download/ltp"))
|
||||
return scene(2, "".join(body))
|
||||
|
||||
|
||||
def install_scene() -> str:
|
||||
s = SCENE * 3
|
||||
body = ['<rect x="250" y="60" width="300" height="320" rx="30" fill="%s" stroke="%s" stroke-width="3"/>' % (CARD, EDGE)]
|
||||
body.append('<rect x="272" y="150" width="256" height="150" rx="20" fill="#3A342C"/>')
|
||||
body.append('<text x="288" y="182" font-family="%s" font-size="16" font-weight="700" fill="%s">Установить «Тихая ночь»?</text>' % (SANS, TEXT))
|
||||
body.append('<text x="288" y="208" font-family="%s" font-size="12" fill="%s">Защитник: Обратите внимание</text>' % (SANS, GOLD))
|
||||
body.append('<text x="288" y="228" font-family="%s" font-size="12" fill="%s">Права: скрывать видео по правилам</text>' % (SANS, DIM))
|
||||
body.append('<text x="410" y="284" font-family="%s" font-size="14" fill="%s">Отмена</text>' % (SANS, DIM))
|
||||
body.append('<g><rect x="468" y="266" width="52" height="26" rx="13" fill="%s"/>'
|
||||
'<text x="494" y="284" text-anchor="middle" font-family="%s" font-size="13" font-weight="700" fill="#2B2620">Ставь</text>'
|
||||
'<animate attributeName="opacity" values="1;1;0.55;1;1" keyTimes="0;%s;%s;%s;1" dur="%gs" repeatCount="indefinite"/></g>'
|
||||
% (GOLD, SANS, frac(s + 1.5), frac(s + 1.8), frac(s + 2.1), TOTAL))
|
||||
body.append('<g opacity="0">%s<rect x="276" y="330" width="248" height="34" rx="17" fill="%s"/>'
|
||||
'<text x="400" y="352" text-anchor="middle" font-family="%s" font-size="14" font-weight="700" fill="#2B2620">Плагин включён ✓</text></g>'
|
||||
% (appear(s + 2.4, 0.2), GREEN, SANS))
|
||||
body.append(caption("4. Установи и включи", "Перед установкой видно права, правила и вердикт защитника"))
|
||||
return scene(3, "".join(body))
|
||||
|
||||
|
||||
def dots() -> str:
|
||||
out = []
|
||||
for i in range(STEPS):
|
||||
a, b = i * SCENE, (i + 1) * SCENE
|
||||
out.append('<circle cx="%g" cy="46" r="7" fill="%s">'
|
||||
'<animate attributeName="fill" values="%s;%s;%s;%s;%s" keyTimes="0;%s;%s;%s;1" dur="%gs" repeatCount="indefinite"/>'
|
||||
'</circle>' % (370 + 20 * i, EDGE, EDGE, EDGE, GOLD, EDGE, EDGE, frac(a), frac(a + 0.01), frac(b), TOTAL))
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def build() -> str:
|
||||
parts = [
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %d %d" width="%d" height="%d" role="img" '
|
||||
'aria-label="Как создать свой плагин для LihonT за четыре шага">' % (W, H, W, H),
|
||||
'<rect width="%d" height="%d" rx="28" fill="%s"/>' % (W, H, BG),
|
||||
'<text x="400" y="52" text-anchor="middle" font-family="%s" font-size="0"> </text>' % SANS,
|
||||
'<text x="40" y="52" font-family="%s" font-size="22" font-weight="700" fill="%s">Свой плагин для LihonT</text>' % (SANS, GOLD),
|
||||
dots(),
|
||||
editor_scene(), terminal_scene(), phone_scene(), install_scene(),
|
||||
'</svg>',
|
||||
]
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
OUT.write_text(build(), encoding="utf-8", newline="\n")
|
||||
print("%s %d bytes" % (OUT, OUT.stat().st_size))
|
||||
@@ -29,6 +29,9 @@ FLAME_HEART = (0xFF, 0xC5, 0x3D, 255)
|
||||
COLD = (0x8E, 0x93, 0x99, 255) # FlowerArt.COLD: the flame that is not lit
|
||||
COLD_HEART = (0xC7, 0xCB, 0xD0, 255)
|
||||
SAMPLE = "7"
|
||||
# FlowerArt.SWAY and FlowerArt.HEART: how far the flame stretches and leans, and how its heart pulses, per frame
|
||||
SWAY = [(1.00, 0.0), (1.06, 0.07), (0.97, 0.0), (1.04, -0.07)]
|
||||
HEART = [1.00, 1.10, 0.92, 1.06]
|
||||
SCALE = 4 # supersampling
|
||||
PIXELS = 512
|
||||
|
||||
@@ -70,7 +73,7 @@ def flatten(commands, place):
|
||||
return points
|
||||
|
||||
|
||||
def render(lit: bool = True) -> Image.Image:
|
||||
def render(lit: bool = True, phase: int = 0) -> Image.Image:
|
||||
flame_color, heart_color = (FLAME, FLAME_HEART) if lit else (COLD, COLD_HEART)
|
||||
size = PIXELS * SCALE
|
||||
k = size / SIDE
|
||||
@@ -94,14 +97,22 @@ def render(lit: bool = True) -> Image.Image:
|
||||
top = SIDE * 0.10
|
||||
scale = flame / 24.0
|
||||
|
||||
def place(point):
|
||||
return ((left + point[0] * scale) * k, (top + point[1] * scale) * k)
|
||||
stretch, lean = SWAY[phase % 4]
|
||||
pulse = HEART[phase % 4] if lit else 1.0
|
||||
|
||||
def place(point, around=None):
|
||||
x, y = point
|
||||
if around is not None: # the heart pulses around its own base
|
||||
x, y = around[0] + (x - around[0]) * pulse, around[1] + (y - around[1]) * pulse
|
||||
dx, dy = x - 12, (y - 22.5) * stretch # the flame sways around its base (12, 22.5)
|
||||
x, y = 12 + dx + lean * dy, 22.5 + dy
|
||||
return ((left + x * scale) * k, (top + y * scale) * k)
|
||||
|
||||
outline = flatten(OUTER, place)
|
||||
if max(abs(a - b) for a, b in zip(FLOWER[:3], flame_color[:3])) < 110: # FlowerArt.MIN_CONTRAST
|
||||
draw.line(outline + [outline[0]], fill=INK, width=int(1.5 * scale * k * 2), joint="curve")
|
||||
draw.polygon(outline, fill=flame_color)
|
||||
draw.polygon(flatten(INNER, place), fill=heart_color)
|
||||
draw.polygon(flatten(INNER, lambda pt: place(pt, (12, 20.3))), fill=heart_color)
|
||||
|
||||
font = ImageFont.truetype(r"C:\Windows\Fonts\arialbd.ttf", int(SIDE * 0.32 * k))
|
||||
draw.text((middle * k, SIDE * 0.735 * k), SAMPLE, font=font, fill=INK, anchor="ms")
|
||||
|
||||
@@ -20,7 +20,7 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
os.chdir(ROOT)
|
||||
|
||||
from lihont import dexpatch, manifest as manifest_module # noqa: E402
|
||||
from lihont import dexpatch, manifest as manifest_module, portmap # noqa: E402
|
||||
from lihont.apkzip import Apk # noqa: E402
|
||||
from lihont.axml import Axml # noqa: E402
|
||||
from lihont.toolchain import Toolchain # noqa: E402
|
||||
@@ -48,6 +48,8 @@ def main() -> None:
|
||||
parser.add_argument("built", help="an APK built by lihont.upgrade")
|
||||
parser.add_argument("-o", "--out", required=True)
|
||||
parser.add_argument("--work", default="work/quick")
|
||||
parser.add_argument("--java", default="src/lihont/two",
|
||||
help="the runtime sources; give the tree of the commit an older APK was built from")
|
||||
args = parser.parse_args()
|
||||
|
||||
source, output, room = Path(args.built).resolve(), Path(args.out).resolve(), Path(args.work).resolve()
|
||||
@@ -58,7 +60,9 @@ def main() -> None:
|
||||
apk = Apk(str(source))
|
||||
try:
|
||||
api = manifest_module.min_sdk(Axml.parse(apk.read("AndroidManifest.xml")))
|
||||
runtime = Path(tools.compile_dex("src/lihont/two", str(room / "runtime"), api)).read_bytes()
|
||||
# with LIHONT_PORT_MAP set the runtime is compiled from a copy that names TikTok's classes and ids of that version
|
||||
sources = portmap.stage_java(args.java, str(room / "java-src"))
|
||||
runtime = Path(tools.compile_dex(sources, str(room / "runtime"), api)).read_bytes()
|
||||
|
||||
target = runtime_dex_of(apk)
|
||||
if target is not None:
|
||||
|
||||
36
src/brand/logo_note_flower_gold.svg
Normal file
36
src/brand/logo_note_flower_gold.svg
Normal file
@@ -0,0 +1,36 @@
|
||||
<svg viewBox="0 0 512 512" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- The gold badge: the same flower as logo_note_flower.svg (central disk, eight petals) in gold, with the same note.
|
||||
Colours follow the user's gold note: warm yellow #F4CF65 and dark amber #8C5807. -->
|
||||
<defs>
|
||||
<linearGradient id="gold" gradientUnits="userSpaceOnUse" x1="90" y1="40" x2="430" y2="480">
|
||||
<stop offset="0" stop-color="#FBE58E"/>
|
||||
<stop offset="0.55" stop-color="#F4CF65"/>
|
||||
<stop offset="1" stop-color="#E2B13C"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<g fill="url(#gold)">
|
||||
<circle cx="256" cy="256" r="168"/>
|
||||
<circle cx="393.47" cy="312.94" r="91.2"/>
|
||||
<circle cx="312.94" cy="393.47" r="91.2"/>
|
||||
<circle cx="199.06" cy="393.47" r="91.2"/>
|
||||
<circle cx="118.53" cy="312.94" r="91.2"/>
|
||||
<circle cx="118.53" cy="199.06" r="91.2"/>
|
||||
<circle cx="199.06" cy="118.53" r="91.2"/>
|
||||
<circle cx="312.94" cy="118.53" r="91.2"/>
|
||||
<circle cx="393.47" cy="199.06" r="91.2"/>
|
||||
</g>
|
||||
|
||||
<g fill="#8C5807" transform="translate(256 256) scale(0.95) translate(-260 -254)">
|
||||
<ellipse cx="205" cy="345" rx="65" ry="48" transform="rotate(-20 205 345)"/>
|
||||
<rect x="250" y="115" width="28" height="230" rx="14"/>
|
||||
<path d="
|
||||
M 264 115
|
||||
C 300 115 365 140 375 205
|
||||
C 380 238 358 265 338 270
|
||||
C 320 274 308 258 316 242
|
||||
C 328 220 338 195 330 175
|
||||
C 320 152 288 145 264 145
|
||||
Z
|
||||
"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
BIN
src/brand/logo_note_flower_gold_1024.png
Normal file
BIN
src/brand/logo_note_flower_gold_1024.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 328 KiB |
10
src/brand/plugin_howto.svg
Normal file
10
src/brand/plugin_howto.svg
Normal file
@@ -0,0 +1,10 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 450" width="800" height="450" role="img" aria-label="Как создать свой плагин для LihonT за четыре шага">
|
||||
<rect width="800" height="450" rx="28" fill="#1E1B16"/>
|
||||
<text x="400" y="52" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="0"> </text>
|
||||
<text x="40" y="52" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="22" font-weight="700" fill="#F0BF6D">Свой плагин для LihonT</text>
|
||||
<circle cx="370" cy="46" r="7" fill="#4E4840"><animate attributeName="fill" values="#4E4840;#4E4840;#F0BF6D;#4E4840;#4E4840" keyTimes="0;0.0000;0.0006;0.2500;1" dur="16s" repeatCount="indefinite"/></circle><circle cx="390" cy="46" r="7" fill="#4E4840"><animate attributeName="fill" values="#4E4840;#4E4840;#F0BF6D;#4E4840;#4E4840" keyTimes="0;0.2500;0.2506;0.5000;1" dur="16s" repeatCount="indefinite"/></circle><circle cx="410" cy="46" r="7" fill="#4E4840"><animate attributeName="fill" values="#4E4840;#4E4840;#F0BF6D;#4E4840;#4E4840" keyTimes="0;0.5000;0.5006;0.7500;1" dur="16s" repeatCount="indefinite"/></circle><circle cx="430" cy="46" r="7" fill="#4E4840"><animate attributeName="fill" values="#4E4840;#4E4840;#F0BF6D;#4E4840;#4E4840" keyTimes="0;0.7500;0.7506;1.0000;1" dur="16s" repeatCount="indefinite"/></circle>
|
||||
<g opacity="0"><animate attributeName="opacity" values="0;0;1;1;0;0" keyTimes="0.0000;0.0000;0.0250;0.2250;0.2500;1.0000" dur="16s" repeatCount="indefinite"/><rect x="80" y="86" width="640" height="236" rx="18" fill="#2B2620" stroke="#4E4840" stroke-width="2"/><circle cx="108" cy="108" r="6" fill="#FF6B6B"/><circle cx="130" cy="108" r="6" fill="#F0BF6D"/><circle cx="152" cy="108" r="6" fill="#9ED69A"/><text x="400" y="113" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="14" fill="#9A9084">night.py</text><clipPath id="ca0"><rect x="110" y="142" width="0" height="30"><animate attributeName="width" values="0;0;560;560;0" keyTimes="0;0.0312;0.0750;0.9875;1" dur="16s" repeatCount="indefinite"/></rect></clipPath><text x="112" y="164" font-family="ui-monospace, Consolas, 'Courier New', monospace" font-size="17" fill="#FFB27A" clip-path="url(#ca0)" xml:space="preserve">from lihont_ltp import *</text><clipPath id="ca1"><rect x="110" y="178" width="0" height="30"><animate attributeName="width" values="0;0;560;560;0" keyTimes="0;0.0750;0.1187;0.9875;1" dur="16s" repeatCount="indefinite"/></rect></clipPath><text x="112" y="200" font-family="ui-monospace, Consolas, 'Courier New', monospace" font-size="17" fill="#EAE1D9" clip-path="url(#ca1)" xml:space="preserve">plugin = Plugin("Тихая ночь", author="Вася")</text><clipPath id="ca2"><rect x="110" y="214" width="0" height="30"><animate attributeName="width" values="0;0;560;560;0" keyTimes="0;0.1375;0.1875;0.9875;1" dur="16s" repeatCount="indefinite"/></rect></clipPath><text x="112" y="236" font-family="ui-monospace, Consolas, 'Courier New', monospace" font-size="17" fill="#EAE1D9" clip-path="url(#ca2)" xml:space="preserve">plugin.video(night & hashtag("fyp"), hide)</text><clipPath id="ca3"><rect x="110" y="250" width="0" height="30"><animate attributeName="width" values="0;0;560;560;0" keyTimes="0;0.1875;0.2313;0.9875;1" dur="16s" repeatCount="indefinite"/></rect></clipPath><text x="112" y="272" font-family="ui-monospace, Consolas, 'Courier New', monospace" font-size="17" fill="#9ED69A" clip-path="url(#ca3)" xml:space="preserve">plugin.save()</text><text x="400" y="395" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="26" font-weight="600" fill="#EAE1D9">1. Напиши правило, как предложение</text><text x="400" y="423" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="16" fill="#9A9084">Видео с #fyp ночью скрыть: три строки на Python</text></g>
|
||||
<g opacity="0"><animate attributeName="opacity" values="0;0;1;1;0;0" keyTimes="0.0000;0.2500;0.2750;0.4750;0.5000;1.0000" dur="16s" repeatCount="indefinite"/><rect x="80" y="86" width="640" height="236" rx="18" fill="#17140F" stroke="#4E4840" stroke-width="2"/><clipPath id="cb0"><rect x="108" y="108" width="0" height="30"><animate attributeName="width" values="0;0;400;400;0" keyTimes="0;0.2750;0.3250;0.9875;1" dur="16s" repeatCount="indefinite"/></rect></clipPath><text x="110" y="130" font-family="ui-monospace, Consolas, 'Courier New', monospace" font-size="17" fill="#EAE1D9" clip-path="url(#cb0)" xml:space="preserve">$ python night.py</text><text x="110" y="170" font-family="ui-monospace, Consolas, 'Courier New', monospace" font-size="16" fill="#F0BF6D" opacity="0" xml:space="preserve">Защитник: Обратите внимание<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.3438;0.3444;1" dur="16s" repeatCount="indefinite"/></text><text x="110" y="200" font-family="ui-monospace, Consolas, 'Courier New', monospace" font-size="16" fill="#9A9084" opacity="0" xml:space="preserve">• Скрывает видео из ленты по условиям правил<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.3688;0.3694;1" dur="16s" repeatCount="indefinite"/></text><text x="110" y="230" font-family="ui-monospace, Consolas, 'Courier New', monospace" font-size="16" fill="#9A9084" opacity="0" xml:space="preserve">Плагин не может: читать сообщения и пароли, запускать код.<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.3937;0.3944;1" dur="16s" repeatCount="indefinite"/></text><text x="110" y="272" font-family="ui-monospace, Consolas, 'Courier New', monospace" font-size="16" fill="#9ED69A" opacity="0" xml:space="preserve">Готово: vasya.tihaya-noch.ltp<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.4250;0.4256;1" dur="16s" repeatCount="indefinite"/></text><g transform="translate(640 250)" opacity="0"><animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.4375;0.4500;1" dur="16s" repeatCount="indefinite"/><rect x="-26" y="-34" width="52" height="68" rx="8" fill="#F0BF6D"/><text x="0" y="8" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="16" font-weight="700" fill="#2B2620">.ltp</text></g><text x="400" y="395" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="26" font-weight="600" fill="#EAE1D9">2. Запусти: защитник покажет всё</text><text x="400" y="423" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="16" fill="#9A9084">Что делает каждое правило и насколько ему можно доверять</text></g>
|
||||
<g opacity="0"><animate attributeName="opacity" values="0;0;1;1;0;0" keyTimes="0.0000;0.5000;0.5250;0.7250;0.7500;1.0000" dur="16s" repeatCount="indefinite"/><rect x="90" y="150" width="230" height="140" rx="12" fill="#2B2620" stroke="#4E4840" stroke-width="2"/><rect x="70" y="296" width="270" height="12" rx="6" fill="#4E4840"/><text x="205" y="212" text-anchor="middle" font-family="ui-monospace, Consolas, 'Courier New', monospace" font-size="15" fill="#EAE1D9">ltp phone</text><text x="205" y="238" text-anchor="middle" font-family="ui-monospace, Consolas, 'Courier New', monospace" font-size="13" fill="#F0BF6D">vasya.tihaya-noch.ltp</text><path d="M320 220 C 400 220 430 220 500 220" stroke="#4E4840" stroke-width="4" fill="none" stroke-dasharray="6 6"/><rect x="500" y="110" width="130" height="236" rx="22" fill="#2B2620" stroke="#4E4840" stroke-width="3"/><rect x="515" y="130" width="100" height="196" rx="10" fill="#17140F"/><text x="565" y="236" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="13" fill="#9A9084">Download/ltp</text><g><rect x="-14" y="-18" width="28" height="36" rx="5" fill="#F0BF6D"/><animateMotion dur="16s" repeatCount="indefinite" keyPoints="0;0;1;1" keyTimes="0;0.5375;0.6500;1" calcMode="linear" path="M330 220 L 540 220"/></g><text x="400" y="395" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="26" font-weight="600" fill="#EAE1D9">3. Отправь на телефон по проводу</text><text x="400" y="423" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="16" fill="#9A9084">Команда ltp phone кладёт файл в Download/ltp</text></g>
|
||||
<g opacity="0"><animate attributeName="opacity" values="0;0;1;1;0;0" keyTimes="0.0000;0.7500;0.7750;0.9750;1.0000;1.0000" dur="16s" repeatCount="indefinite"/><rect x="250" y="60" width="300" height="320" rx="30" fill="#2B2620" stroke="#4E4840" stroke-width="3"/><rect x="272" y="150" width="256" height="150" rx="20" fill="#3A342C"/><text x="288" y="182" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="16" font-weight="700" fill="#EAE1D9">Установить «Тихая ночь»?</text><text x="288" y="208" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="12" fill="#F0BF6D">Защитник: Обратите внимание</text><text x="288" y="228" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="12" fill="#9A9084">Права: скрывать видео по правилам</text><text x="410" y="284" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="14" fill="#9A9084">Отмена</text><g><rect x="468" y="266" width="52" height="26" rx="13" fill="#F0BF6D"/><text x="494" y="284" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="13" font-weight="700" fill="#2B2620">Ставь</text><animate attributeName="opacity" values="1;1;0.55;1;1" keyTimes="0;0.8438;0.8625;0.8812;1" dur="16s" repeatCount="indefinite"/></g><g opacity="0"><animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.9000;0.9125;1" dur="16s" repeatCount="indefinite"/><rect x="276" y="330" width="248" height="34" rx="17" fill="#9ED69A"/><text x="400" y="352" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="14" font-weight="700" fill="#2B2620">Плагин включён ✓</text></g><text x="400" y="395" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="26" font-weight="600" fill="#EAE1D9">4. Установи и включи</text><text x="400" y="423" text-anchor="middle" font-family="system-ui, 'Segoe UI', Roboto, sans-serif" font-size="16" fill="#9A9084">Перед установкой видно права, правила и вердикт защитника</text></g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 10 KiB |
@@ -33,6 +33,15 @@ final class AccountNames {
|
||||
|
||||
private AccountNames() {}
|
||||
|
||||
/** Whether the name is being read by User.getUniqueId (the @handle), which only runs for a plugin that changes names. */
|
||||
private static boolean fromHandle() {
|
||||
StackTraceElement[] trace = new Throwable().getStackTrace();
|
||||
for (int i = 0; i < trace.length && i < 6; i++) {
|
||||
if ("getUniqueId".equals(trace[i].getMethodName())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Called by the User getters: records that `name` (a copy is returned) belongs to `user`. */
|
||||
static String remember(Object user, String name) {
|
||||
if (name == null || name.length() == 0 || user == null) return name;
|
||||
@@ -41,17 +50,21 @@ final class AccountNames {
|
||||
if (!validUid(uid)) return name;
|
||||
lihont.two.avatar.PictureOwners.learn(user, uid);
|
||||
lihont.two.widget.Contacts.learn(user, uid, name);
|
||||
String copy = new String(name);
|
||||
// a plugin may show this account under another name; the badge lookups follow the text that is shown
|
||||
String shown = lihont.two.plugin.PluginEngine.name(uid, name);
|
||||
// The handle is not a display name: TikTok checks it, and a changed one makes it demand a new username.
|
||||
if (!shown.equals(name) && fromHandle()) shown = name;
|
||||
String copy = new String(shown);
|
||||
synchronized (NAMES) {
|
||||
NAMES.put(copy, uid);
|
||||
ORDER.addLast(copy);
|
||||
while (ORDER.size() > LIMIT) NAMES.remove(ORDER.removeFirst());
|
||||
String seen = BY_VALUE.get(name);
|
||||
String seen = BY_VALUE.get(shown);
|
||||
if (seen == null) {
|
||||
BY_VALUE.put(name, uid);
|
||||
BY_VALUE.put(shown, uid);
|
||||
if (BY_VALUE.size() > 4096) BY_VALUE.remove(BY_VALUE.keySet().iterator().next());
|
||||
} else if (!seen.equals(uid)) {
|
||||
BY_VALUE.put(name, "");
|
||||
BY_VALUE.put(shown, "");
|
||||
}
|
||||
}
|
||||
return copy;
|
||||
|
||||
@@ -162,6 +162,29 @@ final class BarStyle implements ViewTreeObserver.OnPreDrawListener, View.OnAttac
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* TikTok may give a tab a background of its own when the selection moves, which silently drops the pill
|
||||
* (the bar was then plain on every tab but the first). Each frame the pill is put back and told which tab
|
||||
* is selected.
|
||||
*/
|
||||
private void keepPills() {
|
||||
for (int i = 0; i < TABS; i++) {
|
||||
NavPill pill = pills[i];
|
||||
View item = bar.getChildAt(i);
|
||||
if (pill == null || item == null) continue;
|
||||
if (item.getBackground() != pill) {
|
||||
if (replaced++ < 6) {
|
||||
android.util.Log.i("LihonT", "bar-style tab " + i + " lost its pill, background is "
|
||||
+ item.getBackground());
|
||||
}
|
||||
item.setBackground(pill);
|
||||
pill.snapTo(item.isSelected());
|
||||
} else {
|
||||
pill.syncTo(item.isSelected());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String describe(View view) {
|
||||
StringBuilder out = new StringBuilder(view.getClass().getName())
|
||||
.append(" ").append(view.getWidth()).append("x").append(view.getHeight())
|
||||
@@ -240,6 +263,7 @@ final class BarStyle implements ViewTreeObserver.OnPreDrawListener, View.OnAttac
|
||||
paintNavigationBar();
|
||||
hideLabels();
|
||||
styleCreate();
|
||||
keepPills();
|
||||
} catch (Throwable failure) {
|
||||
// Decoration must not break a frame.
|
||||
if (replaced++ < 6) android.util.Log.i("LihonT", "bar-style frame check failed: " + failure);
|
||||
|
||||
@@ -23,7 +23,24 @@ public final class BottomBar {
|
||||
|
||||
private BottomBar() {}
|
||||
|
||||
/** Whether this is the main screen with its first (home) tab selected, that is: a video of the feed is on the screen. */
|
||||
public static boolean homeSelected(Activity activity) {
|
||||
try {
|
||||
ViewGroup row = find(activity, activity.getWindow().getDecorView());
|
||||
return row != null && row.getChildAt(0).isSelected();
|
||||
} catch (Throwable unknown) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void onResumed(final Activity activity) {
|
||||
try {
|
||||
// Plugins that draw a picture follow every screen, whatever the look settings are.
|
||||
Windows.install(activity.getApplication());
|
||||
lihont.two.plugin.PluginScreen.attach(activity);
|
||||
} catch (Throwable ignored) {
|
||||
// Plugins are an extra: never let them take the main screen down.
|
||||
}
|
||||
try {
|
||||
HomeTabs.watch(activity);
|
||||
} catch (Throwable ignored) {
|
||||
|
||||
@@ -49,6 +49,13 @@ final class NavPill extends Drawable {
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
/** Follows the tab's selection when the drawable state did not carry it here (the background was swapped meanwhile). */
|
||||
void syncTo(boolean on) {
|
||||
if (on == selected) return;
|
||||
selected = on;
|
||||
animateTo(on ? 1f : 0f);
|
||||
}
|
||||
|
||||
@Override public boolean isStateful() {
|
||||
return true;
|
||||
}
|
||||
|
||||
62
src/lihont/two/chat/BubbleDrawable.java
Normal file
62
src/lihont/two/chat/BubbleDrawable.java
Normal file
@@ -0,0 +1,62 @@
|
||||
package lihont.two.chat;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Path;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.Drawable;
|
||||
|
||||
/**
|
||||
* A picture laid over a bubble like a wallpaper: scaled to cover the whole bubble, cut at the centre to its shape
|
||||
* and clipped to rounded corners, so the picture is never squeezed whatever the length of the message.
|
||||
*/
|
||||
public final class BubbleDrawable extends Drawable {
|
||||
private final Bitmap bitmap;
|
||||
private final int corner;
|
||||
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
|
||||
private final Rect from = new Rect();
|
||||
private final Path clip = new Path();
|
||||
|
||||
/** @param corner the radius of the rounded corners, in pixels */
|
||||
public BubbleDrawable(Bitmap bitmap, int corner) {
|
||||
this.bitmap = bitmap;
|
||||
this.corner = Math.max(1, corner);
|
||||
}
|
||||
|
||||
public boolean uses(Bitmap other) {
|
||||
return bitmap == other;
|
||||
}
|
||||
|
||||
@Override public void draw(Canvas canvas) {
|
||||
Rect box = getBounds();
|
||||
if (box.width() <= 0 || box.height() <= 0) return;
|
||||
float scale = Math.max(box.width() / (float) bitmap.getWidth(), box.height() / (float) bitmap.getHeight());
|
||||
int w = Math.min(bitmap.getWidth(), Math.round(box.width() / scale));
|
||||
int h = Math.min(bitmap.getHeight(), Math.round(box.height() / scale));
|
||||
int left = (bitmap.getWidth() - w) / 2;
|
||||
int top = (bitmap.getHeight() - h) / 2;
|
||||
from.set(left, top, left + w, top + h);
|
||||
clip.reset();
|
||||
clip.addRoundRect(new RectF(box), corner, corner, Path.Direction.CW);
|
||||
int saved = canvas.save();
|
||||
canvas.clipPath(clip);
|
||||
canvas.drawBitmap(bitmap, from, box, paint);
|
||||
canvas.restoreToCount(saved);
|
||||
}
|
||||
|
||||
@Override public void setAlpha(int alpha) {
|
||||
paint.setAlpha(alpha);
|
||||
}
|
||||
|
||||
@Override public void setColorFilter(ColorFilter filter) {
|
||||
paint.setColorFilter(filter);
|
||||
}
|
||||
|
||||
@Override public int getOpacity() {
|
||||
return PixelFormat.TRANSLUCENT;
|
||||
}
|
||||
}
|
||||
127
src/lihont/two/chat/BubbleStore.java
Normal file
127
src/lihont/two/chat/BubbleStore.java
Normal file
@@ -0,0 +1,127 @@
|
||||
package lihont.two.chat;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The bubble pictures, kept in the app's private folder: one for your own messages, one general picture for
|
||||
* everybody who has none of their own (so a stranger who writes first gets it at once), and one per person.
|
||||
* Nothing leaves the phone.
|
||||
*/
|
||||
public final class BubbleStore {
|
||||
public static final String OWN = "own";
|
||||
public static final String GENERAL = "general";
|
||||
private static final String PREFS = "lihont_bubbles";
|
||||
private static final String ENABLED = "enabled";
|
||||
private static final int MAX_SIDE = 512;
|
||||
private static final String PEOPLE = "people";
|
||||
private static final int MAX_PEOPLE = 60;
|
||||
|
||||
private static final Map<String, Bitmap> CACHE = new HashMap<String, Bitmap>();
|
||||
private static String lastSeen;
|
||||
|
||||
private BubbleStore() {}
|
||||
|
||||
public static boolean enabled(Context context) {
|
||||
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(ENABLED, false);
|
||||
}
|
||||
|
||||
public static void setEnabled(Context context, boolean on) {
|
||||
SharedPreferences.Editor edit = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit();
|
||||
edit.putBoolean(ENABLED, on).apply();
|
||||
}
|
||||
|
||||
/** The text colour chosen for your own or for the other person's bubbles, or null for "pick by the picture". */
|
||||
public static Integer textColor(Context context, boolean mine) {
|
||||
SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
String key = mine ? "color_own" : "color_other";
|
||||
return prefs.contains(key) ? Integer.valueOf(prefs.getInt(key, 0)) : null;
|
||||
}
|
||||
|
||||
/** @param color the colour, or null to go back to picking it by the picture */
|
||||
public static void setTextColor(Context context, boolean mine, Integer color) {
|
||||
SharedPreferences.Editor edit = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit();
|
||||
String key = mine ? "color_own" : "color_other";
|
||||
if (color == null) edit.remove(key);
|
||||
else edit.putInt(key, color.intValue());
|
||||
edit.apply();
|
||||
}
|
||||
|
||||
/** Remembers the name of a person whose chat was opened, so that a picture can be chosen for them from a list. */
|
||||
public static void seen(Context context, String person) {
|
||||
if (person == null || person.length() == 0 || person.length() > 40 || person.equals(lastSeen)) return;
|
||||
lastSeen = person;
|
||||
SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
java.util.Set<String> known = new java.util.HashSet<String>(prefs.getStringSet(PEOPLE, new java.util.HashSet<String>()));
|
||||
if (known.contains(person) || known.size() >= MAX_PEOPLE) return;
|
||||
known.add(person);
|
||||
prefs.edit().putStringSet(PEOPLE, known).apply();
|
||||
}
|
||||
|
||||
public static java.util.List<String> people(Context context) {
|
||||
SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
java.util.List<String> list = new java.util.ArrayList<String>(prefs.getStringSet(PEOPLE, new java.util.HashSet<String>()));
|
||||
java.util.Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
|
||||
return list;
|
||||
}
|
||||
|
||||
/** The picture for a slot: OWN, GENERAL or "p:" + person; a person without one gets the general picture. */
|
||||
public static synchronized Bitmap forSlot(Context context, String slot, boolean fallbackToGeneral) {
|
||||
Bitmap own = load(context, slot);
|
||||
if (own != null || !fallbackToGeneral) return own;
|
||||
return load(context, GENERAL);
|
||||
}
|
||||
|
||||
public static boolean has(Context context, String slot) {
|
||||
return file(context, slot).isFile();
|
||||
}
|
||||
|
||||
/** Stores a picture (scaled down) for the slot. */
|
||||
public static synchronized void put(Context context, String slot, Bitmap picture) throws IOException {
|
||||
Bitmap small = picture;
|
||||
int side = Math.max(picture.getWidth(), picture.getHeight());
|
||||
if (side > MAX_SIDE) {
|
||||
float scale = MAX_SIDE / (float) side;
|
||||
small = Bitmap.createScaledBitmap(picture, Math.max(3, Math.round(picture.getWidth() * scale)),
|
||||
Math.max(3, Math.round(picture.getHeight() * scale)), true);
|
||||
}
|
||||
File target = file(context, slot);
|
||||
File parent = target.getParentFile();
|
||||
if (!parent.isDirectory() && !parent.mkdirs()) throw new IOException("no folder");
|
||||
FileOutputStream out = new FileOutputStream(target);
|
||||
try {
|
||||
small.compress(Bitmap.CompressFormat.PNG, 100, out);
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
CACHE.remove(slot);
|
||||
}
|
||||
|
||||
public static synchronized void remove(Context context, String slot) {
|
||||
file(context, slot).delete();
|
||||
CACHE.remove(slot);
|
||||
}
|
||||
|
||||
private static Bitmap load(Context context, String slot) {
|
||||
Bitmap cached = CACHE.get(slot);
|
||||
if (cached != null) return cached;
|
||||
File file = file(context, slot);
|
||||
if (!file.isFile()) return null;
|
||||
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
|
||||
if (bitmap != null) CACHE.put(slot, bitmap);
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
private static File file(Context context, String slot) {
|
||||
String name = slot.replaceAll("[^A-Za-z0-9]", "_") + "_" + Integer.toHexString(slot.hashCode());
|
||||
return new File(new File(context.getFilesDir(), "lihont_bubbles"), name + ".png");
|
||||
}
|
||||
}
|
||||
238
src/lihont/two/chat/Bubbles.java
Normal file
238
src/lihont/two/chat/Bubbles.java
Normal file
@@ -0,0 +1,238 @@
|
||||
package lihont.two.chat;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.graphics.Bitmap;
|
||||
import android.text.Layout;
|
||||
import android.text.TextPaint;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.ViewTreeObserver;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.util.WeakHashMap;
|
||||
|
||||
/**
|
||||
* Puts the chosen pictures behind the message bubbles of a chat screen.
|
||||
*
|
||||
* The screen is recognised by its message list and its rows (ids found by looking at the chat once); a bubble
|
||||
* is the view "f67" inside a row, and it belongs to you when it sits on the right half of the row. The person on
|
||||
* the other side is told by the name in the screen's header; a person with no picture of their own gets the
|
||||
* general one. Texts are never read except that one header name, which is used as a key and kept nowhere.
|
||||
*/
|
||||
public final class Bubbles {
|
||||
private static final String LIST = "u8m";
|
||||
private static final String ROW = "wqh";
|
||||
private static final String BUBBLE = "f67";
|
||||
private static final long NAME_MS = 3000L;
|
||||
private static final int CORNER_DP = 18;
|
||||
|
||||
private static final WeakHashMap<View, Boolean> WATCHED = new WeakHashMap<View, Boolean>();
|
||||
private static final WeakHashMap<Bitmap, Integer> TEXT = new WeakHashMap<Bitmap, Integer>();
|
||||
private static String name;
|
||||
private static long nameAt;
|
||||
|
||||
private Bubbles() {}
|
||||
|
||||
public static void watch(final Activity activity) {
|
||||
if (!BubbleStore.enabled(activity)) return;
|
||||
final View decor = activity.getWindow().getDecorView();
|
||||
if (WATCHED.containsKey(decor)) return;
|
||||
WATCHED.put(decor, Boolean.TRUE);
|
||||
// Before every frame, so a new bubble is dressed before it is first drawn, not a moment later.
|
||||
decor.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
|
||||
@Override public boolean onPreDraw() {
|
||||
try {
|
||||
if (BubbleStore.enabled(activity)) apply(activity, decor);
|
||||
} catch (Throwable ignored) {
|
||||
// Decoration: never let it take a chat down.
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static int id(Activity activity, String name) {
|
||||
return activity.getResources().getIdentifier(name, "id", activity.getPackageName());
|
||||
}
|
||||
|
||||
private static void apply(Activity activity, View decor) {
|
||||
int listId = id(activity, LIST);
|
||||
int rowId = id(activity, ROW);
|
||||
int bubbleId = id(activity, BUBBLE);
|
||||
if (listId == 0 || rowId == 0 || bubbleId == 0) return;
|
||||
View found = decor.findViewById(listId);
|
||||
if (!(found instanceof ViewGroup)) return;
|
||||
ViewGroup list = (ViewGroup) found;
|
||||
String partner = null;
|
||||
Bitmap own = BubbleStore.forSlot(activity, BubbleStore.OWN, false);
|
||||
Bitmap theirs = null;
|
||||
boolean theirsLoaded = false;
|
||||
int corner = Math.round(CORNER_DP * activity.getResources().getDisplayMetrics().density);
|
||||
for (int i = 0; i < list.getChildCount(); i++) {
|
||||
View child = list.getChildAt(i);
|
||||
View row = child.getId() == rowId ? child : child.findViewById(rowId);
|
||||
if (row == null || row.getWidth() == 0) continue;
|
||||
View bubble = row.findViewById(bubbleId);
|
||||
if (bubble == null || bubble.getWidth() == 0) continue;
|
||||
int[] at = new int[2];
|
||||
int[] base = new int[2];
|
||||
bubble.getLocationInWindow(at);
|
||||
row.getLocationInWindow(base);
|
||||
boolean mine = at[0] - base[0] + bubble.getWidth() / 2 > row.getWidth() / 2;
|
||||
Bitmap picture;
|
||||
if (mine) {
|
||||
picture = own;
|
||||
} else {
|
||||
if (!theirsLoaded) {
|
||||
partner = partner == null ? cachedName(decor, list) : partner;
|
||||
BubbleStore.seen(activity, partner);
|
||||
theirs = partner == null ? BubbleStore.forSlot(activity, BubbleStore.GENERAL, false)
|
||||
: BubbleStore.forSlot(activity, "p:" + partner, true);
|
||||
theirsLoaded = true;
|
||||
}
|
||||
picture = theirs;
|
||||
}
|
||||
if (picture == null || isMedia(bubble)) continue;
|
||||
if (!(bubble.getBackground() instanceof BubbleDrawable)
|
||||
|| !((BubbleDrawable) bubble.getBackground()).uses(picture)) {
|
||||
bubble.setBackground(new BubbleDrawable(picture, corner));
|
||||
}
|
||||
// every frame: a colour chosen in the settings, or text TikTok has just re-coloured, is put right at once
|
||||
Integer chosen = BubbleStore.textColor(activity, mine);
|
||||
paint(row, chosen != null ? chosen.intValue() : textColor(picture));
|
||||
}
|
||||
}
|
||||
|
||||
/** The header name is looked up at most every few seconds: walking the whole screen for each frame would be wasteful. */
|
||||
private static String cachedName(View decor, ViewGroup list) {
|
||||
long now = android.os.SystemClock.uptimeMillis();
|
||||
if (now - nameAt > NAME_MS) {
|
||||
name = headerName(decor, list);
|
||||
nameAt = now;
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/** Black text on a light picture, white on a dark one: the average brightness of the picture decides. */
|
||||
private static int textColor(Bitmap picture) {
|
||||
Integer known = TEXT.get(picture);
|
||||
if (known != null) return known.intValue();
|
||||
// the middle of the picture is what lies under the text; the edges are cut off by short bubbles
|
||||
int w = picture.getWidth();
|
||||
int h = picture.getHeight();
|
||||
Bitmap middle = Bitmap.createBitmap(picture, w / 4, h / 4, Math.max(1, w / 2), Math.max(1, h / 2));
|
||||
Bitmap tiny = Bitmap.createScaledBitmap(middle, 8, 8, true);
|
||||
float sum = 0f;
|
||||
float weight = 0f;
|
||||
for (int y = 0; y < 8; y++) {
|
||||
for (int x = 0; x < 8; x++) {
|
||||
int c = tiny.getPixel(x, y);
|
||||
float a = ((c >>> 24) & 0xFF) / 255f;
|
||||
float lum = (0.299f * ((c >> 16) & 0xFF) + 0.587f * ((c >> 8) & 0xFF) + 0.114f * (c & 0xFF)) / 255f;
|
||||
sum += lum * a;
|
||||
weight += a;
|
||||
}
|
||||
}
|
||||
int color = weight == 0f || sum / weight < 0.55f ? 0xFFFFFFFF : 0xFF111111;
|
||||
TEXT.put(picture, Integer.valueOf(color));
|
||||
return color;
|
||||
}
|
||||
|
||||
/** A shared video or a picture is not a text bubble: it has a rounding layout with the media inside. */
|
||||
private static final java.util.HashMap<Class<?>, java.lang.reflect.Field> LAYOUTS =
|
||||
new java.util.HashMap<Class<?>, java.lang.reflect.Field>();
|
||||
private static final java.lang.reflect.Field NONE;
|
||||
|
||||
static {
|
||||
java.lang.reflect.Field none = null;
|
||||
try {
|
||||
none = Bubbles.class.getDeclaredField("NONE");
|
||||
} catch (Throwable ignored) {
|
||||
// used only as a "nothing here" marker
|
||||
}
|
||||
NONE = none;
|
||||
}
|
||||
|
||||
/** The text layout of a custom text view, found once per class as the field of type Layout, or null. */
|
||||
private static Layout layoutOf(View view) {
|
||||
try {
|
||||
java.lang.reflect.Field field = LAYOUTS.get(view.getClass());
|
||||
if (field == null) {
|
||||
field = NONE;
|
||||
for (Class<?> type = view.getClass(); type != null && type != View.class && field == NONE;
|
||||
type = type.getSuperclass()) {
|
||||
for (java.lang.reflect.Field candidate : type.getDeclaredFields()) {
|
||||
if (Layout.class.isAssignableFrom(candidate.getType())) {
|
||||
candidate.setAccessible(true);
|
||||
field = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
LAYOUTS.put(view.getClass(), field);
|
||||
}
|
||||
return field == NONE ? null : (Layout) field.get(view);
|
||||
} catch (Throwable unreadable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isMedia(View bubble) {
|
||||
if (!(bubble instanceof ViewGroup)) return false;
|
||||
ViewGroup group = (ViewGroup) bubble;
|
||||
for (int i = 0; i < group.getChildCount(); i++) {
|
||||
if (group.getChildAt(i).getClass().getName().endsWith("RoundingCornerLayoutCL")) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void paint(View view, int color) {
|
||||
if (view instanceof TextView) {
|
||||
TextView text = (TextView) view;
|
||||
if (text.getCurrentTextColor() == color && text.getShadowRadius() > 0f) return;
|
||||
text.setTextColor(color);
|
||||
// a thin halo of the opposite colour keeps the text readable over a busy picture
|
||||
boolean lightText = ((color >> 16 & 0xFF) * 299 + (color >> 8 & 0xFF) * 587 + (color & 0xFF) * 114) / 1000 > 140;
|
||||
text.setShadowLayer(3f, 0f, 0f, lightText ? 0xCC000000 : 0xCCFFFFFF);
|
||||
}
|
||||
Layout layout = view instanceof TextView ? null : layoutOf(view);
|
||||
if (layout != null) {
|
||||
// TikTok's message text is a view that lays the text out and draws it itself, with no TextView inside
|
||||
TextPaint ink = layout.getPaint();
|
||||
if (ink.getColor() != color) {
|
||||
ink.setColor(color);
|
||||
view.invalidate();
|
||||
}
|
||||
}
|
||||
if (view instanceof ViewGroup) {
|
||||
ViewGroup group = (ViewGroup) view;
|
||||
for (int i = 0; i < group.getChildCount(); i++) paint(group.getChildAt(i), color);
|
||||
}
|
||||
}
|
||||
|
||||
/** The name of the person in the header: the biggest text above the list (the status under it is smaller). */
|
||||
public static String headerName(View decor, ViewGroup list) {
|
||||
int[] where = new int[2];
|
||||
list.getLocationInWindow(where);
|
||||
TextView best = find(decor, where[1], null);
|
||||
return best == null ? null : best.getText().toString().trim();
|
||||
}
|
||||
|
||||
private static TextView find(View view, int limit, TextView best) {
|
||||
if (view instanceof TextView && view.getVisibility() == View.VISIBLE) {
|
||||
TextView text = (TextView) view;
|
||||
CharSequence value = text.getText();
|
||||
int[] at = new int[2];
|
||||
view.getLocationInWindow(at);
|
||||
if (value != null && value.toString().trim().length() > 0 && at[1] < limit && at[1] > 0
|
||||
&& view.getWidth() > 0 && (best == null || text.getTextSize() > best.getTextSize())) {
|
||||
best = text;
|
||||
}
|
||||
}
|
||||
if (view instanceof ViewGroup) {
|
||||
ViewGroup group = (ViewGroup) view;
|
||||
for (int i = 0; i < group.getChildCount(); i++) best = find(group.getChildAt(i), limit, best);
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
56
src/lihont/two/comments/CommentPhotos.java
Normal file
56
src/lihont/two/comments/CommentPhotos.java
Normal file
@@ -0,0 +1,56 @@
|
||||
package lihont.two.comments;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.util.Log;
|
||||
|
||||
import lihont.two.widget.AppContext;
|
||||
|
||||
/**
|
||||
* The switch for TikTok's multi-photo comments (up to nine photos in one comment). TikTok has the picker built in and
|
||||
* offers it only to some accounts; see lihont/comment_photos_patch.py for the one place that asks. With the switch on
|
||||
* the answer is "yes" whatever the account was given, with it off TikTok's own answer is returned untouched.
|
||||
*
|
||||
* The switch is on by default and lives in its own small file of preferences, because it is a choice about the app and
|
||||
* not about one account.
|
||||
*/
|
||||
public final class CommentPhotos {
|
||||
private static final String TAG = "LIHONT";
|
||||
private static final String PREFS = "lihont_comment_photos";
|
||||
private static final String KEY = "multi";
|
||||
private static boolean logged;
|
||||
|
||||
private CommentPhotos() {}
|
||||
|
||||
/** Called with TikTok's own answer; true when the comment keyboard should offer several photos. */
|
||||
public static boolean gate(boolean original) {
|
||||
boolean on = enabled(AppContext.get());
|
||||
boolean result = original || on;
|
||||
if (!logged) {
|
||||
logged = true;
|
||||
try {
|
||||
Log.i(TAG, "comment multi photo: " + original + " -> " + result + (on ? " [switch on]" : " [switch off]"));
|
||||
} catch (Throwable noLogger) {
|
||||
// diagnostic only
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static boolean enabled(Context context) {
|
||||
if (context == null) return true;
|
||||
try {
|
||||
return prefs(context).getBoolean(KEY, true);
|
||||
} catch (RuntimeException unreadable) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import lihont.two.plugin.PluginEngine;
|
||||
import lihont.two.settings.SettingsHost;
|
||||
|
||||
/**
|
||||
@@ -102,10 +103,12 @@ public final class FeedFilter {
|
||||
if (input == null || input.isEmpty()) return input;
|
||||
boolean ads = SettingsHost.hideAds();
|
||||
boolean live = SettingsHost.hideLive();
|
||||
if (!ads && !live) return input;
|
||||
boolean plugins = PluginEngine.feedActive();
|
||||
if (!ads && !live && !plugins) return input;
|
||||
ArrayList<Object> kept = null;
|
||||
int removedAds = 0;
|
||||
int removedLive = 0;
|
||||
int removedPlugins = 0;
|
||||
Map<Integer, Integer> types = new TreeMap<Integer, Integer>();
|
||||
for (int i = 0, size = input.size(); i < size; i++) {
|
||||
Object item = input.get(i);
|
||||
@@ -118,6 +121,9 @@ public final class FeedFilter {
|
||||
} else if (live && isLive(item)) {
|
||||
drop = true;
|
||||
removedLive++;
|
||||
} else if (plugins && PluginEngine.hideFeedItem(item)) {
|
||||
drop = true;
|
||||
removedPlugins++;
|
||||
}
|
||||
if (!drop) count(types, item);
|
||||
}
|
||||
@@ -130,7 +136,7 @@ public final class FeedFilter {
|
||||
kept.add(item);
|
||||
}
|
||||
}
|
||||
report(input.size(), removedAds, removedLive, types);
|
||||
report(input.size(), removedAds, removedLive + removedPlugins, types);
|
||||
return kept == null ? input : kept;
|
||||
}
|
||||
|
||||
|
||||
86
src/lihont/two/ghost/Ghost.java
Normal file
86
src/lihont/two/ghost/Ghost.java
Normal file
@@ -0,0 +1,86 @@
|
||||
package lihont.two.ghost;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.util.Log;
|
||||
|
||||
import lihont.two.widget.AppContext;
|
||||
|
||||
/**
|
||||
* Ghost mode: look without leaving a mark. Each part is its own switch, off by default, kept in a small file of its
|
||||
* own because it is a choice about the app and not about one account.
|
||||
*
|
||||
* Stories: with the switch on, the call that tells TikTok's server a story was viewed is skipped (see
|
||||
* lihont/ghost_patch.py), so the author does not see the person in the list of viewers. The story still plays.
|
||||
*/
|
||||
public final class Ghost {
|
||||
private static final String TAG = "LIHONT";
|
||||
private static final String PREFS = "lihont_ghost";
|
||||
private static final String STORIES = "stories";
|
||||
private static final String MESSAGES = "messages";
|
||||
private static boolean logged;
|
||||
private static boolean loggedMessages;
|
||||
|
||||
private Ghost() {}
|
||||
|
||||
/**
|
||||
* Asked by the chat's "mark the conversation as read" call: true means "do not send it". The conversation then stays
|
||||
* unread for the other person (and for you) until the switch is off and the chat is opened again.
|
||||
*/
|
||||
public static boolean messages() {
|
||||
boolean on = messagesOn(AppContext.get());
|
||||
if (on && !loggedMessages) {
|
||||
loggedMessages = true;
|
||||
try {
|
||||
Log.i(TAG, "ghost: chat read receipts are not sent");
|
||||
} catch (Throwable noLogger) {
|
||||
// diagnostic only
|
||||
}
|
||||
}
|
||||
return on;
|
||||
}
|
||||
|
||||
public static boolean messagesOn(Context context) {
|
||||
if (context == null) return false;
|
||||
try {
|
||||
return prefs(context).getBoolean(MESSAGES, false);
|
||||
} catch (RuntimeException unreadable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void setMessages(Context context, boolean on) {
|
||||
prefs(context).edit().putBoolean(MESSAGES, on).apply();
|
||||
}
|
||||
|
||||
/** Asked by the story-viewed method: true means "do not report this view". */
|
||||
public static boolean stories() {
|
||||
boolean on = storiesOn(AppContext.get());
|
||||
if (on && !logged) {
|
||||
logged = true;
|
||||
try {
|
||||
Log.i(TAG, "ghost: story views are not reported");
|
||||
} catch (Throwable noLogger) {
|
||||
// diagnostic only
|
||||
}
|
||||
}
|
||||
return on;
|
||||
}
|
||||
|
||||
public static boolean storiesOn(Context context) {
|
||||
if (context == null) return false;
|
||||
try {
|
||||
return prefs(context).getBoolean(STORIES, false);
|
||||
} catch (RuntimeException unreadable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void setStories(Context context, boolean on) {
|
||||
prefs(context).edit().putBoolean(STORIES, on).apply();
|
||||
}
|
||||
|
||||
private static SharedPreferences prefs(Context context) {
|
||||
return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,16 @@ public final class Windows implements Application.ActivityLifecycleCallbacks {
|
||||
|
||||
/** Watchers for a screen that has just come to the front; also called by the main screen itself. */
|
||||
public static void attach(Activity activity) {
|
||||
try {
|
||||
lihont.two.plugin.PluginScreen.attach(activity);
|
||||
} catch (Throwable ignored) {
|
||||
// Plugins are an extra.
|
||||
}
|
||||
try {
|
||||
lihont.two.chat.Bubbles.watch(activity);
|
||||
} catch (Throwable ignored) {
|
||||
// bubbles are an extra
|
||||
}
|
||||
try {
|
||||
// The streak keeper does not depend on the look: it only asks whether today's time has come.
|
||||
lihont.two.streak.AutoFlame.onForeground(activity);
|
||||
|
||||
123
src/lihont/two/plugin/Act.java
Normal file
123
src/lihont/two/plugin/Act.java
Normal file
@@ -0,0 +1,123 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* One thing a rule does. A JSON object with exactly one key:
|
||||
*
|
||||
* {"feed.hide": true} the video is left out of the feed (right feed.hide, trigger feed.item)
|
||||
* {"name.prefix": "text"} text before the name (right names, trigger name.show)
|
||||
* {"name.suffix": "text"} text after the name (right names, trigger name.show)
|
||||
* {"name.replace": "text"} another name (right names, trigger name.show)
|
||||
* {"notice": "text"} a short hint on the screen (right ui.notice, any trigger)
|
||||
* {"overlay": {...}} a picture over the app, see OverlaySpec (right ui.overlay, plus ui.sound and
|
||||
* feed.like for a tap that plays a sound or likes; trigger screen.show)
|
||||
* {"download": {...}} a file from a named site, see DownloadSpec (right net.download, trigger screen.show)
|
||||
*
|
||||
* The texts of the name actions may hold {name}, {time} and {date}.
|
||||
*/
|
||||
final class Act {
|
||||
static final int HIDE = 0;
|
||||
static final int PREFIX = 1;
|
||||
static final int SUFFIX = 2;
|
||||
static final int REPLACE = 3;
|
||||
static final int NOTICE = 4;
|
||||
static final int OVERLAY = 5;
|
||||
static final int DOWNLOAD = 6;
|
||||
|
||||
final int kind;
|
||||
final String text;
|
||||
/** The picture of an overlay action, else null. */
|
||||
final OverlaySpec overlay;
|
||||
/** The file of a download action, else null. */
|
||||
final DownloadSpec download;
|
||||
|
||||
private Act(int kind, String text, OverlaySpec overlay) {
|
||||
this(kind, text, overlay, null);
|
||||
}
|
||||
|
||||
private Act(int kind, String text, OverlaySpec overlay, DownloadSpec download) {
|
||||
this.kind = kind;
|
||||
this.text = text;
|
||||
this.overlay = overlay;
|
||||
this.download = download;
|
||||
}
|
||||
|
||||
/** The rights the action needs. */
|
||||
List<String> permissions() {
|
||||
List<String> rights = new ArrayList<String>();
|
||||
if (kind == HIDE) {
|
||||
rights.add(Permission.FEED_HIDE);
|
||||
} else if (kind == NOTICE) {
|
||||
rights.add(Permission.NOTICE);
|
||||
} else if (kind == DOWNLOAD) {
|
||||
rights.add(Permission.NET_DOWNLOAD);
|
||||
} else if (kind == OVERLAY) {
|
||||
rights.add(Permission.OVERLAY);
|
||||
if (overlay.tap.contains(OverlaySpec.TAP_SOUND)) rights.add(Permission.SOUND);
|
||||
if (overlay.tap.contains(OverlaySpec.TAP_LIKE)) rights.add(Permission.LIKE);
|
||||
} else {
|
||||
rights.add(Permission.NAMES);
|
||||
}
|
||||
return rights;
|
||||
}
|
||||
|
||||
/** The action in plain words, for the defender. */
|
||||
String says() {
|
||||
if (kind == HIDE) return "скрыть видео";
|
||||
if (kind == PREFIX) return "дописать «" + text + "» перед именем";
|
||||
if (kind == SUFFIX) return "дописать «" + text + "» после имени";
|
||||
if (kind == REPLACE) return "показать вместо имени «" + text + "»";
|
||||
if (kind == NOTICE) return "показать подсказку «" + text + "»";
|
||||
if (kind == DOWNLOAD) {
|
||||
return "скачать файл " + download.as + " с сайта " + download.host + " (после вашего подтверждения)";
|
||||
}
|
||||
String place = overlay.walk != null
|
||||
? "ходит по экрану: " + (OverlaySpec.WALK_BOUNCE.equals(overlay.walk) ? "туда-сюда" : "бродит") + ", "
|
||||
+ overlay.walkSpeed + " dp/с"
|
||||
: (overlay.movable ? "можно двигать" : "закреплена");
|
||||
StringBuilder out = new StringBuilder("показать картинку " + overlay.image + " (" + overlay.size + " dp, " + place + ")");
|
||||
List<String> taps = new ArrayList<String>();
|
||||
if (overlay.tap.contains(OverlaySpec.TAP_ANIMATE)) taps.add("играет анимация");
|
||||
if (overlay.tap.contains(OverlaySpec.TAP_SOUND)) taps.add("звук");
|
||||
if (overlay.tap.contains(OverlaySpec.TAP_LIKE)) taps.add("лайк видео");
|
||||
if (!taps.isEmpty()) {
|
||||
out.append("; по нажатию: ");
|
||||
for (int i = 0; i < taps.size(); i++) out.append(i > 0 ? ", " : "").append(taps.get(i));
|
||||
}
|
||||
if (overlay.pet != null) out.append("; поглаживание меняет картинку");
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
static Act parse(Object node, String trigger, String where) throws LtpException {
|
||||
Map<String, Object> map = Fields.map(node, where);
|
||||
if (map.size() != 1) throw new LtpException(where + ": в действии должно быть ровно одно поле");
|
||||
String key = map.keySet().iterator().next();
|
||||
Object value = map.get(key);
|
||||
String here = where + ", действие «" + key + "»";
|
||||
if (key.equals("feed.hide")) {
|
||||
if (!Rule.FEED.equals(trigger)) throw new LtpException(here + ": работает только в правиле feed.item");
|
||||
if (!Boolean.TRUE.equals(value)) throw new LtpException(here + ": нужно true");
|
||||
return new Act(HIDE, "", null);
|
||||
}
|
||||
if (key.equals("notice")) return new Act(NOTICE, Fields.text(value, 80, here), null);
|
||||
if (key.equals("overlay")) {
|
||||
if (!Rule.SCREEN.equals(trigger)) throw new LtpException(here + ": работает только в правиле screen.show");
|
||||
return new Act(OVERLAY, "", OverlaySpec.parse(value, here));
|
||||
}
|
||||
if (key.equals("download")) {
|
||||
if (!Rule.SCREEN.equals(trigger)) throw new LtpException(here + ": работает только в правиле screen.show");
|
||||
return new Act(DOWNLOAD, "", null, DownloadSpec.parse(value, here));
|
||||
}
|
||||
int kind = key.equals("name.prefix") ? PREFIX
|
||||
: key.equals("name.suffix") ? SUFFIX
|
||||
: key.equals("name.replace") ? REPLACE : -1;
|
||||
if (kind < 0) throw new LtpException(here + ": такого действия нет");
|
||||
if (!Rule.NAME.equals(trigger)) throw new LtpException(here + ": работает только в правиле name.show");
|
||||
String text = Fields.text(value, 60, here);
|
||||
if (kind == REPLACE && text.trim().length() == 0) throw new LtpException(here + ": имя не может быть пустым");
|
||||
return new Act(kind, text, null);
|
||||
}
|
||||
}
|
||||
340
src/lihont/two/plugin/Cond.java
Normal file
340
src/lihont/two/plugin/Cond.java
Normal file
@@ -0,0 +1,340 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* A condition of a rule. A condition is a JSON object with exactly one key:
|
||||
*
|
||||
* {"text": ["word", ...]} the description has any of the words
|
||||
* {"hashtag": ["tag", ...]} the description has any of the hashtags
|
||||
* {"author": ["name", ...]} the author's username or id is listed ("self" is the signed-in account)
|
||||
* {"uid": ["id", ...]} the account behind a name is listed ("self" is the signed-in account)
|
||||
* {"account": ["name", ...]} the rule works only while one of these accounts is signed in
|
||||
* {"time": "22:00-07:00"} the local time is in the range (it may pass midnight)
|
||||
* {"weekday": [1, 2, ...]} the day of the week (1 Monday to 7 Sunday)
|
||||
* {"all": [cond, ...]} {"any": [cond, ...]} {"not": cond}
|
||||
*/
|
||||
abstract class Cond {
|
||||
static final int MAX_DEPTH = 4;
|
||||
static final int MAX_NODES = 40;
|
||||
|
||||
abstract boolean test(Ctx ctx);
|
||||
|
||||
/** The condition in plain words, for the defender: "в описании есть «a», «b»". */
|
||||
abstract String says();
|
||||
|
||||
/** Whether the condition picks videos or people by what they are (words, tags, author, account id), not just by when. */
|
||||
boolean selects() {
|
||||
return false;
|
||||
}
|
||||
|
||||
private static final String[] DAYS = {"", "пн", "вт", "ср", "чт", "пт", "сб", "вс"};
|
||||
|
||||
private static String items(List<String> words, String before, String after) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (int i = 0; i < words.size() && i < 5; i++) {
|
||||
if (i > 0) out.append(", ");
|
||||
out.append(before).append(words.get(i)).append(after);
|
||||
}
|
||||
if (words.size() > 5) out.append(" и ещё ").append(words.size() - 5);
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static String people(List<String> names) {
|
||||
List<String> shown = new ArrayList<String>();
|
||||
for (String name : names) shown.add(name.equals("self") ? "вы" : name);
|
||||
return items(shown, "", "");
|
||||
}
|
||||
|
||||
private static String clock(int minutes) {
|
||||
return String.format("%02d:%02d", minutes / 60, minutes % 60);
|
||||
}
|
||||
|
||||
private static String nested(Cond part) {
|
||||
String text = part.says();
|
||||
return part instanceof All || part instanceof Any ? "(" + text + ")" : text;
|
||||
}
|
||||
|
||||
private static String join(List<Cond> parts, String separator) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (int i = 0; i < parts.size(); i++) {
|
||||
if (i > 0) out.append(separator);
|
||||
out.append(nested(parts.get(i)));
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
static Cond parse(Object node, String where) throws LtpException {
|
||||
return parse(node, where, 0, new int[] {0});
|
||||
}
|
||||
|
||||
private static Cond parse(Object node, String where, int depth, int[] nodes) throws LtpException {
|
||||
if (depth >= MAX_DEPTH) throw new LtpException(where + ": условия вложены слишком глубоко");
|
||||
if (++nodes[0] > MAX_NODES) throw new LtpException(where + ": в правиле слишком много условий");
|
||||
Map<String, Object> map = Fields.map(node, where);
|
||||
if (map.size() != 1) throw new LtpException(where + ": в условии должно быть ровно одно поле");
|
||||
String key = map.keySet().iterator().next();
|
||||
Object value = map.get(key);
|
||||
String here = where + ", условие «" + key + "»";
|
||||
if (key.equals("text")) return new Text(Fields.words(value, 64, 80, here));
|
||||
if (key.equals("hashtag")) return new Hashtag(Fields.words(value, 64, 60, here));
|
||||
if (key.equals("author")) return new Author(Fields.words(value, 64, 40, here));
|
||||
if (key.equals("uid")) return new Uid(Fields.words(value, 64, 40, here));
|
||||
if (key.equals("account")) return new Account(Fields.words(value, 16, 40, here));
|
||||
if (key.equals("time")) return Time.parse(Fields.text(value, 11, here), here);
|
||||
if (key.equals("weekday")) {
|
||||
List<Object> days = Fields.list(value, here);
|
||||
if (days.isEmpty() || days.size() > 7) throw new LtpException(here + ": от 1 до 7 дней");
|
||||
Set<Integer> set = new HashSet<Integer>();
|
||||
for (Object day : days) set.add(Integer.valueOf(Fields.integer(day, 1, 7, here)));
|
||||
return new Weekday(set);
|
||||
}
|
||||
if (key.equals("all") || key.equals("any")) {
|
||||
List<Object> items = Fields.list(value, here);
|
||||
if (items.isEmpty() || items.size() > 16) throw new LtpException(here + ": от 1 до 16 условий");
|
||||
List<Cond> parts = new ArrayList<Cond>();
|
||||
for (Object item : items) parts.add(parse(item, where, depth + 1, nodes));
|
||||
return key.equals("all") ? new All(parts) : new Any(parts);
|
||||
}
|
||||
if (key.equals("not")) return new Not(parse(value, where, depth + 1, nodes));
|
||||
throw new LtpException(here + ": такого условия нет");
|
||||
}
|
||||
|
||||
private static final class Text extends Cond {
|
||||
private final List<String> words;
|
||||
|
||||
Text(List<String> words) {
|
||||
this.words = words;
|
||||
}
|
||||
|
||||
@Override String says() {
|
||||
return "в описании есть " + items(words, "«", "»");
|
||||
}
|
||||
|
||||
@Override boolean selects() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override boolean test(Ctx ctx) {
|
||||
String text = ctx.text();
|
||||
for (String word : words) {
|
||||
if (text.contains(word)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Hashtag extends Cond {
|
||||
private final List<String> tags = new ArrayList<String>();
|
||||
|
||||
Hashtag(List<String> words) {
|
||||
for (String word : words) tags.add(word.startsWith("#") ? word.substring(1) : word);
|
||||
}
|
||||
|
||||
@Override String says() {
|
||||
return "хэштег " + items(tags, "#", "");
|
||||
}
|
||||
|
||||
@Override boolean selects() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override boolean test(Ctx ctx) {
|
||||
Set<String> have = ctx.hashtags();
|
||||
for (String tag : tags) {
|
||||
if (have.contains(tag)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Author extends Cond {
|
||||
private final List<String> names;
|
||||
|
||||
Author(List<String> names) {
|
||||
this.names = names;
|
||||
}
|
||||
|
||||
@Override String says() {
|
||||
return "автор видео: " + people(names);
|
||||
}
|
||||
|
||||
@Override boolean selects() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override boolean test(Ctx ctx) {
|
||||
for (String name : names) {
|
||||
if (name.equals("self")) {
|
||||
if (ctx.selfName().length() > 0 && ctx.selfName().equals(ctx.author())) return true;
|
||||
if (ctx.selfUid().length() > 0 && ctx.selfUid().equals(ctx.authorUid())) return true;
|
||||
} else if ((ctx.author().length() > 0 && name.equals(ctx.author()))
|
||||
|| (ctx.authorUid().length() > 0 && name.equals(ctx.authorUid()))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Uid extends Cond {
|
||||
private final List<String> ids;
|
||||
|
||||
Uid(List<String> ids) {
|
||||
this.ids = ids;
|
||||
}
|
||||
|
||||
@Override String says() {
|
||||
return ids.size() == 1 && ids.get(0).equals("self") ? "это ваш аккаунт" : "аккаунт: " + people(ids);
|
||||
}
|
||||
|
||||
@Override boolean selects() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override boolean test(Ctx ctx) {
|
||||
String uid = ctx.uid();
|
||||
if (uid.length() == 0) return false;
|
||||
for (String id : ids) {
|
||||
if (id.equals("self") ? uid.equals(ctx.selfUid()) : id.equals(uid)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Account extends Cond {
|
||||
private final List<String> names;
|
||||
|
||||
Account(List<String> names) {
|
||||
this.names = names;
|
||||
}
|
||||
|
||||
@Override String says() {
|
||||
return "вы вошли как " + items(names, "", "");
|
||||
}
|
||||
|
||||
@Override boolean test(Ctx ctx) {
|
||||
for (String name : names) {
|
||||
if (name.equals(ctx.selfName()) || name.equals(ctx.selfUid())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Time extends Cond {
|
||||
private final int from;
|
||||
private final int to;
|
||||
|
||||
private Time(int from, int to) {
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
}
|
||||
|
||||
static Time parse(String text, String where) throws LtpException {
|
||||
if (!text.matches("[0-2][0-9]:[0-5][0-9]-[0-2][0-9]:[0-5][0-9]")) {
|
||||
throw new LtpException(where + ": нужен вид «22:00-07:00»");
|
||||
}
|
||||
int from = Integer.parseInt(text.substring(0, 2)) * 60 + Integer.parseInt(text.substring(3, 5));
|
||||
int to = Integer.parseInt(text.substring(6, 8)) * 60 + Integer.parseInt(text.substring(9, 11));
|
||||
if (from > 1439 || to > 1439 || from == to) throw new LtpException(where + ": время от 00:00 до 23:59, начало не равно концу");
|
||||
return new Time(from, to);
|
||||
}
|
||||
|
||||
@Override String says() {
|
||||
return "время с " + clock(from) + " до " + clock(to);
|
||||
}
|
||||
|
||||
@Override boolean test(Ctx ctx) {
|
||||
int now = ctx.minute();
|
||||
return from < to ? now >= from && now < to : now >= from || now < to;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Weekday extends Cond {
|
||||
private final Set<Integer> days;
|
||||
|
||||
Weekday(Set<Integer> days) {
|
||||
this.days = days;
|
||||
}
|
||||
|
||||
@Override String says() {
|
||||
StringBuilder out = new StringBuilder("в дни: ");
|
||||
List<Integer> sorted = new ArrayList<Integer>(days);
|
||||
java.util.Collections.sort(sorted);
|
||||
for (int i = 0; i < sorted.size(); i++) out.append(i > 0 ? ", " : "").append(DAYS[sorted.get(i).intValue()]);
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
@Override boolean test(Ctx ctx) {
|
||||
return days.contains(Integer.valueOf(ctx.weekday()));
|
||||
}
|
||||
}
|
||||
|
||||
private static final class All extends Cond {
|
||||
private final List<Cond> parts;
|
||||
|
||||
All(List<Cond> parts) {
|
||||
this.parts = parts;
|
||||
}
|
||||
|
||||
@Override String says() {
|
||||
return join(parts, " и ");
|
||||
}
|
||||
|
||||
@Override boolean selects() {
|
||||
for (Cond part : parts) if (part.selects()) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override boolean test(Ctx ctx) {
|
||||
for (Cond part : parts) {
|
||||
if (!part.test(ctx)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Any extends Cond {
|
||||
private final List<Cond> parts;
|
||||
|
||||
Any(List<Cond> parts) {
|
||||
this.parts = parts;
|
||||
}
|
||||
|
||||
@Override String says() {
|
||||
return join(parts, " или ");
|
||||
}
|
||||
|
||||
@Override boolean selects() {
|
||||
for (Cond part : parts) if (!part.selects()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override boolean test(Ctx ctx) {
|
||||
for (Cond part : parts) {
|
||||
if (part.test(ctx)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Not extends Cond {
|
||||
private final Cond inner;
|
||||
|
||||
Not(Cond inner) {
|
||||
this.inner = inner;
|
||||
}
|
||||
|
||||
@Override String says() {
|
||||
return "не " + nested(inner);
|
||||
}
|
||||
|
||||
@Override boolean test(Ctx ctx) {
|
||||
return !inner.test(ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
41
src/lihont/two/plugin/Ctx.java
Normal file
41
src/lihont/two/plugin/Ctx.java
Normal file
@@ -0,0 +1,41 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* What a rule can look at when it runs: one video of the feed, or one name on the screen, plus the moment and the
|
||||
* signed-in account. Every text is lower case and never null, so conditions are plain comparisons. The engine fills
|
||||
* it from TikTok's objects; the tests fill it by hand.
|
||||
*/
|
||||
public interface Ctx {
|
||||
/** The description of the video, lower case. */
|
||||
String text();
|
||||
|
||||
/** The hashtags of the description, lower case, without the #. */
|
||||
Set<String> hashtags();
|
||||
|
||||
/** The public username of the video's author, lower case, or an empty text when TikTok did not say. */
|
||||
String author();
|
||||
|
||||
String authorUid();
|
||||
|
||||
/** The public username of the signed-in account, lower case, or an empty text. */
|
||||
String selfName();
|
||||
|
||||
String selfUid();
|
||||
|
||||
/** For a name on the screen: the id of the account it belongs to; empty for a video. */
|
||||
String uid();
|
||||
|
||||
/** The minute of the local day, 0 to 1439. */
|
||||
int minute();
|
||||
|
||||
/** 1 for Monday to 7 for Sunday. */
|
||||
int weekday();
|
||||
|
||||
/** The local time as HH:mm, for the {time} of a name rule. */
|
||||
String clock();
|
||||
|
||||
/** The local date as dd.MM, for the {date} of a name rule. */
|
||||
String date();
|
||||
}
|
||||
142
src/lihont/two/plugin/Defender.java
Normal file
142
src/lihont/two/plugin/Defender.java
Normal file
@@ -0,0 +1,142 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The defender: reads a plugin that has already been checked and says in plain words what it does and how much
|
||||
* attention it deserves. It only reads; it changes nothing and has no say in whether a plugin works.
|
||||
*
|
||||
* Levels: CALM (nothing that touches what you watch or the account), WATCH (it hides videos, plays sounds or draws over
|
||||
* the app), CAREFUL (it can act for you or touch everything: likes, hides every video, replaces every name, big
|
||||
* picture that cannot be moved).
|
||||
*/
|
||||
public final class Defender {
|
||||
public static final int CALM = 0;
|
||||
public static final int WATCH = 1;
|
||||
public static final int CAREFUL = 2;
|
||||
|
||||
private static final String CANNOT = "Плагин не может: выходить в интернет, читать личные сообщения и пароли, "
|
||||
+ "запускать код. Всё происходит только у вас на экране.";
|
||||
/** For a plugin that downloads files: the one thing it may do online is named, and everything else stays out. */
|
||||
private static final String CANNOT_NET = "Плагин не может: ходить куда-либо, кроме названных сайтов, отправлять туда "
|
||||
+ "что-то о вас, читать личные сообщения и пароли, запускать код. Он только скачивает файлы, "
|
||||
+ "и только после вашего подтверждения.";
|
||||
|
||||
private Defender() {}
|
||||
|
||||
/** What the defender found about one plugin. */
|
||||
public static final class Report {
|
||||
public final int level;
|
||||
/** The lines about risks, most serious first; each starts with its own label. */
|
||||
public final List<String> notes;
|
||||
/** One sentence per rule: what it does. */
|
||||
public final List<String> rules;
|
||||
/** Whether the plugin downloads files, which changes what is said about the internet. */
|
||||
public final boolean net;
|
||||
|
||||
Report(int level, List<String> notes, List<String> rules, boolean net) {
|
||||
this.level = level;
|
||||
this.notes = notes;
|
||||
this.rules = rules;
|
||||
this.net = net;
|
||||
}
|
||||
|
||||
public String verdict() {
|
||||
return level == CAREFUL ? "Осторожно" : level == WATCH ? "Обратите внимание" : "Спокойно";
|
||||
}
|
||||
|
||||
/** Everything for a dialog: the verdict, the notes, the rules in plain words and what a plugin can never do. */
|
||||
public String text() {
|
||||
StringBuilder text = new StringBuilder("Защитник: ").append(verdict()).append('\n');
|
||||
for (String note : notes) text.append("• ").append(note).append('\n');
|
||||
text.append("\nЧто делают правила:\n");
|
||||
for (String rule : rules) text.append("• ").append(rule).append('\n');
|
||||
text.append('\n').append(net ? CANNOT_NET : CANNOT);
|
||||
return text.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static Report check(Plugin plugin) {
|
||||
List<String> careful = new ArrayList<String>();
|
||||
List<String> watch = new ArrayList<String>();
|
||||
List<String> calm = new ArrayList<String>();
|
||||
List<String> rules = new ArrayList<String>();
|
||||
Set<String> seen = new HashSet<String>();
|
||||
|
||||
for (Rule rule : plugin.rules) {
|
||||
rules.add(rule.title + ": " + rule.says());
|
||||
boolean selects = rule.cond != null && rule.cond.selects();
|
||||
for (Act act : rule.acts) {
|
||||
if (act.kind == Act.HIDE) {
|
||||
if (rule.cond == null) {
|
||||
careful.add("Правило «" + rule.title + "» скрывает все видео в ленте без исключений.");
|
||||
} else if (!selects) {
|
||||
careful.add("Правило «" + rule.title + "» скрывает все видео, пока верно условие по времени, дню или аккаунту.");
|
||||
} else if (seen.add("hide")) {
|
||||
watch.add("Скрывает видео из ленты по условиям правил. Что и когда скрыто, видно в журнале плагина.");
|
||||
}
|
||||
} else if (act.kind == Act.REPLACE) {
|
||||
if (!selects) {
|
||||
careful.add("Правило «" + rule.title + "» подменяет все имена на экране на «" + act.text + "».");
|
||||
} else if (seen.add("replace")) {
|
||||
watch.add("Подменяет имя у выбранных аккаунтов: так можно выдать одного человека за другого. Проверьте, у кого.");
|
||||
}
|
||||
} else if (act.kind == Act.PREFIX || act.kind == Act.SUFFIX) {
|
||||
if (seen.add("affix")) calm.add("Дописывает текст к именам, только на вашем экране.");
|
||||
} else if (act.kind == Act.NOTICE) {
|
||||
if (rule.limit > 10 && seen.add("notice")) {
|
||||
watch.add("Показывает подсказки до " + rule.limit + " раз в день.");
|
||||
}
|
||||
} else if (act.kind == Act.DOWNLOAD) {
|
||||
if (seen.add("download")) {
|
||||
watch.add("Скачивает файлы из интернета с сайтов: " + join(plugin.hosts) + ". Работает только когда "
|
||||
+ "вы включите плагину интернет, и каждый адрес сначала покажет вам.");
|
||||
}
|
||||
if (act.download.sha256 == null && seen.add("nohash " + act.download.as)) {
|
||||
watch.add("Файл «" + act.download.as + "» скачивается без проверки по контрольной сумме: "
|
||||
+ "сайт может подменить его на другой.");
|
||||
}
|
||||
} else if (act.kind == Act.OVERLAY) {
|
||||
OverlaySpec spec = act.overlay;
|
||||
if (seen.add("overlay")) watch.add("Показывает картинку поверх приложения.");
|
||||
if (spec.walk != null) {
|
||||
if (seen.add("walk")) watch.add("Картинка сама ходит по экрану и отвлекает.");
|
||||
if (spec.size >= 250) {
|
||||
careful.add("Картинка «" + spec.image + "» большая и ходит по экрану: она закрывает его часть, и её нельзя сдвинуть.");
|
||||
}
|
||||
} else if (!spec.movable && spec.size >= 200) {
|
||||
careful.add("Картинка «" + spec.image + "» большая и закреплена: её нельзя сдвинуть, она закрывает часть экрана.");
|
||||
} else if (spec.size >= 300 && seen.add("big")) {
|
||||
watch.add("Большая картинка закрывает часть экрана.");
|
||||
}
|
||||
if (spec.tap.contains(OverlaySpec.TAP_SOUND) && seen.add("sound")) {
|
||||
watch.add("Играет звук, когда вы нажимаете на картинку.");
|
||||
}
|
||||
if (spec.tap.contains(OverlaySpec.TAP_LIKE) && seen.add("like")) {
|
||||
careful.add("Ставит лайк видео на главной ленте, когда вы нажимаете на картинку плагина. "
|
||||
+ "Это действие аккаунта: случайное нажатие тоже поставит лайк.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!plugin.assets.isEmpty()) {
|
||||
calm.add("Файлов внутри: " + plugin.assets.size() + ". Тип каждого проверен по первым байтам, они входят в хэш.");
|
||||
}
|
||||
if (plugin.license.length() == 0) calm.add("Автор не указал лицензию плагина.");
|
||||
List<String> notes = new ArrayList<String>();
|
||||
for (String note : careful) notes.add("Осторожно: " + note);
|
||||
for (String note : watch) notes.add("Внимание: " + note);
|
||||
notes.addAll(calm);
|
||||
return new Report(careful.isEmpty() ? (watch.isEmpty() ? CALM : WATCH) : CAREFUL, notes, rules,
|
||||
!plugin.hosts.isEmpty());
|
||||
}
|
||||
|
||||
private static String join(List<String> items) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (int i = 0; i < items.size(); i++) out.append(i > 0 ? ", " : "").append(items.get(i));
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
89
src/lihont/two/plugin/DownloadSpec.java
Normal file
89
src/lihont/two/plugin/DownloadSpec.java
Normal file
@@ -0,0 +1,89 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The action "download": a file (a picture or a sound) the plugin wants from a site it named in its manifest. It is
|
||||
* data like everything else in a plugin: the address is written out in full, never built from anything on the phone, so
|
||||
* nothing about the person or the account can travel in it.
|
||||
*
|
||||
* {"download": {"url": "https://cdn.example.com/cat.png", "as": "cat.png", "sha256": "<64 hex digits>"}}
|
||||
*
|
||||
* url https only, the host must be listed in the manifest's "net": {"hosts": [...]}, no port, no login in it
|
||||
* as the name the file gets (the same names as assets/); the plugin's pictures and sounds point at it
|
||||
* sha256 optional: the file is kept only if it has exactly this hash, so the server cannot swap it later
|
||||
*
|
||||
* Nothing is fetched until the person has switched the plugin's internet on and confirmed this very address.
|
||||
*/
|
||||
public final class DownloadSpec {
|
||||
/** A site name: letters, digits and dashes in parts separated by dots, at least two parts. */
|
||||
private static final Pattern HOST = Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+");
|
||||
private static final Pattern ADDRESS_LIKE = Pattern.compile("[0-9.]+");
|
||||
private static final Pattern PATH = Pattern.compile("[A-Za-z0-9._~!$'()*+,;=:@%/-]*(?:\\?[A-Za-z0-9._~!$'()*+,;=:@%/?-]*)?");
|
||||
private static final Pattern HASH = Pattern.compile("[0-9a-f]{64}");
|
||||
|
||||
public static final int MAX_URL = 200;
|
||||
public static final int MAX_HOSTS = 4;
|
||||
public static final int MAX_DOWNLOADS = 4;
|
||||
|
||||
public final String url;
|
||||
public final String host;
|
||||
public final String as;
|
||||
/** Lower-case hex, or null when the plugin does not pin the file. */
|
||||
public final String sha256;
|
||||
|
||||
private DownloadSpec(String url, String host, String as, String sha256) {
|
||||
this.url = url;
|
||||
this.host = host;
|
||||
this.as = as;
|
||||
this.sha256 = sha256;
|
||||
}
|
||||
|
||||
static boolean validHost(String host) {
|
||||
return host.length() <= 253 && HOST.matcher(host).matches() && !ADDRESS_LIKE.matcher(host).matches();
|
||||
}
|
||||
|
||||
static DownloadSpec parse(Object node, String where) throws LtpException {
|
||||
Map<String, Object> map = Fields.map(node, where);
|
||||
for (String key : map.keySet()) {
|
||||
if (!Fields.in(key, "url", "as", "sha256")) throw new LtpException(where + ": у скачивания нет поля «" + key + "»");
|
||||
}
|
||||
String url = Fields.string(map, "url", true, MAX_URL, where);
|
||||
String as = Fields.string(map, "as", true, 40, where);
|
||||
if (!OverlaySpec.validAsset(as)) {
|
||||
throw new LtpException(where + ", «as»: имя файла — строчные латинские буквы, цифры, точка, дефис");
|
||||
}
|
||||
if (OverlaySpec.kind(as).length() == 0) throw new LtpException(where + ", «as»: файл — png, gif, webp, ogg или mp3");
|
||||
String sha = Fields.string(map, "sha256", false, 64, where);
|
||||
if (sha != null && !HASH.matcher(sha).matches()) {
|
||||
throw new LtpException(where + ", «sha256»: нужно 64 цифры и строчные буквы a–f");
|
||||
}
|
||||
return new DownloadSpec(url, hostOf(url, where), as, sha);
|
||||
}
|
||||
|
||||
/** The host of an https address with nothing else odd in it; anything else is refused. */
|
||||
private static String hostOf(String url, String where) throws LtpException {
|
||||
String prefix = "https://";
|
||||
if (!url.startsWith(prefix)) throw new LtpException(where + ", «url»: адрес начинается с https://");
|
||||
String rest = url.substring(prefix.length());
|
||||
int slash = rest.indexOf('/');
|
||||
if (slash < 0) throw new LtpException(where + ", «url»: после сайта нужен путь к файлу");
|
||||
String host = rest.substring(0, slash);
|
||||
if (host.indexOf('@') >= 0 || host.indexOf(':') >= 0) {
|
||||
throw new LtpException(where + ", «url»: в адресе не может быть логина, пароля или порта");
|
||||
}
|
||||
if (!validHost(host)) throw new LtpException(where + ", «url»: «" + host + "» не похоже на имя сайта (строчные буквы, цифры, дефис, точки)");
|
||||
String path = rest.substring(slash);
|
||||
if (path.indexOf('#') >= 0 || !PATH.matcher(path).matches() || path.contains("..")) {
|
||||
throw new LtpException(where + ", «url»: в пути к файлу лишние знаки");
|
||||
}
|
||||
return host.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
/** Whether the person's confirmation of this address can be remembered by this key (the address itself). */
|
||||
String key() {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
79
src/lihont/two/plugin/Downloader.java
Normal file
79
src/lihont/two/plugin/Downloader.java
Normal file
@@ -0,0 +1,79 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
/**
|
||||
* Fetches the one file of a "download" action. It is deliberately small and strict: one GET to the exact address the
|
||||
* plugin wrote down (https only, the host already checked against the manifest), no redirects, no body sent, no
|
||||
* information about the person or the account in it, a size ceiling that is read while the file arrives, and the file
|
||||
* must be a real picture or sound of the kind its name says (and match the hash when the plugin pinned one).
|
||||
*/
|
||||
final class Downloader {
|
||||
static final int MAX_BYTES = PluginPackage.MAX_ASSET;
|
||||
private static final int CONNECT_MS = 8000;
|
||||
private static final int READ_MS = 10000;
|
||||
|
||||
private Downloader() {}
|
||||
|
||||
/** The checked file, or an IOException whose message says in plain words what was wrong. */
|
||||
static byte[] fetch(DownloadSpec spec) throws IOException {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(spec.url).openConnection();
|
||||
try {
|
||||
connection.setInstanceFollowRedirects(false);
|
||||
connection.setUseCaches(false);
|
||||
connection.setConnectTimeout(CONNECT_MS);
|
||||
connection.setReadTimeout(READ_MS);
|
||||
connection.setRequestMethod("GET");
|
||||
connection.setRequestProperty("User-Agent", "LihonT-Plugin/1");
|
||||
connection.setRequestProperty("Accept-Encoding", "identity");
|
||||
int status = connection.getResponseCode();
|
||||
if (status >= 300 && status < 400) throw new IOException("сайт отправил на другой адрес, а это не разрешено");
|
||||
if (status != 200) throw new IOException("сайт ответил кодом " + status);
|
||||
if (!spec.host.equalsIgnoreCase(connection.getURL().getHost())) throw new IOException("адрес изменился");
|
||||
long announced = connection.getContentLengthLong();
|
||||
if (announced > MAX_BYTES) throw new IOException("файл больше " + (MAX_BYTES / 1024) + " КБ");
|
||||
return verify(spec, read(connection.getInputStream()));
|
||||
} finally {
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] read(InputStream stream) throws IOException {
|
||||
try (InputStream in = stream; ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
byte[] chunk = new byte[4096];
|
||||
for (int count; (count = in.read(chunk)) > 0; ) {
|
||||
if (out.size() + count > MAX_BYTES) throw new IOException("файл больше " + (MAX_BYTES / 1024) + " КБ");
|
||||
out.write(chunk, 0, count);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
/** The checks every downloaded file passes before it is kept; also what the tests call. */
|
||||
static byte[] verify(DownloadSpec spec, byte[] data) throws IOException {
|
||||
if (data.length == 0) throw new IOException("файл пустой");
|
||||
if (data.length > MAX_BYTES) throw new IOException("файл больше " + (MAX_BYTES / 1024) + " КБ");
|
||||
if (!PluginPackage.matchesKind(spec.as, data)) throw new IOException("это не тот тип файла, что назван в имени «" + spec.as + "»");
|
||||
if (spec.sha256 != null && !spec.sha256.equals(sha256(data))) {
|
||||
throw new IOException("контрольная сумма не совпала: файл на сайте не тот, что описан в плагине");
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
static String sha256(byte[] data) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(data);
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (byte b : digest) out.append(String.format("%02x", b & 0xff));
|
||||
return out.toString();
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new IllegalStateException(impossible);
|
||||
}
|
||||
}
|
||||
}
|
||||
57
src/lihont/two/plugin/Evaluator.java
Normal file
57
src/lihont/two/plugin/Evaluator.java
Normal file
@@ -0,0 +1,57 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Runs the rules of one plugin against one moment. Pure: it changes nothing and remembers nothing. */
|
||||
public final class Evaluator {
|
||||
static final int MAX_NAME = 80;
|
||||
|
||||
private Evaluator() {}
|
||||
|
||||
/** The first rule that hides the video, or null. */
|
||||
public static Rule hidingRule(Plugin plugin, Ctx ctx) {
|
||||
for (Rule rule : plugin.rules) {
|
||||
if (rule.when.equals(Rule.FEED) && rule.hides() && rule.applies(ctx)) return rule;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Every rule of the trigger whose condition holds now (the engine shows the notices among them). */
|
||||
public static List<Rule> matching(Plugin plugin, String trigger, Ctx ctx) {
|
||||
List<Rule> found = new ArrayList<Rule>();
|
||||
for (Rule rule : plugin.rules) {
|
||||
if (rule.when.equals(trigger) && rule.applies(ctx)) found.add(rule);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The name after the name rules of the plugin; the same text when none applies. */
|
||||
public static String rename(Plugin plugin, Ctx ctx, String name) {
|
||||
String result = name;
|
||||
for (Rule rule : plugin.rules) {
|
||||
if (!rule.when.equals(Rule.NAME) || !rule.applies(ctx)) continue;
|
||||
for (Act act : rule.acts) {
|
||||
if (act.kind == Act.PREFIX) result = expand(act.text, result, ctx) + result;
|
||||
else if (act.kind == Act.SUFFIX) result = result + expand(act.text, result, ctx);
|
||||
else if (act.kind == Act.REPLACE) result = expand(act.text, result, ctx);
|
||||
}
|
||||
}
|
||||
if (result.length() > MAX_NAME) result = result.substring(0, MAX_NAME);
|
||||
return result;
|
||||
}
|
||||
|
||||
static String expand(String template, String name, Ctx ctx) {
|
||||
if (template.indexOf('{') < 0) return template;
|
||||
return template.replace("{name}", name).replace("{time}", ctx.clock()).replace("{date}", ctx.date());
|
||||
}
|
||||
|
||||
/** The texts of the notice actions of a rule. */
|
||||
public static List<String> notices(Rule rule) {
|
||||
List<String> texts = new ArrayList<String>();
|
||||
for (Act act : rule.acts) {
|
||||
if (act.kind == Act.NOTICE) texts.add(act.text);
|
||||
}
|
||||
return texts;
|
||||
}
|
||||
}
|
||||
74
src/lihont/two/plugin/Fields.java
Normal file
74
src/lihont/two/plugin/Fields.java
Normal file
@@ -0,0 +1,74 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/** Typed reads of a parsed JSON tree; every failure is a message the author of the plugin can act on. */
|
||||
final class Fields {
|
||||
private Fields() {}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static Map<String, Object> map(Object node, String where) throws LtpException {
|
||||
if (!(node instanceof Map)) throw new LtpException(where + ": нужен объект {…}");
|
||||
return (Map<String, Object>) node;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static List<Object> list(Object node, String where) throws LtpException {
|
||||
if (!(node instanceof List)) throw new LtpException(where + ": нужен список […]");
|
||||
return (List<Object>) node;
|
||||
}
|
||||
|
||||
/** A text without control characters, at most `max` characters; null when the field is missing and optional. */
|
||||
static String string(Map<String, Object> from, String key, boolean required, int max, String where)
|
||||
throws LtpException {
|
||||
Object value = from.get(key);
|
||||
if (value == null) {
|
||||
if (required) throw new LtpException(where + ": нет поля «" + key + "»");
|
||||
return null;
|
||||
}
|
||||
return text(value, max, where + ", поле «" + key + "»");
|
||||
}
|
||||
|
||||
static String text(Object value, int max, String where) throws LtpException {
|
||||
if (!(value instanceof String)) throw new LtpException(where + ": нужен текст");
|
||||
String text = (String) value;
|
||||
if (text.length() > max) throw new LtpException(where + ": не длиннее " + max + " символов");
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
if (text.charAt(i) < 0x20) throw new LtpException(where + ": управляющие символы запрещены");
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/** A non-empty list of non-empty texts, lower case. */
|
||||
static List<String> words(Object node, int maxItems, int maxLen, String where) throws LtpException {
|
||||
List<Object> items = list(node, where);
|
||||
if (items.isEmpty()) throw new LtpException(where + ": список пуст");
|
||||
if (items.size() > maxItems) throw new LtpException(where + ": не больше " + maxItems + " значений");
|
||||
List<String> out = new ArrayList<String>();
|
||||
for (Object item : items) {
|
||||
String word = text(item, maxLen, where).trim().toLowerCase(Locale.ROOT);
|
||||
if (word.length() == 0) throw new LtpException(where + ": пустое значение");
|
||||
out.add(word);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static boolean in(String value, String... options) {
|
||||
for (String option : options) {
|
||||
if (option.equals(value)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static int integer(Object value, int min, int max, String where) throws LtpException {
|
||||
if (!(value instanceof Double)) throw new LtpException(where + ": нужно число");
|
||||
double number = ((Double) value).doubleValue();
|
||||
if (number != Math.rint(number) || number < min || number > max) {
|
||||
throw new LtpException(where + ": целое от " + min + " до " + max);
|
||||
}
|
||||
return (int) number;
|
||||
}
|
||||
}
|
||||
47
src/lihont/two/plugin/Journal.java
Normal file
47
src/lihont/two/plugin/Journal.java
Normal file
@@ -0,0 +1,47 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* What the plugins did since the app started: the last lines per plugin, so the person can see why a video vanished
|
||||
* or a name changed. In memory only, bounded, and never holds more than a short line per event.
|
||||
*/
|
||||
public final class Journal {
|
||||
private static final int LINES = 40;
|
||||
private static final Map<String, ArrayDeque<String>> BY_PLUGIN = new HashMap<String, ArrayDeque<String>>();
|
||||
private static final Map<String, Integer> COUNT = new HashMap<String, Integer>();
|
||||
|
||||
private Journal() {}
|
||||
|
||||
public static synchronized void add(String plugin, String line) {
|
||||
ArrayDeque<String> lines = BY_PLUGIN.get(plugin);
|
||||
if (lines == null) {
|
||||
lines = new ArrayDeque<String>();
|
||||
BY_PLUGIN.put(plugin, lines);
|
||||
}
|
||||
String clock = new SimpleDateFormat("HH:mm:ss", Locale.ROOT).format(new Date());
|
||||
lines.addFirst(clock + " " + (line.length() > 120 ? line.substring(0, 120) : line));
|
||||
while (lines.size() > LINES) lines.removeLast();
|
||||
Integer seen = COUNT.get(plugin);
|
||||
COUNT.put(plugin, Integer.valueOf(seen == null ? 1 : seen.intValue() + 1));
|
||||
}
|
||||
|
||||
/** The lines of a plugin, newest first. */
|
||||
public static synchronized List<String> lines(String plugin) {
|
||||
ArrayDeque<String> lines = BY_PLUGIN.get(plugin);
|
||||
return lines == null ? new ArrayList<String>() : new ArrayList<String>(lines);
|
||||
}
|
||||
|
||||
/** How many things the plugin has done since the app started. */
|
||||
public static synchronized int count(String plugin) {
|
||||
Integer seen = COUNT.get(plugin);
|
||||
return seen == null ? 0 : seen.intValue();
|
||||
}
|
||||
}
|
||||
171
src/lihont/two/plugin/Json.java
Normal file
171
src/lihont/two/plugin/Json.java
Normal file
@@ -0,0 +1,171 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A strict JSON reader for plugin files: nothing but the standard syntax, a depth limit and a size limit, and it
|
||||
* never builds anything but maps, lists, strings, numbers, booleans and null. Written here instead of using
|
||||
* 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 {
|
||||
static final int MAX_DEPTH = 24;
|
||||
static final int MAX_CHARS = 256 * 1024;
|
||||
|
||||
/** The JSON null. */
|
||||
static final Object NULL = new Object();
|
||||
|
||||
private final String text;
|
||||
private int at;
|
||||
|
||||
private Json(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
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);
|
||||
reader.space();
|
||||
if (reader.at != reader.text.length()) throw reader.fail("после JSON есть лишнее");
|
||||
return value;
|
||||
}
|
||||
|
||||
private LtpException fail(String what) {
|
||||
return new LtpException("В plugin.json ошибка рядом с позицией " + at + ": " + what);
|
||||
}
|
||||
|
||||
private void space() {
|
||||
while (at < text.length()) {
|
||||
char c = text.charAt(at);
|
||||
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') at++;
|
||||
else break;
|
||||
}
|
||||
}
|
||||
|
||||
private Object value(int depth) throws LtpException {
|
||||
if (depth > MAX_DEPTH) throw fail("слишком глубокая вложенность");
|
||||
space();
|
||||
if (at >= text.length()) throw fail("файл оборвался");
|
||||
char c = text.charAt(at);
|
||||
if (c == '{') return object(depth);
|
||||
if (c == '[') return array(depth);
|
||||
if (c == '"') return string();
|
||||
if (c == '-' || (c >= '0' && c <= '9')) return number();
|
||||
if (text.startsWith("true", at)) {
|
||||
at += 4;
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
if (text.startsWith("false", at)) {
|
||||
at += 5;
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
if (text.startsWith("null", at)) {
|
||||
at += 4;
|
||||
return NULL;
|
||||
}
|
||||
throw fail("непонятный символ «" + c + "»");
|
||||
}
|
||||
|
||||
private Map<String, Object> object(int depth) throws LtpException {
|
||||
Map<String, Object> map = new LinkedHashMap<String, Object>();
|
||||
at++;
|
||||
space();
|
||||
if (at < text.length() && text.charAt(at) == '}') {
|
||||
at++;
|
||||
return map;
|
||||
}
|
||||
while (true) {
|
||||
space();
|
||||
if (at >= text.length() || text.charAt(at) != '"') throw fail("ожидалось имя поля в кавычках");
|
||||
String key = string();
|
||||
space();
|
||||
if (at >= text.length() || text.charAt(at) != ':') throw fail("ожидалось «:»");
|
||||
at++;
|
||||
if (map.containsKey(key)) throw fail("поле «" + key + "» повторяется");
|
||||
map.put(key, value(depth + 1));
|
||||
space();
|
||||
if (at >= text.length()) throw fail("файл оборвался");
|
||||
char c = text.charAt(at++);
|
||||
if (c == '}') return map;
|
||||
if (c != ',') throw fail("ожидалось «,» или «}»");
|
||||
}
|
||||
}
|
||||
|
||||
private List<Object> array(int depth) throws LtpException {
|
||||
List<Object> list = new ArrayList<Object>();
|
||||
at++;
|
||||
space();
|
||||
if (at < text.length() && text.charAt(at) == ']') {
|
||||
at++;
|
||||
return list;
|
||||
}
|
||||
while (true) {
|
||||
list.add(value(depth + 1));
|
||||
if (list.size() > 4096) throw fail("слишком длинный список");
|
||||
space();
|
||||
if (at >= text.length()) throw fail("файл оборвался");
|
||||
char c = text.charAt(at++);
|
||||
if (c == ']') return list;
|
||||
if (c != ',') throw fail("ожидалось «,» или «]»");
|
||||
}
|
||||
}
|
||||
|
||||
private String string() throws LtpException {
|
||||
StringBuilder out = new StringBuilder();
|
||||
at++;
|
||||
while (true) {
|
||||
if (at >= text.length()) throw fail("строка не закрыта");
|
||||
char c = text.charAt(at++);
|
||||
if (c == '"') return out.toString();
|
||||
if (c < 0x20) throw fail("в строке управляющий символ");
|
||||
if (c != '\\') {
|
||||
out.append(c);
|
||||
continue;
|
||||
}
|
||||
if (at >= text.length()) throw fail("строка не закрыта");
|
||||
char e = text.charAt(at++);
|
||||
switch (e) {
|
||||
case '"': out.append('"'); break;
|
||||
case '\\': out.append('\\'); break;
|
||||
case '/': out.append('/'); break;
|
||||
case 'b': out.append('\b'); break;
|
||||
case 'f': out.append('\f'); break;
|
||||
case 'n': out.append('\n'); break;
|
||||
case 'r': out.append('\r'); break;
|
||||
case 't': out.append('\t'); break;
|
||||
case 'u':
|
||||
if (at + 4 > text.length()) throw fail("обрыв в \\u");
|
||||
try {
|
||||
out.append((char) Integer.parseInt(text.substring(at, at + 4), 16));
|
||||
} catch (NumberFormatException bad) {
|
||||
throw fail("неверный \\u");
|
||||
}
|
||||
at += 4;
|
||||
break;
|
||||
default:
|
||||
throw fail("неверное экранирование");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Double number() throws LtpException {
|
||||
int start = at;
|
||||
if (text.charAt(at) == '-') at++;
|
||||
while (at < text.length()) {
|
||||
char c = text.charAt(at);
|
||||
if ((c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-') at++;
|
||||
else break;
|
||||
}
|
||||
try {
|
||||
double value = Double.parseDouble(text.substring(start, at));
|
||||
if (Double.isNaN(value) || Double.isInfinite(value)) throw fail("неверное число");
|
||||
return Double.valueOf(value);
|
||||
} catch (NumberFormatException bad) {
|
||||
throw fail("неверное число");
|
||||
}
|
||||
}
|
||||
}
|
||||
10
src/lihont/two/plugin/LtpException.java
Normal file
10
src/lihont/two/plugin/LtpException.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
/** A plugin that cannot be read or is not allowed; the message is written for the person who picked the file. */
|
||||
public final class LtpException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public LtpException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
182
src/lihont/two/plugin/OverlaySpec.java
Normal file
182
src/lihont/two/plugin/OverlaySpec.java
Normal file
@@ -0,0 +1,182 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The action "overlay": a picture the person sees in a corner of the app, which they can drag and tap. It is data like
|
||||
* everything in a plugin: the picture and the sound are files of the plugin (assets/), and the only things a tap can
|
||||
* do are the three listed here, each behind its own right.
|
||||
*
|
||||
* {"overlay": {"image": "cat.gif", "size": 140, "alpha": 100, "right": 16, "bottom": 16, "movable": true,
|
||||
* "tap": ["animate", "sound", "like"], "sound": "meow.ogg", "pet": "pet.gif", "animate_ms": 1250}}
|
||||
*
|
||||
* image picture of the plugin (png, gif, webp); a gif moves while it is animated
|
||||
* size width in dp, 40 to 400 (default 140); the height follows the picture
|
||||
* alpha opacity in percent, 10 to 100 (default 100)
|
||||
* right/bottom distance from the corner in dp (default 16); the person can drag it, and the place is remembered
|
||||
* movable false pins it (default true)
|
||||
* tap what a tap does, any of: "animate" (the gif plays), "sound" (needs "sound"; right ui.sound),
|
||||
* "like" (a like on the video that is on the screen, only on the home feed; right feed.like)
|
||||
* sound sound of the plugin (ogg or mp3)
|
||||
* pet second picture shown when the person strokes the top half of the first one back and forth;
|
||||
* it counts as a tap
|
||||
* animate_ms how long the gif plays after a tap, 200 to 10000 (default 1250)
|
||||
* walk {"mode": "bounce" | "wander", "speed": 10..300 dp/s (default 40), "flip": true}: the picture walks along
|
||||
* the bottom of the screen by itself, turning at the edges (bounce) or at random with pauses (wander);
|
||||
* while it walks it cannot be dragged, and taps on it still work
|
||||
*/
|
||||
public final class OverlaySpec {
|
||||
public static final String TAP_ANIMATE = "animate";
|
||||
public static final String TAP_SOUND = "sound";
|
||||
public static final String TAP_LIKE = "like";
|
||||
public static final String WALK_BOUNCE = "bounce";
|
||||
public static final String WALK_WANDER = "wander";
|
||||
|
||||
private static final Pattern ASSET = Pattern.compile("[a-z0-9][a-z0-9._-]{0,39}");
|
||||
|
||||
public final String image;
|
||||
public final int size;
|
||||
public final int alpha;
|
||||
public final int right;
|
||||
public final int bottom;
|
||||
public final boolean movable;
|
||||
public final List<String> tap;
|
||||
/** Null when there is no sound. */
|
||||
public final String sound;
|
||||
/** Null when there is no stroking picture. */
|
||||
public final String pet;
|
||||
public final int animateMs;
|
||||
/** How the picture walks along the screen ("bounce" or "wander"), or null when it stays where it is. */
|
||||
public final String walk;
|
||||
/** Walking speed in dp per second (10 to 300); 0 when the picture does not walk. */
|
||||
public final int walkSpeed;
|
||||
/** Whether the picture turns to face the way it walks. */
|
||||
public final boolean walkFlip;
|
||||
|
||||
private OverlaySpec(String image, int size, int alpha, int right, int bottom, boolean movable, List<String> tap,
|
||||
String sound, String pet, int animateMs, String walk, int walkSpeed, boolean walkFlip) {
|
||||
this.walk = walk;
|
||||
this.walkSpeed = walkSpeed;
|
||||
this.walkFlip = walkFlip;
|
||||
this.image = image;
|
||||
this.size = size;
|
||||
this.alpha = alpha;
|
||||
this.right = right;
|
||||
this.bottom = bottom;
|
||||
this.movable = movable;
|
||||
this.tap = Collections.unmodifiableList(tap);
|
||||
this.sound = sound;
|
||||
this.pet = pet;
|
||||
this.animateMs = animateMs;
|
||||
}
|
||||
|
||||
static boolean validAsset(String name) {
|
||||
return ASSET.matcher(name).matches();
|
||||
}
|
||||
|
||||
static OverlaySpec parse(Object node, String where) throws LtpException {
|
||||
Map<String, Object> map = Fields.map(node, where);
|
||||
for (String key : map.keySet()) {
|
||||
if (!Fields.in(key, "image", "size", "alpha", "right", "bottom", "movable", "tap", "sound", "pet", "animate_ms",
|
||||
"walk")) {
|
||||
throw new LtpException(where + ": у картинки нет поля «" + key + "»");
|
||||
}
|
||||
}
|
||||
String image = asset(map, "image", true, where);
|
||||
String sound = asset(map, "sound", false, where);
|
||||
String pet = asset(map, "pet", false, where);
|
||||
int size = map.get("size") == null ? 140 : Fields.integer(map.get("size"), 40, 400, where + ", «size»");
|
||||
int alpha = map.get("alpha") == null ? 100 : Fields.integer(map.get("alpha"), 10, 100, where + ", «alpha»");
|
||||
int right = map.get("right") == null ? 16 : Fields.integer(map.get("right"), 0, 2000, where + ", «right»");
|
||||
int bottom = map.get("bottom") == null ? 16 : Fields.integer(map.get("bottom"), 0, 2000, where + ", «bottom»");
|
||||
int animate = map.get("animate_ms") == null ? 1250 : Fields.integer(map.get("animate_ms"), 200, 10000, where + ", «animate_ms»");
|
||||
boolean movable = true;
|
||||
if (map.get("movable") != null) {
|
||||
if (!(map.get("movable") instanceof Boolean)) throw new LtpException(where + ", «movable»: нужно true или false");
|
||||
movable = ((Boolean) map.get("movable")).booleanValue();
|
||||
}
|
||||
List<String> tap = new ArrayList<String>();
|
||||
if (map.get("tap") == null) {
|
||||
tap.add(TAP_ANIMATE);
|
||||
} else {
|
||||
for (Object item : Fields.list(map.get("tap"), where + ", «tap»")) {
|
||||
String what = Fields.text(item, 12, where + ", «tap»");
|
||||
if (!Fields.in(what, TAP_ANIMATE, TAP_SOUND, TAP_LIKE)) {
|
||||
throw new LtpException(where + ", «tap»: можно animate, sound и like, а не «" + what + "»");
|
||||
}
|
||||
if (tap.contains(what)) throw new LtpException(where + ", «tap»: «" + what + "» названо дважды");
|
||||
tap.add(what);
|
||||
}
|
||||
}
|
||||
if (tap.contains(TAP_SOUND) && sound == null) {
|
||||
throw new LtpException(where + ": тап «sound» просит звук, а поля «sound» нет");
|
||||
}
|
||||
if (sound != null && !tap.contains(TAP_SOUND)) {
|
||||
throw new LtpException(where + ": звук «sound» задан, но в «tap» нет «sound»");
|
||||
}
|
||||
String walk = null;
|
||||
int walkSpeed = 0;
|
||||
boolean walkFlip = true;
|
||||
if (map.get("walk") != null) {
|
||||
Map<String, Object> w = Fields.map(map.get("walk"), where + ", «walk»");
|
||||
for (String key : w.keySet()) {
|
||||
if (!Fields.in(key, "mode", "speed", "flip")) throw new LtpException(where + ", «walk»: нет поля «" + key + "»");
|
||||
}
|
||||
walk = Fields.string(w, "mode", true, 10, where + ", «walk»");
|
||||
if (!Fields.in(walk, WALK_BOUNCE, WALK_WANDER)) {
|
||||
throw new LtpException(where + ", «walk»: режим — bounce (туда-сюда) или wander (бродит), а не «" + walk + "»");
|
||||
}
|
||||
walkSpeed = w.get("speed") == null ? 40 : Fields.integer(w.get("speed"), 10, 300, where + ", «walk», «speed»");
|
||||
if (w.get("flip") != null) {
|
||||
if (!(w.get("flip") instanceof Boolean)) throw new LtpException(where + ", «walk», «flip»: нужно true или false");
|
||||
walkFlip = ((Boolean) w.get("flip")).booleanValue();
|
||||
}
|
||||
// a picture that walks cannot be dragged: where it is belongs to the plugin
|
||||
movable = false;
|
||||
}
|
||||
return new OverlaySpec(image, size, alpha, right, bottom, movable, tap, sound, pet, animate, walk, walkSpeed, walkFlip);
|
||||
}
|
||||
|
||||
private static String asset(Map<String, Object> map, String key, boolean required, String where) throws LtpException {
|
||||
String name = Fields.string(map, key, required, 40, where);
|
||||
if (name == null) return null;
|
||||
if (!ASSET.matcher(name).matches()) {
|
||||
throw new LtpException(where + ", «" + key + "»: имя файла — строчные латинские буквы, цифры, точка, дефис");
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/** The files of the plugin this spec points at. */
|
||||
List<String> files() {
|
||||
List<String> files = new ArrayList<String>();
|
||||
files.add(image);
|
||||
if (sound != null) files.add(sound);
|
||||
if (pet != null) files.add(pet);
|
||||
return files;
|
||||
}
|
||||
|
||||
/** Fails when a file it points at is not in the plugin; `assets` null means "not known here". */
|
||||
void check(Set<String> assets, String where) throws LtpException {
|
||||
if (assets == null) return;
|
||||
for (String file : files()) {
|
||||
if (!assets.contains(file)) throw new LtpException(where + ": в плагине нет файла assets/" + file);
|
||||
}
|
||||
String kind = kind(image);
|
||||
if (!"image".equals(kind)) throw new LtpException(where + ": «image» — это png, gif или webp");
|
||||
if (pet != null && !"image".equals(kind(pet))) throw new LtpException(where + ": «pet» — это png, gif или webp");
|
||||
if (sound != null && !"sound".equals(kind(sound))) throw new LtpException(where + ": «sound» — это ogg или mp3");
|
||||
}
|
||||
|
||||
/** "image", "sound" or "" by the extension of an asset name. */
|
||||
static String kind(String name) {
|
||||
String lower = name.toLowerCase(java.util.Locale.ROOT);
|
||||
if (lower.endsWith(".png") || lower.endsWith(".gif") || lower.endsWith(".webp")) return "image";
|
||||
if (lower.endsWith(".ogg") || lower.endsWith(".mp3")) return "sound";
|
||||
return "";
|
||||
}
|
||||
}
|
||||
51
src/lihont/two/plugin/Permission.java
Normal file
51
src/lihont/two/plugin/Permission.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* What a plugin may ask for. A plugin is data, not code, so these are the only things it can ever do; it must name
|
||||
* each one in its manifest, the person approves the list when the plugin is installed, and an action whose right
|
||||
* is missing from the list is refused when the file is read.
|
||||
*/
|
||||
public final class Permission {
|
||||
public static final String FEED_HIDE = "feed.hide";
|
||||
public static final String NAMES = "names";
|
||||
public static final String NOTICE = "ui.notice";
|
||||
public static final String OVERLAY = "ui.overlay";
|
||||
public static final String SOUND = "ui.sound";
|
||||
public static final String LIKE = "feed.like";
|
||||
public static final String NET_DOWNLOAD = "net.download";
|
||||
|
||||
private static final Map<String, String> TEXT = new LinkedHashMap<String, String>();
|
||||
|
||||
static {
|
||||
TEXT.put(FEED_HIDE, "Скрывать видео в ленте по правилам плагина");
|
||||
TEXT.put(NAMES, "Менять имена, которые вы видите (только у вас на экране)");
|
||||
TEXT.put(NOTICE, "Показывать короткие подсказки");
|
||||
TEXT.put(OVERLAY, "Показывать свою картинку поверх приложения (её можно двигать)");
|
||||
TEXT.put(SOUND, "Проигрывать звук плагина, когда вы нажимаете на его картинку");
|
||||
TEXT.put(LIKE, "Ставить лайк видео на главной ленте, когда вы нажимаете на картинку плагина");
|
||||
TEXT.put(NET_DOWNLOAD, "Скачивать картинки и звуки с названных сайтов (включается отдельным переключателем, "
|
||||
+ "каждый адрес вы подтверждаете)");
|
||||
}
|
||||
|
||||
private Permission() {}
|
||||
|
||||
public static boolean known(String name) {
|
||||
return TEXT.containsKey(name);
|
||||
}
|
||||
|
||||
/** The sentence the install dialog shows for a right. */
|
||||
public static String describe(String name) {
|
||||
String text = TEXT.get(name);
|
||||
return text == null ? name : text;
|
||||
}
|
||||
|
||||
public static List<String> all() {
|
||||
return Collections.unmodifiableList(Arrays.asList(TEXT.keySet().toArray(new String[0])));
|
||||
}
|
||||
}
|
||||
245
src/lihont/two/plugin/Plugin.java
Normal file
245
src/lihont/two/plugin/Plugin.java
Normal file
@@ -0,0 +1,245 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A plugin: the parsed and checked plugin.json of an .ltp file. There is no code in it; it holds who made it, which
|
||||
* rights it asks for, and rules. See docs/plugins.md for the format.
|
||||
*
|
||||
* {"ltp": 1, "id": "author.name", "name": "...", "version": "1.0", "author": "...", "description": "...",
|
||||
* "permissions": ["feed.hide"], "rules": [{"title": "...", "when": "feed.item", "if": {...}, "do": [{...}]}]}
|
||||
*/
|
||||
public final class Plugin {
|
||||
/** The format this build reads. A file with a higher number needs a newer LihonT. */
|
||||
public static final int FORMAT = 1;
|
||||
public static final int MAX_RULES = 32;
|
||||
public static final int MAX_LICENSE = 40;
|
||||
public static final int MAX_AI = 4;
|
||||
public static final int MAX_AI_TEXT = 60;
|
||||
|
||||
private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9._-]{2,63}");
|
||||
private static final Pattern VERSION = Pattern.compile("[0-9A-Za-z._-]{1,16}");
|
||||
|
||||
public final String id;
|
||||
public final String name;
|
||||
public final String version;
|
||||
public final String author;
|
||||
public final String description;
|
||||
public final List<String> permissions;
|
||||
public final List<Rule> rules;
|
||||
/** SHA-256 of plugin.json and of every file of the plugin: what the person approved; a changed file has to be approved again. */
|
||||
public final String sha256;
|
||||
/** The names of the files in assets/ that the plugin carries. */
|
||||
public final Set<String> assets;
|
||||
/** The sites the plugin may download from (right net.download); empty for a plugin that never goes online. */
|
||||
public final List<String> hosts;
|
||||
/** What the author says the plugin is licensed under ("MIT", "VCBFU-2", …); empty when they say nothing. */
|
||||
public final String license;
|
||||
/** The AI models the author says helped write it; empty when none are named. Said by the author, not checked. */
|
||||
public final List<String> ai;
|
||||
|
||||
private Plugin(String id, String name, String version, String author, String description,
|
||||
List<String> permissions, List<Rule> rules, String sha256, Set<String> assets, List<String> hosts,
|
||||
String license, List<String> ai) {
|
||||
this.license = license;
|
||||
this.ai = Collections.unmodifiableList(ai);
|
||||
this.hosts = Collections.unmodifiableList(hosts);
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.version = version;
|
||||
this.author = author;
|
||||
this.description = description;
|
||||
this.permissions = Collections.unmodifiableList(permissions);
|
||||
this.rules = Collections.unmodifiableList(rules);
|
||||
this.sha256 = sha256;
|
||||
this.assets = Collections.unmodifiableSet(assets);
|
||||
}
|
||||
|
||||
/** A plugin without files of its own. */
|
||||
public static Plugin parse(byte[] bytes) throws LtpException {
|
||||
return parse(bytes, new LinkedHashMap<String, byte[]>());
|
||||
}
|
||||
|
||||
/** `files` are the plugin's assets by name; they take part in the hash and are what the pictures point at. */
|
||||
public static Plugin parse(byte[] bytes, Map<String, byte[]> files) throws LtpException {
|
||||
if (bytes == null || bytes.length == 0) throw new LtpException("Файл plugin.json пуст");
|
||||
if (bytes.length > Json.MAX_CHARS) throw new LtpException("plugin.json больше 256 КБ");
|
||||
String text;
|
||||
try {
|
||||
text = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString();
|
||||
} catch (CharacterCodingException bad) {
|
||||
throw new LtpException("plugin.json не в кодировке UTF-8");
|
||||
}
|
||||
Map<String, Object> root = Fields.map(Json.parse(text), "plugin.json");
|
||||
|
||||
Object format = root.get("ltp");
|
||||
if (format == null) throw new LtpException("plugin.json: нет поля «ltp» (номер формата)");
|
||||
int number = Fields.integer(format, 1, 1000, "plugin.json, «ltp»");
|
||||
if (number > FORMAT) throw new LtpException("Плагин сделан для формата " + number
|
||||
+ ", а эта версия LihonT читает формат " + FORMAT + ": обновите мод");
|
||||
|
||||
String id = Fields.string(root, "id", true, 64, "plugin.json");
|
||||
if (!ID.matcher(id).matches()) {
|
||||
throw new LtpException("plugin.json: id — латинские строчные буквы, цифры, точка, дефис, подчёркивание, от 3 до 64 знаков");
|
||||
}
|
||||
String name = Fields.string(root, "name", true, 40, "plugin.json").trim();
|
||||
String author = Fields.string(root, "author", true, 40, "plugin.json").trim();
|
||||
String version = Fields.string(root, "version", true, 16, "plugin.json");
|
||||
if (name.length() == 0 || author.length() == 0) throw new LtpException("plugin.json: имя и автор не могут быть пустыми");
|
||||
if (!VERSION.matcher(version).matches()) throw new LtpException("plugin.json: версия — буквы, цифры, точка, дефис");
|
||||
String description = Fields.string(root, "description", false, 240, "plugin.json");
|
||||
if (description == null) description = "";
|
||||
String license = Fields.string(root, "license", false, MAX_LICENSE, "plugin.json");
|
||||
license = license == null ? "" : license.trim();
|
||||
List<String> ai = new ArrayList<String>();
|
||||
if (root.get("ai") != null) {
|
||||
List<Object> named = Fields.list(root.get("ai"), "plugin.json, «ai»");
|
||||
if (named.size() > MAX_AI) throw new LtpException("plugin.json, «ai»: не больше " + MAX_AI + " записей");
|
||||
for (Object item : named) {
|
||||
String model = Fields.text(item, MAX_AI_TEXT, "plugin.json, «ai»").trim();
|
||||
if (model.length() == 0) throw new LtpException("plugin.json, «ai»: пустая запись");
|
||||
ai.add(model);
|
||||
}
|
||||
}
|
||||
|
||||
List<String> permissions = new ArrayList<String>();
|
||||
for (Object item : Fields.list(root.get("permissions") == null ? new ArrayList<Object>() : root.get("permissions"),
|
||||
"plugin.json, «permissions»")) {
|
||||
String right = Fields.text(item, 32, "plugin.json, «permissions»");
|
||||
if (!Permission.known(right)) throw new LtpException("Неизвестное право «" + right + "»: плагин для более новой версии?");
|
||||
if (permissions.contains(right)) throw new LtpException("Право «" + right + "» названо дважды");
|
||||
permissions.add(right);
|
||||
}
|
||||
|
||||
List<Object> raw = Fields.list(root.get("rules"), "plugin.json, «rules»");
|
||||
if (raw.isEmpty()) throw new LtpException("В плагине нет правил");
|
||||
if (raw.size() > MAX_RULES) throw new LtpException("В плагине больше " + MAX_RULES + " правил");
|
||||
List<Rule> rules = new ArrayList<Rule>();
|
||||
for (int i = 0; i < raw.size(); i++) rules.add(Rule.parse(raw.get(i), i, permissions));
|
||||
|
||||
for (String right : permissions) {
|
||||
boolean used = false;
|
||||
for (Rule rule : rules) used = used || rule.uses(right);
|
||||
if (!used) throw new LtpException("Плагин просит право «" + right + "», но не использует его");
|
||||
}
|
||||
Set<String> names = new java.util.TreeSet<String>(files.keySet());
|
||||
List<String> hosts = checkNet(root.get("net"), permissions, rules, names);
|
||||
Set<String> known = new java.util.TreeSet<String>(names);
|
||||
for (Rule rule : rules) {
|
||||
for (DownloadSpec download : rule.downloads()) known.add(download.as);
|
||||
}
|
||||
for (Rule rule : rules) {
|
||||
for (OverlaySpec spec : rule.overlays()) spec.check(known, "Правило «" + rule.title + "»");
|
||||
}
|
||||
return new Plugin(id, name, version, author, description, permissions, rules, sha256(bytes, files), names, hosts,
|
||||
license, ai);
|
||||
}
|
||||
|
||||
/**
|
||||
* The "net" part of the manifest: {"hosts": ["cdn.example.com"]}. It is there exactly when the plugin has the right
|
||||
* net.download, lists every site its downloads go to and no other, and the files it downloads have names of their
|
||||
* own (not those of its assets and not each other's).
|
||||
*/
|
||||
private static List<String> checkNet(Object node, List<String> permissions, List<Rule> rules, Set<String> assets)
|
||||
throws LtpException {
|
||||
boolean right = permissions.contains(Permission.NET_DOWNLOAD);
|
||||
if (node != null && !right) throw new LtpException("plugin.json: есть «net», но нет права «net.download»");
|
||||
List<DownloadSpec> downloads = new ArrayList<DownloadSpec>();
|
||||
for (Rule rule : rules) downloads.addAll(rule.downloads());
|
||||
if (!right) return new ArrayList<String>();
|
||||
if (node == null) throw new LtpException("plugin.json: право «net.download» требует поле «net» со списком сайтов");
|
||||
Map<String, Object> net = Fields.map(node, "plugin.json, «net»");
|
||||
for (String key : net.keySet()) {
|
||||
if (!key.equals("hosts")) throw new LtpException("plugin.json, «net»: нет поля «" + key + "»");
|
||||
}
|
||||
List<String> hosts = new ArrayList<String>();
|
||||
for (Object item : Fields.list(net.get("hosts"), "plugin.json, «net», «hosts»")) {
|
||||
String host = Fields.text(item, 253, "plugin.json, «net», «hosts»");
|
||||
if (!DownloadSpec.validHost(host)) {
|
||||
throw new LtpException("plugin.json, «net»: «" + host + "» не похоже на имя сайта (строчные буквы, цифры, дефис, точки)");
|
||||
}
|
||||
if (hosts.contains(host)) throw new LtpException("plugin.json, «net»: сайт «" + host + "» назван дважды");
|
||||
hosts.add(host);
|
||||
}
|
||||
if (hosts.isEmpty() || hosts.size() > DownloadSpec.MAX_HOSTS) {
|
||||
throw new LtpException("plugin.json, «net»: от 1 до " + DownloadSpec.MAX_HOSTS + " сайтов");
|
||||
}
|
||||
if (downloads.size() > DownloadSpec.MAX_DOWNLOADS) {
|
||||
throw new LtpException("В плагине больше " + DownloadSpec.MAX_DOWNLOADS + " скачиваний");
|
||||
}
|
||||
Set<String> used = new java.util.HashSet<String>();
|
||||
Set<String> as = new java.util.HashSet<String>();
|
||||
for (DownloadSpec download : downloads) {
|
||||
if (!hosts.contains(download.host)) {
|
||||
throw new LtpException("Скачивание с «" + download.host + "»: этого сайта нет в списке «net»");
|
||||
}
|
||||
if (!as.add(download.as)) throw new LtpException("Файл «" + download.as + "» скачивается дважды");
|
||||
if (assets.contains(download.as)) {
|
||||
throw new LtpException("Файл «" + download.as + "» уже есть в плагине, скачать его под этим именем нельзя");
|
||||
}
|
||||
used.add(download.host);
|
||||
}
|
||||
for (String host : hosts) {
|
||||
if (!used.contains(host)) throw new LtpException("Сайт «" + host + "» назван в «net», но с него ничего не скачивается");
|
||||
}
|
||||
return hosts;
|
||||
}
|
||||
|
||||
/** The hash of the manifest alone when there are no files, so a plugin without files keeps the hash it always had. */
|
||||
static String sha256(byte[] bytes, Map<String, byte[]> files) {
|
||||
try {
|
||||
MessageDigest hash = MessageDigest.getInstance("SHA-256");
|
||||
hash.update(bytes);
|
||||
for (Map.Entry<String, byte[]> file : new TreeMap<String, byte[]>(files).entrySet()) {
|
||||
hash.update((byte) 0);
|
||||
hash.update(file.getKey().getBytes(StandardCharsets.UTF_8));
|
||||
hash.update((byte) 0);
|
||||
hash.update(Integer.toString(file.getValue().length).getBytes(StandardCharsets.UTF_8));
|
||||
hash.update((byte) 0);
|
||||
hash.update(file.getValue());
|
||||
}
|
||||
byte[] digest = hash.digest();
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (byte b : digest) out.append(String.format("%02x", b & 0xff));
|
||||
return out.toString();
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new IllegalStateException(impossible);
|
||||
}
|
||||
}
|
||||
|
||||
/** Every file the plugin wants from the internet, in the order of its rules. */
|
||||
public List<DownloadSpec> downloads() {
|
||||
List<DownloadSpec> found = new ArrayList<DownloadSpec>();
|
||||
for (Rule rule : rules) found.addAll(rule.downloads());
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Whether any rule with an overlay picture is in the plugin. */
|
||||
public boolean hasOverlays() {
|
||||
for (Rule rule : rules) {
|
||||
if (!rule.overlays().isEmpty()) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean hasRulesFor(String trigger) {
|
||||
for (Rule rule : rules) {
|
||||
if (rule.when.equals(trigger)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
435
src/lihont/two/plugin/PluginEngine.java
Normal file
435
src/lihont/two/plugin/PluginEngine.java
Normal file
@@ -0,0 +1,435 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
import android.widget.Toast;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import lihont.two.account.CurrentAccount;
|
||||
import lihont.two.widget.AppContext;
|
||||
|
||||
/**
|
||||
* The hooks of the mod call this; it runs the rules of the plugins that are switched on for the signed-in account.
|
||||
*
|
||||
* It is built to be harmless: with no plugin on, every entry point is one volatile read; any failure inside a rule
|
||||
* leaves the video or the name exactly as TikTok made it; the list of active plugins is rebuilt only every few
|
||||
* seconds or when something changes; and a plugin only gets here if the person approved this very file.
|
||||
*/
|
||||
public final class PluginEngine {
|
||||
private static final String TAG = "LIHONT";
|
||||
private static final long FRESH_MS = 3000L;
|
||||
private static final long DAY_MS = 24L * 60 * 60 * 1000;
|
||||
private static final Pattern HASHTAG = Pattern.compile("#([\\p{L}\\p{N}_]{1,60})");
|
||||
|
||||
/** The plugins that are active right now, split by what they hook. */
|
||||
private static final class Snapshot {
|
||||
final String uid;
|
||||
final int version;
|
||||
final long at;
|
||||
final List<Plugin> feed;
|
||||
final List<Plugin> names;
|
||||
final List<Screen> screens;
|
||||
|
||||
Snapshot(String uid, int version, long at, List<Plugin> feed, List<Plugin> names, List<Screen> screens) {
|
||||
this.uid = uid;
|
||||
this.version = version;
|
||||
this.at = at;
|
||||
this.feed = feed;
|
||||
this.names = names;
|
||||
this.screens = screens;
|
||||
}
|
||||
}
|
||||
|
||||
/** An active plugin that has screen rules, with the folder its files are in. */
|
||||
private static final class Screen {
|
||||
final Plugin plugin;
|
||||
final File folder;
|
||||
|
||||
Screen(Plugin plugin, File folder) {
|
||||
this.plugin = plugin;
|
||||
this.folder = folder;
|
||||
}
|
||||
}
|
||||
|
||||
/** A picture a plugin wants on the screen right now. */
|
||||
public static final class Overlay {
|
||||
/** Stable for one picture of one plugin: the manager keeps the view by it. */
|
||||
public final String key;
|
||||
public final Plugin plugin;
|
||||
public final OverlaySpec spec;
|
||||
public final String uid;
|
||||
private final File folder;
|
||||
|
||||
Overlay(String key, Plugin plugin, OverlaySpec spec, String uid, File folder) {
|
||||
this.key = key;
|
||||
this.plugin = plugin;
|
||||
this.spec = spec;
|
||||
this.uid = uid;
|
||||
this.folder = folder;
|
||||
}
|
||||
|
||||
/** A file of the plugin's assets/, or else one the plugin downloaded; the result may not exist (yet). */
|
||||
public File file(String name) {
|
||||
File asset = new File(new File(folder, "assets"), name);
|
||||
return asset.isFile() ? asset : new File(new File(folder, PluginRegistry.DOWNLOADS), name);
|
||||
}
|
||||
}
|
||||
|
||||
/** A file a plugin wants from the internet and does not have yet. */
|
||||
public static final class Pending {
|
||||
public final Plugin plugin;
|
||||
public final DownloadSpec spec;
|
||||
final File folder;
|
||||
|
||||
Pending(Plugin plugin, DownloadSpec spec, File folder) {
|
||||
this.plugin = plugin;
|
||||
this.spec = spec;
|
||||
this.folder = folder;
|
||||
}
|
||||
}
|
||||
|
||||
private static final List<Plugin> NONE = Collections.<Plugin>emptyList();
|
||||
private static final List<Screen> NO_SCREENS = Collections.<Screen>emptyList();
|
||||
private static volatile Snapshot snapshot = new Snapshot("", -1, 0L, NONE, NONE, NO_SCREENS);
|
||||
private static final ThreadLocal<Boolean> BUSY = new ThreadLocal<Boolean>();
|
||||
private static final Map<String, ArrayDeque<Long>> SHOWN = new HashMap<String, ArrayDeque<Long>>();
|
||||
private static final Set<String> LOGGED_NAMES = new HashSet<String>();
|
||||
|
||||
private PluginEngine() {}
|
||||
|
||||
// ---- the state of the engine -----------------------------------------------------------
|
||||
|
||||
private static Snapshot current() {
|
||||
Snapshot now = snapshot;
|
||||
long time = SystemClock.uptimeMillis();
|
||||
if (time - now.at < FRESH_MS && now.version == PluginRegistry.version()) return now;
|
||||
if (BUSY.get() != null) return now;
|
||||
BUSY.set(Boolean.TRUE);
|
||||
try {
|
||||
return rebuild(time);
|
||||
} finally {
|
||||
BUSY.remove();
|
||||
}
|
||||
}
|
||||
|
||||
private static synchronized Snapshot rebuild(long time) {
|
||||
Context context = AppContext.get();
|
||||
if (context == null) return snapshot;
|
||||
String uid = null;
|
||||
List<Plugin> feed = new ArrayList<Plugin>();
|
||||
List<Plugin> names = new ArrayList<Plugin>();
|
||||
List<Screen> screens = new ArrayList<Screen>();
|
||||
int version = PluginRegistry.version();
|
||||
try {
|
||||
uid = CurrentAccount.uid();
|
||||
if (uid != null && !PluginRegistry.safeMode(context)) {
|
||||
for (PluginRegistry.Entry entry : PluginRegistry.entries(context)) {
|
||||
if (entry.plugin == null || !entry.approved || !PluginRegistry.enabled(context, entry.id, uid)) continue;
|
||||
if (entry.plugin.hasRulesFor(Rule.FEED)) feed.add(entry.plugin);
|
||||
if (entry.plugin.hasRulesFor(Rule.NAME)) names.add(entry.plugin);
|
||||
if (entry.plugin.hasRulesFor(Rule.SCREEN)) screens.add(new Screen(entry.plugin, entry.folder));
|
||||
}
|
||||
}
|
||||
if (!feed.isEmpty() || !names.isEmpty() || !screens.isEmpty()) PluginRegistry.started(context);
|
||||
} catch (Throwable unreadable) {
|
||||
feed.clear();
|
||||
names.clear();
|
||||
screens.clear();
|
||||
}
|
||||
snapshot = new Snapshot(uid == null ? "" : uid, version, time, feed, names, screens);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/** Whether any plugin hooks the feed right now (asked once per page, before the items). */
|
||||
public static boolean feedActive() {
|
||||
try {
|
||||
return !current().feed.isEmpty();
|
||||
} catch (Throwable broken) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the feed ----------------------------------------------------------------------------
|
||||
|
||||
/** True when a rule of an active plugin hides this video. Never throws: a video that cannot be judged stays. */
|
||||
public static boolean hideFeedItem(Object item) {
|
||||
Snapshot state = snapshot;
|
||||
if (state.feed.isEmpty() || item == null) return false;
|
||||
try {
|
||||
AwemeCtx ctx = new AwemeCtx(item, state.uid);
|
||||
boolean hide = false;
|
||||
for (Plugin plugin : state.feed) {
|
||||
for (Rule rule : Evaluator.matching(plugin, Rule.FEED, ctx)) {
|
||||
for (String text : Evaluator.notices(rule)) notice(plugin, rule, text);
|
||||
if (rule.hides() && !hide) {
|
||||
hide = true;
|
||||
Journal.add(plugin.id, "Скрыто видео" + (ctx.author().length() > 0 ? " @" + ctx.author() : "")
|
||||
+ " · «" + rule.title + "»");
|
||||
}
|
||||
}
|
||||
}
|
||||
return hide;
|
||||
} catch (Throwable failure) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- screens -----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The pictures the active plugins want on the screen at this moment. Called whenever a screen of the app comes
|
||||
* to the front; it also shows the hints of the screen rules (at most as often as their limit allows).
|
||||
*/
|
||||
public static List<Overlay> overlays() {
|
||||
List<Overlay> wanted = new ArrayList<Overlay>();
|
||||
try {
|
||||
Snapshot state = current();
|
||||
if (state.screens.isEmpty()) return wanted;
|
||||
ScreenCtx ctx = new ScreenCtx(state.uid);
|
||||
for (Screen screen : state.screens) {
|
||||
int index = 0;
|
||||
for (Rule rule : screen.plugin.rules) {
|
||||
if (!rule.when.equals(Rule.SCREEN) || !rule.applies(ctx)) {
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
for (String text : Evaluator.notices(rule)) notice(screen.plugin, rule, text);
|
||||
int n = 0;
|
||||
for (OverlaySpec spec : rule.overlays()) {
|
||||
wanted.add(new Overlay(screen.plugin.id + "#" + index + "." + n++, screen.plugin, spec,
|
||||
state.uid, screen.folder));
|
||||
}
|
||||
index++;
|
||||
}
|
||||
}
|
||||
} catch (Throwable failure) {
|
||||
wanted.clear();
|
||||
}
|
||||
return wanted;
|
||||
}
|
||||
|
||||
/**
|
||||
* The files that the active plugins' screen rules want and that are not on the phone yet. Only for plugins whose
|
||||
* internet the person switched on; what happens next (the question, the download) is PluginNet's.
|
||||
*/
|
||||
public static List<Pending> pendingDownloads() {
|
||||
List<Pending> wanted = new ArrayList<Pending>();
|
||||
try {
|
||||
Snapshot state = current();
|
||||
if (state.screens.isEmpty()) return wanted;
|
||||
Context context = AppContext.get();
|
||||
if (context == null) return wanted;
|
||||
ScreenCtx ctx = new ScreenCtx(state.uid);
|
||||
for (Screen screen : state.screens) {
|
||||
if (screen.plugin.hosts.isEmpty() || !PluginRegistry.netOn(context, screen.plugin.id)) continue;
|
||||
for (Rule rule : screen.plugin.rules) {
|
||||
if (!rule.when.equals(Rule.SCREEN) || !rule.applies(ctx)) continue;
|
||||
for (DownloadSpec spec : rule.downloads()) {
|
||||
if (!new File(new File(screen.folder, PluginRegistry.DOWNLOADS), spec.as).isFile()) {
|
||||
wanted.add(new Pending(screen.plugin, spec, screen.folder));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Throwable failure) {
|
||||
note("pending downloads failed: " + failure);
|
||||
wanted.clear();
|
||||
}
|
||||
return wanted;
|
||||
}
|
||||
|
||||
// ---- names -------------------------------------------------------------------------------
|
||||
|
||||
/** The name to show for the account `uid`; the same text when no plugin changes it. */
|
||||
public static String name(String uid, String name) {
|
||||
if (name == null || uid == null) return name;
|
||||
try {
|
||||
Snapshot state = current();
|
||||
if (state.names.isEmpty()) return name;
|
||||
NameCtx ctx = new NameCtx(uid, state.uid);
|
||||
String result = name;
|
||||
for (Plugin plugin : state.names) {
|
||||
for (Rule rule : Evaluator.matching(plugin, Rule.NAME, ctx)) {
|
||||
for (String text : Evaluator.notices(rule)) notice(plugin, rule, text);
|
||||
}
|
||||
String renamed = Evaluator.rename(plugin, ctx, result);
|
||||
if (!renamed.equals(result)) logName(plugin, uid, result, renamed);
|
||||
result = renamed;
|
||||
}
|
||||
return result;
|
||||
} catch (Throwable failure) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
private static void logName(Plugin plugin, String uid, String before, String after) {
|
||||
String key = plugin.id + "/" + uid;
|
||||
synchronized (LOGGED_NAMES) {
|
||||
if (LOGGED_NAMES.size() > 200 || !LOGGED_NAMES.add(key)) return;
|
||||
}
|
||||
Journal.add(plugin.id, "Имя «" + before + "» показано как «" + after + "»");
|
||||
}
|
||||
|
||||
// ---- notices -----------------------------------------------------------------------------
|
||||
|
||||
/** Shows a rule's hint, at most `limit` times in a day. */
|
||||
private static void notice(Plugin plugin, Rule rule, final String text) {
|
||||
String key = plugin.id + "#" + rule.title;
|
||||
long now = System.currentTimeMillis();
|
||||
synchronized (SHOWN) {
|
||||
ArrayDeque<Long> times = SHOWN.get(key);
|
||||
if (times == null) {
|
||||
if (SHOWN.size() > 256) return;
|
||||
times = new ArrayDeque<Long>();
|
||||
SHOWN.put(key, times);
|
||||
}
|
||||
while (!times.isEmpty() && now - times.peekFirst().longValue() > DAY_MS) times.removeFirst();
|
||||
if (times.size() >= rule.limit) return;
|
||||
times.addLast(Long.valueOf(now));
|
||||
}
|
||||
final Context context = AppContext.get();
|
||||
if (context == null) return;
|
||||
Journal.add(plugin.id, "Подсказка: " + text);
|
||||
new Handler(Looper.getMainLooper()).post(new Runnable() {
|
||||
@Override public void run() {
|
||||
try {
|
||||
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
|
||||
} catch (Throwable ignored) {
|
||||
// a hint that cannot be shown is simply not shown
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---- what a rule sees ----------------------------------------------------------------------
|
||||
|
||||
private static String lower(String value) {
|
||||
return value == null ? "" : value.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private static Object call(Object target, String method) {
|
||||
if (target == null) return null;
|
||||
try {
|
||||
return target.getClass().getMethod(method).invoke(target);
|
||||
} catch (Throwable missing) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String read(Object target, String method) {
|
||||
Object value = call(target, method);
|
||||
return value instanceof CharSequence ? value.toString() : "";
|
||||
}
|
||||
|
||||
/** The moment and the signed-in account, shared by both kinds of context. */
|
||||
private abstract static class Base implements Ctx {
|
||||
private final String selfUid;
|
||||
private final String selfName;
|
||||
private final int minute;
|
||||
private final int weekday;
|
||||
private final String clock;
|
||||
private final String date;
|
||||
|
||||
Base(String selfUid) {
|
||||
this.selfUid = selfUid == null ? "" : selfUid;
|
||||
String name = "";
|
||||
try {
|
||||
name = lower(CurrentAccount.uniqueId());
|
||||
} catch (Throwable unknown) {
|
||||
// the name stays empty
|
||||
}
|
||||
selfName = name;
|
||||
Calendar now = Calendar.getInstance();
|
||||
minute = now.get(Calendar.HOUR_OF_DAY) * 60 + now.get(Calendar.MINUTE);
|
||||
weekday = ((now.get(Calendar.DAY_OF_WEEK) + 5) % 7) + 1;
|
||||
clock = String.format(Locale.ROOT, "%02d:%02d", now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE));
|
||||
date = String.format(Locale.ROOT, "%02d.%02d", now.get(Calendar.DAY_OF_MONTH), now.get(Calendar.MONTH) + 1);
|
||||
}
|
||||
|
||||
@Override public String selfName() { return selfName; }
|
||||
@Override public String selfUid() { return selfUid; }
|
||||
@Override public int minute() { return minute; }
|
||||
@Override public int weekday() { return weekday; }
|
||||
@Override public String clock() { return clock; }
|
||||
@Override public String date() { return date; }
|
||||
}
|
||||
|
||||
/** A video of the feed (a TikTok Aweme), read through its getters. */
|
||||
private static final class AwemeCtx extends Base {
|
||||
private final String text;
|
||||
private final Set<String> tags = new HashSet<String>();
|
||||
private final String author;
|
||||
private final String authorUid;
|
||||
|
||||
AwemeCtx(Object aweme, String selfUid) {
|
||||
super(selfUid);
|
||||
String description = read(aweme, "getDesc");
|
||||
text = lower(description);
|
||||
Matcher found = HASHTAG.matcher(description);
|
||||
while (found.find()) tags.add(lower(found.group(1)));
|
||||
Object person = call(aweme, "getAuthor");
|
||||
author = lower(read(person, "getUniqueId"));
|
||||
authorUid = lower(read(person, "getUid"));
|
||||
}
|
||||
|
||||
@Override public String text() { return text; }
|
||||
@Override public Set<String> hashtags() { return tags; }
|
||||
@Override public String author() { return author; }
|
||||
@Override public String authorUid() { return authorUid; }
|
||||
@Override public String uid() { return ""; }
|
||||
}
|
||||
|
||||
/** A name on the screen: all that is known is the account it belongs to. */
|
||||
private static final class NameCtx extends Base {
|
||||
private final String uid;
|
||||
|
||||
NameCtx(String uid, String selfUid) {
|
||||
super(selfUid);
|
||||
this.uid = lower(uid);
|
||||
}
|
||||
|
||||
@Override public String text() { return ""; }
|
||||
@Override public Set<String> hashtags() { return Collections.<String>emptySet(); }
|
||||
@Override public String author() { return ""; }
|
||||
@Override public String authorUid() { return ""; }
|
||||
@Override public String uid() { return uid; }
|
||||
}
|
||||
|
||||
/** A screen of the app: only the moment and the account are known. */
|
||||
private static final class ScreenCtx extends Base {
|
||||
ScreenCtx(String selfUid) {
|
||||
super(selfUid);
|
||||
}
|
||||
|
||||
@Override public String text() { return ""; }
|
||||
@Override public Set<String> hashtags() { return Collections.<String>emptySet(); }
|
||||
@Override public String author() { return ""; }
|
||||
@Override public String authorUid() { return ""; }
|
||||
@Override public String uid() { return ""; }
|
||||
}
|
||||
|
||||
/** For the log only. */
|
||||
static void note(String message) {
|
||||
try {
|
||||
Log.i(TAG, "plugins: " + message);
|
||||
} catch (Throwable noLogger) {
|
||||
// diagnostic only
|
||||
}
|
||||
}
|
||||
}
|
||||
161
src/lihont/two/plugin/PluginNet.java
Normal file
161
src/lihont/two/plugin/PluginNet.java
Normal file
@@ -0,0 +1,161 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* The internet of plugins, which is only ever "download this file". A file is fetched when all of this holds: the plugin
|
||||
* is approved and on for the account, the person switched its internet on, and the person said yes to this very address
|
||||
* (the dialog shows the site, the address and what happens; the answer is remembered per plugin and address). Nothing is
|
||||
* sent but the request for the file, and a failure leaves the plugin exactly as it was.
|
||||
*/
|
||||
public final class PluginNet {
|
||||
private static final long RETRY_MS = 10L * 60 * 1000;
|
||||
|
||||
private static final Set<String> BUSY = new HashSet<String>();
|
||||
/**
|
||||
* Where the question is on screen right now. A question put on a screen that closes at once (the splash, a TikTok
|
||||
* screen the person is leaving) goes with it, so it is asked again as soon as that screen is gone.
|
||||
*/
|
||||
private static final Map<String, WeakReference<Activity>> ASKED_ON = new HashMap<String, WeakReference<Activity>>();
|
||||
/** "Не сейчас" or a dismissed question: not asked again until the app starts anew. */
|
||||
private static final Set<String> DECLINED = new HashSet<String>();
|
||||
private static final Map<String, Long> FAILED = new HashMap<String, Long>();
|
||||
private static final ExecutorService POOL = Executors.newSingleThreadExecutor();
|
||||
|
||||
private PluginNet() {}
|
||||
|
||||
private static String key(PluginEngine.Pending want) {
|
||||
return want.plugin.id + "|" + want.spec.url;
|
||||
}
|
||||
|
||||
/** Called on the main thread for every screen that comes to the front; `wanted` are the files still missing. */
|
||||
public static void handle(Activity activity, List<PluginEngine.Pending> wanted) {
|
||||
if (activity == null || activity.isFinishing() || wanted.isEmpty()) return;
|
||||
// the settings of the mod are where the switch lives: no dialog there, it appears on the next screen
|
||||
if (activity.getClass().getName().startsWith("lihont.two.settings.")) return;
|
||||
for (PluginEngine.Pending want : wanted) {
|
||||
String key = key(want);
|
||||
long now = System.currentTimeMillis();
|
||||
synchronized (BUSY) {
|
||||
if (BUSY.contains(key) || DECLINED.contains(key)) continue;
|
||||
Long failed = FAILED.get(key);
|
||||
if (failed != null && now - failed.longValue() < RETRY_MS) continue;
|
||||
}
|
||||
if (PluginRegistry.downloadConfirmed(activity, want.plugin.id, want.spec.url)) {
|
||||
start(activity, want);
|
||||
} else {
|
||||
synchronized (BUSY) {
|
||||
WeakReference<Activity> shownOn = ASKED_ON.get(key);
|
||||
Activity there = shownOn == null ? null : shownOn.get();
|
||||
if (there != null && !there.isFinishing() && !there.isDestroyed()) continue;
|
||||
ASKED_ON.put(key, new WeakReference<Activity>(activity));
|
||||
}
|
||||
PluginEngine.note("asking to download " + key + " on " + activity.getClass().getName());
|
||||
ask(activity, want);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ask(final Activity activity, final PluginEngine.Pending want) {
|
||||
DownloadSpec spec = want.spec;
|
||||
String text = "Сайт: " + spec.host + "\nАдрес: " + spec.url + "\nФайл: " + spec.as + " (не больше "
|
||||
+ (Downloader.MAX_BYTES / 1024) + " КБ)\n"
|
||||
+ (spec.sha256 == null ? "Контрольной суммы нет: проверяется только тип файла.\n"
|
||||
: "Файл проверяется по контрольной сумме из плагина.\n")
|
||||
+ "\nНа сайт уйдёт только запрос этого файла, ничего о вас и вашем аккаунте. "
|
||||
+ "Ответ запомнится для этого адреса; отозвать его можно, выключив плагину интернет.";
|
||||
final String key = key(want);
|
||||
try {
|
||||
new AlertDialog.Builder(activity)
|
||||
.setTitle("«" + want.plugin.name + "» просит скачать файл")
|
||||
.setMessage(text)
|
||||
.setNegativeButton("Не сейчас", (dialog, which) -> decline(key))
|
||||
.setPositiveButton("Скачать", (dialog, which) -> {
|
||||
PluginRegistry.confirmDownload(activity, want.plugin.id, spec.url);
|
||||
start(activity, want);
|
||||
})
|
||||
.setOnCancelListener(dialog -> decline(key))
|
||||
.show();
|
||||
} catch (Throwable cannotShow) {
|
||||
PluginEngine.note("the download question could not be shown: " + cannotShow);
|
||||
synchronized (BUSY) {
|
||||
ASKED_ON.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void decline(String key) {
|
||||
synchronized (BUSY) {
|
||||
DECLINED.add(key);
|
||||
}
|
||||
}
|
||||
|
||||
private static void start(Activity activity, final PluginEngine.Pending want) {
|
||||
final String key = key(want);
|
||||
synchronized (BUSY) {
|
||||
if (!BUSY.add(key)) return;
|
||||
}
|
||||
final Context context = activity.getApplicationContext();
|
||||
final WeakReference<Activity> screen = new WeakReference<Activity>(activity);
|
||||
POOL.execute(new Runnable() {
|
||||
@Override public void run() {
|
||||
boolean done = false;
|
||||
try {
|
||||
byte[] data = Downloader.fetch(want.spec);
|
||||
PluginRegistry.Entry now = PluginRegistry.find(context, want.plugin.id);
|
||||
if (now == null || now.plugin == null || !now.plugin.sha256.equals(want.plugin.sha256)) {
|
||||
throw new IOException("плагин за это время изменился");
|
||||
}
|
||||
File folder = new File(want.folder, PluginRegistry.DOWNLOADS);
|
||||
if (!folder.isDirectory() && !folder.mkdirs()) throw new IOException("нет места для файла");
|
||||
File temporary = new File(folder, want.spec.as + ".tmp");
|
||||
FileOutputStream out = new FileOutputStream(temporary);
|
||||
try {
|
||||
out.write(data);
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
File target = new File(folder, want.spec.as);
|
||||
if (target.exists()) target.delete();
|
||||
if (!temporary.renameTo(target)) throw new IOException("файл не записался");
|
||||
Journal.add(want.plugin.id, "Скачан файл " + want.spec.as + " (" + Math.max(1, data.length / 1024)
|
||||
+ " КБ) с " + want.spec.host);
|
||||
done = true;
|
||||
} catch (Throwable failure) {
|
||||
Journal.add(want.plugin.id, "Не скачан файл " + want.spec.as + ": " + failure.getMessage());
|
||||
synchronized (BUSY) {
|
||||
FAILED.put(key, Long.valueOf(System.currentTimeMillis()));
|
||||
}
|
||||
} finally {
|
||||
synchronized (BUSY) {
|
||||
BUSY.remove(key);
|
||||
}
|
||||
}
|
||||
if (done) {
|
||||
new Handler(Looper.getMainLooper()).post(new Runnable() {
|
||||
@Override public void run() {
|
||||
Activity host = screen.get();
|
||||
if (host != null && !host.isFinishing()) PluginScreen.attach(host);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
164
src/lihont/two/plugin/PluginPackage.java
Normal file
164
src/lihont/two/plugin/PluginPackage.java
Normal file
@@ -0,0 +1,164 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
/**
|
||||
* The inside of an .ltp file: a zip with plugin.json, optionally icon.png, and optionally files in assets/ (pictures
|
||||
* and sounds the plugin's rules point at). Nothing else is accepted (no folders, no other names, no repeats), every
|
||||
* file is checked by its first bytes, and every size is limited while it is read, so a zip bomb or a path trick has
|
||||
* nowhere to go: no file is ever written from an entry name.
|
||||
*/
|
||||
public final class PluginPackage {
|
||||
public static final String MANIFEST = "plugin.json";
|
||||
public static final String ICON = "icon.png";
|
||||
public static final String ASSETS = "assets/";
|
||||
public static final String EXTENSION = ".ltp";
|
||||
/** The file as it lies on the disk. */
|
||||
public static final int MAX_FILE = 1024 * 1024;
|
||||
/** Everything inside, unpacked. */
|
||||
public static final int MAX_UNPACKED = 1536 * 1024;
|
||||
public static final int MAX_ICON = 64 * 1024;
|
||||
public static final int MAX_ASSET = 400 * 1024;
|
||||
public static final int MAX_ASSETS = 8;
|
||||
|
||||
private static final byte[] PNG = {(byte) 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a};
|
||||
|
||||
public final byte[] manifest;
|
||||
/** The icon, or null. */
|
||||
public final byte[] icon;
|
||||
/** The files of assets/ by name, in the order of the zip. */
|
||||
public final Map<String, byte[]> assets;
|
||||
|
||||
private PluginPackage(byte[] manifest, byte[] icon, Map<String, byte[]> assets) {
|
||||
this.manifest = manifest;
|
||||
this.icon = icon;
|
||||
this.assets = assets;
|
||||
}
|
||||
|
||||
public static PluginPackage read(InputStream source) throws LtpException {
|
||||
byte[] manifest = null;
|
||||
byte[] icon = null;
|
||||
Map<String, byte[]> assets = new LinkedHashMap<String, byte[]>();
|
||||
int[] unpacked = {0};
|
||||
try {
|
||||
ZipInputStream zip = new ZipInputStream(new LimitedStream(source, MAX_FILE));
|
||||
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
|
||||
String name = entry.getName();
|
||||
if (entry.isDirectory()) throw new LtpException("В плагине не должно быть папок");
|
||||
if (name.equals(MANIFEST)) {
|
||||
if (manifest != null) throw new LtpException("plugin.json повторяется");
|
||||
manifest = readEntry(zip, Json.MAX_CHARS, unpacked);
|
||||
} else if (name.equals(ICON)) {
|
||||
if (icon != null) throw new LtpException("icon.png повторяется");
|
||||
icon = readEntry(zip, MAX_ICON, unpacked);
|
||||
if (!isPng(icon)) throw new LtpException("icon.png — не PNG");
|
||||
} else if (name.startsWith(ASSETS) && OverlaySpec.validAsset(name.substring(ASSETS.length()))) {
|
||||
String file = name.substring(ASSETS.length());
|
||||
if (assets.containsKey(file)) throw new LtpException("Файл «" + file + "» в плагине повторяется");
|
||||
if (assets.size() >= MAX_ASSETS) throw new LtpException("В плагине больше " + MAX_ASSETS + " файлов в assets/");
|
||||
byte[] data = readEntry(zip, MAX_ASSET, unpacked);
|
||||
if (!matchesKind(file, data)) {
|
||||
throw new LtpException("Файл «" + file + "» не похож на " + describeKind(file)
|
||||
+ ": плагин принимает png, gif, webp, ogg и mp3 только настоящие");
|
||||
}
|
||||
assets.put(file, data);
|
||||
} else {
|
||||
throw new LtpException("В плагине лишний файл «" + (name.length() > 40 ? name.substring(0, 40) : name)
|
||||
+ "»: нужны только plugin.json, icon.png и файлы в assets/");
|
||||
}
|
||||
}
|
||||
} catch (IOException broken) {
|
||||
throw new LtpException("Файл не читается как плагин .ltp (" + broken.getMessage() + ")");
|
||||
}
|
||||
if (manifest == null) throw new LtpException("Это не плагин: в файле нет plugin.json");
|
||||
return new PluginPackage(manifest, icon, assets);
|
||||
}
|
||||
|
||||
private static byte[] readEntry(ZipInputStream zip, int max, int[] unpacked) throws IOException, LtpException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
byte[] chunk = new byte[4096];
|
||||
for (int read; (read = zip.read(chunk)) > 0; ) {
|
||||
if (out.size() + read > max) throw new LtpException("Файл в плагине слишком большой");
|
||||
unpacked[0] += read;
|
||||
if (unpacked[0] > MAX_UNPACKED) throw new LtpException("Плагин слишком большой в распакованном виде");
|
||||
out.write(chunk, 0, read);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static boolean isPng(byte[] data) {
|
||||
return startsWith(data, PNG);
|
||||
}
|
||||
|
||||
private static boolean startsWith(byte[] data, byte[] prefix) {
|
||||
if (data.length < prefix.length) return false;
|
||||
for (int i = 0; i < prefix.length; i++) {
|
||||
if (data[i] != prefix[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static String describeKind(String name) {
|
||||
String lower = name.toLowerCase(java.util.Locale.ROOT);
|
||||
if (lower.endsWith(".png")) return "PNG";
|
||||
if (lower.endsWith(".gif")) return "GIF";
|
||||
if (lower.endsWith(".webp")) return "WebP";
|
||||
if (lower.endsWith(".ogg")) return "Ogg";
|
||||
if (lower.endsWith(".mp3")) return "MP3";
|
||||
return "картинку или звук";
|
||||
}
|
||||
|
||||
/** The extension and the first bytes of an asset agree; any other extension is refused. */
|
||||
static boolean matchesKind(String name, byte[] data) {
|
||||
String lower = name.toLowerCase(java.util.Locale.ROOT);
|
||||
if (lower.endsWith(".png")) return isPng(data);
|
||||
if (lower.endsWith(".gif")) return startsWith(data, new byte[] {'G', 'I', 'F', '8'});
|
||||
if (lower.endsWith(".webp")) {
|
||||
return data.length >= 12 && startsWith(data, new byte[] {'R', 'I', 'F', 'F'})
|
||||
&& data[8] == 'W' && data[9] == 'E' && data[10] == 'B' && data[11] == 'P';
|
||||
}
|
||||
if (lower.endsWith(".ogg")) return startsWith(data, new byte[] {'O', 'g', 'g', 'S'});
|
||||
if (lower.endsWith(".mp3")) {
|
||||
if (startsWith(data, new byte[] {'I', 'D', '3'})) return true;
|
||||
return data.length > 2 && (data[0] & 0xFF) == 0xFF && (data[1] & 0xE0) == 0xE0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Reads at most `limit` bytes of the file itself; a bigger one is refused. */
|
||||
private static final class LimitedStream extends InputStream {
|
||||
private final InputStream inner;
|
||||
private int left;
|
||||
|
||||
LimitedStream(InputStream inner, int limit) {
|
||||
this.inner = inner;
|
||||
this.left = limit;
|
||||
}
|
||||
|
||||
@Override public int read() throws IOException {
|
||||
if (left <= 0) return end();
|
||||
int value = inner.read();
|
||||
if (value >= 0) left--;
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override public int read(byte[] buffer, int offset, int length) throws IOException {
|
||||
if (left <= 0) return end();
|
||||
int read = inner.read(buffer, offset, Math.min(length, left));
|
||||
if (read > 0) left -= read;
|
||||
return read;
|
||||
}
|
||||
|
||||
/** The limit is reached: a file that ends exactly here is fine, one that goes on is too big. */
|
||||
private int end() throws IOException {
|
||||
if (inner.read() >= 0) throw new IOException("файл больше " + (MAX_FILE / 1024) + " КБ");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
410
src/lihont/two/plugin/PluginRegistry.java
Normal file
410
src/lihont/two/plugin/PluginRegistry.java
Normal file
@@ -0,0 +1,410 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The plugins on the phone: the files, which accounts each one works for, what the person approved, and the safe
|
||||
* mode. Plugins live in files/ltp/<id>/ (plugin.json, icon.png and, after an update, prev/ with the version before).
|
||||
*
|
||||
* A plugin runs only when all of this holds: it reads without errors, the person approved exactly this file (its
|
||||
* SHA-256 is remembered, so a file changed afterwards is refused until it is looked at again), it is switched on for
|
||||
* the signed-in account, and the safe mode is off.
|
||||
*/
|
||||
public final class PluginRegistry {
|
||||
private static final String PREFS = "lihont_plugins";
|
||||
private static final String PREVIOUS = "prev";
|
||||
/** The files a plugin fetched itself; they are never part of the approved package. */
|
||||
public static final String DOWNLOADS = "downloads";
|
||||
/** Early deaths in a row after which the next start runs without plugins. */
|
||||
private static final int EARLY_DEATHS = 3;
|
||||
private static final long ALIVE_MS = 20000L;
|
||||
|
||||
/** One plugin folder. */
|
||||
public static final class Entry {
|
||||
public final String id;
|
||||
/** Null when the file cannot be read. */
|
||||
public final Plugin plugin;
|
||||
/** Why it cannot be read; null when it can. */
|
||||
public final String problem;
|
||||
/** The person approved exactly this file. */
|
||||
public final boolean approved;
|
||||
public final boolean hasPrevious;
|
||||
public final File folder;
|
||||
|
||||
Entry(String id, Plugin plugin, String problem, boolean approved, boolean hasPrevious, File folder) {
|
||||
this.id = id;
|
||||
this.plugin = plugin;
|
||||
this.problem = problem;
|
||||
this.approved = approved;
|
||||
this.hasPrevious = hasPrevious;
|
||||
this.folder = folder;
|
||||
}
|
||||
|
||||
/** A file of the plugin's assets/, or null when it is not there. */
|
||||
public File asset(String name) {
|
||||
File file = new File(new File(folder, PluginPackage.ASSETS.substring(0, PluginPackage.ASSETS.length() - 1)), name);
|
||||
return file.isFile() ? file : null;
|
||||
}
|
||||
|
||||
public File icon() {
|
||||
File icon = new File(folder, PluginPackage.ICON);
|
||||
return icon.isFile() ? icon : null;
|
||||
}
|
||||
|
||||
/** A file the plugin downloaded, or null when it has not (yet). */
|
||||
public File downloaded(String name) {
|
||||
File file = new File(new File(folder, DOWNLOADS), name);
|
||||
return file.isFile() ? file : null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A file that was read and checked but is not installed yet; the person looks at it first. */
|
||||
public static final class Review {
|
||||
public final Plugin plugin;
|
||||
public final byte[] manifest;
|
||||
public final byte[] icon;
|
||||
/** The files of the plugin's assets/ by name. */
|
||||
public final Map<String, byte[]> assets;
|
||||
/** The same plugin as it is installed now, or null. */
|
||||
public final Entry existing;
|
||||
|
||||
Review(Plugin plugin, byte[] manifest, byte[] icon, Map<String, byte[]> assets, Entry existing) {
|
||||
this.plugin = plugin;
|
||||
this.manifest = manifest;
|
||||
this.icon = icon;
|
||||
this.assets = assets;
|
||||
this.existing = existing;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Entry> cache;
|
||||
private static int version;
|
||||
private static boolean counted;
|
||||
|
||||
private PluginRegistry() {}
|
||||
|
||||
private static SharedPreferences prefs(Context context) {
|
||||
return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
private static File root(Context context) {
|
||||
File folder = new File(context.getApplicationContext().getFilesDir(), "ltp");
|
||||
if (!folder.isDirectory()) folder.mkdirs();
|
||||
return folder;
|
||||
}
|
||||
|
||||
/** Changes whenever the list or a switch changes, so the engine knows to look again. */
|
||||
public static synchronized int version() {
|
||||
return version;
|
||||
}
|
||||
|
||||
private static synchronized void changed() {
|
||||
cache = null;
|
||||
version++;
|
||||
}
|
||||
|
||||
public static synchronized List<Entry> entries(Context context) {
|
||||
if (cache != null) return cache;
|
||||
List<Entry> found = new ArrayList<Entry>();
|
||||
File[] folders = root(context).listFiles();
|
||||
SharedPreferences prefs = prefs(context);
|
||||
if (folders != null) {
|
||||
for (File folder : folders) {
|
||||
if (!folder.isDirectory()) continue;
|
||||
File file = new File(folder, PluginPackage.MANIFEST);
|
||||
boolean previous = new File(new File(folder, PREVIOUS), PluginPackage.MANIFEST).isFile();
|
||||
try {
|
||||
byte[] bytes = readFile(file, Json.MAX_CHARS);
|
||||
Plugin plugin = Plugin.parse(bytes, readAssets(folder));
|
||||
if (!plugin.id.equals(folder.getName())) throw new LtpException("Папка плагина не совпадает с его id");
|
||||
boolean approved = plugin.sha256.equals(prefs.getString("ok." + plugin.id, ""));
|
||||
found.add(new Entry(plugin.id, plugin, null, approved, previous, folder));
|
||||
} catch (LtpException | IOException broken) {
|
||||
found.add(new Entry(folder.getName(), null, broken.getMessage(), false, previous, folder));
|
||||
}
|
||||
}
|
||||
}
|
||||
Collections.sort(found, (a, b) -> a.id.compareTo(b.id));
|
||||
cache = found;
|
||||
return found;
|
||||
}
|
||||
|
||||
public static synchronized Entry find(Context context, String id) {
|
||||
for (Entry entry : entries(context)) {
|
||||
if (entry.id.equals(id)) return entry;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---- the accounts a plugin works for ----------------------------------------------------
|
||||
|
||||
private static Set<String> accounts(Context context, String id) {
|
||||
String raw = prefs(context).getString("on." + id, "");
|
||||
Set<String> set = new LinkedHashSet<String>();
|
||||
for (String part : raw.split(",")) {
|
||||
if (part.length() > 0) set.add(part);
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
public static boolean enabled(Context context, String id, String uid) {
|
||||
return uid != null && accounts(context, id).contains(uid);
|
||||
}
|
||||
|
||||
/** How many accounts have the plugin on. */
|
||||
public static int accountCount(Context context, String id) {
|
||||
return accounts(context, id).size();
|
||||
}
|
||||
|
||||
public static synchronized void setEnabled(Context context, String id, String uid, boolean on) {
|
||||
if (uid == null || uid.length() == 0 || uid.indexOf(',') >= 0) return;
|
||||
Set<String> set = accounts(context, id);
|
||||
if (on) set.add(uid);
|
||||
else set.remove(uid);
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (String account : set) out.append(out.length() == 0 ? "" : ",").append(account);
|
||||
prefs(context).edit().putString("on." + id, out.toString()).apply();
|
||||
version++;
|
||||
}
|
||||
|
||||
// ---- the internet of a plugin -------------------------------------------------------------
|
||||
|
||||
/** Whether the person switched the plugin's internet on; off until they do, whatever the plugin asks. */
|
||||
public static boolean netOn(Context context, String id) {
|
||||
return prefs(context).getBoolean("net." + id, false);
|
||||
}
|
||||
|
||||
public static synchronized void setNetOn(Context context, String id, boolean on) {
|
||||
prefs(context).edit().putBoolean("net." + id, on).apply();
|
||||
version++;
|
||||
}
|
||||
|
||||
/** Whether the person said yes to downloading exactly this address for this plugin. */
|
||||
public static boolean downloadConfirmed(Context context, String id, String url) {
|
||||
return prefs(context).getStringSet("dl." + id, Collections.<String>emptySet()).contains(url);
|
||||
}
|
||||
|
||||
public static synchronized void confirmDownload(Context context, String id, String url) {
|
||||
Set<String> set = new LinkedHashSet<String>(prefs(context).getStringSet("dl." + id, Collections.<String>emptySet()));
|
||||
set.add(url);
|
||||
prefs(context).edit().putStringSet("dl." + id, set).apply();
|
||||
}
|
||||
|
||||
/** A new or changed file may name other sites: its internet goes off, old answers are forgotten and old files go. */
|
||||
private static void forgetNet(Context context, String id, File folder) {
|
||||
prefs(context).edit().remove("net." + id).remove("dl." + id).apply();
|
||||
deleteTree(new File(folder, DOWNLOADS));
|
||||
}
|
||||
|
||||
// ---- reading, installing, removing -------------------------------------------------------
|
||||
|
||||
/** Reads and checks an .ltp file without installing anything. */
|
||||
public static synchronized Review review(Context context, InputStream source) throws LtpException {
|
||||
PluginPackage pack = PluginPackage.read(source);
|
||||
Plugin plugin = Plugin.parse(pack.manifest, pack.assets);
|
||||
return new Review(plugin, pack.manifest, pack.icon, pack.assets, find(context, plugin.id));
|
||||
}
|
||||
|
||||
/** Installs what the person looked at, remembers that they approved this exact file, and turns it on for `uid`. */
|
||||
public static synchronized void install(Context context, Review review, String uid) throws IOException {
|
||||
File folder = new File(root(context), review.plugin.id);
|
||||
File previous = new File(folder, PREVIOUS);
|
||||
if (new File(folder, PluginPackage.MANIFEST).isFile()) {
|
||||
deleteTree(previous);
|
||||
previous.mkdirs();
|
||||
copy(new File(folder, PluginPackage.MANIFEST), new File(previous, PluginPackage.MANIFEST));
|
||||
File oldIcon = new File(folder, PluginPackage.ICON);
|
||||
if (oldIcon.isFile()) copy(oldIcon, new File(previous, PluginPackage.ICON));
|
||||
copyAssets(folder, previous);
|
||||
}
|
||||
folder.mkdirs();
|
||||
write(new File(folder, PluginPackage.MANIFEST), review.manifest);
|
||||
File assetDir = new File(folder, "assets");
|
||||
deleteTree(assetDir);
|
||||
if (!review.assets.isEmpty()) {
|
||||
assetDir.mkdirs();
|
||||
for (Map.Entry<String, byte[]> asset : review.assets.entrySet()) {
|
||||
write(new File(assetDir, asset.getKey()), asset.getValue());
|
||||
}
|
||||
}
|
||||
File icon = new File(folder, PluginPackage.ICON);
|
||||
if (review.icon != null) write(icon, review.icon);
|
||||
else if (icon.isFile()) icon.delete();
|
||||
forgetNet(context, review.plugin.id, folder);
|
||||
prefs(context).edit().putString("ok." + review.plugin.id, review.plugin.sha256).apply();
|
||||
if (uid != null) setEnabled(context, review.plugin.id, uid, true);
|
||||
changed();
|
||||
}
|
||||
|
||||
/** The person looked at a file that changed after the first approval and accepts it. */
|
||||
public static synchronized void approve(Context context, Entry entry) {
|
||||
if (entry.plugin == null) return;
|
||||
forgetNet(context, entry.id, entry.folder);
|
||||
prefs(context).edit().putString("ok." + entry.id, entry.plugin.sha256).apply();
|
||||
changed();
|
||||
}
|
||||
|
||||
public static synchronized void remove(Context context, String id) {
|
||||
deleteTree(new File(root(context), id));
|
||||
prefs(context).edit().remove("ok." + id).remove("on." + id).remove("net." + id).remove("dl." + id).apply();
|
||||
changed();
|
||||
}
|
||||
|
||||
/** Puts the version before the last update back; false when there is none. */
|
||||
public static synchronized boolean rollback(Context context, String id) {
|
||||
File folder = new File(root(context), id);
|
||||
File previous = new File(folder, PREVIOUS);
|
||||
File old = new File(previous, PluginPackage.MANIFEST);
|
||||
if (!old.isFile()) return false;
|
||||
try {
|
||||
byte[] bytes = readFile(old, Json.MAX_CHARS);
|
||||
Plugin plugin = Plugin.parse(bytes, readAssets(previous));
|
||||
if (!plugin.id.equals(id)) return false;
|
||||
write(new File(folder, PluginPackage.MANIFEST), bytes);
|
||||
deleteTree(new File(folder, "assets"));
|
||||
copyAssets(previous, folder);
|
||||
File oldIcon = new File(previous, PluginPackage.ICON);
|
||||
File icon = new File(folder, PluginPackage.ICON);
|
||||
if (oldIcon.isFile()) copy(oldIcon, icon);
|
||||
else if (icon.isFile()) icon.delete();
|
||||
deleteTree(previous);
|
||||
forgetNet(context, id, folder);
|
||||
prefs(context).edit().putString("ok." + id, plugin.sha256).apply();
|
||||
changed();
|
||||
return true;
|
||||
} catch (LtpException | IOException failed) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- safe mode --------------------------------------------------------------------------
|
||||
|
||||
/** Called when the first plugin rule is about to run in this process. */
|
||||
public static synchronized void started(final Context context) {
|
||||
if (counted) return;
|
||||
counted = true;
|
||||
final SharedPreferences prefs = prefs(context);
|
||||
int early = prefs.getInt("early", 0);
|
||||
SharedPreferences.Editor edit = prefs.edit().putInt("early", early + 1);
|
||||
if (early >= EARLY_DEATHS) edit.putBoolean("safe", true);
|
||||
edit.apply();
|
||||
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
|
||||
@Override public void run() {
|
||||
prefs.edit().putInt("early", 0).apply();
|
||||
}
|
||||
}, ALIVE_MS);
|
||||
}
|
||||
|
||||
/** True after the app died soon after its start several times in a row with plugins on: plugins stay off. */
|
||||
public static boolean safeMode(Context context) {
|
||||
return prefs(context).getBoolean("safe", false);
|
||||
}
|
||||
|
||||
public static synchronized void leaveSafeMode(Context context) {
|
||||
prefs(context).edit().putBoolean("safe", false).putInt("early", 0).apply();
|
||||
version++;
|
||||
}
|
||||
|
||||
// ---- files ------------------------------------------------------------------------------
|
||||
|
||||
private static byte[] readFile(File file, int max) throws IOException {
|
||||
if (!file.isFile() || file.length() > max) throw new IOException("нет файла или он слишком большой");
|
||||
byte[] data = new byte[(int) file.length()];
|
||||
InputStream in = new FileInputStream(file);
|
||||
try {
|
||||
int at = 0;
|
||||
while (at < data.length) {
|
||||
int read = in.read(data, at, data.length - at);
|
||||
if (read < 0) break;
|
||||
at += read;
|
||||
}
|
||||
if (at != data.length) throw new IOException("файл оборван");
|
||||
} finally {
|
||||
in.close();
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
private static void write(File file, byte[] data) throws IOException {
|
||||
File temporary = new File(file.getParentFile(), file.getName() + ".tmp");
|
||||
FileOutputStream out = new FileOutputStream(temporary);
|
||||
try {
|
||||
out.write(data);
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
if (file.exists() && !file.delete()) throw new IOException("не заменить " + file.getName());
|
||||
if (!temporary.renameTo(file)) throw new IOException("не записать " + file.getName());
|
||||
}
|
||||
|
||||
/** The files of a plugin folder's assets/ by name; a name or a size outside the rules makes the plugin unreadable. */
|
||||
private static Map<String, byte[]> readAssets(File folder) throws IOException, LtpException {
|
||||
Map<String, byte[]> found = new LinkedHashMap<String, byte[]>();
|
||||
File[] files = new File(folder, "assets").listFiles();
|
||||
if (files == null) return found;
|
||||
java.util.Arrays.sort(files);
|
||||
for (File file : files) {
|
||||
if (!file.isFile() || !OverlaySpec.validAsset(file.getName()) || found.size() >= PluginPackage.MAX_ASSETS) {
|
||||
throw new LtpException("В папке плагина лишний файл «" + file.getName() + "»");
|
||||
}
|
||||
found.put(file.getName(), readFile(file, PluginPackage.MAX_ASSET));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
private static void copyAssets(File from, File to) throws IOException {
|
||||
File[] files = new File(from, "assets").listFiles();
|
||||
if (files == null) return;
|
||||
File target = new File(to, "assets");
|
||||
target.mkdirs();
|
||||
for (File file : files) {
|
||||
if (file.isFile()) copy(file, new File(target, file.getName()));
|
||||
}
|
||||
}
|
||||
|
||||
private static void copy(File from, File to) throws IOException {
|
||||
write(to, readFile(from, PluginPackage.MAX_ASSET));
|
||||
}
|
||||
|
||||
private static void deleteTree(File file) {
|
||||
File[] children = file.listFiles();
|
||||
if (children != null) {
|
||||
for (File child : children) deleteTree(child);
|
||||
}
|
||||
file.delete();
|
||||
}
|
||||
|
||||
/** The bytes of a stream, for a picked file (kept here so the screen does not need the limits). */
|
||||
public static byte[] bytes(InputStream in) throws IOException {
|
||||
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
|
||||
byte[] chunk = new byte[4096];
|
||||
for (int read; (read = in.read(chunk)) > 0; ) {
|
||||
if (out.size() + read > PluginPackage.MAX_FILE + 1) throw new IOException("файл больше "
|
||||
+ (PluginPackage.MAX_FILE / 1024) + " КБ");
|
||||
out.write(chunk, 0, read);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
/** A reader over bytes already in memory. */
|
||||
public static InputStream stream(byte[] data) {
|
||||
return new ByteArrayInputStream(data);
|
||||
}
|
||||
}
|
||||
566
src/lihont/two/plugin/PluginScreen.java
Normal file
566
src/lihont/two/plugin/PluginScreen.java
Normal file
@@ -0,0 +1,566 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.SharedPreferences;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.ImageDecoder;
|
||||
import android.graphics.drawable.AnimatedImageDrawable;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.media.MediaPlayer;
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.util.Log;
|
||||
import android.view.Gravity;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.ImageView;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import lihont.two.bar.BottomBar;
|
||||
|
||||
/**
|
||||
* Draws the pictures of the plugins' "overlay" actions over the screens of the app (see OverlaySpec for what a plugin
|
||||
* may ask). The pictures belong to the plugin, the person can drag them, and a tap does only what the plugin named
|
||||
* and the person approved: play the gif, play a sound, like the video on the home feed.
|
||||
*
|
||||
* It follows the screens: every time a screen of the app comes to the front the wanted pictures are asked from the
|
||||
* engine, pictures nobody wants any more (the plugin was switched off, or the account changed) are taken away, and
|
||||
* the remaining ones move to the screen that is in front.
|
||||
*/
|
||||
public final class PluginScreen {
|
||||
private static final String TAG = "LIHONT";
|
||||
private static final String PREFS = "lihont_plugins";
|
||||
private static final int PET_MS = 2200;
|
||||
private static final int PET_LIFT_DP = 28;
|
||||
private static final int PET_REVERSALS = 3;
|
||||
private static final int PET_STEP_DP = 8;
|
||||
private static final int PET_DRIFT_DP = 40;
|
||||
private static final int DRAG_DP = 10;
|
||||
|
||||
private static final Map<String, Instance> INSTANCES = new HashMap<String, Instance>();
|
||||
|
||||
private PluginScreen() {}
|
||||
|
||||
/** Called for every screen of the app that comes to the front. Never throws. */
|
||||
public static void attach(Activity activity) {
|
||||
try {
|
||||
sync(activity);
|
||||
} catch (Throwable failure) {
|
||||
note("overlay failed: " + failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static void sync(Activity activity) {
|
||||
if (activity == null || activity.isFinishing()) return;
|
||||
if (Looper.myLooper() != Looper.getMainLooper()) return;
|
||||
List<PluginEngine.Overlay> wanted = PluginEngine.overlays();
|
||||
try {
|
||||
PluginNet.handle(activity, PluginEngine.pendingDownloads());
|
||||
} catch (Throwable failure) {
|
||||
note("download check failed: " + failure);
|
||||
}
|
||||
Set<String> keep = new HashSet<String>();
|
||||
for (PluginEngine.Overlay overlay : wanted) keep.add(overlay.key);
|
||||
for (Iterator<Map.Entry<String, Instance>> it = INSTANCES.entrySet().iterator(); it.hasNext(); ) {
|
||||
Map.Entry<String, Instance> entry = it.next();
|
||||
if (!keep.contains(entry.getKey())) {
|
||||
entry.getValue().remove();
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
// The settings of the mod stay free: a picture there could cover the switch that turns it off.
|
||||
if (activity.getClass().getName().startsWith("lihont.two.settings.")) return;
|
||||
for (PluginEngine.Overlay overlay : wanted) {
|
||||
Instance instance = INSTANCES.get(overlay.key);
|
||||
if (instance != null && !instance.overlay.plugin.sha256.equals(overlay.plugin.sha256)) {
|
||||
instance.remove();
|
||||
instance = null;
|
||||
}
|
||||
if (instance == null) {
|
||||
instance = new Instance(overlay);
|
||||
INSTANCES.put(overlay.key, instance);
|
||||
}
|
||||
instance.show(activity);
|
||||
}
|
||||
}
|
||||
|
||||
private static void note(String message) {
|
||||
try {
|
||||
Log.i(TAG, "plugins: " + message);
|
||||
} catch (Throwable noLogger) {
|
||||
// diagnostic only
|
||||
}
|
||||
}
|
||||
|
||||
/** One picture of one plugin. */
|
||||
private static final class Instance {
|
||||
final PluginEngine.Overlay overlay;
|
||||
final OverlaySpec spec;
|
||||
final Handler ui = new Handler(Looper.getMainLooper());
|
||||
|
||||
Activity host;
|
||||
ImageView view;
|
||||
ImageView petView;
|
||||
MediaPlayer player;
|
||||
boolean animating;
|
||||
int petSession;
|
||||
int rightPx = -1;
|
||||
int bottomPx = -1;
|
||||
|
||||
Instance(PluginEngine.Overlay overlay) {
|
||||
this.overlay = overlay;
|
||||
this.spec = overlay.spec;
|
||||
}
|
||||
|
||||
// ---- on the screen -----------------------------------------------------------------
|
||||
|
||||
void show(Activity activity) {
|
||||
if (host == activity && view != null && view.getParent() != null) return;
|
||||
detach();
|
||||
File imageFile = overlay.file(spec.image);
|
||||
if (!imageFile.isFile()) return;
|
||||
View decorView = activity.getWindow() == null ? null : activity.getWindow().getDecorView();
|
||||
if (!(decorView instanceof ViewGroup)) return;
|
||||
ViewGroup decor = (ViewGroup) decorView;
|
||||
float density = activity.getResources().getDisplayMetrics().density;
|
||||
loadPosition(activity, density);
|
||||
|
||||
ImageView picture = new ImageView(activity);
|
||||
picture.setAdjustViewBounds(true);
|
||||
picture.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
Drawable drawable = decode(activity, imageFile);
|
||||
if (drawable == null) return;
|
||||
picture.setImageDrawable(drawable);
|
||||
picture.setAlpha(spec.alpha / 100f);
|
||||
picture.setClickable(true);
|
||||
int width = Math.round(spec.size * density);
|
||||
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
|
||||
params.rightMargin = rightPx;
|
||||
params.bottomMargin = bottomPx;
|
||||
picture.setLayoutParams(params);
|
||||
|
||||
ImageView pet = null;
|
||||
if (spec.pet != null && overlay.file(spec.pet).isFile()) {
|
||||
pet = new ImageView(activity);
|
||||
pet.setAdjustViewBounds(true);
|
||||
pet.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
pet.setAlpha(spec.alpha / 100f);
|
||||
pet.setClickable(false);
|
||||
pet.setFocusable(false);
|
||||
pet.setVisibility(View.GONE);
|
||||
FrameLayout.LayoutParams petParams = new FrameLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
petParams.gravity = Gravity.BOTTOM | Gravity.RIGHT;
|
||||
petParams.rightMargin = rightPx;
|
||||
petParams.bottomMargin = bottomPx + Math.round(PET_LIFT_DP * density);
|
||||
pet.setLayoutParams(petParams);
|
||||
}
|
||||
|
||||
Touch touch = new Touch(picture, pet, params, density);
|
||||
picture.setOnTouchListener(touch);
|
||||
decor.addView(picture);
|
||||
if (pet != null) decor.addView(pet);
|
||||
view = picture;
|
||||
petView = pet;
|
||||
host = activity;
|
||||
Journal.add(overlay.plugin.id, "Картинка «" + spec.image + "» на экране " + shortName(activity));
|
||||
if (spec.walk != null) startWalking(decor, width, density);
|
||||
}
|
||||
|
||||
// ---- walking -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The picture walks along the bottom of the screen by itself: it starts at its place at the right, goes left
|
||||
* and turns at the edges ("bounce"), or turns and stops at random ("wander"). Only the translation of the view
|
||||
* changes, so no layout pass is needed, and the loop ends by itself when the picture leaves the screen.
|
||||
*/
|
||||
private void startWalking(final ViewGroup decor, final int widthPx, final float density) {
|
||||
final ImageView picture = view;
|
||||
if (picture == null) return;
|
||||
final boolean wander = OverlaySpec.WALK_WANDER.equals(spec.walk);
|
||||
final java.util.Random random = new java.util.Random();
|
||||
final float[] state = {0f, -1f}; // x, direction
|
||||
final long[] clock = {0L, 0L}; // last frame, paused until (milliseconds)
|
||||
picture.postOnAnimation(new Runnable() {
|
||||
@Override public void run() {
|
||||
if (view != picture || picture.getParent() == null) return;
|
||||
long now = android.view.animation.AnimationUtils.currentAnimationTimeMillis();
|
||||
float seconds = clock[0] == 0L ? 0f : Math.min(now - clock[0], 64L) / 1000f;
|
||||
clock[0] = now;
|
||||
float limit = Math.max(0f, decor.getWidth() - widthPx - Math.max(rightPx, 0));
|
||||
if (now >= clock[1]) {
|
||||
state[0] += state[1] * spec.walkSpeed * density * seconds;
|
||||
if (state[0] <= -limit) {
|
||||
state[0] = -limit;
|
||||
state[1] = 1f;
|
||||
} else if (state[0] >= 0f) {
|
||||
state[0] = 0f;
|
||||
state[1] = -1f;
|
||||
}
|
||||
if (wander && random.nextInt(240) == 0) {
|
||||
if (random.nextBoolean()) state[1] = -state[1];
|
||||
else clock[1] = now + 600L + random.nextInt(2000);
|
||||
}
|
||||
}
|
||||
picture.setTranslationX(state[0]);
|
||||
if (petView != null) petView.setTranslationX(state[0]);
|
||||
if (spec.walkFlip) {
|
||||
float face = state[1] < 0f ? -1f : 1f; // the art looks right; it is mirrored on the way left
|
||||
picture.setScaleX(face);
|
||||
if (petView != null) petView.setScaleX(face);
|
||||
}
|
||||
picture.postOnAnimation(this);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void remove() {
|
||||
detach();
|
||||
releasePlayer();
|
||||
}
|
||||
|
||||
private void detach() {
|
||||
for (ImageView picture : new ImageView[] {petView, view}) {
|
||||
if (picture != null && picture.getParent() instanceof ViewGroup) {
|
||||
((ViewGroup) picture.getParent()).removeView(picture);
|
||||
}
|
||||
}
|
||||
petView = null;
|
||||
view = null;
|
||||
host = null;
|
||||
petSession++;
|
||||
}
|
||||
|
||||
private String shortName(Activity activity) {
|
||||
String name = activity.getClass().getName();
|
||||
return name.substring(name.lastIndexOf('.') + 1);
|
||||
}
|
||||
|
||||
// ---- the place ----------------------------------------------------------------------
|
||||
|
||||
private String positionKey() {
|
||||
return "pos." + overlay.key + "." + overlay.uid;
|
||||
}
|
||||
|
||||
private void loadPosition(Activity activity, float density) {
|
||||
if (rightPx >= 0) return;
|
||||
float right = spec.right;
|
||||
float bottom = spec.bottom;
|
||||
try {
|
||||
String saved = activity.getSharedPreferences(PREFS, Activity.MODE_PRIVATE).getString(positionKey(), null);
|
||||
if (saved != null) {
|
||||
String[] parts = saved.split(",");
|
||||
right = Float.parseFloat(parts[0]);
|
||||
bottom = Float.parseFloat(parts[1]);
|
||||
}
|
||||
} catch (RuntimeException unreadable) {
|
||||
// the place from the plugin is used
|
||||
}
|
||||
rightPx = Math.round(right * density);
|
||||
bottomPx = Math.round(bottom * density);
|
||||
}
|
||||
|
||||
private void savePosition(float density) {
|
||||
if (host == null) return;
|
||||
SharedPreferences prefs = host.getSharedPreferences(PREFS, Activity.MODE_PRIVATE);
|
||||
prefs.edit().putString(positionKey(), (rightPx / density) + "," + (bottomPx / density)).apply();
|
||||
}
|
||||
|
||||
// ---- the picture itself -------------------------------------------------------------
|
||||
|
||||
private Drawable decode(Activity activity, File file) {
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= 28) {
|
||||
return ImageDecoder.decodeDrawable(ImageDecoder.createSource(file));
|
||||
}
|
||||
} catch (Throwable unreadable) {
|
||||
// falls back to a still picture
|
||||
}
|
||||
try {
|
||||
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
|
||||
return bitmap == null ? null : new BitmapDrawable(activity.getResources(), bitmap);
|
||||
} catch (Throwable unreadable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- what a tap does ----------------------------------------------------------------
|
||||
|
||||
void onTap() {
|
||||
if (animating || host == null) return;
|
||||
animating = true;
|
||||
StringBuilder did = new StringBuilder();
|
||||
long hold = spec.animateMs;
|
||||
if (spec.tap.contains(OverlaySpec.TAP_SOUND)) {
|
||||
long played = playSound();
|
||||
if (played > 0) {
|
||||
did.append("звук ");
|
||||
hold = Math.max(hold, played);
|
||||
}
|
||||
}
|
||||
if (spec.tap.contains(OverlaySpec.TAP_ANIMATE) && play(view)) did.append("анимация ");
|
||||
if (spec.tap.contains(OverlaySpec.TAP_LIKE)) {
|
||||
did.append(like() ? "лайк" : "лайк не поставлен (не главная лента)");
|
||||
}
|
||||
Journal.add(overlay.plugin.id, "Нажатие на картинку: " + did.toString().trim());
|
||||
ui.postDelayed(new Runnable() {
|
||||
@Override public void run() {
|
||||
animating = false;
|
||||
}
|
||||
}, hold);
|
||||
}
|
||||
|
||||
/** Plays the gif of a view for animate_ms and then shows its first frame again. */
|
||||
private boolean play(final ImageView target) {
|
||||
if (target == null || Build.VERSION.SDK_INT < 28) return false;
|
||||
Drawable drawable = target.getDrawable();
|
||||
if (!(drawable instanceof AnimatedImageDrawable)) return false;
|
||||
try {
|
||||
((AnimatedImageDrawable) drawable).start();
|
||||
final File file = overlay.file(target == petView && spec.pet != null ? spec.pet : spec.image);
|
||||
ui.postDelayed(new Runnable() {
|
||||
@Override public void run() {
|
||||
try {
|
||||
if (host == null || target.getParent() == null) return;
|
||||
((AnimatedImageDrawable) target.getDrawable()).stop();
|
||||
Drawable first = decode(host, file);
|
||||
if (first != null) target.setImageDrawable(first);
|
||||
} catch (Throwable ignored) {
|
||||
// the picture stays as it is
|
||||
}
|
||||
}
|
||||
}, spec.animateMs);
|
||||
return true;
|
||||
} catch (Throwable failure) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private long playSound() {
|
||||
releasePlayer();
|
||||
File file = overlay.file(spec.sound);
|
||||
if (!file.isFile()) return 0L;
|
||||
try {
|
||||
final MediaPlayer mp = new MediaPlayer();
|
||||
mp.setDataSource(file.getAbsolutePath());
|
||||
mp.prepare();
|
||||
final int duration = Math.max(mp.getDuration(), 200);
|
||||
mp.start();
|
||||
player = mp;
|
||||
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
|
||||
@Override public void onCompletion(MediaPlayer done) {
|
||||
try {
|
||||
done.release();
|
||||
} catch (Throwable ignored) {
|
||||
// already gone
|
||||
}
|
||||
if (player == done) player = null;
|
||||
}
|
||||
});
|
||||
return duration;
|
||||
} catch (Throwable failure) {
|
||||
note("sound failed: " + failure);
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
private void releasePlayer() {
|
||||
MediaPlayer mp = player;
|
||||
player = null;
|
||||
if (mp == null) return;
|
||||
try {
|
||||
mp.release();
|
||||
} catch (Throwable ignored) {
|
||||
// already gone
|
||||
}
|
||||
}
|
||||
|
||||
/** A like on the video that is on the home feed: the double tap TikTok itself understands. */
|
||||
private boolean like() {
|
||||
final Activity current = host;
|
||||
if (current == null || !BottomBar.homeSelected(current)) return false;
|
||||
final View decor = current.getWindow().getDecorView();
|
||||
DisplayMetrics metrics = current.getResources().getDisplayMetrics();
|
||||
final float x = metrics.widthPixels * 0.5f;
|
||||
final float y = metrics.heightPixels * 0.45f;
|
||||
tap(decor, x, y);
|
||||
ui.postDelayed(new Runnable() {
|
||||
@Override public void run() {
|
||||
try {
|
||||
if (current.isFinishing() || !BottomBar.homeSelected(current)) return;
|
||||
tap(decor, x, y);
|
||||
} catch (Throwable ignored) {
|
||||
// the second tap is optional
|
||||
}
|
||||
}
|
||||
}, 75L);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void tap(View decor, float x, float y) {
|
||||
long down = SystemClock.uptimeMillis();
|
||||
MotionEvent press = MotionEvent.obtain(down, down, MotionEvent.ACTION_DOWN, x, y, 0);
|
||||
decor.dispatchTouchEvent(press);
|
||||
press.recycle();
|
||||
MotionEvent release = MotionEvent.obtain(down, down + 35, MotionEvent.ACTION_UP, x, y, 0);
|
||||
decor.dispatchTouchEvent(release);
|
||||
release.recycle();
|
||||
}
|
||||
|
||||
// ---- stroking ------------------------------------------------------------------------
|
||||
|
||||
private void showPet() {
|
||||
if (petView == null) return;
|
||||
final int session = ++petSession;
|
||||
try {
|
||||
Drawable drawable = decode(host, overlay.file(spec.pet));
|
||||
if (drawable == null) return;
|
||||
petView.setImageDrawable(drawable);
|
||||
petView.setVisibility(View.VISIBLE);
|
||||
if (Build.VERSION.SDK_INT >= 28 && drawable instanceof AnimatedImageDrawable) {
|
||||
((AnimatedImageDrawable) drawable).start();
|
||||
}
|
||||
ui.postDelayed(new Runnable() {
|
||||
@Override public void run() {
|
||||
hidePet(session);
|
||||
}
|
||||
}, PET_MS);
|
||||
} catch (Throwable failure) {
|
||||
note("pet failed: " + failure);
|
||||
}
|
||||
}
|
||||
|
||||
private void hidePet(int session) {
|
||||
if (session != petSession || petView == null) return;
|
||||
petView.setVisibility(View.GONE);
|
||||
Drawable drawable = petView.getDrawable();
|
||||
if (Build.VERSION.SDK_INT >= 28 && drawable instanceof AnimatedImageDrawable) {
|
||||
try {
|
||||
((AnimatedImageDrawable) drawable).stop();
|
||||
} catch (Throwable ignored) {
|
||||
// already stopped
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- fingers --------------------------------------------------------------------------
|
||||
|
||||
private final class Touch implements View.OnTouchListener {
|
||||
private final ImageView picture;
|
||||
private final ImageView pet;
|
||||
private final FrameLayout.LayoutParams params;
|
||||
private final float density;
|
||||
|
||||
private float startX;
|
||||
private float startY;
|
||||
private int startRight;
|
||||
private int startBottom;
|
||||
private boolean dragging;
|
||||
private boolean topZone;
|
||||
private float lastX;
|
||||
private int lastDirection;
|
||||
private int reversals;
|
||||
private boolean petted;
|
||||
|
||||
Touch(ImageView picture, ImageView pet, FrameLayout.LayoutParams params, float density) {
|
||||
this.picture = picture;
|
||||
this.pet = pet;
|
||||
this.params = params;
|
||||
this.density = density;
|
||||
}
|
||||
|
||||
@Override public boolean onTouch(View v, MotionEvent event) {
|
||||
switch (event.getActionMasked()) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
startX = event.getRawX();
|
||||
startY = event.getRawY();
|
||||
startRight = params.rightMargin;
|
||||
startBottom = params.bottomMargin;
|
||||
dragging = false;
|
||||
topZone = pet != null && event.getY() < picture.getHeight() / 2f;
|
||||
lastX = startX;
|
||||
lastDirection = 0;
|
||||
reversals = 0;
|
||||
petted = false;
|
||||
return true;
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
return move(event);
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
return release(event.getActionMasked() == MotionEvent.ACTION_UP);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean move(MotionEvent event) {
|
||||
float dx = event.getRawX() - startX;
|
||||
float dy = event.getRawY() - startY;
|
||||
if (topZone) {
|
||||
if (Math.abs(dy) > PET_DRIFT_DP * density && spec.movable) {
|
||||
topZone = false; // a long vertical move is a drag, not a stroke
|
||||
} else {
|
||||
float step = event.getRawX() - lastX;
|
||||
if (Math.abs(step) >= PET_STEP_DP * density) {
|
||||
int direction = step > 0 ? 1 : -1;
|
||||
if (lastDirection != 0 && direction != lastDirection) reversals++;
|
||||
lastDirection = direction;
|
||||
lastX = event.getRawX();
|
||||
if (reversals >= PET_REVERSALS) {
|
||||
petted = true;
|
||||
reversals = 0;
|
||||
showPet();
|
||||
onTap();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (spec.movable && !dragging && (Math.abs(dx) > DRAG_DP * density || Math.abs(dy) > DRAG_DP * density)) {
|
||||
dragging = true;
|
||||
}
|
||||
if (dragging) {
|
||||
int right = Math.max(0, startRight - Math.round(dx));
|
||||
int bottom = Math.max(0, startBottom - Math.round(dy));
|
||||
params.rightMargin = right;
|
||||
params.bottomMargin = bottom;
|
||||
picture.setLayoutParams(params);
|
||||
if (pet != null) {
|
||||
FrameLayout.LayoutParams petParams = (FrameLayout.LayoutParams) pet.getLayoutParams();
|
||||
petParams.rightMargin = right;
|
||||
petParams.bottomMargin = bottom + Math.round(PET_LIFT_DP * density);
|
||||
pet.setLayoutParams(petParams);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean release(boolean up) {
|
||||
if (dragging) {
|
||||
rightPx = params.rightMargin;
|
||||
bottomPx = params.bottomMargin;
|
||||
savePosition(density);
|
||||
} else if (petted) {
|
||||
hidePet(petSession);
|
||||
} else if (up) {
|
||||
onTap();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
115
src/lihont/two/plugin/Rule.java
Normal file
115
src/lihont/two/plugin/Rule.java
Normal file
@@ -0,0 +1,115 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** "When this happens, and the condition holds, do these things." */
|
||||
public final class Rule {
|
||||
/** A video of the feed is about to be shown. */
|
||||
public static final String FEED = "feed.item";
|
||||
/** A name is about to be shown. */
|
||||
public static final String NAME = "name.show";
|
||||
/** A screen of the app comes to the front. */
|
||||
public static final String SCREEN = "screen.show";
|
||||
|
||||
public static final int MAX_ACTIONS = 8;
|
||||
public static final int DEFAULT_LIMIT = 3;
|
||||
public static final int MAX_LIMIT = 20;
|
||||
|
||||
public final String title;
|
||||
public final String when;
|
||||
final Cond cond;
|
||||
final List<Act> acts;
|
||||
/** How many times a day the notices of this rule may appear. */
|
||||
public final int limit;
|
||||
|
||||
private Rule(String title, String when, Cond cond, List<Act> acts, int limit) {
|
||||
this.title = title;
|
||||
this.when = when;
|
||||
this.cond = cond;
|
||||
this.acts = acts;
|
||||
this.limit = limit;
|
||||
}
|
||||
|
||||
boolean applies(Ctx ctx) {
|
||||
return cond == null || cond.test(ctx);
|
||||
}
|
||||
|
||||
/** The rule in one plain sentence: "Видео в ленте, если хэштег #a → скрыть видео". */
|
||||
String says() {
|
||||
StringBuilder out = new StringBuilder(when.equals(FEED) ? "Видео в ленте" : when.equals(NAME) ? "Имя на экране"
|
||||
: "Экран приложения");
|
||||
if (cond != null) out.append(", если ").append(cond.says());
|
||||
out.append(" → ");
|
||||
boolean notice = false;
|
||||
for (int i = 0; i < acts.size(); i++) {
|
||||
out.append(i > 0 ? "; " : "").append(acts.get(i).says());
|
||||
notice = notice || acts.get(i).kind == Act.NOTICE;
|
||||
}
|
||||
if (notice) out.append(" (подсказок в день не больше ").append(limit).append(")");
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
boolean hides() {
|
||||
for (Act act : acts) {
|
||||
if (act.kind == Act.HIDE) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static Rule parse(Object node, int index, List<String> permissions) throws LtpException {
|
||||
String where = "Правило " + (index + 1);
|
||||
Map<String, Object> map = Fields.map(node, where);
|
||||
String title = Fields.string(map, "title", false, 60, where);
|
||||
if (title == null || title.trim().length() == 0) title = where;
|
||||
where = "Правило «" + title + "»";
|
||||
String when = Fields.string(map, "when", true, 20, where);
|
||||
if (!FEED.equals(when) && !NAME.equals(when) && !SCREEN.equals(when)) {
|
||||
throw new LtpException(where + ": «when» — это feed.item, name.show или screen.show");
|
||||
}
|
||||
Cond cond = map.get("if") == null ? null : Cond.parse(map.get("if"), where);
|
||||
List<Object> raw = Fields.list(map.get("do"), where + ", поле «do»");
|
||||
if (raw.isEmpty() || raw.size() > MAX_ACTIONS) {
|
||||
throw new LtpException(where + ": в «do» от 1 до " + MAX_ACTIONS + " действий");
|
||||
}
|
||||
List<Act> acts = new ArrayList<Act>();
|
||||
for (Object item : raw) {
|
||||
Act act = Act.parse(item, when, where);
|
||||
for (String right : act.permissions()) {
|
||||
if (!permissions.contains(right)) {
|
||||
throw new LtpException(where + ": действию нужно право «" + right + "», его нет в «permissions»");
|
||||
}
|
||||
}
|
||||
acts.add(act);
|
||||
}
|
||||
int limit = map.get("limit") == null ? DEFAULT_LIMIT : Fields.integer(map.get("limit"), 1, MAX_LIMIT, where + ", «limit»");
|
||||
return new Rule(title, when, cond, acts, limit);
|
||||
}
|
||||
|
||||
/** Whether the rule uses the right (so a manifest cannot ask for rights it never uses). */
|
||||
boolean uses(String permission) {
|
||||
for (Act act : acts) {
|
||||
if (act.permissions().contains(permission)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The download actions of the rule. */
|
||||
List<DownloadSpec> downloads() {
|
||||
List<DownloadSpec> found = new ArrayList<DownloadSpec>();
|
||||
for (Act act : acts) {
|
||||
if (act.kind == Act.DOWNLOAD) found.add(act.download);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The picture actions of the rule. */
|
||||
List<OverlaySpec> overlays() {
|
||||
List<OverlaySpec> found = new ArrayList<OverlaySpec>();
|
||||
for (Act act : acts) {
|
||||
if (act.kind == Act.OVERLAY) found.add(act.overlay);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
}
|
||||
@@ -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 · Luna (пре-релиз)";
|
||||
private static final String VERSION_LINE = "LihonT 2.0 · Luna";
|
||||
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 =
|
||||
"• Material 3 в TikTok: нижняя панель с кнопкой «+», меню профиля, профили, настройки и комментарии.\n"
|
||||
"• Призрак (раздел «Приватность»): истории без отметки о просмотре и чаты без «прочитано». Переключатели выключены, пока вы их не включите.\n"
|
||||
+ "• Несколько фото в одном комментарии (до 9), если это даёт сервер для вашего аккаунта.\n"
|
||||
+ "• Плагины .ltp: правила для ленты, имён и картинок без кода. Права вы одобряете сами, плагины включаются на каждый аккаунт отдельно, есть журнал, откат версии и защитник, который говорит простыми словами, что делает плагин.\n"
|
||||
+ "• Плагин может скачивать картинки и звуки с названных сайтов, но только когда вы включили ему интернет и подтвердили адрес. У плагина видны лицензия и ИИ, которые назвал автор.\n"
|
||||
+ "• Свои пузыри в чате: ваша картинка для сообщений, общая для незнакомцев и своя для каждого человека, цвет текста на выбор. Картинки хранятся только на телефоне.\n"
|
||||
+ "• Material 3 в TikTok: нижняя панель с кнопкой «+», меню профиля, профили, настройки и комментарии.\n"
|
||||
+ "• Свой цвет оформления или цвет телефона, один цвет у всех цветочков, чёрный фон AMOLED.\n"
|
||||
+ "• Форма аватарок: круг, цветочек, квадрат, шестиугольник, сердечко, треугольник. Ваша форма видна другим с модом.\n"
|
||||
+ "• Компактная нижняя панель без подписей.\n"
|
||||
@@ -75,6 +80,7 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
|
||||
// The "Свой значок" screen: a full-screen dialog that lives on top of this activity.
|
||||
private CustomIconStore iconStore;
|
||||
private PluginSettings plugins;
|
||||
private Dialog iconsDialog;
|
||||
private LinearLayout iconsList;
|
||||
private FrameLayout iconsHost;
|
||||
@@ -177,6 +183,8 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.REPOST, palette.onPrimaryContainer, 8),
|
||||
settings.commentReposts(), TOGGLE_REPOSTS));
|
||||
cardFunc.addView(Md3.cardDivider(this, palette));
|
||||
cardFunc.addView(commentPhotosRow());
|
||||
cardFunc.addView(Md3.cardDivider(this, palette));
|
||||
cardFunc.addView(switchRow("Интерфейс в стиле MD3",
|
||||
"Нижняя панель, меню профиля и настройки TikTok. Выключено: вид Serena 1.2",
|
||||
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BOTTOM_BAR, palette.onPrimaryContainer, 8),
|
||||
@@ -191,6 +199,31 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
settings.downloadMenu(), TOGGLE_MENU));
|
||||
addSection("Функции", cardFunc, true);
|
||||
|
||||
LinearLayout cardPrivacy = Md3.card(this, palette);
|
||||
cardPrivacy.addView(ghostStoriesRow());
|
||||
cardPrivacy.addView(Md3.cardDivider(this, palette));
|
||||
cardPrivacy.addView(ghostMessagesRow());
|
||||
addSection("Приватность", cardPrivacy, false);
|
||||
|
||||
LinearLayout cardChat = Md3.card(this, palette);
|
||||
cardChat.addView(bubblesSwitchRow());
|
||||
cardChat.addView(Md3.cardDivider(this, palette));
|
||||
cardChat.addView(bubbleSlotRow("Мои пузыри", "Картинка для ваших сообщений", lihont.two.chat.BubbleStore.OWN));
|
||||
cardChat.addView(Md3.cardDivider(this, palette));
|
||||
cardChat.addView(bubbleSlotRow("Общая картинка", "Для всех, у кого нет своей: и для тех, кто написал вам впервые",
|
||||
lihont.two.chat.BubbleStore.GENERAL));
|
||||
cardChat.addView(Md3.cardDivider(this, palette));
|
||||
cardChat.addView(bubbleColorRow("Цвет текста: мой", true));
|
||||
cardChat.addView(Md3.cardDivider(this, palette));
|
||||
cardChat.addView(bubbleColorRow("Цвет текста: собеседника", false));
|
||||
cardChat.addView(Md3.cardDivider(this, palette));
|
||||
LinearLayout personRow = Md3.listItem(this, palette,
|
||||
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.ADD_PHOTO, palette.onPrimaryContainer, 8),
|
||||
"Картинка для человека", "Выберите из тех, с кем вы переписывались, потом фото", Md3.chevron(this, palette), true);
|
||||
personRow.setOnClickListener(v -> askBubblePerson());
|
||||
cardChat.addView(personRow);
|
||||
addSection("Пузыри чата", cardChat, false);
|
||||
|
||||
LinearLayout cardFeed = Md3.card(this, palette);
|
||||
cardFeed.addView(switchRow("Убрать рекламу", "Рекламные ролики и вставки между видео",
|
||||
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.AD_OFF, palette.onPrimaryContainer, 8),
|
||||
@@ -248,6 +281,11 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
new KeeperSettings(this, palette, this::buildScreen).fill(cardKeeper);
|
||||
addSection("Огоньки", cardKeeper, false);
|
||||
|
||||
LinearLayout cardPlugins = Md3.card(this, palette);
|
||||
plugins = new PluginSettings(this, palette, this::buildScreen);
|
||||
plugins.fill(cardPlugins);
|
||||
addSection("Плагины", cardPlugins, false);
|
||||
|
||||
LinearLayout cardAbout = Md3.card(this, palette);
|
||||
cardAbout.addView(Md3.listItem(this, palette,
|
||||
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.INFO, palette.onPrimaryContainer, 8),
|
||||
@@ -264,7 +302,7 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
cardAbout.addView(Md3.cardDivider(this, palette));
|
||||
cardAbout.addView(linkRow("Исходный код", SOURCE_URL, Md3Icon.CODE, SOURCE_URL));
|
||||
cardAbout.addView(Md3.cardDivider(this, palette));
|
||||
cardAbout.addView(linkRow("Лицензия", "EVHNMKHU", Md3Icon.INFO, LICENSE_URL));
|
||||
cardAbout.addView(linkRow("Лицензия", "VCBFU v2", Md3Icon.INFO, LICENSE_URL));
|
||||
addSection("О моде", cardAbout, false);
|
||||
|
||||
status = Md3.text(this, "", Md3.BODY_SMALL, false, palette.onSurfaceVariant);
|
||||
@@ -352,6 +390,256 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
return row;
|
||||
}
|
||||
|
||||
/** Several photos in one comment (TikTok's own picker, up to nine); a choice about the app, so it has its own store. */
|
||||
private View commentPhotosRow() {
|
||||
Md3Switch toggle = new Md3Switch(this, palette);
|
||||
toggle.setContentDescription("Несколько фото в комментарии");
|
||||
toggle.setChecked(lihont.two.comments.CommentPhotos.enabled(this), false);
|
||||
toggle.setOnCheckedChangeListener((view, value) -> {
|
||||
lihont.two.comments.CommentPhotos.set(this, value);
|
||||
showRestartNotice();
|
||||
});
|
||||
LinearLayout row = Md3.listItem(this, palette,
|
||||
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.ADD_PHOTO, palette.onPrimaryContainer, 8),
|
||||
"Несколько фото в комментарии", "До 9 фото в одном комментарии. Принимает ли их сервер, "
|
||||
+ "зависит от аккаунта", 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);
|
||||
toggle.setContentDescription("Призрак: истории");
|
||||
toggle.setChecked(lihont.two.ghost.Ghost.storiesOn(this), false);
|
||||
toggle.setOnCheckedChangeListener((view, value) -> lihont.two.ghost.Ghost.setStories(this, value));
|
||||
LinearLayout row = Md3.listItem(this, palette,
|
||||
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.SEARCH, palette.onPrimaryContainer, 8),
|
||||
"Призрак: истории", "Смотреть истории без отметки: автор не увидит вас среди зрителей",
|
||||
toggle, true);
|
||||
row.setOnClickListener(v -> toggle.toggle());
|
||||
return row;
|
||||
}
|
||||
|
||||
/** Ghost mode for chats: the "read" mark is not sent, so the other person does not see that the chat was opened. */
|
||||
private View ghostMessagesRow() {
|
||||
Md3Switch toggle = new Md3Switch(this, palette);
|
||||
toggle.setContentDescription("Призрак: сообщения");
|
||||
toggle.setChecked(lihont.two.ghost.Ghost.messagesOn(this), false);
|
||||
toggle.setOnCheckedChangeListener((view, value) -> lihont.two.ghost.Ghost.setMessages(this, value));
|
||||
LinearLayout row = Md3.listItem(this, palette,
|
||||
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.SEND, palette.onPrimaryContainer, 8),
|
||||
"Призрак: сообщения", "Читать чаты без «прочитано»: собеседник не увидит, что вы открыли переписку. "
|
||||
+ "У вас непрочитанное тоже останется", toggle, true);
|
||||
row.setOnClickListener(v -> toggle.toggle());
|
||||
return row;
|
||||
}
|
||||
|
||||
private static final int REQUEST_BUBBLE = 4102;
|
||||
private String bubbleSlot;
|
||||
|
||||
private View bubblesSwitchRow() {
|
||||
Md3Switch toggle = new Md3Switch(this, palette);
|
||||
toggle.setContentDescription("Свои пузыри в чате");
|
||||
toggle.setChecked(lihont.two.chat.BubbleStore.enabled(this), false);
|
||||
toggle.setOnCheckedChangeListener((view, value) -> {
|
||||
lihont.two.chat.BubbleStore.setEnabled(this, value);
|
||||
showRestartNotice();
|
||||
});
|
||||
LinearLayout row = Md3.listItem(this, palette,
|
||||
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.SEND, palette.onPrimaryContainer, 8),
|
||||
"Свои пузыри", "Картинки вместо фона сообщений. Хранятся только на телефоне", toggle, true);
|
||||
row.setOnClickListener(v -> toggle.toggle());
|
||||
return row;
|
||||
}
|
||||
|
||||
/** One picture slot: tap to choose a picture, long tap to remove it. */
|
||||
private View bubbleSlotRow(String title, String subtitle, final String slot) {
|
||||
LinearLayout row = Md3.listItem(this, palette,
|
||||
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.ADD_PHOTO, palette.onPrimaryContainer, 8),
|
||||
title, subtitle + (lihont.two.chat.BubbleStore.has(this, slot) ? " · выбрана" : ""),
|
||||
Md3.chevron(this, palette), true);
|
||||
row.setOnClickListener(v -> pickBubble(slot));
|
||||
row.setOnLongClickListener(v -> {
|
||||
lihont.two.chat.BubbleStore.remove(this, slot);
|
||||
Toast.makeText(this, "Картинка убрана", Toast.LENGTH_SHORT).show();
|
||||
return true;
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
/** A Material 3 dialog: title, a body, and text buttons (the first one is the neutral action, if any). */
|
||||
private Dialog bubbleDialog(String title, View body, String neutral, final Runnable onNeutral) {
|
||||
final Dialog dialog = new Dialog(this);
|
||||
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
|
||||
LinearLayout root = new LinearLayout(this);
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this));
|
||||
root.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16));
|
||||
root.addView(Md3.text(this, title, Md3.HEADLINE_SMALL, false, palette.onSurface));
|
||||
LinearLayout.LayoutParams bodyParams = new LinearLayout.LayoutParams(-1, -2);
|
||||
bodyParams.topMargin = Md3.dp(this, 16);
|
||||
root.addView(body, bodyParams);
|
||||
LinearLayout actions = new LinearLayout(this);
|
||||
actions.setGravity(Gravity.END);
|
||||
LinearLayout.LayoutParams actionsParams = new LinearLayout.LayoutParams(-1, -2);
|
||||
actionsParams.topMargin = Md3.dp(this, 16);
|
||||
root.addView(actions, actionsParams);
|
||||
if (neutral != null) {
|
||||
TextView extra = Md3.textButton(this, palette, neutral);
|
||||
extra.setOnClickListener(v -> {
|
||||
dialog.dismiss();
|
||||
onNeutral.run();
|
||||
});
|
||||
actions.addView(extra);
|
||||
}
|
||||
TextView cancel = Md3.textButton(this, palette, "Отмена");
|
||||
cancel.setOnClickListener(v -> dialog.dismiss());
|
||||
LinearLayout.LayoutParams cancelParams = new LinearLayout.LayoutParams(-2, -2);
|
||||
cancelParams.leftMargin = Md3.dp(this, 8);
|
||||
actions.addView(cancel, cancelParams);
|
||||
dialog.setContentView(root);
|
||||
styleDialog(dialog);
|
||||
dialog.show();
|
||||
sizeDialog(dialog, 0.9f);
|
||||
return dialog;
|
||||
}
|
||||
|
||||
/** The people whose chats have been opened since the bubbles were switched on, to choose from; or a typed name. */
|
||||
private void askBubblePerson() {
|
||||
final java.util.List<String> people = lihont.two.chat.BubbleStore.people(this);
|
||||
LinearLayout list = new LinearLayout(this);
|
||||
list.setOrientation(LinearLayout.VERTICAL);
|
||||
final Dialog[] shown = new Dialog[1];
|
||||
if (people.isEmpty()) {
|
||||
list.addView(Md3.text(this, "Пока никого. Откройте чат, и человек появится здесь.", Md3.BODY_MEDIUM,
|
||||
false, palette.onSurfaceVariant));
|
||||
}
|
||||
for (final String person : people) {
|
||||
TextView item = Md3.text(this, person, Md3.BODY_LARGE, false, palette.onSurface);
|
||||
item.setPadding(Md3.dp(this, 8), Md3.dp(this, 14), Md3.dp(this, 8), Md3.dp(this, 14));
|
||||
item.setBackground(Md3.stateLayer(this, Md3.SHAPE_EXTRA_SMALL, Md3.stateLayerColor(palette.onSurface)));
|
||||
item.setClickable(true);
|
||||
item.setOnClickListener(v -> {
|
||||
shown[0].dismiss();
|
||||
pickBubble("p:" + person);
|
||||
});
|
||||
list.addView(item);
|
||||
}
|
||||
ScrollView scroll = new ScrollView(this);
|
||||
scroll.addView(list, new ScrollView.LayoutParams(-1, -2));
|
||||
shown[0] = bubbleDialog("Для кого картинка", scroll, "Другое имя", this::askBubbleName);
|
||||
}
|
||||
|
||||
private void askBubbleName() {
|
||||
final EditText name = new EditText(this);
|
||||
name.setHint("Имя в шапке чата");
|
||||
name.setHintTextColor(palette.onSurfaceVariant);
|
||||
name.setTextColor(palette.onSurface);
|
||||
name.setTextSize(Md3.BODY_LARGE);
|
||||
name.setSingleLine(true);
|
||||
name.setBackground(Md3.outlined(Color.TRANSPARENT, palette.outline, 1f, Md3.SHAPE_EXTRA_SMALL, this));
|
||||
name.setPadding(Md3.dp(this, 16), Md3.dp(this, 14), Md3.dp(this, 16), Md3.dp(this, 14));
|
||||
bubbleDialog("Для кого картинка", name, "Дальше", () -> {
|
||||
String value = name.getText().toString().trim();
|
||||
if (value.length() > 0) pickBubble("p:" + value);
|
||||
});
|
||||
}
|
||||
|
||||
private static final int[] BUBBLE_COLORS = {0xFFFFFFFF, 0xFF000000, 0xFFFFEB3B, 0xFFFF9800, 0xFFF44336, 0xFFE91E63,
|
||||
0xFF9C27B0, 0xFF3F51B5, 0xFF2196F3, 0xFF00BCD4, 0xFF4CAF50, 0xFFCDDC39};
|
||||
|
||||
private View bubbleColorRow(final String title, final boolean mine) {
|
||||
Integer now = lihont.two.chat.BubbleStore.textColor(this, mine);
|
||||
final int side = Md3.dp(this, 28);
|
||||
View swatch = new View(this) {
|
||||
@Override protected void onMeasure(int widthSpec, int heightSpec) {
|
||||
setMeasuredDimension(side, side);
|
||||
}
|
||||
};
|
||||
swatch.setBackground(Md3.outlined(now != null ? now.intValue() : palette.surfaceContainerHigh, palette.outline,
|
||||
1f, 14f, this));
|
||||
LinearLayout row = Md3.listItem(this, palette,
|
||||
Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.ADD_PHOTO, palette.onPrimaryContainer, 8),
|
||||
title, now == null ? "Сам по картинке: светлая даёт чёрный, тёмная белый" : "Свой цвет",
|
||||
swatch, true);
|
||||
row.setOnClickListener(v -> chooseBubbleColor(title, mine));
|
||||
return row;
|
||||
}
|
||||
|
||||
private void chooseBubbleColor(String title, final boolean mine) {
|
||||
final Dialog[] shown = new Dialog[1];
|
||||
LinearLayout grid = new LinearLayout(this);
|
||||
grid.setOrientation(LinearLayout.VERTICAL);
|
||||
grid.setGravity(Gravity.CENTER_HORIZONTAL);
|
||||
LinearLayout line = null;
|
||||
for (int i = 0; i < BUBBLE_COLORS.length; i++) {
|
||||
if (i % 4 == 0) {
|
||||
line = new LinearLayout(this);
|
||||
grid.addView(line);
|
||||
}
|
||||
final int color = BUBBLE_COLORS[i];
|
||||
View chip = new View(this);
|
||||
chip.setBackground(Md3.outlined(color, palette.outline, 1f, Md3.SHAPE_FULL, this));
|
||||
chip.setClickable(true);
|
||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Md3.dp(this, 48), Md3.dp(this, 48));
|
||||
params.setMargins(Md3.dp(this, 6), Md3.dp(this, 6), Md3.dp(this, 6), Md3.dp(this, 6));
|
||||
line.addView(chip, params);
|
||||
chip.setOnClickListener(v -> {
|
||||
lihont.two.chat.BubbleStore.setTextColor(this, mine, Integer.valueOf(color));
|
||||
shown[0].dismiss();
|
||||
Toast.makeText(this, "Цвет сохранён", Toast.LENGTH_SHORT).show();
|
||||
});
|
||||
}
|
||||
shown[0] = bubbleDialog(title, grid, "Сам по картинке", () ->
|
||||
lihont.two.chat.BubbleStore.setTextColor(this, mine, null));
|
||||
}
|
||||
|
||||
private void pickBubble(String slot) {
|
||||
bubbleSlot = slot;
|
||||
try {
|
||||
startActivityForResult(IconShortcuts.pickIntent(), REQUEST_BUBBLE);
|
||||
} catch (ActivityNotFoundException | SecurityException none) {
|
||||
Toast.makeText(this, "Не нашлось приложения для выбора фото", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void bubblePicked(final Uri uri) {
|
||||
final String slot = bubbleSlot;
|
||||
if (slot == null) return;
|
||||
new Thread(() -> {
|
||||
boolean ok = false;
|
||||
try {
|
||||
android.graphics.BitmapFactory.Options bounds = new android.graphics.BitmapFactory.Options();
|
||||
bounds.inJustDecodeBounds = true;
|
||||
java.io.InputStream measure = getContentResolver().openInputStream(uri);
|
||||
try {
|
||||
android.graphics.BitmapFactory.decodeStream(measure, null, bounds);
|
||||
} finally {
|
||||
if (measure != null) measure.close();
|
||||
}
|
||||
android.graphics.BitmapFactory.Options options = new android.graphics.BitmapFactory.Options();
|
||||
options.inSampleSize = Math.max(1, Math.max(bounds.outWidth, bounds.outHeight) / 1024);
|
||||
java.io.InputStream in = getContentResolver().openInputStream(uri);
|
||||
Bitmap picture;
|
||||
try {
|
||||
picture = android.graphics.BitmapFactory.decodeStream(in, null, options);
|
||||
} finally {
|
||||
if (in != null) in.close();
|
||||
}
|
||||
if (picture != null) {
|
||||
lihont.two.chat.BubbleStore.put(this, slot, picture);
|
||||
ok = true;
|
||||
}
|
||||
} catch (IOException | RuntimeException | OutOfMemoryError unreadable) {
|
||||
// Reported below.
|
||||
}
|
||||
final boolean done = ok;
|
||||
handler.post(() -> Toast.makeText(this, done ? "Картинка сохранена" : "Не удалось открыть это фото",
|
||||
Toast.LENGTH_SHORT).show());
|
||||
}, "lihont-bubble-decode").start();
|
||||
}
|
||||
|
||||
private View regionRow() {
|
||||
View trailing = Md3.chevron(this, palette);
|
||||
trailing.setTag("region");
|
||||
@@ -950,6 +1238,16 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
|
||||
@Override protected void onActivityResult(int request, int result, Intent data) {
|
||||
super.onActivityResult(request, result, data);
|
||||
if (request == REQUEST_BUBBLE) {
|
||||
if (result == RESULT_OK && data != null && data.getData() != null) bubblePicked(data.getData());
|
||||
return;
|
||||
}
|
||||
if (request == PluginSettings.REQUEST_PICK) {
|
||||
if (result == RESULT_OK && data != null && data.getData() != null && plugins != null) {
|
||||
plugins.picked(data.getData());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (request != IconShortcuts.REQUEST_PICK || result != RESULT_OK || data == null || iconStore == null) return;
|
||||
final Uri uri = data.getData();
|
||||
if (uri == null) return;
|
||||
@@ -1334,11 +1632,21 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this));
|
||||
root.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24));
|
||||
root.addView(Md3.text(this, title, Md3.HEADLINE_SMALL, false, palette.onSurface));
|
||||
// A long text scrolls between the title and the buttons, so the buttons never fall off the screen.
|
||||
final boolean tall = message != null && message.length() > 320;
|
||||
if (message != null) {
|
||||
TextView body = Md3.text(this, message, Md3.BODY_MEDIUM, false, palette.onSurfaceVariant);
|
||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2);
|
||||
params.topMargin = Md3.dp(this, 16);
|
||||
root.addView(body, params);
|
||||
if (tall) {
|
||||
ScrollView scroll = new ScrollView(this);
|
||||
scroll.addView(body);
|
||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, 0, 1f);
|
||||
params.topMargin = Md3.dp(this, 16);
|
||||
root.addView(scroll, params);
|
||||
} else {
|
||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2);
|
||||
params.topMargin = Md3.dp(this, 16);
|
||||
root.addView(body, params);
|
||||
}
|
||||
}
|
||||
LinearLayout actions = new LinearLayout(this);
|
||||
actions.setGravity(Gravity.END);
|
||||
@@ -1364,6 +1672,10 @@ public final class LihonTSettingsActivity extends Activity {
|
||||
styleDialog(dialog);
|
||||
dialog.show();
|
||||
sizeDialog(dialog, 0.9f);
|
||||
if (tall && dialog.getWindow() != null) {
|
||||
android.util.DisplayMetrics screen = getResources().getDisplayMetrics();
|
||||
dialog.getWindow().setLayout((int) (screen.widthPixels * 0.9f), (int) (screen.heightPixels * 0.85f));
|
||||
}
|
||||
return dialog;
|
||||
}
|
||||
|
||||
|
||||
350
src/lihont/two/settings/PluginSettings.java
Normal file
350
src/lihont/two/settings/PluginSettings.java
Normal file
@@ -0,0 +1,350 @@
|
||||
package lihont.two.settings;
|
||||
|
||||
import android.app.Dialog;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.net.Uri;
|
||||
import android.view.View;
|
||||
import android.view.Window;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
import lihont.two.account.CurrentAccount;
|
||||
import lihont.two.plugin.Defender;
|
||||
import lihont.two.plugin.Journal;
|
||||
import lihont.two.plugin.LtpException;
|
||||
import lihont.two.plugin.Permission;
|
||||
import lihont.two.plugin.Plugin;
|
||||
import lihont.two.plugin.PluginRegistry;
|
||||
import lihont.two.plugin.Rule;
|
||||
|
||||
/**
|
||||
* The "Плагины" section of the mod settings. A plugin (.ltp) is a file of rules, not code; this screen installs one
|
||||
* only after showing what it asks for, keeps the person's approval tied to the exact file, and switches each plugin
|
||||
* on or off for the signed-in account on its own.
|
||||
*/
|
||||
final class PluginSettings {
|
||||
static final int REQUEST_PICK = 4107;
|
||||
|
||||
private final LihonTSettingsActivity activity;
|
||||
private final Md3.Palette palette;
|
||||
private final Runnable rebuild;
|
||||
private final String uid;
|
||||
|
||||
PluginSettings(LihonTSettingsActivity activity, Md3.Palette palette, Runnable rebuild) {
|
||||
this.activity = activity;
|
||||
this.palette = palette;
|
||||
this.rebuild = rebuild;
|
||||
this.uid = CurrentAccount.uid();
|
||||
}
|
||||
|
||||
void fill(LinearLayout card) {
|
||||
if (PluginRegistry.safeMode(activity)) {
|
||||
LinearLayout safe = Md3.listItem(activity, palette, avatar("!"), "Безопасный режим",
|
||||
"Приложение несколько раз подряд закрылось сразу после запуска, поэтому плагины выключены. "
|
||||
+ "Нажмите, чтобы включить их снова.", null, true);
|
||||
safe.setOnClickListener(v -> activity.basicDialog("Включить плагины снова?",
|
||||
"Плагины не содержат кода и вряд ли виноваты, но проверьте, что падений больше нет. "
|
||||
+ "Если приложение опять закроется, отключите плагин в списке.",
|
||||
"Отмена", "Включить", () -> {
|
||||
PluginRegistry.leaveSafeMode(activity);
|
||||
rebuild.run();
|
||||
}));
|
||||
card.addView(safe);
|
||||
card.addView(Md3.cardDivider(activity, palette));
|
||||
}
|
||||
List<PluginRegistry.Entry> entries = PluginRegistry.entries(activity);
|
||||
if (uid == null) {
|
||||
card.addView(Md3.listItem(activity, palette, avatar("•"), "Плагины",
|
||||
"Войдите в TikTok: плагины включаются для каждого аккаунта отдельно", null, false));
|
||||
card.addView(Md3.cardDivider(activity, palette));
|
||||
}
|
||||
for (PluginRegistry.Entry entry : entries) {
|
||||
card.addView(pluginRow(entry));
|
||||
card.addView(Md3.cardDivider(activity, palette));
|
||||
}
|
||||
if (entries.isEmpty()) {
|
||||
card.addView(Md3.listItem(activity, palette, avatar("0"), "Плагинов пока нет",
|
||||
"Это файлы .ltp: правила для ленты и имён без кода", null, false));
|
||||
card.addView(Md3.cardDivider(activity, palette));
|
||||
}
|
||||
LinearLayout add = Md3.listItem(activity, palette, avatar("+"), "Установить плагин",
|
||||
"Выберите файл .ltp; перед установкой вы увидите, что он просит", Md3.chevron(activity, palette), true);
|
||||
add.setOnClickListener(v -> pick());
|
||||
card.addView(add);
|
||||
card.addView(Md3.cardDivider(activity, palette));
|
||||
LinearLayout how = Md3.listItem(activity, palette, avatar("?"), "Как сделать свой плагин",
|
||||
"Формат, условия и действия", Md3.chevron(activity, palette), true);
|
||||
how.setOnClickListener(v -> activity.basicDialog("Свой плагин", HOW, null, "Закрыть", null));
|
||||
card.addView(how);
|
||||
}
|
||||
|
||||
private View avatar(CharSequence value) {
|
||||
return Md3.flowerAvatar(activity, palette.primaryContainer, palette.onPrimaryContainer, value, 8);
|
||||
}
|
||||
|
||||
// ---- one plugin -------------------------------------------------------------------------
|
||||
|
||||
private View pluginRow(final PluginRegistry.Entry entry) {
|
||||
String letter = entry.plugin == null || entry.plugin.name.length() == 0 ? "!"
|
||||
: entry.plugin.name.substring(0, 1).toUpperCase();
|
||||
if (entry.plugin == null) {
|
||||
LinearLayout row = Md3.listItem(activity, palette, avatar("!"), entry.id,
|
||||
"Не читается: " + entry.problem, null, true);
|
||||
row.setOnClickListener(v -> details(entry));
|
||||
return row;
|
||||
}
|
||||
final Md3Switch toggle = new Md3Switch(activity, palette);
|
||||
toggle.setContentDescription("Плагин " + entry.plugin.name);
|
||||
boolean on = uid != null && entry.approved && PluginRegistry.enabled(activity, entry.id, uid);
|
||||
toggle.setChecked(on, false);
|
||||
toggle.setOnCheckedChangeListener((view, value) -> {
|
||||
if (uid == null) {
|
||||
Toast.makeText(activity, "Сначала войдите в TikTok", Toast.LENGTH_SHORT).show();
|
||||
view.setChecked(false, true);
|
||||
return;
|
||||
}
|
||||
if (value && !entry.approved) {
|
||||
view.setChecked(false, false);
|
||||
review(entry.plugin, null, null, entry);
|
||||
return;
|
||||
}
|
||||
PluginRegistry.setEnabled(activity, entry.id, uid, value);
|
||||
rebuild.run();
|
||||
});
|
||||
String detail = "v" + entry.plugin.version + " · " + entry.plugin.author + " · правил: " + entry.plugin.rules.size()
|
||||
+ (entry.approved ? "" : " · изменён, нужна проверка")
|
||||
+ (entry.approved ? accountsNote(entry) : "");
|
||||
LinearLayout row = Md3.listItem(activity, palette, avatar(letter), entry.plugin.name, detail, toggle, true);
|
||||
row.setOnClickListener(v -> details(entry));
|
||||
return row;
|
||||
}
|
||||
|
||||
private String accountsNote(PluginRegistry.Entry entry) {
|
||||
int count = PluginRegistry.accountCount(activity, entry.id);
|
||||
return count == 0 ? " · выключен" : " · аккаунтов: " + count;
|
||||
}
|
||||
|
||||
private Dialog dialog(LinearLayout root) {
|
||||
final Dialog dialog = new Dialog(activity);
|
||||
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
|
||||
root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), activity));
|
||||
ScrollView scroll = new ScrollView(activity);
|
||||
scroll.addView(root);
|
||||
dialog.setContentView(scroll);
|
||||
activity.styleDialog(dialog);
|
||||
return dialog;
|
||||
}
|
||||
|
||||
private void details(final PluginRegistry.Entry entry) {
|
||||
LinearLayout root = new LinearLayout(activity);
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setPadding(0, Md3.dp(activity, 20), 0, Md3.dp(activity, 8));
|
||||
final Dialog dialog = dialog(root);
|
||||
int side = Md3.dp(activity, 24);
|
||||
Bitmap icon = entry.icon() == null ? null : BitmapFactory.decodeFile(entry.icon().getAbsolutePath());
|
||||
if (icon != null) {
|
||||
ImageView picture = new ImageView(activity);
|
||||
picture.setImageBitmap(icon);
|
||||
LinearLayout.LayoutParams size = new LinearLayout.LayoutParams(Md3.dp(activity, 56), Md3.dp(activity, 56));
|
||||
size.leftMargin = side;
|
||||
size.bottomMargin = Md3.dp(activity, 8);
|
||||
root.addView(picture, size);
|
||||
}
|
||||
TextView title = Md3.text(activity, entry.plugin == null ? entry.id : entry.plugin.name, Md3.HEADLINE_SMALL,
|
||||
false, palette.onSurface);
|
||||
title.setPadding(side, 0, side, Md3.dp(activity, 4));
|
||||
root.addView(title);
|
||||
TextView body = Md3.text(activity, describe(entry), Md3.BODY_MEDIUM, false, palette.onSurfaceVariant);
|
||||
body.setPadding(side, Md3.dp(activity, 4), side, Md3.dp(activity, 12));
|
||||
root.addView(body);
|
||||
if (entry.plugin != null) {
|
||||
action(root, dialog, "Журнал: что плагин делал", () -> journal(entry));
|
||||
if (!entry.plugin.hosts.isEmpty() && entry.approved) {
|
||||
final boolean online = PluginRegistry.netOn(activity, entry.id);
|
||||
action(root, dialog, online ? "Интернет плагина включён: выключить" : "Включить плагину интернет",
|
||||
() -> internet(entry, online));
|
||||
}
|
||||
if (!entry.approved) action(root, dialog, "Проверить файл и одобрить", () -> review(entry.plugin, null, null, entry));
|
||||
}
|
||||
if (entry.hasPrevious) {
|
||||
action(root, dialog, "Вернуть прошлую версию", () -> activity.basicDialog("Вернуть прошлую версию?",
|
||||
"Текущая версия будет заменена той, что стояла до обновления.", "Отмена", "Вернуть", () -> {
|
||||
boolean done = PluginRegistry.rollback(activity, entry.id);
|
||||
Toast.makeText(activity, done ? "Прошлая версия на месте" : "Не получилось вернуть", Toast.LENGTH_SHORT).show();
|
||||
rebuild.run();
|
||||
}));
|
||||
}
|
||||
action(root, dialog, "Удалить", () -> activity.basicDialog("Удалить плагин?",
|
||||
"«" + (entry.plugin == null ? entry.id : entry.plugin.name) + "» пропадёт со всех аккаунтов.",
|
||||
"Отмена", "Удалить", () -> {
|
||||
PluginRegistry.remove(activity, entry.id);
|
||||
rebuild.run();
|
||||
}));
|
||||
dialog.show();
|
||||
activity.sizeDialog(dialog, 0.9f);
|
||||
}
|
||||
|
||||
private void action(LinearLayout root, final Dialog dialog, String label, final Runnable run) {
|
||||
TextView button = Md3.textButton(activity, palette, label);
|
||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-2, -2);
|
||||
params.leftMargin = Md3.dp(activity, 12);
|
||||
button.setOnClickListener(v -> {
|
||||
dialog.dismiss();
|
||||
run.run();
|
||||
});
|
||||
root.addView(button, params);
|
||||
}
|
||||
|
||||
private String describe(PluginRegistry.Entry entry) {
|
||||
if (entry.plugin == null) return "Файл плагина не читается: " + entry.problem;
|
||||
Plugin plugin = entry.plugin;
|
||||
StringBuilder text = new StringBuilder();
|
||||
text.append("v").append(plugin.version).append(" · ").append(plugin.author).append('\n');
|
||||
if (plugin.description.length() > 0) text.append(plugin.description).append('\n');
|
||||
text.append(origin(plugin));
|
||||
text.append("\nЧто плагин может:\n");
|
||||
for (String right : plugin.permissions) text.append("• ").append(Permission.describe(right)).append('\n');
|
||||
text.append('\n').append(Defender.check(plugin).text()).append('\n');
|
||||
if (!plugin.hosts.isEmpty()) {
|
||||
text.append("\nИнтернет плагина: ").append(PluginRegistry.netOn(activity, entry.id) ? "включён" : "выключен")
|
||||
.append(" (сайты: ").append(android.text.TextUtils.join(", ", plugin.hosts)).append(")\n");
|
||||
}
|
||||
text.append("\nСегодня сработал: ").append(Journal.count(plugin.id)).append(" раз");
|
||||
text.append("\nSHA-256: ").append(plugin.sha256.substring(0, 16)).append("…");
|
||||
if (!entry.approved) text.append("\n\nФайл изменился после того, как вы его одобрили. Плагин выключен, пока вы его не проверите.");
|
||||
return text.toString();
|
||||
}
|
||||
|
||||
/** The switch of a plugin's internet: off by default, and turning it on is a question of its own. */
|
||||
private void internet(final PluginRegistry.Entry entry, boolean online) {
|
||||
if (online) {
|
||||
PluginRegistry.setNetOn(activity, entry.id, false);
|
||||
Toast.makeText(activity, "Интернет плагину выключен", Toast.LENGTH_SHORT).show();
|
||||
rebuild.run();
|
||||
return;
|
||||
}
|
||||
StringBuilder sites = new StringBuilder();
|
||||
for (String host : entry.plugin.hosts) sites.append("• ").append(host).append('\n');
|
||||
activity.basicDialog("Включить плагину интернет?",
|
||||
"«" + entry.plugin.name + "» сможет скачивать файлы (картинки и звуки) только с этих сайтов:\n"
|
||||
+ sites + "\nКаждый адрес перед скачиванием покажется вам, и скачается он только после вашего "
|
||||
+ "«Скачать». Больше плагин ничего не отправляет и не получает.",
|
||||
"Отмена", "Включить", () -> {
|
||||
PluginRegistry.setNetOn(activity, entry.id, true);
|
||||
Toast.makeText(activity, "Интернет плагину включён", Toast.LENGTH_SHORT).show();
|
||||
rebuild.run();
|
||||
});
|
||||
}
|
||||
|
||||
/** The licence and the AI the author names; what the author says, not something the mod checks. */
|
||||
private static String origin(Plugin plugin) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
if (plugin.license.length() > 0) out.append("Лицензия: ").append(plugin.license).append(" (со слов автора)\n");
|
||||
if (!plugin.ai.isEmpty()) {
|
||||
out.append("Написан с помощью ИИ: ").append(android.text.TextUtils.join(", ", plugin.ai)).append(" (со слов автора)\n");
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private void journal(PluginRegistry.Entry entry) {
|
||||
List<String> lines = Journal.lines(entry.id);
|
||||
StringBuilder text = new StringBuilder();
|
||||
if (lines.isEmpty()) text.append("С запуска приложения плагин ничего не делал.");
|
||||
for (String line : lines) text.append(line).append('\n');
|
||||
activity.basicDialog("Журнал: " + entry.plugin.name, text.toString().trim(), null, "Закрыть", null);
|
||||
}
|
||||
|
||||
// ---- installing --------------------------------------------------------------------------
|
||||
|
||||
private void pick() {
|
||||
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
|
||||
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
||||
intent.setType("*/*");
|
||||
try {
|
||||
activity.startActivityForResult(intent, REQUEST_PICK);
|
||||
} catch (ActivityNotFoundException | SecurityException none) {
|
||||
Toast.makeText(activity, "Нет приложения для выбора файла", Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
|
||||
/** The result of the file picker: read and check the file, then show it to the person. */
|
||||
void picked(Uri uri) {
|
||||
PluginRegistry.Review review;
|
||||
try {
|
||||
InputStream in = activity.getContentResolver().openInputStream(uri);
|
||||
if (in == null) throw new IOException("файл не открывается");
|
||||
byte[] data;
|
||||
try {
|
||||
data = PluginRegistry.bytes(in);
|
||||
} finally {
|
||||
in.close();
|
||||
}
|
||||
review = PluginRegistry.review(activity, PluginRegistry.stream(data));
|
||||
} catch (LtpException refused) {
|
||||
activity.basicDialog("Это не подходит", refused.getMessage(), null, "Понятно", null);
|
||||
return;
|
||||
} catch (IOException | RuntimeException unreadable) {
|
||||
activity.basicDialog("Файл не открылся", String.valueOf(unreadable.getMessage()), null, "Понятно", null);
|
||||
return;
|
||||
}
|
||||
review(review.plugin, review.manifest, review, review.existing);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the person sees before a plugin goes on: who made it, what it may do, what its rules are. Confirming either
|
||||
* installs the file (a fresh review) or approves the file already on the phone (an existing entry).
|
||||
*/
|
||||
private void review(final Plugin plugin, byte[] manifest, final PluginRegistry.Review fresh,
|
||||
final PluginRegistry.Entry existing) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
text.append(plugin.author).append(" · версия ").append(plugin.version).append('\n');
|
||||
if (plugin.description.length() > 0) text.append(plugin.description).append('\n');
|
||||
text.append(origin(plugin));
|
||||
if (fresh != null && existing != null && existing.plugin != null) {
|
||||
text.append(existing.plugin.version.equals(plugin.version) ? "\nЭта версия уже стоит, файл будет заменён"
|
||||
: "\nОбновление: с версии " + existing.plugin.version + " на " + plugin.version)
|
||||
.append(". Прошлую версию можно будет вернуть.\n");
|
||||
}
|
||||
text.append("\nЧто плагин сможет:\n");
|
||||
for (String right : plugin.permissions) text.append("• ").append(Permission.describe(right)).append('\n');
|
||||
text.append('\n').append(Defender.check(plugin).text()).append('\n');
|
||||
text.append("\nИзменённый файл придётся одобрить заново.\nSHA-256: ")
|
||||
.append(plugin.sha256.substring(0, 16)).append("…");
|
||||
final boolean installing = fresh != null;
|
||||
activity.basicDialog(installing ? "Установить «" + plugin.name + "»?" : "Одобрить «" + plugin.name + "»?",
|
||||
text.toString(), "Отмена", installing ? "Установить" : "Одобрить", () -> {
|
||||
try {
|
||||
if (installing) {
|
||||
PluginRegistry.install(activity, fresh, uid);
|
||||
} else {
|
||||
PluginRegistry.approve(activity, existing);
|
||||
if (uid != null) PluginRegistry.setEnabled(activity, existing.id, uid, true);
|
||||
}
|
||||
Toast.makeText(activity, uid == null ? "Установлено" : "Включено для этого аккаунта",
|
||||
Toast.LENGTH_SHORT).show();
|
||||
} catch (IOException failed) {
|
||||
Toast.makeText(activity, "Не удалось записать плагин", Toast.LENGTH_LONG).show();
|
||||
}
|
||||
rebuild.run();
|
||||
});
|
||||
}
|
||||
|
||||
private static final String HOW =
|
||||
"Плагин — это файл .ltp (zip) с plugin.json внутри. Кода в нём нет: только правила «когда → если → делай».\n\n"
|
||||
+ "Когда: feed.item (видео в ленте) или name.show (имя на экране).\n"
|
||||
+ "Если: text, hashtag, author, uid, account, time, weekday, а также all, any, not.\n"
|
||||
+ "Делай: feed.hide, name.prefix, name.suffix, name.replace, notice.\n\n"
|
||||
+ "Каждое действие нужно заранее назвать в permissions: feed.hide, names, ui.notice. "
|
||||
+ "Права вы подтверждаете при установке, а плагин включается для каждого аккаунта отдельно.\n\n"
|
||||
+ "Полное описание и примеры лежат в репозитории: docs/plugins.md.";
|
||||
}
|
||||
@@ -80,7 +80,14 @@ public final class SettingsCell {
|
||||
* Intercepts row icons in LX/0LDm;->LIZ and wraps them in Material 3 flower badges. With the MD3
|
||||
* switch off TikTok's own icons stay, and the mod's own row gets its note icon without a badge.
|
||||
*/
|
||||
public static Object transformIcon(Object iconObj, String title, Object composerObj) {
|
||||
public static Object transformIcon(Object iconObj, String titleText, Object composerObj) {
|
||||
// TikTok 47.1.3 (and so every build made from pre2's smali) passes the title as a String
|
||||
return transformIcon(iconObj, (CharSequence) titleText, composerObj);
|
||||
}
|
||||
|
||||
public static Object transformIcon(Object iconObj, CharSequence titleText, Object composerObj) {
|
||||
// TikTok 47.1.3 hands over a String here, 47.5.15 a rich text object that is a CharSequence.
|
||||
String title = titleText == null ? "" : titleText.toString();
|
||||
try {
|
||||
if (title == null) title = "";
|
||||
boolean md3 = SettingsHost.md3();
|
||||
@@ -348,29 +355,75 @@ public final class SettingsCell {
|
||||
return dark ? darkPalette[idx] : lightPalette[idx];
|
||||
}
|
||||
|
||||
private static Canvas getNativeCanvas(Object drawScope) {
|
||||
if (drawScope == null) return null;
|
||||
private static Method scopeStep;
|
||||
private static Method contextStep;
|
||||
|
||||
/** The android Canvas a compose object keeps in a field of its own, or null. */
|
||||
private static Canvas canvasIn(Object holder) {
|
||||
try {
|
||||
Method getContext = drawScope.getClass().getMethod("LJLJI");
|
||||
Object drawContext = getContext.invoke(drawScope);
|
||||
if (drawContext == null) return null;
|
||||
Method getCanvas = drawContext.getClass().getMethod("LIZ");
|
||||
Object composeCanvas = getCanvas.invoke(drawContext);
|
||||
if (composeCanvas == null) return null;
|
||||
|
||||
try {
|
||||
Field f = composeCanvas.getClass().getField("LIZ");
|
||||
Object c = f.get(composeCanvas);
|
||||
if (c instanceof Canvas) return (Canvas) c;
|
||||
} catch (Throwable ignored) {}
|
||||
|
||||
for (Field f : composeCanvas.getClass().getDeclaredFields()) {
|
||||
for (Field f : holder.getClass().getDeclaredFields()) {
|
||||
if (Canvas.class.isAssignableFrom(f.getType())) {
|
||||
f.setAccessible(true);
|
||||
Object c = f.get(composeCanvas);
|
||||
Object c = f.get(holder);
|
||||
if (c instanceof Canvas) return (Canvas) c;
|
||||
}
|
||||
}
|
||||
} catch (Throwable ignored) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean legacyFailed;
|
||||
|
||||
/** The chain by the member names of TikTok 47.1.3; null on any other version. */
|
||||
private static Canvas legacyCanvas(Object drawScope) {
|
||||
try {
|
||||
Object drawContext = drawScope.getClass().getMethod("LJLJI").invoke(drawScope);
|
||||
if (drawContext == null) return null;
|
||||
Object composeCanvas = drawContext.getClass().getMethod("LIZ").invoke(drawContext);
|
||||
return composeCanvas == null ? null : canvasIn(composeCanvas);
|
||||
} catch (Throwable otherVersion) {
|
||||
legacyFailed = true;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Canvas getNativeCanvas(Object drawScope) {
|
||||
if (drawScope == null) return null;
|
||||
if (!legacyFailed) {
|
||||
Canvas known = legacyCanvas(drawScope);
|
||||
if (known != null) return known;
|
||||
}
|
||||
try {
|
||||
// Method names change with every TikTok version, so when the 47.1.3 names are not there the chain draw
|
||||
// scope -> draw context -> compose canvas -> android Canvas is found by shape: a public no-argument
|
||||
// method whose result holds a Canvas.
|
||||
Canvas direct = canvasIn(drawScope);
|
||||
if (direct != null) return direct;
|
||||
if (scopeStep != null && scopeStep.getDeclaringClass().isInstance(drawScope)) {
|
||||
Object drawContext = scopeStep.invoke(drawScope);
|
||||
Object composeCanvas = drawContext == null ? null : contextStep.invoke(drawContext);
|
||||
return composeCanvas == null ? null : canvasIn(composeCanvas);
|
||||
}
|
||||
for (Method m : drawScope.getClass().getMethods()) {
|
||||
if (m.getParameterTypes().length != 0 || m.getReturnType().isPrimitive()
|
||||
|| m.getReturnType() == Object.class || m.getReturnType() == String.class) continue;
|
||||
Object drawContext = m.invoke(drawScope);
|
||||
if (drawContext == null) continue;
|
||||
Canvas c = canvasIn(drawContext);
|
||||
if (c != null) return c;
|
||||
for (Method n : drawContext.getClass().getMethods()) {
|
||||
if (n.getParameterTypes().length != 0 || n.getReturnType().isPrimitive()
|
||||
|| n.getReturnType() == Object.class || n.getReturnType() == String.class) continue;
|
||||
Object composeCanvas = n.invoke(drawContext);
|
||||
if (composeCanvas == null) continue;
|
||||
c = canvasIn(composeCanvas);
|
||||
if (c != null) {
|
||||
scopeStep = m;
|
||||
contextStep = n;
|
||||
return c;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
Log.e(TAG, "getNativeCanvas failed", t);
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@
|
||||
<svg class="icon icon-light" aria-hidden="true"><use href="/assets/site/icons.svg#dark-mode"/></svg>
|
||||
<svg class="icon icon-dark" aria-hidden="true"><use href="/assets/site/icons.svg#light-mode"/></svg>
|
||||
</button>
|
||||
<a class="btn btn--filled" href="/lihont2/">Тест 2.0</a>
|
||||
<a class="btn btn--filled" href="https://git.lihont.space/lihont/LihonT/releases/tag/v2.0-luna-pre2" rel="noopener">Скачать 2.0</a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
@@ -86,9 +86,9 @@
|
||||
<h1 id="hero-title" class="t-display-lg hero__title">Твой TikTok<br>в стиле <em>Material 3</em></h1>
|
||||
<p class="t-body-lg t-muted">Адаптивная палитра Monet, отдельные скруглённые карточки настроек, фирменные цветочки-бейджи, перенесённые оригинальные настройки TikTok и выбор любого региона мира.</p>
|
||||
<div class="cluster">
|
||||
<a class="btn btn--filled btn--lg btn--icon-lead" href="/lihont2/">
|
||||
<svg class="icon" aria-hidden="true"><use href="/assets/site/icons.svg#lock"/></svg>
|
||||
Закрытый тест 2.0
|
||||
<a class="btn btn--filled btn--lg btn--icon-lead" href="https://git.lihont.space/lihont/LihonT/releases/tag/v2.0-luna-pre2" rel="noopener">
|
||||
<svg class="icon" aria-hidden="true"><use href="/assets/site/icons.svg#download"/></svg>
|
||||
Скачать 2.0 pre2
|
||||
</a>
|
||||
<a class="btn btn--tonal btn--lg btn--icon-lead" href="#versions">
|
||||
<svg class="icon" aria-hidden="true"><use href="/assets/site/icons.svg#download"/></svg>
|
||||
@@ -161,14 +161,17 @@
|
||||
<div class="stack" style="gap: 8px">
|
||||
<div class="cluster" style="gap: 8px">
|
||||
<h2 id="spotlight-title" class="t-headline-md">LihonT 2.0 Native</h2>
|
||||
<span class="chip chip--tonal">Закрытое тестирование</span>
|
||||
<span class="chip chip--tonal">Пре-релиз pre2</span>
|
||||
</div>
|
||||
<p class="t-body-lg t-muted" style="max-width: 62ch">Новая версия мода на актуальной базе TikTok 47.1.3 в дизайне Material 3: отдельные скруглённые кнопки в настройках, палитра Monet, обновлённый интерфейс и расширенные настройки.</p>
|
||||
<p class="t-body-lg t-muted" style="max-width: 62ch">Новая версия мода на актуальной базе TikTok 47.1.3 в дизайне Material 3: отдельные скруглённые кнопки в настройках, палитра Monet, виджет серии огоньков с хранителем, свои настройки для каждого аккаунта и расширенные настройки. Исходники и APK открыты, это ещё тестовая сборка.</p>
|
||||
</div>
|
||||
<div class="stack" style="gap: 8px">
|
||||
<a class="btn btn--filled btn--lg btn--icon-lead" href="https://git.lihont.space/lihont/LihonT/releases/tag/v2.0-luna-pre2" rel="noopener">
|
||||
<svg class="icon" aria-hidden="true"><use href="/assets/site/icons.svg#download"/></svg>
|
||||
Скачать pre2
|
||||
</a>
|
||||
<a class="btn btn--text" href="/lihont2/">Портал участников</a>
|
||||
</div>
|
||||
<a class="btn btn--filled btn--lg btn--icon-lead" href="/lihont2/">
|
||||
<svg class="icon" aria-hidden="true"><use href="/assets/site/icons.svg#key"/></svg>
|
||||
Вход для участников
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -323,11 +326,11 @@
|
||||
<div class="accordion">
|
||||
<details>
|
||||
<summary><span>Что нового в LihonT 2.0?</span><svg class="icon" aria-hidden="true"><use href="/assets/site/icons.svg#expand-more"/></svg></summary>
|
||||
<div class="accordion__answer">LihonT 2.0 — переход на Material Design 3. Экраны «Настройки и конфиденциальность» переписаны в Material You: каждая строка — отдельная скруглённая кнопка, фирменные цветочки-бейджи, диалог выбора региона с очисткой кэша и быстрой перезагрузкой.</div>
|
||||
<div class="accordion__answer">LihonT 2.0 — переход на Material Design 3. Экраны «Настройки и конфиденциальность» переписаны в Material You: каждая строка — отдельная скруглённая кнопка, фирменные цветочки-бейджи, диалог выбора региона с очисткой кэша и быстрой перезагрузкой. В pre2 добавились виджет серии огоньков с хранителем и свои настройки для каждого аккаунта.</div>
|
||||
</details>
|
||||
<details>
|
||||
<summary><span>Какую версию выбрать: Serena, Luna или 2.0?</span><svg class="icon" aria-hidden="true"><use href="/assets/site/icons.svg#expand-more"/></svg></summary>
|
||||
<div class="accordion__answer">Если участвуешь в тестировании — выбирай LihonT 2.0. Нужна проверенная стабильная сборка — Serena 1.2 (классика) или Luna 1.2 (со значком сообщества).</div>
|
||||
<div class="accordion__answer">Хочешь самое новое и не против багов — ставь LihonT 2.0 (пре-релиз, скачивается с git.lihont.space). Нужна проверенная стабильная сборка — Serena 1.2 (классика) или Luna 1.2 (со значком сообщества).</div>
|
||||
</details>
|
||||
<details>
|
||||
<summary><span>Какой APK скачать: обычный или отдельный (клон)?</span><svg class="icon" aria-hidden="true"><use href="/assets/site/icons.svg#expand-more"/></svg></summary>
|
||||
|
||||
51
tests/java/lihont/two/plugin/GuardDump.java
Normal file
51
tests/java/lihont/two/plugin/GuardDump.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Reads plugin folders (plugin.json and assets/) and prints what the real defender says about each. The Python library's
|
||||
* tests compare this output with its own defender: the two must never disagree.
|
||||
*/
|
||||
public final class GuardDump {
|
||||
private GuardDump() {}
|
||||
|
||||
private static byte[] bytes(File file) throws IOException {
|
||||
byte[] bytes = new byte[(int) file.length()];
|
||||
FileInputStream in = new FileInputStream(file);
|
||||
try {
|
||||
int at = 0;
|
||||
while (at < bytes.length) at += in.read(bytes, at, bytes.length - at);
|
||||
} finally {
|
||||
in.close();
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
boolean hashes = args.length > 0 && args[0].equals("--hash");
|
||||
for (String folder : args) {
|
||||
if (folder.equals("--hash")) continue;
|
||||
Map<String, byte[]> files = new LinkedHashMap<String, byte[]>();
|
||||
File[] found = new File(folder, "assets").listFiles();
|
||||
if (found != null) {
|
||||
Arrays.sort(found);
|
||||
for (File file : found) files.put(file.getName(), bytes(file));
|
||||
}
|
||||
String out;
|
||||
try {
|
||||
Plugin plugin = Plugin.parse(bytes(new File(folder, "plugin.json")), files);
|
||||
out = hashes ? plugin.sha256 : Defender.check(plugin).text();
|
||||
} catch (LtpException refused) {
|
||||
out = "REFUSED: " + refused.getMessage();
|
||||
}
|
||||
System.out.println("=====" + new File(folder).getName());
|
||||
System.out.println(new String(out.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
703
tests/java/lihont/two/plugin/PluginTest.java
Normal file
703
tests/java/lihont/two/plugin/PluginTest.java
Normal file
@@ -0,0 +1,703 @@
|
||||
package lihont.two.plugin;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
/** The plugin core on a plain JVM: reading, refusing, conditions, names, the zip. Each scenario prints PASS or fails. */
|
||||
public final class PluginTest {
|
||||
private PluginTest() {}
|
||||
|
||||
/** A hand-made moment: a video or a name. */
|
||||
private static final class Fake implements Ctx {
|
||||
String text = "";
|
||||
Set<String> tags = new HashSet<String>();
|
||||
String author = "";
|
||||
String authorUid = "";
|
||||
String selfName = "me";
|
||||
String selfUid = "1000001";
|
||||
String uid = "";
|
||||
int minute = 12 * 60;
|
||||
int weekday = 3;
|
||||
|
||||
@Override public String text() { return text; }
|
||||
@Override public Set<String> hashtags() { return tags; }
|
||||
@Override public String author() { return author; }
|
||||
@Override public String authorUid() { return authorUid; }
|
||||
@Override public String selfName() { return selfName; }
|
||||
@Override public String selfUid() { return selfUid; }
|
||||
@Override public String uid() { return uid; }
|
||||
@Override public int minute() { return minute; }
|
||||
@Override public int weekday() { return weekday; }
|
||||
@Override public String clock() { return "14:35"; }
|
||||
@Override public String date() { return "25.10"; }
|
||||
}
|
||||
|
||||
private static void check(boolean condition, String what) {
|
||||
if (!condition) throw new AssertionError(what);
|
||||
}
|
||||
|
||||
private static Plugin plugin(String json) throws LtpException {
|
||||
return Plugin.parse(json.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String head(String permissions, String rule) {
|
||||
return "{\"ltp\":1,\"id\":\"test.plugin\",\"name\":\"T\",\"version\":\"1\",\"author\":\"A\","
|
||||
+ "\"permissions\":" + permissions + ",\"rules\":[" + rule + "]}";
|
||||
}
|
||||
|
||||
private static String hide(String condition) {
|
||||
return "{\"title\":\"r\",\"when\":\"feed.item\"" + (condition == null ? "" : ",\"if\":" + condition)
|
||||
+ ",\"do\":[{\"feed.hide\":true}]}";
|
||||
}
|
||||
|
||||
private static void refused(String json, String needle) {
|
||||
try {
|
||||
plugin(json);
|
||||
} catch (LtpException expected) {
|
||||
check(expected.getMessage().contains(needle), "message «" + expected.getMessage() + "» lacks «" + needle + "»");
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("accepted, expected a refusal with «" + needle + "»: " + json);
|
||||
}
|
||||
|
||||
// ---- scenarios -------------------------------------------------------------------------
|
||||
|
||||
private static void parse() throws Exception {
|
||||
Plugin p = plugin(head("[\"feed.hide\"]", hide("{\"text\":[\"Giveaway\",\"розыгрыш\"]}")));
|
||||
check(p.id.equals("test.plugin") && p.rules.size() == 1 && p.permissions.contains("feed.hide"), "fields");
|
||||
check(p.sha256.length() == 64, "hash length");
|
||||
Fake f = new Fake();
|
||||
f.text = "big giveaway today";
|
||||
check(Evaluator.hidingRule(p, f) != null, "text word, case-insensitive");
|
||||
f.text = "cooking";
|
||||
check(Evaluator.hidingRule(p, f) == null, "no match");
|
||||
// a rule without a condition applies to everything
|
||||
Plugin all = plugin(head("[\"feed.hide\"]", hide(null)));
|
||||
check(Evaluator.hidingRule(all, f) != null, "no condition means always");
|
||||
// the shipped samples are valid, files of their assets/ included
|
||||
for (File file : new File("plugins").listFiles()) {
|
||||
if (!file.isDirectory()) continue;
|
||||
Plugin sample = sample(file.getName());
|
||||
check(sample.id.equals(file.getName()), "folder is the id: " + file.getName());
|
||||
}
|
||||
}
|
||||
|
||||
private static void refusals() throws Exception {
|
||||
String ok = hide("{\"text\":[\"a\"]}");
|
||||
refused(head("[]", ok), "feed.hide"); // the action's right is not declared
|
||||
refused(head("[\"feed.hide\",\"names\"]", ok), "не использует"); // a right nobody uses
|
||||
refused(head("[\"feed.hide\",\"feed.hide\"]", ok), "дважды");
|
||||
refused(head("[\"teleport\"]", ok), "Неизвестное право");
|
||||
refused("{\"ltp\":2,\"id\":\"test.plugin\",\"name\":\"T\",\"version\":\"1\",\"author\":\"A\","
|
||||
+ "\"permissions\":[],\"rules\":[" + ok + "]}", "обновите мод");
|
||||
refused(head("[\"feed.hide\"]", ok).replace("test.plugin", "Bad Id"), "id");
|
||||
refused(head("[\"feed.hide\"]", ok).replace("\"ltp\":1,", ""), "ltp");
|
||||
refused(head("[\"feed.hide\"]", hide("{\"text\":[\"a\"],\"hashtag\":[\"b\"]}")), "ровно одно");
|
||||
refused(head("[\"feed.hide\"]", hide("{\"magic\":[\"a\"]}")), "такого условия нет");
|
||||
refused(head("[\"feed.hide\"]", hide("{\"time\":\"25:00-07:00\"}")), "время");
|
||||
refused(head("[\"feed.hide\"]", hide("{\"time\":\"10:00-10:00\"}")), "не равно");
|
||||
refused(head("[\"feed.hide\"]", hide("{\"weekday\":[8]}")), "от 1 до 7");
|
||||
refused(head("[\"feed.hide\"]", hide("{\"text\":[]}")), "пуст");
|
||||
refused(head("[\"feed.hide\"]", "{\"title\":\"r\",\"when\":\"app.start\",\"do\":[{\"feed.hide\":true}]}"), "screen.show");
|
||||
refused(head("[\"feed.hide\"]", "{\"title\":\"r\",\"when\":\"name.show\",\"do\":[{\"feed.hide\":true}]}"), "только в правиле feed.item");
|
||||
refused(head("[\"names\"]", "{\"title\":\"r\",\"when\":\"feed.item\",\"do\":[{\"name.prefix\":\"x\"}]}"), "только в правиле name.show");
|
||||
refused(head("[\"feed.hide\"]", "{\"title\":\"r\",\"when\":\"feed.item\",\"do\":[]}"), "от 1 до");
|
||||
refused(head("[\"feed.hide\"]", "{\"title\":\"r\",\"when\":\"feed.item\",\"do\":[{\"launch\":\"rm\"}]}"), "такого действия нет");
|
||||
refused(head("[\"feed.hide\"]", ok).replace("\"name\":\"T\"", "\"name\":\"T\\u0001\""), "управляющие");
|
||||
refused(head("[\"feed.hide\"]", ok).replace("\"id\":", "\"id\":\"x.y.z\",\"id\":"), "повторяется");
|
||||
refused("[1,2]", "нужен объект");
|
||||
refused("{\"ltp\":1,", "ожидалось имя поля");
|
||||
// nesting
|
||||
StringBuilder deep = new StringBuilder("{\"text\":[\"a\"]}");
|
||||
for (int i = 0; i < 6; i++) deep.insert(0, "{\"not\":").append("}");
|
||||
refused(head("[\"feed.hide\"]", hide(deep.toString())), "глубоко");
|
||||
// bytes that are not UTF-8
|
||||
try {
|
||||
Plugin.parse(new byte[] {'{', (byte) 0xff, (byte) 0xfe, '}'});
|
||||
throw new AssertionError("accepted bad UTF-8");
|
||||
} catch (LtpException expected) {
|
||||
check(expected.getMessage().contains("UTF-8"), "utf-8 message");
|
||||
}
|
||||
// too big
|
||||
try {
|
||||
Plugin.parse(new byte[Json.MAX_CHARS + 1]);
|
||||
throw new AssertionError("accepted a huge file");
|
||||
} catch (LtpException expected) {
|
||||
check(expected.getMessage().contains("256"), "size message");
|
||||
}
|
||||
}
|
||||
|
||||
private static void conditions() throws Exception {
|
||||
Fake f = new Fake();
|
||||
Plugin tags = plugin(head("[\"feed.hide\"]", hide("{\"hashtag\":[\"#Prank\",\"fyp\"]}")));
|
||||
f.tags.add("prank");
|
||||
check(Evaluator.hidingRule(tags, f) != null, "hashtag with # and case");
|
||||
f.tags.clear();
|
||||
f.tags.add("cats");
|
||||
check(Evaluator.hidingRule(tags, f) == null, "other hashtag");
|
||||
|
||||
Plugin author = plugin(head("[\"feed.hide\"]", hide("{\"author\":[\"spammer\",\"self\"]}")));
|
||||
f.author = "spammer";
|
||||
check(Evaluator.hidingRule(author, f) != null, "author by name");
|
||||
f.author = "me";
|
||||
check(Evaluator.hidingRule(author, f) != null, "author self by name");
|
||||
f.author = "";
|
||||
f.authorUid = "1000001";
|
||||
check(Evaluator.hidingRule(author, f) != null, "author self by id");
|
||||
f.authorUid = "2";
|
||||
check(Evaluator.hidingRule(author, f) == null, "other author");
|
||||
|
||||
Plugin night = plugin(head("[\"feed.hide\"]", hide("{\"time\":\"22:00-07:00\"}")));
|
||||
f.minute = 23 * 60;
|
||||
check(Evaluator.hidingRule(night, f) != null, "late evening is in the range");
|
||||
f.minute = 3 * 60;
|
||||
check(Evaluator.hidingRule(night, f) != null, "small hours are in the range");
|
||||
f.minute = 7 * 60;
|
||||
check(Evaluator.hidingRule(night, f) == null, "the end is outside");
|
||||
f.minute = 12 * 60;
|
||||
check(Evaluator.hidingRule(night, f) == null, "noon is outside");
|
||||
Plugin day = plugin(head("[\"feed.hide\"]", hide("{\"time\":\"09:00-18:00\"}")));
|
||||
check(Evaluator.hidingRule(day, f) != null, "plain range");
|
||||
|
||||
Plugin weekend = plugin(head("[\"feed.hide\"]", hide("{\"weekday\":[6,7]}")));
|
||||
f.weekday = 6;
|
||||
check(Evaluator.hidingRule(weekend, f) != null, "saturday");
|
||||
f.weekday = 2;
|
||||
check(Evaluator.hidingRule(weekend, f) == null, "tuesday");
|
||||
|
||||
Plugin combo = plugin(head("[\"feed.hide\"]",
|
||||
hide("{\"all\":[{\"weekday\":[2]},{\"not\":{\"text\":[\"keep\"]}},{\"any\":[{\"text\":[\"x\"]},{\"hashtag\":[\"y\"]}]}]}")));
|
||||
f.weekday = 2;
|
||||
f.text = "x here";
|
||||
check(Evaluator.hidingRule(combo, f) != null, "all/any/not true");
|
||||
f.text = "x keep";
|
||||
check(Evaluator.hidingRule(combo, f) == null, "not makes it false");
|
||||
|
||||
Plugin account = plugin(head("[\"feed.hide\"]", hide("{\"account\":[\"someoneelse\"]}")));
|
||||
check(Evaluator.hidingRule(account, f) == null, "rule for another account stays silent");
|
||||
Plugin mine = plugin(head("[\"feed.hide\"]", hide("{\"account\":[\"ME\"]}")));
|
||||
f.text = "";
|
||||
check(Evaluator.hidingRule(mine, f) != null, "rule for this account");
|
||||
}
|
||||
|
||||
private static void names() throws Exception {
|
||||
String rules = "{\"title\":\"p\",\"when\":\"name.show\",\"if\":{\"uid\":[\"self\"]},\"do\":[{\"name.suffix\":\" · {time}\"}]},"
|
||||
+ "{\"title\":\"q\",\"when\":\"name.show\",\"if\":{\"uid\":[\"555\"]},\"do\":[{\"name.prefix\":\"★ \"},{\"name.suffix\":\" ({date})\"}]},"
|
||||
+ "{\"title\":\"r\",\"when\":\"name.show\",\"if\":{\"uid\":[\"777\"]},\"do\":[{\"name.replace\":\"Друг {name}\"}]}";
|
||||
Plugin p = plugin(head("[\"names\"]", rules));
|
||||
Fake f = new Fake();
|
||||
f.uid = "1000001";
|
||||
check(Evaluator.rename(p, f, "Я").equals("Я · 14:35"), "own name gets the time");
|
||||
f.uid = "555";
|
||||
check(Evaluator.rename(p, f, "Аня").equals("★ Аня (25.10)"), "prefix and suffix together");
|
||||
f.uid = "777";
|
||||
check(Evaluator.rename(p, f, "Боб").equals("Друг Боб"), "replace may use {name}");
|
||||
f.uid = "999";
|
||||
check(Evaluator.rename(p, f, "Кто-то").equals("Кто-то"), "other accounts are untouched");
|
||||
f.uid = "";
|
||||
check(Evaluator.rename(p, f, "Видео").equals("Видео"), "no account, no rename");
|
||||
// the result is capped
|
||||
StringBuilder long80 = new StringBuilder();
|
||||
for (int i = 0; i < 90; i++) long80.append('x');
|
||||
f.uid = "555";
|
||||
check(Evaluator.rename(p, f, long80.toString()).length() == Evaluator.MAX_NAME, "capped at 80");
|
||||
// notices are read from the rule
|
||||
Plugin n = plugin(head("[\"feed.hide\",\"ui.notice\"]",
|
||||
"{\"title\":\"n\",\"when\":\"feed.item\",\"limit\":2,\"do\":[{\"feed.hide\":true},{\"notice\":\"hi\"}]}"));
|
||||
List<Rule> matched = Evaluator.matching(n, Rule.FEED, new Fake());
|
||||
check(matched.size() == 1 && Evaluator.notices(matched.get(0)).equals(Arrays.asList("hi")), "notice text");
|
||||
check(matched.get(0).limit == 2 && matched.get(0).hides(), "limit and hide");
|
||||
}
|
||||
|
||||
private static byte[] zip(Object... pairs) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
ZipOutputStream zip = new ZipOutputStream(out);
|
||||
for (int i = 0; i < pairs.length; i += 2) {
|
||||
String name = (String) pairs[i];
|
||||
zip.putNextEntry(new ZipEntry(name));
|
||||
if (!name.endsWith("/")) zip.write((byte[]) pairs[i + 1]);
|
||||
zip.closeEntry();
|
||||
}
|
||||
zip.close();
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static void packageRefused(byte[] data, String needle) {
|
||||
try {
|
||||
PluginPackage.read(new ByteArrayInputStream(data));
|
||||
} catch (LtpException expected) {
|
||||
check(expected.getMessage().contains(needle), "message «" + expected.getMessage() + "» lacks «" + needle + "»");
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("package accepted, expected «" + needle + "»");
|
||||
}
|
||||
|
||||
private static void pack() throws Exception {
|
||||
byte[] json = head("[\"feed.hide\"]", hide(null)).getBytes(StandardCharsets.UTF_8);
|
||||
byte[] png = new byte[] {(byte) 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3};
|
||||
PluginPackage ok = PluginPackage.read(new ByteArrayInputStream(zip("plugin.json", json, "icon.png", png)));
|
||||
check(Arrays.equals(ok.manifest, json) && ok.icon != null, "a good package");
|
||||
check(PluginPackage.read(new ByteArrayInputStream(zip("plugin.json", json))).icon == null, "icon is optional");
|
||||
packageRefused(zip("icon.png", png), "нет plugin.json");
|
||||
packageRefused(zip("plugin.json", json, "classes.dex", new byte[] {1}), "лишний файл");
|
||||
packageRefused(zip("plugin.json", json, "../evil.json", json), "лишний файл");
|
||||
packageRefused(zip("plugin.json", json, "sub/plugin.json", json), "лишний файл");
|
||||
packageRefused(zip("plugin.json", json, "dir/", new byte[0]), "папок");
|
||||
packageRefused(zip("plugin.json", json, "icon.png", new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9}), "не PNG");
|
||||
// java.util.zip will not write two entries of one name, so make the second one by changing a letter
|
||||
byte[] twice = zip("plugin.json", json, "plugin.jsoX", json);
|
||||
for (int i = 0; i + 11 <= twice.length; i++) {
|
||||
if (new String(twice, i, 11, StandardCharsets.ISO_8859_1).equals("plugin.jsoX")) twice[i + 10] = 'n';
|
||||
}
|
||||
packageRefused(twice, "повторяется");
|
||||
packageRefused(zip("plugin.json", json, "icon.png", png, "a", png, "b", png), "лишний файл");
|
||||
packageRefused(new byte[] {1, 2, 3, 4}, "plugin.json");
|
||||
// a zip bomb: tiny file, huge entry
|
||||
byte[] bomb = new byte[Json.MAX_CHARS + 1000];
|
||||
Arrays.fill(bomb, (byte) 'a');
|
||||
packageRefused(zip("plugin.json", bomb), "слишком большой");
|
||||
// a file that is simply too big
|
||||
byte[] big = new byte[PluginPackage.MAX_FILE + 5000];
|
||||
new java.util.Random(1).nextBytes(big);
|
||||
packageRefused(zip("plugin.json", json, "icon.png", big), "");
|
||||
}
|
||||
|
||||
|
||||
private static byte[] bytes(File file) throws IOException {
|
||||
byte[] bytes = new byte[(int) file.length()];
|
||||
FileInputStream in = new FileInputStream(file);
|
||||
try {
|
||||
int at = 0;
|
||||
while (at < bytes.length) at += in.read(bytes, at, bytes.length - at);
|
||||
} finally {
|
||||
in.close();
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static Map<String, byte[]> assetsOf(String id) throws IOException {
|
||||
Map<String, byte[]> files = new LinkedHashMap<String, byte[]>();
|
||||
File[] found = new File("plugins/" + id + "/assets").listFiles();
|
||||
if (found != null) {
|
||||
Arrays.sort(found);
|
||||
for (File file : found) files.put(file.getName(), bytes(file));
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
private static Plugin sample(String id) throws Exception {
|
||||
return Plugin.parse(bytes(new File("plugins/" + id + "/plugin.json")), assetsOf(id));
|
||||
}
|
||||
|
||||
private static void dayCycle() throws Exception {
|
||||
Plugin p = sample("lihont.day-cycle");
|
||||
check(p.permissions.equals(Arrays.asList("names", "ui.notice")), "rights");
|
||||
Fake me = new Fake();
|
||||
me.uid = me.selfUid;
|
||||
String[][] cases = {
|
||||
{"06:00", "Я ☀️"}, {"11:59", "Я ☀️"}, {"12:00", "Я 🌤️"}, {"17:59", "Я 🌤️"},
|
||||
{"18:00", "Я 🌆"}, {"22:59", "Я 🌆"}, {"23:00", "Я 🌙"}, {"00:00", "Я 🌙"}, {"05:59", "Я 🌙"},
|
||||
};
|
||||
for (String[] c : cases) {
|
||||
me.minute = Integer.parseInt(c[0].substring(0, 2)) * 60 + Integer.parseInt(c[0].substring(3));
|
||||
me.weekday = 3;
|
||||
check(Evaluator.rename(p, me, "Я").equals(c[1]), c[0] + " gives " + Evaluator.rename(p, me, "Я") + " not " + c[1]);
|
||||
}
|
||||
me.minute = 20 * 60;
|
||||
me.weekday = 5;
|
||||
check(Evaluator.rename(p, me, "Я").equals("Я 🌆 🎉"), "friday adds the party: " + Evaluator.rename(p, me, "Я"));
|
||||
me.weekday = 6;
|
||||
check(Evaluator.rename(p, me, "Я").equals("Я 🌆"), "saturday does not");
|
||||
Fake other = new Fake();
|
||||
other.uid = "555";
|
||||
other.minute = 9 * 60;
|
||||
check(Evaluator.rename(p, other, "Аня").equals("Аня"), "other people keep their names");
|
||||
|
||||
// the hints: at most one a day each, only at their time
|
||||
Fake feed = new Fake();
|
||||
feed.minute = 7 * 60;
|
||||
feed.weekday = 2;
|
||||
List<Rule> morning = Evaluator.matching(p, Rule.FEED, feed);
|
||||
check(morning.size() == 1 && Evaluator.notices(morning.get(0)).get(0).startsWith("Доброе утро"), "morning hint");
|
||||
check(morning.get(0).limit == 1, "once a day");
|
||||
feed.minute = 3 * 60;
|
||||
List<Rule> night = Evaluator.matching(p, Rule.FEED, feed);
|
||||
check(night.size() == 1 && Evaluator.notices(night.get(0)).get(0).contains("за полночь"), "night hint");
|
||||
feed.minute = 12 * 60;
|
||||
check(Evaluator.matching(p, Rule.FEED, feed).isEmpty(), "no hint at noon");
|
||||
feed.minute = 20 * 60;
|
||||
feed.weekday = 5;
|
||||
List<Rule> friday = Evaluator.matching(p, Rule.FEED, feed);
|
||||
check(friday.size() == 1 && Evaluator.notices(friday.get(0)).get(0).startsWith("Пятница"), "friday evening hint");
|
||||
for (Rule rule : p.rules) check(!rule.hides(), "the plugin never hides a video");
|
||||
}
|
||||
|
||||
private static Map<String, byte[]> files(String... names) {
|
||||
Map<String, byte[]> map = new LinkedHashMap<String, byte[]>();
|
||||
for (String name : names) map.put(name, new byte[] {1, 2, 3});
|
||||
return map;
|
||||
}
|
||||
|
||||
private static String screen(String overlay, String permissions) {
|
||||
return "{\"ltp\":1,\"id\":\"test.plugin\",\"name\":\"T\",\"version\":\"1\",\"author\":\"A\","
|
||||
+ "\"permissions\":" + permissions + ",\"rules\":[{\"title\":\"r\",\"when\":\"screen.show\","
|
||||
+ "\"do\":[{\"overlay\":" + overlay + "}]}]}";
|
||||
}
|
||||
|
||||
private static void refusedWith(String json, Map<String, byte[]> files, String needle) {
|
||||
try {
|
||||
Plugin.parse(json.getBytes(StandardCharsets.UTF_8), files);
|
||||
} catch (LtpException expected) {
|
||||
check(expected.getMessage().contains(needle), "message «" + expected.getMessage() + "» lacks «" + needle + "»");
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("accepted, expected a refusal with «" + needle + "»: " + json);
|
||||
}
|
||||
|
||||
private static void overlay() throws Exception {
|
||||
Map<String, byte[]> files = files("cat.gif", "meow.ogg", "pet.gif");
|
||||
String plain = "{\"image\":\"cat.gif\"}";
|
||||
Plugin one = Plugin.parse(screen(plain, "[\"ui.overlay\"]").getBytes(StandardCharsets.UTF_8), files);
|
||||
check(one.assets.size() == 3 && one.hasOverlays() && one.hasRulesFor(Rule.SCREEN), "a plain picture");
|
||||
OverlaySpec spec = one.rules.get(0).overlays().get(0);
|
||||
check(spec.size == 140 && spec.alpha == 100 && spec.right == 16 && spec.bottom == 16 && spec.movable
|
||||
&& spec.animateMs == 1250 && spec.tap.equals(Arrays.asList("animate")) && spec.sound == null && spec.pet == null,
|
||||
"defaults");
|
||||
|
||||
String full = "{\"image\":\"cat.gif\",\"size\":200,\"alpha\":80,\"right\":5,\"bottom\":9,\"movable\":false,"
|
||||
+ "\"tap\":[\"animate\",\"sound\",\"like\"],\"sound\":\"meow.ogg\",\"pet\":\"pet.gif\",\"animate_ms\":900}";
|
||||
String allRights = "[\"ui.overlay\",\"ui.sound\",\"feed.like\"]";
|
||||
Plugin two = Plugin.parse(screen(full, allRights).getBytes(StandardCharsets.UTF_8), files);
|
||||
OverlaySpec all = two.rules.get(0).overlays().get(0);
|
||||
check(all.size == 200 && all.alpha == 80 && !all.movable && all.tap.size() == 3 && all.pet.equals("pet.gif")
|
||||
&& all.animateMs == 900, "all fields");
|
||||
|
||||
// every right is needed, and only the ones that are used may be asked for
|
||||
refusedWith(screen(plain, "[]"), files, "ui.overlay");
|
||||
refusedWith(screen(full, "[\"ui.overlay\",\"feed.like\"]"), files, "ui.sound");
|
||||
refusedWith(screen(full, "[\"ui.overlay\",\"ui.sound\"]"), files, "feed.like");
|
||||
refusedWith(screen(plain, "[\"ui.overlay\",\"ui.sound\"]"), files, "не использует");
|
||||
refusedWith(screen(plain, "[\"ui.overlay\",\"feed.like\"]"), files, "не использует");
|
||||
// the files must be in the plugin and be the right kind
|
||||
refusedWith(screen("{\"image\":\"gone.gif\"}", "[\"ui.overlay\"]"), files, "assets/gone.gif");
|
||||
refusedWith(screen(full, allRights), files("cat.gif", "pet.gif"), "assets/meow.ogg");
|
||||
refusedWith(screen("{\"image\":\"meow.ogg\"}", "[\"ui.overlay\"]"), files, "png, gif или webp");
|
||||
refusedWith(screen("{\"image\":\"cat.gif\",\"tap\":[\"sound\"],\"sound\":\"cat.gif\"}", "[\"ui.overlay\",\"ui.sound\"]"),
|
||||
files, "ogg или mp3");
|
||||
// ranges, names, unknown fields, the wrong trigger
|
||||
refusedWith(screen("{\"image\":\"cat.gif\",\"size\":10}", "[\"ui.overlay\"]"), files, "от 40 до 400");
|
||||
refusedWith(screen("{\"image\":\"cat.gif\",\"size\":401}", "[\"ui.overlay\"]"), files, "от 40 до 400");
|
||||
refusedWith(screen("{\"image\":\"cat.gif\",\"alpha\":5}", "[\"ui.overlay\"]"), files, "от 10 до 100");
|
||||
refusedWith(screen("{\"image\":\"cat.gif\",\"right\":-1}", "[\"ui.overlay\"]"), files, "от 0 до");
|
||||
refusedWith(screen("{\"image\":\"cat.gif\",\"animate_ms\":10}", "[\"ui.overlay\"]"), files, "от 200 до 10000");
|
||||
refusedWith(screen("{\"image\":\"cat.gif\",\"color\":1}", "[\"ui.overlay\"]"), files, "нет поля «color»");
|
||||
refusedWith(screen("{\"image\":\"../cat.gif\"}", "[\"ui.overlay\"]"), files, "имя файла");
|
||||
refusedWith(screen("{\"image\":\"Cat.GIF\"}", "[\"ui.overlay\"]"), files, "имя файла");
|
||||
refusedWith(screen("{}", "[\"ui.overlay\"]"), files, "image");
|
||||
refusedWith(screen("{\"image\":\"cat.gif\",\"tap\":[\"explode\"]}", "[\"ui.overlay\"]"), files, "animate, sound и like");
|
||||
refusedWith(screen("{\"image\":\"cat.gif\",\"tap\":[\"like\",\"like\"]}", "[\"ui.overlay\",\"feed.like\"]"), files, "дважды");
|
||||
refusedWith(screen("{\"image\":\"cat.gif\",\"tap\":[\"sound\"]}", "[\"ui.overlay\",\"ui.sound\"]"), files, "нет");
|
||||
refusedWith(screen("{\"image\":\"cat.gif\",\"sound\":\"meow.ogg\"}", "[\"ui.overlay\",\"ui.sound\"]"), files, "нет «sound»");
|
||||
refusedWith(screen(plain, "[\"ui.overlay\"]").replace("screen.show", "feed.item"), files, "screen.show");
|
||||
refusedWith(head("[\"ui.overlay\"]", "{\"title\":\"r\",\"when\":\"name.show\",\"do\":[{\"overlay\":" + plain + "}]}"),
|
||||
files, "screen.show");
|
||||
// a plugin that points at no files cannot be read on its own either
|
||||
try {
|
||||
Plugin.parse(screen(plain, "[\"ui.overlay\"]").getBytes(StandardCharsets.UTF_8));
|
||||
throw new AssertionError("accepted a picture without files");
|
||||
} catch (LtpException expected) {
|
||||
check(expected.getMessage().contains("assets/cat.gif"), "no files message");
|
||||
}
|
||||
// a time condition decides whether the picture is wanted
|
||||
String timed = "{\"ltp\":1,\"id\":\"test.plugin\",\"name\":\"T\",\"version\":\"1\",\"author\":\"A\","
|
||||
+ "\"permissions\":[\"ui.overlay\"],\"rules\":[{\"title\":\"night\",\"when\":\"screen.show\","
|
||||
+ "\"if\":{\"time\":\"22:00-06:00\"},\"do\":[{\"overlay\":" + plain + "}]}]}";
|
||||
Plugin night = Plugin.parse(timed.getBytes(StandardCharsets.UTF_8), files);
|
||||
Fake f = new Fake();
|
||||
f.minute = 23 * 60;
|
||||
check(Evaluator.matching(night, Rule.SCREEN, f).size() == 1, "shown at night");
|
||||
f.minute = 12 * 60;
|
||||
check(Evaluator.matching(night, Rule.SCREEN, f).isEmpty(), "not at noon");
|
||||
}
|
||||
|
||||
private static void assetsPackage() throws Exception {
|
||||
byte[] json = head("[\"feed.hide\"]", hide(null)).getBytes(StandardCharsets.UTF_8);
|
||||
byte[] gif = "GIF89a....".getBytes(StandardCharsets.ISO_8859_1);
|
||||
byte[] ogg = "OggS....".getBytes(StandardCharsets.ISO_8859_1);
|
||||
byte[] png = new byte[] {(byte) 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a, 1};
|
||||
byte[] mp3 = new byte[] {'I', 'D', '3', 3, 0};
|
||||
byte[] webp = "RIFF....WEBP".getBytes(StandardCharsets.ISO_8859_1);
|
||||
PluginPackage ok = PluginPackage.read(new ByteArrayInputStream(zip("plugin.json", json, "assets/cat.gif", gif,
|
||||
"assets/meow.ogg", ogg, "assets/a.png", png, "assets/b.mp3", mp3, "assets/c.webp", webp)));
|
||||
check(ok.assets.size() == 5 && Arrays.equals(ok.assets.get("cat.gif"), gif), "assets are read");
|
||||
// the hash follows the files, and a plugin with no files keeps the plain hash
|
||||
Plugin plain = Plugin.parse(json);
|
||||
Plugin withFiles = Plugin.parse(json, ok.assets);
|
||||
check(!plain.sha256.equals(withFiles.sha256), "files change the hash");
|
||||
Map<String, byte[]> changed = new LinkedHashMap<String, byte[]>(ok.assets);
|
||||
changed.put("cat.gif", "GIF89a....X".getBytes(StandardCharsets.ISO_8859_1));
|
||||
check(!Plugin.parse(json, changed).sha256.equals(withFiles.sha256), "a changed file changes the hash");
|
||||
check(plain.sha256.equals(Plugin.parse(json, new LinkedHashMap<String, byte[]>()).sha256), "no files, same hash");
|
||||
// refusals
|
||||
packageRefused(zip("plugin.json", json, "assets/cat.gif", ogg), "не похож на GIF");
|
||||
packageRefused(zip("plugin.json", json, "assets/meow.ogg", gif), "не похож на Ogg");
|
||||
packageRefused(zip("plugin.json", json, "assets/x.exe", gif), "картинку или звук");
|
||||
packageRefused(zip("plugin.json", json, "assets/Cat.gif", gif), "лишний файл");
|
||||
packageRefused(zip("plugin.json", json, "assets/../cat.gif", gif), "лишний файл");
|
||||
packageRefused(zip("plugin.json", json, "assets/sub/cat.gif", gif), "лишний файл");
|
||||
packageRefused(zip("plugin.json", json, "assets/", new byte[0]), "папок");
|
||||
byte[] huge = new byte[PluginPackage.MAX_ASSET + 10];
|
||||
huge[0] = 'G';
|
||||
huge[1] = 'I';
|
||||
huge[2] = 'F';
|
||||
huge[3] = '8';
|
||||
packageRefused(zip("plugin.json", json, "assets/big.gif", huge), "слишком большой");
|
||||
Object[] nine = new Object[2 + 9 * 2];
|
||||
nine[0] = "plugin.json";
|
||||
nine[1] = json;
|
||||
for (int i = 0; i < 9; i++) {
|
||||
nine[2 + i * 2] = "assets/f" + i + ".gif";
|
||||
nine[3 + i * 2] = gif;
|
||||
}
|
||||
packageRefused(zip(nine), "больше 8");
|
||||
}
|
||||
|
||||
private static void boykisser() throws Exception {
|
||||
Plugin p = sample("lihont.boykisser");
|
||||
check(p.permissions.equals(Arrays.asList("ui.overlay", "ui.sound", "feed.like")), "rights");
|
||||
check(p.assets.equals(new java.util.TreeSet<String>(Arrays.asList("boykisser.gif", "meow.ogg", "pet.gif"))), "files");
|
||||
OverlaySpec spec = p.rules.get(0).overlays().get(0);
|
||||
check(spec.tap.equals(Arrays.asList("animate", "sound", "like")) && spec.pet.equals("pet.gif")
|
||||
&& spec.sound.equals("meow.ogg") && spec.movable, "taps");
|
||||
check(Evaluator.matching(p, Rule.SCREEN, new Fake()).size() == 1, "it is always on a screen");
|
||||
}
|
||||
|
||||
private static void defender() throws Exception {
|
||||
// a narrow hide rule is worth a look, nothing more, and says what it does in plain words
|
||||
Plugin narrow = sample("lihont.test-fyp");
|
||||
Defender.Report report = Defender.check(narrow);
|
||||
check(report.level == Defender.WATCH, "narrow hide: watch, was " + report.level);
|
||||
check(report.rules.get(0).contains("хэштег #fyp, #foryou, #foryoupage"), "rule says its tags: " + report.rules);
|
||||
check(report.rules.get(0).contains("скрыть видео"), "rule says it hides: " + report.rules);
|
||||
check(report.text().contains("Защитник: Обратите внимание"), "verdict in the text");
|
||||
check(report.text().contains("не может: выходить в интернет"), "what a plugin never does");
|
||||
|
||||
// names with a plain emoji around the owner's own name: calm
|
||||
Plugin day = sample("lihont.day-cycle");
|
||||
check(Defender.check(day).level != Defender.CAREFUL, "day cycle is not careful");
|
||||
|
||||
// hiding every video, with or without a time condition
|
||||
Plugin all = plugin(head("[\"feed.hide\"]", hide(null)));
|
||||
check(Defender.check(all).level == Defender.CAREFUL, "hide all: careful");
|
||||
check(Defender.check(all).notes.get(0).contains("скрывает все видео"), "says it hides all");
|
||||
Plugin timed = plugin(head("[\"feed.hide\"]", hide("{\"time\":\"22:00-07:00\"}")));
|
||||
check(Defender.check(timed).level == Defender.CAREFUL, "hide by time only: careful");
|
||||
check(Defender.check(timed).rules.get(0).contains("время с 22:00 до 07:00"), "time in words");
|
||||
Plugin both = plugin(head("[\"feed.hide\"]",
|
||||
hide("{\"all\":[{\"text\":[\"a\"]},{\"not\":{\"weekday\":[6,7]}}]}")));
|
||||
check(Defender.check(both).level == Defender.WATCH, "words and a day: watch");
|
||||
check(Defender.check(both).rules.get(0).contains("в описании есть «a» и не в дни: сб, вс"), "nested in words: "
|
||||
+ Defender.check(both).rules);
|
||||
|
||||
// replacing every name
|
||||
Plugin names = plugin(head("[\"names\"]",
|
||||
"{\"title\":\"x\",\"when\":\"name.show\",\"do\":[{\"name.replace\":\"Ыы\"}]}"));
|
||||
check(Defender.check(names).level == Defender.CAREFUL, "replace all names: careful");
|
||||
Plugin one = plugin(head("[\"names\"]",
|
||||
"{\"title\":\"x\",\"when\":\"name.show\",\"if\":{\"uid\":[\"123456\"]},\"do\":[{\"name.replace\":\"Ыы\"}]}"));
|
||||
check(Defender.check(one).level == Defender.WATCH, "replace a chosen name: watch");
|
||||
|
||||
// the pictures: likes are careful, the boykisser asks for one
|
||||
Plugin boykisser = sample("lihont.boykisser");
|
||||
Defender.Report meow = Defender.check(boykisser);
|
||||
check(meow.level == Defender.CAREFUL, "boykisser likes: careful");
|
||||
check(meow.text().contains("лайк видео"), "like in words: " + meow.text());
|
||||
check(meow.text().contains("Играет звук"), "sound is named");
|
||||
check(meow.notes.get(0).startsWith("Осторожно"), "most serious first");
|
||||
|
||||
// the deliberately bad plugin trips every alarm at once
|
||||
Defender.Report bad = Defender.check(sample("lihont.test-malware"));
|
||||
check(bad.level == Defender.CAREFUL, "bad plugin: careful");
|
||||
int alarms = 0;
|
||||
for (String note : bad.notes) alarms += note.startsWith("Осторожно") ? 1 : 0;
|
||||
check(alarms == 4, "four alarms for the bad plugin, was " + alarms + ": " + bad.notes);
|
||||
check(bad.text().contains("скрывает все видео в ленте без исключений"), "hide-all alarm");
|
||||
check(bad.text().contains("подменяет все имена"), "replace-all alarm");
|
||||
check(bad.text().contains("закреплена"), "pinned picture alarm");
|
||||
}
|
||||
|
||||
/** A screen plugin that downloads `download` (JSON of one action) and shows the picture it fetches. */
|
||||
private static String online(String permissions, String net, String download) {
|
||||
return "{\"ltp\":1,\"id\":\"test.plugin\",\"name\":\"T\",\"version\":\"1\",\"author\":\"A\","
|
||||
+ "\"permissions\":" + permissions + (net == null ? "" : ",\"net\":" + net)
|
||||
+ ",\"rules\":[{\"title\":\"r\",\"when\":\"screen.show\",\"do\":[" + download
|
||||
+ ",{\"overlay\":{\"image\":\"cat.png\"}}]}]}";
|
||||
}
|
||||
|
||||
private static String fetch(String url, String as, String sha) {
|
||||
return "{\"download\":{\"url\":\"" + url + "\",\"as\":\"" + as + "\"" + (sha == null ? "" : ",\"sha256\":\"" + sha + "\"")
|
||||
+ "}}";
|
||||
}
|
||||
|
||||
private static final String RIGHTS = "[\"net.download\",\"ui.overlay\"]";
|
||||
private static final String CDN = "{\"hosts\":[\"cdn.example.com\"]}";
|
||||
private static final String GOOD = fetch("https://cdn.example.com/a/cat.png", "cat.png", null);
|
||||
|
||||
private static void refusedNet(String json, String needle) {
|
||||
refusedWith(json, files(), needle);
|
||||
}
|
||||
|
||||
private static void download() throws Exception {
|
||||
Plugin good = Plugin.parse(online(RIGHTS, CDN, GOOD).getBytes(StandardCharsets.UTF_8), files());
|
||||
check(good.hosts.equals(Arrays.asList("cdn.example.com")), "hosts: " + good.hosts);
|
||||
check(good.downloads().size() == 1 && good.downloads().get(0).as.equals("cat.png")
|
||||
&& good.downloads().get(0).host.equals("cdn.example.com")
|
||||
&& good.downloads().get(0).sha256 == null, "the download is read");
|
||||
check(good.assets.isEmpty(), "a downloaded file is not an asset");
|
||||
check(Plugin.parse(head("[\"feed.hide\"]", hide(null)).getBytes(StandardCharsets.UTF_8)).hosts.isEmpty(),
|
||||
"no net, no hosts");
|
||||
String pinned = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
Plugin withHash = Plugin.parse(online(RIGHTS, CDN, fetch("https://cdn.example.com/cat.png", "cat.png", pinned))
|
||||
.getBytes(StandardCharsets.UTF_8), files());
|
||||
check(withHash.downloads().get(0).sha256.equals(pinned), "the hash is kept");
|
||||
Plugin query = Plugin.parse(online(RIGHTS, CDN, fetch("https://cdn.example.com/cat.png?v=2", "cat.png", null))
|
||||
.getBytes(StandardCharsets.UTF_8), files());
|
||||
check(query.downloads().get(0).url.endsWith("?v=2"), "a plain query string is fine");
|
||||
|
||||
// the right, the list of sites and the actions have to agree
|
||||
refusedNet(online("[\"ui.overlay\"]", CDN, GOOD), "net.download");
|
||||
refusedNet(online("[\"ui.overlay\"]", CDN, "{\"overlay\":{\"image\":\"cat.png\"}}"), "есть «net», но нет права");
|
||||
refusedNet(online(RIGHTS, null, GOOD), "требует поле «net»");
|
||||
refusedNet(online(RIGHTS, "{\"hosts\":[]}", GOOD), "от 1 до 4");
|
||||
refusedNet(online(RIGHTS, "{\"hosts\":[\"cdn.example.com\",\"other.example.org\"]}", GOOD), "ничего не скачивается");
|
||||
refusedNet(online(RIGHTS, "{\"hosts\":[\"other.example.org\"]}", GOOD), "нет в списке");
|
||||
refusedNet(online(RIGHTS, "{\"hosts\":[\"cdn.example.com\",\"cdn.example.com\"]}", GOOD), "дважды");
|
||||
refusedNet(online(RIGHTS, "{\"hosts\":[\"cdn.example.com\"],\"x\":1}", GOOD), "нет поля «x»");
|
||||
refusedNet(online("[\"net.download\",\"ui.overlay\"]", CDN, "{\"overlay\":{\"image\":\"cat.png\"}}"), "не использует");
|
||||
|
||||
// the address: https, a plain host, no port, no login, no tricks
|
||||
refusedNet(online(RIGHTS, CDN, fetch("http://cdn.example.com/cat.png", "cat.png", null)), "https://");
|
||||
refusedNet(online(RIGHTS, CDN, fetch("https://cdn.example.com:8443/cat.png", "cat.png", null)), "логина, пароля или порта");
|
||||
refusedNet(online(RIGHTS, CDN, fetch("https://user@cdn.example.com/cat.png", "cat.png", null)), "логина, пароля или порта");
|
||||
refusedNet(online(RIGHTS, "{\"hosts\":[\"10.0.0.1\"]}", fetch("https://10.0.0.1/cat.png", "cat.png", null)), "имя сайта");
|
||||
refusedNet(online(RIGHTS, "{\"hosts\":[\"localhost\"]}", fetch("https://localhost/cat.png", "cat.png", null)), "имя сайта");
|
||||
refusedNet(online(RIGHTS, "{\"hosts\":[\"Cdn.Example.com\"]}", GOOD), "имя сайта");
|
||||
refusedNet(online(RIGHTS, CDN, fetch("https://cdn.example.com", "cat.png", null)), "нужен путь");
|
||||
refusedNet(online(RIGHTS, CDN, fetch("https://cdn.example.com/../cat.png", "cat.png", null)), "лишние знаки");
|
||||
refusedNet(online(RIGHTS, CDN, fetch("https://cdn.example.com/cat.png#top", "cat.png", null)), "лишние знаки");
|
||||
refusedNet(online(RIGHTS, CDN, fetch("https://cdn.example.com/cat png", "cat.png", null)), "лишние знаки");
|
||||
|
||||
// the file: a name of the usual kind, a real hash, no repeats, none of the plugin's own names
|
||||
refusedNet(online(RIGHTS, CDN, fetch("https://cdn.example.com/a.txt", "a.txt", null)), "png, gif, webp, ogg или mp3");
|
||||
refusedNet(online(RIGHTS, CDN, fetch("https://cdn.example.com/Cat.png", "Cat.PNG", null)), "имя файла");
|
||||
refusedNet(online(RIGHTS, CDN, fetch("https://cdn.example.com/cat.png", "cat.png", "abc")), "64 цифры");
|
||||
refusedNet(online(RIGHTS, CDN, GOOD + "," + fetch("https://cdn.example.com/b/cat.png", "cat.png", null)), "дважды");
|
||||
refusedWith(online(RIGHTS, CDN, GOOD), files("cat.png"), "уже есть в плагине");
|
||||
refusedNet(online(RIGHTS, CDN, "{\"download\":{\"url\":\"https://cdn.example.com/cat.png\"}}"), "as");
|
||||
refusedNet(online(RIGHTS, CDN, "{\"download\":{\"url\":\"https://cdn.example.com/cat.png\",\"as\":\"cat.png\",\"post\":1}}"),
|
||||
"нет поля «post»");
|
||||
StringBuilder many = new StringBuilder();
|
||||
for (int i = 0; i < 5; i++) many.append(i > 0 ? "," : "").append(fetch("https://cdn.example.com/c" + i + ".png", "c" + i + ".png", null));
|
||||
refusedNet(online(RIGHTS, CDN, many.toString()), "больше 4 скачиваний");
|
||||
// only a screen rule may download
|
||||
refusedNet("{\"ltp\":1,\"id\":\"test.plugin\",\"name\":\"T\",\"version\":\"1\",\"author\":\"A\",\"permissions\":[\"net.download\"],"
|
||||
+ "\"net\":" + CDN + ",\"rules\":[{\"title\":\"r\",\"when\":\"feed.item\",\"do\":[" + GOOD + "]}]}",
|
||||
"screen.show");
|
||||
|
||||
// what is checked about the bytes that arrive
|
||||
DownloadSpec spec = good.downloads().get(0);
|
||||
byte[] png = {(byte) 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3};
|
||||
check(Downloader.verify(spec, png) == png, "a real png passes");
|
||||
failsWith(spec, new byte[] {1, 2, 3, 4}, "тип файла");
|
||||
failsWith(spec, new byte[0], "пустой");
|
||||
failsWith(spec, new byte[Downloader.MAX_BYTES + 1], "больше");
|
||||
DownloadSpec pinnedSpec = Plugin.parse(online(RIGHTS, CDN, fetch("https://cdn.example.com/cat.png", "cat.png",
|
||||
Downloader.sha256(png))).getBytes(StandardCharsets.UTF_8), files()).downloads().get(0);
|
||||
check(Downloader.verify(pinnedSpec, png) == png, "the pinned hash matches");
|
||||
byte[] other = png.clone();
|
||||
other[10] = 9;
|
||||
failsWith(pinnedSpec, other, "контрольная сумма");
|
||||
|
||||
// the defender says what it found, and that the one exception to "no internet" is named
|
||||
Defender.Report open = Defender.check(good);
|
||||
check(open.level == Defender.WATCH, "a plain download: watch, was " + open.level);
|
||||
check(open.net && open.text().contains("Скачивает файлы из интернета с сайтов: cdn.example.com"), "sites named: " + open.text());
|
||||
check(open.text().contains("без проверки по контрольной сумме"), "unpinned is mentioned");
|
||||
check(open.text().contains("ходить куда-либо, кроме названных сайтов"), "the exception is named");
|
||||
check(!open.text().contains("выходить в интернет"), "the plain 'no internet' line is not shown");
|
||||
check(!Defender.check(withHash).text().contains("без проверки"), "a pinned file has no such note");
|
||||
check(open.rules.get(0).contains("скачать файл cat.png с сайта cdn.example.com"), "the rule in words: " + open.rules);
|
||||
check(!Defender.check(sample("lihont.test-fyp")).net, "a plugin without downloads keeps the old line");
|
||||
}
|
||||
|
||||
private static void failsWith(DownloadSpec spec, byte[] data, String needle) {
|
||||
try {
|
||||
Downloader.verify(spec, data);
|
||||
} catch (IOException expected) {
|
||||
check(expected.getMessage().contains(needle), "message «" + expected.getMessage() + "» lacks «" + needle + "»");
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("accepted, expected a refusal with «" + needle + "»");
|
||||
}
|
||||
|
||||
private static void origin() throws Exception {
|
||||
String plain = head("[\"feed.hide\"]", hide("{\"hashtag\":[\"a\"]}"));
|
||||
Plugin none = plugin(plain);
|
||||
check(none.license.isEmpty() && none.ai.isEmpty(), "no fields: empty");
|
||||
check(Defender.check(none).text().contains("Автор не указал лицензию плагина."), "the defender notes a missing licence");
|
||||
String said = plain.replace("\"author\":\"A\",", "\"author\":\"A\",\"license\":\" MIT \",\"ai\":[\"Claude Sonnet 5.5\",\" GPT \"],");
|
||||
Plugin full = plugin(said);
|
||||
check(full.license.equals("MIT") && full.ai.equals(Arrays.asList("Claude Sonnet 5.5", "GPT")), "read and trimmed: " + full.ai);
|
||||
check(!Defender.check(full).text().contains("не указал лицензию"), "no note when the licence is named");
|
||||
check(Defender.check(full).level == Defender.WATCH, "the fields do not change the verdict");
|
||||
check(!full.sha256.equals(none.sha256), "the fields are part of the approved file");
|
||||
// limits
|
||||
refused(plain.replace("\"author\":\"A\",", "\"author\":\"A\",\"license\":\"" + "x".repeat(41) + "\","), "license");
|
||||
refused(plain.replace("\"author\":\"A\",", "\"author\":\"A\",\"license\":5,"), "нужен текст");
|
||||
refused(plain.replace("\"author\":\"A\",", "\"author\":\"A\",\"ai\":\"Claude\","), "нужен список");
|
||||
refused(plain.replace("\"author\":\"A\",", "\"author\":\"A\",\"ai\":[\"a\",\"b\",\"c\",\"d\",\"e\"],"), "не больше 4");
|
||||
refused(plain.replace("\"author\":\"A\",", "\"author\":\"A\",\"ai\":[\" \"],"), "пустая запись");
|
||||
refused(plain.replace("\"author\":\"A\",", "\"author\":\"A\",\"ai\":[7],"), "нужен текст");
|
||||
// the shipped plugins say what they are
|
||||
Plugin shipped = sample("lihont.quiet-night");
|
||||
check(shipped.license.equals("VCBFU-2") && shipped.ai.size() == 1, "shipped plugins name licence and AI");
|
||||
}
|
||||
|
||||
private static void hash() throws Exception {
|
||||
byte[] a = head("[\"feed.hide\"]", hide(null)).getBytes(StandardCharsets.UTF_8);
|
||||
byte[] b = head("[\"feed.hide\"]", hide(null)).replace("\"A\"", "\"B\"").getBytes(StandardCharsets.UTF_8);
|
||||
check(Plugin.parse(a).sha256.equals(Plugin.parse(a).sha256), "same bytes, same hash");
|
||||
check(!Plugin.parse(a).sha256.equals(Plugin.parse(b).sha256), "other bytes, other hash");
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String name = args[0];
|
||||
if (name.equals("parse")) parse();
|
||||
else if (name.equals("refusals")) refusals();
|
||||
else if (name.equals("conditions")) conditions();
|
||||
else if (name.equals("names")) names();
|
||||
else if (name.equals("package")) pack();
|
||||
else if (name.equals("hash")) hash();
|
||||
else if (name.equals("daycycle")) dayCycle();
|
||||
else if (name.equals("overlay")) overlay();
|
||||
else if (name.equals("assets")) assetsPackage();
|
||||
else if (name.equals("boykisser")) boykisser();
|
||||
else if (name.equals("defender")) defender();
|
||||
else if (name.equals("download")) download();
|
||||
else if (name.equals("origin")) origin();
|
||||
else throw new IllegalArgumentException(name);
|
||||
System.out.println("PASS " + name);
|
||||
}
|
||||
}
|
||||
109
tests/test_comment_photos_patch.py
Normal file
109
tests/test_comment_photos_patch.py
Normal file
@@ -0,0 +1,109 @@
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from lihont import comment_photos_patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
# LX/09Pr;->LIZ()Z of TikTok 47.1.3 as baksmali writes it (the line markers are real).
|
||||
GATE = """.class public final LX/09Pr;
|
||||
.super Ljava/lang/Object;
|
||||
.source "SourceFile"
|
||||
|
||||
# static fields
|
||||
.field public static final LIZ:LX/0AK0;
|
||||
|
||||
|
||||
# direct methods
|
||||
.method public static constructor <clinit>()V
|
||||
.registers 2
|
||||
|
||||
return-void
|
||||
.end method
|
||||
|
||||
.method public static LIZ()Z
|
||||
.registers 3
|
||||
.prologue
|
||||
|
||||
sget-object v0, LX/09Pr;->LIZ:LX/0AK0;
|
||||
|
||||
.line 33554432
|
||||
invoke-interface {v0}, LX/0AK0;->getValue()Ljava/lang/Object;
|
||||
|
||||
.line 33554433
|
||||
move-result-object v0
|
||||
|
||||
check-cast v0, Ljava/lang/Number;
|
||||
|
||||
invoke-virtual {v0}, Ljava/lang/Number;->intValue()I
|
||||
|
||||
move-result v2
|
||||
|
||||
if-eqz v2, :cond_14
|
||||
|
||||
const/4 v1, 0x1
|
||||
|
||||
if-eq v2, v1, :cond_14
|
||||
|
||||
const/4 v0, 0x2
|
||||
|
||||
if-eq v2, v0, :cond_15
|
||||
|
||||
:cond_14
|
||||
const/4 v1, 0x0
|
||||
|
||||
:cond_15
|
||||
return v1
|
||||
.end method
|
||||
"""
|
||||
|
||||
|
||||
class GateTest(unittest.TestCase):
|
||||
def test_the_answer_passes_through_the_hook_just_before_it_is_returned(self):
|
||||
text = comment_photos_patch.rewrite_gate(GATE)
|
||||
self.assertIn(
|
||||
" :cond_15\n invoke-static {v1}, %s\n\n move-result v1\n\n return v1\n.end method"
|
||||
% comment_photos_patch.HOOK, text)
|
||||
# nothing else of the class changes
|
||||
self.assertEqual(text.count("CommentPhotos"), 1)
|
||||
self.assertIn("if-eq v2, v0, :cond_15", text)
|
||||
self.assertIn(".registers 3", text)
|
||||
|
||||
def test_a_second_pass_is_refused(self):
|
||||
once = comment_photos_patch.rewrite_gate(GATE)
|
||||
with self.assertRaises(ValueError):
|
||||
comment_photos_patch.rewrite_gate(once)
|
||||
|
||||
def test_another_method_shape_is_refused(self):
|
||||
with self.assertRaises(ValueError):
|
||||
comment_photos_patch.rewrite_gate(GATE.replace("Ljava/lang/Number;->intValue()I", "Ljava/lang/Number;->longValue()J"))
|
||||
with self.assertRaises(ValueError):
|
||||
comment_photos_patch.rewrite_gate(GATE.replace(".registers 3", ".registers 4"))
|
||||
with self.assertRaises(ValueError):
|
||||
comment_photos_patch.rewrite_gate(GATE.replace("LIZ()Z", "LIZZ()Z"))
|
||||
|
||||
def test_two_returns_are_refused(self):
|
||||
with self.assertRaises(ValueError):
|
||||
comment_photos_patch.rewrite_gate(GATE.replace(" :cond_14\n", " return v1\n :cond_14\n"))
|
||||
|
||||
def test_runtime_target_matches_the_hook(self):
|
||||
self.assertEqual(comment_photos_patch.runtime_targets(), [comment_photos_patch.HOOK])
|
||||
source = (ROOT / "src" / "lihont" / "two" / "comments" / "CommentPhotos.java").read_text(encoding="utf-8")
|
||||
self.assertIn("public static boolean gate(boolean original)", source)
|
||||
# the hook is the only thing that makes the answer "yes": TikTok's own answer is never turned into "no"
|
||||
self.assertIn("original || on", source)
|
||||
|
||||
def test_the_build_applies_the_patch_and_checks_its_hook(self):
|
||||
build = (ROOT / "lihont" / "upgrade.py").read_text(encoding="utf-8")
|
||||
self.assertIn('step("comment_photos", patch_comment_photos', build)
|
||||
self.assertIn("comment_photos_patch.runtime_targets()", build)
|
||||
|
||||
def test_the_settings_screen_has_the_switch_and_it_is_on_by_default(self):
|
||||
screen = (ROOT / "src" / "lihont" / "two" / "settings" / "LihonTSettingsActivity.java").read_text(encoding="utf-8")
|
||||
self.assertIn("commentPhotosRow()", screen)
|
||||
source = (ROOT / "src" / "lihont" / "two" / "comments" / "CommentPhotos.java").read_text(encoding="utf-8")
|
||||
self.assertIn("getBoolean(KEY, true)", source)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
168
tests/test_ghost_patch.py
Normal file
168
tests/test_ghost_patch.py
Normal file
@@ -0,0 +1,168 @@
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from lihont import ghost_patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
# LX/0RDS;->LIZJ of TikTok 47.1.3 as baksmali writes it (shortened after the first calls).
|
||||
SAMPLE = """.class public final LX/0RDS;
|
||||
.super Ljava/lang/Object;
|
||||
|
||||
.method public final LIZIZ()V
|
||||
.registers 2
|
||||
|
||||
return-void
|
||||
.end method
|
||||
|
||||
.method public final LIZJ(Ljava/lang/Boolean;Ljava/lang/String;Ljava/lang/String;)V
|
||||
.registers 8
|
||||
|
||||
.prologue
|
||||
.line 50331648
|
||||
if-eqz p1, :cond_3c
|
||||
|
||||
.line 50331649
|
||||
invoke-virtual {p1}, Ljava/lang/Boolean;->booleanValue()Z
|
||||
|
||||
move-result v0
|
||||
|
||||
invoke-static {v0}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
|
||||
|
||||
move-result-object v2
|
||||
|
||||
:goto_a
|
||||
sget-object v1, Lcom/ss/android/ugc/aweme/story/api/StoryApi;->LIZIZ:Lcom/ss/android/ugc/aweme/story/api/StoryApi;
|
||||
|
||||
invoke-virtual {v1, p2, v0, v2}, Lcom/ss/android/ugc/aweme/story/api/StoryApi;->reportStoryViewed(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;)LX/12YD;
|
||||
|
||||
move-result-object v1
|
||||
|
||||
return-void
|
||||
|
||||
:cond_3c
|
||||
const/4 v2, 0x0
|
||||
|
||||
goto :goto_a
|
||||
.end method
|
||||
"""
|
||||
|
||||
|
||||
# LX/13pM;->LIZIZ of TikTok 47.1.3: the suspend entry that marks a conversation as read (shortened).
|
||||
MARK = """.class public final LX/13pM;
|
||||
.super Ljava/lang/Object;
|
||||
|
||||
.method public final LIZ(LX/13oK;LX/13pS;Z)Lcom/bytedance/im/core/proto/Request;
|
||||
.registers 4
|
||||
|
||||
const/4 v0, 0x0
|
||||
|
||||
return-object v0
|
||||
.end method
|
||||
|
||||
.method public final LIZIZ(Ljava/lang/Long;Ljava/lang/String;LX/01h3;)Ljava/lang/Object;
|
||||
.registers 10
|
||||
|
||||
.prologue
|
||||
.line 50331648
|
||||
instance-of v0, p3, LX/0c58;
|
||||
|
||||
.line 50331649
|
||||
if-eqz v0, :cond_45
|
||||
|
||||
move-object v5, p3
|
||||
|
||||
check-cast v5, LX/0c58;
|
||||
|
||||
invoke-static {}, LX/0NPd;->LJFF()Ljava/lang/Object;
|
||||
|
||||
move-result-object v4
|
||||
|
||||
:cond_45
|
||||
new-instance v5, LX/0c58;
|
||||
|
||||
return-object v4
|
||||
.end method
|
||||
"""
|
||||
|
||||
|
||||
class MarkReadTest(unittest.TestCase):
|
||||
def test_the_entry_returns_unit_at_once_while_the_switch_is_on_but_never_cuts_a_resumed_call(self):
|
||||
text = ghost_patch.rewrite_mark_read(MARK)
|
||||
self.assertIn(
|
||||
" .line 50331648\n"
|
||||
" invoke-static {}, %s\n\n move-result v0\n\n if-eqz v0, :lihont_mark_read\n\n"
|
||||
" instance-of v0, p3, LX/0c58;\n\n if-nez v0, :lihont_mark_read\n\n"
|
||||
" sget-object v0, Lkotlin/Unit;->LIZ:Lkotlin/Unit;\n\n return-object v0\n\n :lihont_mark_read\n\n"
|
||||
" instance-of v0, p3, LX/0c58;\n" % ghost_patch.MARK_READ_HOOK, text)
|
||||
# nothing else of the class changes: the request builder is untouched
|
||||
self.assertEqual(text.count("Ghost;"), 1)
|
||||
self.assertIn("LIZ(LX/13oK;LX/13pS;Z)Lcom/bytedance/im/core/proto/Request;", text)
|
||||
|
||||
def test_a_second_pass_is_refused(self):
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_mark_read(ghost_patch.rewrite_mark_read(MARK))
|
||||
|
||||
def test_another_shape_is_refused(self):
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_mark_read(MARK.replace(".registers 10", ".registers 11"))
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_mark_read(MARK.replace("LX/0NPd;->LJFF()", "LX/0NPd;->LJFG()"))
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_mark_read(MARK.replace("instance-of v0, p3", "instance-of v1, p3"))
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_mark_read(MARK.replace("LIZIZ(", "LIZJ("))
|
||||
|
||||
|
||||
class StoryViewTest(unittest.TestCase):
|
||||
def test_the_method_returns_before_anything_is_sent_while_the_switch_is_on(self):
|
||||
text = ghost_patch.rewrite_story_view(SAMPLE)
|
||||
self.assertIn(
|
||||
" .line 50331648\n"
|
||||
" invoke-static {}, %s\n\n move-result v0\n\n if-eqz v0, :lihont_story_view\n\n return-void\n\n"
|
||||
" :lihont_story_view\n\n if-eqz p1, :cond_3c\n" % ghost_patch.HOOK, text)
|
||||
# the injected jump skips the return only when the switch is off: if-eqz means "zero, carry on"
|
||||
self.assertEqual(text.count("return-void"), 3) # the other method's, the injected one, the method's own
|
||||
|
||||
def test_other_methods_and_the_report_call_are_untouched(self):
|
||||
text = ghost_patch.rewrite_story_view(SAMPLE)
|
||||
self.assertEqual(text.count("Ghost;"), 1)
|
||||
self.assertIn("reportStoryViewed(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;)LX/12YD;", text)
|
||||
self.assertTrue(text.startswith(".class public final LX/0RDS;"))
|
||||
|
||||
def test_a_second_pass_is_refused(self):
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_story_view(ghost_patch.rewrite_story_view(SAMPLE))
|
||||
|
||||
def test_another_shape_is_refused(self):
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_story_view(SAMPLE.replace("reportStoryViewed", "reportSomething"))
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_story_view(SAMPLE.replace(".registers 8", ".registers 9"))
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_story_view(SAMPLE.replace("if-eqz p1, :cond_3c", "if-nez p1, :cond_3c"))
|
||||
with self.assertRaises(ValueError):
|
||||
ghost_patch.rewrite_story_view(SAMPLE.replace("LIZJ(", "LIZK("))
|
||||
|
||||
def test_runtime_and_build_are_in_step(self):
|
||||
self.assertEqual(ghost_patch.runtime_targets(), [ghost_patch.HOOK, ghost_patch.MARK_READ_HOOK])
|
||||
source = (ROOT / "src" / "lihont" / "two" / "ghost" / "Ghost.java").read_text(encoding="utf-8")
|
||||
self.assertIn("public static boolean stories()", source)
|
||||
self.assertIn("public static boolean messages()", source)
|
||||
# ghost mode is a choice: off until the person turns it on
|
||||
self.assertIn('getBoolean(STORIES, false)', source)
|
||||
self.assertIn('getBoolean(MESSAGES, false)', source)
|
||||
build = (ROOT / "lihont" / "upgrade.py").read_text(encoding="utf-8")
|
||||
self.assertIn('step("ghost_stories", patch_ghost_stories', build)
|
||||
self.assertIn('step("ghost_messages", patch_ghost_messages', build)
|
||||
self.assertIn("ghost_patch.runtime_targets()", build)
|
||||
screen = (ROOT / "src" / "lihont" / "two" / "settings" / "LihonTSettingsActivity.java").read_text(encoding="utf-8")
|
||||
self.assertIn("ghostStoriesRow()", screen)
|
||||
self.assertIn("ghostMessagesRow()", screen)
|
||||
# both live in their own section, not in the list of functions
|
||||
self.assertIn('addSection("Приватность", cardPrivacy', screen)
|
||||
self.assertNotIn("cardFunc.addView(ghostStoriesRow())", screen)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
466
tests/test_ltp_sdk.py
Normal file
466
tests/test_ltp_sdk.py
Normal file
@@ -0,0 +1,466 @@
|
||||
"""lihont-ltp: the Python library for plugin authors. Its checks and its defender must agree with the app's own."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SDK = ROOT / "sdk" / "lihont-ltp"
|
||||
sys.path.insert(0, str(SDK))
|
||||
|
||||
from lihont_ltp import * # noqa: E402,F401,F403
|
||||
from lihont_ltp import guard as guard_module # noqa: E402
|
||||
from lihont_ltp import validate # noqa: E402
|
||||
from lihont_ltp.cli import main as cli_main # noqa: E402
|
||||
from lihont_ltp.errors import LtpError # noqa: E402
|
||||
from lihont_ltp.pack import read_ltp # noqa: E402
|
||||
|
||||
CORE = ["Act", "Cond", "Ctx", "Defender", "DownloadSpec", "Evaluator", "Fields", "GuardDump", "Journal", "Json",
|
||||
"LtpException", "OverlaySpec", "Permission", "Plugin", "PluginPackage", "Rule"]
|
||||
|
||||
|
||||
def build(plugin):
|
||||
return plugin.build(SDK / "examples")
|
||||
|
||||
|
||||
class Language(unittest.TestCase):
|
||||
def test_a_rule_reads_like_a_sentence_and_rights_are_worked_out(self):
|
||||
plugin = Plugin("Тихая ночь", author="Вася")
|
||||
plugin.video(hashtag("fyp", "#ForYou"), hide, say("скрыто"))
|
||||
manifest = build(plugin)[0]
|
||||
self.assertEqual(manifest["id"], "vasya.tihaya-noch")
|
||||
self.assertEqual(manifest["permissions"], ["feed.hide", "ui.notice"])
|
||||
self.assertEqual(manifest["rules"][0]["if"], {"hashtag": ["fyp", "#ForYou"]})
|
||||
self.assertEqual(manifest["rules"][0]["do"], [{"feed.hide": True}, {"notice": "скрыто"}])
|
||||
|
||||
def test_and_or_not_make_groups_and_flatten_chains(self):
|
||||
plugin = Plugin("X", author="Вася")
|
||||
plugin.video(word("a") & word("b") & ~hashtag("c"), hide)
|
||||
condition = build(plugin)[0]["rules"][0]["if"]
|
||||
self.assertEqual(condition, {"all": [{"text": ["a"]}, {"text": ["b"]}, {"not": {"hashtag": ["c"]}}]})
|
||||
plugin = Plugin("X", author="Вася")
|
||||
plugin.video(word("a") | word("b") | word("c"), hide)
|
||||
self.assertEqual(build(plugin)[0]["rules"][0]["if"], {"any": [{"text": ["a"]}, {"text": ["b"]}, {"text": ["c"]}]})
|
||||
|
||||
def test_me_means_the_author_in_videos_and_the_name_in_names(self):
|
||||
plugin = Plugin("X", author="Вася")
|
||||
plugin.video(me, say("моё"))
|
||||
plugin.name(me & morning, after("!"))
|
||||
rules = build(plugin)[0]["rules"]
|
||||
self.assertEqual(rules[0]["if"], {"author": ["self"]})
|
||||
self.assertEqual(rules[1]["if"], {"all": [{"uid": ["self"]}, {"time": "06:00-12:00"}]})
|
||||
|
||||
def test_weekdays_accept_english_and_russian_names(self):
|
||||
self.assertEqual(weekday("fri", "сб").to_json("video"), {"weekday": [5, 6]})
|
||||
with self.assertRaises(LtpError):
|
||||
weekday("funday")
|
||||
|
||||
def test_the_picture_collects_its_taps_and_rights(self):
|
||||
plugin = Plugin("Кот", author="Вася")
|
||||
plugin.screen(picture("star.png", on_tap=[wiggle, like]))
|
||||
manifest = build(plugin)[0]
|
||||
self.assertEqual(manifest["permissions"], ["ui.overlay", "feed.like"])
|
||||
self.assertEqual(manifest["rules"][0]["do"][0]["overlay"]["tap"], ["animate", "like"])
|
||||
|
||||
def test_a_download_lists_its_sites_by_itself_and_comes_with_the_right(self):
|
||||
plugin = Plugin("Кот из сети", author="Вася")
|
||||
plugin.screen(download("https://cdn.example.com/a/cat.png", "cat.png"),
|
||||
download("https://img.example.org/dog.gif", "dog.gif", sha256="ab" * 32),
|
||||
picture("cat.png"))
|
||||
manifest, assets, report = build(plugin)
|
||||
self.assertEqual(manifest["permissions"], ["net.download", "ui.overlay"])
|
||||
self.assertEqual(manifest["net"], {"hosts": ["cdn.example.com", "img.example.org"]})
|
||||
self.assertEqual(assets, {}) # fetched files are not packed
|
||||
self.assertTrue(report.net and report.level == guard_module.WATCH)
|
||||
self.assertIn("ходить куда-либо, кроме названных сайтов", report.text())
|
||||
self.assertEqual(list(manifest)[-2:], ["net", "rules"])
|
||||
|
||||
def test_the_licence_and_the_ai_go_into_the_manifest_and_the_review_checks_them(self):
|
||||
from lihont_ltp import review
|
||||
plugin = Plugin("Своё", author="Вася", description="Скрывает fyp", license="MIT", ai="Claude Sonnet 5.5")
|
||||
plugin.video(hashtag("fyp"), hide)
|
||||
manifest, assets, report = build(plugin)
|
||||
self.assertEqual(manifest["license"], "MIT")
|
||||
self.assertEqual(manifest["ai"], ["Claude Sonnet 5.5"])
|
||||
self.assertNotIn("не указал лицензию", report.text())
|
||||
self.assertEqual(review.problems(manifest, assets), [])
|
||||
# a plugin that says nothing, hides everything and fetches without a pin has things to fix
|
||||
bad = Plugin("Плохое", author="Вася")
|
||||
bad.video(hide)
|
||||
bad.screen(download("https://cdn.example.com/c.png", "c.png"), picture("c.png"))
|
||||
manifest, assets, report = build(bad)
|
||||
self.assertIn("Автор не указал лицензию плагина.", report.text())
|
||||
found = " ".join(review.problems(manifest, assets))
|
||||
for needle in ("MIT или VCBFU-2", "Нет описания", "Осторожно", "без sha256"):
|
||||
self.assertIn(needle, found)
|
||||
other = Plugin("Другое", author="В", description="x", license="GPL-3.0")
|
||||
other.video(hashtag("a"), hide)
|
||||
self.assertIn("указано «GPL-3.0»", " ".join(review.problems(*build(other)[:2])))
|
||||
for name in ("VCBFU-2", "vcbfu", "mit"):
|
||||
fine = Plugin("Ок", author="В", description="x", license=name)
|
||||
fine.video(hashtag("a"), hide)
|
||||
self.assertEqual(review.problems(*build(fine)[:2]), [], name)
|
||||
|
||||
def test_the_fields_are_checked_like_in_the_app(self):
|
||||
def make(**kw):
|
||||
plugin = Plugin("X", author="В", **kw)
|
||||
plugin.video(hashtag("a"), hide)
|
||||
return lambda: build(plugin)
|
||||
for kwargs, needle in (({"license": "x" * 41}, "не больше 40"), ({"ai": ["a"] * 5}, "не больше 4"),
|
||||
({"ai": [" "]}, "пустая запись"), ({"ai": [7]}, "нужен текст")):
|
||||
with self.assertRaises(LtpError, msg=str(kwargs)) as raised:
|
||||
make(**kwargs)()
|
||||
self.assertIn(needle, str(raised.exception))
|
||||
|
||||
def test_a_plugin_without_downloads_has_no_net_part(self):
|
||||
plugin = Plugin("X", author="Вася")
|
||||
plugin.video(hashtag("a"), hide)
|
||||
manifest, _assets, report = build(plugin)
|
||||
self.assertNotIn("net", manifest)
|
||||
self.assertFalse(report.net)
|
||||
self.assertIn("выходить в интернет", report.text())
|
||||
|
||||
def test_a_forgotten_condition_means_always(self):
|
||||
plugin = Plugin("X", author="Вася")
|
||||
plugin.video(hide)
|
||||
manifest = build(plugin)[0]
|
||||
self.assertNotIn("if", manifest["rules"][0])
|
||||
self.assertEqual(build(plugin)[2].level, guard_module.CAREFUL)
|
||||
|
||||
def test_the_russian_names_work(self):
|
||||
from lihont_ltp.ru import Плагин, скрыть, хэштег
|
||||
plugin = Плагин("Тест", автор="Вася")
|
||||
plugin.видео(хэштег("fyp"), скрыть)
|
||||
self.assertEqual(build(plugin)[0]["rules"][0]["do"], [{"feed.hide": True}])
|
||||
|
||||
|
||||
class FriendlyErrors(unittest.TestCase):
|
||||
def fails(self, make, needle):
|
||||
with self.assertRaises(LtpError) as raised:
|
||||
make()
|
||||
self.assertIn(needle, str(raised.exception))
|
||||
|
||||
def test_mistakes_are_explained_in_russian(self):
|
||||
self.fails(lambda: Plugin("X"), "Укажи автора")
|
||||
self.fails(lambda: Plugin("X", author="В").video("fyp", hide), "условие")
|
||||
self.fails(lambda: Plugin("X", author="В").video(hashtag("a")), "нет действий")
|
||||
self.fails(lambda: Plugin("X", author="В").video(hashtag("a"), "hide"), "действия")
|
||||
self.fails(lambda: hashtag(), "напиши хотя бы одно")
|
||||
self.fails(lambda: hashtag(5), "в кавычках")
|
||||
self.fails(lambda: Plugin("X", author="В").screen(say("x"), when=me), "me")
|
||||
|
||||
def test_rules_of_the_app_are_checked_before_the_phone_sees_the_file(self):
|
||||
def bad(setup):
|
||||
plugin = Plugin("X", author="Вася")
|
||||
setup(plugin)
|
||||
return lambda: build(plugin)
|
||||
self.fails(bad(lambda p: p.name(me, hide)), "только в правилах про видео")
|
||||
self.fails(bad(lambda p: p.video(always, after("x"))), "только в правилах про имена")
|
||||
self.fails(bad(lambda p: p.video(hashtag("a"), say("x" * 81))), "не больше 80")
|
||||
self.fails(bad(lambda p: p.video(between("10:00", "10:00"), hide)), "начало не равно концу")
|
||||
self.fails(bad(lambda p: p.screen(picture("Cat.GIF"))), "нельзя")
|
||||
self.fails(bad(lambda p: p.screen(picture("nope.png"))), "нет рядом со скриптом")
|
||||
self.fails(bad(lambda p: p.video(hashtag("a"), say("x"), limit=99)), "от 1 до 20")
|
||||
self.fails(bad(lambda p: p.screen(picture("star.png", on_tap=[sound("star.png")]))), "Звук")
|
||||
self.fails(lambda: build(Plugin("X", author="Вася", id="Ab").video(hide)), "id")
|
||||
|
||||
def test_mistakes_in_downloads_are_explained(self):
|
||||
def screen(*actions):
|
||||
plugin = Plugin("X", author="Вася")
|
||||
plugin.screen(*actions)
|
||||
return lambda: build(plugin)
|
||||
pic = picture("cat.png")
|
||||
self.fails(screen(download("http://cdn.example.com/cat.png", "cat.png"), pic), "https://")
|
||||
self.fails(screen(download("https://cdn.example.com:8443/cat.png", "cat.png"), pic), "порта")
|
||||
self.fails(screen(download("https://me@cdn.example.com/cat.png", "cat.png"), pic), "логина")
|
||||
self.fails(screen(download("https://10.0.0.1/cat.png", "cat.png"), pic), "имя сайта")
|
||||
self.fails(screen(download("https://localhost/cat.png", "cat.png"), pic), "имя сайта")
|
||||
self.fails(screen(download("https://cdn.example.com", "cat.png"), pic), "нужен путь")
|
||||
self.fails(screen(download("https://cdn.example.com/../cat.png", "cat.png"), pic), "лишние знаки")
|
||||
self.fails(screen(download("https://cdn.example.com/cat.png", "cat.txt"), pic), "png, gif, webp")
|
||||
self.fails(screen(download("https://cdn.example.com/cat.png", "Cat.PNG"), pic), "нельзя")
|
||||
self.fails(screen(download("https://cdn.example.com/cat.png", "cat.png", sha256="abc"), pic), "64 цифры")
|
||||
self.fails(screen(download("https://cdn.example.com/a.png", "cat.png"),
|
||||
download("https://cdn.example.com/b.png", "cat.png"), pic), "дважды")
|
||||
self.fails(lambda: download("https://cdn.example.com/cat.png", 5), "в кавычках")
|
||||
many = [download("https://cdn.example.com/c%d.png" % n, "c%d.png" % n) for n in range(5)]
|
||||
self.fails(screen(*many, pic), "больше 4")
|
||||
plugin = Plugin("X", author="Вася")
|
||||
plugin.video(always, download("https://cdn.example.com/cat.png", "cat.png"))
|
||||
self.fails(lambda: build(plugin), "только в правилах про экран")
|
||||
# a picture that points at its own file and the same name downloaded: the plugin already holds it
|
||||
plugin = Plugin("X", author="Вася")
|
||||
plugin.screen(download("https://cdn.example.com/star.png", "star.png"), picture("star.png"))
|
||||
manifest, assets, _report = build(plugin)
|
||||
self.assertEqual(assets, {}) # star.png lies next to the examples, but a fetched name is never packed
|
||||
|
||||
def test_too_many_conditions_and_rules_are_refused(self):
|
||||
plugin = Plugin("X", author="Вася")
|
||||
for number in range(33):
|
||||
plugin.video(word("w%d" % number), hide)
|
||||
self.fails(lambda: build(plugin), "больше 32")
|
||||
deep = word("a")
|
||||
for _ in range(5):
|
||||
deep = ~deep
|
||||
plugin = Plugin("X", author="Вася")
|
||||
plugin.video(deep, hide)
|
||||
self.fails(lambda: build(plugin), "глубоко")
|
||||
|
||||
|
||||
class Files(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="ltp-sdk-")
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.out = Path(self.temporary.name)
|
||||
|
||||
def test_the_examples_build_and_read_back(self):
|
||||
env = dict(os.environ, LTP_OUT_DIR=str(self.out), PYTHONPATH=str(SDK), PYTHONIOENCODING="utf-8")
|
||||
examples = sorted((SDK / "examples").glob("*.py"))
|
||||
self.assertGreaterEqual(len(examples), 5)
|
||||
for example in examples:
|
||||
done = subprocess.run([sys.executable, "-X", "utf8", str(example)], env=env, capture_output=True, text=True,
|
||||
encoding="utf-8")
|
||||
self.assertEqual(done.returncode, 0, "%s\n%s" % (example.name, done.stderr))
|
||||
self.assertIn("Защитник:", done.stdout)
|
||||
files = sorted(self.out.glob("*.ltp"))
|
||||
self.assertEqual(len(files), len(examples))
|
||||
for file in files:
|
||||
manifest, assets, _icon = read_ltp(file)
|
||||
self.assertTrue(manifest["id"])
|
||||
with zipfile.ZipFile(file) as archive:
|
||||
for name in archive.namelist():
|
||||
self.assertTrue(name in ("plugin.json", "icon.png") or name.startswith("assets/"))
|
||||
|
||||
def test_the_cli_makes_a_template_that_runs_and_checks_a_file(self):
|
||||
cwd = os.getcwd()
|
||||
os.chdir(self.out)
|
||||
try:
|
||||
self.assertEqual(cli_main(["new", "Мой плагин", "--author", "Вася"]), 0)
|
||||
self.assertEqual(cli_main(["new", "Мой плагин"]), 1) # does not overwrite
|
||||
env = dict(os.environ, PYTHONPATH=str(SDK), PYTHONIOENCODING="utf-8")
|
||||
done = subprocess.run([sys.executable, "-X", "utf8", "moy-plagin.py"], env=env, capture_output=True,
|
||||
text=True, encoding="utf-8")
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertTrue((self.out / "vasya.moy-plagin.ltp").is_file())
|
||||
self.assertEqual(cli_main(["guard", "vasya.moy-plagin.ltp"]), 0)
|
||||
(self.out / "broken.ltp").write_bytes(b"not a zip")
|
||||
self.assertEqual(cli_main(["guard", "broken.ltp"]), 1)
|
||||
# the template has no licence yet: the review says so; with one it passes
|
||||
self.assertEqual(cli_main(["review", "vasya.moy-plagin.ltp"]), 1)
|
||||
good = Plugin("Готовый", author="Вася", description="Скрывает fyp", license="MIT")
|
||||
good.video(hashtag("fyp"), hide)
|
||||
path = good.save(self.out, show=False)
|
||||
self.assertEqual(cli_main(["review", str(path)]), 0)
|
||||
finally:
|
||||
os.chdir(cwd)
|
||||
|
||||
def test_a_file_with_extra_things_inside_is_refused(self):
|
||||
path = self.out / "evil.ltp"
|
||||
with zipfile.ZipFile(path, "w") as archive:
|
||||
archive.writestr("plugin.json", "{}")
|
||||
archive.writestr("classes.dex", b"dex")
|
||||
with self.assertRaises(LtpError):
|
||||
read_ltp(path)
|
||||
|
||||
|
||||
class AgreesWithTheApp(unittest.TestCase):
|
||||
"""The same plugin must get the same words from the Java defender and from this library's."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.javac = shutil.which("javac")
|
||||
cls.java = shutil.which("java")
|
||||
if not cls.javac or not cls.java:
|
||||
raise RuntimeError("these tests need a JDK")
|
||||
cls.temporary = tempfile.TemporaryDirectory(prefix="ltp-sdk-java-")
|
||||
cls.addClassCleanup(cls.temporary.cleanup)
|
||||
cls.work = Path(cls.temporary.name)
|
||||
cls.classes = cls.work / "classes"
|
||||
cls.classes.mkdir()
|
||||
sources = []
|
||||
for name in CORE:
|
||||
folder = ROOT / "tests" / "java" if name == "GuardDump" else ROOT / "src"
|
||||
sources.append(str(folder / "lihont" / "two" / "plugin" / (name + ".java")))
|
||||
done = subprocess.run([cls.javac, "-encoding", "UTF-8", "-d", str(cls.classes)] + sources,
|
||||
capture_output=True, text=True)
|
||||
if done.returncode != 0:
|
||||
raise RuntimeError(done.stdout + done.stderr)
|
||||
|
||||
def java_says(self, folders):
|
||||
done = subprocess.run([self.java, "-Dfile.encoding=UTF-8", "-Dstdout.encoding=UTF-8", "-cp", str(self.classes),
|
||||
"lihont.two.plugin.GuardDump"] + [str(f) for f in folders],
|
||||
capture_output=True, encoding="utf-8", cwd=str(ROOT))
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
result = {}
|
||||
for block in done.stdout.split("=====")[1:]:
|
||||
name, _, text = block.partition("\n")
|
||||
result[name.strip()] = text.rstrip("\n")
|
||||
return result
|
||||
|
||||
def folder_of(self, name, manifest, assets):
|
||||
folder = self.work / name
|
||||
(folder / "assets").mkdir(parents=True)
|
||||
(folder / "plugin.json").write_text(json.dumps(manifest, ensure_ascii=False), encoding="utf-8")
|
||||
for asset, body in assets.items():
|
||||
(folder / "assets" / asset).write_bytes(body)
|
||||
return folder
|
||||
|
||||
def test_the_shipped_plugins_get_identical_words(self):
|
||||
folders, python = [], {}
|
||||
for folder in sorted(p for p in (ROOT / "plugins").iterdir() if p.is_dir()):
|
||||
manifest = json.loads((folder / "plugin.json").read_text(encoding="utf-8"))
|
||||
assets = {a.name: a.read_bytes() for a in (folder / "assets").glob("*")} if (folder / "assets").is_dir() else {}
|
||||
validate.check_manifest(manifest, assets)
|
||||
python[folder.name] = guard_module.check(manifest, assets.keys()).text()
|
||||
folders.append(folder)
|
||||
self.assertGreaterEqual(len(folders), 6)
|
||||
java = self.java_says(folders)
|
||||
for name, text in python.items():
|
||||
self.assertEqual(java[name], text, name)
|
||||
|
||||
def test_the_hash_the_review_prints_is_the_one_the_app_shows(self):
|
||||
from lihont_ltp import review
|
||||
folders, expected = [], {}
|
||||
for folder in sorted(p for p in (ROOT / "plugins").iterdir() if p.is_dir()):
|
||||
ltp = self.work / (folder.name + ".ltp")
|
||||
with zipfile.ZipFile(ltp, "w") as archive:
|
||||
archive.writestr("plugin.json", (folder / "plugin.json").read_bytes())
|
||||
if (folder / "assets").is_dir():
|
||||
for asset in sorted((folder / "assets").glob("*")):
|
||||
archive.writestr("assets/" + asset.name, asset.read_bytes())
|
||||
expected[folder.name] = review.plugin_hash(ltp)
|
||||
folders.append(folder)
|
||||
done = subprocess.run([self.java, "-Dfile.encoding=UTF-8", "-cp", str(self.classes), "lihont.two.plugin.GuardDump",
|
||||
"--hash"] + [str(f) for f in folders], capture_output=True, encoding="utf-8", cwd=str(ROOT))
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
java = {}
|
||||
for block in done.stdout.split("=====")[1:]:
|
||||
name, _, text = block.partition("\n")
|
||||
java[name.strip()] = text.strip()
|
||||
self.assertGreaterEqual(len(expected), 6)
|
||||
for name, value in expected.items():
|
||||
self.assertEqual(java[name], value, name)
|
||||
|
||||
def test_plugins_made_with_the_library_get_identical_words_and_the_app_accepts_them(self):
|
||||
made = {}
|
||||
|
||||
def make(key, plugin):
|
||||
made[key] = build(plugin)
|
||||
|
||||
p = Plugin("a", author="В", id="v.a")
|
||||
p.video(hashtag("fyp"), hide)
|
||||
make("narrow", p)
|
||||
p = Plugin("b", author="В", id="v.b")
|
||||
p.video(hide)
|
||||
p.video(between("22:00", "07:00"), hide, title="ночью")
|
||||
make("hide-all", p)
|
||||
p = Plugin("c", author="В", id="v.c")
|
||||
p.name(always, rename("Аноним"))
|
||||
p.name(person("123456"), rename("Ыы"), title="этот")
|
||||
p.name(me & morning, before("*"), after("!"))
|
||||
make("names", p)
|
||||
p = Plugin("d", author="В", id="v.d")
|
||||
p.video(word("a", "b", "c", "d", "e", "f", "g") & ~hashtag("x") & author("y", "self") | weekday("sat", "fri"),
|
||||
say("t"), limit=15)
|
||||
make("deep", p)
|
||||
p = Plugin("e", author="В", id="v.e")
|
||||
p.screen(picture("star.png", size=320, movable=False, on_tap=[wiggle, like], pet="star.png"))
|
||||
p.screen(picture("star.png", size=120, on_tap=[]), title="пустая")
|
||||
make("pictures", p)
|
||||
p = Plugin("f", author="В", id="v.f")
|
||||
p.screen(download("https://cdn.example.com/a/cat.png", "cat.png"),
|
||||
download("https://img.example.org/dog.gif", "dog.gif", sha256="ab" * 32), picture("cat.png"))
|
||||
make("online", p)
|
||||
p = Plugin("g", author="В", id="v.g")
|
||||
p.screen(download("https://cdn.example.com/cat.png", "cat.png", sha256="cd" * 32), picture("cat.png"),
|
||||
say("загружено"))
|
||||
make("online-pinned", p)
|
||||
folders = [self.folder_of(key, manifest, assets) for key, (manifest, assets, _r) in made.items()]
|
||||
java = self.java_says(folders)
|
||||
for key, (_m, _a, report) in made.items():
|
||||
self.assertNotIn("REFUSED", java[key], "%s: %s" % (key, java[key]))
|
||||
self.assertEqual(java[key], report.text(), key)
|
||||
|
||||
def test_what_the_library_refuses_the_app_refuses_too(self):
|
||||
bad = {
|
||||
"hide-in-names": {"title": "t", "when": "name.show", "do": [{"feed.hide": True}]},
|
||||
"overlay-in-video": {"title": "t", "when": "feed.item", "do": [{"overlay": {"image": "star.png"}}]},
|
||||
"empty-do": {"title": "t", "when": "feed.item", "do": []},
|
||||
"bad-time": {"title": "t", "when": "feed.item", "if": {"time": "25:00-07:00"}, "do": [{"feed.hide": True}]},
|
||||
"bad-limit": {"title": "t", "when": "feed.item", "limit": 99, "do": [{"notice": "x"}]},
|
||||
"two-keys": {"title": "t", "when": "feed.item", "if": {"text": ["a"], "uid": ["b"]}, "do": [{"feed.hide": True}]},
|
||||
}
|
||||
folders = []
|
||||
for key, rule in bad.items():
|
||||
manifest = {"ltp": 1, "id": "bad." + key, "name": "x", "version": "1", "author": "a",
|
||||
"permissions": ["feed.hide", "ui.notice", "ui.overlay"], "rules": [rule]}
|
||||
with self.assertRaises(LtpError, msg=key):
|
||||
validate.check_manifest(manifest, {"star.png": (SDK / "examples" / "files" / "star.png").read_bytes()})
|
||||
folders.append(self.folder_of(key, manifest, {}))
|
||||
java = self.java_says(folders)
|
||||
for key in bad:
|
||||
self.assertIn("REFUSED", java[key], key)
|
||||
|
||||
def test_what_is_wrong_in_a_download_is_refused_by_both(self):
|
||||
def manifest(net, *downloads, rights=("net.download", "ui.overlay")):
|
||||
do = [{"download": d} for d in downloads] + [{"overlay": {"image": "cat.png"}}]
|
||||
out = {"ltp": 1, "id": "net.case", "name": "x", "version": "1", "author": "a", "permissions": list(rights),
|
||||
"rules": [{"title": "t", "when": "screen.show", "do": do}]}
|
||||
if net is not None:
|
||||
out["net"] = net
|
||||
return out
|
||||
|
||||
good = {"url": "https://cdn.example.com/cat.png", "as": "cat.png"}
|
||||
cdn = {"hosts": ["cdn.example.com"]}
|
||||
cases = {
|
||||
"no-net": manifest(None, good),
|
||||
"net-no-right": manifest(cdn, good, rights=("ui.overlay",)),
|
||||
"empty-hosts": manifest({"hosts": []}, good),
|
||||
"unused-host": manifest({"hosts": ["cdn.example.com", "x.example.org"]}, good),
|
||||
"other-host": manifest({"hosts": ["x.example.org"]}, good),
|
||||
"double-host": manifest({"hosts": ["cdn.example.com", "cdn.example.com"]}, good),
|
||||
"extra-key": manifest({"hosts": ["cdn.example.com"], "x": 1}, good),
|
||||
"http": manifest(cdn, dict(good, url="http://cdn.example.com/cat.png")),
|
||||
"port": manifest(cdn, dict(good, url="https://cdn.example.com:81/cat.png")),
|
||||
"login": manifest(cdn, dict(good, url="https://u@cdn.example.com/cat.png")),
|
||||
"ip": manifest({"hosts": ["10.0.0.1"]}, {"url": "https://10.0.0.1/cat.png", "as": "cat.png"}),
|
||||
"upper": manifest({"hosts": ["Cdn.Example.com"]}, good),
|
||||
"no-path": manifest(cdn, dict(good, url="https://cdn.example.com")),
|
||||
"dots": manifest(cdn, dict(good, url="https://cdn.example.com/../cat.png")),
|
||||
"fragment": manifest(cdn, dict(good, url="https://cdn.example.com/cat.png#x")),
|
||||
"space": manifest(cdn, dict(good, url="https://cdn.example.com/cat png")),
|
||||
"txt": manifest(cdn, dict(good, **{"as": "cat.txt"})),
|
||||
"bad-hash": manifest(cdn, dict(good, sha256="abc")),
|
||||
"twice": manifest(cdn, good, dict(good, url="https://cdn.example.com/b.png")),
|
||||
"extra-field": manifest(cdn, dict(good, post=1)),
|
||||
"no-as": manifest(cdn, {"url": "https://cdn.example.com/cat.png"}),
|
||||
}
|
||||
folders = []
|
||||
for key, case in cases.items():
|
||||
with self.assertRaises(LtpError, msg=key):
|
||||
validate.check_manifest(case, {})
|
||||
folders.append(self.folder_of(key, case, {}))
|
||||
# a file that is also in the plugin cannot be fetched under the same name
|
||||
clash = manifest(cdn, good)
|
||||
star = (SDK / "examples" / "files" / "star.png").read_bytes()
|
||||
clash["rules"][0]["do"][-1] = {"overlay": {"image": "cat.png"}}
|
||||
with self.assertRaises(LtpError):
|
||||
validate.check_manifest(clash, {"cat.png": star})
|
||||
folders.append(self.folder_of("clash", clash, {"cat.png": star}))
|
||||
# and the good one passes both
|
||||
validate.check_manifest(manifest(cdn, good), {})
|
||||
folders.append(self.folder_of("fine", manifest(cdn, good), {}))
|
||||
java = self.java_says(folders)
|
||||
for key in list(cases) + ["clash"]:
|
||||
self.assertIn("REFUSED", java[key], "%s: %s" % (key, java[key]))
|
||||
self.assertNotIn("REFUSED", java["fine"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
160
tests/test_plugins.py
Normal file
160
tests/test_plugins.py
Normal file
@@ -0,0 +1,160 @@
|
||||
"""The LihonT plugin core (.ltp files) on a real JVM, and the files the packer makes.
|
||||
|
||||
The core of lihont.two.plugin (reading, refusing, conditions, names, the zip) is plain Java, so the tests compile it
|
||||
with javac and run each scenario in its own process. The Android parts (registry, engine, screen) are covered by the
|
||||
runtime compile test.
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CORE = ["Act", "Cond", "Ctx", "Defender", "DownloadSpec", "Downloader", "Evaluator", "Fields", "Journal", "Json",
|
||||
"LtpException", "OverlaySpec", "Permission", "Plugin", "PluginPackage", "Rule"]
|
||||
HARNESS = ROOT / "tests" / "java" / "lihont" / "two" / "plugin" / "PluginTest.java"
|
||||
|
||||
|
||||
class PluginCoreTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.javac = shutil.which("javac")
|
||||
cls.java = shutil.which("java")
|
||||
if not cls.javac or not cls.java:
|
||||
raise RuntimeError("Plugin tests require a JDK with java and javac")
|
||||
cls.temporary = tempfile.TemporaryDirectory(prefix="lihont-plugin-tests-")
|
||||
cls.addClassCleanup(cls.temporary.cleanup)
|
||||
cls.classes = Path(cls.temporary.name) / "classes"
|
||||
cls.classes.mkdir()
|
||||
cls.environment = dict(os.environ)
|
||||
cls.environment.pop("JAVA_TOOL_OPTIONS", None)
|
||||
sources = [str(ROOT / "src" / "lihont" / "two" / "plugin" / (name + ".java")) for name in CORE]
|
||||
cls.run_command([cls.javac, "--release", "17", "-encoding", "UTF-8", "-Xlint:all", "-Werror",
|
||||
"-d", str(cls.classes)] + sources + [str(HARNESS)])
|
||||
|
||||
@classmethod
|
||||
def run_command(cls, command, cwd=None):
|
||||
result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", env=cls.environment,
|
||||
timeout=120, cwd=cwd)
|
||||
if result.returncode:
|
||||
raise AssertionError("Command failed with exit %d: %s\n%s%s" % (result.returncode, command[0],
|
||||
result.stdout, result.stderr))
|
||||
return result
|
||||
|
||||
def run_scenario(self, name):
|
||||
result = self.run_command([self.java, "-Dfile.encoding=UTF-8", "-cp", str(self.classes),
|
||||
"lihont.two.plugin.PluginTest", name], cwd=str(ROOT))
|
||||
self.assertEqual(result.stdout.strip(), "PASS " + name)
|
||||
|
||||
def test_a_good_plugin_is_read_and_the_samples_are_valid(self):
|
||||
self.run_scenario("parse")
|
||||
|
||||
def test_bad_plugins_are_refused_with_a_reason(self):
|
||||
self.run_scenario("refusals")
|
||||
|
||||
def test_conditions(self):
|
||||
self.run_scenario("conditions")
|
||||
|
||||
def test_name_rules(self):
|
||||
self.run_scenario("names")
|
||||
|
||||
def test_the_zip_is_read_strictly(self):
|
||||
self.run_scenario("package")
|
||||
|
||||
def test_the_hash_follows_the_bytes(self):
|
||||
self.run_scenario("hash")
|
||||
|
||||
def test_overlay_pictures_need_their_rights_and_files(self):
|
||||
self.run_scenario("overlay")
|
||||
|
||||
def test_files_of_a_plugin_are_checked_by_their_first_bytes_and_hashed(self):
|
||||
self.run_scenario("assets")
|
||||
|
||||
def test_defender_reads_rules_in_plain_words_and_grades_the_risk(self):
|
||||
self.run_scenario("defender")
|
||||
|
||||
def test_downloads_need_a_right_named_sites_and_a_real_file(self):
|
||||
self.run_scenario("download")
|
||||
|
||||
def test_the_licence_and_the_ai_of_a_plugin_are_read_and_shown_as_the_authors_word(self):
|
||||
self.run_scenario("origin")
|
||||
settings = (ROOT / "src" / "lihont" / "two" / "settings" / "PluginSettings.java").read_text(encoding="utf-8")
|
||||
self.assertGreaterEqual(settings.count("origin(plugin)"), 2) # the install dialog and the card
|
||||
self.assertIn("(со слов автора)", settings)
|
||||
|
||||
def test_the_download_is_a_plain_get_that_carries_nothing_about_the_person(self):
|
||||
source = (ROOT / "src" / "lihont" / "two" / "plugin" / "Downloader.java").read_text(encoding="utf-8")
|
||||
self.assertIn('setRequestMethod("GET")', source)
|
||||
self.assertIn("setInstanceFollowRedirects(false)", source)
|
||||
self.assertEqual(source.count("setRequestProperty"), 2) # User-Agent and Accept-Encoding, nothing else
|
||||
self.assertNotIn("setDoOutput", source)
|
||||
net = (ROOT / "src" / "lihont" / "two" / "plugin" / "PluginNet.java").read_text(encoding="utf-8")
|
||||
self.assertIn("downloadConfirmed", net) # no file without the person's yes for that address
|
||||
engine = (ROOT / "src" / "lihont" / "two" / "plugin" / "PluginEngine.java").read_text(encoding="utf-8")
|
||||
self.assertIn("PluginRegistry.netOn(", engine) # and none while the plugin's internet is off
|
||||
|
||||
def test_long_dialogs_scroll_and_the_review_shows_the_defender(self):
|
||||
activity = (ROOT / "src" / "lihont" / "two" / "settings" / "LihonTSettingsActivity.java").read_text(encoding="utf-8")
|
||||
self.assertIn("new ScrollView(this)", activity)
|
||||
settings = (ROOT / "src" / "lihont" / "two" / "settings" / "PluginSettings.java").read_text(encoding="utf-8")
|
||||
self.assertGreaterEqual(settings.count("Defender.check(plugin)"), 2)
|
||||
|
||||
def test_a_plugin_never_changes_the_handle_that_tiktok_validates(self):
|
||||
names = (ROOT / "src" / "lihont" / "two" / "badge" / "AccountNames.java").read_text(encoding="utf-8")
|
||||
self.assertIn('"getUniqueId".equals(trace[i].getMethodName())', names)
|
||||
self.assertIn("fromHandle()) shown = name", names)
|
||||
|
||||
def test_boykisser_plugin_is_valid(self):
|
||||
self.run_scenario("boykisser")
|
||||
|
||||
def test_day_cycle_plugin_changes_only_my_name_by_the_time_of_day(self):
|
||||
self.run_scenario("daycycle")
|
||||
|
||||
|
||||
class PackerTest(unittest.TestCase):
|
||||
def test_packed_samples_hold_only_the_allowed_files(self):
|
||||
with tempfile.TemporaryDirectory(prefix="lihont-ltp-") as out:
|
||||
result = subprocess.run([sys.executable, "-I", str(ROOT / "scripts" / "make_ltp.py"), "-o", out],
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=60, cwd=str(ROOT))
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
files = sorted(Path(out).glob("*.ltp"))
|
||||
self.assertGreaterEqual(len(files), 4)
|
||||
for file in files:
|
||||
with zipfile.ZipFile(file) as archive:
|
||||
for name in archive.namelist():
|
||||
self.assertTrue(name in ("plugin.json", "icon.png") or name.startswith("assets/"), file.name)
|
||||
self.assertIn("plugin.json", archive.namelist())
|
||||
|
||||
|
||||
class HooksTest(unittest.TestCase):
|
||||
"""The hooks that connect the engine to the mod stay in place."""
|
||||
|
||||
def test_the_feed_filter_asks_the_engine(self):
|
||||
text = (ROOT / "src" / "lihont" / "two" / "feed" / "FeedFilter.java").read_text(encoding="utf-8")
|
||||
self.assertIn("PluginEngine.feedActive()", text)
|
||||
self.assertIn("PluginEngine.hideFeedItem(item)", text)
|
||||
|
||||
def test_names_pass_through_the_engine(self):
|
||||
text = (ROOT / "src" / "lihont" / "two" / "badge" / "AccountNames.java").read_text(encoding="utf-8")
|
||||
self.assertIn("PluginEngine.name(uid, name)", text)
|
||||
|
||||
def test_screens_reach_the_plugin_overlay(self):
|
||||
windows = (ROOT / "src" / "lihont" / "two" / "look" / "Windows.java").read_text(encoding="utf-8")
|
||||
self.assertIn("PluginScreen.attach(activity)", windows)
|
||||
bar = (ROOT / "src" / "lihont" / "two" / "bar" / "BottomBar.java").read_text(encoding="utf-8")
|
||||
self.assertIn("PluginScreen.attach(activity)", bar)
|
||||
self.assertIn("homeSelected", bar)
|
||||
|
||||
def test_the_settings_screen_has_the_plugin_section(self):
|
||||
text = (ROOT / "src" / "lihont" / "two" / "settings" / "LihonTSettingsActivity.java").read_text(encoding="utf-8")
|
||||
self.assertIn('addSection("Плагины"', text)
|
||||
self.assertIn("PluginSettings.REQUEST_PICK", text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
69
tests/test_portmap.py
Normal file
69
tests/test_portmap.py
Normal file
@@ -0,0 +1,69 @@
|
||||
"""lihont.portmap: renaming obfuscated classes in patch sources for another TikTok version, and the dex locator."""
|
||||
|
||||
import json
|
||||
import struct
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from lihont import portmap
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
MAP = {"LX/0qvH;": "LX/124L;", "LX/1DvK;": "LX/1Qia;", "LX/0L1b;": "LX/0qvH;"}
|
||||
|
||||
|
||||
class Rename(unittest.TestCase):
|
||||
def test_descriptors_inner_classes_and_paths_follow_the_map(self):
|
||||
text = 'A = "LX/1DvK;"\nB = "LX/1DvK;->lihont(I)V"\nC = "LX/1DvK$0;"\nD = "X/1DvK.smali"\nE = \'LX/0qvH;\''
|
||||
out = portmap.rename(text, MAP)
|
||||
self.assertIn('A = "LX/1Qia;"', out)
|
||||
self.assertIn('"LX/1Qia;->lihont(I)V"', out)
|
||||
self.assertIn('"LX/1Qia$0;"', out)
|
||||
self.assertIn('"X/1Qia.smali"', out)
|
||||
self.assertIn("'LX/124L;'", out)
|
||||
|
||||
def test_a_type_that_follows_primitive_letters_in_a_descriptor_is_renamed(self):
|
||||
self.assertEqual(portmap.rename("LIZ(LX/1DvK;ZZLX/0L1b;I)V", MAP), "LIZ(LX/1Qia;ZZLX/0qvH;I)V")
|
||||
|
||||
def test_a_new_name_that_is_an_old_name_is_not_renamed_twice(self):
|
||||
out = portmap.rename('"LX/0L1b;" "LX/0qvH;"', MAP)
|
||||
self.assertEqual(out, '"LX/0qvH;" "LX/124L;"')
|
||||
|
||||
def test_longer_names_and_other_classes_are_left_alone(self):
|
||||
text = '"LX/1DvKx;" "LX/21DvK;" "Lcom/x/1DvK;"'
|
||||
self.assertEqual(portmap.rename(text, MAP), text)
|
||||
|
||||
def test_an_empty_map_changes_nothing(self):
|
||||
self.assertEqual(portmap.rename("LX/1DvK;", {}), "LX/1DvK;")
|
||||
|
||||
def test_the_shipped_map_is_consistent(self):
|
||||
data = json.loads((ROOT / "lihont" / "portmaps" / "47.5.15.json").read_text(encoding="utf-8"))
|
||||
classes = data["classes"]
|
||||
self.assertGreaterEqual(len(classes), 20)
|
||||
for old, new in classes.items():
|
||||
self.assertRegex(old, r"^LX/[0-9A-Za-z]+;$")
|
||||
self.assertRegex(new, r"^LX/[0-9A-Za-z]+;$")
|
||||
self.assertEqual(len(set(classes.values())), len(classes), "two old classes point at one new class")
|
||||
for old in data["ambiguous"]:
|
||||
self.assertNotIn(old, classes)
|
||||
|
||||
|
||||
class Locator(unittest.TestCase):
|
||||
def test_a_dex_lists_the_classes_it_defines(self):
|
||||
# a minimal dex: one string, one type, one class_def
|
||||
name = b"LX/Test;"
|
||||
data = bytearray(112 + 4 + 1 + len(name) + 1 + 4 + 32)
|
||||
string_off = 112 + 4 + 4
|
||||
struct.pack_into("<2I", data, 56, 1, 112) # string_ids
|
||||
struct.pack_into("<2I", data, 64, 1, 116) # type_ids
|
||||
struct.pack_into("<2I", data, 96, 1, 120) # class_defs
|
||||
struct.pack_into("<I", data, 112, string_off + 32) # string data offset
|
||||
struct.pack_into("<I", data, 116, 0) # type 0 -> string 0
|
||||
struct.pack_into("<I", data, 120, 0) # class_def.class_idx = 0
|
||||
at = string_off + 32
|
||||
data[at] = len(name)
|
||||
data[at + 1:at + 1 + len(name)] = name
|
||||
self.assertEqual(portmap.defined_classes(bytes(data)), ["LX/Test;"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -145,8 +145,17 @@ class SettingsPatchTest(unittest.TestCase):
|
||||
|
||||
def test_rewrite_0ldm_injects_transform_icon(self):
|
||||
patched = settings_patch.rewrite_0ldm(LDM_SAMPLE)
|
||||
self.assertIn("SettingsCell;->transformIcon(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;", patched)
|
||||
self.assertIn("SettingsCell;->transformIcon(Ljava/lang/Object;Ljava/lang/CharSequence;Ljava/lang/Object;)Ljava/lang/Object;", patched)
|
||||
self.assertIn("move-object/from16 p8, v0", patched)
|
||||
with self.assertRaises(ValueError):
|
||||
settings_patch.rewrite_0ldm(patched)
|
||||
|
||||
def test_the_runtime_keeps_both_title_types_that_patched_builds_call(self):
|
||||
# pre2 (and any APK patched before the port to 47.5.15) calls transformIcon with a String title, newer
|
||||
# patches with a CharSequence; a runtime swapped into an old APK must answer both or the settings crash
|
||||
from pathlib import Path
|
||||
source = (Path(__file__).resolve().parents[1] / "src" / "lihont" / "two" / "settings" / "SettingsCell.java").read_text(
|
||||
encoding="utf-8")
|
||||
self.assertIn("transformIcon(Object iconObj, String titleText, Object composerObj)", source)
|
||||
self.assertIn("transformIcon(Object iconObj, CharSequence titleText, Object composerObj)", source)
|
||||
|
||||
|
||||
@@ -249,7 +249,11 @@ class LanguageCardTest(unittest.TestCase):
|
||||
|
||||
def test_a_missing_background_call_is_refused(self):
|
||||
with self.assertRaises(ValueError):
|
||||
theme_patch.rewrite_language_card(CARD.replace("v11, v0, v1, v15}", "v10, v0, v1, v15}"))
|
||||
theme_patch.rewrite_language_card(CARD.replace("LX/0L5k;->LIZIZ", "LX/0L5k;->LIZJJ"))
|
||||
|
||||
def test_the_register_of_the_modifier_is_taken_from_the_call(self):
|
||||
patched = theme_patch.rewrite_language_card(CARD.replace("v11, v0, v1, v15}", "v6, v0, v1, v15}"))
|
||||
self.assertIn("invoke-static {v6, v0, v1, v15, v3}, " + theme_patch.CARD_HOOK, patched)
|
||||
|
||||
def test_card_target_is_the_hook(self):
|
||||
self.assertEqual(theme_patch.card_targets(), [theme_patch.CARD_HOOK])
|
||||
|
||||
Reference in New Issue
Block a user