from html import escape from ..agent import sanitize from ..checkmk import ServiceState from ..models import state_name from .constants import LIST_LIMIT, OUTPUT_MAX from .models import Reply SEVERITY_ORDER = {2: 0, 3: 1, 1: 2} def clean(value: object, limit: int = OUTPUT_MAX) -> str: return sanitize(value, limit, single_line=True) def plain(text: str) -> Reply: return Reply(text, escape(text)) def service_entry(item: ServiceState, with_host: bool = True) -> tuple[str, str]: name = f"{clean(item.host, 60)} / {clean(item.service, 60)}" if with_host else clean(item.service, 60) state = state_name(item.state) note = " (Downtime)" if item.in_downtime else "" output = clean(item.output) text = f"{state} {name}{note}: {output}" return text, f"{state} {escape(name)}{note}: {escape(output)}" def service_list(items: list[ServiceState], with_host: bool = True) -> tuple[list[str], list[str]]: ordered = sorted(items, key=lambda i: (SEVERITY_ORDER.get(i.state, 9), i.host, i.service)) texts, htmls = [], [] for item in ordered[:LIST_LIMIT]: text, html = service_entry(item, with_host) texts.append(text) htmls.append(html) if len(ordered) > LIST_LIMIT: more = f"... und {len(ordered) - LIST_LIMIT} weitere" texts.append(more) htmls.append(escape(more)) return texts, htmls def join(heading: str, texts: list[str], htmls: list[str]) -> Reply: return Reply("\n".join([heading, *texts]), "\n".join([f"{escape(heading)}", *htmls]))