Files
LihonT/sdk/lihont-ltp/lihont_ltp/validate.py
cheb0chik 3540ac84ea LihonT 2.3.0 (Serena): profile music, AI video dubbing, PiP & bg play, fonts, cleaner
- Shared moderated MP3 profile music (with floating mini-player and MediaSession controls, zero bubble when absent)
- AI video dubbing into Russian with burned-in ASS subtitles inside AgentChat (`services/members/dub.py`)
- Picture-in-Picture 9:16 and background audio playback (`PlayControl` + `play_patch.py`)
- System/custom .ttf fonts & emoji packs (`FontsAndEmoji`), account cleaner (`AccountCleaner`)
- Feed blacklist, muted sound restoration, OLED burn-in shift, A/B flag editor, presets, long comments
- Updated site homepage (`src/web/index.html`) for LihonT 2.3.0 Serena
2026-11-26 15:40:32 +03:00

622 lines
32 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", "ui.theme", "ui.icons")
ACTIONS = ("feed.hide", "feed.keep", "name.prefix", "name.suffix", "name.replace", "name.style", "notice", "overlay",
"download")
NAME_STYLES = ("upper", "lower", "reverse", "wave", "spaced")
NUMBERS = {"duration": 86400, "likes": 2000000000, "comments": 2000000000, "shares": 2000000000,
"plays": 2000000000, "age": 36500, "followers": 2000000000}
FLAGS = ("verified", "photo", "liked")
TAPS = ("animate", "sound", "like", "confetti", "buzz")
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_THEME_NAME = 24
ICON_SLOTS = ("like", "comment", "collect", "share")
MAX_RADIUS = 40
MAX_OUTLINE = 6
MAX_SHADOW = 12
THEME_KEYS = ("name", "dark", "page", "card", "text", "muted", "accent", "on_accent", "line", "title_from", "title_to",
"radius", "outline", "shadow", "bevel", "tick_box", "title_bars", "preview")
MAX_PREVIEW = 4
THEME_COLOURS = ("page", "card", "text", "muted", "accent", "on_accent", "line", "title_from", "title_to")
THEME_FLAGS = ("dark", "bevel", "tick_box", "title_bars")
COLOUR = re.compile(r"#[0-9a-f]{6}")
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 _bounds(value, high, where):
"""Пара [от, до]; вместо границы можно null, хотя бы одна граница нужна."""
if not isinstance(value, list) or len(value) != 2:
raise LtpError("%s: нужно [от, до], вместо границы можно null" % where)
out = []
for item in value:
out.append(None if item is None else _integer(item, 0, high, where))
if out[0] is None and out[1] is None:
raise LtpError("%s: назови хотя бы одну границу" % where)
if out[0] is not None and out[1] is not None and out[0] > out[1]:
raise LtpError("%s: «от» больше, чем «до»" % where)
return out
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 NUMBERS:
_bounds(value, NUMBERS[key], here)
elif key in FLAGS:
if value is not True:
raise LtpError("%s: нужно true (для «не» поставь ~ перед условием)" % here)
elif key == "music":
_words(value, 64, 80, here)
elif key == "chance":
_integer(value, 1, 100, 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 in ("feed.hide", "feed.keep"):
if trigger != "feed.item":
raise LtpError("«скрыть» и «оставить» работают только в правилах про видео: %s" % where)
if value is not True:
raise LtpError("%s: нужно true" % here)
elif key == "name.style":
if trigger != "name.show":
raise LtpError("«вид имени» работает только в правилах про имена: %s" % where)
_text(value, 12, here)
if value not in NAME_STYLES:
raise LtpError("%s: вид имени — upper, lower, reverse, wave или spaced, а не «%s»" % (here, value))
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 TAPS:
raise LtpError("%s, «tap»: можно wiggle, sound(...), like, confetti и buzz" % 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 in ("feed.hide", "feed.keep"):
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_icons(icons, where="plugin.json, «icons»"):
"""Значки кнопок ленты: кнопка → файл картинки. Те же правила, что в Plugin.java (parseIcons)."""
if not isinstance(icons, dict):
raise LtpError("%s: нужен объект {…}" % where)
for key in icons:
if key not in ICON_SLOTS:
raise LtpError("%s: нет кнопки «%s» (можно like, comment, collect, share)" % (where, key))
named = 0
for slot in ICON_SLOTS:
if icons.get(slot) is None:
continue
name = _text(icons[slot], 40, where + ", «%s»" % slot)
if KINDS.get("." + name.rsplit(".", 1)[-1].lower(), "") != "image":
raise LtpError("%s, «%s»: это png, gif или webp, а не «%s»" % (where, slot, name))
named += 1
if not named:
raise LtpError("%s: назови хотя бы одну кнопку" % where)
def theme_colour(theme, key, default):
"""Цвет темы как число 0xRRGGBB; если поля нет — значение по умолчанию (те же, что в приложении)."""
value = theme.get(key)
return default if value is None else int(value[1:], 16)
def theme_values(theme):
"""Цвета темы с теми же умолчаниями, что в ThemeData.java: (текст, карточка, акцент, текст на акценте)."""
text = theme_colour(theme, "text", 0)
card = theme_colour(theme, "card", 0)
accent = theme_colour(theme, "accent", 0)
on_accent = theme_colour(theme, "on_accent", 0xFFFFFF)
return text, card, accent, on_accent
def _linear(channel):
c = channel / 255.0
return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
def _luminance(rgb):
return 0.2126 * _linear((rgb >> 16) & 0xFF) + 0.7152 * _linear((rgb >> 8) & 0xFF) + 0.0722 * _linear(rgb & 0xFF)
def contrast_tenths(a, b):
"""Контраст WCAG в десятых (21.0 это 210), отбрасывая лишнее, как в Java: так проверки совпадают."""
one = _luminance(a) + 0.05
two = _luminance(b) + 0.05
ratio = one / two if one > two else two / one
return int(ratio * 10)
def check_theme(theme, where="plugin.json, «theme»"):
"""Тема: цвета и несколько чисел, ничего больше. Те же поля и границы, что в ThemeData.java."""
if not isinstance(theme, dict):
raise LtpError("%s: нужен объект {…}" % where)
for key in theme:
if key not in THEME_KEYS:
raise LtpError("%s: нет поля «%s»" % (where, key))
name = _text(theme.get("name"), MAX_THEME_NAME, where + ", поле «name»").strip()
if not name:
raise LtpError("%s: название темы не может быть пустым" % where)
for key in ("page", "card", "text", "accent"):
if theme.get(key) is None:
raise LtpError("%s: нет поля «%s»" % (where, key))
for key in THEME_COLOURS:
value = theme.get(key)
if value is not None:
_text(value, 7, where + ", поле «%s»" % key)
if not COLOUR.fullmatch(value):
raise LtpError("%s, поле «%s»: цвет пишут как #rrggbb, например #2b1d3a (маленькими буквами)" % (where, key))
for key, high in (("radius", MAX_RADIUS), ("outline", MAX_OUTLINE), ("shadow", MAX_SHADOW)):
if theme.get(key) is not None:
_integer(theme[key], 0, high, where + ", поле «%s»" % key)
if theme.get("preview") is not None:
cards = theme["preview"]
if not isinstance(cards, list):
raise LtpError("%s: нужен список […]" % (where + ", поле «preview»"))
if not 1 <= len(cards) <= MAX_PREVIEW:
raise LtpError("%s, поле «preview»: от 1 до %d картинок" % (where, MAX_PREVIEW))
for card in cards:
file = _text(card, 40, where + ", поле «preview»")
if KINDS.get("." + file.rsplit(".", 1)[-1].lower(), "") != "image":
raise LtpError("%s, поле «preview»: это png, gif или webp, а не «%s»" % (where, file))
if len(set(cards)) != len(cards):
raise LtpError("%s, поле «preview»: одна и та же картинка названа дважды" % where)
for key in THEME_FLAGS:
if theme.get(key) is not None and not isinstance(theme[key], bool):
raise LtpError("%s, поле «%s»: нужно true или false" % (where, key))
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("Одно право названо дважды")
theme = manifest.get("theme")
if theme is not None:
if "ui.theme" not in permissions:
raise LtpError("plugin.json: есть «theme», но нет права «ui.theme»")
check_theme(theme)
elif "ui.theme" in permissions:
raise LtpError("plugin.json: право «ui.theme» требует поле «theme»")
icons = manifest.get("icons")
if icons is not None:
if "ui.icons" not in permissions:
raise LtpError("plugin.json: есть «icons», но нет права «ui.icons»")
check_icons(icons)
elif "ui.icons" in permissions:
raise LtpError("plugin.json: право «ui.icons» требует поле «icons»")
looks = theme is not None or icons is not None
rules = manifest.get("rules")
if rules is None and looks:
rules = [] # a plugin that only brings a theme or icons has no rules
if not isinstance(rules, list) or (not rules and not looks):
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 ("ui.theme", "ui.icons") and 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])
for slot in ICON_SLOTS:
name = (manifest.get("icons") or {}).get(slot)
if name and name not in names:
names.append(name)
for card in (manifest.get("theme") or {}).get("preview") or []:
if card not in names:
names.append(card)
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))
for card in (manifest.get("theme") or {}).get("preview") or []:
if card not in assets:
raise LtpError("Плагину нужен файл %s для превью темы, а его нет рядом со скриптом (положи рядом или в папку files)"
% card)
for slot, name in (manifest.get("icons") or {}).items():
if name not in assets:
raise LtpError("Плагину нужен файл %s для кнопки %s, а его нет рядом со скриптом (положи рядом или в папку files)"
% (name, slot))
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))