Files
LihonT/sdk/lihont-ltp/lihont_ltp/validate.py
2026-11-01 17:52:48 +03:00

454 lines
23 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Проверка плагина теми же правилами, что в приложении (src/lihont/two/plugin/*.java).
Если проверка здесь прошла, приложение файл примет. Если нет, ошибка объяснит, что исправить.
"""
import re
from .errors import LtpError
FORMAT = 1
ID = re.compile(r"[a-z0-9][a-z0-9._-]{2,63}")
VERSION = re.compile(r"[0-9A-Za-z._-]{1,16}")
ASSET = re.compile(r"[a-z0-9][a-z0-9._-]{0,39}")
TIME = re.compile(r"[0-2][0-9]:[0-5][0-9]-[0-2][0-9]:[0-5][0-9]")
MAX_RULES = 32
MAX_ACTIONS = 8
MAX_LIMIT = 20
MAX_DEPTH = 4
MAX_NODES = 40
MAX_ASSETS = 8
MAX_ASSET = 400 * 1024
MAX_ICON = 64 * 1024
MAX_FILE = 1024 * 1024
TRIGGERS = ("feed.item", "name.show", "screen.show")
RIGHTS = ("feed.hide", "names", "ui.notice", "ui.overlay", "ui.sound", "feed.like", "net.download")
ACTIONS = ("feed.hide", "name.prefix", "name.suffix", "name.replace", "notice", "overlay", "download")
OVERLAY_KEYS = ("image", "size", "alpha", "right", "bottom", "movable", "tap", "sound", "pet", "animate_ms", "walk")
WALK_MODES = ("bounce", "wander")
WALK_KEYS = ("mode", "speed", "flip")
DOWNLOAD_KEYS = ("url", "as", "sha256")
MAX_LICENSE = 40
MAX_AI = 4
MAX_AI_TEXT = 60
MAX_URL = 200
MAX_HOSTS = 4
MAX_DOWNLOADS = 4
HOST = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+")
ADDRESS_LIKE = re.compile(r"[0-9.]+")
URL_PATH = re.compile(r"[A-Za-z0-9._~!$'()*+,;=:@%/-]*(?:\?[A-Za-z0-9._~!$'()*+,;=:@%/?-]*)?")
SHA256 = re.compile(r"[0-9a-f]{64}")
PNG = b"\x89PNG\r\n\x1a\n"
KINDS = {".png": "image", ".gif": "image", ".webp": "image", ".ogg": "sound", ".mp3": "sound"}
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 _text(value, limit, where):
if not isinstance(value, str):
raise LtpError("%s: нужен текст" % where)
if len(value) > limit:
raise LtpError("%s: слишком длинно, не больше %d символов (сейчас %d)" % (where, limit, len(value)))
if any(ord(c) < 0x20 for c in value):
raise LtpError("%s: в тексте не должно быть переносов строки и других управляющих символов" % where)
return value
def _integer(value, low, high, where):
if isinstance(value, bool) or not isinstance(value, (int, float)) or value != int(value) or not low <= value <= high:
raise LtpError("%s: нужно целое число от %d до %d" % (where, low, high))
return int(value)
def _words(value, max_items, max_len, where):
if not isinstance(value, list) or not value:
raise LtpError("%s: нужен непустой список" % where)
if len(value) > max_items:
raise LtpError("%s: не больше %d значений" % (where, max_items))
out = []
for item in value:
word = _text(item, max_len, where).strip().lower()
if not word:
raise LtpError("%s: пустое значение" % where)
out.append(word)
return out
def check_condition(node, where, depth=0, counter=None):
counter = counter if counter is not None else [0]
if depth >= MAX_DEPTH:
raise LtpError("%s: условия вложены слишком глубоко (не больше %d уровней скобок)" % (where, MAX_DEPTH))
counter[0] += 1
if counter[0] > MAX_NODES:
raise LtpError("%s: слишком много условий в одном правиле (не больше %d)" % (where, MAX_NODES))
if not isinstance(node, dict) or len(node) != 1:
raise LtpError("%s: условие должно быть одним из слов: word, hashtag, author, account, between, weekday..." % where)
key, value = next(iter(node.items()))
here = "%s, условие «%s»" % (where, key)
if key == "text":
_words(value, 64, 80, here)
elif key == "hashtag":
_words(value, 64, 60, here)
elif key in ("author", "uid"):
_words(value, 64, 40, here)
elif key == "account":
_words(value, 16, 40, here)
elif key == "time":
if not isinstance(value, str) or not TIME.fullmatch(value):
raise LtpError("%s: время пишется так: между 22:00 и 07:00" % here)
start = int(value[0:2]) * 60 + int(value[3:5])
end = int(value[6:8]) * 60 + int(value[9:11])
if start > 1439 or end > 1439 or start == end:
raise LtpError("%s: время от 00:00 до 23:59, начало не равно концу" % here)
elif key == "weekday":
if not isinstance(value, list) or not 1 <= len(value) <= 7:
raise LtpError("%s: от 1 до 7 дней" % here)
for day in value:
_integer(day, 1, 7, here)
elif key in ("all", "any"):
if not isinstance(value, list) or not 1 <= len(value) <= 16:
raise LtpError("%s: внутри от 1 до 16 условий" % here)
for part in value:
check_condition(part, where, depth + 1, counter)
elif key == "not":
check_condition(value, where, depth + 1, counter)
else:
raise LtpError("%s: такого условия нет" % here)
def check_action(node, trigger, where):
if not isinstance(node, dict) or len(node) != 1:
raise LtpError("%s: в действии должно быть ровно одно поле" % where)
key, value = next(iter(node.items()))
here = "%s, действие «%s»" % (where, key)
if key not in ACTIONS:
raise LtpError("%s: такого действия нет" % here)
if key == "feed.hide":
if trigger != "feed.item":
raise LtpError("«скрыть» работает только в правилах про видео: %s" % where)
if value is not True:
raise LtpError("%s: нужно true" % here)
elif key == "notice":
_text(value, 80, here)
elif key == "overlay":
if trigger != "screen.show":
raise LtpError("«картинка» работает только в правилах про экран: %s" % where)
check_overlay(value, here)
elif key == "download":
if trigger != "screen.show":
raise LtpError("«скачать» работает только в правилах про экран: %s" % where)
check_download(value, here)
else:
if trigger != "name.show":
raise LtpError("«до имени / после имени / вместо имени» работают только в правилах про имена: %s" % where)
text = _text(value, 60, here)
if key == "name.replace" and not text.strip():
raise LtpError("%s: новое имя не может быть пустым" % here)
def _asset_name(map_, key, required, where):
value = map_.get(key)
if value is None:
if required:
raise LtpError("%s: нет поля «%s»" % (where, key))
return None
_text(value, 40, "%s, «%s»" % (where, key))
if not ASSET.fullmatch(value):
raise LtpError("%s, «%s»: имя файла «%s» нельзя: только строчные латинские буквы, цифры, точка и дефис "
"(например cat.gif)" % (where, key, value))
return value
def check_overlay(node, where):
if not isinstance(node, dict):
raise LtpError("%s: нужен объект" % where)
for key in node:
if key not in OVERLAY_KEYS:
raise LtpError("%s: у картинки нет настройки «%s»" % (where, key))
_asset_name(node, "image", True, where)
sound = _asset_name(node, "sound", False, where)
_asset_name(node, "pet", False, where)
for key, low, high in (("size", 40, 400), ("alpha", 10, 100), ("right", 0, 2000), ("bottom", 0, 2000),
("animate_ms", 200, 10000)):
if node.get(key) is not None:
_integer(node[key], low, high, "%s, «%s»" % (where, key))
if node.get("movable") is not None and not isinstance(node["movable"], bool):
raise LtpError("%s, «movable»: нужно True или False" % where)
if node.get("walk") is not None:
walk = node["walk"]
if not isinstance(walk, dict):
raise LtpError("%s, «walk»: нужен объект" % where)
for key in walk:
if key not in WALK_KEYS:
raise LtpError("%s, «walk»: нет поля «%s»" % (where, key))
mode = walk.get("mode")
if mode is None:
raise LtpError("%s, «walk»: нет поля «mode»" % where)
_text(mode, 10, "%s, «walk»" % where)
if mode not in WALK_MODES:
raise LtpError("%s, «walk»: режим — bounce (туда-сюда) или wander (бродит), а не «%s»" % (where, mode))
if walk.get("speed") is not None:
_integer(walk["speed"], 10, 300, "%s, «walk», «speed»" % where)
if walk.get("flip") is not None and not isinstance(walk["flip"], bool):
raise LtpError("%s, «walk», «flip»: нужно True или False" % where)
taps = node.get("tap")
if taps is not None:
if not isinstance(taps, list):
raise LtpError("%s, «tap»: нужен список" % where)
for tap in taps:
if tap not in ("animate", "sound", "like"):
raise LtpError("%s, «tap»: можно wiggle, sound(...) и like" % where)
if len(set(taps)) != len(taps):
raise LtpError("%s, «tap»: одно и то же действие названо дважды" % where)
else:
taps = ["animate"]
if "sound" in taps and sound is None:
raise LtpError("%s: при нажатии должен играть звук, а файла звука нет: используй sound(\"файл.ogg\")" % where)
if sound is not None and "sound" not in taps:
raise LtpError("%s: звук задан, но не включён в on_tap" % where)
def valid_host(host):
return len(host) <= 253 and HOST.fullmatch(host) is not None and ADDRESS_LIKE.fullmatch(host) is None
def host_of(url, where):
"""Сайт из адреса https://сайт/путь; всё лишнее (порт, логин, решётка, «..») — ошибка."""
if not url.startswith("https://"):
raise LtpError("%s, «url»: адрес начинается с https://" % where)
rest = url[len("https://"):]
slash = rest.find("/")
if slash < 0:
raise LtpError("%s, «url»: после сайта нужен путь к файлу" % where)
host = rest[:slash]
if "@" in host or ":" in host:
raise LtpError("%s, «url»: в адресе не может быть логина, пароля или порта" % where)
if not valid_host(host):
raise LtpError("%s, «url»: «%s» не похоже на имя сайта (строчные буквы, цифры, дефис, точки)" % (where, host))
path = rest[slash:]
if "#" in path or URL_PATH.fullmatch(path) is None or ".." in path:
raise LtpError("%s, «url»: в пути к файлу лишние знаки" % where)
return host
def check_download(node, where):
"""Проверяет одно скачивание и возвращает (сайт, имя файла)."""
if not isinstance(node, dict):
raise LtpError("%s: нужен объект" % where)
for key in node:
if key not in DOWNLOAD_KEYS:
raise LtpError("%s: у скачивания нет поля «%s»" % (where, key))
url = node.get("url")
if url is None:
raise LtpError("%s: нет поля «url»" % where)
_text(url, MAX_URL, "%s, «url»" % where)
name = _asset_name(node, "as", True, where)
if "." + name.rsplit(".", 1)[-1].lower() not in KINDS:
raise LtpError("%s, «as»: файл — png, gif, webp, ogg или mp3" % where)
digest = node.get("sha256")
if digest is not None and (not isinstance(digest, str) or SHA256.fullmatch(digest) is None):
raise LtpError("%s, «sha256»: нужно 64 цифры и строчные буквы a–f" % where)
return host_of(url, where), name
def rights_of(action):
key = next(iter(action))
if key == "feed.hide":
return ["feed.hide"]
if key == "download":
return ["net.download"]
if key == "notice":
return ["ui.notice"]
if key == "overlay":
rights = ["ui.overlay"]
taps = action[key].get("tap") or ["animate"]
if "sound" in taps:
rights.append("ui.sound")
if "like" in taps:
rights.append("feed.like")
return rights
return ["names"]
def check_manifest(manifest, assets=None):
"""`assets` — словарь «имя файла → байты» (или None, если файлы тут неизвестны)."""
if not isinstance(manifest, dict):
raise LtpError("plugin.json: нужен объект")
if manifest.get("ltp") != FORMAT:
raise LtpError("plugin.json: этот мод читает формат %d" % FORMAT)
plugin_id = manifest.get("id")
if not isinstance(plugin_id, str) or not ID.fullmatch(plugin_id):
raise LtpError("id «%s» не подходит: латинские строчные буквы, цифры, точка, дефис, от 3 до 64 знаков. "
"Задай свой: Plugin(..., id=\"vasya.tihaya-noch\")" % (plugin_id,))
name = _text(manifest.get("name"), 40, "Название").strip()
author = _text(manifest.get("author"), 40, "Автор").strip()
if not name or not author:
raise LtpError("Название и автор не могут быть пустыми")
version = _text(manifest.get("version"), 16, "Версия")
if not VERSION.fullmatch(version):
raise LtpError("Версия «%s»: только буквы, цифры, точка и дефис, например 1.0" % version)
if manifest.get("description") is not None:
_text(manifest["description"], 240, "Описание")
if manifest.get("license") is not None:
_text(manifest["license"], MAX_LICENSE, "Лицензия")
if manifest.get("ai") is not None:
models = manifest["ai"]
if not isinstance(models, list):
raise LtpError("plugin.json, «ai»: нужен список")
if len(models) > MAX_AI:
raise LtpError("plugin.json, «ai»: не больше %d записей" % MAX_AI)
for model in models:
if not _text(model, MAX_AI_TEXT, "plugin.json, «ai»").strip():
raise LtpError("plugin.json, «ai»: пустая запись")
permissions = manifest.get("permissions", [])
if not isinstance(permissions, list):
raise LtpError("permissions: нужен список")
for right in permissions:
if right not in RIGHTS:
raise LtpError("Неизвестное право «%s»" % right)
if len(set(permissions)) != len(permissions):
raise LtpError("Одно право названо дважды")
rules = manifest.get("rules")
if not isinstance(rules, list) or not rules:
raise LtpError("В плагине нет правил: добавь хотя бы одно, например plugin.video(hashtag(\"fyp\"), hide)")
if len(rules) > MAX_RULES:
raise LtpError("В плагине больше %d правил" % MAX_RULES)
used = set()
downloads = []
for index, rule in enumerate(rules):
where = "Правило %d" % (index + 1)
if not isinstance(rule, dict):
raise LtpError("%s: нужен объект" % where)
title = rule.get("title")
if title is not None:
_text(title, 60, where)
if title.strip():
where = "Правило «%s»" % title
trigger = rule.get("when")
if trigger not in TRIGGERS:
raise LtpError("%s: when — это feed.item, name.show или screen.show" % where)
if rule.get("if") is not None:
check_condition(rule["if"], where)
actions = rule.get("do")
if not isinstance(actions, list) or not 1 <= len(actions) <= MAX_ACTIONS:
raise LtpError("%s: в правиле от 1 до %d действий" % (where, MAX_ACTIONS))
for action in actions:
check_action(action, trigger, where)
if "download" in action:
downloads.append(check_download(action["download"], where))
for right in rights_of(action):
if right not in permissions:
raise LtpError("%s: действию нужно право «%s», его нет в permissions" % (where, right))
used.add(right)
if rule.get("limit") is not None:
_integer(rule["limit"], 1, MAX_LIMIT, where + ", «limit»")
for right in permissions:
if right not in used:
raise LtpError("Плагин просит право «%s», но не использует его" % right)
check_net(manifest.get("net"), permissions, downloads, assets)
if assets is not None:
check_assets(manifest, assets)
def check_net(net, permissions, downloads, assets):
"""Поле «net» (сайты) есть ровно тогда, когда есть право net.download; в нём все сайты скачиваний и никаких других."""
right = "net.download" in permissions
if net is not None and not right:
raise LtpError("plugin.json: есть «net», но нет права «net.download»")
if not right:
return
if net is None:
raise LtpError("plugin.json: право «net.download» требует поле «net» со списком сайтов")
if not isinstance(net, dict):
raise LtpError("plugin.json, «net»: нужен объект")
for key in net:
if key != "hosts":
raise LtpError("plugin.json, «net»: нет поля «%s»" % key)
raw = net.get("hosts")
if not isinstance(raw, list):
raise LtpError("plugin.json, «net», «hosts»: нужен список")
hosts = []
for host in raw:
_text(host, 253, "plugin.json, «net», «hosts»")
if not valid_host(host):
raise LtpError("plugin.json, «net»: «%s» не похоже на имя сайта (строчные буквы, цифры, дефис, точки)" % host)
if host in hosts:
raise LtpError("plugin.json, «net»: сайт «%s» назван дважды" % host)
hosts.append(host)
if not 1 <= len(hosts) <= MAX_HOSTS:
raise LtpError("plugin.json, «net»: от 1 до %d сайтов" % MAX_HOSTS)
if len(downloads) > MAX_DOWNLOADS:
raise LtpError("В плагине больше %d скачиваний" % MAX_DOWNLOADS)
used, names = set(), set()
for host, name in downloads:
if host not in hosts:
raise LtpError("Скачивание с «%s»: этого сайта нет в списке «net»" % host)
if name in names:
raise LtpError("Файл «%s» скачивается дважды" % name)
if assets is not None and name in assets:
raise LtpError("Файл «%s» уже есть в плагине, скачать его под этим именем нельзя" % name)
names.add(name)
used.add(host)
for host in hosts:
if host not in used:
raise LtpError("Сайт «%s» назван в «net», но с него ничего не скачивается" % host)
def downloaded_files(manifest):
"""Имена файлов, которые плагин скачивает сам (их не нужно класть в плагин)."""
return {action["download"].get("as") for rule in manifest.get("rules", []) for action in rule.get("do", [])
if "download" in action}
def referenced_files(manifest):
fetched = downloaded_files(manifest)
names = []
for rule in manifest.get("rules", []):
for action in rule.get("do", []):
if "overlay" in action:
spec = action["overlay"]
for key in ("image", "sound", "pet"):
if spec.get(key) and spec[key] not in fetched:
names.append(spec[key])
return names
def check_assets(manifest, assets):
if len(assets) > MAX_ASSETS:
raise LtpError("В плагине больше %d файлов" % MAX_ASSETS)
for name, body in assets.items():
suffix = "." + name.rsplit(".", 1)[-1].lower() if "." in name else ""
check = MAGIC.get(suffix)
if not ASSET.fullmatch(name) or check is None or not check(body):
raise LtpError("Файл %s не подходит: png, gif, webp, ogg или mp3, имя строчными латинскими буквами, "
"и внутри должен быть именно этот тип файла" % name)
if len(body) > MAX_ASSET:
raise LtpError("Файл %s больше 400 КБ (сейчас %d КБ): сожми его" % (name, len(body) // 1024))
fetched = downloaded_files(manifest)
for rule in manifest.get("rules", []):
for action in rule.get("do", []):
if "overlay" not in action:
continue
spec = action["overlay"]
for key, expected in (("image", "image"), ("pet", "image"), ("sound", "sound")):
name = spec.get(key)
if not name:
continue
if name not in assets and name not in fetched:
raise LtpError("Плагину нужен файл %s, а его нет рядом со скриптом (положи рядом или в папку files)"
% name)
kind = KINDS.get("." + name.rsplit(".", 1)[-1].lower(), "")
if kind != expected:
raise LtpError("%s: «%s» — это %s, а файл %s другого типа" % (
"Картинка" if key != "sound" else "Звук", key,
"png, gif или webp" if expected == "image" else "ogg или mp3", name))