100 lines
3.1 KiB
Python
100 lines
3.1 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
"""Bestätigte Termine als iCalendar (RFC 5545), als Datei oder Abo.
|
|
|
|
Enthalten sind nur die bestätigten Termin-Optionen der Abstimmungen eines
|
|
Formulars, ohne Angaben zu Personen.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Iterable
|
|
from datetime import UTC, date, datetime, time, timedelta
|
|
from typing import Any
|
|
from zoneinfo import ZoneInfo
|
|
|
|
from surveybox.forms import types
|
|
|
|
DEFAULT_MINUTES = 60
|
|
|
|
|
|
def _escape(text: str) -> str:
|
|
return (
|
|
text.replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,")
|
|
.replace("\r\n", "\\n").replace("\n", "\\n")
|
|
)
|
|
|
|
|
|
def _fold(line: str) -> str:
|
|
"""Zeilen über 75 Byte umbrechen, ohne UTF-8-Zeichen zu teilen."""
|
|
raw = line.encode("utf-8")
|
|
if len(raw) <= 75:
|
|
return line
|
|
parts: list[str] = []
|
|
current = b""
|
|
for char in line:
|
|
encoded = char.encode("utf-8")
|
|
limit = 75 if not parts else 74
|
|
if len(current) + len(encoded) > limit:
|
|
parts.append(current.decode("utf-8"))
|
|
current = b""
|
|
current += encoded
|
|
parts.append(current.decode("utf-8"))
|
|
return "\r\n ".join(parts)
|
|
|
|
|
|
def _utc(value: datetime) -> str:
|
|
return value.astimezone(UTC).strftime("%Y%m%dT%H%M%SZ")
|
|
|
|
|
|
def confirmed_events(questions: Iterable[Any]) -> list[tuple[Any, dict[str, Any]]]:
|
|
"""(Frage, Option) aller bestätigten Termine."""
|
|
events = []
|
|
for question in questions:
|
|
cfg = question.config
|
|
if question.type != "poll" or cfg.get("mode") != "dates":
|
|
continue
|
|
confirmed = set(cfg.get("confirmed") or [])
|
|
for option in types.options_of(question):
|
|
if option["id"] in confirmed:
|
|
events.append((question, option))
|
|
return events
|
|
|
|
|
|
def build(
|
|
*,
|
|
title: str,
|
|
url: str,
|
|
host: str,
|
|
events: Iterable[tuple[Any, dict[str, Any]]],
|
|
tz: ZoneInfo,
|
|
now: datetime | None = None,
|
|
) -> str:
|
|
stamp = _utc(now or datetime.now(UTC))
|
|
lines = [
|
|
"BEGIN:VCALENDAR",
|
|
"VERSION:2.0",
|
|
"PRODID:-//Surveybox//DE",
|
|
"CALSCALE:GREGORIAN",
|
|
f"X-WR-CALNAME:{_escape(title)}",
|
|
]
|
|
for question, option in events:
|
|
day = date.fromisoformat(str(option["date"]))
|
|
summary = title if not option.get("label") else f"{title}: {option['label']}"
|
|
lines += [
|
|
"BEGIN:VEVENT",
|
|
f"UID:{option['id']}-{question.id}@{host}",
|
|
f"DTSTAMP:{stamp}",
|
|
]
|
|
if option.get("time"):
|
|
start = datetime.combine(day, time.fromisoformat(str(option["time"])), tzinfo=tz)
|
|
end = start + timedelta(minutes=int(option.get("duration") or DEFAULT_MINUTES))
|
|
lines += [f"DTSTART:{_utc(start)}", f"DTEND:{_utc(end)}"]
|
|
else:
|
|
lines += [
|
|
f"DTSTART;VALUE=DATE:{day.strftime('%Y%m%d')}",
|
|
f"DTEND;VALUE=DATE:{(day + timedelta(days=1)).strftime('%Y%m%d')}",
|
|
]
|
|
lines += [f"SUMMARY:{_escape(summary)}", f"URL:{url}", "END:VEVENT"]
|
|
lines.append("END:VCALENDAR")
|
|
return "\r\n".join(_fold(line) for line in lines) + "\r\n"
|