1. обновил инструкцию

2. добавил в админку Добавление обновлений, чтобы не через код
This commit is contained in:
2026-06-22 17:58:20 +03:00
parent 3e6f767a12
commit 55cb965d9f
5 changed files with 1016 additions and 404 deletions

269
app.py
View File

@@ -27,6 +27,8 @@ from urllib.parse import quote, urlencode
import traceback import traceback
import contextlib import contextlib
import os import os
import html
import re
from parsers.parser_game import run_parser_game from parsers.parser_game import run_parser_game
from parsers.parser_players import run_parser_players from parsers.parser_players import run_parser_players
from parsers.parser_schedule import run_parser_schedule from parsers.parser_schedule import run_parser_schedule
@@ -1924,6 +1926,230 @@ async def list_vmix_clients():
return {"items": clients} return {"items": clients}
INFO_TEMPLATE_PATH = BASE_DIR / "templates" / "info.html"
def _clean_update_text(value: str | None) -> str:
return (value or "").strip()
def _escape_text(value: str | None) -> str:
return html.escape(_clean_update_text(value), quote=True)
def _split_lines(value: str | None) -> list[str]:
return [line.strip() for line in (value or "").splitlines() if line.strip()]
def _format_update_date(value: str | None) -> str:
value = _clean_update_text(value)
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
try:
return datetime.strptime(value, "%Y-%m-%d").strftime("%d.%m.%Y")
except ValueError:
return value
return value
def _paragraphs_html(value: str | None) -> str:
lines = _split_lines(value)
if not lines:
return "<p>Описание не заполнено.</p>"
return "\n".join(f"<p>{_escape_text(line)}</p>" for line in lines)
def _normalize_update_image_path(value: str | None) -> str:
path = _clean_update_text(value)
if not path:
return ""
# Удобный вариант для админки: можно ввести только имя файла,
# например "no photo.png" — оно превратится в /static/docs/no photo.png.
if path.startswith("static/"):
path = "/" + path
elif path.startswith("docs/"):
path = "/static/" + path
elif not path.startswith(("/static/", "http://", "https://")):
path = "/static/docs/" + path.lstrip("/")
return path
def _image_html(value: str | None, alt: str | None = None) -> str:
path = _normalize_update_image_path(value)
if not path:
return ""
return f'\n <img src="{html.escape(path, quote=True)}" alt="{_escape_text(alt or "Скриншот обновления")}">'
def _build_update_block(
version: str,
date: str,
operator_actions: str,
item_badges: list[str],
item_titles: list[str],
item_texts: list[str],
item_images: list[str] | None = None,
) -> str:
badge_meta = {
"new": ("new", "Новое"),
"fix": ("fix", "Исправлено"),
"improve": ("improve", "Улучшено"),
"important": ("important", "Важно"),
}
version_html = _escape_text(version)
date_html = _escape_text(date)
actions = _split_lines(operator_actions)
if actions:
actions_html = "\n".join(f"<li>{_escape_text(action)}</li>" for action in actions)
else:
actions_html = "<li>Ознакомиться с обновлением перед работой с матчем.</li>"
item_images = item_images or []
update_items: list[str] = []
max_len = max(len(item_titles), len(item_texts), len(item_badges), len(item_images), 1)
for index in range(max_len):
title = _clean_update_text(item_titles[index] if index < len(item_titles) else "")
text = _clean_update_text(item_texts[index] if index < len(item_texts) else "")
badge = _clean_update_text(item_badges[index] if index < len(item_badges) else "new")
image = _clean_update_text(item_images[index] if index < len(item_images) else "")
if not title and not text:
continue
badge_class, badge_label = badge_meta.get(badge, badge_meta["new"])
item_title_html = _escape_text(title or "Без названия")
item_text_html = _paragraphs_html(text) + _image_html(image, title or "Скриншот обновления")
update_items.append(
f''' <div class="update-item">
<span class="update-badge {badge_class}">{badge_label}</span>
<div class="update-content">
<div class="update-title">{item_title_html}</div>
<div class="update-text">
{item_text_html}
</div>
</div>
</div>'''
)
if not update_items:
update_items.append(
''' <div class="update-item">
<span class="update-badge new">Новое</span>
<div class="update-content">
<div class="update-title">Обновление системы</div>
<div class="update-text">
<p>Описание не заполнено.</p>
</div>
</div>
</div>'''
)
items_html = "\n".join(update_items)
return f'''
<details class="update-details" open>
<summary>
<article class="update-card latest">
<div class="update-header">
<div>
<div class="update-version-big update-date">Версия {version_html}</div>
<div class="update-version">{date_html}</div>
</div>
<div class="update-toggle"></div>
</div>
<div class="update-actions">
<div class="update-actions-title">Что сделать оператору</div>
<ul>
{actions_html}
</ul>
</div>
<div class="update-items">
{items_html}
</div>
</article>
</summary>
</details>
'''.rstrip()
def _update_latest_summary(html_text: str, version: str, date: str, item_titles: list[str]) -> str:
titles = [title.strip() for title in item_titles if title and title.strip()]
if not titles:
titles = ["Добавлено новое обновление системы."]
list_items = "\n".join(f" <li>{_escape_text(title)}</li>" for title in titles[:5])
summary_html = f''' <div class="latest-update-box">
<div class="latest-update-title">Последние изменения: версия {_escape_text(version)} от {_escape_text(date)}</div>
<ul class="latest-update-list">
{list_items}
</ul>
</div>'''
pattern = re.compile(r' <div class="latest-update-box">.*? </div>', re.S)
return pattern.sub(summary_html, html_text, count=1)
def add_update_to_info_template(
version: str,
date: str,
operator_actions: str,
item_badges: list[str],
item_titles: list[str],
item_texts: list[str],
item_images: list[str] | None = None,
) -> None:
version = _clean_update_text(version)
date = _format_update_date(date)
if not version:
raise ValueError("Укажите номер версии.")
if not date:
raise ValueError("Укажите дату обновления.")
html_text = INFO_TEMPLATE_PATH.read_text(encoding="utf-8")
insert_marker = ' <div class="updates-timeline">'
if insert_marker not in html_text:
raise RuntimeError("Не найден блок updates-timeline в templates/info.html.")
# У старых карточек убираем отметку latest, чтобы зелёная лента NEW была только у свежего обновления.
html_text = html_text.replace('update-card latest', 'update-card')
new_update_html = _build_update_block(
version=version,
date=date,
operator_actions=operator_actions,
item_badges=item_badges,
item_titles=item_titles,
item_texts=item_texts,
item_images=item_images,
)
html_text = html_text.replace(
insert_marker,
insert_marker + "\n" + new_update_html,
1,
)
html_text = _update_latest_summary(html_text, version, date, item_titles)
INFO_TEMPLATE_PATH.write_text(html_text, encoding="utf-8")
@app.get("/info", response_class=HTMLResponse) @app.get("/info", response_class=HTMLResponse)
def info_page(request: Request): def info_page(request: Request):
return templates.TemplateResponse(name="info.html", request=request, context={}) return templates.TemplateResponse(name="info.html", request=request, context={})
@@ -1934,6 +2160,8 @@ def render_admin_db_index(
parser_output: str | None = None, parser_output: str | None = None,
parser_name: str | None = None, parser_name: str | None = None,
parser_success: bool | None = None, parser_success: bool | None = None,
update_output: str | None = None,
update_success: bool | None = None,
): ):
return templates.TemplateResponse( return templates.TemplateResponse(
name="admin_db_index.html", name="admin_db_index.html",
@@ -1943,6 +2171,8 @@ def render_admin_db_index(
"parser_output": parser_output, "parser_output": parser_output,
"parser_name": parser_name, "parser_name": parser_name,
"parser_success": parser_success, "parser_success": parser_success,
"update_output": update_output,
"update_success": update_success,
}, },
) )
@@ -2002,6 +2232,45 @@ def admin_db_run_parser(request: Request, parser_name: str = Form(...)):
) )
@app.post("/admin/db/add-update", response_class=HTMLResponse)
def admin_db_add_update(
request: Request,
version: str = Form(...),
date: str = Form(...),
operator_actions: str = Form(default=""),
item_badge: list[str] = Form(default=[]),
item_title: list[str] = Form(default=[]),
item_text: list[str] = Form(default=[]),
item_image: list[str] = Form(default=[]),
):
current_user = getattr(request.state, "current_user", None)
if not current_user or current_user.get("role") != "admin":
return RedirectResponse(url="/login", status_code=303)
try:
add_update_to_info_template(
version=version,
date=date,
operator_actions=operator_actions,
item_badges=item_badge,
item_titles=item_title,
item_texts=item_text,
item_images=item_image,
)
return render_admin_db_index(
request,
update_output=f"Обновление версии {version.strip()} добавлено в templates/info.html и будет отображаться сверху на странице /info.",
update_success=True,
)
except Exception:
return render_admin_db_index(
request,
update_output="Ошибка при добавлении обновления:\n" + traceback.format_exc(),
update_success=False,
)
@app.post("/admin/db/create-account", response_class=HTMLResponse) @app.post("/admin/db/create-account", response_class=HTMLResponse)
def admin_db_create_account( def admin_db_create_account(
request: Request, request: Request,

BIN
static/docs/no photo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

View File

@@ -150,7 +150,8 @@
pointer-events: none; pointer-events: none;
} }
.account-modal { .account-modal,
.update-modal {
position: fixed; position: fixed;
inset: 0; inset: 0;
display: none; display: none;
@@ -161,11 +162,13 @@
padding: 20px; padding: 20px;
} }
.account-modal.active { .account-modal.active,
.update-modal.active {
display: flex; display: flex;
} }
.account-modal-card { .account-modal-card,
.update-modal-card {
width: min(100%, 460px); width: min(100%, 460px);
background: rgba(12, 17, 26, 0.98); background: rgba(12, 17, 26, 0.98);
border: 1px solid rgba(0, 255, 136, 0.28); border: 1px solid rgba(0, 255, 136, 0.28);
@@ -174,13 +177,21 @@
padding: 24px; padding: 24px;
} }
.account-modal-title { .update-modal-card {
width: min(100%, 760px);
max-height: 92vh;
overflow-y: auto;
}
.account-modal-title,
.update-modal-title {
font-size: 22px; font-size: 22px;
font-weight: 700; font-weight: 700;
margin-bottom: 8px; margin-bottom: 8px;
} }
.account-modal-subtitle { .account-modal-subtitle,
.update-modal-subtitle {
color: var(--muted); color: var(--muted);
margin-bottom: 18px; margin-bottom: 18px;
line-height: 1.5; line-height: 1.5;
@@ -200,7 +211,8 @@
} }
.field-input, .field-input,
.field-select { .field-select,
.field-textarea {
width: 100%; width: 100%;
min-height: 44px; min-height: 44px;
border-radius: 12px; border-radius: 12px;
@@ -212,12 +224,75 @@
outline: none; outline: none;
} }
.field-textarea {
min-height: 96px;
padding: 12px 14px;
resize: vertical;
line-height: 1.45;
font-family: Arial, sans-serif;
}
.field-input:focus, .field-input:focus,
.field-select:focus { .field-select:focus,
.field-textarea:focus {
border-color: var(--accent); border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(0, 255, 136, 0.12); box-shadow: 0 0 0 3px rgba(0, 255, 136, 0.12);
} }
.update-form-grid {
display: grid;
grid-template-columns: 1fr 180px;
gap: 14px;
}
.update-items-editor {
display: grid;
gap: 14px;
}
.update-item-form {
display: grid;
grid-template-columns: 160px minmax(0, 1fr);
gap: 12px;
padding: 14px;
border: 1px solid var(--border);
border-radius: 14px;
background: rgba(255, 255, 255, 0.025);
}
.update-item-text,
.update-item-image {
grid-column: 1 / -1;
}
.helper-text {
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.add-row-btn {
min-height: 38px;
padding: 0 14px;
border-radius: 999px;
border: 1px dashed rgba(0, 255, 136, 0.45);
background: rgba(0, 255, 136, 0.06);
color: var(--accent);
font-weight: 700;
cursor: pointer;
}
.add-row-btn:hover {
background: rgba(0, 255, 136, 0.12);
}
@media (max-width: 720px) {
.update-form-grid,
.update-item-form {
grid-template-columns: 1fr;
}
}
.modal-actions { .modal-actions {
display: flex; display: flex;
gap: 12px; gap: 12px;
@@ -308,6 +383,7 @@
<div class="account-actions"> <div class="account-actions">
<button type="button" class="account-toggle-btn" id="openCreateAccountBtn"> Создать аккаунт</button> <button type="button" class="account-toggle-btn" id="openCreateAccountBtn"> Создать аккаунт</button>
<button type="button" class="account-toggle-btn" id="openAddUpdateBtn">📝 Добавить обновление</button>
</div> </div>
{% if account_output %} {% if account_output %}
@@ -339,6 +415,21 @@
<pre class="log-output">{{ parser_output }}</pre> <pre class="log-output">{{ parser_output }}</pre>
</div> </div>
{% endif %} {% endif %}
{% if update_output %}
<div class="log-block {% if update_success %}success{% else %}error{% endif %}">
<div class="log-title">Добавление обновления</div>
<div class="log-status">
Статус:
{% if update_success %}
успешно
{% else %}
ошибка
{% endif %}
</div>
<pre class="log-output">{{ update_output }}</pre>
</div>
{% endif %}
</div> </div>
</div> </div>
@@ -376,6 +467,78 @@
</div> </div>
</div> </div>
<div id="updateModal" class="update-modal" aria-hidden="true">
<div class="update-modal-card">
<div class="update-modal-title">Добавить обновление</div>
<div class="update-modal-subtitle">
Заполните версию, дату, действия для оператора и пункты изменений. При необходимости добавьте путь к картинке. После сохранения новая версия появится сверху на странице /info.
</div>
<form method="post" action="/admin/db/add-update" id="addUpdateForm">
<div class="form-grid">
<div class="update-form-grid">
<div>
<label class="field-label" for="updateVersion">Версия</label>
<input class="field-input" id="updateVersion" type="text" name="version" placeholder="1.4" required>
</div>
<div>
<label class="field-label" for="updateDate">Дата</label>
<input class="field-input" id="updateDate" type="date" name="date" required>
</div>
</div>
<div>
<label class="field-label" for="operatorActions">Что сделать оператору</label>
<textarea class="field-textarea" id="operatorActions" name="operator_actions" placeholder="Каждое действие с новой строки">Скачать новый проект vMix перед работой с матчем.
Полностью заменить все файлы проекта.</textarea>
<div class="helper-text">Каждая строка станет отдельным пунктом списка.</div>
</div>
<div>
<label class="field-label">Пункты обновления</label>
<div class="update-items-editor" id="updateItemsEditor">
<div class="update-item-form">
<div>
<label class="field-label">Тип</label>
<select class="field-select" name="item_badge">
<option value="new">Новое</option>
<option value="fix">Исправлено</option>
<option value="improve">Улучшено</option>
<option value="important">Важно</option>
</select>
</div>
<div>
<label class="field-label">Заголовок</label>
<input class="field-input" type="text" name="item_title" placeholder="Например: Верхний счёт" required>
</div>
<div class="update-item-text">
<label class="field-label">Описание</label>
<textarea class="field-textarea" name="item_text" placeholder="Опишите изменение. Каждая строка станет отдельным абзацем." required></textarea>
</div>
<div class="update-item-image">
<label class="field-label">Картинка / скриншот</label>
<input class="field-input" type="text" name="item_image" placeholder="Например: /static/docs/no photo.png или просто no photo.png">
<div class="helper-text">Картинку нужно положить в static/docs. Если указать только имя файла, система сама подставит /static/docs/.</div>
</div>
</div>
</div>
<button type="button" class="add-row-btn" id="addUpdateItemBtn"> Добавить ещё пункт</button>
</div>
</div>
<div class="modal-actions">
<button type="button" class="cancel-btn" id="closeAddUpdateBtn">Отмена</button>
<button type="submit" class="submit-btn">Сохранить обновление</button>
</div>
</form>
</div>
</div>
<div id="matrixLoader" class="matrix-loader" aria-hidden="true"> <div id="matrixLoader" class="matrix-loader" aria-hidden="true">
<canvas id="matrixCanvas" class="matrix-canvas"></canvas> <canvas id="matrixCanvas" class="matrix-canvas"></canvas>
<div class="matrix-content"> <div class="matrix-content">
@@ -394,6 +557,12 @@
const openCreateAccountBtn = document.getElementById("openCreateAccountBtn"); const openCreateAccountBtn = document.getElementById("openCreateAccountBtn");
const closeCreateAccountBtn = document.getElementById("closeCreateAccountBtn"); const closeCreateAccountBtn = document.getElementById("closeCreateAccountBtn");
const accountModal = document.getElementById("accountModal"); const accountModal = document.getElementById("accountModal");
const openAddUpdateBtn = document.getElementById("openAddUpdateBtn");
const closeAddUpdateBtn = document.getElementById("closeAddUpdateBtn");
const updateModal = document.getElementById("updateModal");
const updateDate = document.getElementById("updateDate");
const addUpdateItemBtn = document.getElementById("addUpdateItemBtn");
const updateItemsEditor = document.getElementById("updateItemsEditor");
let drops = []; let drops = [];
let fontSize = 18; let fontSize = 18;
let columns = 0; let columns = 0;
@@ -463,6 +632,37 @@
accountModal.setAttribute("aria-hidden", "true"); accountModal.setAttribute("aria-hidden", "true");
} }
function openUpdateModal() {
if (!updateModal) return;
if (updateDate && !updateDate.value) {
updateDate.value = new Date().toISOString().slice(0, 10);
}
updateModal.classList.add("active");
updateModal.setAttribute("aria-hidden", "false");
}
function closeUpdateModal() {
if (!updateModal) return;
updateModal.classList.remove("active");
updateModal.setAttribute("aria-hidden", "true");
}
function addUpdateItem() {
if (!updateItemsEditor) return;
const firstItem = updateItemsEditor.querySelector(".update-item-form");
if (!firstItem) return;
const clone = firstItem.cloneNode(true);
clone.querySelectorAll("input, textarea").forEach((field) => {
field.value = "";
});
clone.querySelectorAll("select").forEach((field) => {
field.selectedIndex = 0;
});
updateItemsEditor.appendChild(clone);
}
parserForms.forEach((form) => { parserForms.forEach((form) => {
form.addEventListener("submit", () => { form.addEventListener("submit", () => {
const parserTitle = form.dataset.parserTitle || "Запуск парсера"; const parserTitle = form.dataset.parserTitle || "Запуск парсера";
@@ -492,12 +692,38 @@
}); });
} }
if (openAddUpdateBtn) {
openAddUpdateBtn.addEventListener("click", openUpdateModal);
}
if (closeAddUpdateBtn) {
closeAddUpdateBtn.addEventListener("click", closeUpdateModal);
}
if (updateModal) {
updateModal.addEventListener("click", (event) => {
if (event.target === updateModal) {
closeUpdateModal();
}
});
}
if (addUpdateItemBtn) {
addUpdateItemBtn.addEventListener("click", addUpdateItem);
}
document.addEventListener("keydown", (event) => { document.addEventListener("keydown", (event) => {
if (event.key === "Escape") { if (event.key === "Escape") {
closeAccountModal(); closeAccountModal();
closeUpdateModal();
} }
}); });
const queryParams = new URLSearchParams(window.location.search);
if (queryParams.get("open_update") === "1") {
openUpdateModal();
}
resizeCanvas(); resizeCanvas();
window.addEventListener("resize", resizeCanvas); window.addEventListener("resize", resizeCanvas);
</script> </script>

File diff suppressed because it is too large Load Diff