184 build - поправлен mapping для других аккаунтов, 2 идентификатора удалений, и пустые ворота должны работать

This commit is contained in:
2026-10-02 15:00:10 +03:00
parent 6f6c5dc153
commit 0f46e42077
6 changed files with 448 additions and 39 deletions

120
README_BUILD184.txt Normal file
View File

@@ -0,0 +1,120 @@
BUILD184 — 2026.10.02.5
Обновление плашек верхнего счёта, Value/SelectedName, SQL-признаки удаления и сессия Mapping
Установка поверх BUILD183:
1. Остановите сервер, сохраните копии пяти заменяемых файлов.
2. Распакуйте архив в корень проекта с app.py, сохранив папки и заменив файлы.
3. Запустите сервер, обновите страницу Ctrl+F5.
В архиве только пять изменённых файлов программы и эта инструкция.
Локальные конфиги, SQL-источники, связи Mapping и база данных не заменяются.
Изменений схемы БД и новых зависимостей нет. Новые системные переменные
регистрируются автоматически при запуске механизма Mapping.
Верхний счёт / Отложенный штраф / Пустые ворота:
- Условные шаги OverlayInput1–8In (и старые OverlayInput1–8) в включённом
сценарии, отмеченном как верхний счёт, теперь проверяются при изменении
флагов HOME/AWAY/ANY: empty_net и delayed_penalty.
- При появлении условия обновляются связанные данные титра и выдаётся
настроенный Input. При исчезновении условия плашка снимается со своего слоя.
Весь сценарий, основной счёт, задержки и команды таймеров повторно не запускаются.
- Снятие проверяет Input, который находится на слое: посторонний титр,
заменивший плашку, не снимается. Основной Input защищён от снятия флагом.
- При смене HOME/AWAY на одном слое сначала снимается старая плашка, затем
обновляется и выдаётся новая. Если несколько активных шагов адресуют один
слой, приоритет у последнего шага сценария, как при его обычном исполнении.
- Плашки восстанавливаются после получения Agent tally. Одна вспомогательная
плашка не удерживает основной счёт в состоянии «в эфире», если счёт снят.
- Изменения выполняются в общей очереди титров. Во время ожидания SQL
повторно проверяются флаги, основной счёт, матч, Agent, сессия и права.
Устаревшая выдача отменяется. Зрители команды не отправляют.
Пример шага с картинки:
Function: OverlayInput3In
Условие: HOME — пустые ворота включены
Input: EMPTY NET HOME - GT
SelectedName: Text_Away.Text
Value: EMPTY NET
Если у команды включены пустые ворота и верхний счёт в эфире, теперь
отправляется SetText в Text_Away.Text, затем OverlayInput3In.
При выключении пустых ворот отправляется OverlayInput3Out, если на слое
остаётся этот Input. Снимать и заново выдавать основной счёт не требуется.
Value/SelectedName:
- В шаге vMix с PreviewInput, ActiveInput или OverlayInput1–8[/In], если
заданы SelectedName и Value, поле заполняется отдельной командой перед
выдачей/Preview. Тип поля из актуальной структуры выбранного Agent определяет
SetText, SetImage или SetColor, в том числе при первом вызове.
- SQL/Mapping читается один раз для Input перед заполнением поля.
Явный Value из шага применяется после Mapping.
- Поддерживаются числовой Value=0, шаблоны, альтернативный Input и поле
при выданном счёте. Пустой результат заданного шаблона очищает поле.
Незаданный Value не создаёт лишнюю команду очистки.
- Прямые SetText и нативные команды Countdown не дублируются.
Рабочий механизм основного времени и удалений сохранён.
Применение конфига Mapping на другом аккаунте/компьютере:
- Передаются текущие матч, матчевая сессия и выбранный Agent этого браузера.
- Сервер использует именно эту сессию. Последняя сессия аккаунта из другой
вкладки, в том числе пустой канал без матча, больше не подменяет выбранный матч.
- Проверяются принадлежность активной сессии и Agent аккаунту и совпадение
выбранного матча. Устаревший или чужой токен не подменяется другой сессией.
- Для клиента без токена допускается только действующее назначение именно
выбранного Agent. При несовпадении матча выполнение останавливается.
- Сначала назначается правильный матч без отправки старого Mapping, затем
применяется выбранный конфиг. Защита сессии/Agent от соседнего браузера сохранена.
Новые SQL-параметры:
:home_has_penalty
:away_has_penalty
Значение каждого — строка true или false для всей команды, независимо от
выбранной карточки. true, если есть хотя бы одно назначенное незавершённое
удаление с остатком времени. Учитываются удаления до запуска и на паузе,
командные, дисциплинарные 10/20 и обоюдные удаления. Черновики без необходимых
данных, история, законченные и нулевые удаления не учитываются.
После удаления/завершения последней карточки команды значение false.
Если матч не определён — false. Значения берутся из сохранённого состояния
матча; вручную подменить их через Mapping нельзя.
Готовый запрос, возвращающий настоящие boolean поля PostgreSQL:
SELECT
CAST(:home_has_penalty AS boolean) AS "home_has_penalty",
CAST(:away_has_penalty AS boolean) AS "away_has_penalty";
Пример использования в условии:
CASE
WHEN CAST(:home_has_penalty AS boolean) THEN 'HOME PENALTY'
ELSE ''
END AS "home_penalty_caption"
Параметры также видны в «Переменные» / «Система · Удаления» и напрямую
доступны в Mapping как context.home_has_penalty и context.away_has_penalty.
Проверки:
- 22 новые backend-проверки применения конфига: точная сессия, более новый
пустой/другой канал, другой аккаунт со своим Agent, чужие и закрытые токены,
несовпадение матча, изменение назначения при ожидании, защита другого браузера.
- 7 прежних проверок маршрутизации нескольких Agent, копирования конфигов
и защиты сессии/Agent другого браузера прошли.
- Браузерная проверка применения Mapping по реальным кнопкам интерфейса:
текущие матч/токен/Agent, другой аккаунт/компьютер, старый канал настроек,
неверный Agent в сохранённых настройках и понятные сообщения ошибок.
Прежние браузерные проверки Mapping BUILD170/175/183 также прошли.
- 82 локальные проверки backend, включая 26 новых вариантов признаков
удаления, прошлые SQL/Mapping, контекст игрока, команды и Preview.
- 29 подходящих статических проверок интерфейса прошли.
- Браузерные проверки: условия плашек и подписи; HOME/AWAY; защита слоя;
восстановление по tally; все восемь Overlay; быстрая смена флагов и смена
матча/Agent/сессии/прав при ожидании SQL; реальная кнопка нижней панели;
тексты/картинки/цвета; один запрос Mapping; удаления последней карточки;
прежние кнопки и триггеры Preview; общая ссылка «Свои плюсы».
- Синтаксис Python и JavaScript проверен.
В старых статических проверках остаются 9 устаревших ожиданий предыдущих
механизмов timer-fast/PauseCountdown и четырёх Overlay; те же проверки
не проходят и на версии до этой правки. Ради них рабочий Countdown не менялся.
Реальный PostgreSQL и ваш vMix не использовались: проверки выполнялись
изолированно, с имитацией команд и состояния Agent.

2
app.py
View File

@@ -35,7 +35,7 @@ from khl_site.khl_data_center import APP as khl_site_app, configure_storage, syn
from hockey_data.khl_career import KhlCareerService
BASE_DIR = Path(__file__).resolve().parent
BUILD_VERSION = "2026.10.02.4"
BUILD_VERSION = "2026.10.02.5"
# compatibility: BUILD_VERSION = "2026.09.24.2"
# compatibility: BUILD_VERSION = "2026.09.23.8"
# compatibility: BUILD_VERSION = "2026.09.23.7"

View File

@@ -4112,10 +4112,12 @@ class VmixAgentHub:
return runtime, report
@refresh_plan_changed
async def use_mapping_profile_for_user(self, profile_id: int, payload: Any, user: HockeyUser) -> dict[str, Any]:
async def use_mapping_profile_for_user(self, profile_id: int, payload: Any, user: HockeyUser,
*, request: Request | None = None) -> dict[str, Any]:
"""Use any saved Mapping config on the Agent selected for the user's current match."""
requested = str(getattr(payload, "device_id", "") or "").strip()
session_token = str(getattr(payload, "session_token", "") or "").strip()
expected_game_id = str(getattr(payload, "game_id", "") or "").strip()
def validate_profile_target(requested=requested):
with self.database.session() as session:
@@ -4130,12 +4132,12 @@ class VmixAgentHub:
OperatorSession.wfl_user_id == user.id,
OperatorSession.status == "active",
)))
if operator is None:
operator = session.scalar(
select(OperatorSession)
.where(and_(OperatorSession.wfl_user_id == user.id, OperatorSession.status == "active"))
.order_by(desc(OperatorSession.id))
)
if operator is None:
raise HTTPException(status_code=404, detail="Матчевая сессия этого браузера не найдена или закрыта. Откройте матч заново.")
if not str(operator.game_external_id or "").strip():
raise HTTPException(status_code=409, detail="В сессии этого браузера не выбран матч. Откройте матч заново.")
if expected_game_id and str(operator.game_external_id) != expected_game_id:
raise HTTPException(status_code=409, detail="Матч в сессии изменился. Обновите страницу и примените Mapping заново.")
if not requested and operator is not None:
requested = str(operator.vmix_device_uuid or "").strip()
@@ -4162,13 +4164,44 @@ class VmixAgentHub:
raise HTTPException(status_code=409, detail="Ваш Agent ещё не передал структуру vMix")
if not bool(device.vmix_connected):
raise HTTPException(status_code=409, detail="На вашем Agent сейчас не подключён vMix")
return requested
requested = await run_db(validate_profile_target)
if operator is not None:
game_id = str(operator.game_external_id)
tournament_id = str(operator.tournament_external_id or "")
operator_token = session_token
else:
# A selected Agent can already be correctly assigned even
# when this browser has not created its personal channel.
# Never pick another tab's latest account-wide session.
current = session.scalar(select(VmixAssignment).where(and_(
VmixAssignment.device_id == device.id,
VmixAssignment.assignment_key == device.current_assignment_key,
VmixAssignment.wfl_user_id == user.id,
VmixAssignment.active.is_(True))))
if current is None or not device.current_match_external_id or current.game_external_id != device.current_match_external_id:
raise HTTPException(status_code=409, detail="Выбранный Agent не назначен на матч. Откройте матч и выберите этот Agent.")
game_id = str(current.game_external_id)
tournament_id = str(current.tournament_external_id or "")
operator_token = str(current.operator_session_token or "")
if expected_game_id and game_id != expected_game_id:
raise HTTPException(status_code=409, detail="Выбранный Agent назначен на другой матч. Выберите Agent для текущего матча.")
return requested, game_id, tournament_id, operator_token
requested, game_id, tournament_id, operator_token = await run_db(validate_profile_target)
# Guard the concrete resolved target as well as explicit route values;
# a single-Agent fallback must not steal another browser's on-air Agent.
if request is not None:
access = MatchAccess(self.database)
await run_db(access.protect_device, request, user, requested)
if operator_token:
await run_db(access.protect_session, request, user, operator_token)
# Make sure this concrete Agent is attached to the current match before sending values.
assignment = await self.assign_current_match(user, device_id=requested)
if assignment is None:
raise HTTPException(status_code=409, detail="Сначала откройте матч в основном интерфейсе")
if session_token:
assignment = await self.assign_match(wfl_user_id=user.id, game_external_id=game_id,
tournament_external_id=tournament_id, device_id=requested,
operator_session_token=operator_token, wait_for_mapping=False, update_operator_binding=False)
if assignment is None:
raise HTTPException(status_code=409, detail="Не удалось назначить матч выбранному Agent. Обновите страницу и повторите применение Mapping.")
def persist_profile_binding():
with self.database.session() as session:
@@ -4176,6 +4209,23 @@ class VmixAgentHub:
device = session.scalar(select(VmixDevice).where(VmixDevice.device_uuid == requested))
if source is None or device is None:
raise HTTPException(status_code=404, detail="Mapping или Agent больше недоступен")
current = session.scalar(select(VmixAssignment).where(and_(
VmixAssignment.device_id == device.id,
VmixAssignment.assignment_key == device.current_assignment_key,
VmixAssignment.wfl_user_id == user.id,
VmixAssignment.active.is_(True))))
if (device.wfl_user_id != user.id or not device.is_active_for_account
or current is None or device.current_match_external_id != game_id
or current.game_external_id != game_id
or str(current.operator_session_token or "") != operator_token):
raise HTTPException(status_code=409, detail="Agent или его назначение изменились. Обновите страницу и примените Mapping заново.")
if session_token:
operator = session.scalar(select(OperatorSession).where(and_(
OperatorSession.session_token == session_token,
OperatorSession.wfl_user_id == user.id,
OperatorSession.status == "active")))
if operator is None or str(operator.game_external_id or "") != game_id:
raise HTTPException(status_code=409, detail="Матчевая сессия изменилась. Обновите страницу и примените Mapping заново.")
source_payload = self._mapping_profile_payload(session, source, include_inventory=False, include_fields=True)
source_fields = list(source_payload.get("fields") or [])
target_fingerprint = str(device.project_fingerprint or "")
@@ -4994,6 +5044,7 @@ class MappingInputRenamePayload(BaseModel):
class MappingProfileUsePayload(BaseModel):
device_id: str = Field(default="", max_length=128)
session_token: str = Field(default="", max_length=128)
game_id: str = Field(default="", max_length=64)
class MappingProfileCopyPayload(BaseModel):
@@ -5443,8 +5494,9 @@ def create_hockey_agent_router(
return await hub.create_mapping_profile(payload, user)
@router.post("/api/hockey/admin/vmix-mapping/profiles/{profile_id}/use", dependencies=admin)
async def mapping_profile_use(profile_id: int, payload: MappingProfileUsePayload, user: HockeyUser = Depends(auth_dependency)) -> dict[str, Any]:
return await hub.use_mapping_profile_for_user(profile_id, payload, user)
async def mapping_profile_use(profile_id: int, payload: MappingProfileUsePayload, request: Request,
user: HockeyUser = Depends(auth_dependency)) -> dict[str, Any]:
return await hub.use_mapping_profile_for_user(profile_id, payload, user, request=request)
@router.post("/api/hockey/admin/vmix-mapping/profiles/{profile_id}/duplicate", dependencies=admin)
async def mapping_profile_duplicate(profile_id: int, user: HockeyUser = Depends(auth_dependency)) -> dict[str, Any]:

View File

@@ -68,6 +68,10 @@ PLAYER_PANEL_BUTTON_FIELDS = {
"_preview_input": TITLE_BUTTON_FIELDS["input"],
}
# Presence flags belong to the saved match dashboard, never to an operator's
# selected card or an editable Mapping variable.
TEAM_PENALTY_PRESENCE_KEYS = ("home_has_penalty", "away_has_penalty")
DEFAULT_CONTEXT_VARIABLES: tuple[dict[str, Any], ...] = (
*({"key": f"title_button_{key}", "label": label, "category": "Титры · Нажатая кнопка",
@@ -78,6 +82,11 @@ DEFAULT_CONTEXT_VARIABLES: tuple[dict[str, Any], ...] = (
{"key": "tournament_id", "label": "Текущий турнир", "category": "Система", "entity_type": "tournament", "scope": "match", "source_type": "system"},
{"key": "team1_id", "label": "Команда 1 / хозяева", "category": "Система", "entity_type": "team", "scope": "match", "source_type": "system"},
{"key": "team2_id", "label": "Команда 2 / гости", "category": "Система", "entity_type": "team", "scope": "match", "source_type": "system"},
*({"key": key, "label": f"{side} — есть удаление (true/false)",
"category": "Система · Удаления", "entity_type": "penalty", "scope": "match_shared",
"source_type": "system", "value_type": "text", "default_value": "false",
"description": "true, если у команды есть назначенное незавершённое удаление с оставшимся временем. Учитываются пауза, командные и дисциплинарные удаления; выбранная карточка не влияет."}
for key, side in zip(TEAM_PENALTY_PRESENCE_KEYS, ("HOME", "AWAY"))),
{"key": "account_id", "label": "Аккаунт оператора", "category": "Система", "entity_type": "account", "scope": "account", "source_type": "system"},
{"key": "device_id", "label": "Активный Agent", "category": "Система", "entity_type": "device", "scope": "session", "source_type": "system"},
{"key": "assignment_id", "label": "Текущее назначение Agent", "category": "Система", "entity_type": "assignment", "scope": "session", "source_type": "system"},
@@ -335,6 +344,17 @@ class MappingDataService:
session.execute(text("SELECT pg_advisory_xact_lock(hashtext('hockey_mapping_defaults'))"))
existing_var_rows = {row.key: row for row in session.scalars(select(MappingContextVariable))}
existing_vars = set(existing_var_rows)
# Reserve the new runtime contract even if an older configuration
# already contains a manually created variable with this key.
for key in TEAM_PENALTY_PRESENCE_KEYS:
row = existing_var_rows.get(key)
if row is not None:
row.source_type = "system"
row.scope = "match_shared"
row.value_type = "text"
row.entity_type = "penalty"
row.default_value = "false"
row.is_system = True
# Build78 initially stored automatic HOME/AWAY penalty identifiers as
# account-scoped match values. Migrate existing databases in-place so
# an operator can set a penalty and an admin can immediately see it in Mapping.
@@ -702,6 +722,7 @@ class MappingDataService:
if key in supplied:
context[key] = str(supplied[key]) if supplied[key] is not None else ""
context["account_id"] = str(user.id)
context.update({key: "false" for key in TEAM_PENALTY_PRESENCE_KEYS})
context.setdefault("ui_language", self._current_language(supplied))
context.update({f"title_button_{key}": "" for key in TITLE_BUTTON_FIELDS})
if not context.get("device_id"):
@@ -761,6 +782,25 @@ class MappingDataService:
except Exception:
stadium_local = None
control = session.scalar(select(GameControlState).where(GameControlState.game_external_id == resolved_game_id))
if game is not None and control is not None:
timer_state = HockeyDataService._timer_state_from_row(control)
board = timer_state["penalty_board"]
# The service counter validates side/infraction/preset/time. In
# addition, a personal draft needs its player, while a complete
# team penalty is valid without one (including legacy spelling).
participant_ready = []
for penalty in board["penalties"]:
player = penalty.get("player")
infraction = penalty.get("infraction")
team_penalty = bool(penalty.get("teamPenalty") or penalty.get("team_penalty")
or (isinstance(infraction, dict) and (infraction.get("teamPenalty") or infraction.get("team_penalty"))))
if team_penalty or (isinstance(player, dict) and bool(player)):
participant_ready.append(penalty)
home_count, away_count = HockeyDataService._active_penalty_counts({
**timer_state, "penalty_board": {**board, "penalties": participant_ready},
})
context["home_has_penalty"] = "true" if home_count else "false"
context["away_has_penalty"] = "true" if away_count else "false"
if game is not None:
score_control = HockeyDataService._score_control_payload(game, control)
context.setdefault("score_home", str(score_control["home"]))
@@ -816,6 +856,8 @@ class MappingDataService:
sql_key = re.sub(r"[^A-Za-z0-9_]+", "_", raw_key_text).strip("_")[:120]
if not sql_key or not re.match(r"^[A-Za-z]", sql_key):
sql_key = f"panel_{sql_key}"[:120]
if sql_key in TEAM_PENALTY_PRESENCE_KEYS:
continue
context.setdefault(sql_key, str(raw_value))
if player_match:
panel_id, field_key = player_match.groups()

View File

@@ -182,7 +182,10 @@
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(data.detail || `Ошибка запроса: ${response.status}`);
const detail = data.detail;
const message = typeof detail === "string" ? detail
: detail?.message || detail?.code || (detail ? JSON.stringify(detail) : `Ошибка запроса: ${response.status}`);
throw new Error(message);
}
return data;
}
@@ -250,10 +253,10 @@
|| ""
),
token: String(
operatorSession?.channel_key
|| operatorSession?.token
|| state.vmixChannel?.channel_key
operatorSession?.token
|| operatorSession?.channel_key
|| state.vmixChannel?.token
|| state.vmixChannel?.channel_key
|| runtimeStorage.getItem("hockey.operatorSessionToken")
|| ""
),
@@ -1560,6 +1563,26 @@
return context;
}
function mappingProfileUseTarget() {
const runtime = window.UIBuilderRuntime?.getData?.()?.hockey || {};
const gameId = String(runtime.selected_game?.external_id || runtime.selected_game?.id || "").trim();
const operatorSession = runtime.operator_session || runtime.session || {};
const sessionGameId = String(operatorSession.game_external_id || operatorSession.game_id || "").trim();
let sessionToken = gameId && (!sessionGameId || sessionGameId === gameId)
? String(operatorSession.token || operatorSession.channel_key || "").trim()
: "";
// A settings channel may belong to a different tab, account or match.
// Use only this workspace's session, or its matching tab-scoped fallback.
if (!sessionToken && gameId && String(runtimeStorage.getItem("hockey.selectedGameId") || "").trim() === gameId) {
sessionToken = String(runtimeStorage.getItem("hockey.operatorSessionToken") || "").trim();
}
return {
game_id: gameId,
device_id: String(window.HockeyAgentRuntime?.currentDeviceId?.() || runtimeStorage.getItem("hockey.vmix.selected_device") || "").trim(),
session_token: sessionToken,
};
}
let mappingCatalogRequestRevision = 0;
async function loadMappingCatalog() {
const revision = ++mappingCatalogRequestRevision;
@@ -3330,14 +3353,13 @@
const profileId = Number(button.dataset.mapUseProfile || 0);
if (!profileId) return;
const selected = (state.mappingProfiles?.profiles || []).find((item) => Number(item.id) === profileId);
const deviceId = String(runtimeStorage.getItem("hockey.vmix.selected_device") || "").trim();
const sessionToken = String(selectedContext().token || "").trim();
const target = mappingProfileUseTarget();
button.disabled = true;
button.textContent = "Применяю…";
try {
const result = await request(`/api/hockey/admin/vmix-mapping/profiles/${profileId}/use`, {
method: "POST",
body: JSON.stringify({ device_id: deviceId, session_token: sessionToken }),
body: JSON.stringify(target),
});
await loadMapping(profileId);
const applied = result.applied || {};

View File

@@ -126,6 +126,7 @@
vmixTabMappingRefreshPending: false,
vmixTabMappingRefreshQueued: "",
hockeyTeamStateOverlayActive: new Map(),
hockeyScoreboardConditionalTargets: new Map(),
shortcutSequenceOverlayState: new Map(),
quickPanelActiveTab: "",
vmixOverlayRuntime: new Map(),
@@ -4578,7 +4579,7 @@ function startCustomTooltips() {
const addTarget = (layer, input) => {
const normalizedLayer = String(layer || "").trim();
const normalizedInput = String(input || "").trim();
if (!/[1-4]/.test(normalizedLayer) || !normalizedInput) return;
if (!/^[1-8]$/.test(normalizedLayer) || !normalizedInput) return;
if (targets.some((item) => item.layer === normalizedLayer && normalizeRuntimeVmixInputRef(item.input) === normalizeRuntimeVmixInputRef(normalizedInput))) return;
targets.push({ layer: normalizedLayer, input: normalizedInput });
};
@@ -4656,6 +4657,7 @@ function startCustomTooltips() {
const id = String(sequenceId || "");
if (!id) return false;
const sequence = shortcutSequenceById(id);
if (sequence?.is_scoreboard_sequence) return hockeyScoreboardSequenceIsLive(sequence);
// When Agent tally is available, the vMix XML API is the source of truth. Do
// not let optimistic click/ACK history keep a stale button illuminated.
if (state.vmixOverlayTallyAuthoritative) return sequenceMatchesRuntimeOverlay(sequence);
@@ -4738,6 +4740,9 @@ function startCustomTooltips() {
rebalanceVmixPenaltyTargets({ scoreboardActive: true, forceOverlay: true })
.catch((error) => console.error("Penalty display after scoreboard tally error", error));
}
if (scoreboardWasLive !== scoreboardLive && hockeyCanControl()) {
hockeySyncScoreboardConditionalSteps().catch((error) => console.error("Team-state display after scoreboard tally error", error));
}
}
function hockeySettingsDataRefreshPaused() {
@@ -4862,6 +4867,8 @@ function startCustomTooltips() {
const rawCommands = typeof commands === "function" ? commands() : commands;
const clean = (rawCommands || []).map(compactVmixCommand).filter((command) => command.Function);
if (!clean.length) return { ok: true, applied: 0, results: [] };
const stillCurrent = () => !execution?.isCurrent || execution.isCurrent();
if (!stillCurrent()) return { ok: true, skipped: true, applied: 0, results: [] };
// A click must resolve SQL even when the source's periodic refresh is off.
// Refresh before the first title command, so explicit SetText steps can
// still override Mapping. Preview + Overlay in one run reuse this read.
@@ -4894,8 +4901,10 @@ function startCustomTooltips() {
if (!hockeyCanControl() || gameId !== hockeyTimerSelectedGameId() || deviceId !== currentRuntimeVmixDeviceId()) {
throw new Error("Выбранный матч, Agent или права управления изменились");
}
if (!stillCurrent()) return { ok: true, skipped: true, applied: 0, results: [] };
}
}
if (!stillCurrent()) return { ok: true, skipped: true, applied: 0, results: [] };
state.vmixCommandQueueDepth += 1;
const controller = new AbortController();
// BUILD100: runtime vMix delivery is ACKed command-by-command on the server.
@@ -5676,6 +5685,52 @@ function startCustomTooltips() {
return actions.length;
}
function shortcutVmixStepCommands(step, context, { scoreboardActive = null } = {}) {
const live = scoreboardActive === null ? hockeyScoreboardIsLive() : Boolean(scoreboardActive);
const useAlternate = Boolean(step.use_scoreboard_alternate && live && step.scoreboard_alternate_input);
const command = {
Function: templateSequenceValue(step.function, context),
Input: templateSequenceValue(useAlternate ? step.scoreboard_alternate_input : step.input, context),
Value: templateSequenceValue(step.value, context),
SelectedName: templateSequenceValue(useAlternate && step.scoreboard_alternate_selected_name
? step.scoreboard_alternate_selected_name : step.selected_name, context),
Duration: templateSequenceValue(step.duration, context),
Mix: templateSequenceValue(step.mix, context),
};
if (!command.Function) throw new Error("В шаге vMix не указана Function");
const configuredValue = step.value !== null && step.value !== undefined && String(step.value) !== "";
if (!/^(PreviewInput|ActiveInput|OverlayInput[1-8](In)?)$/i.test(command.Function)
|| !command.Input || !command.SelectedName || !configuredValue) return [command];
const field = (vmixInputByRef(command.Input)?.fields || []).find((item) => String(item.name || "") === String(command.SelectedName));
const kind = String(field?.type || field?.field_type || "").toLowerCase();
const setter = kind === "image" || /\.Source$/i.test(command.SelectedName) ? "SetImage"
: ["color", "colour"].includes(kind) || /\.Color$/i.test(command.SelectedName) ? "SetColor" : "SetText";
// Overlay/Preview functions do not write fields. Mapping runs once before
// this batch; the explicit caption then overrides it before presentation.
return [{ Function: setter, Input: command.Input, SelectedName: command.SelectedName, Value: command.Value }, command];
}
function hockeyTeamStateSequenceStep(step) {
return step?.enabled !== false && step?.type === "vmix_command" && [
"home_delayed_penalty", "away_delayed_penalty", "any_delayed_penalty",
"home_empty_net", "away_empty_net", "any_empty_net",
].includes(step.condition);
}
function hockeyRememberScoreboardConditionalStep(sequence, step, commands) {
if (!sequence?.is_scoreboard_sequence || !hockeyTeamStateSequenceStep(step)) return;
const command = commands.at(-1);
const parsed = vmixOverlayLayer(command?.Function);
if (!parsed || !["In", "toggle"].includes(parsed.action) || !command.Input) return;
const input = vmixInputByRef(command.Input)?.title || String(command.Input);
const signature = JSON.stringify(commands.map((value) => compactVmixCommand({ ...value, Input: input })));
state.hockeyScoreboardConditionalTargets.set(parsed.layer, {
input, signature, sequenceId: sequence.id,
gameId: hockeyTimerSelectedGameId(), deviceId: currentRuntimeVmixDeviceId(),
sessionToken: currentRuntimeHockeySessionToken(),
});
}
async function runShortcutSequenceStep(sequence, step, execution = null) {
if (!hockeyCanControl()) return false;
const context = buildShortcutRuntimeContext(sequence);
@@ -5697,21 +5752,21 @@ function startCustomTooltips() {
return await hockeyScoreCommand(step.score_command || "home_plus", { refreshMapping: true, announce: false });
}
case "vmix_command": {
const useAlternate = Boolean(step.use_scoreboard_alternate && hockeyScoreboardIsLive() && step.scoreboard_alternate_input);
const inputTemplate = useAlternate ? step.scoreboard_alternate_input : step.input;
const selectedNameTemplate = useAlternate && step.scoreboard_alternate_selected_name
? step.scoreboard_alternate_selected_name
: step.selected_name;
const command = {
Function: templateSequenceValue(step.function, context),
Input: templateSequenceValue(inputTemplate, context),
Value: templateSequenceValue(step.value, context),
SelectedName: templateSequenceValue(selectedNameTemplate, context),
Duration: templateSequenceValue(step.duration, context),
Mix: templateSequenceValue(step.mix, context),
};
if (!command.Function) throw new Error("В шаге vMix не указана Function");
return await sendRuntimeVmixSequence([command], execution);
const scoreboardActive = hockeyScoreboardIsLive();
let commands = shortcutVmixStepCommands(step, context, { scoreboardActive });
if (commands.length > 1) {
const gameId = hockeyTimerSelectedGameId(), deviceId = currentRuntimeVmixDeviceId(), sessionToken = currentRuntimeHockeySessionToken();
const input = await hockeyRuntimeVmixInputTitle(commands.at(-1).Input);
if (!hockeyCanControl() || gameId !== hockeyTimerSelectedGameId() || deviceId !== currentRuntimeVmixDeviceId()
|| sessionToken !== currentRuntimeHockeySessionToken()) throw new Error("Выбранный матч, Agent или сессия изменились");
// Inventory may be loaded for the first time here. Choose the setter
// from this Agent's actual field type, including GT colour fields.
commands = shortcutVmixStepCommands(step, context, { scoreboardActive });
commands.forEach((command) => { command.Input = input; });
}
const result = await sendRuntimeVmixSequence(commands, execution);
if (result && result.ok !== false && !result.skipped) hockeyRememberScoreboardConditionalStep(sequence, step, commands);
return result;
}
case "hockey_vmix_timers_start": {
const gameTimer = componentByActionId(step.game_timer_action_id || "hockey_game_timer");
@@ -5894,6 +5949,7 @@ function startCustomTooltips() {
state.shortcutSequenceOverlayState.set(sequence.id, false);
state.quickPanelOnAirSequences.delete(String(sequence.id || ""));
refreshQuickPanelOnAirClasses();
if (sequence.is_scoreboard_sequence) hockeySyncScoreboardConditionalSteps().catch((error) => console.error("Team-state cleanup error", error));
window.dispatchEvent(new CustomEvent("ui-builder:shortcut-sequence-finish", { detail: { sequence: clone(sequence), meta: { ...meta, overlay_group_action: "off" } } }));
if (meta.source === "quick-panel-button") toast(`Выполнено: ${sequence.name} · кнопка «${meta.button_label || sequence.name}»`);
else if (String(meta.source || "").startsWith("keyboard")) toast(`Шорткат выполнен: ${sequence.name}`);
@@ -5931,6 +5987,9 @@ function startCustomTooltips() {
if (sequence.is_scoreboard_sequence) {
activateConfiguredPenaltyCountdowns();
await rebalanceVmixPenaltyTargets({ scoreboardActive: true, forceOverlay: true });
// This can already be inside the title-button FIFO. Schedule the
// reconciliation after it, without awaiting a second entry into it.
hockeySyncScoreboardConditionalSteps().catch((error) => console.error("Team-state reconciliation error", error));
}
window.dispatchEvent(new CustomEvent("ui-builder:shortcut-sequence-finish", { detail: { sequence: clone(sequence), meta: { ...meta, overlay_group_action: sequence.toggle_all_overlays_on_repeat ? "on" : "" } } }));
const mappingNotice = hockeyTitleMappingNotice(execution.titleMappingWarnings);
@@ -13935,6 +13994,9 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
if (previousControl && hockeyTeamStateFlagSignature(previousControl) !== hockeyTeamStateFlagSignature(payload) && hockeyTeamStateScoreboardIsLive()) {
hockeySyncTeamStateOverlays({ force: true }).catch((error) => console.error("vMix team-state overlay sync error", error));
}
if (!previousControl || hockeyTeamStateFlagSignature(previousControl) !== hockeyTeamStateFlagSignature(payload)) {
hockeySyncScoreboardConditionalSteps().catch((error) => console.error("vMix conditional team-state sync error", error));
}
if (dispatch) {
window.dispatchEvent(new CustomEvent("hockey:game-control-updated", {
detail: {
@@ -14004,17 +14066,127 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
};
}
function hockeyScoreboardPrimaryOverlayTargets(sequence) {
const context = buildShortcutRuntimeContext(sequence);
const overlaySteps = (sequence.steps || []).filter((step) => step?.enabled !== false && step.type === "vmix_command"
&& !hockeyTeamStateSequenceStep(step) && ["In", "toggle"].includes(vmixOverlayLayer(templateSequenceValue(step.function, context))?.action));
const primarySteps = overlaySteps.some((step) => !step.condition || step.condition === "always")
? overlaySteps.filter((step) => !step.condition || step.condition === "always") : overlaySteps;
return primarySteps.flatMap((step) => {
const layer = vmixOverlayLayer(templateSequenceValue(step.function, context)).layer;
return [step.input, ...(step.use_scoreboard_alternate ? [step.scoreboard_alternate_input] : [])]
.map((value) => String(templateSequenceValue(value, context) || "")).filter(Boolean)
.map((input) => ({ layer, input: vmixInputByRef(input)?.title || input }));
});
}
function hockeyScoreboardSequenceIsLive(sequence) {
const targets = hockeyScoreboardPrimaryOverlayTargets(sequence);
if (!targets.length) {
if (state.vmixOverlayTallyAuthoritative) return sequenceMatchesRuntimeOverlay(sequence);
return sequenceStillOwnsRuntimeOverlay(sequence.id) || sequenceMatchesRuntimeOverlay(sequence)
|| state.quickPanelServerOnAirSequences.has(sequence.id) || state.quickPanelOnAirSequences.has(sequence.id)
|| Boolean(state.shortcutSequenceOverlayState.get(sequence.id));
}
if (targets.some((target) => runtimeOverlayMatchesInput(state.vmixOverlayRuntime.get(target.layer), target.input))) return true;
// An auxiliary EN/DP plate cannot keep the main scorebug 'on air'.
if (state.vmixOverlayTallyAuthoritative || sequenceStillOwnsRuntimeOverlay(sequence.id)
|| targets.some((target) => state.vmixOverlayRuntime.has(target.layer))) return false;
return state.quickPanelServerOnAirSequences.has(sequence.id) || state.quickPanelOnAirSequences.has(sequence.id)
|| Boolean(state.shortcutSequenceOverlayState.get(sequence.id));
}
function hockeyScoreboardIsLive() {
// Use the Agent tally too: the title may have been shown before a reload,
// or directly in vMix rather than through this browser's local latch.
return (state.config.shortcut_sequences || []).some((sequence) =>
sequence?.enabled !== false && sequence.is_scoreboard_sequence && shortcutSequenceIsOnAir(sequence.id));
sequence?.enabled !== false && sequence.is_scoreboard_sequence && hockeyScoreboardSequenceIsLive(sequence));
}
function hockeyTeamStateScoreboardIsLive() {
return hockeyScoreboardIsLive();
}
async function hockeySyncScoreboardConditionalSteps({ force = false } = {}) {
if (!hockeyCanControl()) return 0;
const gameId = hockeyTimerSelectedGameId(), deviceId = currentRuntimeVmixDeviceId(), sessionToken = currentRuntimeHockeySessionToken();
return hockeyQueueTitleButtonAction(async () => {
const sameContext = () => hockeyCanControl() && gameId === hockeyTimerSelectedGameId()
&& deviceId === currentRuntimeVmixDeviceId() && sessionToken === currentRuntimeHockeySessionToken();
if (!sameContext()) return 0;
const flagsSignature = hockeyTeamStateFlagSignature(getByPath(state.data, "hockey.game_control"));
const desired = new Map(), candidates = new Map();
const primaryTargets = [];
for (const sequence of state.config.shortcut_sequences || []) {
if (sequence.enabled === false || !sequence.is_scoreboard_sequence) continue;
primaryTargets.push(...hockeyScoreboardPrimaryOverlayTargets(sequence));
const live = hockeyScoreboardSequenceIsLive(sequence);
const context = buildShortcutRuntimeContext(sequence);
for (const step of sequence.steps || []) {
if (!hockeyTeamStateSequenceStep(step)) continue;
const initial = shortcutVmixStepCommands(step, context, { scoreboardActive: live }).at(-1);
const parsed = vmixOverlayLayer(initial.Function);
if (!parsed || !["In", "toggle"].includes(parsed.action) || !initial.Input) continue;
try {
const input = await hockeyRuntimeVmixInputTitle(initial.Input);
const commands = shortcutVmixStepCommands(step, context, { scoreboardActive: live });
const command = commands.at(-1);
commands.forEach((value) => { value.Input = input; });
// Live reconciliation must be idempotent even for legacy Toggle steps.
command.Function = `OverlayInput${parsed.layer}In`;
const target = { input, commands, signature: JSON.stringify(commands.map(compactVmixCommand)),
sequenceId: sequence.id, sequenceName: sequence.name, gameId, deviceId, sessionToken };
if (!candidates.has(parsed.layer)) candidates.set(parsed.layer, []);
candidates.get(parsed.layer).push(target);
if (live && sequenceConditionMatches(step.condition, context, step.condition_value)) desired.set(parsed.layer, target);
} catch (error) { console.warn("Cannot resolve team-state Input", error); }
}
}
const stillCurrent = () => sameContext() && flagsSignature === hockeyTeamStateFlagSignature(getByPath(state.data, "hockey.game_control"));
if (!stillCurrent()) return 0;
let applied = 0;
const layers = new Set([...state.hockeyScoreboardConditionalTargets.keys(), ...candidates.keys()]);
// OUT is scoped to the actual old Input on its layer, including recovery
// after a reload. Never remove a different title that replaced that plate.
for (const layer of layers) {
const previous = state.hockeyScoreboardConditionalTargets.get(layer), next = desired.get(layer);
const current = state.vmixOverlayRuntime.get(layer);
const old = [previous, ...(candidates.get(layer) || [])].find((target) => target
&& (!target.gameId || (target.gameId === gameId && target.deviceId === deviceId && target.sessionToken === sessionToken))
&& runtimeOverlayMatchesInput(current, target.input) && target.input !== next?.input
&& !primaryTargets.some((main) => main.layer === layer && runtimeOverlayMatchesInput(current, main.input)));
if (old) {
const result = await sendRuntimeVmixSequence([{ Function: `OverlayInput${layer}Out`, Input: old.input }], {
isCurrent: () => stillCurrent() && runtimeOverlayMatchesInput(state.vmixOverlayRuntime.get(layer), old.input),
});
if (result && !result.skipped) applied += 1;
}
if (!next || previous?.input !== next.input) state.hockeyScoreboardConditionalTargets.delete(layer);
}
for (const [layer, target] of desired) {
if (!stillCurrent()) break;
const previous = state.hockeyScoreboardConditionalTargets.get(layer);
if (!force && previous?.signature === target.signature && previous.gameId === gameId
&& previous.deviceId === deviceId && previous.sessionToken === sessionToken
&& runtimeOverlayMatchesInput(state.vmixOverlayRuntime.get(layer), target.input)) continue;
const isCurrent = () => {
const sequence = shortcutSequenceById(target.sequenceId);
return Boolean(stillCurrent() && sequence && sequence.enabled !== false && hockeyScoreboardSequenceIsLive(sequence));
};
if (!isCurrent()) continue;
try {
const result = await sendRuntimeVmixSequence(target.commands, { sequence_id: target.sequenceId,
sequence_name: target.sequenceName, titleMappingRefreshes: new Map(), isCurrent });
if (result && result.ok !== false && !result.skipped) {
state.hockeyScoreboardConditionalTargets.set(layer, target);
applied += target.commands.length;
}
} catch (error) { console.error("vMix team-state step failed", error); }
}
return applied;
});
}
async function hockeySyncTeamStateOverlays({ scoreboardActive = null, force = false } = {}) {
const live = scoreboardActive === null ? hockeyTeamStateScoreboardIsLive() : Boolean(scoreboardActive);
const flags = hockeyMatchFlags();
@@ -17302,6 +17474,7 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
if (!gameId) return;
hockeyLoadGameControl(gameId, { force: true, rerender: false }).then(() => {
if (hockeyTeamStateScoreboardIsLive()) hockeySyncTeamStateOverlays({ force: true }).catch(() => {});
hockeySyncScoreboardConditionalSteps({ force: true }).catch((error) => console.error("Team-state settings refresh error", error));
});
};
window.addEventListener("hockey:data-refresh-paused", (event) => {