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

57 lines
2.5 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.
"""Упаковка и чтение файлов .ltp (это обычный zip: plugin.json, иногда icon.png и папка assets/)."""
import json
import zipfile
from pathlib import Path
from . import validate
from .errors import LtpError
def write_ltp(path, manifest, assets, icon=None):
path = Path(path)
raw = json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8")
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as archive:
archive.writestr("plugin.json", raw)
for name in sorted(assets):
archive.writestr("assets/" + name, assets[name])
if icon is not None:
if not icon.startswith(validate.PNG) or len(icon) > validate.MAX_ICON:
raise LtpError("icon.png должна быть PNG не больше 64 КБ")
archive.writestr("icon.png", icon)
if path.stat().st_size > validate.MAX_FILE:
raise LtpError("Файл получился больше 1 МБ: уменьши картинки или звуки")
return path
def read_ltp(path):
"""Читает .ltp и проверяет как приложение. Возвращает (manifest, assets, icon)."""
path = Path(path)
if not path.is_file():
raise LtpError("Файл %s не найден" % path)
if path.stat().st_size > validate.MAX_FILE:
raise LtpError("Файл больше 1 МБ: приложение его не примет")
try:
archive = zipfile.ZipFile(path)
except zipfile.BadZipFile:
raise LtpError("%s — это не .ltp (не zip-архив)" % path.name)
with archive:
manifest, assets, icon = None, {}, None
for info in archive.infolist():
name = info.filename
if name == "plugin.json":
try:
manifest = json.loads(archive.read(name).decode("utf-8"))
except (UnicodeDecodeError, ValueError) as error:
raise LtpError("plugin.json не читается: %s" % error)
elif name == "icon.png":
icon = archive.read(name)
elif name.startswith("assets/") and name.count("/") == 1 and len(name) > 7:
assets[name[7:]] = archive.read(name)
else:
raise LtpError("В файле лишнее: %s (разрешены plugin.json, icon.png и файлы в assets/)" % name)
if manifest is None:
raise LtpError("В файле нет plugin.json")
validate.check_manifest(manifest, assets)
return manifest, assets, icon