Files
LihonT/sdk/lihont-ltp/lihont_ltp/core.py
cheb0chik 38e7b2551e LihonT 2 Serena alpha 2
Plugin icons for the feed buttons (right ui.icons: like, comment, collect, share), preview cards that a theme author
attaches and the list of looks shows before a theme is picked, the sample plugins lihont.icons-sticker, lihont.theme-win95 and
lihont.theme-sunset with their pictures, docs, SDK, skill and tests for all of it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 13:08:56 +03:00

546 lines
24 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.
"""Язык плагинов: условия, действия и сам плагин.
Всё пишется почти как предложение:
plugin.video(hashtag("fyp"), hide) # видео с #fyp: скрыть
plugin.name(me & morning, after(" ☀️")) # моё имя утром: добавить солнышко
plugin.screen(picture("cat.gif")) # на экране: показать картинку
Права (permissions) считаются сами, их писать не нужно.
"""
import inspect
import json
import os
import re
from pathlib import Path
from . import guard as guard_module
from . import validate
from .errors import LtpError
_TRANSLIT = dict(zip("абвгдеёжзийклмнопрстуфхцчшщъыьэюя",
["a", "b", "v", "g", "d", "e", "e", "zh", "z", "i", "y", "k", "l", "m", "n", "o", "p", "r", "s",
"t", "u", "f", "h", "c", "ch", "sh", "sch", "", "y", "", "e", "yu", "ya"]))
_DAYS = {"mon": 1, "tue": 2, "wed": 3, "thu": 4, "fri": 5, "sat": 6, "sun": 7,
"пн": 1, "вт": 2, "ср": 3, "чт": 4, "пт": 5, "сб": 6, "вс": 7}
def _slug(text):
out = "".join(_TRANSLIT.get(c, c) for c in text.lower())
out = re.sub(r"[^a-z0-9]+", "-", out).strip("-")
return out
# ---- условия -------------------------------------------------------------------------------------------------
class Condition:
"""Условие «если…». Склеивай через & («и»), | («или»), ~ («не»)."""
def __and__(self, other):
return _group("all", self, _cond(other))
def __or__(self, other):
return _group("any", self, _cond(other))
def __invert__(self):
return _Not(self)
def __rand__(self, other):
return _group("all", _cond(other), self)
def __ror__(self, other):
return _group("any", _cond(other), self)
def to_json(self, kind):
raise NotImplementedError
class _Leaf(Condition):
def __init__(self, key, value):
self.key = key
self.value = value
def to_json(self, kind):
return {self.key: self.value}
class _Me(Condition):
"""«Я»: в правилах про видео это автор видео, в правилах про имена это имя на экране."""
def to_json(self, kind):
if kind == "video":
return {"author": ["self"]}
if kind == "name":
return {"uid": ["self"]}
raise LtpError("Слово «me» (я) нужно в правилах про видео или про имена, в правиле про экран оно не имеет смысла")
class _Group(Condition):
def __init__(self, key, parts):
self.key = key
self.parts = parts
def to_json(self, kind):
return {self.key: [part.to_json(kind) for part in self.parts]}
class _Not(Condition):
def __init__(self, part):
self.part = part
def to_json(self, kind):
return {"not": self.part.to_json(kind)}
def _group(key, left, right):
parts = []
for side in (left, right):
if isinstance(side, _Group) and side.key == key:
parts.extend(side.parts)
else:
parts.append(side)
return _Group(key, parts)
def _cond(value):
if not isinstance(value, Condition):
raise LtpError("Здесь нужно условие (например word(\"привет\") или hashtag(\"fyp\")), а получилось: %r" % (value,))
return value
def _strings(values, name):
if not values:
raise LtpError("%s(...): напиши хотя бы одно значение, например %s(\"fyp\")" % (name, name))
out = []
for value in values:
if not isinstance(value, str):
raise LtpError("%s(...): значения пишутся в кавычках, например %s(\"fyp\")" % (name, name))
out.append(value)
return out
def word(*words):
"""В описании видео есть любое из этих слов: word("розыгрыш", "giveaway")."""
return _Leaf("text", _strings(words, "word"))
def hashtag(*tags):
"""У видео есть любой из этих хэштегов (# писать не нужно): hashtag("fyp", "foryou")."""
return _Leaf("hashtag", _strings(tags, "hashtag"))
def author(*names):
"""Видео выложил этот человек (ник или id): author("vasya")."""
return _Leaf("author", _strings(names, "author"))
def person(*ids):
"""Имя на экране принадлежит этому аккаунту (id): person("6812345")."""
return _Leaf("uid", _strings(ids, "person"))
def account(*names):
"""Правило работает, только пока ты вошёл под этим аккаунтом: account("cheb0chik")."""
return _Leaf("account", _strings(names, "account"))
def between(start, end):
"""Время суток: between("22:00", "07:00") (можно через полночь)."""
return _Leaf("time", "%s-%s" % (start, end))
def weekday(*days):
"""Дни недели: weekday("fri") или weekday("sat", "sun"); можно и по-русски: weekday("пт")."""
numbers = []
for day in days:
if isinstance(day, int) and not isinstance(day, bool):
numbers.append(day)
elif isinstance(day, str) and day.lower() in _DAYS:
numbers.append(_DAYS[day.lower()])
else:
raise LtpError("weekday(%r): день пишется так: mon, tue, wed, thu, fri, sat, sun (или пн, вт, ср, чт, пт, сб, вс)"
% (day,))
if not numbers:
raise LtpError("weekday(...): напиши хотя бы один день, например weekday(\"fri\")")
return _Leaf("weekday", numbers)
def all_of(*conditions):
"""Все условия сразу (то же, что &)."""
parts = [_cond(c) for c in conditions]
return parts[0] if len(parts) == 1 else _Group("all", parts)
def any_of(*conditions):
"""Любое из условий (то же, что |)."""
parts = [_cond(c) for c in conditions]
return parts[0] if len(parts) == 1 else _Group("any", parts)
me = _Me()
morning = between("06:00", "12:00")
day = between("12:00", "18:00")
evening = between("18:00", "23:00")
night = between("23:00", "06:00")
friday = weekday("fri")
weekend = weekday("sat", "sun")
class _Always:
"""Без условия: правило работает всегда."""
always = _Always()
# ---- действия ------------------------------------------------------------------------------------------------
class Action:
def __init__(self, key, value, name):
self.key = key
self.value = value
self.name = name
def to_json(self):
return {self.key: self.value}
class Tap:
"""Что происходит, когда нажимаешь на картинку."""
def __init__(self, key, sound_file=None):
self.key = key
self.sound_file = sound_file
hide = Action("feed.hide", True, "hide")
wiggle = Tap("animate")
like = Tap("like")
confetti = Tap("confetti")
buzz = Tap("buzz")
def say(text):
"""Показать короткую подсказку (не чаще нескольких раз в день): say("Тихая ночь")."""
return Action("notice", text, "say")
def before(text):
"""Дописать текст перед именем: before("⭐ ")."""
return Action("name.prefix", text, "before")
def after(text):
"""Дописать текст после имени: after(" ☀️")."""
return Action("name.suffix", text, "after")
def rename(text):
"""Показать другое имя вместо настоящего (только у тебя на экране): rename("Аноним")."""
return Action("name.replace", text, "rename")
def style(kind):
"""Вид имени на твоём экране: style("upper") — ЗАГЛАВНЫМИ, "lower" — строчными, "reverse" — наоборот,
"wave" — пРиВеТ, "spaced" — п р и в е т. Только у тебя на экране; лучше с условием (me, person(...))."""
return Action("name.style", kind, "style")
def sound(file):
"""Играть звук при нажатии на картинку: picture("cat.gif", on_tap=[sound("meow.ogg")])."""
return Tap("sound", file)
class Walk:
"""Как картинка ходит по экрану сама: bounce(...) или wander(...)."""
def __init__(self, mode, speed, flip):
self.mode = mode
self.speed = speed
self.flip = flip
def to_json(self):
return {"mode": self.mode, "speed": self.speed, "flip": self.flip}
def bounce(speed=40, flip=True):
"""Ходит туда-сюда вдоль низа экрана и разворачивается у краёв: picture("кот.png", walk=bounce(speed=40)).
speed — скорость, dp в секунду (10–300). flip=True — на пути влево картинка отражается (рисуй её лицом вправо).
"""
return Walk("bounce", speed, flip)
def wander(speed=40, flip=True):
"""Бродит: идёт, иногда останавливается и разворачивается в случайный момент: picture("привидение.png", walk=wander())."""
return Walk("wander", speed, flip)
def picture(file, size=140, right=16, bottom=16, opacity=100, movable=True, on_tap=None, pet=None, wiggle_ms=1250,
walk=None):
"""Картинка в углу приложения. Файл лежит рядом со скриптом (png, gif или webp).
on_tap=[wiggle, sound("мяу.ogg"), like] — что делать, когда на неё нажали (ещё confetti — конфетти и buzz — вибрация).
pet="погладили.gif" — вторая картинка, когда водишь пальцем по верхней половине.
walk=bounce(speed=40) или wander() — картинка сама ходит по экрану (двигать её пальцем тогда нельзя).
"""
taps = on_tap if on_tap is not None else [wiggle]
sound_file = None
keys = []
for tap in taps:
if not isinstance(tap, Tap):
raise LtpError("picture(..., on_tap=[...]): внутри можно wiggle, sound(\"файл.ogg\"), like, confetti и buzz")
keys.append(tap.key)
if tap.sound_file:
sound_file = tap.sound_file
spec = {"image": file, "size": size, "alpha": opacity, "right": right, "bottom": bottom, "movable": movable,
"tap": keys, "animate_ms": wiggle_ms}
if sound_file:
spec["sound"] = sound_file
if pet:
spec["pet"] = pet
if walk is not None:
if not isinstance(walk, Walk):
raise LtpError("picture(..., walk=...): внутри bounce(...) или wander(...)")
spec["walk"] = walk.to_json()
return Action("overlay", spec, "picture")
def download(url, name, sha256=None):
"""Скачать файл (картинку или звук) с сайта и положить его плагину под этим именем.
plugin.screen(download("https://cdn.example.com/cat.png", "cat.png"), picture("cat.png"))
Это единственное, что плагин делает в интернете. Скачивание включается отдельным переключателем в телефоне,
а каждый адрес человек подтверждает кнопкой «Скачать». Адрес пишется целиком (https, без порта), сайты
попадают в плагин сами. sha256="..." (64 знака) пинит файл: другой файл на сайте мод не примет.
"""
if not isinstance(url, str) or not isinstance(name, str):
raise LtpError("download(\"https://сайт/файл.png\", \"имя.png\"): адрес и имя пишутся в кавычках")
spec = {"url": url, "as": name}
if sha256 is not None:
spec["sha256"] = sha256
return Action("download", spec, "download")
# ---- плагин --------------------------------------------------------------------------------------------------
class Plugin:
"""Один плагин. Создай, добавь правила и вызови .save().
plugin = Plugin("Тихая ночь", author="Вася")
plugin.video(night & hashtag("challenge"), hide)
plugin.save()
"""
def __init__(self, name, author="", description="", version="1.0", id=None, icon=None, license=None, ai=None):
if not author:
raise LtpError("Укажи автора: Plugin(\"%s\", author=\"Твой ник\")" % name)
if ai is not None and isinstance(ai, str):
ai = [ai]
self.title = name
self.author = author
self.license = license
self.ai = list(ai) if ai else []
self.description = description
self.version = version
self.icon = icon
self.id = id or "%s.%s" % (_slug(author) or "me", _slug(name) or "plugin")
self._rules = []
self._theme = None
self._icons = None
self._base = _caller_folder()
# правила ----------------------------------------------------------------------------------------------------
def video(self, when, *actions, title=None, limit=None):
"""Правило про видео в ленте: plugin.video(hashtag("fyp"), hide)."""
return self._add("video", "feed.item", when, actions, title, limit)
def name(self, when, *actions, title=None, limit=None):
"""Правило про имена на экране: plugin.name(me, after(" ☀️"))."""
return self._add("name", "name.show", when, actions, title, limit)
def screen(self, *actions, when=always, title=None, limit=None):
"""Правило про экраны приложения: plugin.screen(picture("cat.gif"))."""
if actions and actions[0] is always:
actions = actions[1:]
return self._add("screen", "screen.show", when, actions, title, limit)
def theme(self, name=None, *, page, card, text, accent, muted=None, on_accent=None, line=None, title_from=None,
title_to=None, dark=False, radius=None, outline=None, shadow=None, bevel=False, tick_box=False,
title_bars=False, preview=None):
"""Тема оформления: цвета и пара чисел. Тема только красит: она ничего не прячет и не двигает.
plugin.theme("Закат", page="#2b1d3a", card="#3d2b52", text="#fbe9ff", accent="#ff8a5b", radius=20)
preview=["card1.png", "card2.png"] — до четырёх своих картинок-карточек: их видно в списке «Оформление»
до выбора темы (png, gif или webp рядом со скриптом).
Цвета пишутся как #rrggbb маленькими буквами. radius 0–40, outline 0–6, shadow 0–12.
bevel даёт объёмные рамки (как Windows 95), tick_box рисует переключатель галочкой, title_bars делает
заголовки разделов полосой.
"""
theme = {"name": name or self.title, "page": page, "card": card, "text": text, "accent": accent}
for key, value in (("muted", muted), ("on_accent", on_accent), ("line", line), ("title_from", title_from),
("title_to", title_to), ("radius", radius), ("outline", outline), ("shadow", shadow)):
if value is not None:
theme[key] = value
for key, value in (("dark", dark), ("bevel", bevel), ("tick_box", tick_box), ("title_bars", title_bars)):
if value:
theme[key] = True
if preview:
theme["preview"] = [preview] if isinstance(preview, str) else list(preview)
self._theme = theme
return self
def icons(self, like=None, comment=None, collect=None, share=None):
"""Свои картинки для кнопок справа в ленте: лайк, комментарии, избранное, поделиться.
plugin.icons(like="heart.png", comment="bubble.png")
Картинки (png, gif или webp) лежат рядом со скриптом. Кнопки остаются на месте и работают как раньше:
меняется только картинка на них.
"""
icons = {slot: value for slot, value in (("like", like), ("comment", comment), ("collect", collect),
("share", share)) if value}
if not icons:
raise LtpError("icons(...): назови хотя бы одну кнопку, например icons(like=\"heart.png\")")
self._icons = icons
return self
def _add(self, kind, trigger, when, actions, title, limit):
if isinstance(when, Action): # забыли условие: plugin.video(hide) значит «всегда»
actions = (when,) + tuple(actions)
when = always
if when is not always and not isinstance(when, Condition):
raise LtpError("Первое в правиле — условие (например hashtag(\"fyp\")) или always, а получилось: %r" % (when,))
for action in actions:
if not isinstance(action, Action):
raise LtpError("После условия идут действия (hide, say(...), after(...), picture(...)), а получилось: %r"
% (action,))
if not actions:
raise LtpError("В правиле нет действий: что делать? Например hide или say(\"текст\")")
rule = {"title": title, "when": trigger, "kind": kind}
if when is not always:
rule["if"] = when.to_json(kind)
rule["do"] = [a.to_json() for a in actions]
if limit is not None:
rule["limit"] = limit
self._rules.append(rule)
return self
# сборка -----------------------------------------------------------------------------------------------------
def manifest(self):
rules, rights = [], []
for index, source in enumerate(self._rules):
rule = {"title": source["title"] or "Правило %d" % (index + 1), "when": source["when"]}
if "if" in source:
rule["if"] = source["if"]
if "limit" in source:
rule["limit"] = source["limit"]
rule["do"] = source["do"]
rules.append(rule)
for action in source["do"]:
for right in validate.rights_of(action):
if right not in rights:
rights.append(right)
manifest = {"ltp": validate.FORMAT, "id": self.id, "name": self.title, "version": self.version,
"author": self.author, "description": self.description}
if self.license:
manifest["license"] = self.license
if self.ai:
manifest["ai"] = self.ai
if self._theme is not None:
rights.append("ui.theme")
if self._icons is not None:
rights.append("ui.icons")
manifest["permissions"] = rights
if "net.download" in rights:
# сайты берутся из адресов скачиваний: писать их отдельно не нужно
hosts = []
for rule in rules:
for action in rule["do"]:
if "download" in action:
url = str(action["download"].get("url", ""))
host = url[len("https://"):].split("/", 1)[0] if url.startswith("https://") else ""
if host and host not in hosts:
hosts.append(host)
manifest["net"] = {"hosts": hosts}
if self._theme is not None:
manifest["theme"] = self._theme
if self._icons is not None:
manifest["icons"] = self._icons
if rules or (self._theme is None and self._icons is None):
manifest["rules"] = rules
if not self.description:
del manifest["description"]
return manifest
def _find_assets(self, manifest, folder):
assets = {}
for name in validate.referenced_files(manifest):
for place in (folder / name, folder / "files" / name):
if place.is_file():
assets[name] = place.read_bytes()
break
return assets
def build(self, folder=None):
"""Проверить и собрать. Возвращает (manifest, assets, report). Ошибка — LtpError с понятным текстом."""
folder = Path(folder) if folder else self._base
manifest = self.manifest()
assets = self._find_assets(manifest, folder)
validate.check_manifest(manifest, assets)
report = guard_module.check(manifest, assets.keys())
return manifest, assets, report
def guard(self, folder=None):
"""Показать защитника, ничего не сохраняя."""
report = self.build(folder)[2]
print(report.text())
return report
def save(self, folder=None, show=True):
"""Собрать файл <id>.ltp рядом со скриптом и показать защитника. Возвращает путь к файлу."""
from .pack import write_ltp
folder = Path(folder) if folder else self._base
manifest, assets, report = self.build(folder)
icon = None
if self.icon:
icon_path = folder / self.icon
if not icon_path.is_file():
raise LtpError("Иконка %s не найдена рядом со скриптом" % self.icon)
icon = icon_path.read_bytes()
out = Path(os.environ["LTP_OUT_DIR"]) if os.environ.get("LTP_OUT_DIR") else folder
out.mkdir(parents=True, exist_ok=True)
path = write_ltp(out / (self.id + ".ltp"), manifest, assets, icon)
if show:
print(report.text())
print("\nГотово: %s (%d байт)" % (path, path.stat().st_size))
print("Отправить на телефон по проводу: ltp phone \"%s\"" % path.name)
return path
def _caller_folder():
"""Папка скрипта, который создал плагин: рядом с ним лежат картинки и сюда сохраняется .ltp."""
here = Path(__file__).resolve().parent
frame = inspect.currentframe()
try:
while frame is not None:
name = frame.f_code.co_filename
if name and not name.startswith("<") and Path(name).resolve().parent != here:
return Path(name).resolve().parent
frame = frame.f_back
return Path.cwd()
finally:
del frame
def manifest_json(manifest):
return json.dumps(manifest, ensure_ascii=False, indent=2)