Initial Commit: Status Testing
This commit is contained in:
1 parent
1eff675f05
commit
42dd1f2d4a
286 files changed
+64800
-369
No files matched your search
@@ -0,0 +1,15 @@
|
|||||||
|
.git
|
||||||
|
.gitea
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
**/__pycache__
|
||||||
|
**/*.pyc
|
||||||
|
**/*.mo
|
||||||
|
.pytest_cache
|
||||||
|
.mypy_cache
|
||||||
|
.ruff_cache
|
||||||
|
.venv
|
||||||
|
tests
|
||||||
|
scripts
|
||||||
|
docs
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# Surveybox – Einstellungen für den Start
|
||||||
|
# Kopieren nach .env und ausfüllen. Die .env enthält Geheimnisse:
|
||||||
|
# chmod 600 .env
|
||||||
|
|
||||||
|
# --- Docker Compose -------------------------------------------------------
|
||||||
|
# Name des Stacks; bei mehreren Instanzen auf einem Host je Instanz eindeutig.
|
||||||
|
COMPOSE_PROJECT_NAME=surveybox
|
||||||
|
# "db" startet den mitgelieferten PostgreSQL-Container.
|
||||||
|
# Leer lassen, wenn ein vorhandener Datenbankserver genutzt wird.
|
||||||
|
COMPOSE_PROFILES=db
|
||||||
|
# Adresse und Port, unter denen der Reverse Proxy die App erreicht.
|
||||||
|
# 127.0.0.1 = nur Programme direkt auf dem Host. Läuft der Proxy auf einem
|
||||||
|
# anderen Rechner ODER selbst als Container (z. B. Nginx Proxy Manager),
|
||||||
|
# hier die interne IP des Docker-Hosts eintragen.
|
||||||
|
SURVEYBOX_HTTP_BIND=127.0.0.1
|
||||||
|
SURVEYBOX_HTTP_PORT=8000
|
||||||
|
# Subnetz des Docker-Netzes dieses Stacks. Muss frei sein: keine
|
||||||
|
# Überschneidung mit LAN, VPN oder anderen Docker-Netzen. Jede Instanz
|
||||||
|
# bekommt ein eigenes. Gateway ist automatisch die erste Adresse (.1).
|
||||||
|
# Private Bereiche: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16.
|
||||||
|
SURVEYBOX_NET_SUBNET=172.30.40.0/24
|
||||||
|
|
||||||
|
# --- Instanz --------------------------------------------------------------
|
||||||
|
# Öffentliche Adresse, wie Nutzer sie aufrufen. Später nicht mehr ändern:
|
||||||
|
# Passkeys sind an diese Domain gebunden.
|
||||||
|
SURVEYBOX_PUBLIC_URL=https://foo.bar
|
||||||
|
# Mindestens 32 Zeichen. Erzeugen mit: openssl rand -hex 32
|
||||||
|
# NIE ÄNDERN, sobald Konten existieren: Daraus abgeleitet sind u. a. die
|
||||||
|
# Verschlüsselung der TOTP-Geheimnisse und die Wiederherstellungscodes.
|
||||||
|
SURVEYBOX_SECRET_KEY=
|
||||||
|
SURVEYBOX_DEFAULT_LANGUAGE=de
|
||||||
|
SURVEYBOX_TIMEZONE=Europe/Berlin
|
||||||
|
# Quellcode der Instanz (AGPL), erscheint als Link in der Fußzeile. Leer: kein Link.
|
||||||
|
#SURVEYBOX_SOURCE_URL=https://git.example.de/surveybox
|
||||||
|
|
||||||
|
# --- Datenbank ------------------------------------------------------------
|
||||||
|
# Mitgelieferter Container: Host "db", Passwort frei wählen.
|
||||||
|
# Erzeugen mit: openssl rand -base64 32
|
||||||
|
SURVEYBOX_DB_HOST=db
|
||||||
|
SURVEYBOX_DB_PORT=5432
|
||||||
|
SURVEYBOX_DB_NAME=surveybox
|
||||||
|
SURVEYBOX_DB_USER=surveybox
|
||||||
|
SURVEYBOX_DB_PASSWORD=
|
||||||
|
# Externer Server: mindestens "require", besser "verify-full" mit
|
||||||
|
# SURVEYBOX_DB_SSLROOTCERT (Pfad im Container, z. B. unter /data).
|
||||||
|
SURVEYBOX_DB_SSLMODE=prefer
|
||||||
|
#SURVEYBOX_DB_SSLROOTCERT=/data/db-ca.crt
|
||||||
|
|
||||||
|
# --- Sicherungen ----------------------------------------------------------
|
||||||
|
# Tägliche Sicherung ab dieser Stunde (Ortszeit)
|
||||||
|
SURVEYBOX_BACKUP_HOUR=3
|
||||||
|
SURVEYBOX_BACKUP_KEEP_DAILY=14
|
||||||
|
SURVEYBOX_BACKUP_KEEP_PRE_UPGRADE=10
|
||||||
|
|
||||||
|
# --- Reverse Proxy ----------------------------------------------------------
|
||||||
|
# Adresse(n), von denen der Reverse Proxy bei Surveybox ankommt. Nur von dort
|
||||||
|
# wird X-Forwarded-For geglaubt; das braucht die Begrenzung von Fehlversuchen
|
||||||
|
# je Besucher. Läuft der Proxy auf demselben Docker-Host, ist das meist das
|
||||||
|
# Gateway des Surveybox-Netzes (erste Adresse von SURVEYBOX_NET_SUBNET).
|
||||||
|
# Leer lassen, wenn kein Proxy davor steht.
|
||||||
|
SURVEYBOX_TRUSTED_PROXIES=172.30.40.1
|
||||||
|
# Seiten, die Surveybox in einem Rahmen anzeigen dürfen (z. B. die Nextcloud über
|
||||||
|
# die App "External sites"). Nur https, durch Leerzeichen getrennt, und nur unter
|
||||||
|
# derselben Domain (cloud.example.de neben umfrage.example.de). Leer: verboten.
|
||||||
|
#SURVEYBOX_FRAME_ANCESTORS=https://cloud.example.de
|
||||||
|
|
||||||
|
# --- Uploads -----------------------------------------------------------------
|
||||||
|
# Obergrenze für eine Anfrage mit Dateien (MB). Die Grenzen je Dateiart
|
||||||
|
# (Bilder, Videos, Uploads) stellt der Administrator unter Einstellungen ein,
|
||||||
|
# höchstens bis hier. Der Reverse Proxy muss so große Anfragen zulassen,
|
||||||
|
# bei nginx z. B. "client_max_body_size 250m;".
|
||||||
|
SURVEYBOX_MAX_UPLOAD_MB=250
|
||||||
|
|
||||||
|
# --- Sitzungen ---------------------------------------------------------------
|
||||||
|
# Abmeldung nach so vielen Minuten ohne Aktivität, spätestens nach so vielen Tagen
|
||||||
|
SURVEYBOX_SESSION_IDLE_MINUTES=480
|
||||||
|
SURVEYBOX_SESSION_MAX_DAYS=14
|
||||||
|
# Aufbewahrung des Protokolls (Anmeldungen, Verwaltungsaktionen)
|
||||||
|
SURVEYBOX_AUDIT_RETENTION_DAYS=365
|
||||||
|
|
||||||
|
# --- Betrieb --------------------------------------------------------------
|
||||||
|
SURVEYBOX_WEB_WORKERS=2
|
||||||
|
SURVEYBOX_LOG_LEVEL=info
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
#
|
||||||
|
# Gitea Actions (act_runner).
|
||||||
|
#
|
||||||
|
# checks: Codeprüfung, Sicherheitsprüfung der Abhängigkeiten, Tests gegen
|
||||||
|
# echtes PostgreSQL. Läuft in einem Python-Container; der
|
||||||
|
# PostgreSQL-Dienst ist dort unter dem Namen "postgres" erreichbar.
|
||||||
|
# image: Image bauen, Installation/Update/Wiederherstellung im Wegwerf-Stack.
|
||||||
|
# Braucht Zugriff auf den Docker-Daemon des Runners (act_runner reicht
|
||||||
|
# ihn standardmäßig in den Job-Container durch). Wer Zugriff auf den
|
||||||
|
# Docker-Socket hat, hat Root auf dem Host: dafür einen eigenen Runner
|
||||||
|
# auf einem Test-Host verwenden, nicht den Produktiv-Host.
|
||||||
|
# audit: wöchentlich bekannte Sicherheitslücken in den Abhängigkeiten prüfen
|
||||||
|
# (ersetzt den bei Gitea fehlenden Dependabot).
|
||||||
|
|
||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
workflow_dispatch:
|
||||||
|
schedule:
|
||||||
|
- cron: "17 5 * * 1"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
checks:
|
||||||
|
if: github.event_name != 'schedule'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: python:3.13-slim-trixie
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:18-alpine
|
||||||
|
env:
|
||||||
|
POSTGRES_DB: surveybox
|
||||||
|
POSTGRES_USER: surveybox
|
||||||
|
POSTGRES_PASSWORD: surveybox-ci
|
||||||
|
env:
|
||||||
|
SURVEYBOX_TEST_DB: "1"
|
||||||
|
SURVEYBOX_PUBLIC_URL: http://localhost
|
||||||
|
SURVEYBOX_SECRET_KEY: ci-secret-key-ci-secret-key-ci-secret-key
|
||||||
|
SURVEYBOX_DB_HOST: postgres
|
||||||
|
SURVEYBOX_DB_PASSWORD: surveybox-ci
|
||||||
|
SURVEYBOX_DB_SSLMODE: disable
|
||||||
|
SURVEYBOX_DATA_DIR: /tmp/surveybox-data
|
||||||
|
steps:
|
||||||
|
- name: Werkzeuge (git, Node für Actions, PostgreSQL-Client 18)
|
||||||
|
run: |
|
||||||
|
set -eux
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y --no-install-recommends git nodejs ca-certificates curl gnupg
|
||||||
|
install -d /usr/share/postgresql-common/pgdg
|
||||||
|
curl -fsSL -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc \
|
||||||
|
https://www.postgresql.org/media/keys/ACCC4CF8.asc
|
||||||
|
echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt trixie-pgdg main" \
|
||||||
|
> /etc/apt/sources.list.d/pgdg.list
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y --no-install-recommends postgresql-client-18
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Abhängigkeiten
|
||||||
|
run: |
|
||||||
|
pip install --require-hashes --no-deps -r requirements.lock
|
||||||
|
pip install --require-hashes --no-deps -r requirements-dev.lock
|
||||||
|
- name: Auf PostgreSQL warten
|
||||||
|
run: |
|
||||||
|
for i in $(seq 1 30); do
|
||||||
|
pg_isready -h postgres -U surveybox -d surveybox && exit 0
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
exit 1
|
||||||
|
- name: Bekannte Sicherheitslücken in Abhängigkeiten
|
||||||
|
run: pip-audit --strict --disable-pip --no-deps -r requirements.lock
|
||||||
|
- name: Ruff
|
||||||
|
run: ruff check .
|
||||||
|
- name: Mypy
|
||||||
|
run: mypy
|
||||||
|
- name: Übersetzungen kompilieren
|
||||||
|
run: pybabel compile --statistics -D messages -d surveybox/locale
|
||||||
|
- name: Modelle und Migrationen stimmen überein
|
||||||
|
run: |
|
||||||
|
python -m surveybox.cli migrate
|
||||||
|
alembic check
|
||||||
|
- name: Tests
|
||||||
|
run: pytest -q
|
||||||
|
|
||||||
|
image:
|
||||||
|
if: github.event_name != 'schedule'
|
||||||
|
needs: checks
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: docker:cli
|
||||||
|
steps:
|
||||||
|
- name: Werkzeuge
|
||||||
|
run: apk add --no-cache bash git nodejs coreutils
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Docker erreichbar?
|
||||||
|
run: docker version && docker compose version
|
||||||
|
- name: Installations- und Update-Test
|
||||||
|
env:
|
||||||
|
# Ab dem ersten Release das zuletzt veröffentlichte Image eintragen.
|
||||||
|
OLD_IMAGE: ""
|
||||||
|
UPGRADE_TEST_SUBNET: 172.30.254.0/24
|
||||||
|
run: ./scripts/upgrade-test.sh
|
||||||
|
- name: Image auf bekannte Lücken prüfen (Trivy)
|
||||||
|
env:
|
||||||
|
# Feste Version eintragen, sobald der Runner sie vorhält
|
||||||
|
TRIVY_IMAGE: aquasec/trivy:latest
|
||||||
|
run: |
|
||||||
|
docker build -q -t surveybox:scan .
|
||||||
|
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock "$TRIVY_IMAGE" \
|
||||||
|
image --exit-code 1 --severity HIGH,CRITICAL --ignore-unfixed --no-progress \
|
||||||
|
--scanners vuln surveybox:scan
|
||||||
|
|
||||||
|
audit:
|
||||||
|
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: python:3.13-slim-trixie
|
||||||
|
steps:
|
||||||
|
- name: Werkzeuge
|
||||||
|
run: apt-get update && apt-get install -y --no-install-recommends git nodejs ca-certificates
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: pip-audit
|
||||||
|
run: |
|
||||||
|
pip install --require-hashes --no-deps -r requirements-dev.lock
|
||||||
|
pip-audit --strict --disable-pip --no-deps -r requirements.lock
|
||||||
+5
-173
@@ -1,176 +1,8 @@
|
|||||||
# ---> Python
|
|
||||||
# Byte-compiled / optimized / DLL files
|
|
||||||
__pycache__/
|
|
||||||
*.py[cod]
|
|
||||||
*$py.class
|
|
||||||
|
|
||||||
# C extensions
|
|
||||||
*.so
|
|
||||||
|
|
||||||
# Distribution / packaging
|
|
||||||
.Python
|
|
||||||
build/
|
|
||||||
develop-eggs/
|
|
||||||
dist/
|
|
||||||
downloads/
|
|
||||||
eggs/
|
|
||||||
.eggs/
|
|
||||||
lib/
|
|
||||||
lib64/
|
|
||||||
parts/
|
|
||||||
sdist/
|
|
||||||
var/
|
|
||||||
wheels/
|
|
||||||
share/python-wheels/
|
|
||||||
*.egg-info/
|
|
||||||
.installed.cfg
|
|
||||||
*.egg
|
|
||||||
MANIFEST
|
|
||||||
|
|
||||||
# PyInstaller
|
|
||||||
# Usually these files are written by a python script from a template
|
|
||||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
||||||
*.manifest
|
|
||||||
*.spec
|
|
||||||
|
|
||||||
# Installer logs
|
|
||||||
pip-log.txt
|
|
||||||
pip-delete-this-directory.txt
|
|
||||||
|
|
||||||
# Unit test / coverage reports
|
|
||||||
htmlcov/
|
|
||||||
.tox/
|
|
||||||
.nox/
|
|
||||||
.coverage
|
|
||||||
.coverage.*
|
|
||||||
.cache
|
|
||||||
nosetests.xml
|
|
||||||
coverage.xml
|
|
||||||
*.cover
|
|
||||||
*.py,cover
|
|
||||||
.hypothesis/
|
|
||||||
.pytest_cache/
|
|
||||||
cover/
|
|
||||||
|
|
||||||
# Translations
|
|
||||||
*.mo
|
|
||||||
*.pot
|
|
||||||
|
|
||||||
# Django stuff:
|
|
||||||
*.log
|
|
||||||
local_settings.py
|
|
||||||
db.sqlite3
|
|
||||||
db.sqlite3-journal
|
|
||||||
|
|
||||||
# Flask stuff:
|
|
||||||
instance/
|
|
||||||
.webassets-cache
|
|
||||||
|
|
||||||
# Scrapy stuff:
|
|
||||||
.scrapy
|
|
||||||
|
|
||||||
# Sphinx documentation
|
|
||||||
docs/_build/
|
|
||||||
|
|
||||||
# PyBuilder
|
|
||||||
.pybuilder/
|
|
||||||
target/
|
|
||||||
|
|
||||||
# Jupyter Notebook
|
|
||||||
.ipynb_checkpoints
|
|
||||||
|
|
||||||
# IPython
|
|
||||||
profile_default/
|
|
||||||
ipython_config.py
|
|
||||||
|
|
||||||
# pyenv
|
|
||||||
# For a library or package, you might want to ignore these files since the code is
|
|
||||||
# intended to run in multiple environments; otherwise, check them in:
|
|
||||||
# .python-version
|
|
||||||
|
|
||||||
# pipenv
|
|
||||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
||||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
||||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
||||||
# install all needed dependencies.
|
|
||||||
#Pipfile.lock
|
|
||||||
|
|
||||||
# UV
|
|
||||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
||||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
||||||
# commonly ignored for libraries.
|
|
||||||
#uv.lock
|
|
||||||
|
|
||||||
# poetry
|
|
||||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
||||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
||||||
# commonly ignored for libraries.
|
|
||||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
||||||
#poetry.lock
|
|
||||||
|
|
||||||
# pdm
|
|
||||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
||||||
#pdm.lock
|
|
||||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
|
||||||
# in version control.
|
|
||||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
|
||||||
.pdm.toml
|
|
||||||
.pdm-python
|
|
||||||
.pdm-build/
|
|
||||||
|
|
||||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
||||||
__pypackages__/
|
|
||||||
|
|
||||||
# Celery stuff
|
|
||||||
celerybeat-schedule
|
|
||||||
celerybeat.pid
|
|
||||||
|
|
||||||
# SageMath parsed files
|
|
||||||
*.sage.py
|
|
||||||
|
|
||||||
# Environments
|
|
||||||
.env
|
.env
|
||||||
.venv
|
__pycache__/
|
||||||
env/
|
*.pyc
|
||||||
venv/
|
*.mo
|
||||||
ENV/
|
.pytest_cache/
|
||||||
env.bak/
|
|
||||||
venv.bak/
|
|
||||||
|
|
||||||
# Spyder project settings
|
|
||||||
.spyderproject
|
|
||||||
.spyproject
|
|
||||||
|
|
||||||
# Rope project settings
|
|
||||||
.ropeproject
|
|
||||||
|
|
||||||
# mkdocs documentation
|
|
||||||
/site
|
|
||||||
|
|
||||||
# mypy
|
|
||||||
.mypy_cache/
|
.mypy_cache/
|
||||||
.dmypy.json
|
|
||||||
dmypy.json
|
|
||||||
|
|
||||||
# Pyre type checker
|
|
||||||
.pyre/
|
|
||||||
|
|
||||||
# pytype static type analyzer
|
|
||||||
.pytype/
|
|
||||||
|
|
||||||
# Cython debug symbols
|
|
||||||
cython_debug/
|
|
||||||
|
|
||||||
# PyCharm
|
|
||||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
||||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
||||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
||||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
||||||
#.idea/
|
|
||||||
|
|
||||||
# Ruff stuff:
|
|
||||||
.ruff_cache/
|
.ruff_cache/
|
||||||
|
.venv/
|
||||||
# PyPI configuration file
|
|
||||||
.pypirc
|
|
||||||
|
|
||||||
+78
@@ -0,0 +1,78 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
#
|
||||||
|
# Ein Image für Web und Worker. Läuft ohne Root und mit schreibgeschütztem
|
||||||
|
# Dateisystem; beschreibbar sind nur /data (Volume) und /tmp (tmpfs).
|
||||||
|
|
||||||
|
ARG PYTHON_VERSION=3.13
|
||||||
|
ARG DEBIAN_SUITE=trixie
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Bauen: Abhängigkeiten aus der Lock-Datei (nur mit passenden Hashes)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
FROM python:${PYTHON_VERSION}-slim-${DEBIAN_SUITE} AS build
|
||||||
|
|
||||||
|
ENV PIP_NO_CACHE_DIR=1 \
|
||||||
|
PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||||
|
|
||||||
|
WORKDIR /build
|
||||||
|
COPY requirements.lock ./
|
||||||
|
RUN python -m venv /opt/venv \
|
||||||
|
&& /opt/venv/bin/pip install --require-hashes --no-deps --only-binary=:all: -r requirements.lock
|
||||||
|
|
||||||
|
COPY surveybox ./surveybox
|
||||||
|
RUN /opt/venv/bin/pybabel compile --statistics -D messages -d surveybox/locale \
|
||||||
|
&& /opt/venv/bin/python -m compileall -q surveybox
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Laufzeit
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
FROM python:${PYTHON_VERSION}-slim-${DEBIAN_SUITE} AS runtime
|
||||||
|
|
||||||
|
ARG DEBIAN_SUITE
|
||||||
|
# PostgreSQL-Client-Werkzeuge für die Sicherung. Mehrere Hauptversionen,
|
||||||
|
# damit zu jedem unterstützten Server ein passendes pg_dump vorhanden ist.
|
||||||
|
ARG PG_CLIENT_VERSIONS="17 18 19"
|
||||||
|
|
||||||
|
RUN set -eux; \
|
||||||
|
apt-get update; \
|
||||||
|
apt-get install -y --no-install-recommends ca-certificates curl gnupg; \
|
||||||
|
install -d /usr/share/postgresql-common/pgdg; \
|
||||||
|
curl -fsSL -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc \
|
||||||
|
https://www.postgresql.org/media/keys/ACCC4CF8.asc; \
|
||||||
|
echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt ${DEBIAN_SUITE}-pgdg main" \
|
||||||
|
> /etc/apt/sources.list.d/pgdg.list; \
|
||||||
|
apt-get update; \
|
||||||
|
pkgs=""; for v in ${PG_CLIENT_VERSIONS}; do pkgs="$pkgs postgresql-client-$v"; done; \
|
||||||
|
apt-get install -y --no-install-recommends $pkgs; \
|
||||||
|
apt-get purge -y --auto-remove curl gnupg; \
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
RUN groupadd --system --gid 10001 surveybox \
|
||||||
|
&& useradd --system --uid 10001 --gid surveybox --home-dir /nonexistent \
|
||||||
|
--no-create-home --shell /usr/sbin/nologin surveybox \
|
||||||
|
&& install -d -o surveybox -g surveybox -m 0750 /data /data/backups
|
||||||
|
|
||||||
|
COPY --from=build /opt/venv /opt/venv
|
||||||
|
COPY --from=build /build/surveybox /app/surveybox
|
||||||
|
|
||||||
|
ENV PATH=/opt/venv/bin:$PATH \
|
||||||
|
PYTHONPATH=/app \
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
SURVEYBOX_DATA_DIR=/data
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
USER surveybox:surveybox
|
||||||
|
VOLUME ["/data"]
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=10s --start-period=300s --retries=3 \
|
||||||
|
CMD ["python", "-m", "surveybox.cli", "healthcheck"]
|
||||||
|
|
||||||
|
ENTRYPOINT ["python", "-m", "surveybox.cli"]
|
||||||
|
CMD ["web"]
|
||||||
|
|
||||||
|
LABEL org.opencontainers.image.title="Surveybox" \
|
||||||
|
org.opencontainers.image.description="Formulare und Abstimmungen, selbst gehostet" \
|
||||||
|
org.opencontainers.image.licenses="AGPL-3.0-or-later"
|
||||||
@@ -1,235 +1,661 @@
|
|||||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
Version 3, 19 November 2007
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
Preamble
|
Preamble
|
||||||
|
|
||||||
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
The precise terms and conditions for copying, distribution and modification follow.
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
TERMS AND CONDITIONS
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
0. Definitions.
|
0. Definitions.
|
||||||
|
|
||||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
A "covered work" means either the unmodified Program or a work based on the Program.
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
1. Source Code.
|
1. Source Code.
|
||||||
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
|
||||||
|
|
||||||
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
subprograms and other parts of the work.
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
The Corresponding Source for a work in source code form is that same work.
|
Source.
|
||||||
|
|
||||||
2. Basic Permissions.
|
The Corresponding Source for a work in source code form is that
|
||||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
same work.
|
||||||
|
|
||||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
2. Basic Permissions.
|
||||||
|
|
||||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
4. Conveying Verbatim Copies.
|
|
||||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
5. Conveying Modified Source Versions.
|
with facilities for running those works, provided that you comply with
|
||||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
makes it unnecessary.
|
||||||
|
|
||||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
6. Conveying Non-Source Forms.
|
No covered work shall be deemed part of an effective technological
|
||||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
7. Additional Terms.
|
and you may offer support or warranty protection for a fee.
|
||||||
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
it, and giving a relevant date.
|
||||||
|
|
||||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
8. Termination.
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
work need not make them do so.
|
||||||
|
|
||||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
9. Acceptance Not Required for Having Copies.
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
parts of the aggregate.
|
||||||
|
|
||||||
10. Automatic Licensing of Downstream Recipients.
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
11. Patents.
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
customarily used for software interchange.
|
||||||
|
|
||||||
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
|
product that is covered by this License, on a durable physical
|
||||||
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
12. No Surrender of Others' Freedom.
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
|
|
||||||
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
14. Revised Versions of this License.
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
charge under subsection 6d.
|
||||||
|
|
||||||
15. Disclaimer of Warranty.
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
included in conveying the object code work.
|
||||||
|
|
||||||
16. Limitation of Liability.
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
17. Interpretation of Sections 15 and 16.
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
END OF TERMS AND CONDITIONS
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
How to Apply These Terms to Your New Programs
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
surveybox
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
Copyright (C) 2026 marco.morath
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
Also add information on how to contact you by electronic and paper mail.
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
@@ -1,2 +1,939 @@
|
|||||||
# surveybox
|
# Surveybox
|
||||||
|
|
||||||
|
Formulare und Abstimmungen in einer selbst gehosteten Anwendung.
|
||||||
|
Lizenz: AGPL-3.0-or-later.
|
||||||
|
|
||||||
|
## Aufbau
|
||||||
|
|
||||||
|
| Dienst | Aufgabe |
|
||||||
|
| --- | --- |
|
||||||
|
| `web` | Webserver (FastAPI). Bringt beim Start die Datenbank auf den aktuellen Stand. |
|
||||||
|
| `worker` | Hintergrundaufgaben, zurzeit die tägliche Sicherung. Startet erst, wenn `web` gesund ist. |
|
||||||
|
| `db` | PostgreSQL 18. Entfällt bei einem externen Datenbankserver. |
|
||||||
|
|
||||||
|
`web` und `worker` nutzen dasselbe Image. Die Container laufen ohne Root,
|
||||||
|
mit schreibgeschütztem Dateisystem und ohne Linux-Capabilities. Beschreibbar
|
||||||
|
sind nur das Volume `/data` (Sicherungen, später Uploads) und `/tmp`.
|
||||||
|
|
||||||
|
Alle Tabellen liegen im Datenbankschema `surveybox`. Surveybox kann daher
|
||||||
|
auch eine vorhandene Datenbank mitbenutzen, und Sicherung und
|
||||||
|
Wiederherstellung betreffen nie etwas anderes.
|
||||||
|
|
||||||
|
## Erstinstallation
|
||||||
|
|
||||||
|
Voraussetzungen: Docker Engine mit Compose v2.24 oder neuer, ein Reverse
|
||||||
|
Proxy mit TLS (z. B. Nginx Proxy Manager).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone <repository> surveybox && cd surveybox
|
||||||
|
|
||||||
|
# Einmalig: Lizenztext der AGPL ablegen
|
||||||
|
curl -fsSL -o LICENSE https://www.gnu.org/licenses/agpl-3.0.txt
|
||||||
|
|
||||||
|
# Einmalig (und nach jeder Änderung an requirements*.in):
|
||||||
|
# Abhängigkeiten mit Versionen und Hashes festschreiben
|
||||||
|
./scripts/lock.sh
|
||||||
|
|
||||||
|
cp .env.example .env
|
||||||
|
chmod 600 .env
|
||||||
|
# In .env eintragen:
|
||||||
|
# SURVEYBOX_SECRET_KEY → openssl rand -hex 32
|
||||||
|
# SURVEYBOX_DB_PASSWORD → openssl rand -base64 32
|
||||||
|
# SURVEYBOX_PUBLIC_URL → endgültige Adresse, später nicht mehr ändern
|
||||||
|
# SURVEYBOX_NET_SUBNET → freies Subnetz für dieses Stack-Netz (siehe unten)
|
||||||
|
|
||||||
|
docker compose build
|
||||||
|
docker compose up -d
|
||||||
|
docker compose ps # web und worker müssen "healthy" melden
|
||||||
|
```
|
||||||
|
|
||||||
|
Im Reverse Proxy einen Host für die öffentliche Adresse anlegen, Ziel ist
|
||||||
|
`http://<host>:8000`. Läuft der Proxy auf einem anderen Rechner oder selbst als
|
||||||
|
Container (z. B. Nginx Proxy Manager), in der `.env` `SURVEYBOX_HTTP_BIND` auf
|
||||||
|
die interne IP des Docker-Hosts setzen; `127.0.0.1` ist aus einem anderen
|
||||||
|
Container heraus nicht erreichbar.
|
||||||
|
|
||||||
|
### Netz
|
||||||
|
|
||||||
|
Das Docker-Netz des Stacks hat ein festes Subnetz aus `SURVEYBOX_NET_SUBNET`.
|
||||||
|
Ohne diese Angabe sucht Docker sich selbst einen Bereich aus, der mit dem LAN,
|
||||||
|
einem VPN oder anderen Stacks kollidieren kann. Das Subnetz muss frei sein und
|
||||||
|
sollte aus einem privaten Bereich stammen (`10.0.0.0/8`, `172.16.0.0/12`,
|
||||||
|
`192.168.0.0/16`); Gateway ist automatisch die erste Adresse. Jede Instanz
|
||||||
|
braucht ihr eigenes Subnetz. Wer das Subnetz eines bestehenden Stacks ändert,
|
||||||
|
muss ihn einmal mit `docker compose down` und `docker compose up -d` neu anlegen
|
||||||
|
(die Volumes bleiben erhalten).
|
||||||
|
|
||||||
|
Tipp für den ganzen Host: In `/etc/docker/daemon.json` legt
|
||||||
|
`"default-address-pools"` fest, aus welchem Bereich Docker für alle Stacks ohne
|
||||||
|
eigene Angabe Subnetze vergibt.
|
||||||
|
|
||||||
|
Prüfen: `https://<adresse>/health/ready` antwortet mit `{"status":"ready"}`.
|
||||||
|
|
||||||
|
### Erster Administrator
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec web python -m surveybox.cli create-admin \
|
||||||
|
--email admin@example.de --name "Vorname Nachname"
|
||||||
|
```
|
||||||
|
|
||||||
|
Der Befehl gibt einen einmaligen Link aus (7 Tage gültig). Darüber das
|
||||||
|
Passwort setzen, anmelden, dann verlangt Surveybox einen zweiten Faktor:
|
||||||
|
einen Passkey oder eine Authenticator-App. Für Administratoren ist der
|
||||||
|
zweite Faktor Pflicht.
|
||||||
|
|
||||||
|
### Gruppen, Gruppenadministratoren und Gruppenersteller
|
||||||
|
|
||||||
|
Gruppen lassen sich verschachteln (z. B. Gesamtwehr → Abteilung → Jugend).
|
||||||
|
Je Gruppe gibt es unter *Gruppen* zwei Rollen:
|
||||||
|
|
||||||
|
- **Gruppenadministrator:** verwaltet die Gruppe und alle Untergruppen:
|
||||||
|
Konten anlegen (als Teilnehmer, mit Einladungslink), Mitglieder zuordnen,
|
||||||
|
Untergruppen anlegen, Gruppenrollen vergeben, Umfragen der Gruppen
|
||||||
|
verwalten. Andere Benutzer und Umfragen sieht er nicht. Er braucht einen
|
||||||
|
zweiten Faktor. Ohne Gruppenadministrator verwalten die
|
||||||
|
Instanzadministratoren die Gruppe.
|
||||||
|
- **Gruppenersteller:** legt Umfragen für die Gruppe und ihre Untergruppen an.
|
||||||
|
Jede solche Umfrage gehört zu einer Gruppe und ist zunächst für sie
|
||||||
|
freigegeben. Als Zugriff stehen eigene Gruppen und Mitglieder sowie Links
|
||||||
|
zur Wahl, nicht „alle angemeldeten Benutzer“.
|
||||||
|
|
||||||
|
Rechte wirken nach unten, Freigaben auch: Eine Umfrage für eine Gruppe
|
||||||
|
erreicht die Mitglieder aller Untergruppen. Die instanzweite Rolle
|
||||||
|
*Ersteller* bleibt und darf Umfragen für alle anlegen.
|
||||||
|
|
||||||
|
Jede Gruppe gibt außerdem an, für welche Benutzertypen sie passt. Beim
|
||||||
|
Anlegen eines Benutzers erscheinen nach der Wahl des Typs die passenden
|
||||||
|
Gruppen.
|
||||||
|
|
||||||
|
### Passkeys
|
||||||
|
|
||||||
|
Ein Passkey ersetzt Passwort und Code; bestätigt wird mit Fingerabdruck,
|
||||||
|
Gesicht oder Geräte-PIN. Er gilt nur für die Domain aus
|
||||||
|
`SURVEYBOX_PUBLIC_URL`. Surveybox speichert nur den öffentlichen Schlüssel.
|
||||||
|
Im Browser läuft dafür ein kleines Skript (`static/js/passkeys.js`); ohne
|
||||||
|
JavaScript funktioniert die Anmeldung mit Passwort weiterhin.
|
||||||
|
|
||||||
|
### Zugang verloren
|
||||||
|
|
||||||
|
Passwort vergessen oder Telefon mit der Authenticator-App verloren, und kein
|
||||||
|
Wiederherstellungscode zur Hand:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec web python -m surveybox.cli user-link \
|
||||||
|
--email admin@example.de --reset-2fa
|
||||||
|
```
|
||||||
|
|
||||||
|
Das entfernt alle zweiten Faktoren (Authenticator-App und Passkeys) und gibt
|
||||||
|
einen Link zum Setzen eines neuen Passworts aus (24 Stunden gültig). Für andere Benutzer geht das auch in der
|
||||||
|
Verwaltung unter *Benutzer → Anmeldung zurücksetzen*.
|
||||||
|
|
||||||
|
### Formulare
|
||||||
|
|
||||||
|
Administratoren und Ersteller legen Formulare unter *Formulare* an. Ein
|
||||||
|
neues Formular ist ein Entwurf und für niemanden sonst sichtbar. Nach dem
|
||||||
|
Veröffentlichen gilt die Adresse `/f/<Kennung>`; die Kennung ist zufällig und
|
||||||
|
nicht erratbar. Wer ausfüllen darf, steht in den Einstellungen:
|
||||||
|
|
||||||
|
| Zugriff | Anmeldung nötig | Hinweis |
|
||||||
|
|---|---|---|
|
||||||
|
| Alle angemeldeten Benutzer | ja | Erscheint auf deren Startseite |
|
||||||
|
| Ausgewählte Benutzer und Gruppen | ja | Erscheint auf deren Startseite; neue Gruppenmitglieder haben sofort Zugang |
|
||||||
|
| Alle mit dem Link | nein | Gäste ohne Konto |
|
||||||
|
| Link und Passwort | nein | Freischaltung gilt 12 Stunden; ein neues Passwort sperrt alte Freischaltungen |
|
||||||
|
|
||||||
|
Bei anonymen Formularen speichert Surveybox die Antworten ohne Bezug zur
|
||||||
|
Person. Damit angemeldete Benutzer trotzdem nur einmal teilnehmen, merkt es
|
||||||
|
sich einen nicht umkehrbaren Prüfwert aus Formular und Benutzer. Die
|
||||||
|
Anonymität lässt sich nach der ersten Antwort nicht mehr umschalten; anonyme
|
||||||
|
Antworten können nicht nachträglich geändert werden.
|
||||||
|
|
||||||
|
**Seiten.** Ein Seitenumbruch beginnt eine neue Seite. Teilnehmende blättern
|
||||||
|
mit *Weiter* und *Zurück*; jede Seite wird vor dem Weiterblättern geprüft.
|
||||||
|
Ohne JavaScript stehen alle Seiten untereinander.
|
||||||
|
|
||||||
|
**Bedingungen.** Im Frage-Editor unter *Bedingung*: anzeigen oder
|
||||||
|
ausblenden, wenn alle (UND) oder mindestens eine (ODER) Regel zutrifft. Eine
|
||||||
|
Regel vergleicht eine frühere Frage: ist, ist nicht, enthält, enthält nicht,
|
||||||
|
größer, kleiner, beantwortet, nicht beantwortet. Bei einer Überschrift gilt
|
||||||
|
die Bedingung für den ganzen Abschnitt, bei einem Seitenumbruch für die ganze
|
||||||
|
Seite. Der Browser blendet sofort ein und aus; beim Absenden prüft der Server
|
||||||
|
alles noch einmal: Ausgeblendete Fragen sind nie Pflicht, und ihre Antworten
|
||||||
|
werden verworfen, auch wenn jemand sie trotzdem schickt. Regeln dürfen nur
|
||||||
|
auf frühere Fragen zeigen; Verschiebungen, die das brechen würden, lehnt der
|
||||||
|
Designer ab. Wird eine Frage gelöscht, entfallen Regeln, die auf sie zeigen.
|
||||||
|
Der Designer zeigt bei jeder Frage, wann sie erscheint und wie viele
|
||||||
|
Bedingungen sie steuert.
|
||||||
|
|
||||||
|
**Abstimmung (Fragetyp).** Optionen sind Texte oder Termine (Datum,
|
||||||
|
optional Uhrzeit und Dauer). Je Option Ja/Nein oder Ja/Vielleicht/Nein.
|
||||||
|
Teilnehmende können weitere Optionen vorschlagen, wenn das eingeschaltet ist;
|
||||||
|
ein Vorschlag zählt als ihr Ja. Unter *Antworten* steht eine Ergebnistabelle,
|
||||||
|
die beste Option ist markiert; dort lassen sich Optionen bestätigen. Wer die
|
||||||
|
Ergebnisse sehen darf, steuert *Teilnehmende sehen die Ergebnisse* in den
|
||||||
|
Einstellungen.
|
||||||
|
|
||||||
|
**Kalender.** In den Einstellungen: aus, Kalenderdatei (ICS) für
|
||||||
|
Teilnehmende oder zusätzlich ein Abo-Link für Kalenderprogramme. Enthalten
|
||||||
|
sind nur bestätigte Termine, ohne Angaben zu Personen. Der Abo-Link
|
||||||
|
funktioniert ohne Anmeldung; wer ihn kennt, sieht die Termine. Er lässt sich
|
||||||
|
erneuern, dann gilt der alte nicht mehr.
|
||||||
|
|
||||||
|
**Teilnahme mit Plätzen (Fragetyp).** Ein Eintrag mit einem Häkchen
|
||||||
|
*Anmelden* und einer Platzzahl (leer: unbegrenzt), wahlweise mit Warteliste
|
||||||
|
und Ausblenden, wenn ausgebucht. Für mehrere Schichten oder Termine legt man
|
||||||
|
eine Fragengruppe an (siehe unten), darin je Eintrag eine Frage. Ältere
|
||||||
|
Fragen mit mehreren Optionen bleiben unverändert nutzbar und bearbeitbar.
|
||||||
|
Freie Plätze stehen auf der Seite und werden alle
|
||||||
|
20 Sekunden aktualisiert. Beim Absenden wird die Frage in der Datenbank
|
||||||
|
gesperrt; zwei gleichzeitige Buchungen können den letzten Platz nicht doppelt
|
||||||
|
belegen. Ist ein Platz inzwischen weg, bleibt das Formular ausgefüllt und
|
||||||
|
zeigt einen Hinweis. Wird ein Platz frei (Antwort geändert, mehr Plätze im
|
||||||
|
Designer), rückt die am längsten wartende Person nach. Eine Höchstzahl an
|
||||||
|
Plätzen je Person über alle Teilnahme-Felder steht in den Einstellungen.
|
||||||
|
|
||||||
|
**Teilnehmer-Name (Fragetyp).** Vor- und Nachname (immer Pflicht) und
|
||||||
|
wahlweise eine E-Mail-Adresse (freiwillig, Pflicht oder gar nicht). Bei
|
||||||
|
Angemeldeten sind die Felder aus dem Konto vorausgefüllt. Die Frage ist als
|
||||||
|
personenbezogen markiert. Steht unter *E-Mail-Adresse von Gästen* „aus der
|
||||||
|
Antwort“, nimmt Surveybox auch die Adresse aus diesem Feld.
|
||||||
|
|
||||||
|
**Eingetragene Namen anzeigen.** Für Schichtpläne und Anmeldelisten zeigt das
|
||||||
|
Formular auf Wunsch bei jedem Eintrag, wer sich schon eingetragen hat (auch
|
||||||
|
die Warteliste): mit vollem Namen oder datensparsam als Vorname und
|
||||||
|
Anfangsbuchstabe des Nachnamens (Einstellungen → Plätze, Kalender und
|
||||||
|
Kommentare). Der Name kommt aus dem Teilnehmer-Namen, sonst aus dem Konto;
|
||||||
|
Gäste ohne Namen erscheinen als „Gast“. E-Mail-Adressen erscheinen nie. Das
|
||||||
|
Formular weist oben darauf hin. Bei anonymen Formularen ist das abgeschaltet.
|
||||||
|
|
||||||
|
**Fragengruppen.** Das Element *Fragengruppe* fasst gleichartige Fragen
|
||||||
|
zusammen: Teilnahme mit Plätzen, Ja/Nein, Bewertungsskala oder
|
||||||
|
Einfachauswahl. Zur Gruppe gehören alle direkt folgenden Fragen des gewählten
|
||||||
|
Typs; eine andere Frageart, eine Überschrift, ein Seitenumbruch oder eine
|
||||||
|
weitere Gruppe beendet sie. Damit die Tabelle stimmt, müssen die Fragen
|
||||||
|
zueinander passen (gleiche Skala, gleiche Ja/Nein-Texte, gleiche
|
||||||
|
Antwortmöglichkeiten ohne *Sonstiges*); eine unpassende Frage beendet die
|
||||||
|
Gruppe ebenfalls. Im Designer sind die Fragen der Gruppe eingerückt;
|
||||||
|
*Frage in die Gruppe einfügen* legt eine neue Frage direkt am Ende der Gruppe
|
||||||
|
an und übernimmt Skala bzw. Texte. Teilnehmende sehen die Gruppe als Tabelle
|
||||||
|
mit einer Zeile je Frage (z. B. Schicht | freie Plätze | Häkchen).
|
||||||
|
*Mindestens auswählen* (0 = freiwillig) und *Höchstens auswählbar*
|
||||||
|
(0 = unbegrenzt) gelten bei Teilnahme für die Anmeldungen und bei Ja/Nein für
|
||||||
|
die Zahl der „Ja“ in der Gruppe; ist die Höchstzahl erreicht, sperrt die Seite
|
||||||
|
weitere Häkchen, verbindlich prüft der Server beim Absenden. Blendet eine
|
||||||
|
Bedingung Zeilen aus, verlangt die Gruppe höchstens so viele Einträge, wie
|
||||||
|
sichtbar sind.
|
||||||
|
|
||||||
|
Pflicht in Gruppen: Bei Teilnahme-Gruppen legt allein die Gruppe fest, ob und
|
||||||
|
wie viele Einträge gewählt werden müssen; *Antwort erforderlich* gibt es an den
|
||||||
|
einzelnen Einträgen dort nicht (eine Pflicht-Schicht hieße „genau diese
|
||||||
|
buchen“ und widerspräche der Höchstzahl). Bei Ja/Nein, Bewertung und
|
||||||
|
Einfachauswahl bleibt *Antwort erforderlich* je Zeile und heißt „diese Zeile
|
||||||
|
beantworten“; das verträgt sich mit der Höchstzahl, weil auch „Nein“ eine
|
||||||
|
Antwort ist. Eine Bedingung an der Gruppe gilt für alle ihre Fragen; einzelne
|
||||||
|
Fragen können zusätzlich eigene Bedingungen haben. Bilder und Videos einer
|
||||||
|
Frage erscheinen in der Tabelle nicht.
|
||||||
|
|
||||||
|
**Kommentare.** Je Formular aus, moderiert (Standard) oder öffentlich, auf
|
||||||
|
Wunsch ohne Namen für andere (Verwalter sehen ihn). Unter *Kommentare* im
|
||||||
|
Designer schalten Verwalter frei oder löschen. Autoren ändern und löschen
|
||||||
|
eigene Kommentare; im moderierten Modus muss ein geänderter Kommentar neu
|
||||||
|
freigegeben werden. Reiner Text, höchstens zehn Kommentare je Person und
|
||||||
|
Stunde.
|
||||||
|
|
||||||
|
Benachrichtigungen per E-Mail siehe *E-Mail und Benachrichtigungen*.
|
||||||
|
|
||||||
|
**Zusammenfassung.** Unter *Antworten* zählt Surveybox jede Auswahl- und
|
||||||
|
Ja/Nein-Frage automatisch aus; bei Zahlen und Bewertungen stehen Summe und
|
||||||
|
Durchschnitt dabei.
|
||||||
|
|
||||||
|
Auswertung mit Diagrammen und Export folgt in Phase 8.
|
||||||
|
|
||||||
|
**Team und Vorlagen.** Unter *Team* nimmt der Eigentümer Benutzer oder
|
||||||
|
Gruppen auf: Mitbearbeitende ändern Fragen und Einstellungen und sehen die
|
||||||
|
Antworten, Auswertende sehen nur die Antworten. Team verwalten und löschen
|
||||||
|
darf nur der Eigentümer (und Administratoren). *Kopieren* legt einen Entwurf
|
||||||
|
mit allen Fragen, Einstellungen und Medien an, ohne Antworten. *Als Vorlage
|
||||||
|
speichern* legt eine Vorlage an; sie erscheint in der Formularliste und ist
|
||||||
|
für andere Ersteller erst sichtbar, wenn der Eigentümer sie freigibt.
|
||||||
|
|
||||||
|
**Designer.** Fragen lassen sich am Griff ⠿ ziehen oder mit dem Griff im
|
||||||
|
Fokus per Pfeiltaste verschieben; ohne JavaScript bleiben die Pfeil-Knöpfe.
|
||||||
|
Im Optionen- und Termin-Editor fügt *Zeile hinzufügen* weitere leere Zeilen an.
|
||||||
|
Die *Live-Vorschau* öffnet sich in einem eigenen Fenster, zeigt das Formular
|
||||||
|
als Handy, Tablet oder Desktop und lädt sich nach jeder Änderung neu.
|
||||||
|
|
||||||
|
### E-Mail und Benachrichtigungen
|
||||||
|
|
||||||
|
**SMTP-Relay.** Unter *Verwaltung → E-Mail* (nicht in der `.env`): Server,
|
||||||
|
Port, STARTTLS oder TLS, Benutzer und Passwort, Absenderadresse und -name,
|
||||||
|
Antwort-an-Adresse. Unverschlüsselte Verbindungen gibt es nicht, das
|
||||||
|
Zertifikat wird immer geprüft. Das Passwort liegt verschlüsselt in der
|
||||||
|
Datenbank (Schlüssel aus `SURVEYBOX_SECRET_KEY`) und wird nicht wieder
|
||||||
|
angezeigt; ändert sich der Schlüssel, muss es neu eingegeben werden.
|
||||||
|
*Testnachricht jetzt senden* schickt sofort eine Mail und zeigt den Fehler
|
||||||
|
des Servers, falls es nicht klappt. Jede Änderung und jede Testmail steht im
|
||||||
|
Protokoll.
|
||||||
|
|
||||||
|
Absender ist immer die Adresse des Relays (SPF, DKIM, DMARC). Antworten auf
|
||||||
|
Mails lenkt die Antwort-an-Adresse um: ein Standard in den E-Mail-Einstellungen,
|
||||||
|
je Formular in dessen Einstellungen überschreibbar.
|
||||||
|
|
||||||
|
**Warteschlange.** Mails werden in derselben Transaktion eingetragen wie die
|
||||||
|
auslösende Aktion und vom Worker alle 30 Sekunden versendet. Ist kein Relay
|
||||||
|
eingerichtet, bleiben sie liegen; die Admin-Seite zeigt das an. Bei
|
||||||
|
vorübergehenden Fehlern versucht der Worker es nach 1, 5 und 15 Minuten und
|
||||||
|
nach 1, 4 und 12 Stunden erneut, eine endgültige Ablehnung (5xx) beendet die
|
||||||
|
Zustellung sofort. Der Inhalt einer Mail liegt verschlüsselt in der Datenbank
|
||||||
|
und wird nach dem Versand gelöscht (Links zum Setzen eines Passworts gehören
|
||||||
|
nicht in eine Sicherung). Das Zustellprotokoll (Art, Empfänger, Status,
|
||||||
|
letzter Fehler) bleibt 90 Tage.
|
||||||
|
|
||||||
|
**Passwort vergessen.** Auf der Anmeldeseite. Die Seite antwortet immer gleich,
|
||||||
|
ob es ein Konto gibt oder nicht; Anfragen sind je IP und je Adresse begrenzt
|
||||||
|
(drei Links je Adresse und Stunde). Der Link gilt 24 Stunden und einmal; ein
|
||||||
|
eingerichteter zweiter Faktor bleibt aktiv.
|
||||||
|
|
||||||
|
**Einladungen.** Beim Anlegen eines Benutzers ist *Einladung per E-Mail
|
||||||
|
senden* vorbelegt. Auf der Seite eines Benutzers lässt sich ein neuer Link
|
||||||
|
per Mail senden oder wie bisher anzeigen.
|
||||||
|
|
||||||
|
**Benachrichtigungen.** Für angemeldete Benutzer und Gäste mit bestätigter
|
||||||
|
Adresse (Gäste nur die Ereignisse für Teilnehmende):
|
||||||
|
|
||||||
|
| Ereignis | Empfänger |
|
||||||
|
|---|---|
|
||||||
|
| Teilnahme eingegangen (mit Link zum Formular) | Teilnehmende |
|
||||||
|
| Von der Warteliste nachgerückt | Teilnehmende |
|
||||||
|
| Termin einer Abstimmung bestätigt | Teilnehmende |
|
||||||
|
| Eigener Kommentar freigeschaltet | Kommentierende |
|
||||||
|
| Neuer Kommentar (wenn im Formular eingeschaltet) | Eigentümer und Mitbearbeitende |
|
||||||
|
| Eintrag ausgebucht (höchstens einmal je Tag und Eintrag) | Eigentümer |
|
||||||
|
| Enddatum erreicht | Eigentümer |
|
||||||
|
| Folge-Mail eines Formulars (siehe unten) | Teilnehmende |
|
||||||
|
| Gewählter Eintrag oder Termin gestrichen (Buchungen darauf entfallen) | Teilnehmende |
|
||||||
|
| Erinnerung vor dem Enddatum (je Formular einstellbar) | Eingeladene ohne Teilnahme |
|
||||||
|
| Tägliche Zusammenfassung neuer und geänderter Antworten (ab 7 Uhr) | Eigentümer und Mitbearbeitende |
|
||||||
|
|
||||||
|
Alle sind voreingestellt an. Jede Person schaltet sie unter *Mein Konto →
|
||||||
|
Benachrichtigungen* einzeln ab. Jede Benachrichtigung enthält einen
|
||||||
|
Abmeldelink: für dieses Formular oder für diese Art von Benachrichtigung; das
|
||||||
|
Mailprogramm kann per `List-Unsubscribe` mit einem Klick abbestellen (RFC 8058).
|
||||||
|
Mails enthalten Links statt Antwortinhalten. Bei anonymen Formularen gibt es
|
||||||
|
keine Mails an Teilnehmende, weil die Mail Person und Teilnahme verbinden
|
||||||
|
würde. Ein Fehler beim Erzeugen einer Benachrichtigung verhindert nie die
|
||||||
|
eigentliche Aktion; er steht im Log des Dienstes.
|
||||||
|
|
||||||
|
Mails gehen in der Sprache des Profils, bei „wie mein Browser“ in der
|
||||||
|
Standardsprache (`SURVEYBOX_DEFAULT_LANGUAGE`).
|
||||||
|
|
||||||
|
**Erinnerung.** In den Formulareinstellungen unter *Teilnahme*: so viele Tage
|
||||||
|
vor dem Enddatum (1 bis 30) erinnert Surveybox alle Personen der Zugriffsliste
|
||||||
|
(Benutzer und Gruppen samt Untergruppen), die noch nicht teilgenommen haben;
|
||||||
|
nur bei Zugriff „Ausgewählte Benutzer und Gruppen“ und mit Enddatum. Jede
|
||||||
|
Person einmal je Enddatum.
|
||||||
|
|
||||||
|
### Eigene Mail-Vorlagen
|
||||||
|
|
||||||
|
*E-Mail → E-Mail-Vorlagen* (`/admin/mail/templates`): Jede Mail (Einladung,
|
||||||
|
Passwort zurücksetzen, Teilnahmebestätigungen, Warteliste, Erinnerung, Hinweise
|
||||||
|
an Verwalter usw.) kann je Sprache einen eigenen Betreff und Text bekommen.
|
||||||
|
Ohne eigenen Text gilt der Standardtext. Test-Mail und Folge-Mails haben ihre
|
||||||
|
eigenen Texte und sind nicht dabei.
|
||||||
|
|
||||||
|
Eigene Vorlagen sind reiner Text mit Platzhaltern in geschweiften Klammern,
|
||||||
|
bewusst kein Jinja: Administratoren können darüber nichts ausführen.
|
||||||
|
|
||||||
|
- `{greeting}`: Anrede („Hallo Erika,“ oder „Hallo,“)
|
||||||
|
- `{details}`: der Standardtext der Mail ohne Anrede, mit allem, was je nach
|
||||||
|
Lage dazugehört (Listen, Hinweise für Gäste, Bestätigungslinks)
|
||||||
|
- `{app}`: Name der Anwendung, `{title}`: Titel des Formulars
|
||||||
|
- je Mailart die einfachen Werte, etwa `{name}`, `{link}`, `{entry}`,
|
||||||
|
`{closes}`; die Seite listet sie mit Beschreibung auf
|
||||||
|
|
||||||
|
Der Vorschlag beim ersten Bearbeiten ist `{greeting}` + `{details}`: eigener
|
||||||
|
Text davor oder danach, der Rest bleibt wie gewohnt. Wer `{details}` weglässt,
|
||||||
|
muss die Links der Mailart selbst einsetzen (z. B. `{link}`); unbekannte
|
||||||
|
Platzhalter werden abgelehnt. Die Seite zeigt eine Vorschau mit Beispieldaten
|
||||||
|
und den Standardtext daneben. Die Fußzeile mit Abmeldelink hängt Surveybox
|
||||||
|
immer an. Jede Änderung steht im Protokoll („E-Mail-Vorlage geändert“); die
|
||||||
|
Vorlagen liegen in der Datenbank und sind damit Teil der Sicherung.
|
||||||
|
|
||||||
|
### Folge-Mails mit Dokumenten
|
||||||
|
|
||||||
|
Im Designer unter *Folge-Mails*: je Formular bis zu 20 Mails mit Betreff, Text
|
||||||
|
(Platzhalter `{name}` und `{form}`) und bis zu 20 Dokumenten (PDF,
|
||||||
|
Office-Formate, Bilder, ZIP; Bilder werden ohne Metadaten neu berechnet).
|
||||||
|
Dokumente lassen sich schon beim Anlegen hochladen, weitere nach dem Speichern.
|
||||||
|
Zeitpunkt: direkt nach der Teilnahme, beim Schließen des Formulars, zu einem
|
||||||
|
festen Zeitpunkt oder nur von Hand. *Jetzt senden* zeigt die Zahl der
|
||||||
|
Empfänger, die die Mail noch nicht haben, und darüber eine Vorschau.
|
||||||
|
|
||||||
|
Empfänger sind alle Teilnehmenden mit bekannter Adresse (Konto oder
|
||||||
|
bestätigte Gast-Adresse), wahlweise nur mit bestätigtem Platz. Jede Person
|
||||||
|
erhält jede Folge-Mail höchstens einmal, auch wenn sie ihre Antwort ändert;
|
||||||
|
Gäste bekommen eine Mail „direkt nach der Teilnahme“, sobald sie ihre Adresse
|
||||||
|
bestätigt haben. Bei anonymen Formularen gibt es keine Folge-Mails.
|
||||||
|
|
||||||
|
Die Mail enthält Links statt Anhängen. Jeder Link ist persönlich, signiert und
|
||||||
|
läuft ab (Standard 90 Tage, einstellbar). Angemeldete finden die Dokumente
|
||||||
|
zusätzlich auf der Seite des Formulars, Gäste auf der Seite ihres persönlichen
|
||||||
|
Links. Surveybox zählt nur, wie oft ein Dokument heruntergeladen wurde, ohne
|
||||||
|
Bezug zur Person. *Kopieren* übernimmt Folge-Mails und Dokumente, aber nicht
|
||||||
|
den Versandstand.
|
||||||
|
|
||||||
|
*Empfänger* zeigt je Folge-Mail alle Teilnehmenden mit ihrem Stand: erhalten
|
||||||
|
(mit Zeitpunkt und Zustand in der Mail-Warteschlange), noch nicht gesendet,
|
||||||
|
kein bestätigter Platz, Adresse nicht bestätigt, keine Adresse oder abbestellt.
|
||||||
|
Wer die Mail bekommen darf, hat daneben *Senden* bzw. *Erneut senden*.
|
||||||
|
|
||||||
|
Bei „beim Schließen“, „zu einem festen Zeitpunkt“ und „nur von Hand“ fragt der
|
||||||
|
Editor, ob *später Hinzukommende* die Mail automatisch erhalten. Bei „Ja“ geht
|
||||||
|
sie an alle, die nach dem ersten Versand teilnehmen oder ihre Gast-Adresse
|
||||||
|
bestätigen. Bei „Nein“ sendet man sie bei Bedarf über die Empfängerseite.
|
||||||
|
Folge-Mails aus früheren Versionen fragen das beim nächsten Speichern ab. Gäste
|
||||||
|
erscheinen ohne Adresse, weil das Formular ihnen das zusagt; nur bei der
|
||||||
|
Einstellung „Adresse aus einer E-Mail-Frage“ steht die Adresse dabei.
|
||||||
|
|
||||||
|
Folge-Mails erreichen Gäste nur mit bestätigter Adresse. Ist mindestens eine
|
||||||
|
Folge-Mail eingerichtet, die noch versendet werden kann, weist das Formular
|
||||||
|
Gäste darauf hin. Wer ohne Adresse absendet, bekommt den Hinweis einmal und
|
||||||
|
kann danach bewusst ohne Adresse teilnehmen. Die Eingangsbestätigung und die
|
||||||
|
Dankeseite sagen, dass die Informationen erst nach der Bestätigung ankommen.
|
||||||
|
Können Gäste gar keine Adresse angeben, zeigt die Übersicht der Folge-Mails
|
||||||
|
das an.
|
||||||
|
|
||||||
|
### Gäste und persönliche Links
|
||||||
|
|
||||||
|
Gäste nehmen ohne Konto teil (Zugriff per Link). Jede Gast-Antwort bekommt
|
||||||
|
einen persönlichen Link `/r/…` (256 Bit Zufall, in der Datenbank nur als
|
||||||
|
Hash). Damit sieht der Gast seine Antwort und kann sie ändern oder löschen,
|
||||||
|
solange das Formular Änderungen erlaubt und offen ist; beim Löschen werden
|
||||||
|
Plätze frei und Wartende rücken nach. Nach dem Absenden zeigt die Dankeseite
|
||||||
|
den Link einmal an.
|
||||||
|
|
||||||
|
*E-Mail-Adresse von Gästen* in den Formulareinstellungen: nicht fragen,
|
||||||
|
optional, Pflicht (eigenes Feld am Ende des Formulars, das die Verwalter nicht
|
||||||
|
sehen) oder *Antwort auf die Frage „E-Mail-Adresse“ verwenden* (die erste Frage
|
||||||
|
dieses Typs; die Adresse ist dann Teil der Antwort, und ändert der Gast sie
|
||||||
|
über seinen Link, gilt die neue). Hat ein Formular eine E-Mail-Frage, steht
|
||||||
|
die Einstellung aber auf „nicht fragen“, weisen die Einstellungen darauf hin.
|
||||||
|
Mit Adresse bekommt der Gast eine Mail mit seinem Link und einem
|
||||||
|
Bestätigungslink. Benachrichtigungen (nachgerückt, Termin bestätigt)
|
||||||
|
gibt es erst nach der Bestätigung (Double-Opt-in); jede enthält einen
|
||||||
|
Abmeldelink. Unbestätigte Adressen löscht der Worker nach sieben Tagen; die
|
||||||
|
Antwort bleibt, der Link auch. Die Adresse sehen die Verwalter nicht; brauchen
|
||||||
|
sie Kontaktdaten, gehört eine Frage *E-Mail-Adresse* ins Formular. Bei
|
||||||
|
anonymen Formularen gibt es weder Adresse noch Link.
|
||||||
|
|
||||||
|
*Meine Links anfordern* (`/links`): Der Gast gibt seine Adresse ein und
|
||||||
|
erhält alle Links neu; die alten werden ungültig. Die Seite antwortet immer
|
||||||
|
gleich. Falsche Links (`/r/…`) und Anfragen sind je IP und Adresse begrenzt.
|
||||||
|
|
||||||
|
Surveybox selbst protokolliert keine Aufrufe (Zugriffslog aus). Schreibt der
|
||||||
|
Reverse-Proxy ein Zugriffslog, stehen persönliche Links (`/r/`), Einladungen
|
||||||
|
(`/setup/`) und Registrierungslinks (`/register/`) darin; dort am besten
|
||||||
|
kürzen oder ausschließen.
|
||||||
|
|
||||||
|
### Selbstregistrierung
|
||||||
|
|
||||||
|
Unter *Verwaltung → Einstellungen → Selbstregistrierung*:
|
||||||
|
|
||||||
|
- *Aus*: Konten legen nur Administratoren an.
|
||||||
|
- *Gäste* (Standard): wer als Gast seine Adresse bestätigt hat. Die
|
||||||
|
Bestätigungsseite und die Seite des persönlichen Links bieten *Konto
|
||||||
|
anlegen* an.
|
||||||
|
- *Offen*: jede Person; die Anmeldeseite zeigt *Konto anlegen*.
|
||||||
|
|
||||||
|
Ablauf: Name und Adresse eingeben, Mail mit Link (24 Stunden), Passwort
|
||||||
|
setzen. Das Konto entsteht erst dann; unbestätigte Anfragen hinterlassen
|
||||||
|
nichts in der Datenbank. Neue Konten sind Teilnehmer. Gast-Antworten mit
|
||||||
|
derselben bestätigten Adresse gehen auf das Konto über (auch wenn ein
|
||||||
|
Administrator das Konto anlegt und die Person die Einladung annimmt); die
|
||||||
|
einzelnen Links entfallen dann. Gibt es schon ein Konto, bekommt die Adresse
|
||||||
|
einen Hinweis mit Link zur Anmeldung statt eines zweiten Kontos.
|
||||||
|
|
||||||
|
### Auswertung und Export
|
||||||
|
|
||||||
|
Die Seite *Antworten* eines Formulars zeigt:
|
||||||
|
|
||||||
|
- **Filter** nach Eingangszeitraum und nach einer Antwort (Ja/Nein, Auswahl,
|
||||||
|
Bewertung, Teilnahme). Übersicht, Listen und Export richten sich danach; der
|
||||||
|
Filter steht in der Adresse und lässt sich verlinken.
|
||||||
|
- **Übersicht je Frage:** Balken für Auswahl, Ja/Nein und Bewertung, Summe und
|
||||||
|
Durchschnitt für Zahlen, Matrix für Abstimmungen, Freitexte als Liste (die
|
||||||
|
ersten 50), bei Teilnahme-Feldern eine Teilnehmerliste je Eintrag mit
|
||||||
|
Warteliste. Verwalter sehen dort immer den vollen Namen (Teilnehmer-Name,
|
||||||
|
sonst Kontoname).
|
||||||
|
- **Alle Antworten im Überblick:** dieselbe Tabelle wie im Export direkt auf
|
||||||
|
der Seite (die Nummer öffnet die einzelne Antwort). Bei Zugriff „Ausgewählte
|
||||||
|
Benutzer und Gruppen“ stehen auch die Eingeladenen ohne Antwort darin
|
||||||
|
(Spalte *Rückmeldung*: eingegangen / noch keine Rückmeldung, Gruppen samt
|
||||||
|
Untergruppen); „Nur fehlende Rückmeldungen“ zeigt nur diese. Bei anonymen
|
||||||
|
Formularen bleibt offen, wer teilgenommen hat. Mit aktivem Filter erscheinen
|
||||||
|
nur passende Antworten.
|
||||||
|
- **Einzelantworten** zum Blättern (vor und zurück). Wer das Formular
|
||||||
|
bearbeiten darf, kann eine Antwort löschen; Plätze werden frei, die
|
||||||
|
Warteliste rückt nach. Die Löschung steht im Protokoll und im Löschjournal.
|
||||||
|
- **Antwort ändern** (wer das Formular bearbeiten darf), etwa wenn jemand
|
||||||
|
telefonisch um eine Änderung bittet: dasselbe Formular wie beim Ausfüllen,
|
||||||
|
dazu ein **Vermerk** als Pflichtfeld (warum, auf wessen Wunsch). Gespeichert
|
||||||
|
werden Vermerk, Zeitpunkt, wer geändert hat und welche Fragen sich geändert
|
||||||
|
haben; die Liste steht unter der Antwort („Änderungen durch Verwalter“).
|
||||||
|
Plätze werden neu vergeben, die Warteliste rückt nach. Die Änderung steht im
|
||||||
|
Protokoll (ohne Inhalte). Vermerke gehören zur Datenauskunft der Person
|
||||||
|
(ohne Namen der Verwalter) und werden beim Anonymisieren gelöscht, mit der
|
||||||
|
Antwort ohnehin.
|
||||||
|
- **Teilnehmerlisten als PDF** (nur mit Teilnahme-Feldern, nicht bei anonymen
|
||||||
|
Formularen), etwa zum Abzeichnen vor Ort: je Eintrag eines Teilnahme-Feldes
|
||||||
|
eine Tabelle mit Nummer und Name, freie Plätze als leere Zeilen, darunter
|
||||||
|
die Warteliste. Wahlweise mit Spalte für Unterschriften und jeder
|
||||||
|
Eintrag auf einer neuen Seite. A4 hoch, Ränder wie beim XLSX-Export, oben
|
||||||
|
Logo und Titel, unten „Seite X von Y“, Überschriftenzeile auf jeder Seite.
|
||||||
|
Richtet sich nach dem Filter und steht im Protokoll (Format `lists`).
|
||||||
|
Schrift ist Bitstream Vera aus reportlab (eingebettet); Zeichen, die sie
|
||||||
|
nicht kennt, erscheinen als Grundbuchstabe (ř → r).
|
||||||
|
- **Export** als XLSX, ODS (OpenDocument), PDF oder CSV: eine Zeile je Antwort,
|
||||||
|
eine Spalte je Frage, also dieselbe Tabelle wie in der Übersicht
|
||||||
|
(Teilnehmer-Name in drei Spalten, Abstimmungen eine Spalte je Option, Plätze
|
||||||
|
mit Hinweis auf die Warteliste). „Personenbezogene Daten weglassen“ lässt
|
||||||
|
personenbezogene Fragen und den Kontonamen weg. XLSX und ODS haben ein
|
||||||
|
einziges Blatt: oben Logo, Titel, Filter und Zeitpunkt, darunter die
|
||||||
|
Tabelle mit Autofilter. Das PDF zeigt dieselbe Tabelle im Querformat; die
|
||||||
|
Spalten werden nach Inhalt verteilt, lange Texte umbrochen, bei vielen
|
||||||
|
Spalten wird die Schrift kleiner. Die CSV-Datei verwendet
|
||||||
|
Semikolons und UTF-8 mit BOM. Zellen, die mit `=`, `+`, `-` oder `@`
|
||||||
|
beginnen, werden in der CSV-Datei entschärft. Adressen von Gästen, die das
|
||||||
|
Formular verborgen hält, erscheinen nie. Eingeladene ohne Antwort stehen
|
||||||
|
auch im Export (nicht ohne personenbezogene Daten). Jeder Export steht im Protokoll
|
||||||
|
(Format, Anzahl, mit oder ohne personenbezogene Daten).
|
||||||
|
|
||||||
|
Die PDF-Dateien erzeugt das Paket `reportlab` (neu in `requirements.in`;
|
||||||
|
nach dem Update einmal `scripts/lock.sh` ausführen und beide `.lock`-Dateien
|
||||||
|
einchecken). Fehlt es im Image, zeigt die Seite statt des Knopfes einen
|
||||||
|
Hinweis. XLSX und ODS schreibt Surveybox selbst (ohne zusätzliches Paket). Beide
|
||||||
|
sind für den Druck eingerichtet: A4 quer, Ränder 2 cm oben, 1,2 cm unten, je 1 cm
|
||||||
|
links und rechts, alle Spalten auf einer Seitenbreite (Höhe beliebig),
|
||||||
|
Überschriftenzeile (fett, 20 % grau) auf jeder Seite wiederholt und unten
|
||||||
|
zentriert „Seite X von Y“.
|
||||||
|
|
||||||
|
### Ergebnisse für Teilnehmende
|
||||||
|
|
||||||
|
In den Einstellungen des Formulars legt „Teilnehmende sehen die Ergebnisse“
|
||||||
|
fest, ob und wann: *nie*, *nach der eigenen Teilnahme* oder *nach dem Ende
|
||||||
|
des Formulars*. Die Ergebnisseite (`/f/<token>/results`, mit persönlichem
|
||||||
|
Link `/r/<token>/results`) zeigt nur Zahlen: Balken, Summen, Durchschnitte,
|
||||||
|
Abstimmungen mit bestätigten Terminen, Reihenfolgen und die Belegung von
|
||||||
|
Teilnahme-Feldern. Nie gezeigt werden Freitexte, Dateien und als
|
||||||
|
personenbezogen markierte Fragen; Namen bei Einträgen nur, wenn das Formular
|
||||||
|
sie ohnehin allen zeigt. Der Knopf „Ergebnisse ansehen“ erscheint nach dem
|
||||||
|
Absenden, auf der Seite eines beendeten Formulars und beim persönlichen Link.
|
||||||
|
|
||||||
|
Wer teilgenommen hat, erkennt Surveybox am Konto oder am persönlichen Link.
|
||||||
|
Gäste ohne Link erhalten nach dem Absenden ein Cookie
|
||||||
|
(`surveybox_done_…`, eine Woche, nur für dieses Formular, enthält nur eine
|
||||||
|
Prüfsumme über das Formular und nichts zur Person). Bei sehr wenigen Antworten
|
||||||
|
lassen die Zahlen Rückschlüsse auf einzelne Personen zu; darauf weist die
|
||||||
|
Einstellung hin.
|
||||||
|
|
||||||
|
### Löschfristen
|
||||||
|
|
||||||
|
Antworten bleiben nicht unbegrenzt gespeichert. Die Frist beginnt mit dem Ende
|
||||||
|
des Formulars: dem Enddatum oder dem Zeitpunkt, an dem es von Hand geschlossen
|
||||||
|
wurde. Ein Formular ohne Ende (offen ohne Enddatum, Entwurf, Vorlage) läuft nie
|
||||||
|
ab; wird ein geschlossenes Formular wieder geöffnet, ruht die Frist.
|
||||||
|
|
||||||
|
- Dauer: je Formular in den Einstellungen; leer heißt Standard der Instanz
|
||||||
|
(2 Jahre, unter *Administration → Einstellungen → Aufbewahrung der Antworten*).
|
||||||
|
- Danach, je nach Einstellung „Wenn die Löschfrist abläuft oder eine Person
|
||||||
|
gelöscht wird“:
|
||||||
|
- *anonymisieren*: Konto, Gast-Adresse und persönlicher Link werden von der
|
||||||
|
Antwort getrennt, Antworten auf personenbezogene Fragen (und deren Dateien)
|
||||||
|
gelöscht; der Rest bleibt für das Ergebnis.
|
||||||
|
- *löschen*: die Antworten verschwinden vollständig.
|
||||||
|
- In beiden Fällen entfallen die Merker gegen doppelte Teilnahme und der
|
||||||
|
Versandstand der Folge-Mails. Kommentare verlieren ihre Autorenangabe bzw.
|
||||||
|
werden beim Löschen mitgelöscht.
|
||||||
|
- Der Eigentümer bekommt 14 Tage vorher eine Mail. Kommt der Hinweis später
|
||||||
|
(kurze Frist, oder bei bestehenden Formularen direkt nach dem Update), wird
|
||||||
|
frühestens sieben Tage nach dem Hinweis gelöscht.
|
||||||
|
- Einstellungen und Antwortenseite zeigen das geplante Datum. Das Protokoll
|
||||||
|
vermerkt jede Anwendung (Formular, Art, Anzahl), ohne Inhalte.
|
||||||
|
- Gast-Adressen ohne Antwort werden nach sieben Tagen gelöscht.
|
||||||
|
|
||||||
|
Der Worker prüft die Fristen stündlich beim Aufräumen.
|
||||||
|
|
||||||
|
### Personen löschen
|
||||||
|
|
||||||
|
- *Eigenes Konto*: unter *Konto → Konto löschen*. Nur innerhalb von zehn
|
||||||
|
Minuten nach der Anmeldung; sonst meldet die Seite ab und fragt erneut nach
|
||||||
|
der Anmeldung. Für jedes eigene Formular wählt man, ob es an eine Person
|
||||||
|
übergeht, die es mitbearbeitet, oder mit allen Antworten gelöscht wird.
|
||||||
|
- *Administrator*: in der Benutzerverwaltung bei der Person, ebenfalls nur kurz
|
||||||
|
nach der Anmeldung. Die Formulare der Person gehen gesammelt an einen
|
||||||
|
Ersteller oder Administrator oder werden gelöscht. Der letzte aktive
|
||||||
|
Administrator lässt sich nicht löschen.
|
||||||
|
- *Gäste*: auf *Meine Links* unter „Meine Daten löschen“. Ein Link per Mail
|
||||||
|
(24 Stunden gültig) führt zu einer Übersicht; erst die Bestätigung dort
|
||||||
|
löscht alles, was an der Adresse hängt. Unbekannte Adressen bekommen
|
||||||
|
dieselbe Antwort, aber keine Mail.
|
||||||
|
|
||||||
|
Vor jeder Löschung zeigt eine Übersicht, was geschieht:
|
||||||
|
|
||||||
|
| Daten | Verhalten |
|
||||||
|
| --- | --- |
|
||||||
|
| Konto, Passkeys, Sitzungen, Einstellungen, Mailprotokoll | gelöscht |
|
||||||
|
| Gast-Adresse, Bestätigung, Mailprotokoll | gelöscht |
|
||||||
|
| Antworten | je Formular anonymisiert oder gelöscht (wie bei der Löschfrist) |
|
||||||
|
| Plätze in laufenden Formularen | freigegeben, die Warteliste rückt nach |
|
||||||
|
| Plätze in beendeten Formularen | bleiben beim Anonymisieren als anonyme Teilnahme gezählt |
|
||||||
|
| Kommentare eines Kontos | bleiben, Autor „Gelöschter Benutzer“ |
|
||||||
|
| Protokoll | nur „Gelöschtes Konto Nr. …“, ohne Namen oder Adresse |
|
||||||
|
|
||||||
|
Gelöschte Daten bleiben bis zur Rotation in den Sicherungen. Jede Löschung
|
||||||
|
steht deshalb zusätzlich im Löschjournal `/data/erasures.jsonl` (nur Kennungen).
|
||||||
|
Die Wiederherstellung (`… web restore …`, siehe Sicherungen) legt eine Marke ab; sobald Web und Worker wieder laufen
|
||||||
|
und das Schema aktuell ist, wendet der Worker alle Löschungen seit dem
|
||||||
|
Zeitpunkt der Sicherung erneut an. Auch angewendete Löschfristen und über den
|
||||||
|
persönlichen Link gelöschte Antworten stehen im Journal. Einträge, die älter
|
||||||
|
als die älteste vorhandene Sicherung sind, entfernt der Worker. Wer `/data`
|
||||||
|
mit einem eigenen Werkzeug zurückspielt, spielt auch das Journal zurück; dann
|
||||||
|
greift dieser Schutz nicht.
|
||||||
|
|
||||||
|
### Datenexport für Betroffene
|
||||||
|
|
||||||
|
Auskunft (Art. 15 DSGVO) und Datenübertragbarkeit (Art. 20) als JSON-Datei:
|
||||||
|
|
||||||
|
- *Angemeldete*: *Konto → Meine Daten herunterladen*: Konto, Passkeys (nur
|
||||||
|
Namen und Daten), Sitzungen, Benachrichtigungseinstellungen, Gruppen,
|
||||||
|
Antworten mit Plätzen und Vermerken, Kommentare, eigene Formulare, erhaltene Folge-Mails,
|
||||||
|
Mailprotokoll (ohne Inhalte) und die eigenen Einträge im Protokoll.
|
||||||
|
- *Gäste*: auf *Meine Links* unter „Meine Daten herunterladen“ per Mail-Link
|
||||||
|
(24 Stunden gültig): Adresse, Antworten, Folge-Mails, Mailprotokoll. Auf der
|
||||||
|
Seite des persönlichen Links lässt sich außerdem diese eine Antwort
|
||||||
|
herunterladen, auch ohne Adresse.
|
||||||
|
- *Administratoren*: in der Benutzerverwaltung bei der Person („Daten
|
||||||
|
exportieren“) und für Gast-Adressen unter der Benutzerliste.
|
||||||
|
|
||||||
|
Hochgeladene Dateien stehen mit Name und Größe in der Datei; ihr Inhalt bleibt
|
||||||
|
über die Antwort abrufbar. Antworten in anonymen Formularen und anonymisierte
|
||||||
|
Antworten lassen sich niemandem zuordnen und fehlen deshalb. Jeder Export
|
||||||
|
steht ohne Inhalte im Protokoll. Die Datei wird nie zwischengespeichert
|
||||||
|
(`Cache-Control: no-store`).
|
||||||
|
|
||||||
|
### Gestaltung (White-Labeling)
|
||||||
|
|
||||||
|
*Administration → Einstellungen → Gestaltung* (`/admin/appearance`):
|
||||||
|
|
||||||
|
- **Logo:** Ohne eigenes Logo zeigt Surveybox sein eigenes Zeichen (eine Box mit
|
||||||
|
Haken) in der Kopfzeile und als Favicon. Ein eigenes Logo (PNG, JPEG oder WebP,
|
||||||
|
höchstens 5 MB; kein SVG, weil SVG-Dateien Skripte enthalten können) wird wie
|
||||||
|
jedes Bild neu berechnet und ohne Metadaten in drei Fassungen unter
|
||||||
|
`/data/branding` abgelegt: Logo für Kopfzeile und Exporte, Favicon (64 x 64)
|
||||||
|
und Icon für den Startbildschirm (180 x 180). Leere Ränder werden
|
||||||
|
abgeschnitten. Zusätzlich lässt sich ein **Logo für die dunkle Darstellung**
|
||||||
|
hochladen (z. B. mit heller Schrift).
|
||||||
|
- **Name der Anwendung:** ersetzt „Surveybox“ in Kopfzeile, Browser-Tab,
|
||||||
|
Startseite und in E-Mails (Betreff und Fußzeile). Der Absendername der Mails
|
||||||
|
steht weiter unter *E-Mail*.
|
||||||
|
- **Darstellung:** automatisch (wie im Browser), immer hell oder immer dunkel.
|
||||||
|
- **Farben:** Primärfarbe (Knöpfe, Links), Akzentfarbe (Balken, Sterne,
|
||||||
|
Auswahl, Hinweiskästen), Hintergrund und Text, jeweils mit „Standard“. Die
|
||||||
|
Farben gelten für die helle Darstellung; die dunkle leitet lesbare Töne der
|
||||||
|
Primär- und Akzentfarbe ab. Hinweise und Linien werden aus Text und
|
||||||
|
Hintergrund berechnet. Der Kontrast wird nach WCAG 2.1 (AA) geprüft; ist er
|
||||||
|
zu gering, warnt die Seite, speichert aber trotzdem.
|
||||||
|
- **Schrift:** eigene Schriftdatei (WOFF2, WOFF, TTF oder OTF, höchstens 2 MB),
|
||||||
|
ausgeliefert vom eigenen Server. Die Datei wird an ihren ersten Bytes geprüft.
|
||||||
|
- **Startseite:** eigener Text für alle Besucher.
|
||||||
|
- **Fußzeile:** eigener Text, Links zu Impressum und Datenschutzerklärung (nur
|
||||||
|
`https://`), auf jeder Seite, auch in eingebetteten Formularen. Dahinter steht
|
||||||
|
immer „Surveybox <Version>“; mit `SURVEYBOX_SOURCE_URL` wird daraus ein Link
|
||||||
|
zum Quellcode (AGPL: Wer eine geänderte Fassung als Dienst anbietet, muss den
|
||||||
|
Nutzern den Quellcode zugänglich machen).
|
||||||
|
- **Eigenes CSS** für Sonderfälle (bis 20 000 Zeichen), nach allen anderen
|
||||||
|
Stilen geladen. Die Content-Security-Policy bleibt streng: fremde Adressen für
|
||||||
|
Bilder oder Schriften blockiert der Browser.
|
||||||
|
- **Export und Import:** alles samt Logos und Schrift als eine JSON-Datei, etwa
|
||||||
|
für eine zweite Instanz. Beim Import werden Eingaben und Bilder wie beim
|
||||||
|
Hochladen geprüft; Logo und Schrift werden nur ersetzt, wenn die Datei sie
|
||||||
|
enthält. „Name, Farben und Texte zurücksetzen“ stellt den Standard wieder her.
|
||||||
|
|
||||||
|
Farben, Schrift und eigenes CSS liefert `/branding/theme.css` aus, nach
|
||||||
|
`app.css` geladen und über die Version im Link zwischengespeichert. Alle Texte
|
||||||
|
landen escaped im HTML; nichts davon wird als Skript ausgeführt. Jede Änderung
|
||||||
|
steht im Protokoll („Gestaltung geändert“). Der Stand liegt in
|
||||||
|
`/data/branding` (Logo, Schrift, `appearance.json`) im Volume, nicht in der
|
||||||
|
Datenbanksicherung: Wer `/data` nicht als Ganzes sichert, legt den Export der
|
||||||
|
Gestaltung zu den Sicherungen.
|
||||||
|
|
||||||
|
### Einbinden in die Nextcloud
|
||||||
|
|
||||||
|
Surveybox lässt sich als Menüeintrag in die Nextcloud einbinden (App
|
||||||
|
„External sites“), ohne Single Sign-on: Man meldet sich im Rahmen einmal bei
|
||||||
|
Surveybox an.
|
||||||
|
|
||||||
|
1. **Gleiche Domain:** Surveybox und Nextcloud müssen unter derselben
|
||||||
|
Hauptdomain laufen, z. B. `umfrage.example.de` neben `cloud.example.de`.
|
||||||
|
Sonst gelten die Cookies im Rahmen als fremd, und Browser blockieren sie:
|
||||||
|
Anmelden und Absenden gehen dann nicht.
|
||||||
|
2. **Einbetten erlauben:** in der `.env`
|
||||||
|
`SURVEYBOX_FRAME_ANCESTORS=https://cloud.example.de` (nur `https`, mehrere
|
||||||
|
durch Leerzeichen getrennt), dann `docker compose up -d`. Ohne Eintrag ist
|
||||||
|
Einbetten verboten (`frame-ancestors 'none'`, `X-Frame-Options: DENY`). Mit
|
||||||
|
Eintrag erlaubt die Content-Security-Policy genau diese Seiten;
|
||||||
|
`X-Frame-Options` entfällt dann, weil es nur eine Adresse kennt.
|
||||||
|
3. **Nextcloud:** App „External sites“ installieren, unter *Verwaltung →
|
||||||
|
Externe Seiten* einen Eintrag anlegen: Name z. B. „Umfragen“, Adresse
|
||||||
|
`https://umfrage.example.de/?embed=1`, Symbol nach Wahl; die Option zum
|
||||||
|
Umleiten (Öffnen außerhalb der Nextcloud) bleibt aus. Die App erlaubt die
|
||||||
|
Adresse in der Content-Security-Policy der Nextcloud selbst.
|
||||||
|
|
||||||
|
Im Rahmen zeigt Surveybox eine **kompakte Darstellung**: schmale Leiste mit
|
||||||
|
Navigation und Sprachen, ohne Logo und Fußzeile (Impressum und
|
||||||
|
Datenschutzerklärung bleiben als Links unten), weniger Abstände. Erkannt wird
|
||||||
|
der Rahmen am Browser (`Sec-Fetch-Dest: iframe`); `?embed=1` schaltet die
|
||||||
|
Darstellung zusätzlich fest ein (Cookie `surveybox_embed`), `?embed=0` wieder
|
||||||
|
aus. „Neuer Tab ↗“ öffnet die aktuelle Seite außerhalb des Rahmens.
|
||||||
|
|
||||||
|
Einschränkungen: **Passkeys** funktionieren im Rahmen nicht, weil die
|
||||||
|
Nextcloud dem Rahmen die nötige Berechtigung nicht gibt; im Rahmen mit Passwort
|
||||||
|
(und Authenticator-App) anmelden oder über „Neuer Tab“. Einzelne Formulare
|
||||||
|
lassen sich auf freigegebenen Seiten derselben Domain per
|
||||||
|
`<iframe src="…/f/<token>?embed=1">` einbetten (der Formular-Editor zeigt den
|
||||||
|
Code, sobald Einbetten erlaubt ist). Auf fremden Domains (z. B. der Website
|
||||||
|
eines Vereins) bitte verlinken statt einbetten.
|
||||||
|
|
||||||
|
Prüfliste für den Test in der Nextcloud:
|
||||||
|
|
||||||
|
- Menüeintrag öffnet Surveybox im Rahmen, kompakte Darstellung, Sprache wie
|
||||||
|
im Browser.
|
||||||
|
- Anmelden mit Passwort und Authenticator-App im Rahmen; Abmelden.
|
||||||
|
- Formular ausfüllen und absenden (auch mit Datei-Upload), Dankeseite,
|
||||||
|
„Ergebnisse ansehen“.
|
||||||
|
- Formular anlegen, Vorschau im Editor, Antworten ansehen, Export
|
||||||
|
herunterladen.
|
||||||
|
- „Neuer Tab ↗“ öffnet dieselbe Seite normal; danach im Rahmen weiter
|
||||||
|
angemeldet.
|
||||||
|
- Ohne `SURVEYBOX_FRAME_ANCESTORS` zeigt die Nextcloud eine Fehlermeldung
|
||||||
|
statt der Seite (Einbetten verboten).
|
||||||
|
|
||||||
|
### Bilder, Videos und Dateien
|
||||||
|
|
||||||
|
- **Bilder zu Fragen:** JPEG, PNG oder WebP. Gespeichert wird eine neu
|
||||||
|
berechnete WebP-Fassung ohne Metadaten (Standort, Kamera), höchstens
|
||||||
|
2560 Pixel groß, dazu ein Vorschaubild. SVG ist nicht erlaubt. Jedes Bild
|
||||||
|
braucht eine Beschreibung für Screenreader.
|
||||||
|
- **Bildauswahl:** Einfach- und Mehrfachauswahl mit Darstellung
|
||||||
|
*Bildkacheln*; jedes Bild hängt an seiner Antwortmöglichkeit.
|
||||||
|
- **Videos:** MP4 oder WebM, optional mit Vorschaubild und Untertiteln
|
||||||
|
(WebVTT). Surveybox liefert sie selbst aus, mit Vorspulen.
|
||||||
|
- **Externe Videos:** YouTube, Vimeo und PeerTube-Instanzen, die ein
|
||||||
|
Administrator unter *Einstellungen* freigibt. Das Video lädt erst nach
|
||||||
|
einem Klick der teilnehmenden Person; bis dahin gehen keine Daten an den
|
||||||
|
Anbieter. Nur freigegebene Anbieter stehen in der Content-Security-Policy.
|
||||||
|
- **Eigene Video-Quellen:** ebenfalls unter *Einstellungen*, je Quelle Host
|
||||||
|
(optional mit Port, nur HTTPS) und Art: *MediaCMS* (Adresse
|
||||||
|
`…/view?m=…`), *Player-Seite* (wird als Rahmen eingebettet) oder
|
||||||
|
*Videodatei* (MP4/WebM, etwa vom eigenen NAS, direkt abgespielt). Für eigene
|
||||||
|
Server lässt sich der Klick vorab abschalten.
|
||||||
|
- **Datei-Upload (Fragetyp):** erlaubte Arten je Frage (PDF, Bilder,
|
||||||
|
Office, Text/CSV, ZIP), Anzahl und Größe einstellbar. Die Art wird am
|
||||||
|
Inhalt geprüft, nicht an der Endung. Bilder verlieren ihre Metadaten.
|
||||||
|
Hochgeladene Dateien sieht nur, wer die Antworten sehen darf, und nur als
|
||||||
|
Download. Dateien aus nicht abgeschickten Formularen verschwinden nach
|
||||||
|
24 Stunden. Je Adresse höchstens 100 neue Dateien pro Stunde.
|
||||||
|
|
||||||
|
Größengrenzen je Art stehen unter *Einstellungen* (nur Administratoren),
|
||||||
|
höchstens bis `SURVEYBOX_MAX_UPLOAD_MB` (Standard 250). **Der Reverse Proxy
|
||||||
|
muss Anfragen dieser Größe zulassen**, bei nginx etwa
|
||||||
|
`client_max_body_size 250m;`, sonst lehnt schon der Proxy große Videos ab.
|
||||||
|
|
||||||
|
Dateien liegen unter `/data/media`, Uploads werden zuerst nach `/data/tmp`
|
||||||
|
geschrieben (nicht ins kleine tmpfs).
|
||||||
|
|
||||||
|
### Wichtige Einstellungen zur Sicherheit
|
||||||
|
|
||||||
|
- `SURVEYBOX_SECRET_KEY` nie ändern, sobald Konten existieren. Daraus sind die
|
||||||
|
Verschlüsselung der TOTP-Geheimnisse und die Wiederherstellungscodes abgeleitet.
|
||||||
|
- `SURVEYBOX_TRUSTED_PROXIES` auf die Adresse setzen, von der der Reverse Proxy
|
||||||
|
ankommt. Nur dann zählt Surveybox Fehlversuche je Besucher statt für alle
|
||||||
|
gemeinsam.
|
||||||
|
- Surveybox verbietet bis zur Phase 9 das Einbetten in fremde Seiten
|
||||||
|
(`frame-ancestors 'none'`). Die Einbindung in Nextcloud wird dann einstellbar.
|
||||||
|
|
||||||
|
## Externer Datenbankserver
|
||||||
|
|
||||||
|
1. In der `.env` `COMPOSE_PROFILES=` leer setzen und `SURVEYBOX_DB_HOST` usw.
|
||||||
|
eintragen. Für Verbindungen über das Netz `SURVEYBOX_DB_SSLMODE=verify-full`
|
||||||
|
und `SURVEYBOX_DB_SSLROOTCERT` setzen.
|
||||||
|
2. Auf dem Server Benutzer und Datenbank anlegen:
|
||||||
|
```sql
|
||||||
|
CREATE ROLE surveybox LOGIN PASSWORD '...';
|
||||||
|
CREATE DATABASE surveybox OWNER surveybox;
|
||||||
|
```
|
||||||
|
Soll eine vorhandene Datenbank mitbenutzt werden, braucht der Benutzer dort
|
||||||
|
das Recht `CREATE` (für das Schema `surveybox`).
|
||||||
|
3. Unterstützt sind PostgreSQL-Server bis Version 19; das Image enthält die
|
||||||
|
Sicherungswerkzeuge der Versionen 17, 18 und 19.
|
||||||
|
|
||||||
|
## Updates
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git pull
|
||||||
|
docker compose build
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
Beim Start des neuen `web`-Containers passiert Folgendes:
|
||||||
|
|
||||||
|
1. Migrationssperre setzen; ein zweiter Prozess wartet.
|
||||||
|
2. Stand der Datenbank prüfen. Ist die Datenbank neuer als das Image (z. B.
|
||||||
|
nach einem versehentlichen Zurückgehen auf ein altes Image), startet
|
||||||
|
Surveybox nicht und ändert nichts.
|
||||||
|
3. Sicherung nach `/data/backups/pre-upgrade/` schreiben und prüfen. Schlägt
|
||||||
|
die Sicherung fehl, findet kein Update statt.
|
||||||
|
4. Alle ausstehenden Migrationen in **einer** Transaktion ausführen. Schlägt
|
||||||
|
eine fehl, wird alles zurückgerollt: Die Datenbank ist unverändert. Der
|
||||||
|
Container bleibt als „unhealthy“ stehen, statt sich ständig neu zu starten;
|
||||||
|
der Grund steht in `docker compose logs web`. Nach der Behebung
|
||||||
|
`docker compose up -d --force-recreate web` (oder zurück zur alten Version).
|
||||||
|
|
||||||
|
Nach einem fehlgeschlagenen Update auf die vorherige Version zurück:
|
||||||
|
`git checkout <vorheriges-tag> && docker compose build && docker compose up -d`.
|
||||||
|
Die Datenbank muss dafür nicht zurückgespielt werden.
|
||||||
|
|
||||||
|
War das Update erfolgreich, die neue Version hat aber einen Fehler, gehört
|
||||||
|
zur alten Version auch der alte Datenbankstand:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose stop web worker
|
||||||
|
docker compose run --rm --no-deps web restore pre-upgrade/<datei>.dump --yes
|
||||||
|
git checkout <vorheriges-tag> && docker compose build && docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
## Sicherungen
|
||||||
|
|
||||||
|
| Verzeichnis in `/data/backups` | Entsteht | Aufbewahrung |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `daily/` | täglich ab `SURVEYBOX_BACKUP_HOUR` (Worker) | `SURVEYBOX_BACKUP_KEEP_DAILY` Stück |
|
||||||
|
| `pre-upgrade/` | vor jedem Update | `SURVEYBOX_BACKUP_KEEP_PRE_UPGRADE` Stück |
|
||||||
|
| `manual/` | `docker compose exec web python -m surveybox.cli backup` | 20 Stück |
|
||||||
|
| `pre-restore/` | automatisch vor jeder Wiederherstellung | 20 Stück |
|
||||||
|
|
||||||
|
Sicherungen sind `pg_dump`-Dateien im Custom-Format, nur lesbar für den
|
||||||
|
Container-Benutzer (UID 10001). Jede Sicherung wird nach dem Schreiben mit
|
||||||
|
`pg_restore --list` geprüft; unvollständige Dateien bekommen nie den
|
||||||
|
endgültigen Namen.
|
||||||
|
|
||||||
|
Bilder, Videos und hochgeladene Dateien gehören mit zur Sicherung: Neben
|
||||||
|
jeder `.dump`-Datei liegt eine Liste der Dateien (`.media`), die Dateien
|
||||||
|
selbst einmal unter `/data/backups/media` (als harter Link, also ohne
|
||||||
|
zusätzlichen Platz). Beim Wiederherstellen legt Surveybox fehlende Dateien
|
||||||
|
zurück. Gelöscht wird eine Datei im Volume erst, wenn nichts mehr auf sie
|
||||||
|
verweist und sie älter als einen Tag ist.
|
||||||
|
|
||||||
|
Die Sicherungen liegen im Docker-Volume. Für eine Kopie außerhalb des Hosts
|
||||||
|
das Volume-Verzeichnis (`docker volume inspect surveybox_data`) in die
|
||||||
|
bestehende Datensicherung aufnehmen, z. B. Borgmatic.
|
||||||
|
|
||||||
|
**Wiederherstellen:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose stop web worker
|
||||||
|
docker compose run --rm --no-deps web restore daily/<datei>.dump --yes
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
Vor dem Zurückspielen sichert Surveybox den aktuellen Stand nach
|
||||||
|
`pre-restore/`. Das Ersetzen des Schemas und das Einspielen laufen in einer
|
||||||
|
Transaktion: Bricht etwas ab, bleibt der bisherige Stand erhalten. War die
|
||||||
|
Sicherung älter als das Image, migriert der nächste Start sie automatisch.
|
||||||
|
|
||||||
|
## Mehrere Instanzen auf einem Host
|
||||||
|
|
||||||
|
Jede Instanz bekommt ein eigenes Verzeichnis mit eigener `.env`:
|
||||||
|
`COMPOSE_PROJECT_NAME` und `SURVEYBOX_HTTP_PORT` müssen sich unterscheiden.
|
||||||
|
Instanzen teilen weder Volumes noch Datenbanken.
|
||||||
|
|
||||||
|
## Entwicklung
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m venv .venv && . .venv/bin/activate
|
||||||
|
pip install --require-hashes --no-deps -r requirements.lock -r requirements-dev.lock
|
||||||
|
pybabel compile -D messages -d surveybox/locale
|
||||||
|
|
||||||
|
ruff check . && mypy && pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
Tests mit dem Marker `db` brauchen eine Wegwerf-Datenbank (wird geleert!):
|
||||||
|
`SURVEYBOX_TEST_DB=1` und die `SURVEYBOX_DB_*`-Variablen setzen.
|
||||||
|
|
||||||
|
### CI mit Gitea Actions
|
||||||
|
|
||||||
|
`.gitea/workflows/ci.yml` hat drei Jobs:
|
||||||
|
|
||||||
|
| Job | Wann | Was |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `checks` | jeder Push und Pull Request | Ruff, Mypy, pip-audit, Abgleich Modelle/Migrationen, Tests gegen PostgreSQL 18 |
|
||||||
|
| `image` | nach `checks` | Image bauen, `scripts/upgrade-test.sh`: Installation, Update vom letzten Release, Neustart, Sicherung und Wiederherstellung |
|
||||||
|
| `audit` | montags früh und von Hand | bekannte Sicherheitslücken in den Abhängigkeiten |
|
||||||
|
|
||||||
|
Voraussetzungen am act_runner: Gitea mit aktivierten Actions, ein Runner mit
|
||||||
|
Label `ubuntu-latest` und Docker. Der Job `image` braucht den Docker-Daemon
|
||||||
|
des Runners (act_runner reicht ihn standardmäßig durch). Zugriff auf den
|
||||||
|
Docker-Socket bedeutet Root-Rechte auf dem Host: Den Runner daher auf einem
|
||||||
|
eigenen Test-Host oder in einer VM betreiben, nicht auf dem Produktiv-Host.
|
||||||
|
Das Subnetz des Wegwerf-Stacks steht in `UPGRADE_TEST_SUBNET` im Workflow.
|
||||||
|
|
||||||
|
Gitea kennt keinen Dependabot. Neue Versionen der Abhängigkeiten holt
|
||||||
|
`UPGRADE=1 ./scripts/lock.sh`; der Job `audit` meldet bekannte Lücken.
|
||||||
|
|
||||||
|
### Migrationen
|
||||||
|
|
||||||
|
Neue Migration nach einer Änderung an `surveybox/models`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m surveybox.cli migrate # Datenbank auf aktuellen Stand
|
||||||
|
alembic revision --autogenerate -m "kurze beschreibung"
|
||||||
|
```
|
||||||
|
|
||||||
|
Regeln, damit Updates nie hängen bleiben:
|
||||||
|
|
||||||
|
- Kleine Schritte; jede Migration muss auch nach einem Abbruch erneut laufen können.
|
||||||
|
- Daten bereinigen, bevor eine Spalte verkleinert, `NOT NULL` oder eindeutig wird.
|
||||||
|
- Alles muss in der gemeinsamen Transaktion laufen: kein
|
||||||
|
`CREATE INDEX CONCURRENTLY`, kein `autocommit_block`.
|
||||||
|
- Aufwändige Datenpflege als Hintergrundaufgabe im Worker, nicht in der Migration.
|
||||||
|
- Nie eine veröffentlichte Migration nachträglich ändern; stattdessen eine neue anlegen.
|
||||||
|
|
||||||
|
### Übersetzungen
|
||||||
|
|
||||||
|
Texte im Code sind englisch und werden mit `_()` bzw. `gettext()` markiert.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pybabel extract -F babel.cfg -o surveybox/locale/messages.pot .
|
||||||
|
pybabel update -i surveybox/locale/messages.pot -d surveybox/locale -D messages
|
||||||
|
# messages.po in de, en, fr übersetzen
|
||||||
|
pybabel compile -D messages -d surveybox/locale
|
||||||
|
```
|
||||||
|
|
||||||
|
Ein Test prüft, dass alle drei Kataloge vollständig sind und jeden Text der
|
||||||
|
Vorlagen enthalten.
|
||||||
|
|
||||||
|
## Weitere Unterlagen
|
||||||
|
|
||||||
|
- `docs/betrieb.md`: Routinen, Überwachung, alle Einstellungen der `.env`,
|
||||||
|
Vorgehen bei Störungen.
|
||||||
|
- `docs/sicherheit.md`: Umsetzung nach OWASP ASVS (Stufe 2), automatische
|
||||||
|
Prüfungen, Ablauf und Ergebnisprotokoll der Abnahme
|
||||||
|
(`scripts/zap-baseline.sh`, `scripts/loadtest.py`, Update-Test mit Daten).
|
||||||
|
- `docs/datenschutz.md`: Verzeichnis von Verarbeitungstätigkeiten,
|
||||||
|
Rechtsgrundlagen, TOM, Cookies, Betroffenenrechte, Baustein für die
|
||||||
|
Datenschutzerklärung.
|
||||||
|
|
||||||
|
## Lizenz
|
||||||
|
|
||||||
|
Surveybox steht unter der GNU Affero General Public License, Version 3 oder
|
||||||
|
später (AGPL-3.0-or-later). Wer eine veränderte Version als Dienst anbietet,
|
||||||
|
muss den Quellcode der Änderungen bereitstellen.
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
# Nur für die Entwicklung (`alembic revision --autogenerate -m "..."`).
|
||||||
|
# Im Betrieb migriert `surveybox migrate` bzw. der Start des Web-Dienstes.
|
||||||
|
[alembic]
|
||||||
|
script_location = surveybox/migrations
|
||||||
|
file_template = %%(rev)s_%%(slug)s
|
||||||
|
prepend_sys_path = .
|
||||||
|
|
||||||
|
[loggers]
|
||||||
|
keys = root,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARNING
|
||||||
|
handlers = console
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
[python: surveybox/**.py]
|
||||||
|
[jinja2: surveybox/web/templates/**.html]
|
||||||
|
extensions = jinja2.ext.i18n
|
||||||
|
[jinja2: surveybox/web/templates/mail/**.txt]
|
||||||
|
extensions = jinja2.ext.i18n
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
#
|
||||||
|
# Eine Surveybox-Instanz. Für eine zweite Instanz auf demselben Host das
|
||||||
|
# Verzeichnis kopieren und eine eigene .env anlegen (anderer Projektname,
|
||||||
|
# anderer Port). Instanzen teilen nichts.
|
||||||
|
#
|
||||||
|
# Externe Datenbank: in der .env COMPOSE_PROFILES leer lassen und die
|
||||||
|
# Verbindungsdaten eintragen. Der Dienst "db" startet dann nicht.
|
||||||
|
#
|
||||||
|
# Netz: Das Subnetz des Stacks steht fest in der .env (SURVEYBOX_NET_SUBNET),
|
||||||
|
# damit Docker sich nicht selbst einen Bereich nimmt, der mit dem LAN, einem
|
||||||
|
# VPN oder anderen Stacks kollidiert. Jede Instanz braucht ein eigenes Subnetz.
|
||||||
|
|
||||||
|
name: ${COMPOSE_PROJECT_NAME:-surveybox}
|
||||||
|
|
||||||
|
x-app: &app
|
||||||
|
image: ${SURVEYBOX_IMAGE:-surveybox:local}
|
||||||
|
build: .
|
||||||
|
env_file: ${SURVEYBOX_ENV_FILE:-.env}
|
||||||
|
restart: unless-stopped
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp:size=64m,mode=1777
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
volumes:
|
||||||
|
- data:/data
|
||||||
|
stop_grace_period: 30s
|
||||||
|
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: postgres:18-alpine
|
||||||
|
profiles: [db]
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: ${SURVEYBOX_DB_NAME:-surveybox}
|
||||||
|
POSTGRES_USER: ${SURVEYBOX_DB_USER:-surveybox}
|
||||||
|
POSTGRES_PASSWORD: ${SURVEYBOX_DB_PASSWORD:?SURVEYBOX_DB_PASSWORD fehlt in der .env}
|
||||||
|
POSTGRES_INITDB_ARGS: "--encoding=UTF8 --data-checksums"
|
||||||
|
volumes:
|
||||||
|
# Ab PostgreSQL 18 wird /var/lib/postgresql eingebunden, nicht .../data.
|
||||||
|
- pgdata:/var/lib/postgresql
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\""]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
|
||||||
|
web:
|
||||||
|
<<: *app
|
||||||
|
command: ["web"]
|
||||||
|
ports:
|
||||||
|
- "${SURVEYBOX_HTTP_BIND:-127.0.0.1}:${SURVEYBOX_HTTP_PORT:-8000}:8000"
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
required: false
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-m", "surveybox.cli", "healthcheck"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 300s
|
||||||
|
|
||||||
|
worker:
|
||||||
|
<<: *app
|
||||||
|
command: ["worker"]
|
||||||
|
depends_on:
|
||||||
|
web:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-m", "surveybox.cli", "healthcheck", "--worker"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 120s
|
||||||
|
|
||||||
|
networks:
|
||||||
|
default:
|
||||||
|
ipam:
|
||||||
|
driver: default
|
||||||
|
config:
|
||||||
|
- subnet: ${SURVEYBOX_NET_SUBNET:?SURVEYBOX_NET_SUBNET fehlt in der .env}
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
data:
|
||||||
|
pgdata:
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
# Betriebshandbuch
|
||||||
|
|
||||||
|
Kurzfassung für den laufenden Betrieb einer Instanz. Ausführliche
|
||||||
|
Beschreibungen stehen im README; dieses Dokument bündelt Routinen,
|
||||||
|
Einstellungen und das Vorgehen bei Störungen.
|
||||||
|
|
||||||
|
## Aufbau
|
||||||
|
|
||||||
|
- `web` (Oberfläche, Port 8000 nur auf `127.0.0.1`, davor ein Reverse Proxy mit
|
||||||
|
TLS) und `worker` (Mails, Erinnerungen, Löschfristen, Sicherungen) aus
|
||||||
|
demselben Image.
|
||||||
|
- PostgreSQL 18 im Dienst `db` oder extern.
|
||||||
|
- Volume `/data`: `backups/`, `media/` (Uploads, Bilder, Videos), `branding/`
|
||||||
|
(Logo, Schrift, Gestaltung), `erasures.jsonl` (Löschjournal).
|
||||||
|
- Container ohne Root, schreibgeschützt, ohne Capabilities; `/tmp` als tmpfs.
|
||||||
|
|
||||||
|
## Routinen
|
||||||
|
|
||||||
|
| Wann | Was | Wie |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| täglich (automatisch) | Sicherung der Datenbank samt Dateiliste, Prüfung, Aufräumen | Worker ab `SURVEYBOX_BACKUP_HOUR`; Ergebnis unter *Protokoll* |
|
||||||
|
| stündlich (automatisch) | Löschfristen, abgelaufene Sitzungen, Tokens, unbestätigte Gast-Adressen, Mail-Warteschlange | Worker |
|
||||||
|
| wöchentlich | Sicherungen außerhalb des Hosts kopieren (`/data/backups`, inkl. `media/`) | eigener Backup-Job (z. B. Borgmatic) |
|
||||||
|
| wöchentlich (CI) | bekannte Lücken in Abhängigkeiten | CI-Job `audit`; bei Fund: `UPGRADE=1 scripts/lock.sh`, testen, ausliefern |
|
||||||
|
| monatlich | *Protokoll* sichten (fehlgeschlagene Anmeldungen, Exporte, Löschungen); *E-Mail* auf fehlgeschlagene Mails prüfen | Oberfläche |
|
||||||
|
| bei jedem Update | `git pull && docker compose build && docker compose up -d`; Sicherung vor dem Update entsteht automatisch | README „Updates“ |
|
||||||
|
| jährlich | Wiederherstellung auf einer Testinstanz proben; Sicherheitstest wiederholen (`docs/sicherheit.md`) | README „Sicherungen“ |
|
||||||
|
|
||||||
|
## Überwachung
|
||||||
|
|
||||||
|
- Gesundheitsprüfung der Container: `docker compose ps` (beide `healthy`).
|
||||||
|
- Von außen: `GET /health/ready` liefert 200, solange Web und Datenbank
|
||||||
|
erreichbar sind und das Schema aktuell ist, sonst 503 (für Uptime-Kuma o. ä.);
|
||||||
|
`GET /health/live` prüft nur den Webprozess.
|
||||||
|
- Logs: `docker compose logs -f web worker`. Keine Antwortinhalte, keine
|
||||||
|
Geheimnisse in den Logs; persönliche Links sind vom Zugriffslog
|
||||||
|
ausgenommen.
|
||||||
|
|
||||||
|
## Einstellungen (`.env`)
|
||||||
|
|
||||||
|
| Variable | Standard | Bedeutung |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `SURVEYBOX_PUBLIC_URL` | – | Öffentliche Adresse; nach der Installation nicht mehr ändern (Passkeys) |
|
||||||
|
| `SURVEYBOX_SECRET_KEY` | – | mind. 32 Zeichen; nie ändern, sobald Konten existieren |
|
||||||
|
| `SURVEYBOX_DEFAULT_LANGUAGE` | `de` | `de`, `en` oder `fr` |
|
||||||
|
| `SURVEYBOX_TIMEZONE` | `Europe/Berlin` | Zeitzone für Anzeigen, Erinnerungen, Sicherungen |
|
||||||
|
| `SURVEYBOX_DB_HOST`, `_PORT`, `_NAME`, `_USER`, `_PASSWORD` | `db`, 5432, `surveybox`, `surveybox`, – | Datenbank |
|
||||||
|
| `SURVEYBOX_DB_SSLMODE`, `_SSLROOTCERT` | `prefer`, – | TLS zur externen Datenbank |
|
||||||
|
| `SURVEYBOX_SOURCE_URL` | leer | Link zum Quellcode in der Fußzeile (AGPL) |
|
||||||
|
| `SURVEYBOX_DATA_DIR` | `/data` | Datenverzeichnis im Container |
|
||||||
|
| `SURVEYBOX_MAX_UPLOAD_MB` | 250 | Obergrenze je Anfrage mit Dateien |
|
||||||
|
| `SURVEYBOX_BACKUP_HOUR`, `_KEEP_DAILY`, `_KEEP_PRE_UPGRADE` | 3, 14, 10 | Sicherungen |
|
||||||
|
| `SURVEYBOX_SKIP_PRE_UPGRADE_BACKUP` | `false` | nur im Notfall |
|
||||||
|
| `SURVEYBOX_WEB_WORKERS` | 2 | Prozesse für die Oberfläche |
|
||||||
|
| `SURVEYBOX_TRUSTED_PROXIES` | leer | Reverse Proxy, dessen `X-Forwarded-For` gilt |
|
||||||
|
| `SURVEYBOX_FRAME_ANCESTORS` | leer | Seiten, die Surveybox einbetten dürfen (Nextcloud) |
|
||||||
|
| `SURVEYBOX_SESSION_IDLE_MINUTES`, `_MAX_DAYS` | 480, 14 | Sitzungsdauer |
|
||||||
|
| `SURVEYBOX_AUDIT_RETENTION_DAYS` | 365 | Aufbewahrung des Protokolls |
|
||||||
|
| `SURVEYBOX_LOG_LEVEL` | `info` | `debug`, `info`, `warning`, `error` |
|
||||||
|
|
||||||
|
Alles Weitere (SMTP, Medien, Registrierung, Löschfristen, Gestaltung,
|
||||||
|
Mail-Vorlagen) stellen Administratoren in der Oberfläche ein; es liegt in der
|
||||||
|
Datenbank bzw. in `/data/branding` und ist damit gesichert.
|
||||||
|
|
||||||
|
## Störungen
|
||||||
|
|
||||||
|
| Symptom | Vorgehen |
|
||||||
|
| --- | --- |
|
||||||
|
| `web` bleibt „unhealthy“ nach einem Update | `docker compose logs web`: Migration fehlgeschlagen? Die Datenbank ist dann unverändert. Fehler beheben und `docker compose up -d --force-recreate web` oder zur vorigen Version zurück (README „Updates“) |
|
||||||
|
| Startet nicht: „Datenbank ist neuer als das Image“ | Altes Image erwischt; neues Image bauen. Nie die Datenbank „passend machen“ |
|
||||||
|
| Mails kommen nicht an | *E-Mail*: Warteschlange und Fehler; Testmail senden; SPF/DKIM/DMARC des Relays prüfen |
|
||||||
|
| Administrator hat keinen Zugang mehr | README „Zugang verloren“ (`docker compose exec web python -m surveybox.cli user-link …`) |
|
||||||
|
| Speicher voll | `/data/backups` prüfen (`SURVEYBOX_BACKUP_KEEP_DAILY`), große Uploads unter *Einstellungen → Medien* begrenzen |
|
||||||
|
| Sicherung zurückspielen | `docker compose stop web worker`, `docker compose run --rm --no-deps web restore <datei> --yes`, starten; das Löschjournal löscht danach erneut, was nach der Sicherung gelöscht wurde |
|
||||||
|
| Nextcloud zeigt Surveybox nicht im Rahmen | `SURVEYBOX_FRAME_ANCESTORS` gesetzt? Gleiche Hauptdomain? (README „Einbinden in die Nextcloud“) |
|
||||||
|
|
||||||
|
## Abnahme und Sicherheit
|
||||||
|
|
||||||
|
Ablauf, Werkzeuge und Ergebnisprotokoll: `docs/sicherheit.md`.
|
||||||
|
Datenschutz-Unterlagen (Verarbeitungsverzeichnis, TOM, Cookies,
|
||||||
|
Datenschutzerklärung): `docs/datenschutz.md`.
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
# Datenschutz: Unterlagen für Betreiber
|
||||||
|
|
||||||
|
Vorlagen und Fakten für den Betrieb einer Surveybox-Instanz nach der DSGVO.
|
||||||
|
Die Angaben zur Technik gelten für Surveybox selbst; Angaben in eckigen
|
||||||
|
Klammern ergänzt der Betreiber. Die Texte sind Arbeitshilfen, keine
|
||||||
|
Rechtsberatung: Verantwortlich bleibt der Betreiber, im Zweifel mit seiner
|
||||||
|
oder seinem Datenschutzbeauftragten.
|
||||||
|
|
||||||
|
## 1. Verzeichnis von Verarbeitungstätigkeiten (Art. 30 DSGVO)
|
||||||
|
|
||||||
|
| Angabe | Inhalt |
|
||||||
|
| --- | --- |
|
||||||
|
| Verantwortlicher | [Name, Anschrift, Kontakt; ggf. Datenschutzbeauftragte/r] |
|
||||||
|
| Bezeichnung | Durchführung von Umfragen, Anmeldungen und Terminabstimmungen mit Surveybox |
|
||||||
|
| Zwecke | Formulare erstellen und auswerten; Teilnahme an Umfragen, Abstimmungen und Schichtplänen; Benachrichtigung der Teilnehmenden (Bestätigung, Warteliste, Erinnerung, Folge-Mails); Verwaltung von Benutzerkonten und Gruppen |
|
||||||
|
| Betroffene | Benutzer mit Konto (Administratoren, Ersteller, Teilnehmende); Gäste ohne Konto; eingeladene Personen; in Antworten genannte Personen |
|
||||||
|
| Datenkategorien | Konto: Name, E-Mail-Adresse, Sprache, Rolle, Gruppen, Passwort-Hash (Argon2id), Passkey-Schlüssel (öffentlich), verschlüsseltes TOTP-Geheimnis, Sitzungen. Gäste: optional E-Mail-Adresse, Hash des persönlichen Links. Antworten: Inhalte nach Formular, ggf. Teilnehmer-Name, hochgeladene Dateien, Zeitpunkte. Kommentare. Protokoll: Ereignis, Zeitpunkt, handelnde Person (keine IP-Adressen). Zähler gegen Missbrauch (Anmeldung, Uploads, Mails): pseudonymisierte IP bzw. Adresse, nur für das jeweilige Zeitfenster. Mail-Warteschlange: Empfänger, Art, verschlüsselter Inhalt |
|
||||||
|
| Besondere Kategorien (Art. 9) | Keine vorgesehen. Wer Formulare mit solchen Fragen erstellt (z. B. Gesundheit, Unverträglichkeiten), prüft das je Formular und markiert die Fragen als personenbezogen |
|
||||||
|
| Empfänger | Innerhalb der Organisation: Verwalter und Auswertende des jeweiligen Formulars. Auftragsverarbeiter: [Betreiber des SMTP-Relays], [Hoster/Rechenzentrum, falls nicht selbst betrieben] |
|
||||||
|
| Drittland | Keine Übermittlung durch Surveybox. [Prüfen: SMTP-Relay, Hoster] |
|
||||||
|
| Löschfristen | Antworten: Löschfrist je Formular (Standard [730] Tage nach Ende), danach anonymisieren oder löschen; Konten: bis zur Löschung durch Admin oder Person selbst; Gast-Adressen ohne Bestätigung: 7 Tage; Protokoll: `SURVEYBOX_AUDIT_RETENTION_DAYS` (Standard 365 Tage); Mail-Warteschlange: nach Versand ohne Inhalt; Sicherungen: täglich `SURVEYBOX_BACKUP_KEEP_DAILY` Stück, Löschjournal sorgt nach dem Zurückspielen für erneutes Löschen |
|
||||||
|
| TOM | Siehe Abschnitt 3 und `docs/sicherheit.md` |
|
||||||
|
|
||||||
|
## 2. Rechtsgrundlagen (Anhaltspunkte)
|
||||||
|
|
||||||
|
| Verarbeitung | Mögliche Rechtsgrundlage |
|
||||||
|
| --- | --- |
|
||||||
|
| Benutzerkonten in einer Organisation | Art. 6 Abs. 1 lit. b (Mitgliedschaft, Vertrag) oder lit. f (berechtigtes Interesse an der Organisation der Arbeit); bei Beschäftigten § 26 BDSG |
|
||||||
|
| Teilnahme an einem Formular | je nach Zweck lit. b (z. B. Anmeldung zu einer Veranstaltung), lit. a (freiwillige Umfrage; Einwilligungsfeld je Formular verfügbar) oder lit. f |
|
||||||
|
| Gast-Adresse mit Bestätigung (Double-Opt-in) | lit. a (Einwilligung, jederzeit widerrufbar über Abmeldelink oder „Meine Links“) |
|
||||||
|
| Protokoll, Sicherungen, Zähler gegen Missbrauch | lit. f (Sicherheit des Dienstes) bzw. Art. 32 |
|
||||||
|
|
||||||
|
## 3. Technische und organisatorische Maßnahmen (Art. 32 DSGVO)
|
||||||
|
|
||||||
|
| Ziel | Maßnahmen in Surveybox | Aufgabe des Betreibers |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Vertraulichkeit | Anmeldung mit Argon2id, Passkeys, TOTP (Pflicht für Admins); Rechte je Rolle, Gruppe und Formular auf dem Server geprüft; nicht erratbare Links; TLS mit HSTS; strenge CSP; keine externen Ressourcen; Mail-Inhalte und Geheimnisse verschlüsselt gespeichert | Reverse Proxy mit TLS; `.env` nur für Admins lesbar; Server-Zugang absichern |
|
||||||
|
| Integrität | CSRF-Schutz; Prüfung aller Eingaben; Protokoll der Admin-Aktionen, Exporte, Änderungen und Löschungen; Vermerk bei Änderung fremder Antworten | Protokoll regelmäßig sichten |
|
||||||
|
| Verfügbarkeit | Tägliche Sicherung mit Prüfung; Sicherung vor jedem Update; Update in einer Transaktion mit Rücksprung | Sicherungen (`/data/backups`) zusätzlich außerhalb des Hosts aufbewahren; Wiederherstellung jährlich proben |
|
||||||
|
| Belastbarkeit | Container ohne Root, schreibgeschützt, ohne Capabilities; Begrenzung von Anmeldeversuchen und Uploads | Host aktuell halten; Image nach Updates neu bauen |
|
||||||
|
| Datenminimierung | Anonyme Formulare ohne Bezug zur Person; Gast-Adressen nur mit Bestätigung; Adressen für Organisatoren unsichtbar, wenn das Formular es vorsieht; Exporte ohne personenbezogene Daten wählbar | Formulare sparsam gestalten; personenbezogene Fragen markieren |
|
||||||
|
| Löschung | Löschfristen je Formular; Löschen von Konten, Gästen und einzelnen Antworten mit Vorschau; Löschjournal für zurückgespielte Sicherungen | Löschfristen passend einstellen |
|
||||||
|
|
||||||
|
## 4. Cookies und ähnliche Techniken
|
||||||
|
|
||||||
|
Surveybox setzt nur technisch notwendige Cookies, alle `HttpOnly` und
|
||||||
|
`SameSite=Lax`, bei https `Secure`. Kein Tracking, keine Cookies von Dritten,
|
||||||
|
daher kein Einwilligungsbanner nötig (§ 25 Abs. 2 TDDDG).
|
||||||
|
|
||||||
|
| Name | Zweck | Dauer |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `__Host-surveybox_session` | Anmeldung (Sitzung) | bis Abmeldung, Leerlauf `SURVEYBOX_SESSION_IDLE_MINUTES`, höchstens `SURVEYBOX_SESSION_MAX_DAYS` |
|
||||||
|
| `__Host-surveybox_csrf` | Schutz vor untergeschobenen Anfragen | Browsersitzung |
|
||||||
|
| `surveybox_lang` | gewählte Sprache | 1 Jahr |
|
||||||
|
| `surveybox_fp_<Nr.>` | Formular mit Passwort entsperrt | 12 Stunden |
|
||||||
|
| `surveybox_personal_link` | persönlichen Link einmal auf der Dankeseite zeigen | 10 Minuten |
|
||||||
|
| `surveybox_done_<…>` | Gast hat teilgenommen (Ergebnisse ansehen); nur Prüfsumme über das Formular | 7 Tage |
|
||||||
|
| `sb_comment_<Nr.>` | eigene Kommentare als Gast wiedererkennen | 1 Jahr |
|
||||||
|
| `surveybox_embed` | kompakte Darstellung im Rahmen | Browsersitzung |
|
||||||
|
|
||||||
|
Ohne https (nur zum Testen) entfällt das Präfix `__Host-`.
|
||||||
|
|
||||||
|
## 5. Rechte der Betroffenen
|
||||||
|
|
||||||
|
| Recht | So geht es in Surveybox |
|
||||||
|
| --- | --- |
|
||||||
|
| Auskunft, Übertragbarkeit (Art. 15, 20) | Konto → „Meine Daten herunterladen“ (JSON); Gäste über „Meine Links“ per Mail-Link oder über den persönlichen Link; Admins in der Benutzerverwaltung bzw. für Gast-Adressen |
|
||||||
|
| Berichtigung (Art. 16) | Eigene Antwort ändern (sofern das Formular es erlaubt) oder durch Verwalter mit Vermerk; Profil im Konto |
|
||||||
|
| Löschung (Art. 17) | Konto löschen (selbst oder durch Admin); Gäste über „Meine Links“ oder den persönlichen Link; einzelne Antworten durch Verwalter; Löschjournal wirkt auch nach dem Zurückspielen einer Sicherung |
|
||||||
|
| Widerspruch, Widerruf (Art. 21, 7) | Benachrichtigungen im Konto oder per Abmeldelink abbestellen; Gast-Adresse widerrufen über „Meine Links“ |
|
||||||
|
|
||||||
|
Anfragen, die nicht über die Oberfläche gehen, beantwortet [Stelle] innerhalb
|
||||||
|
eines Monats; Auskunft und Löschung erledigt ein Administrator wie oben.
|
||||||
|
|
||||||
|
## 6. Baustein für die Datenschutzerklärung
|
||||||
|
|
||||||
|
> **Umfragen und Anmeldungen (Surveybox)**
|
||||||
|
>
|
||||||
|
> Für Umfragen, Anmeldungen und Terminabstimmungen betreiben wir die Anwendung
|
||||||
|
> Surveybox auf eigenen Servern [bei Hoster]. Wenn Sie ein Formular ausfüllen,
|
||||||
|
> speichern wir Ihre Antworten und den Zeitpunkt; bei Formularen für
|
||||||
|
> angemeldete Benutzer zusätzlich den Bezug zu Ihrem Konto. Bei anonymen
|
||||||
|
> Formularen speichern wir keinen Bezug zu Ihrer Person. Geben Sie als Gast
|
||||||
|
> Ihre E-Mail-Adresse an, senden wir Ihnen eine Bestätigung mit einem
|
||||||
|
> persönlichen Link; weitere Mails erhalten Sie nur, wenn Sie Ihre Adresse
|
||||||
|
> bestätigen. Unbestätigte Adressen löschen wir nach 7 Tagen.
|
||||||
|
>
|
||||||
|
> Zweck ist die Durchführung und Auswertung des jeweiligen Formulars;
|
||||||
|
> Rechtsgrundlage ist [Art. 6 Abs. 1 lit. … DSGVO]. Die Antworten sehen nur die
|
||||||
|
> für das Formular zuständigen Personen. Wir löschen oder anonymisieren
|
||||||
|
> Antworten [Frist] nach dem Ende des Formulars. Mails versenden wir über
|
||||||
|
> [SMTP-Anbieter]. Surveybox setzt nur technisch notwendige Cookies (Anmeldung,
|
||||||
|
> Sprache, Schutz vor Missbrauch) und lädt keine Inhalte von Dritten.
|
||||||
|
>
|
||||||
|
> Über den persönlichen Link oder die Seite „Meine Links“ können Sie Ihre
|
||||||
|
> Antwort einsehen, ändern, herunterladen oder löschen, soweit das Formular es
|
||||||
|
> zulässt. Im Übrigen gelten Ihre Rechte nach Art. 15 bis 21 DSGVO; wenden Sie
|
||||||
|
> sich dazu an [Kontakt].
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
# Sicherheit: Nachweis und Abnahme
|
||||||
|
|
||||||
|
Maßstab ist der OWASP Application Security Verification Standard (ASVS) 4.0.3,
|
||||||
|
Stufe 2. Dieses Dokument ordnet die Anforderungen der Umsetzung zu, beschreibt
|
||||||
|
die automatischen Prüfungen und den Ablauf der Abnahme vor der ersten
|
||||||
|
produktiven Nutzung. Die Ergebnistabelle am Ende wird bei jeder Abnahme
|
||||||
|
ausgefüllt.
|
||||||
|
|
||||||
|
## Umsetzung nach ASVS-Kapiteln
|
||||||
|
|
||||||
|
| ASVS | Thema | Umsetzung in Surveybox | Geprüft durch |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| V1 | Architektur | Ein Image für Web und Worker, PostgreSQL, Volume `/data`; keine externen Dienste außer SMTP-Relay | Review |
|
||||||
|
| V2 | Authentisierung | Argon2id; Passkeys (WebAuthn); TOTP mit Wiederherstellungscodes; zweiter Faktor Pflicht für Administratoren; Sperre nach Fehlversuchen; Begrenzung je IP und Konto; „Passwort vergessen“ antwortet immer gleich | `test_accounts`, `test_passkeys_groups`, `test_mail` |
|
||||||
|
| V3 | Sitzungen | Zufällige Sitzungs-ID (serverseitig), Cookie `__Host-…` mit `Secure`, `HttpOnly`, `SameSite=Lax`; Leerlauf- und Höchstdauer; Abmelden auf allen Geräten; neue Sitzung nach Anmeldung | `test_accounts`, `test_security_matrix` |
|
||||||
|
| V4 | Zugriffskontrolle | Jede Anfrage prüft Rolle, Gruppe und Freigabe auf dem Server; Formular-IDs, Links und Tokens sind zufällig (UUID bzw. 128 Bit und mehr) | `test_security_matrix` (alle Routen), `test_group_scope`, `test_media_team` |
|
||||||
|
| V5 | Eingaben und Ausgaben | Typisierte Prüfung (FastAPI/Pydantic und eigene Prüfungen je Fragetyp); SQL nur über SQLAlchemy mit Parametern; Jinja mit automatischem Escaping; Mail- und Gestaltungsvorlagen ohne ausführbare Syntax; Exporte entschärfen Formeln (CSV), schreiben Text immer als Text (XLSX, ODS) und maskieren PDF-Markup | `test_question_types`, `test_xlsx_units`, `test_phase8c_units`, `test_mail_custom_units` |
|
||||||
|
| V6 | Kryptografie | Geheimnisse aus `SURVEYBOX_SECRET_KEY` abgeleitet (HKDF je Zweck); TOTP-Geheimnisse und SMTP-Passwort verschlüsselt; Mail-Inhalte in der Warteschlange verschlüsselt | `test_security_units`, `test_mail` |
|
||||||
|
| V7 | Fehler und Protokoll | Keine Stacktraces an Benutzer; Protokoll für Anmeldungen, Admin-Aktionen, Exporte, Löschungen, ohne Antwortinhalte; Aufbewahrung `SURVEYBOX_AUDIT_RETENTION_DAYS` | `test_audit_actions` |
|
||||||
|
| V8 | Datenschutz | Datensparsamkeit, Löschfristen, Löschjournal, Auskunft (Art. 15/20), keine externen Ressourcen, `Cache-Control: no-store` | `test_retention`, `test_erasure`, `test_subject_export` |
|
||||||
|
| V9 | Kommunikation | TLS am Reverse Proxy; HSTS; SMTP mit STARTTLS oder TLS | Konfiguration, ZAP |
|
||||||
|
| V10 | Schadcode | Feste Versionen mit Hashes (`requirements.lock`); `pip-audit` bei jedem Lauf und wöchentlich; Image-Scan mit Trivy | CI |
|
||||||
|
| V12 | Dateien | Typprüfung am Inhalt, Größenlimits, Speicherung außerhalb des Web-Pfads, Auslieferung nur nach Rechteprüfung, Bilder neu berechnet ohne Metadaten, kein SVG; Dokumente nur als Download mit `sandbox`-CSP | `test_media_units`, `test_form_files` |
|
||||||
|
| V13 | Schnittstellen | Keine öffentliche API; JSON-Endpunkte mit CSRF-Prüfung über Kopfzeile | `test_security_matrix` |
|
||||||
|
| V14 | Konfiguration | Strenge Content-Security-Policy ohne Inline-Skripte und -Stile; `X-Content-Type-Options`, `Referrer-Policy: same-origin`, `Permissions-Policy`, COOP/CORP; Einbetten nur für `SURVEYBOX_FRAME_ANCESTORS`; Container ohne Root, schreibgeschützt, ohne Capabilities | `test_security_units`, `test_security_matrix`, `test_embed`, ZAP |
|
||||||
|
|
||||||
|
Nicht zutreffend: V11 (Geschäftslogik mit Zahlungen o. ä.) nur als Plätze und
|
||||||
|
Wartelisten, abgedeckt durch Sperren in der Datenbank (`test_phase5`).
|
||||||
|
|
||||||
|
## Automatische Prüfungen (CI)
|
||||||
|
|
||||||
|
Bei jedem Push laufen:
|
||||||
|
|
||||||
|
- **ruff** mit den Sicherheitsregeln von Bandit (`S`) und **mypy** (strikt).
|
||||||
|
- **pip-audit** gegen `requirements.lock`; wöchentlich zusätzlich ohne Push.
|
||||||
|
- **Tests** gegen PostgreSQL, darunter `tests/test_security_matrix.py`:
|
||||||
|
- jede ändernde Anfrage hat die CSRF-Prüfung (Ausnahme mit Grund: der
|
||||||
|
Abmeldelink nach RFC 8058),
|
||||||
|
- jede Seite unter `/admin`, `/forms` und `/account` verlangt eine Anmeldung,
|
||||||
|
`/admin` außerdem Administratorrechte (alle Routen, nicht nur Stichproben),
|
||||||
|
- Sicherheits-Header auf Seiten, statischen Dateien, Fehlerseiten und
|
||||||
|
Weiterleitungen,
|
||||||
|
- keine Weiterleitung nach außen (`next=`), Cookies mit `HttpOnly` und
|
||||||
|
`SameSite`,
|
||||||
|
- Teilnehmer-Seite unter 100 KB ohne Bilder und ohne externe Ressourcen.
|
||||||
|
- **Installations- und Update-Test** im Wegwerf-Stack (`scripts/upgrade-test.sh`).
|
||||||
|
- **Trivy**: Image auf bekannte Lücken (hoch und kritisch, mit verfügbarer
|
||||||
|
Korrektur) – bricht den Lauf ab.
|
||||||
|
|
||||||
|
## Abnahme vor der ersten produktiven Nutzung
|
||||||
|
|
||||||
|
Alle Schritte gegen eine **Testinstanz** mit Testdaten, nie gegen die
|
||||||
|
produktive Instanz.
|
||||||
|
|
||||||
|
1. **CI grün** auf dem Stand, der ausgeliefert wird.
|
||||||
|
2. **OWASP ZAP** (passiver Baseline-Scan):
|
||||||
|
`scripts/zap-baseline.sh https://test.umfrage.example.de`.
|
||||||
|
Ergebnis `zap-report.html`. Regeln mit Begründung in
|
||||||
|
`scripts/zap-rules.tsv`; Header- und Cookie-Regeln sind dort als Fehler
|
||||||
|
eingestellt. Erwartet: keine FAIL-Meldungen; WARN-Meldungen einzeln bewerten
|
||||||
|
und hier eintragen.
|
||||||
|
3. **Lasttest** (nur lesend):
|
||||||
|
`python3 scripts/loadtest.py https://test.umfrage.example.de --path / --path /login --path /f/<token> --users 20 --requests 100`.
|
||||||
|
Ziel: 95. Perzentil unter 200 ms. Für Seiten hinter der Anmeldung
|
||||||
|
`--cookie "__Host-surveybox_session=…"` angeben.
|
||||||
|
4. **Update-Test mit Daten**: vor dem Update der Testinstanz das laufende Image
|
||||||
|
markieren (`docker tag surveybox:local surveybox:vorher`), dann
|
||||||
|
`OLD_IMAGE=surveybox:vorher scripts/upgrade-test.sh`. Danach die
|
||||||
|
Testinstanz selbst aktualisieren und prüfen: Formulare, Antworten, Logo und
|
||||||
|
Gestaltung sind unverändert, im Protokoll steht die Sicherung vor dem
|
||||||
|
Update.
|
||||||
|
5. **Wiederherstellung**: eine Sicherung auf einer zweiten Testinstanz
|
||||||
|
zurückspielen (`restore`), anmelden, Stichproben prüfen, Löschjournal wird
|
||||||
|
angewendet.
|
||||||
|
6. **Stichproben von Hand**:
|
||||||
|
- Anmelden mit falschem Passwort, bis die Sperre greift; Meldung verrät
|
||||||
|
nicht, ob das Konto existiert.
|
||||||
|
- Formular-Link eines Formulars mit Zugriff „Ausgewählte Benutzer“ als nicht
|
||||||
|
eingeladene Person öffnen: kein Zugriff.
|
||||||
|
- Antwort-ID einer fremden Antwort in die Adresse einsetzen: 404.
|
||||||
|
- Datei-Upload mit umbenannter Datei (z. B. `.exe` als `.pdf`): abgelehnt.
|
||||||
|
- In Freitexten und Titeln `<script>alert(1)</script>` eingeben: erscheint
|
||||||
|
als Text, auch in Exporten und Mails.
|
||||||
|
- Seite in einem fremden `<iframe>` einbetten: vom Browser blockiert.
|
||||||
|
|
||||||
|
## Ergebnis der Abnahme
|
||||||
|
|
||||||
|
| Datum | Stand (Commit/Image) | Prüfung | Ergebnis | Bemerkung |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| | | CI | | |
|
||||||
|
| | | ZAP Baseline | | |
|
||||||
|
| | | Lasttest (95 %) | | |
|
||||||
|
| | | Update mit Daten | | |
|
||||||
|
| | | Wiederherstellung | | |
|
||||||
|
| | | Stichproben | | |
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
#
|
||||||
|
# Projektmetadaten und Werkzeugeinstellungen.
|
||||||
|
# Die Laufzeit-Abhängigkeiten stehen in requirements.in und werden mit
|
||||||
|
# scripts/lock.sh in requirements.lock (mit Hashes) festgeschrieben.
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "surveybox"
|
||||||
|
version = "0.1.0.dev0"
|
||||||
|
description = "Formulare und Abstimmungen, selbst gehostet"
|
||||||
|
readme = "README.md"
|
||||||
|
license = "AGPL-3.0-or-later"
|
||||||
|
requires-python = ">=3.13"
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
line-length = 100
|
||||||
|
target-version = "py313"
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
select = ["E", "F", "W", "I", "B", "UP", "S", "SIM", "RUF"]
|
||||||
|
|
||||||
|
[tool.ruff.lint.per-file-ignores]
|
||||||
|
"tests/*" = ["S101", "S105", "S106", "S603", "S607"]
|
||||||
|
|
||||||
|
[tool.mypy]
|
||||||
|
python_version = "3.13"
|
||||||
|
strict = true
|
||||||
|
packages = ["surveybox"]
|
||||||
|
|
||||||
|
[[tool.mypy.overrides]]
|
||||||
|
module = ["babel.*", "reportlab.*"]
|
||||||
|
ignore_missing_imports = true
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
markers = [
|
||||||
|
"db: braucht eine PostgreSQL-Testdatenbank (SURVEYBOX_TEST_DB=1)",
|
||||||
|
]
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Werkzeuge für Entwicklung und CI, nicht im Image.
|
||||||
|
-c requirements.lock
|
||||||
|
|
||||||
|
pytest>=8
|
||||||
|
httpx>=0.27
|
||||||
|
ruff>=0.6
|
||||||
|
mypy>=1.11
|
||||||
|
pip-audit>=2.7
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Laufzeit-Abhängigkeiten von Surveybox.
|
||||||
|
# Nur hier ändern, danach scripts/lock.sh ausführen.
|
||||||
|
# So wenige Pakete wie möglich: jedes neue Paket braucht einen guten Grund.
|
||||||
|
|
||||||
|
fastapi>=0.115
|
||||||
|
uvicorn>=0.30
|
||||||
|
sqlalchemy>=2.0.30
|
||||||
|
alembic>=1.13
|
||||||
|
psycopg[binary]>=3.2
|
||||||
|
pydantic-settings>=2.4
|
||||||
|
jinja2>=3.1.4
|
||||||
|
babel>=2.15
|
||||||
|
tzdata>=2024.1
|
||||||
|
python-multipart>=0.0.9
|
||||||
|
argon2-cffi>=23.1
|
||||||
|
cryptography>=43
|
||||||
|
segno>=1.6
|
||||||
|
webauthn>=2.2
|
||||||
|
# Bilder neu berechnen (ohne Metadaten, begrenzte Größe), siehe surveybox/media/images.py
|
||||||
|
pillow>=11
|
||||||
|
# Teilnehmerlisten als PDF (surveybox/forms/participant_pdf.py); Texte werden maskiert,
|
||||||
|
# Markup aus Antworten wird nie ausgewertet
|
||||||
|
reportlab>=4.4
|
||||||
Executable
+79
@@ -0,0 +1,79 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Lasttest gegen eine TESTINSTANZ: Antwortzeiten üblicher Seiten (nur Lesen).
|
||||||
|
|
||||||
|
Ziel aus dem Pflichtenheft: unter 200 ms für übliche Seiten. Das Skript ruft
|
||||||
|
Seiten gleichzeitig ab und meldet je Seite Median, 95. Perzentil und Maximum.
|
||||||
|
Es braucht nur Python 3, keine Pakete, und sendet ausschließlich GET-Anfragen.
|
||||||
|
|
||||||
|
python3 scripts/loadtest.py https://test.umfrage.example.de \\
|
||||||
|
--path / --path /login --path /f/<token> --users 20 --requests 50
|
||||||
|
|
||||||
|
Mit --cookie "surveybox_session=…" (bzw. __Host-surveybox_session=…) lassen
|
||||||
|
sich auch Seiten hinter der Anmeldung messen, z. B. /forms. Den Wert aus den
|
||||||
|
Entwicklerwerkzeugen des Browsers kopieren und danach abmelden.
|
||||||
|
|
||||||
|
Hinweis: Die Anmeldung begrenzt Fehlversuche je IP, Seiten zum Lesen nicht.
|
||||||
|
Bitte nur gegen eigene Testinstanzen laufen lassen.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import statistics
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
|
|
||||||
|
def fetch(url: str, cookie: str | None) -> tuple[float, int]:
|
||||||
|
request = urllib.request.Request(url, headers={ # noqa: S310 (Adresse vom Aufrufer)
|
||||||
|
"User-Agent": "surveybox-loadtest", "Accept-Language": "de",
|
||||||
|
**({"Cookie": cookie} if cookie else {})})
|
||||||
|
start = time.perf_counter()
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(request, timeout=30) as resp: # noqa: S310
|
||||||
|
resp.read()
|
||||||
|
status = resp.status
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
status = exc.code
|
||||||
|
return (time.perf_counter() - start) * 1000, status
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__,
|
||||||
|
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
parser.add_argument("base", help="Adresse der Testinstanz, z. B. https://test.example.de")
|
||||||
|
parser.add_argument("--path", action="append", default=[],
|
||||||
|
help="Seite (mehrfach möglich); Standard: / und /login")
|
||||||
|
parser.add_argument("--users", type=int, default=10, help="gleichzeitige Abrufe")
|
||||||
|
parser.add_argument("--requests", type=int, default=50, help="Abrufe je Seite")
|
||||||
|
parser.add_argument("--limit-ms", type=float, default=200.0,
|
||||||
|
help="Grenze für das 95. Perzentil (Standard 200)")
|
||||||
|
parser.add_argument("--cookie", default=None, help="Cookie-Kopf für angemeldete Seiten")
|
||||||
|
args = parser.parse_args()
|
||||||
|
paths = args.path or ["/", "/login"]
|
||||||
|
base = args.base.rstrip("/")
|
||||||
|
failed = False
|
||||||
|
print(f"{'Seite':40} {'Median':>8} {'95 %':>8} {'Max':>8} Fehler")
|
||||||
|
for path in paths:
|
||||||
|
url = base + path
|
||||||
|
fetch(url, args.cookie) # aufwärmen
|
||||||
|
with ThreadPoolExecutor(max_workers=args.users) as pool:
|
||||||
|
results = list(pool.map(fetch, [url] * args.requests, [args.cookie] * args.requests))
|
||||||
|
times = sorted(t for t, _ in results)
|
||||||
|
errors = sum(1 for _, status in results if status >= 400)
|
||||||
|
p95 = times[max(int(len(times) * 0.95) - 1, 0)]
|
||||||
|
too_slow = p95 > args.limit_ms
|
||||||
|
failed = failed or too_slow or errors > 0
|
||||||
|
mark = " ZU LANGSAM" if too_slow else ""
|
||||||
|
print(f"{path[:40]:40} {statistics.median(times):7.0f} {p95:7.0f} {times[-1]:7.0f}"
|
||||||
|
f" {errors}{mark}")
|
||||||
|
print(f"\nGrenze 95. Perzentil: {args.limit_ms:.0f} ms bei {args.users} gleichzeitigen Abrufen")
|
||||||
|
return 1 if failed else 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
Executable
+35
@@ -0,0 +1,35 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
#
|
||||||
|
# Schreibt die Abhängigkeiten mit exakten Versionen und Hashes fest:
|
||||||
|
# requirements.in -> requirements.lock (Image)
|
||||||
|
# requirements-dev.in -> requirements-dev.lock (Tests, CI)
|
||||||
|
#
|
||||||
|
# Läuft in einem Wegwerf-Container, braucht also nur Docker.
|
||||||
|
# Nach jeder Änderung an einer .in-Datei ausführen und beide .lock-Dateien
|
||||||
|
# mit ins Repository aufnehmen.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
PYTHON_IMAGE="${PYTHON_IMAGE:-python:3.13-slim-trixie}"
|
||||||
|
UPGRADE_FLAG="${UPGRADE:+--upgrade}"
|
||||||
|
|
||||||
|
docker run --rm \
|
||||||
|
--user "$(id -u):$(id -g)" \
|
||||||
|
-e HOME=/tmp \
|
||||||
|
-v "$PWD":/src -w /src \
|
||||||
|
"$PYTHON_IMAGE" \
|
||||||
|
sh -euc "
|
||||||
|
python -m pip install --quiet --user uv
|
||||||
|
UV=/tmp/.local/bin/uv
|
||||||
|
\$UV pip compile requirements.in \
|
||||||
|
--universal --python-version 3.13 --generate-hashes $UPGRADE_FLAG \
|
||||||
|
--output-file requirements.lock
|
||||||
|
\$UV pip compile requirements-dev.in \
|
||||||
|
--universal --python-version 3.13 --generate-hashes $UPGRADE_FLAG \
|
||||||
|
--output-file requirements-dev.lock
|
||||||
|
"
|
||||||
|
|
||||||
|
echo "Fertig: requirements.lock und requirements-dev.lock aktualisiert."
|
||||||
|
echo "Alle Pakete auf den neuesten Stand heben: UPGRADE=1 $0"
|
||||||
Executable
+98
@@ -0,0 +1,98 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
#
|
||||||
|
# Prüft Neuinstallation und Update in einem Wegwerf-Stack.
|
||||||
|
#
|
||||||
|
# NEW_IMAGE das zu prüfende Image (Standard: surveybox:test, wird gebaut)
|
||||||
|
# OLD_IMAGE optional: das zuletzt veröffentlichte Image. Ist es gesetzt,
|
||||||
|
# wird zuerst damit installiert und dann auf NEW_IMAGE aktualisiert.
|
||||||
|
# UPGRADE_TEST_SUBNET Subnetz des Wegwerf-Stacks (Standard 172.30.254.0/24)
|
||||||
|
#
|
||||||
|
# Prüfungen:
|
||||||
|
# 1. Instanz wird gesund (Web und Worker)
|
||||||
|
# 2. zweite Migration meldet "aktuell" (mehrfach ausführbar)
|
||||||
|
# 3. bei einem Update liegt eine Sicherung vor dem Update vor
|
||||||
|
# 4. Neustart nach dem Update: weiterhin gesund
|
||||||
|
# 5. Sicherung erstellen und zurückspielen funktioniert
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
NEW_IMAGE="${NEW_IMAGE:-surveybox:test}"
|
||||||
|
OLD_IMAGE="${OLD_IMAGE:-}"
|
||||||
|
# Eigenes Subnetz für den Wegwerf-Stack; darf mit nichts auf dem Host kollidieren.
|
||||||
|
TEST_SUBNET="${UPGRADE_TEST_SUBNET:-172.30.254.0/24}"
|
||||||
|
PROJECT="surveybox-upgradetest-$$"
|
||||||
|
WORKDIR="$(mktemp -d)"
|
||||||
|
ENV_FILE="$WORKDIR/.env"
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
SURVEYBOX_ENV_FILE="$ENV_FILE" docker compose -p "$PROJECT" --env-file "$ENV_FILE" \
|
||||||
|
-f compose.yaml down -v --remove-orphans >/dev/null 2>&1 || true
|
||||||
|
rm -rf "$WORKDIR"
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
|
||||||
|
if [[ "$NEW_IMAGE" == "surveybox:test" ]]; then
|
||||||
|
docker build -t "$NEW_IMAGE" .
|
||||||
|
fi
|
||||||
|
|
||||||
|
cat >"$ENV_FILE" <<EOF
|
||||||
|
COMPOSE_PROFILES=db
|
||||||
|
SURVEYBOX_HTTP_BIND=127.0.0.1
|
||||||
|
SURVEYBOX_HTTP_PORT=0
|
||||||
|
SURVEYBOX_NET_SUBNET=$TEST_SUBNET
|
||||||
|
SURVEYBOX_PUBLIC_URL=http://localhost
|
||||||
|
SURVEYBOX_SECRET_KEY=$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
|
||||||
|
SURVEYBOX_DB_PASSWORD=$(head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n')
|
||||||
|
SURVEYBOX_DB_HOST=db
|
||||||
|
SURVEYBOX_LOG_LEVEL=info
|
||||||
|
EOF
|
||||||
|
compose() {
|
||||||
|
SURVEYBOX_IMAGE="$1" SURVEYBOX_ENV_FILE="$ENV_FILE" \
|
||||||
|
docker compose -p "$PROJECT" --env-file "$ENV_FILE" -f compose.yaml "${@:2}"
|
||||||
|
}
|
||||||
|
|
||||||
|
step() { printf '\n==> %s\n' "$*"; }
|
||||||
|
fail() {
|
||||||
|
printf 'FEHLER: %s\n' "$*" >&2
|
||||||
|
SURVEYBOX_ENV_FILE="$ENV_FILE" docker compose -p "$PROJECT" --env-file "$ENV_FILE" \
|
||||||
|
-f compose.yaml logs --tail=80 >&2 || true
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if [[ -n "$OLD_IMAGE" ]]; then
|
||||||
|
step "Installation mit dem alten Image $OLD_IMAGE"
|
||||||
|
compose "$OLD_IMAGE" up -d --no-build --wait --wait-timeout 300 db web worker \
|
||||||
|
|| fail "altes Image wird nicht gesund"
|
||||||
|
compose "$OLD_IMAGE" stop web worker
|
||||||
|
fi
|
||||||
|
|
||||||
|
step "Start mit dem neuen Image $NEW_IMAGE"
|
||||||
|
compose "$NEW_IMAGE" up -d --no-build --wait --wait-timeout 300 db web worker \
|
||||||
|
|| fail "neues Image wird nicht gesund"
|
||||||
|
|
||||||
|
step "Zweite Migration muss 'aktuell' melden"
|
||||||
|
out="$(compose "$NEW_IMAGE" exec -T web python -m surveybox.cli migrate 2>&1)" || fail "migrate: $out"
|
||||||
|
grep -q "Datenbank ist aktuell" <<<"$out" || fail "zweite Migration nicht als aktuell erkannt: $out"
|
||||||
|
|
||||||
|
if [[ -n "$OLD_IMAGE" ]]; then
|
||||||
|
step "Sicherung vor dem Update vorhanden?"
|
||||||
|
compose "$NEW_IMAGE" exec -T web sh -c 'ls /data/backups/pre-upgrade/*.dump' \
|
||||||
|
|| fail "keine Sicherung vor dem Update gefunden"
|
||||||
|
fi
|
||||||
|
|
||||||
|
step "Neustart"
|
||||||
|
compose "$NEW_IMAGE" restart web worker
|
||||||
|
compose "$NEW_IMAGE" up -d --no-build --wait --wait-timeout 300 web worker \
|
||||||
|
|| fail "nach dem Neustart nicht gesund"
|
||||||
|
|
||||||
|
step "Sicherung erstellen und zurückspielen"
|
||||||
|
file="$(compose "$NEW_IMAGE" exec -T web python -m surveybox.cli backup | tail -n1)" \
|
||||||
|
|| fail "Sicherung fehlgeschlagen"
|
||||||
|
compose "$NEW_IMAGE" stop web worker
|
||||||
|
compose "$NEW_IMAGE" run --rm --no-deps web restore "$file" --yes || fail "Wiederherstellung fehlgeschlagen"
|
||||||
|
compose "$NEW_IMAGE" up -d --no-build --wait --wait-timeout 300 web worker \
|
||||||
|
|| fail "nach der Wiederherstellung nicht gesund"
|
||||||
|
|
||||||
|
step "Alles in Ordnung."
|
||||||
Executable
+25
@@ -0,0 +1,25 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
#
|
||||||
|
# Sicherheitstest mit OWASP ZAP (Baseline-Scan) gegen eine TESTINSTANZ.
|
||||||
|
# Passiv: ZAP ruft die Seiten auf und prüft Antworten und Header, greift aber
|
||||||
|
# nichts an. Nie gegen eine produktive Instanz mit echten Daten laufen lassen.
|
||||||
|
#
|
||||||
|
# scripts/zap-baseline.sh https://test.umfrage.example.de
|
||||||
|
#
|
||||||
|
# Ergebnis: zap-report.html und zap-report.md im aktuellen Verzeichnis.
|
||||||
|
# Bekannte, begründete Ausnahmen stehen in scripts/zap-rules.tsv.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
target="${1:?Adresse der Testinstanz angeben, z. B. https://test.umfrage.example.de}"
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
ZAP_IMAGE="${ZAP_IMAGE:-ghcr.io/zaproxy/zaproxy:stable}"
|
||||||
|
|
||||||
|
docker run --rm -t \
|
||||||
|
--user "$(id -u):$(id -g)" \
|
||||||
|
-v "$PWD:/zap/wrk:rw" \
|
||||||
|
"$ZAP_IMAGE" zap-baseline.py \
|
||||||
|
-t "$target" \
|
||||||
|
-c scripts/zap-rules.tsv \
|
||||||
|
-r zap-report.html -w zap-report.md \
|
||||||
|
-j -m 5 -I
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Regeln für scripts/zap-baseline.sh: <ID> <IGNORE|INFO|WARN|FAIL> <Begründung>
|
||||||
|
# Standard: alles WARN. Hier nur Abweichungen mit Grund.
|
||||||
|
10096 IGNORE Zeitstempel in Antworten sind Datumsangaben von Formularen, keine Serverzeit-Lecks
|
||||||
|
10049 IGNORE Inhalte sind absichtlich nicht zwischenspeicherbar (Cache-Control: no-store)
|
||||||
|
10055 FAIL CSP muss streng bleiben: jede Meldung ist ein Fehler
|
||||||
|
10020 FAIL Fehlender Schutz gegen Einbetten (X-Frame-Options / frame-ancestors)
|
||||||
|
10021 FAIL X-Content-Type-Options fehlt
|
||||||
|
10038 FAIL Content-Security-Policy fehlt
|
||||||
|
10010 FAIL Cookie ohne HttpOnly
|
||||||
|
10054 FAIL Cookie ohne SameSite
|
||||||
|
@@ -0,0 +1,4 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Surveybox - Formulare und Abstimmungen, selbst gehostet."""
|
||||||
|
|
||||||
|
__version__ = "0.1.0.dev0"
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Benutzerkonten: Anmeldung, Sitzungen, zweiter Faktor, Protokoll."""
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Protokoll von Anmeldungen und Verwaltungsaktionen.
|
||||||
|
|
||||||
|
Grundsatz: keine Inhalte, keine E-Mail-Adressen, keine IP-Adressen. Personen
|
||||||
|
werden nur über ihre interne Konto-ID referenziert; wird ein Konto gelöscht,
|
||||||
|
bleibt der Eintrag ohne Bezug zur Person stehen.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import delete
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.models import AuditEvent
|
||||||
|
|
||||||
|
# Erlaubte Aktionen; die Oberfläche übersetzt sie.
|
||||||
|
ACTIONS = {
|
||||||
|
"auth.login",
|
||||||
|
"auth.login_failed",
|
||||||
|
"auth.locked",
|
||||||
|
"auth.logout",
|
||||||
|
"auth.mfa_failed",
|
||||||
|
"auth.recovery_code_used",
|
||||||
|
"account.password_changed",
|
||||||
|
"account.totp_enabled",
|
||||||
|
"account.totp_disabled",
|
||||||
|
"account.recovery_codes_generated",
|
||||||
|
"account.sessions_revoked",
|
||||||
|
"account.setup_completed",
|
||||||
|
"admin.user_created",
|
||||||
|
"admin.user_updated",
|
||||||
|
"admin.link_created",
|
||||||
|
"admin.sessions_revoked",
|
||||||
|
"admin.mfa_reset",
|
||||||
|
"account.passkey_added",
|
||||||
|
"account.passkey_removed",
|
||||||
|
"auth.passkey_failed",
|
||||||
|
"admin.group_created",
|
||||||
|
"admin.group_updated",
|
||||||
|
"admin.group_deleted",
|
||||||
|
"admin.group_member_added",
|
||||||
|
"admin.group_member_removed",
|
||||||
|
"form.created",
|
||||||
|
"form.deleted",
|
||||||
|
"form.status_changed",
|
||||||
|
"form.copied",
|
||||||
|
"form.team_changed",
|
||||||
|
"admin.settings_changed",
|
||||||
|
"admin.group_role_changed",
|
||||||
|
"admin.mail_settings_changed",
|
||||||
|
"admin.mail_test",
|
||||||
|
"account.reset_requested",
|
||||||
|
"account.notifications_changed",
|
||||||
|
"account.registered",
|
||||||
|
"admin.registration_changed",
|
||||||
|
"admin.privacy_changed",
|
||||||
|
"form.retention_applied",
|
||||||
|
"account.deleted",
|
||||||
|
"account.exported",
|
||||||
|
"admin.user_exported",
|
||||||
|
"admin.guest_exported",
|
||||||
|
"guest.exported",
|
||||||
|
"admin.branding_changed",
|
||||||
|
"admin.appearance_changed",
|
||||||
|
"admin.mail_template_changed",
|
||||||
|
"form.exported",
|
||||||
|
"response.deleted",
|
||||||
|
"response.edited",
|
||||||
|
"guest.deleted",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def record(
|
||||||
|
db: Session,
|
||||||
|
action: str,
|
||||||
|
*,
|
||||||
|
actor_id: int | None = None,
|
||||||
|
target_type: str | None = None,
|
||||||
|
target_id: str | int | None = None,
|
||||||
|
details: dict[str, Any] | None = None,
|
||||||
|
) -> None:
|
||||||
|
if action not in ACTIONS:
|
||||||
|
raise ValueError(f"Unbekannte Protokollaktion: {action}")
|
||||||
|
db.add(
|
||||||
|
AuditEvent(
|
||||||
|
action=action,
|
||||||
|
actor_id=actor_id,
|
||||||
|
target_type=target_type,
|
||||||
|
target_id=None if target_id is None else str(target_id),
|
||||||
|
details=details,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def purge_older_than(db: Session, days: int) -> int:
|
||||||
|
cutoff = datetime.now(UTC) - timedelta(days=days)
|
||||||
|
result = db.execute(delete(AuditEvent).where(AuditEvent.occurred_at < cutoff))
|
||||||
|
return int(result.rowcount or 0) # type: ignore[attr-defined]
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Benutzergruppen. Später: Formulare an Gruppen freigeben."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from sqlalchemy import delete, func, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.accounts import audit
|
||||||
|
from surveybox.accounts.service import AccountError
|
||||||
|
from surveybox.models import GroupMember, GroupRole, GroupRoleKind, Role, UserAccount, UserGroup
|
||||||
|
|
||||||
|
MAX_NAME = 80
|
||||||
|
MAX_DESCRIPTION = 500
|
||||||
|
|
||||||
|
|
||||||
|
def _clean(name: str, description: str) -> tuple[str, str | None]:
|
||||||
|
name = " ".join(name.split())
|
||||||
|
description = description.strip()
|
||||||
|
if not name or len(name) > MAX_NAME:
|
||||||
|
raise AccountError("group_name_invalid")
|
||||||
|
if len(description) > MAX_DESCRIPTION:
|
||||||
|
raise AccountError("group_description_invalid")
|
||||||
|
return name, description or None
|
||||||
|
|
||||||
|
|
||||||
|
def find(db: Session, public_id: str) -> UserGroup | None:
|
||||||
|
try:
|
||||||
|
pid = uuid.UUID(public_id)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return db.scalar(select(UserGroup).where(UserGroup.public_id == pid))
|
||||||
|
|
||||||
|
|
||||||
|
def list_with_counts(db: Session) -> list[tuple[UserGroup, int]]:
|
||||||
|
counts = (
|
||||||
|
select(GroupMember.group_id, func.count().label("n"))
|
||||||
|
.group_by(GroupMember.group_id)
|
||||||
|
.subquery()
|
||||||
|
)
|
||||||
|
rows = db.execute(
|
||||||
|
select(UserGroup, func.coalesce(counts.c.n, 0))
|
||||||
|
.outerjoin(counts, counts.c.group_id == UserGroup.id)
|
||||||
|
.order_by(UserGroup.name)
|
||||||
|
).all()
|
||||||
|
return [(group, int(n)) for group, n in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def _name_taken(db: Session, name: str, exclude_id: int | None = None) -> bool:
|
||||||
|
stmt = select(UserGroup.id).where(func.lower(UserGroup.name) == name.lower())
|
||||||
|
if exclude_id is not None:
|
||||||
|
stmt = stmt.where(UserGroup.id != exclude_id)
|
||||||
|
return db.scalar(stmt) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def clean_roles(values: list[str] | None) -> list[str] | None:
|
||||||
|
"""Gewählte Benutzertypen; keine oder alle bedeuten "für alle" (NULL)."""
|
||||||
|
valid = [r.value for r in Role]
|
||||||
|
chosen = [r for r in valid if r in (values or [])]
|
||||||
|
return None if not chosen or len(chosen) == len(valid) else chosen
|
||||||
|
|
||||||
|
|
||||||
|
def create(
|
||||||
|
db: Session,
|
||||||
|
name: str,
|
||||||
|
description: str,
|
||||||
|
actor_id: int,
|
||||||
|
roles: list[str] | None = None,
|
||||||
|
parent: UserGroup | None = None,
|
||||||
|
) -> UserGroup:
|
||||||
|
name, desc = _clean(name, description)
|
||||||
|
if _name_taken(db, name):
|
||||||
|
raise AccountError("group_name_taken")
|
||||||
|
group = UserGroup(
|
||||||
|
name=name,
|
||||||
|
description=desc,
|
||||||
|
roles=clean_roles(roles),
|
||||||
|
parent_id=parent.id if parent is not None else None,
|
||||||
|
)
|
||||||
|
db.add(group)
|
||||||
|
db.flush()
|
||||||
|
audit.record(db, "admin.group_created", actor_id=actor_id, target_type="group",
|
||||||
|
target_id=group.id)
|
||||||
|
return group
|
||||||
|
|
||||||
|
|
||||||
|
def update(
|
||||||
|
db: Session,
|
||||||
|
group: UserGroup,
|
||||||
|
name: str,
|
||||||
|
description: str,
|
||||||
|
actor_id: int,
|
||||||
|
roles: list[str] | None = None,
|
||||||
|
) -> None:
|
||||||
|
name, desc = _clean(name, description)
|
||||||
|
if _name_taken(db, name, exclude_id=group.id):
|
||||||
|
raise AccountError("group_name_taken")
|
||||||
|
group.name = name
|
||||||
|
group.description = desc
|
||||||
|
group.roles = clean_roles(roles)
|
||||||
|
audit.record(db, "admin.group_updated", actor_id=actor_id, target_type="group",
|
||||||
|
target_id=group.id)
|
||||||
|
|
||||||
|
|
||||||
|
def remove(db: Session, group: UserGroup, actor_id: int) -> None:
|
||||||
|
"""Löscht die Gruppe; ihre Untergruppen rücken eine Ebene nach oben."""
|
||||||
|
for child in db.scalars(select(UserGroup).where(UserGroup.parent_id == group.id)):
|
||||||
|
child.parent_id = group.parent_id
|
||||||
|
db.flush()
|
||||||
|
audit.record(db, "admin.group_deleted", actor_id=actor_id, target_type="group",
|
||||||
|
target_id=group.id)
|
||||||
|
db.delete(group)
|
||||||
|
|
||||||
|
|
||||||
|
def set_parent(db: Session, group: UserGroup, parent: UserGroup | None, actor_id: int) -> None:
|
||||||
|
from surveybox.accounts import scope
|
||||||
|
|
||||||
|
new_parent = parent.id if parent is not None else None
|
||||||
|
if new_parent == group.parent_id:
|
||||||
|
return
|
||||||
|
if new_parent == group.id or scope.would_cycle(scope.load_tree(db), group.id, new_parent):
|
||||||
|
raise AccountError("group_cycle")
|
||||||
|
group.parent_id = new_parent
|
||||||
|
audit.record(db, "admin.group_updated", actor_id=actor_id, target_type="group",
|
||||||
|
target_id=group.id, details={"parent": new_parent})
|
||||||
|
|
||||||
|
|
||||||
|
def roles_in(db: Session, group: UserGroup) -> list[tuple[UserAccount, str]]:
|
||||||
|
rows = db.execute(
|
||||||
|
select(UserAccount, GroupRole.role)
|
||||||
|
.join(GroupRole, GroupRole.user_id == UserAccount.id)
|
||||||
|
.where(GroupRole.group_id == group.id)
|
||||||
|
.order_by(GroupRole.role, UserAccount.display_name)
|
||||||
|
).all()
|
||||||
|
return [(user, role) for user, role in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def add_role(db: Session, group: UserGroup, user: UserAccount, role: str, actor_id: int) -> None:
|
||||||
|
if role not in {r.value for r in GroupRoleKind}:
|
||||||
|
raise AccountError("group_role_invalid")
|
||||||
|
if db.get(GroupRole, (group.id, user.id, role)) is not None:
|
||||||
|
return
|
||||||
|
db.add(GroupRole(group_id=group.id, user_id=user.id, role=role))
|
||||||
|
audit.record(db, "admin.group_role_changed", actor_id=actor_id, target_type="user",
|
||||||
|
target_id=user.id, details={"group": group.id, "role": role, "added": True})
|
||||||
|
|
||||||
|
|
||||||
|
def remove_role(
|
||||||
|
db: Session, group: UserGroup, user: UserAccount, role: str, actor_id: int
|
||||||
|
) -> None:
|
||||||
|
row = db.get(GroupRole, (group.id, user.id, role))
|
||||||
|
if row is None:
|
||||||
|
return
|
||||||
|
db.delete(row)
|
||||||
|
audit.record(db, "admin.group_role_changed", actor_id=actor_id, target_type="user",
|
||||||
|
target_id=user.id, details={"group": group.id, "role": role, "added": False})
|
||||||
|
|
||||||
|
|
||||||
|
def subgroups(db: Session, group: UserGroup) -> list[UserGroup]:
|
||||||
|
return list(
|
||||||
|
db.scalars(
|
||||||
|
select(UserGroup).where(UserGroup.parent_id == group.id).order_by(UserGroup.name)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def members(db: Session, group: UserGroup) -> list[UserAccount]:
|
||||||
|
return list(
|
||||||
|
db.scalars(
|
||||||
|
select(UserAccount)
|
||||||
|
.join(GroupMember, GroupMember.user_id == UserAccount.id)
|
||||||
|
.where(GroupMember.group_id == group.id)
|
||||||
|
.order_by(UserAccount.display_name)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def non_members(db: Session, group: UserGroup) -> list[UserAccount]:
|
||||||
|
in_group = select(GroupMember.user_id).where(GroupMember.group_id == group.id)
|
||||||
|
return list(
|
||||||
|
db.scalars(
|
||||||
|
select(UserAccount)
|
||||||
|
.where(UserAccount.id.not_in(in_group), UserAccount.is_active.is_(True))
|
||||||
|
.order_by(UserAccount.display_name)
|
||||||
|
.limit(1000)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def groups_of(db: Session, user: UserAccount) -> list[UserGroup]:
|
||||||
|
return list(
|
||||||
|
db.scalars(
|
||||||
|
select(UserGroup)
|
||||||
|
.join(GroupMember, GroupMember.group_id == UserGroup.id)
|
||||||
|
.where(GroupMember.user_id == user.id)
|
||||||
|
.order_by(UserGroup.name)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def add_member(db: Session, group: UserGroup, user: UserAccount, actor_id: int) -> None:
|
||||||
|
if db.get(GroupMember, (group.id, user.id)) is not None:
|
||||||
|
return
|
||||||
|
db.add(GroupMember(group_id=group.id, user_id=user.id))
|
||||||
|
audit.record(db, "admin.group_member_added", actor_id=actor_id, target_type="user",
|
||||||
|
target_id=user.id, details={"group": group.id})
|
||||||
|
|
||||||
|
|
||||||
|
def remove_member(db: Session, group: UserGroup, user: UserAccount, actor_id: int) -> None:
|
||||||
|
result = db.execute(
|
||||||
|
delete(GroupMember).where(GroupMember.group_id == group.id, GroupMember.user_id == user.id)
|
||||||
|
)
|
||||||
|
if result.rowcount: # type: ignore[attr-defined]
|
||||||
|
audit.record(db, "admin.group_member_removed", actor_id=actor_id, target_type="user",
|
||||||
|
target_id=user.id, details={"group": group.id})
|
||||||
|
|
||||||
|
|
||||||
|
def all_groups(db: Session) -> list[UserGroup]:
|
||||||
|
return list(db.scalars(select(UserGroup).order_by(UserGroup.name)))
|
||||||
|
|
||||||
|
|
||||||
|
def list_with_counts_by_id(db: Session) -> list[tuple[int, int]]:
|
||||||
|
rows = db.execute(
|
||||||
|
select(GroupMember.group_id, func.count()).group_by(GroupMember.group_id)
|
||||||
|
).all()
|
||||||
|
return [(gid, int(n)) for gid, n in rows]
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Passkeys (WebAuthn) mit py_webauthn.
|
||||||
|
|
||||||
|
- Anmeldung ohne Benutzername: Der Passkey sagt, wem er gehört.
|
||||||
|
- Benutzerprüfung ist Pflicht (PIN, Fingerabdruck, Gesicht). Ein Passkey ersetzt
|
||||||
|
damit Passwort und zweiten Faktor zugleich.
|
||||||
|
- Als zweiter Faktor nach dem Passwort ist er ebenfalls nutzbar.
|
||||||
|
- Gespeichert werden nur öffentlicher Schlüssel, Zähler und ein Name; keine
|
||||||
|
Bestätigung des Herstellers (attestation "none"), keine Gerätedaten.
|
||||||
|
|
||||||
|
Die Challenge liegt mit Ablaufzeit in der Datenbank und gilt genau einmal.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import secrets
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import delete, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from webauthn import (
|
||||||
|
generate_authentication_options,
|
||||||
|
generate_registration_options,
|
||||||
|
options_to_json,
|
||||||
|
verify_authentication_response,
|
||||||
|
verify_registration_response,
|
||||||
|
)
|
||||||
|
from webauthn.helpers import parse_authentication_credential_json
|
||||||
|
from webauthn.helpers.structs import (
|
||||||
|
AttestationConveyancePreference,
|
||||||
|
AuthenticatorSelectionCriteria,
|
||||||
|
AuthenticatorTransport,
|
||||||
|
PublicKeyCredentialDescriptor,
|
||||||
|
ResidentKeyRequirement,
|
||||||
|
UserVerificationRequirement,
|
||||||
|
)
|
||||||
|
|
||||||
|
from surveybox.accounts import audit
|
||||||
|
from surveybox.accounts.service import AccountError
|
||||||
|
from surveybox.models import (
|
||||||
|
AuthChallenge,
|
||||||
|
ChallengePurpose,
|
||||||
|
RecoveryCode,
|
||||||
|
UserAccount,
|
||||||
|
WebAuthnCredential,
|
||||||
|
)
|
||||||
|
from surveybox.security.tokens import new_token, token_hash
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
CHALLENGE_LIFETIME = timedelta(minutes=5)
|
||||||
|
RP_NAME = "Surveybox"
|
||||||
|
MAX_PASSKEYS = 20
|
||||||
|
KNOWN_TRANSPORTS = {t.value for t in AuthenticatorTransport}
|
||||||
|
|
||||||
|
|
||||||
|
def _rp(settings: Settings) -> tuple[str, str]:
|
||||||
|
return settings.public_host, settings.public_origin
|
||||||
|
|
||||||
|
|
||||||
|
def _store_challenge(
|
||||||
|
db: Session, purpose: ChallengePurpose, challenge: bytes, user_id: int | None
|
||||||
|
) -> str:
|
||||||
|
handle = new_token()
|
||||||
|
db.add(
|
||||||
|
AuthChallenge(
|
||||||
|
handle_hash=token_hash(handle),
|
||||||
|
purpose=purpose,
|
||||||
|
user_id=user_id,
|
||||||
|
challenge=challenge,
|
||||||
|
expires_at=datetime.now(UTC) + CHALLENGE_LIFETIME,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return handle
|
||||||
|
|
||||||
|
|
||||||
|
def _take_challenge(
|
||||||
|
db: Session, handle: str, purpose: ChallengePurpose, user_id: int | None
|
||||||
|
) -> bytes:
|
||||||
|
"""Holt und löscht die Challenge. Jede Challenge gilt genau einmal."""
|
||||||
|
if not handle or len(handle) > 128:
|
||||||
|
raise AccountError("passkey_expired")
|
||||||
|
row = db.scalar(select(AuthChallenge).where(AuthChallenge.handle_hash == token_hash(handle)))
|
||||||
|
if row is None:
|
||||||
|
raise AccountError("passkey_expired")
|
||||||
|
db.delete(row)
|
||||||
|
if (
|
||||||
|
row.purpose != purpose
|
||||||
|
or row.user_id != user_id
|
||||||
|
or row.expires_at <= datetime.now(UTC)
|
||||||
|
):
|
||||||
|
raise AccountError("passkey_expired")
|
||||||
|
return row.challenge
|
||||||
|
|
||||||
|
|
||||||
|
def _descriptor(cred: WebAuthnCredential) -> PublicKeyCredentialDescriptor:
|
||||||
|
transports = [
|
||||||
|
AuthenticatorTransport(t) for t in (cred.transports or []) if t in KNOWN_TRANSPORTS
|
||||||
|
]
|
||||||
|
return PublicKeyCredentialDescriptor(id=cred.credential_id, transports=transports or None)
|
||||||
|
|
||||||
|
|
||||||
|
def _options(options: Any, handle: str) -> dict[str, Any]:
|
||||||
|
return {"challengeId": handle, "publicKey": json.loads(options_to_json(options))}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Registrieren
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def registration_options(db: Session, settings: Settings, user: UserAccount) -> dict[str, Any]:
|
||||||
|
if len(user.passkeys) >= MAX_PASSKEYS:
|
||||||
|
raise AccountError("passkey_limit")
|
||||||
|
if user.webauthn_user_id is None:
|
||||||
|
user.webauthn_user_id = secrets.token_bytes(32)
|
||||||
|
rp_id, _ = _rp(settings)
|
||||||
|
options = generate_registration_options(
|
||||||
|
rp_id=rp_id,
|
||||||
|
rp_name=RP_NAME,
|
||||||
|
user_id=user.webauthn_user_id,
|
||||||
|
user_name=user.email,
|
||||||
|
user_display_name=user.display_name,
|
||||||
|
attestation=AttestationConveyancePreference.NONE,
|
||||||
|
authenticator_selection=AuthenticatorSelectionCriteria(
|
||||||
|
resident_key=ResidentKeyRequirement.REQUIRED,
|
||||||
|
user_verification=UserVerificationRequirement.REQUIRED,
|
||||||
|
),
|
||||||
|
exclude_credentials=[_descriptor(c) for c in user.passkeys],
|
||||||
|
)
|
||||||
|
handle = _store_challenge(db, ChallengePurpose.REGISTER, options.challenge, user.id)
|
||||||
|
return _options(options, handle)
|
||||||
|
|
||||||
|
|
||||||
|
def register(
|
||||||
|
db: Session,
|
||||||
|
settings: Settings,
|
||||||
|
user: UserAccount,
|
||||||
|
handle: str,
|
||||||
|
credential: dict[str, Any],
|
||||||
|
name: str,
|
||||||
|
) -> WebAuthnCredential:
|
||||||
|
challenge = _take_challenge(db, handle, ChallengePurpose.REGISTER, user.id)
|
||||||
|
rp_id, origin = _rp(settings)
|
||||||
|
try:
|
||||||
|
verified = verify_registration_response(
|
||||||
|
credential=credential,
|
||||||
|
expected_challenge=challenge,
|
||||||
|
expected_rp_id=rp_id,
|
||||||
|
expected_origin=origin,
|
||||||
|
require_user_verification=True,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
raise AccountError("passkey_failed") from exc
|
||||||
|
|
||||||
|
exists = db.scalar(
|
||||||
|
select(WebAuthnCredential.id).where(
|
||||||
|
WebAuthnCredential.credential_id == verified.credential_id
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if exists is not None:
|
||||||
|
raise AccountError("passkey_exists")
|
||||||
|
|
||||||
|
response = credential.get("response")
|
||||||
|
raw_transports = response.get("transports") if isinstance(response, dict) else None
|
||||||
|
transports = [
|
||||||
|
t for t in (raw_transports if isinstance(raw_transports, list) else [])
|
||||||
|
if isinstance(t, str) and t in KNOWN_TRANSPORTS
|
||||||
|
]
|
||||||
|
clean_name = " ".join(name.split())[:60] or "Passkey"
|
||||||
|
row = WebAuthnCredential(
|
||||||
|
user_id=user.id,
|
||||||
|
credential_id=verified.credential_id,
|
||||||
|
public_key=verified.credential_public_key,
|
||||||
|
sign_count=verified.sign_count,
|
||||||
|
transports=transports or None,
|
||||||
|
name=clean_name,
|
||||||
|
backed_up=bool(verified.credential_backed_up),
|
||||||
|
)
|
||||||
|
user.passkeys.append(row)
|
||||||
|
audit.record(db, "account.passkey_added", actor_id=user.id)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Anmelden / zweiter Faktor
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def login_options(db: Session, settings: Settings) -> dict[str, Any]:
|
||||||
|
rp_id, _ = _rp(settings)
|
||||||
|
options = generate_authentication_options(
|
||||||
|
rp_id=rp_id, user_verification=UserVerificationRequirement.REQUIRED
|
||||||
|
)
|
||||||
|
handle = _store_challenge(db, ChallengePurpose.LOGIN, options.challenge, None)
|
||||||
|
return _options(options, handle)
|
||||||
|
|
||||||
|
|
||||||
|
def mfa_options(db: Session, settings: Settings, user: UserAccount) -> dict[str, Any]:
|
||||||
|
if not user.passkeys:
|
||||||
|
raise AccountError("passkey_none")
|
||||||
|
rp_id, _ = _rp(settings)
|
||||||
|
options = generate_authentication_options(
|
||||||
|
rp_id=rp_id,
|
||||||
|
allow_credentials=[_descriptor(c) for c in user.passkeys],
|
||||||
|
user_verification=UserVerificationRequirement.REQUIRED,
|
||||||
|
)
|
||||||
|
handle = _store_challenge(db, ChallengePurpose.MFA, options.challenge, user.id)
|
||||||
|
return _options(options, handle)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_assertion(
|
||||||
|
db: Session,
|
||||||
|
settings: Settings,
|
||||||
|
handle: str,
|
||||||
|
credential: dict[str, Any],
|
||||||
|
purpose: ChallengePurpose,
|
||||||
|
user: UserAccount | None = None,
|
||||||
|
) -> UserAccount:
|
||||||
|
challenge = _take_challenge(db, handle, purpose, user.id if user else None)
|
||||||
|
try:
|
||||||
|
parsed = parse_authentication_credential_json(credential)
|
||||||
|
except Exception as exc:
|
||||||
|
raise AccountError("passkey_failed") from exc
|
||||||
|
|
||||||
|
row = db.scalar(
|
||||||
|
select(WebAuthnCredential).where(WebAuthnCredential.credential_id == parsed.raw_id)
|
||||||
|
)
|
||||||
|
if row is None or (user is not None and row.user_id != user.id):
|
||||||
|
raise AccountError("passkey_unknown")
|
||||||
|
owner = db.get(UserAccount, row.user_id)
|
||||||
|
if owner is None or not owner.is_active:
|
||||||
|
raise AccountError("passkey_unknown")
|
||||||
|
user_handle = parsed.response.user_handle
|
||||||
|
if user_handle is not None and user_handle != owner.webauthn_user_id:
|
||||||
|
raise AccountError("passkey_unknown")
|
||||||
|
|
||||||
|
rp_id, origin = _rp(settings)
|
||||||
|
try:
|
||||||
|
verified = verify_authentication_response(
|
||||||
|
credential=credential,
|
||||||
|
expected_challenge=challenge,
|
||||||
|
expected_rp_id=rp_id,
|
||||||
|
expected_origin=origin,
|
||||||
|
credential_public_key=row.public_key,
|
||||||
|
credential_current_sign_count=row.sign_count,
|
||||||
|
require_user_verification=True,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
raise AccountError("passkey_failed") from exc
|
||||||
|
|
||||||
|
row.sign_count = verified.new_sign_count
|
||||||
|
row.backed_up = bool(verified.credential_backed_up)
|
||||||
|
row.last_used_at = datetime.now(UTC)
|
||||||
|
return owner
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Verwalten
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def remove(db: Session, user: UserAccount, credential_pk: int) -> None:
|
||||||
|
row = next((c for c in user.passkeys if c.id == credential_pk), None)
|
||||||
|
if row is None:
|
||||||
|
raise AccountError("passkey_unknown")
|
||||||
|
if user.is_admin and not user.has_totp and len(user.passkeys) <= 1:
|
||||||
|
raise AccountError("admin_needs_mfa")
|
||||||
|
user.passkeys.remove(row) # delete-orphan: Zeile wird gelöscht
|
||||||
|
if not user.has_second_factor:
|
||||||
|
db.execute(delete(RecoveryCode).where(RecoveryCode.user_id == user.id))
|
||||||
|
audit.record(db, "account.passkey_removed", actor_id=user.id)
|
||||||
|
|
||||||
|
|
||||||
|
def purge_expired_challenges(db: Session) -> int:
|
||||||
|
result = db.execute(delete(AuthChallenge).where(AuthChallenge.expires_at < datetime.now(UTC)))
|
||||||
|
return int(result.rowcount or 0) # type: ignore[attr-defined]
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Ratenbegrenzung über die Datenbank (gilt für alle Webprozesse gemeinsam)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
from sqlalchemy import delete, text
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.models import RateLimit
|
||||||
|
|
||||||
|
_HIT = text(
|
||||||
|
"""
|
||||||
|
INSERT INTO rate_limit (key, window_start, count)
|
||||||
|
VALUES (:key, :now, 1)
|
||||||
|
ON CONFLICT (key) DO UPDATE SET
|
||||||
|
count = CASE WHEN rate_limit.window_start <= :cutoff THEN 1
|
||||||
|
ELSE rate_limit.count + 1 END,
|
||||||
|
window_start = CASE WHEN rate_limit.window_start <= :cutoff THEN :now
|
||||||
|
ELSE rate_limit.window_start END
|
||||||
|
RETURNING count
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def hit(db: Session, key: str, limit: int, window: timedelta) -> bool:
|
||||||
|
"""Zählt einen Versuch. False, wenn das Limit im Zeitfenster überschritten ist."""
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
count = db.execute(_HIT, {"key": key, "now": now, "cutoff": now - window}).scalar_one()
|
||||||
|
return int(count) <= limit
|
||||||
|
|
||||||
|
|
||||||
|
def exceeded(db: Session, key: str, limit: int, window: timedelta) -> bool:
|
||||||
|
"""Ist das Limit im laufenden Zeitfenster schon erreicht? Zählt nicht mit."""
|
||||||
|
row = db.get(RateLimit, key)
|
||||||
|
if row is None:
|
||||||
|
return False
|
||||||
|
if row.window_start <= datetime.now(UTC) - window:
|
||||||
|
return False
|
||||||
|
return row.count >= limit
|
||||||
|
|
||||||
|
|
||||||
|
def reset(db: Session, key: str) -> None:
|
||||||
|
db.execute(delete(RateLimit).where(RateLimit.key == key))
|
||||||
|
|
||||||
|
|
||||||
|
def purge_stale(db: Session, older_than: timedelta = timedelta(days=1)) -> int:
|
||||||
|
cutoff = datetime.now(UTC) - older_than
|
||||||
|
result = db.execute(delete(RateLimit).where(RateLimit.window_start < cutoff))
|
||||||
|
return int(result.rowcount or 0) # type: ignore[attr-defined]
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Selbstregistrierung (freiwilliges Konto).
|
||||||
|
|
||||||
|
Drei Stufen, eingestellt in der Verwaltung:
|
||||||
|
|
||||||
|
- "off": keine Selbstregistrierung; Konten legen nur Administratoren an.
|
||||||
|
- "guests" (Standard): nur, wer als Gast eine Adresse bestätigt hat, also
|
||||||
|
über einen Formularlink teilgenommen hat.
|
||||||
|
- "open": jede Person mit einer E-Mail-Adresse.
|
||||||
|
|
||||||
|
Ablauf: Name und Adresse eingeben, Mail mit Link (24 Stunden), Passwort
|
||||||
|
setzen. Erst dann entsteht das Konto; unbestätigte Anfragen hinterlassen
|
||||||
|
nichts in der Datenbank. Der Link ist signiert statt gespeichert und kann nur
|
||||||
|
einmal ein Konto anlegen (die Adresse ist danach vergeben). Neue Konten sind
|
||||||
|
immer Teilnehmer. Gast-Antworten mit derselben bestätigten Adresse gehen auf
|
||||||
|
das Konto über (forms.guests.claim_for_user).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.accounts import audit, ratelimit, service
|
||||||
|
from surveybox.models import AppSetting, Role, UserAccount
|
||||||
|
from surveybox.security.client_ip import ip_key
|
||||||
|
from surveybox.security.tokens import constant_time_equal, derive_key, keyed_hash
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
KEY = "accounts"
|
||||||
|
LEVELS = ("off", "guests", "open")
|
||||||
|
DEFAULT_LEVEL = "guests"
|
||||||
|
VALIDITY = timedelta(hours=24)
|
||||||
|
PER_IP = 10
|
||||||
|
PER_EMAIL = 3
|
||||||
|
WINDOW = timedelta(hours=1)
|
||||||
|
|
||||||
|
|
||||||
|
class RegistrationError(ValueError):
|
||||||
|
def __init__(self, code: str) -> None:
|
||||||
|
super().__init__(code)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
def level(db: Session) -> str:
|
||||||
|
row = db.get(AppSetting, KEY)
|
||||||
|
value = (row.value or {}).get("self_registration") if row is not None else None
|
||||||
|
return value if value in LEVELS else DEFAULT_LEVEL
|
||||||
|
|
||||||
|
|
||||||
|
def set_level(db: Session, value: str) -> None:
|
||||||
|
if value not in LEVELS:
|
||||||
|
raise RegistrationError("level_invalid")
|
||||||
|
row = db.get(AppSetting, KEY)
|
||||||
|
if row is None:
|
||||||
|
db.add(AppSetting(key=KEY, value={"self_registration": value}))
|
||||||
|
else:
|
||||||
|
row.value = {**(row.value or {}), "self_registration": value}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Signierter Link
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _b64(data: bytes) -> str:
|
||||||
|
return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
def _unb64(text: str) -> bytes:
|
||||||
|
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
||||||
|
|
||||||
|
|
||||||
|
def _mac(secret_key: str, payload: bytes) -> bytes:
|
||||||
|
return keyed_hash(derive_key(secret_key, "registration"), payload.decode("ascii"))[:20]
|
||||||
|
|
||||||
|
|
||||||
|
def make_token(
|
||||||
|
secret_key: str, email: str, name: str, language: str, now: float | None = None
|
||||||
|
) -> str:
|
||||||
|
expires = int((now if now is not None else time.time()) + VALIDITY.total_seconds())
|
||||||
|
payload = _b64(json.dumps({"e": email, "n": name, "l": language, "x": expires},
|
||||||
|
ensure_ascii=False).encode("utf-8")).encode("ascii")
|
||||||
|
return f"{payload.decode('ascii')}.{_b64(_mac(secret_key, payload))}"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Pending:
|
||||||
|
email: str
|
||||||
|
name: str
|
||||||
|
language: str
|
||||||
|
|
||||||
|
|
||||||
|
def parse_token(secret_key: str, token: str, now: float | None = None) -> Pending | None:
|
||||||
|
if not token or len(token) > 1500 or "." not in token:
|
||||||
|
return None
|
||||||
|
raw, _, mac = token.partition(".")
|
||||||
|
try:
|
||||||
|
given = _unb64(mac)
|
||||||
|
expected = _mac(secret_key, raw.encode("ascii"))
|
||||||
|
if not constant_time_equal(expected, given):
|
||||||
|
return None
|
||||||
|
data = json.loads(_unb64(raw).decode("utf-8"))
|
||||||
|
email, name, language, expires = data["e"], data["n"], data["l"], int(data["x"])
|
||||||
|
except (binascii.Error, UnicodeError, ValueError, KeyError, TypeError):
|
||||||
|
return None
|
||||||
|
if expires < (now if now is not None else time.time()):
|
||||||
|
return None
|
||||||
|
if not all(isinstance(v, str) for v in (email, name, language)):
|
||||||
|
return None
|
||||||
|
return Pending(email, name, language)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Ablauf
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Request:
|
||||||
|
"""Was nach einer Anfrage zu senden ist."""
|
||||||
|
|
||||||
|
email: str
|
||||||
|
name: str
|
||||||
|
token: str | None # None: Konto existiert schon (Hinweis statt Link)
|
||||||
|
|
||||||
|
|
||||||
|
def request(
|
||||||
|
db: Session, settings: Settings, email: str, name: str, language: str, client_ip: str
|
||||||
|
) -> Request | None:
|
||||||
|
"""Prüft eine Anfrage. None: nichts senden (Aufrufer antwortet trotzdem gleich)."""
|
||||||
|
current = level(db)
|
||||||
|
if current == "off":
|
||||||
|
return None
|
||||||
|
address = service.normalize_email(email)
|
||||||
|
display = " ".join(name.split())
|
||||||
|
if not service.email_valid(address):
|
||||||
|
raise RegistrationError("email_invalid")
|
||||||
|
if not display or len(display) > 120:
|
||||||
|
raise RegistrationError("name_invalid")
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
ip_limit = f"register-ip:{ip_key(secret, client_ip)}"
|
||||||
|
mail_limit = f"register-mail:{ip_key(secret, address)}"
|
||||||
|
if ratelimit.exceeded(db, ip_limit, PER_IP, WINDOW):
|
||||||
|
return None
|
||||||
|
ratelimit.hit(db, ip_limit, PER_IP, WINDOW)
|
||||||
|
if ratelimit.exceeded(db, mail_limit, PER_EMAIL, WINDOW):
|
||||||
|
return None
|
||||||
|
ratelimit.hit(db, mail_limit, PER_EMAIL, WINDOW)
|
||||||
|
if service.find_by_email(db, address) is not None:
|
||||||
|
return Request(address, display, None)
|
||||||
|
if current == "guests":
|
||||||
|
from surveybox.forms import guests
|
||||||
|
|
||||||
|
if guests.confirmed_contact(db, address) is None:
|
||||||
|
return None
|
||||||
|
return Request(address, display, make_token(secret, address, display, language))
|
||||||
|
|
||||||
|
|
||||||
|
def complete(db: Session, pending: Pending, password: str) -> UserAccount:
|
||||||
|
"""Konto anlegen. Wirft AccountError (Passwort) oder RegistrationError."""
|
||||||
|
if level(db) == "off":
|
||||||
|
raise RegistrationError("registration_off")
|
||||||
|
if service.find_by_email(db, pending.email) is not None:
|
||||||
|
raise RegistrationError("email_taken")
|
||||||
|
user = service.create_user(db, pending.email, pending.name, Role.PARTICIPANT, None)
|
||||||
|
user.language = pending.language or None
|
||||||
|
service.set_password(db, user, password)
|
||||||
|
user.email_verified_at = datetime.now(UTC)
|
||||||
|
audit.record(db, "account.registered", actor_id=user.id, target_type="user",
|
||||||
|
target_id=user.id)
|
||||||
|
from surveybox.forms import guests
|
||||||
|
|
||||||
|
guests.claim_for_user(db, user)
|
||||||
|
return user
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Reichweite eines Benutzers in der Gruppenhierarchie.
|
||||||
|
|
||||||
|
- Rechte wirken nach unten: Wer eine Gruppe verwaltet (Gruppenadministrator)
|
||||||
|
oder in ihr Umfragen anlegt (Gruppenersteller), darf das auch in allen
|
||||||
|
Untergruppen. Gruppenadministratoren dürfen immer auch Umfragen anlegen.
|
||||||
|
- Mitgliedschaft wirkt nach oben: Wer Mitglied einer Untergruppe ist, zählt
|
||||||
|
bei Freigaben und Teams auch als Mitglied der darüberliegenden Gruppen.
|
||||||
|
- Instanzadministratoren verwalten alles; Gruppen ohne eigenen
|
||||||
|
Gruppenadministrator verwalten nur sie.
|
||||||
|
|
||||||
|
Die Hierarchie ist klein (einige hundert Gruppen); sie wird je Anfrage
|
||||||
|
einmal vollständig geladen und im Speicher ausgewertet.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Iterable, Mapping
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.models import GroupMember, GroupRole, GroupRoleKind, Role, UserAccount, UserGroup
|
||||||
|
|
||||||
|
Tree = Mapping[int, int | None] # Gruppe -> übergeordnete Gruppe
|
||||||
|
|
||||||
|
|
||||||
|
def load_tree(db: Session) -> dict[int, int | None]:
|
||||||
|
return {gid: parent for gid, parent in db.execute(select(UserGroup.id, UserGroup.parent_id))}
|
||||||
|
|
||||||
|
|
||||||
|
def children_map(tree: Tree) -> dict[int, list[int]]:
|
||||||
|
result: dict[int, list[int]] = {}
|
||||||
|
for gid, parent in tree.items():
|
||||||
|
if parent is not None:
|
||||||
|
result.setdefault(parent, []).append(gid)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def descendants(tree: Tree, roots: Iterable[int]) -> set[int]:
|
||||||
|
"""Die Gruppen selbst und alles darunter."""
|
||||||
|
kids = children_map(tree)
|
||||||
|
result: set[int] = set()
|
||||||
|
stack = [r for r in roots if r in tree]
|
||||||
|
while stack:
|
||||||
|
gid = stack.pop()
|
||||||
|
if gid in result:
|
||||||
|
continue
|
||||||
|
result.add(gid)
|
||||||
|
stack.extend(kids.get(gid, []))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def ancestors(tree: Tree, ids: Iterable[int]) -> set[int]:
|
||||||
|
"""Die Gruppen selbst und alles darüber."""
|
||||||
|
result: set[int] = set()
|
||||||
|
for gid in ids:
|
||||||
|
current: int | None = gid
|
||||||
|
while current is not None and current not in result and current in tree:
|
||||||
|
result.add(current)
|
||||||
|
current = tree[current]
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def would_cycle(tree: Tree, group_id: int, new_parent: int | None) -> bool:
|
||||||
|
return new_parent is not None and new_parent in descendants(tree, [group_id])
|
||||||
|
|
||||||
|
|
||||||
|
def depth_order(tree: Tree, names: Mapping[int, str], only: set[int] | None = None) -> list[
|
||||||
|
tuple[int, int]
|
||||||
|
]:
|
||||||
|
"""(Gruppe, Tiefe) in Baumreihenfolge, alphabetisch je Ebene."""
|
||||||
|
kids = children_map(tree)
|
||||||
|
visible = set(tree) if only is None else only
|
||||||
|
roots = [g for g in visible if tree.get(g) not in visible]
|
||||||
|
ordered: list[tuple[int, int]] = []
|
||||||
|
|
||||||
|
def walk(gid: int, depth: int) -> None:
|
||||||
|
ordered.append((gid, depth))
|
||||||
|
for child in sorted(kids.get(gid, []), key=lambda c: names.get(c, "").lower()):
|
||||||
|
if child in visible:
|
||||||
|
walk(child, depth + 1)
|
||||||
|
|
||||||
|
for root in sorted(roots, key=lambda r: names.get(r, "").lower()):
|
||||||
|
walk(root, 0)
|
||||||
|
return ordered
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Scope:
|
||||||
|
user_id: int
|
||||||
|
instance_admin: bool
|
||||||
|
global_creator: bool # Instanzrolle Administrator oder Ersteller
|
||||||
|
managed: frozenset[int] = field(default_factory=frozenset) # als Gruppenadmin
|
||||||
|
creating: frozenset[int] = field(default_factory=frozenset) # darf Umfragen anlegen
|
||||||
|
direct_admin: frozenset[int] = field(default_factory=frozenset)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def group_admin(self) -> bool:
|
||||||
|
return bool(self.managed)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def can_create_forms(self) -> bool:
|
||||||
|
return self.global_creator or bool(self.creating)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def can_manage_groups(self) -> bool:
|
||||||
|
return self.instance_admin or self.group_admin
|
||||||
|
|
||||||
|
def manages(self, group_id: int | None) -> bool:
|
||||||
|
return self.instance_admin or (group_id is not None and group_id in self.managed)
|
||||||
|
|
||||||
|
def may_create_in(self, group_id: int | None) -> bool:
|
||||||
|
if group_id is None:
|
||||||
|
return self.global_creator
|
||||||
|
return self.global_creator or group_id in self.creating
|
||||||
|
|
||||||
|
|
||||||
|
def roles_of(db: Session, user_id: int) -> dict[str, set[int]]:
|
||||||
|
result: dict[str, set[int]] = {GroupRoleKind.ADMIN: set(), GroupRoleKind.CREATOR: set()}
|
||||||
|
for gid, role in db.execute(
|
||||||
|
select(GroupRole.group_id, GroupRole.role).where(GroupRole.user_id == user_id)
|
||||||
|
):
|
||||||
|
result.setdefault(role, set()).add(gid)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def scope_for(db: Session, user: UserAccount, tree: Tree | None = None) -> Scope:
|
||||||
|
roles = roles_of(db, user.id)
|
||||||
|
tree = tree if tree is not None else (load_tree(db) if any(roles.values()) else {})
|
||||||
|
managed = descendants(tree, roles[GroupRoleKind.ADMIN])
|
||||||
|
creating = managed | descendants(tree, roles[GroupRoleKind.CREATOR])
|
||||||
|
return Scope(
|
||||||
|
user_id=user.id,
|
||||||
|
instance_admin=user.role == Role.ADMIN,
|
||||||
|
global_creator=user.role in (Role.ADMIN, Role.CREATOR),
|
||||||
|
managed=frozenset(managed),
|
||||||
|
creating=frozenset(creating),
|
||||||
|
direct_admin=frozenset(roles[GroupRoleKind.ADMIN]),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def has_group_admin_role(db: Session, user_id: int) -> bool:
|
||||||
|
return (
|
||||||
|
db.scalar(
|
||||||
|
select(GroupRole.user_id)
|
||||||
|
.where(GroupRole.user_id == user_id, GroupRole.role == GroupRoleKind.ADMIN)
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
is not None
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def role_flags(db: Session, user_id: int) -> dict[str, bool]:
|
||||||
|
"""Für die Navigation: hat der Benutzer Gruppenrollen?"""
|
||||||
|
found = set(db.scalars(select(GroupRole.role).where(GroupRole.user_id == user_id).distinct()))
|
||||||
|
return {"admin": GroupRoleKind.ADMIN in found, "creator": bool(found)}
|
||||||
|
|
||||||
|
|
||||||
|
def member_groups(db: Session, user_id: int, tree: Tree | None = None) -> set[int]:
|
||||||
|
"""Gruppen, in denen der Benutzer Mitglied ist, samt allen übergeordneten."""
|
||||||
|
direct = set(db.scalars(select(GroupMember.group_id).where(GroupMember.user_id == user_id)))
|
||||||
|
if not direct:
|
||||||
|
return set()
|
||||||
|
return ancestors(tree if tree is not None else load_tree(db), direct)
|
||||||
|
|
||||||
|
|
||||||
|
def users_in_groups(db: Session, group_ids: Iterable[int]) -> list[UserAccount]:
|
||||||
|
ids = list(group_ids)
|
||||||
|
if not ids:
|
||||||
|
return []
|
||||||
|
members = select(GroupMember.user_id).where(GroupMember.group_id.in_(ids))
|
||||||
|
return list(
|
||||||
|
db.scalars(
|
||||||
|
select(UserAccount)
|
||||||
|
.where(UserAccount.id.in_(members), UserAccount.is_active.is_(True))
|
||||||
|
.order_by(UserAccount.display_name)
|
||||||
|
.limit(2000)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def user_fully_inside(db: Session, scope: Scope, user: UserAccount) -> bool:
|
||||||
|
"""Darf ein Gruppenadministrator dieses Konto bearbeiten (Einladungslink usw.)?
|
||||||
|
|
||||||
|
Nur Teilnehmer ohne Instanzrolle, die ausschließlich in Gruppen seiner
|
||||||
|
Reichweite Mitglied sind und keine Gruppenrollen außerhalb haben.
|
||||||
|
"""
|
||||||
|
if scope.instance_admin:
|
||||||
|
return True
|
||||||
|
if user.role != Role.PARTICIPANT or user.id == scope.user_id:
|
||||||
|
return False
|
||||||
|
groups = set(db.scalars(select(GroupMember.group_id).where(GroupMember.user_id == user.id)))
|
||||||
|
role_groups = set(db.scalars(select(GroupRole.group_id).where(GroupRole.user_id == user.id)))
|
||||||
|
return bool(groups) and (groups | role_groups) <= scope.managed
|
||||||
|
|
||||||
|
|
||||||
|
def ordered_groups(db: Session, only: Iterable[int] | None = None) -> list[tuple[UserGroup, int]]:
|
||||||
|
"""Gruppen als Baum (Gruppe, Tiefe), optional nur eine Auswahl."""
|
||||||
|
groups = {g.id: g for g in db.scalars(select(UserGroup))}
|
||||||
|
tree = {g.id: g.parent_id for g in groups.values()}
|
||||||
|
names = {g.id: g.name for g in groups.values()}
|
||||||
|
visible = None if only is None else set(only)
|
||||||
|
return [(groups[gid], depth) for gid, depth in depth_order(tree, names, visible)]
|
||||||
|
|
||||||
|
|
||||||
|
def creatable_groups(db: Session, found: Scope) -> list[tuple[UserGroup, int]]:
|
||||||
|
"""Gruppen, für die der Benutzer Umfragen anlegen darf."""
|
||||||
|
if found.global_creator:
|
||||||
|
return ordered_groups(db)
|
||||||
|
return ordered_groups(db, found.creating)
|
||||||
@@ -0,0 +1,497 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Abläufe rund um Konten: Anmeldung, zweiter Faktor, Einmal-Links, Verwaltung.
|
||||||
|
|
||||||
|
Alle Funktionen ändern nur die übergebene Datenbanksitzung; committen muss
|
||||||
|
der Aufrufer. So bleibt ein Ablauf (z. B. Konto anlegen + Protokolleintrag)
|
||||||
|
eine Transaktion.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from enum import StrEnum
|
||||||
|
|
||||||
|
from sqlalchemy import delete, func, select, update
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.accounts import audit, ratelimit, sessions
|
||||||
|
from surveybox.models import ActionToken, RecoveryCode, Role, TokenPurpose, UserAccount
|
||||||
|
from surveybox.security import passwords, recovery, secretbox, totp
|
||||||
|
from surveybox.security.client_ip import ip_key
|
||||||
|
from surveybox.security.tokens import new_token, token_hash
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
LOCK_AFTER_FAILURES = 5
|
||||||
|
LOCK_DURATION = timedelta(minutes=15)
|
||||||
|
# Fehlversuche je Adresse im Zeitfenster; erfolgreiche Anmeldungen zählen nicht.
|
||||||
|
LOGIN_LIMIT_PER_IP = 30
|
||||||
|
LOGIN_WINDOW = timedelta(minutes=15)
|
||||||
|
LINK_LIMIT_PER_IP = 30
|
||||||
|
# "Passwort vergessen": je IP und je Adresse begrenzt
|
||||||
|
RESET_LIMIT_PER_IP = 10
|
||||||
|
RESET_LIMIT_PER_EMAIL = 3
|
||||||
|
RESET_WINDOW = timedelta(hours=1)
|
||||||
|
INVITE_VALIDITY = timedelta(days=7)
|
||||||
|
RESET_VALIDITY = timedelta(hours=24)
|
||||||
|
TOTP_PURPOSE = "totp"
|
||||||
|
ISSUER = "Surveybox"
|
||||||
|
|
||||||
|
_EMAIL = re.compile(r"^[^@\s]{1,64}@[^@\s]{1,252}\.[^@\s]{2,}$")
|
||||||
|
|
||||||
|
|
||||||
|
class AccountError(ValueError):
|
||||||
|
"""Fehler mit einem Code, den die Oberfläche übersetzt."""
|
||||||
|
|
||||||
|
def __init__(self, code: str) -> None:
|
||||||
|
super().__init__(code)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
class LoginOutcome(StrEnum):
|
||||||
|
OK = "ok"
|
||||||
|
MFA_REQUIRED = "mfa_required"
|
||||||
|
INVALID = "invalid"
|
||||||
|
RATE_LIMITED = "rate_limited"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class LoginResult:
|
||||||
|
outcome: LoginOutcome
|
||||||
|
user: UserAccount | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Suchen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_email(email: str) -> str:
|
||||||
|
return email.strip().lower()
|
||||||
|
|
||||||
|
|
||||||
|
def email_valid(email: str) -> bool:
|
||||||
|
return len(email) <= 254 and _EMAIL.fullmatch(email) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def find_by_email(db: Session, email: str) -> UserAccount | None:
|
||||||
|
return db.scalar(select(UserAccount).where(UserAccount.email == normalize_email(email)))
|
||||||
|
|
||||||
|
|
||||||
|
def find_by_public_id(db: Session, public_id: str) -> UserAccount | None:
|
||||||
|
try:
|
||||||
|
pid = uuid.UUID(public_id)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return db.scalar(select(UserAccount).where(UserAccount.public_id == pid))
|
||||||
|
|
||||||
|
|
||||||
|
def count_active_admins(db: Session) -> int:
|
||||||
|
return int(
|
||||||
|
db.scalar(
|
||||||
|
select(func.count())
|
||||||
|
.select_from(UserAccount)
|
||||||
|
.where(UserAccount.role == Role.ADMIN, UserAccount.is_active.is_(True))
|
||||||
|
)
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Anmeldung
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def password_login(
|
||||||
|
db: Session, settings: Settings, email: str, password: str, client_ip: str
|
||||||
|
) -> LoginResult:
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
key = f"login-ip:{ip_key(secret, client_ip)}"
|
||||||
|
if ratelimit.exceeded(db, key, LOGIN_LIMIT_PER_IP, LOGIN_WINDOW):
|
||||||
|
return LoginResult(LoginOutcome.RATE_LIMITED)
|
||||||
|
|
||||||
|
user = find_by_email(db, email) if email_valid(normalize_email(email)) else None
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
|
||||||
|
if user is not None and user.locked_until is not None and user.locked_until > now:
|
||||||
|
passwords.verify_password(None, password) # gleiche Antwortzeit
|
||||||
|
ratelimit.hit(db, key, LOGIN_LIMIT_PER_IP, LOGIN_WINDOW)
|
||||||
|
return LoginResult(LoginOutcome.INVALID)
|
||||||
|
|
||||||
|
ok, needs_rehash = passwords.verify_password(user.password_hash if user else None, password)
|
||||||
|
if user is None or not ok or not user.is_active:
|
||||||
|
ratelimit.hit(db, key, LOGIN_LIMIT_PER_IP, LOGIN_WINDOW)
|
||||||
|
if user is not None and not ok:
|
||||||
|
user.failed_logins += 1
|
||||||
|
audit.record(db, "auth.login_failed", target_type="user", target_id=user.id)
|
||||||
|
if user.failed_logins >= LOCK_AFTER_FAILURES:
|
||||||
|
user.locked_until = now + LOCK_DURATION
|
||||||
|
user.failed_logins = 0
|
||||||
|
audit.record(db, "auth.locked", target_type="user", target_id=user.id)
|
||||||
|
return LoginResult(LoginOutcome.INVALID)
|
||||||
|
|
||||||
|
user.failed_logins = 0
|
||||||
|
user.locked_until = None
|
||||||
|
if needs_rehash:
|
||||||
|
user.password_hash = passwords.hash_password(password)
|
||||||
|
if user.has_second_factor:
|
||||||
|
return LoginResult(LoginOutcome.MFA_REQUIRED, user)
|
||||||
|
return LoginResult(LoginOutcome.OK, user)
|
||||||
|
|
||||||
|
|
||||||
|
def complete_login(db: Session, user: UserAccount, method: str) -> None:
|
||||||
|
user.last_login_at = datetime.now(UTC)
|
||||||
|
audit.record(db, "auth.login", actor_id=user.id, details={"method": method})
|
||||||
|
|
||||||
|
|
||||||
|
def verify_second_factor(
|
||||||
|
db: Session, settings: Settings, user: UserAccount, code: str
|
||||||
|
) -> str | None:
|
||||||
|
"""'totp', 'recovery' oder None."""
|
||||||
|
digits = totp.normalize_code(code)
|
||||||
|
if len(digits) == totp.DIGITS and len(code.strip()) <= 8:
|
||||||
|
secret = totp_secret(settings, user)
|
||||||
|
if secret is not None:
|
||||||
|
step = totp.verify(secret, digits, time.time(), user.totp_last_step)
|
||||||
|
if step is not None:
|
||||||
|
user.totp_last_step = step
|
||||||
|
return "totp"
|
||||||
|
return None
|
||||||
|
|
||||||
|
key = settings.secret_key.get_secret_value()
|
||||||
|
row = db.scalar(
|
||||||
|
select(RecoveryCode).where(
|
||||||
|
RecoveryCode.user_id == user.id,
|
||||||
|
RecoveryCode.code_hash == recovery.code_hash(key, code),
|
||||||
|
RecoveryCode.used_at.is_(None),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
row.used_at = datetime.now(UTC)
|
||||||
|
audit.record(db, "auth.recovery_code_used", actor_id=user.id)
|
||||||
|
return "recovery"
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Zweiter Faktor (TOTP) und Wiederherstellungscodes
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _totp_context(user: UserAccount) -> bytes:
|
||||||
|
return f"user:{user.id}".encode()
|
||||||
|
|
||||||
|
|
||||||
|
def totp_secret(settings: Settings, user: UserAccount) -> str | None:
|
||||||
|
if user.totp_secret_enc is None or user.totp_enabled_at is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
raw = secretbox.decrypt(
|
||||||
|
settings.secret_key.get_secret_value(),
|
||||||
|
TOTP_PURPOSE,
|
||||||
|
user.totp_secret_enc,
|
||||||
|
_totp_context(user),
|
||||||
|
)
|
||||||
|
except secretbox.DecryptionError:
|
||||||
|
return None
|
||||||
|
return raw.decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
|
def seal_pending_totp(settings: Settings, user: UserAccount, secret: str) -> str:
|
||||||
|
"""Geheimnis während der Einrichtung verschlüsselt im Formular mitführen."""
|
||||||
|
blob = secretbox.encrypt(
|
||||||
|
settings.secret_key.get_secret_value(), "totp-pending", secret.encode(), _totp_context(user)
|
||||||
|
)
|
||||||
|
return blob.hex()
|
||||||
|
|
||||||
|
|
||||||
|
def open_pending_totp(settings: Settings, user: UserAccount, sealed: str) -> str | None:
|
||||||
|
try:
|
||||||
|
raw = secretbox.decrypt(
|
||||||
|
settings.secret_key.get_secret_value(),
|
||||||
|
"totp-pending",
|
||||||
|
bytes.fromhex(sealed),
|
||||||
|
_totp_context(user),
|
||||||
|
)
|
||||||
|
except (ValueError, secretbox.DecryptionError):
|
||||||
|
return None
|
||||||
|
return raw.decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
|
def totp_qr_svg(user: UserAccount, secret: str) -> str:
|
||||||
|
import segno
|
||||||
|
|
||||||
|
uri = totp.provisioning_uri(secret, user.email, ISSUER)
|
||||||
|
svg: str = segno.make(uri, error="m").svg_inline(scale=5, dark="#000", light="#fff")
|
||||||
|
return svg
|
||||||
|
|
||||||
|
|
||||||
|
def enable_totp(
|
||||||
|
db: Session, settings: Settings, user: UserAccount, secret: str, code: str
|
||||||
|
) -> list[str]:
|
||||||
|
"""Aktiviert TOTP und gibt neue Wiederherstellungscodes zurück."""
|
||||||
|
step = totp.verify(secret, code, time.time(), None)
|
||||||
|
if step is None:
|
||||||
|
raise AccountError("totp_wrong_code")
|
||||||
|
user.totp_secret_enc = secretbox.encrypt(
|
||||||
|
settings.secret_key.get_secret_value(), TOTP_PURPOSE, secret.encode(), _totp_context(user)
|
||||||
|
)
|
||||||
|
user.totp_enabled_at = datetime.now(UTC)
|
||||||
|
user.totp_last_step = step
|
||||||
|
audit.record(db, "account.totp_enabled", actor_id=user.id)
|
||||||
|
return regenerate_recovery_codes(db, settings, user)
|
||||||
|
|
||||||
|
|
||||||
|
def disable_totp(db: Session, user: UserAccount, actor_id: int | None) -> None:
|
||||||
|
user.totp_secret_enc = None
|
||||||
|
user.totp_enabled_at = None
|
||||||
|
user.totp_last_step = None
|
||||||
|
if not user.has_passkey:
|
||||||
|
db.execute(delete(RecoveryCode).where(RecoveryCode.user_id == user.id))
|
||||||
|
audit.record(
|
||||||
|
db, "account.totp_disabled", actor_id=actor_id, target_type="user", target_id=user.id
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def reset_second_factors(db: Session, user: UserAccount, actor_id: int | None) -> None:
|
||||||
|
"""Alle zweiten Faktoren entfernen (Gerät verloren): TOTP, Passkeys, Codes."""
|
||||||
|
user.totp_secret_enc = None
|
||||||
|
user.totp_enabled_at = None
|
||||||
|
user.totp_last_step = None
|
||||||
|
user.passkeys.clear() # delete-orphan
|
||||||
|
db.execute(delete(RecoveryCode).where(RecoveryCode.user_id == user.id))
|
||||||
|
audit.record(
|
||||||
|
db, "admin.mfa_reset", actor_id=actor_id, target_type="user", target_id=user.id
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def regenerate_recovery_codes(db: Session, settings: Settings, user: UserAccount) -> list[str]:
|
||||||
|
key = settings.secret_key.get_secret_value()
|
||||||
|
db.execute(delete(RecoveryCode).where(RecoveryCode.user_id == user.id))
|
||||||
|
codes = recovery.generate_codes()
|
||||||
|
for code in codes:
|
||||||
|
db.add(RecoveryCode(user_id=user.id, code_hash=recovery.code_hash(key, code)))
|
||||||
|
audit.record(db, "account.recovery_codes_generated", actor_id=user.id)
|
||||||
|
return codes
|
||||||
|
|
||||||
|
|
||||||
|
def remaining_recovery_codes(db: Session, user: UserAccount) -> int:
|
||||||
|
return int(
|
||||||
|
db.scalar(
|
||||||
|
select(func.count())
|
||||||
|
.select_from(RecoveryCode)
|
||||||
|
.where(RecoveryCode.user_id == user.id, RecoveryCode.used_at.is_(None))
|
||||||
|
)
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Passwort
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def check_current_password(user: UserAccount, password: str) -> bool:
|
||||||
|
ok, _ = passwords.verify_password(user.password_hash, password)
|
||||||
|
return ok
|
||||||
|
|
||||||
|
|
||||||
|
def set_password(db: Session, user: UserAccount, new_password: str) -> None:
|
||||||
|
problems = passwords.password_problems(new_password, user.email)
|
||||||
|
if problems:
|
||||||
|
raise AccountError(f"password_{problems[0]}")
|
||||||
|
user.password_hash = passwords.hash_password(new_password)
|
||||||
|
user.password_changed_at = datetime.now(UTC)
|
||||||
|
user.failed_logins = 0
|
||||||
|
user.locked_until = None
|
||||||
|
|
||||||
|
|
||||||
|
def change_password(
|
||||||
|
db: Session, user: UserAccount, current: str, new: str, current_session_id: int
|
||||||
|
) -> None:
|
||||||
|
if not check_current_password(user, current):
|
||||||
|
raise AccountError("current_password_wrong")
|
||||||
|
set_password(db, user, new)
|
||||||
|
sessions.destroy_all(db, user.id, except_session_id=current_session_id)
|
||||||
|
audit.record(db, "account.password_changed", actor_id=user.id)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Einmal-Links (Einladung, Zurücksetzen)
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def create_link(
|
||||||
|
db: Session,
|
||||||
|
user: UserAccount,
|
||||||
|
created_by_id: int | None,
|
||||||
|
action: str = "admin.link_created",
|
||||||
|
) -> tuple[str, ActionToken]:
|
||||||
|
"""Einladung, wenn noch kein Passwort gesetzt ist, sonst Zurücksetzen.
|
||||||
|
|
||||||
|
Ältere, noch offene Links derselben Person werden ungültig.
|
||||||
|
"""
|
||||||
|
purpose = TokenPurpose.INVITE if user.password_hash is None else TokenPurpose.RESET
|
||||||
|
validity = INVITE_VALIDITY if purpose == TokenPurpose.INVITE else RESET_VALIDITY
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
db.execute(
|
||||||
|
update(ActionToken)
|
||||||
|
.where(ActionToken.user_id == user.id, ActionToken.used_at.is_(None))
|
||||||
|
.values(used_at=now)
|
||||||
|
)
|
||||||
|
token = new_token()
|
||||||
|
row = ActionToken(
|
||||||
|
token_hash=token_hash(token),
|
||||||
|
purpose=purpose,
|
||||||
|
user_id=user.id,
|
||||||
|
created_by_id=created_by_id,
|
||||||
|
created_at=now,
|
||||||
|
expires_at=now + validity,
|
||||||
|
)
|
||||||
|
db.add(row)
|
||||||
|
audit.record(
|
||||||
|
db,
|
||||||
|
action,
|
||||||
|
actor_id=created_by_id,
|
||||||
|
target_type="user",
|
||||||
|
target_id=user.id,
|
||||||
|
details={"purpose": str(purpose)},
|
||||||
|
)
|
||||||
|
return token, row
|
||||||
|
|
||||||
|
|
||||||
|
def request_reset(
|
||||||
|
db: Session, settings: Settings, email: str, client_ip: str
|
||||||
|
) -> tuple[str, ActionToken, UserAccount] | None:
|
||||||
|
""""Passwort vergessen": neuer Link für ein aktives Konto mit dieser Adresse.
|
||||||
|
|
||||||
|
Gibt None zurück, wenn es kein solches Konto gibt oder zu viele Anfragen
|
||||||
|
kamen. Der Aufrufer antwortet in jedem Fall gleich, damit sich nicht
|
||||||
|
herausfinden lässt, welche Adressen ein Konto haben.
|
||||||
|
"""
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
address = normalize_email(email)
|
||||||
|
ip_limit = f"reset-ip:{ip_key(secret, client_ip)}"
|
||||||
|
mail_limit = f"reset-mail:{ip_key(secret, address)}"
|
||||||
|
if ratelimit.exceeded(db, ip_limit, RESET_LIMIT_PER_IP, RESET_WINDOW):
|
||||||
|
return None
|
||||||
|
ratelimit.hit(db, ip_limit, RESET_LIMIT_PER_IP, RESET_WINDOW)
|
||||||
|
if not email_valid(address):
|
||||||
|
return None
|
||||||
|
if ratelimit.exceeded(db, mail_limit, RESET_LIMIT_PER_EMAIL, RESET_WINDOW):
|
||||||
|
return None
|
||||||
|
ratelimit.hit(db, mail_limit, RESET_LIMIT_PER_EMAIL, RESET_WINDOW)
|
||||||
|
user = find_by_email(db, address)
|
||||||
|
if user is None or not user.is_active:
|
||||||
|
return None
|
||||||
|
token, row = create_link(db, user, None, action="account.reset_requested")
|
||||||
|
return token, row, user
|
||||||
|
|
||||||
|
|
||||||
|
def link_url(settings: Settings, token: str) -> str:
|
||||||
|
return f"{settings.public_origin}/setup/{token}"
|
||||||
|
|
||||||
|
|
||||||
|
def find_link(
|
||||||
|
db: Session, settings: Settings, token: str, client_ip: str
|
||||||
|
) -> tuple[ActionToken, UserAccount] | None:
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
key = f"link-ip:{ip_key(secret, client_ip)}"
|
||||||
|
if ratelimit.exceeded(db, key, LINK_LIMIT_PER_IP, LOGIN_WINDOW):
|
||||||
|
return None
|
||||||
|
row = (
|
||||||
|
db.scalar(select(ActionToken).where(ActionToken.token_hash == token_hash(token)))
|
||||||
|
if token and len(token) <= 128
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
if row is None or row.used_at is not None or row.expires_at <= datetime.now(UTC):
|
||||||
|
ratelimit.hit(db, key, LINK_LIMIT_PER_IP, LOGIN_WINDOW)
|
||||||
|
return None
|
||||||
|
user = db.get(UserAccount, row.user_id)
|
||||||
|
if user is None or not user.is_active:
|
||||||
|
return None
|
||||||
|
return row, user
|
||||||
|
|
||||||
|
|
||||||
|
def complete_link(db: Session, row: ActionToken, user: UserAccount, password: str) -> None:
|
||||||
|
set_password(db, user, password)
|
||||||
|
row.used_at = datetime.now(UTC)
|
||||||
|
sessions.destroy_all(db, user.id)
|
||||||
|
audit.record(
|
||||||
|
db, "account.setup_completed", actor_id=user.id, details={"purpose": row.purpose}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Verwaltung
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def create_user(
|
||||||
|
db: Session, email: str, display_name: str, role: Role, created_by_id: int | None
|
||||||
|
) -> UserAccount:
|
||||||
|
email = normalize_email(email)
|
||||||
|
display_name = display_name.strip()
|
||||||
|
if not email_valid(email):
|
||||||
|
raise AccountError("email_invalid")
|
||||||
|
if not display_name or len(display_name) > 120:
|
||||||
|
raise AccountError("name_invalid")
|
||||||
|
if find_by_email(db, email) is not None:
|
||||||
|
raise AccountError("email_taken")
|
||||||
|
user = UserAccount(email=email, display_name=display_name, role=role, is_active=True)
|
||||||
|
db.add(user)
|
||||||
|
db.flush()
|
||||||
|
audit.record(
|
||||||
|
db,
|
||||||
|
"admin.user_created",
|
||||||
|
actor_id=created_by_id,
|
||||||
|
target_type="user",
|
||||||
|
target_id=user.id,
|
||||||
|
details={"role": str(role)},
|
||||||
|
)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def update_user(
|
||||||
|
db: Session,
|
||||||
|
admin: UserAccount,
|
||||||
|
user: UserAccount,
|
||||||
|
*,
|
||||||
|
display_name: str,
|
||||||
|
role: Role,
|
||||||
|
is_active: bool,
|
||||||
|
) -> list[str]:
|
||||||
|
display_name = display_name.strip()
|
||||||
|
if not display_name or len(display_name) > 120:
|
||||||
|
raise AccountError("name_invalid")
|
||||||
|
removes_admin = user.is_admin and (role != Role.ADMIN or not is_active)
|
||||||
|
if removes_admin and user.id == admin.id:
|
||||||
|
raise AccountError("cannot_demote_self")
|
||||||
|
if removes_admin and user.is_active and count_active_admins(db) <= 1:
|
||||||
|
raise AccountError("last_admin")
|
||||||
|
|
||||||
|
changed: list[str] = []
|
||||||
|
if user.display_name != display_name:
|
||||||
|
user.display_name = display_name
|
||||||
|
changed.append("display_name")
|
||||||
|
if user.role != role:
|
||||||
|
user.role = role
|
||||||
|
changed.append("role")
|
||||||
|
if user.is_active != is_active:
|
||||||
|
user.is_active = is_active
|
||||||
|
changed.append("is_active")
|
||||||
|
if not is_active:
|
||||||
|
sessions.destroy_all(db, user.id)
|
||||||
|
if changed:
|
||||||
|
audit.record(
|
||||||
|
db,
|
||||||
|
"admin.user_updated",
|
||||||
|
actor_id=admin.id,
|
||||||
|
target_type="user",
|
||||||
|
target_id=user.id,
|
||||||
|
details={"fields": changed, "role": user.role, "active": user.is_active},
|
||||||
|
)
|
||||||
|
return changed
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Serverseitige Sitzungen.
|
||||||
|
|
||||||
|
Im Cookie steht nur ein Zufallswert; die Datenbank kennt nur seinen Hash.
|
||||||
|
Wer eine Datenbanksicherung hat, kann damit keine Sitzung übernehmen.
|
||||||
|
Nach dem zweiten Faktor bekommt die Sitzung einen neuen Wert (Schutz vor
|
||||||
|
Session Fixation). Abmelden auf allen Geräten löscht einfach die Zeilen.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
from sqlalchemy import delete, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.models import SessionState, UserAccount, UserSession
|
||||||
|
from surveybox.security.tokens import new_token, token_hash
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
PENDING_MFA_LIFETIME = timedelta(minutes=5)
|
||||||
|
TOUCH_INTERVAL = timedelta(minutes=5)
|
||||||
|
MAX_MFA_ATTEMPTS = 5
|
||||||
|
|
||||||
|
|
||||||
|
def cookie_name(settings: Settings) -> str:
|
||||||
|
# __Host- erzwingt im Browser: nur über HTTPS, nur diese Domain, Pfad /.
|
||||||
|
return "__Host-surveybox_session" if settings.uses_https else "surveybox_session"
|
||||||
|
|
||||||
|
|
||||||
|
def summarize_user_agent(ua: str | None) -> str | None:
|
||||||
|
"""Nur Browser und System, keine Versionsnummern."""
|
||||||
|
if not ua:
|
||||||
|
return None
|
||||||
|
browser = next(
|
||||||
|
(
|
||||||
|
name
|
||||||
|
for key, name in (
|
||||||
|
("Edg/", "Edge"),
|
||||||
|
("Firefox/", "Firefox"),
|
||||||
|
("Chrome/", "Chrome"),
|
||||||
|
("Safari/", "Safari"),
|
||||||
|
)
|
||||||
|
if key in ua
|
||||||
|
),
|
||||||
|
"Browser",
|
||||||
|
)
|
||||||
|
system = next(
|
||||||
|
(
|
||||||
|
name
|
||||||
|
for key, name in (
|
||||||
|
("Android", "Android"),
|
||||||
|
("iPhone", "iOS"),
|
||||||
|
("iPad", "iPadOS"),
|
||||||
|
("Windows", "Windows"),
|
||||||
|
("Mac OS X", "macOS"),
|
||||||
|
("Linux", "Linux"),
|
||||||
|
)
|
||||||
|
if key in ua
|
||||||
|
),
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
return f"{browser} · {system}" if system else browser
|
||||||
|
|
||||||
|
|
||||||
|
def create(
|
||||||
|
db: Session,
|
||||||
|
settings: Settings,
|
||||||
|
user: UserAccount,
|
||||||
|
state: SessionState,
|
||||||
|
user_agent: str | None,
|
||||||
|
) -> str:
|
||||||
|
token = new_token()
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
lifetime = (
|
||||||
|
PENDING_MFA_LIFETIME
|
||||||
|
if state == SessionState.PENDING_MFA
|
||||||
|
else timedelta(days=settings.session_max_days)
|
||||||
|
)
|
||||||
|
db.add(
|
||||||
|
UserSession(
|
||||||
|
token_hash=token_hash(token),
|
||||||
|
user_id=user.id,
|
||||||
|
state=state,
|
||||||
|
created_at=now,
|
||||||
|
last_seen_at=now,
|
||||||
|
expires_at=now + lifetime,
|
||||||
|
reauth_at=now if state == SessionState.ACTIVE else None,
|
||||||
|
user_agent=summarize_user_agent(user_agent),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def load(db: Session, settings: Settings, token: str | None) -> UserSession | None:
|
||||||
|
if not token or len(token) > 128:
|
||||||
|
return None
|
||||||
|
session = db.scalar(select(UserSession).where(UserSession.token_hash == token_hash(token)))
|
||||||
|
if session is None:
|
||||||
|
return None
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
idle_limit = timedelta(minutes=settings.session_idle_minutes)
|
||||||
|
expired = session.expires_at <= now or (
|
||||||
|
session.state == SessionState.ACTIVE and session.last_seen_at + idle_limit <= now
|
||||||
|
)
|
||||||
|
if expired:
|
||||||
|
db.delete(session)
|
||||||
|
db.commit()
|
||||||
|
return None
|
||||||
|
if now - session.last_seen_at >= TOUCH_INTERVAL:
|
||||||
|
session.last_seen_at = now
|
||||||
|
db.commit()
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
def activate(db: Session, settings: Settings, session: UserSession) -> str:
|
||||||
|
"""Nach bestandenem zweiten Faktor: neuer Wert, volle Laufzeit."""
|
||||||
|
token = new_token()
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
session.token_hash = token_hash(token)
|
||||||
|
session.state = SessionState.ACTIVE
|
||||||
|
session.expires_at = now + timedelta(days=settings.session_max_days)
|
||||||
|
session.last_seen_at = now
|
||||||
|
session.reauth_at = now
|
||||||
|
session.mfa_attempts = 0
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def destroy(db: Session, session: UserSession) -> None:
|
||||||
|
db.delete(session)
|
||||||
|
|
||||||
|
|
||||||
|
def destroy_all(db: Session, user_id: int, except_session_id: int | None = None) -> int:
|
||||||
|
stmt = delete(UserSession).where(UserSession.user_id == user_id)
|
||||||
|
if except_session_id is not None:
|
||||||
|
stmt = stmt.where(UserSession.id != except_session_id)
|
||||||
|
result = db.execute(stmt)
|
||||||
|
return int(result.rowcount or 0) # type: ignore[attr-defined]
|
||||||
|
|
||||||
|
|
||||||
|
def list_for_user(db: Session, user_id: int) -> list[UserSession]:
|
||||||
|
return list(
|
||||||
|
db.scalars(
|
||||||
|
select(UserSession)
|
||||||
|
.where(UserSession.user_id == user_id, UserSession.state == SessionState.ACTIVE)
|
||||||
|
.order_by(UserSession.last_seen_at.desc())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def purge_expired(db: Session, settings: Settings) -> int:
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
idle_cutoff = now - timedelta(minutes=settings.session_idle_minutes)
|
||||||
|
result = db.execute(
|
||||||
|
delete(UserSession).where(
|
||||||
|
(UserSession.expires_at <= now) | (UserSession.last_seen_at <= idle_cutoff)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return int(result.rowcount or 0) # type: ignore[attr-defined]
|
||||||
@@ -0,0 +1,386 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Gestaltung der Instanz (White-Labeling): Name, Farben, Darstellung, Schrift,
|
||||||
|
Startseite, Fußzeile mit Impressum und Datenschutz, eigenes CSS.
|
||||||
|
|
||||||
|
Der Stand liegt wie das Logo unter /data/branding (appearance.json, dazu eine
|
||||||
|
hochgeladene Schrift). Seiten prüfen nur die Änderungszeit der Datei; alle Prozesse
|
||||||
|
sehen Änderungen sofort, ohne Datenbankabfrage.
|
||||||
|
|
||||||
|
Farben gelten für die helle Darstellung. Die dunkle Darstellung behält ihren
|
||||||
|
Hintergrund und leitet Primär- und Akzentfarbe so ab, dass sie lesbar bleiben.
|
||||||
|
Zu wenig Kontrast verhindert das Speichern nicht, es wird aber gewarnt.
|
||||||
|
|
||||||
|
Alles, was hier hereinkommt, landet entweder escaped im HTML oder in einer eigenen
|
||||||
|
CSS-Datei (/branding/theme.css): Nichts davon wird als HTML oder Skript ausgeführt.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
from dataclasses import asdict, dataclass, field, replace
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from surveybox.i18n import N_
|
||||||
|
|
||||||
|
STATE_FILE = "appearance.json"
|
||||||
|
FONT_FILE = "font.bin"
|
||||||
|
FONT_FAMILY = "SurveyboxCustom"
|
||||||
|
FONT_MAX_BYTES = 2 * 1024 * 1024
|
||||||
|
DEFAULT_NAME = "Surveybox"
|
||||||
|
MODES = ("auto", "light", "dark")
|
||||||
|
MAX_NAME = 60
|
||||||
|
MAX_WELCOME = 2000
|
||||||
|
MAX_FOOTER = 300
|
||||||
|
MAX_URL = 500
|
||||||
|
MAX_CSS = 20000
|
||||||
|
_COLOR = re.compile(r"#[0-9a-fA-F]{6}")
|
||||||
|
_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
|
||||||
|
|
||||||
|
# Standardfarben aus app.css (hell und dunkel)
|
||||||
|
LIGHT = {"primary": "#1f5fae", "bg": "#f6f7f9", "surface": "#ffffff", "text": "#1c1e21",
|
||||||
|
"muted": "#5b6270", "border": "#dfe2e7", "ok": "#1d7a3a", "error": "#b3261e"}
|
||||||
|
DARK = {"primary": "#7fb0f0", "bg": "#121417", "surface": "#1b1e23", "text": "#e8eaed",
|
||||||
|
"muted": "#a3a9b4", "border": "#2c3138", "ok": "#6fcf8f", "error": "#f2948d"}
|
||||||
|
FONT_FORMATS = {b"wOF2": "woff2", b"wOFF": "woff", b"\x00\x01\x00\x00": "truetype",
|
||||||
|
b"OTTO": "opentype", b"true": "truetype"}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Appearance:
|
||||||
|
name: str = DEFAULT_NAME
|
||||||
|
mode: str = "auto"
|
||||||
|
primary: str = ""
|
||||||
|
accent: str = ""
|
||||||
|
background: str = ""
|
||||||
|
text: str = ""
|
||||||
|
welcome: str = ""
|
||||||
|
footer_text: str = ""
|
||||||
|
imprint_url: str = ""
|
||||||
|
privacy_url: str = ""
|
||||||
|
css: str = ""
|
||||||
|
font_format: str = "" # leer: keine eigene Schrift
|
||||||
|
version: str = ""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def themed(self) -> bool:
|
||||||
|
"""Braucht die Seite /branding/theme.css?"""
|
||||||
|
return bool(self.mode != "auto" or self.primary or self.accent or self.background
|
||||||
|
or self.text or self.css or self.font_format)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def color_scheme(self) -> str:
|
||||||
|
return {"light": "light", "dark": "dark"}.get(self.mode, "light dark")
|
||||||
|
|
||||||
|
def to_json(self) -> dict[str, Any]:
|
||||||
|
data = asdict(self)
|
||||||
|
data.pop("version")
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT = Appearance()
|
||||||
|
_cache: dict[Path, tuple[int, Appearance]] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def directory(data_dir: Path) -> Path:
|
||||||
|
return data_dir / "branding"
|
||||||
|
|
||||||
|
|
||||||
|
def current(data_dir: Path) -> Appearance:
|
||||||
|
state = directory(data_dir) / STATE_FILE
|
||||||
|
try:
|
||||||
|
mtime = state.stat().st_mtime_ns
|
||||||
|
except OSError:
|
||||||
|
return DEFAULT
|
||||||
|
cached = _cache.get(state)
|
||||||
|
if cached is not None and cached[0] == mtime:
|
||||||
|
return cached[1]
|
||||||
|
try:
|
||||||
|
data = json.loads(state.read_text(encoding="utf-8"))
|
||||||
|
found, _ = parse(data)
|
||||||
|
found = replace(found, version=str(data.get("version", "")),
|
||||||
|
font_format=str(data.get("font_format", ""))
|
||||||
|
if (directory(data_dir) / FONT_FILE).is_file() else "")
|
||||||
|
except (OSError, ValueError, TypeError, AttributeError):
|
||||||
|
found = DEFAULT
|
||||||
|
_cache[state] = (mtime, found)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def save(data_dir: Path, appearance: Appearance) -> Appearance:
|
||||||
|
target = directory(data_dir)
|
||||||
|
target.mkdir(parents=True, exist_ok=True)
|
||||||
|
data = {**appearance.to_json(), "version": secrets.token_hex(6)}
|
||||||
|
state = target / STATE_FILE
|
||||||
|
temp = state.with_suffix(".tmp")
|
||||||
|
temp.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
||||||
|
os.replace(temp, state)
|
||||||
|
return current(data_dir)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Eingaben prüfen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
ERRORS = {
|
||||||
|
"name": N_("Please enter a name (at most 60 characters)."),
|
||||||
|
"color": N_("Please enter colours as #RRGGBB, for example #1f5fae."),
|
||||||
|
"url": N_("Links must start with https:// (at most 500 characters)."),
|
||||||
|
"too_long": N_("A text is too long."),
|
||||||
|
"font": N_("Please upload a font as WOFF2, WOFF, TTF or OTF (at most 2 MB)."),
|
||||||
|
"import": N_("The file is not a design export of Surveybox."),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _line(value: Any, limit: int) -> str:
|
||||||
|
text = _CONTROL.sub("", str(value or "")).replace("\r", "").replace("\n", " ").strip()
|
||||||
|
return text[:limit] if len(text) > limit else text
|
||||||
|
|
||||||
|
|
||||||
|
def _block(value: Any) -> str:
|
||||||
|
return _CONTROL.sub("", str(value or "")).replace("\r\n", "\n").replace("\r", "\n").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def parse(data: dict[str, Any]) -> tuple[Appearance, list[str]]:
|
||||||
|
"""Eingaben (Formular oder Import) prüfen. Fehler sind Schlüssel aus ERRORS."""
|
||||||
|
errors: list[str] = []
|
||||||
|
name = _line(data.get("name"), 1000)
|
||||||
|
if not name or len(name) > MAX_NAME:
|
||||||
|
errors.append("name")
|
||||||
|
name = name[:MAX_NAME] or DEFAULT_NAME
|
||||||
|
mode = str(data.get("mode") or "auto")
|
||||||
|
if mode not in MODES:
|
||||||
|
mode = "auto"
|
||||||
|
colors: dict[str, str] = {}
|
||||||
|
for key in ("primary", "accent", "background", "text"):
|
||||||
|
value = str(data.get(key) or "").strip().lower()
|
||||||
|
if value and not _COLOR.fullmatch(value):
|
||||||
|
errors.append("color")
|
||||||
|
value = ""
|
||||||
|
colors[key] = value
|
||||||
|
urls: dict[str, str] = {}
|
||||||
|
for key in ("imprint_url", "privacy_url"):
|
||||||
|
value = str(data.get(key) or "").strip()
|
||||||
|
if value and (not value.startswith("https://") or len(value) > MAX_URL
|
||||||
|
or re.search(r"[\s<>\"'\\]", value)):
|
||||||
|
errors.append("url")
|
||||||
|
value = ""
|
||||||
|
urls[key] = value
|
||||||
|
welcome = _block(data.get("welcome"))
|
||||||
|
footer = _line(data.get("footer_text"), 10_000)
|
||||||
|
css = _block(data.get("css"))
|
||||||
|
if len(welcome) > MAX_WELCOME or len(footer) > MAX_FOOTER or len(css) > MAX_CSS:
|
||||||
|
errors.append("too_long")
|
||||||
|
welcome, footer, css = welcome[:MAX_WELCOME], footer[:MAX_FOOTER], css[:MAX_CSS]
|
||||||
|
return Appearance(name=name, mode=mode, welcome=welcome, footer_text=footer, css=css,
|
||||||
|
**colors, **urls), sorted(set(errors))
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Schrift
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def font_format(data: bytes) -> str | None:
|
||||||
|
"""WOFF2, WOFF, TrueType oder OpenType an den ersten Bytes erkennen."""
|
||||||
|
if not data or len(data) > FONT_MAX_BYTES:
|
||||||
|
return None
|
||||||
|
return FONT_FORMATS.get(data[:4])
|
||||||
|
|
||||||
|
|
||||||
|
def save_font(data_dir: Path, data: bytes) -> Appearance:
|
||||||
|
found = font_format(data)
|
||||||
|
if found is None:
|
||||||
|
raise ValueError("font")
|
||||||
|
target = directory(data_dir)
|
||||||
|
target.mkdir(parents=True, exist_ok=True)
|
||||||
|
temp = target / (FONT_FILE + ".tmp")
|
||||||
|
temp.write_bytes(data)
|
||||||
|
os.replace(temp, target / FONT_FILE)
|
||||||
|
return save(data_dir, replace(current(data_dir), font_format=found))
|
||||||
|
|
||||||
|
|
||||||
|
def remove_font(data_dir: Path) -> Appearance:
|
||||||
|
(directory(data_dir) / FONT_FILE).unlink(missing_ok=True)
|
||||||
|
return save(data_dir, replace(current(data_dir), font_format=""))
|
||||||
|
|
||||||
|
|
||||||
|
def font_path(data_dir: Path) -> Path | None:
|
||||||
|
path = directory(data_dir) / FONT_FILE
|
||||||
|
return path if path.is_file() else None
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Farben, Kontrast, theme.css
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _rgb(color: str) -> tuple[int, int, int]:
|
||||||
|
return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
|
||||||
|
|
||||||
|
|
||||||
|
def _hex(rgb: tuple[float, float, float]) -> str:
|
||||||
|
return "#" + "".join(f"{max(0, min(255, round(c))):02x}" for c in rgb)
|
||||||
|
|
||||||
|
|
||||||
|
def mix(a: str, b: str, amount: float) -> str:
|
||||||
|
"""a mit `amount` Anteil b mischen (0: a, 1: b)."""
|
||||||
|
ra, rb = _rgb(a), _rgb(b)
|
||||||
|
return _hex(tuple(x + (y - x) * amount for x, y in zip(ra, rb, strict=True))) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
def luminance(color: str) -> float:
|
||||||
|
def channel(value: int) -> float:
|
||||||
|
c = value / 255
|
||||||
|
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
|
||||||
|
|
||||||
|
r, g, b = (channel(v) for v in _rgb(color))
|
||||||
|
return 0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||||
|
|
||||||
|
|
||||||
|
def contrast(a: str, b: str) -> float:
|
||||||
|
la, lb = sorted((luminance(a), luminance(b)), reverse=True)
|
||||||
|
return (la + 0.05) / (lb + 0.05)
|
||||||
|
|
||||||
|
|
||||||
|
def _readable(color: str, against: str, toward: str, minimum: float = 4.5) -> str:
|
||||||
|
"""Farbe schrittweise zu `toward` schieben, bis der Kontrast reicht."""
|
||||||
|
for step in range(21):
|
||||||
|
candidate = mix(color, toward, step / 20)
|
||||||
|
if contrast(candidate, against) >= minimum:
|
||||||
|
return candidate
|
||||||
|
return toward
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Palette:
|
||||||
|
light: dict[str, str] = field(default_factory=dict)
|
||||||
|
dark: dict[str, str] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
def palette(look: Appearance) -> Palette:
|
||||||
|
light = dict(LIGHT)
|
||||||
|
if look.background:
|
||||||
|
light["bg"] = look.background
|
||||||
|
light["surface"] = ("#ffffff" if luminance(look.background) > 0.2
|
||||||
|
else mix(look.background, "#ffffff", 0.06))
|
||||||
|
if look.text:
|
||||||
|
light["text"] = look.text
|
||||||
|
if look.background or look.text:
|
||||||
|
light["muted"] = _readable(mix(light["text"], light["bg"], 0.4), light["surface"],
|
||||||
|
light["text"])
|
||||||
|
light["border"] = mix(light["text"], light["surface"], 0.85)
|
||||||
|
light["primary"] = look.primary or LIGHT["primary"]
|
||||||
|
light["accent"] = look.accent or light["primary"]
|
||||||
|
dark = dict(DARK)
|
||||||
|
dark["primary"] = (_readable(look.primary, DARK["surface"], "#ffffff")
|
||||||
|
if look.primary else DARK["primary"])
|
||||||
|
dark["accent"] = (_readable(look.accent, DARK["surface"], "#ffffff")
|
||||||
|
if look.accent else dark["primary"])
|
||||||
|
return Palette(light, dark)
|
||||||
|
|
||||||
|
|
||||||
|
WARNINGS = {
|
||||||
|
"text": N_("The text colour has too little contrast to the background (%(ratio)s : 1, at "
|
||||||
|
"least 4.5 : 1 is needed)."),
|
||||||
|
"button": N_("Text on buttons has too little contrast to the primary colour (%(ratio)s : 1, "
|
||||||
|
"at least 4.5 : 1 is needed)."),
|
||||||
|
"link": N_("Links in the primary colour have too little contrast to the background "
|
||||||
|
"(%(ratio)s : 1, at least 4.5 : 1 is needed)."),
|
||||||
|
"accent": N_("The accent colour has too little contrast to the background (%(ratio)s : 1, "
|
||||||
|
"at least 3 : 1 is needed for markings)."),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def warnings(look: Appearance) -> list[tuple[str, str]]:
|
||||||
|
"""Zu wenig Kontrast (WCAG 2.1, Stufe AA): (Schlüssel aus WARNINGS, Verhältnis)."""
|
||||||
|
colors = palette(look).light
|
||||||
|
checks = [
|
||||||
|
("text", contrast(colors["text"], colors["surface"]), 4.5),
|
||||||
|
("text", contrast(colors["text"], colors["bg"]), 4.5),
|
||||||
|
("button", contrast(colors["surface"], colors["primary"]), 4.5),
|
||||||
|
("link", contrast(colors["primary"], colors["surface"]), 4.5),
|
||||||
|
("accent", contrast(colors["accent"], colors["surface"]), 3.0),
|
||||||
|
]
|
||||||
|
found: dict[str, float] = {}
|
||||||
|
for key, ratio, minimum in checks:
|
||||||
|
if ratio < minimum:
|
||||||
|
found[key] = min(ratio, found.get(key, ratio))
|
||||||
|
return [(key, f"{ratio:.1f}") for key, ratio in found.items()]
|
||||||
|
|
||||||
|
|
||||||
|
def _vars(colors: dict[str, str], scheme: str) -> str:
|
||||||
|
names = ("primary", "accent", "bg", "surface", "text", "muted", "border", "ok", "error")
|
||||||
|
body = "".join(f"--sb-{name}:{colors[name]};" for name in names if name in colors)
|
||||||
|
return f"color-scheme:{scheme};{body}"
|
||||||
|
|
||||||
|
|
||||||
|
def theme_css(look: Appearance, font_url: str | None) -> str:
|
||||||
|
"""Eigene CSS-Datei der Instanz; wird nach app.css geladen und überschreibt sie."""
|
||||||
|
colors = palette(look)
|
||||||
|
parts = ["/* Gestaltung der Instanz (Surveybox, Einstellungen > Gestaltung) */"]
|
||||||
|
if look.font_format and font_url:
|
||||||
|
parts.append(f'@font-face{{font-family:"{FONT_FAMILY}";src:url("{font_url}") '
|
||||||
|
f'format("{look.font_format}");font-display:swap}}')
|
||||||
|
parts.append(f':root{{--sb-font:"{FONT_FAMILY}",system-ui,-apple-system,"Segoe UI",'
|
||||||
|
'Roboto,"Noto Sans",sans-serif}')
|
||||||
|
if look.mode == "light":
|
||||||
|
parts.append(f":root{{{_vars(colors.light, 'light')}}}")
|
||||||
|
elif look.mode == "dark":
|
||||||
|
parts.append(f":root{{{_vars(colors.dark, 'dark')}}}")
|
||||||
|
else:
|
||||||
|
parts.append(f":root{{{_vars(colors.light, 'light dark')}}}")
|
||||||
|
parts.append("@media (prefers-color-scheme: dark){:root{"
|
||||||
|
f"{_vars(colors.dark, 'light dark')}}}}}")
|
||||||
|
if look.css:
|
||||||
|
parts.append("/* Eigenes CSS */")
|
||||||
|
parts.append(look.css)
|
||||||
|
return "\n".join(parts) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Export und Import
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
EXPORT_FORMAT = "surveybox-appearance"
|
||||||
|
|
||||||
|
|
||||||
|
def export(look: Appearance, files: dict[str, bytes]) -> dict[str, Any]:
|
||||||
|
"""Gestaltung samt Logo und Schrift (Base64) als JSON-Daten."""
|
||||||
|
import base64
|
||||||
|
|
||||||
|
return {
|
||||||
|
"format": EXPORT_FORMAT,
|
||||||
|
"version": 1,
|
||||||
|
"appearance": look.to_json(),
|
||||||
|
"files": {name: base64.b64encode(data).decode("ascii") for name, data in files.items()},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def read_export(raw: bytes) -> tuple[dict[str, Any], dict[str, bytes]]:
|
||||||
|
"""Export-Datei lesen; ValueError, wenn sie keine ist."""
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = json.loads(raw.decode("utf-8"))
|
||||||
|
except (UnicodeDecodeError, ValueError) as exc:
|
||||||
|
raise ValueError("import") from exc
|
||||||
|
if not isinstance(data, dict) or data.get("format") != EXPORT_FORMAT:
|
||||||
|
raise ValueError("import")
|
||||||
|
settings = data.get("appearance")
|
||||||
|
files_raw = data.get("files") or {}
|
||||||
|
if not isinstance(settings, dict) or not isinstance(files_raw, dict):
|
||||||
|
raise ValueError("import")
|
||||||
|
files: dict[str, bytes] = {}
|
||||||
|
for name in ("logo", "logo_dark", "font"):
|
||||||
|
value = files_raw.get(name)
|
||||||
|
if isinstance(value, str) and value:
|
||||||
|
try:
|
||||||
|
files[name] = base64.b64decode(value, validate=True)
|
||||||
|
except (binascii.Error, ValueError) as exc:
|
||||||
|
raise ValueError("import") from exc
|
||||||
|
return settings, files
|
||||||
@@ -0,0 +1,409 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Sicherung und Wiederherstellung mit pg_dump / pg_restore.
|
||||||
|
|
||||||
|
Das Image enthält mehrere PostgreSQL-Client-Versionen. Für jede Sicherung
|
||||||
|
wird die zum Server passende Version gewählt: gleiche Hauptversion, sonst
|
||||||
|
die nächsthöhere. pg_dump kann ältere Server sichern, aber keine neueren.
|
||||||
|
|
||||||
|
Sicherungen landen zuerst als .partial-Datei, werden mit `pg_restore --list`
|
||||||
|
geprüft und erst dann unter ihrem endgültigen Namen abgelegt. Eine
|
||||||
|
abgebrochene Sicherung sieht also nie wie eine gültige aus.
|
||||||
|
|
||||||
|
Dieses Modul importiert oben nur die Standardbibliothek, damit sich die
|
||||||
|
reinen Hilfsfunktionen ohne Datenbanktreiber testen lassen.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import TYPE_CHECKING, Literal
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
PG_LIB_ROOT = Path("/usr/lib/postgresql")
|
||||||
|
# Alle Tabellen von Surveybox liegen in diesem Schema (siehe db.DB_SCHEMA).
|
||||||
|
# Gesichert und wiederhergestellt wird nur dieses Schema, nie die ganze Datenbank.
|
||||||
|
DB_SCHEMA = "surveybox"
|
||||||
|
BackupKind = Literal["daily", "pre-upgrade", "manual", "pre-restore"]
|
||||||
|
BACKUP_KINDS: tuple[BackupKind, ...] = ("daily", "pre-upgrade", "manual", "pre-restore")
|
||||||
|
DUMP_TIMEOUT = 6 * 60 * 60 # Sekunden; großzügig, eine Umfrage-DB ist klein
|
||||||
|
|
||||||
|
_SAFE = re.compile(r"[^0-9A-Za-z_]+")
|
||||||
|
_SCHEMA_NAME = re.compile(r"[a-z_][a-z0-9_]{0,62}")
|
||||||
|
|
||||||
|
|
||||||
|
class BackupError(RuntimeError):
|
||||||
|
"""Sicherung oder Wiederherstellung ist fehlgeschlagen."""
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Reine Hilfsfunktionen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def available_pg_versions(lib_root: Path = PG_LIB_ROOT) -> list[int]:
|
||||||
|
if not lib_root.is_dir():
|
||||||
|
return []
|
||||||
|
return sorted(
|
||||||
|
int(p.name)
|
||||||
|
for p in lib_root.iterdir()
|
||||||
|
if p.name.isdigit() and (p / "bin" / "pg_dump").is_file()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def find_pg_tool(tool: str, server_major: int, lib_root: Path = PG_LIB_ROOT) -> Path:
|
||||||
|
"""Pfad zu pg_dump/pg_restore passend zur Hauptversion des Servers."""
|
||||||
|
versions = available_pg_versions(lib_root)
|
||||||
|
suitable = [v for v in versions if v >= server_major]
|
||||||
|
if not suitable:
|
||||||
|
have = ", ".join(map(str, versions)) or "keine"
|
||||||
|
raise BackupError(
|
||||||
|
f"Kein {tool} für PostgreSQL {server_major} vorhanden (im Image: {have}). "
|
||||||
|
"Der Datenbankserver ist neuer als die Werkzeuge in diesem Image."
|
||||||
|
)
|
||||||
|
path = lib_root / str(suitable[0]) / "bin" / tool
|
||||||
|
if not path.is_file():
|
||||||
|
raise BackupError(f"{path} fehlt")
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def _safe(part: str) -> str:
|
||||||
|
return _SAFE.sub("_", part)[:64]
|
||||||
|
|
||||||
|
|
||||||
|
def backup_filename(
|
||||||
|
kind: BackupKind,
|
||||||
|
now: datetime,
|
||||||
|
from_rev: str | None = None,
|
||||||
|
to_rev: str | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""Dateiname, alphabetisch gleich chronologisch sortiert."""
|
||||||
|
stamp = now.astimezone(UTC).strftime("%Y%m%dT%H%M%SZ")
|
||||||
|
name = f"surveybox-{kind}-{stamp}"
|
||||||
|
if from_rev is not None and to_rev is not None:
|
||||||
|
name += f"-from-{_safe(from_rev)}-to-{_safe(to_rev)}"
|
||||||
|
return f"{name}.dump"
|
||||||
|
|
||||||
|
|
||||||
|
def backup_time(path: Path) -> datetime | None:
|
||||||
|
"""Zeitpunkt einer Sicherung aus ihrem Namen (surveybox-<art>-<UTC-Stempel>…)."""
|
||||||
|
for part in path.stem.split("-"):
|
||||||
|
if len(part) == 16 and part.endswith("Z") and "T" in part:
|
||||||
|
try:
|
||||||
|
return datetime.strptime(part, "%Y%m%dT%H%M%SZ").replace(tzinfo=UTC)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def list_backups(directory: Path) -> list[Path]:
|
||||||
|
"""Fertige Sicherungen eines Verzeichnisses, älteste zuerst."""
|
||||||
|
if not directory.is_dir():
|
||||||
|
return []
|
||||||
|
return sorted(p for p in directory.glob("surveybox-*.dump") if p.is_file())
|
||||||
|
|
||||||
|
|
||||||
|
def apply_retention(directory: Path, keep: int) -> list[Path]:
|
||||||
|
"""Löscht die ältesten Sicherungen, bis höchstens `keep` übrig sind."""
|
||||||
|
if keep < 1:
|
||||||
|
raise ValueError("keep muss mindestens 1 sein")
|
||||||
|
files = list_backups(directory)
|
||||||
|
doomed = files[:-keep] if len(files) > keep else []
|
||||||
|
for path in doomed:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
log.info("Alte Sicherung gelöscht: %s", path.name)
|
||||||
|
return doomed
|
||||||
|
|
||||||
|
|
||||||
|
def _subprocess_env(pg_env: Mapping[str, str]) -> dict[str, str]:
|
||||||
|
# Bewusst nicht die ganze Umgebung weitergeben (Geheimnisse der App).
|
||||||
|
return {
|
||||||
|
"PATH": "/usr/local/bin:/usr/bin:/bin",
|
||||||
|
"LANG": "C.UTF-8",
|
||||||
|
"PGPASSFILE": "/dev/null",
|
||||||
|
**pg_env,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _run(cmd: list[str], pg_env: Mapping[str, str], what: str) -> None:
|
||||||
|
try:
|
||||||
|
proc = subprocess.run( # noqa: S603 - feste Argumentliste, keine Shell
|
||||||
|
cmd,
|
||||||
|
env=_subprocess_env(pg_env),
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=DUMP_TIMEOUT,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||||
|
raise BackupError(f"{what} konnte nicht ausgeführt werden: {exc}") from exc
|
||||||
|
if proc.returncode != 0:
|
||||||
|
tail = (proc.stderr or proc.stdout or "").strip()[-2000:]
|
||||||
|
raise BackupError(f"{what} fehlgeschlagen (Code {proc.returncode}): {tail}")
|
||||||
|
|
||||||
|
|
||||||
|
def _fsync_dir(directory: Path) -> None:
|
||||||
|
fd = os.open(directory, os.O_RDONLY)
|
||||||
|
try:
|
||||||
|
os.fsync(fd)
|
||||||
|
finally:
|
||||||
|
os.close(fd)
|
||||||
|
|
||||||
|
|
||||||
|
def dump_to_file(
|
||||||
|
pg_dump: Path,
|
||||||
|
pg_restore: Path,
|
||||||
|
pg_env: Mapping[str, str],
|
||||||
|
target: Path,
|
||||||
|
schema: str = DB_SCHEMA,
|
||||||
|
) -> Path:
|
||||||
|
"""Sichert das Schema `schema` der Datenbank aus `pg_env` nach `target`."""
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||||
|
partial = target.with_name(target.name + ".partial")
|
||||||
|
partial.unlink(missing_ok=True)
|
||||||
|
try:
|
||||||
|
_run(
|
||||||
|
[
|
||||||
|
str(pg_dump),
|
||||||
|
"--format=custom",
|
||||||
|
"--compress=6",
|
||||||
|
f"--schema={schema}",
|
||||||
|
f"--file={partial}",
|
||||||
|
],
|
||||||
|
pg_env,
|
||||||
|
"pg_dump",
|
||||||
|
)
|
||||||
|
os.chmod(partial, 0o600)
|
||||||
|
with partial.open("rb") as fh:
|
||||||
|
os.fsync(fh.fileno())
|
||||||
|
_run([str(pg_restore), "--list", str(partial)], pg_env, "Prüfung der Sicherung")
|
||||||
|
os.replace(partial, target)
|
||||||
|
_fsync_dir(target.parent)
|
||||||
|
except BaseException:
|
||||||
|
partial.unlink(missing_ok=True)
|
||||||
|
raise
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def restore_from_file(
|
||||||
|
pg_restore: Path,
|
||||||
|
psql: Path,
|
||||||
|
pg_env: Mapping[str, str],
|
||||||
|
source: Path,
|
||||||
|
workdir: Path,
|
||||||
|
schema: str = DB_SCHEMA,
|
||||||
|
) -> None:
|
||||||
|
"""Ersetzt das Schema `schema` durch den Inhalt der Sicherung.
|
||||||
|
|
||||||
|
Löschen des alten Schemas und Einspielen der Sicherung laufen in EINER
|
||||||
|
Transaktion (psql --single-transaction). Schlägt etwas fehl, bleibt der
|
||||||
|
bisherige Stand vollständig erhalten. Weil das ganze Schema ersetzt wird,
|
||||||
|
stören auch Tabellen nicht, die ein späteres Update angelegt hat.
|
||||||
|
"""
|
||||||
|
if not source.is_file():
|
||||||
|
raise BackupError(f"Sicherung nicht gefunden: {source}")
|
||||||
|
if not _SCHEMA_NAME.fullmatch(schema):
|
||||||
|
raise BackupError(f"Ungültiger Schemaname: {schema}")
|
||||||
|
_run([str(pg_restore), "--list", str(source)], pg_env, "Prüfung der Sicherung")
|
||||||
|
|
||||||
|
workdir.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||||
|
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%S%fZ")
|
||||||
|
prelude = workdir / f".restore-{stamp}-0.sql"
|
||||||
|
script = workdir / f".restore-{stamp}-1.sql"
|
||||||
|
try:
|
||||||
|
prelude.write_text(f"DROP SCHEMA IF EXISTS {schema} CASCADE;\n", encoding="utf-8")
|
||||||
|
os.chmod(prelude, 0o600)
|
||||||
|
_run(
|
||||||
|
[
|
||||||
|
str(pg_restore),
|
||||||
|
"--no-owner",
|
||||||
|
"--no-privileges",
|
||||||
|
f"--file={script}",
|
||||||
|
str(source),
|
||||||
|
],
|
||||||
|
pg_env,
|
||||||
|
"Umwandlung der Sicherung",
|
||||||
|
)
|
||||||
|
os.chmod(script, 0o600)
|
||||||
|
_run(
|
||||||
|
[
|
||||||
|
str(psql),
|
||||||
|
"--no-psqlrc",
|
||||||
|
"--quiet",
|
||||||
|
"--single-transaction",
|
||||||
|
"--set=ON_ERROR_STOP=1",
|
||||||
|
f"--file={prelude}",
|
||||||
|
f"--file={script}",
|
||||||
|
],
|
||||||
|
pg_env,
|
||||||
|
"Einspielen der Sicherung",
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
prelude.unlink(missing_ok=True)
|
||||||
|
script.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Mit Einstellungen und Datenbank
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Dateien (Bilder, Videos, Uploads)
|
||||||
|
#
|
||||||
|
# Dateien sind unveränderlich. Jede Sicherung schreibt neben die .dump-Datei
|
||||||
|
# eine Liste der vorhandenen Dateien (<name>.media). Die Dateien selbst liegen
|
||||||
|
# einmal in <backups>/media, als harter Link (kostet keinen Platz) oder, wenn
|
||||||
|
# das Sicherungsziel auf einem anderen Dateisystem liegt, als Kopie. Wird eine
|
||||||
|
# Sicherung gelöscht, verschwinden die Dateien, die keine Sicherung mehr nennt.
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
MEDIA_SUFFIX = ".media"
|
||||||
|
_MEDIA_KEY = re.compile(r"[0-9a-f]{2}/[0-9a-f]{32}")
|
||||||
|
|
||||||
|
|
||||||
|
def manifest_for(dump: Path) -> Path:
|
||||||
|
return dump.with_suffix(MEDIA_SUFFIX)
|
||||||
|
|
||||||
|
|
||||||
|
def _link_or_copy(source: Path, target: Path) -> None:
|
||||||
|
if target.exists():
|
||||||
|
return
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
partial = target.with_name(target.name + ".partial")
|
||||||
|
try:
|
||||||
|
os.link(source, partial)
|
||||||
|
except OSError:
|
||||||
|
shutil.copy2(source, partial)
|
||||||
|
os.replace(partial, target)
|
||||||
|
|
||||||
|
|
||||||
|
def read_manifest(path: Path) -> list[str]:
|
||||||
|
if not path.is_file():
|
||||||
|
return []
|
||||||
|
keys = path.read_text(encoding="utf-8").split()
|
||||||
|
return [k for k in keys if _MEDIA_KEY.fullmatch(k)]
|
||||||
|
|
||||||
|
|
||||||
|
def backup_media(media_dir: Path, store: Path, dump: Path) -> int:
|
||||||
|
"""Hält die aktuellen Dateien in `store` fest und schreibt das Manifest."""
|
||||||
|
from surveybox.media.storage import stored_keys
|
||||||
|
|
||||||
|
keys = sorted(stored_keys(media_dir))
|
||||||
|
for key in keys:
|
||||||
|
try:
|
||||||
|
_link_or_copy(media_dir / key, store / key)
|
||||||
|
except FileNotFoundError:
|
||||||
|
continue # inzwischen gelöscht (älter als einen Tag, ohne Verweis)
|
||||||
|
manifest = manifest_for(dump)
|
||||||
|
partial = manifest.with_name(manifest.name + ".partial")
|
||||||
|
partial.write_text("\n".join(keys) + ("\n" if keys else ""), encoding="utf-8")
|
||||||
|
os.replace(partial, manifest)
|
||||||
|
return len(keys)
|
||||||
|
|
||||||
|
|
||||||
|
def prune_media_store(backup_root: Path, store: Path) -> int:
|
||||||
|
"""Löscht Dateien im Sicherungsspeicher, die kein Manifest mehr nennt."""
|
||||||
|
from surveybox.media.storage import stored_keys
|
||||||
|
|
||||||
|
wanted: set[str] = set()
|
||||||
|
for kind in BACKUP_KINDS:
|
||||||
|
for manifest in (backup_root / kind).glob(f"surveybox-*{MEDIA_SUFFIX}"):
|
||||||
|
wanted.update(read_manifest(manifest))
|
||||||
|
removed = 0
|
||||||
|
for key in list(stored_keys(store)):
|
||||||
|
if key not in wanted:
|
||||||
|
(store / key).unlink(missing_ok=True)
|
||||||
|
removed += 1
|
||||||
|
return removed
|
||||||
|
|
||||||
|
|
||||||
|
def restore_media(media_dir: Path, store: Path, dump: Path) -> int:
|
||||||
|
"""Legt alle Dateien einer Sicherung wieder ab, die im Volume fehlen."""
|
||||||
|
restored = 0
|
||||||
|
for key in read_manifest(manifest_for(dump)):
|
||||||
|
source = store / key
|
||||||
|
if (media_dir / key).exists() or not source.is_file():
|
||||||
|
continue
|
||||||
|
_link_or_copy(source, media_dir / key)
|
||||||
|
restored += 1
|
||||||
|
return restored
|
||||||
|
|
||||||
|
|
||||||
|
def _tools(settings: Settings) -> tuple[Path, Path, Path]:
|
||||||
|
from surveybox.db import get_engine, server_major_version
|
||||||
|
|
||||||
|
major = server_major_version(get_engine())
|
||||||
|
return (
|
||||||
|
find_pg_tool("pg_dump", major),
|
||||||
|
find_pg_tool("pg_restore", major),
|
||||||
|
find_pg_tool("psql", major),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def keep_for(settings: Settings, kind: BackupKind) -> int:
|
||||||
|
if kind == "daily":
|
||||||
|
return settings.backup_keep_daily
|
||||||
|
if kind == "pre-upgrade":
|
||||||
|
return settings.backup_keep_pre_upgrade
|
||||||
|
return 20
|
||||||
|
|
||||||
|
|
||||||
|
def create_backup(
|
||||||
|
settings: Settings,
|
||||||
|
kind: BackupKind,
|
||||||
|
from_rev: str | None = None,
|
||||||
|
to_rev: str | None = None,
|
||||||
|
) -> Path:
|
||||||
|
pg_dump, pg_restore, _ = _tools(settings)
|
||||||
|
directory = settings.backup_dir / kind
|
||||||
|
target = directory / backup_filename(kind, datetime.now(UTC), from_rev, to_rev)
|
||||||
|
log.info("Sicherung wird erstellt: %s (mit %s)", target, pg_dump)
|
||||||
|
dump_to_file(pg_dump, pg_restore, settings.pg_env(), target)
|
||||||
|
# Nach dem Dump: Verwaiste Dateien löscht nur der Worker, der Sicherung und
|
||||||
|
# Aufräumen nacheinander erledigt, und nur Dateien, die älter als einen Tag
|
||||||
|
# sind. So fehlen im Manifest keine Dateien, die der Dump noch kennt.
|
||||||
|
files = backup_media(settings.media_dir, settings.backup_dir / "media", target)
|
||||||
|
size_mb = target.stat().st_size / 1_048_576
|
||||||
|
log.info("Sicherung fertig: %s (%.1f MB, %d Dateien)", target.name, size_mb, files)
|
||||||
|
for removed in apply_retention(directory, keep_for(settings, kind)):
|
||||||
|
manifest_for(removed).unlink(missing_ok=True)
|
||||||
|
prune_media_store(settings.backup_dir, settings.backup_dir / "media")
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def create_pre_upgrade_backup(settings: Settings, from_rev: str, to_rev: str) -> Path:
|
||||||
|
# Immer eine frische Sicherung: Eine ältere vom selben Ausgangsstand könnte
|
||||||
|
# Daten verpassen, die seither mit der alten Version erfasst wurden.
|
||||||
|
return create_backup(settings, "pre-upgrade", from_rev=from_rev, to_rev=to_rev)
|
||||||
|
|
||||||
|
|
||||||
|
def restore_backup(settings: Settings, source: Path) -> Path:
|
||||||
|
"""Sichert erst den aktuellen Stand, spielt dann `source` zurück."""
|
||||||
|
safety = create_backup(settings, "pre-restore")
|
||||||
|
_, pg_restore, psql = _tools(settings)
|
||||||
|
log.info("Wiederherstellung aus %s", source)
|
||||||
|
restore_from_file(pg_restore, psql, settings.pg_env(), source, settings.backup_dir)
|
||||||
|
files = restore_media(settings.media_dir, settings.backup_dir / "media", source)
|
||||||
|
# Löschungen seit dieser Sicherung wendet der Worker erneut an, sobald das
|
||||||
|
# Schema aktuell ist (erasure_journal).
|
||||||
|
from surveybox import erasure_journal
|
||||||
|
|
||||||
|
taken = backup_time(source) or datetime.fromtimestamp(source.stat().st_mtime, UTC)
|
||||||
|
erasure_journal.mark_restore(settings, taken)
|
||||||
|
log.info(
|
||||||
|
"Wiederherstellung abgeschlossen (%d Dateien zurückgelegt). Vorheriger Stand in %s",
|
||||||
|
files,
|
||||||
|
safety,
|
||||||
|
)
|
||||||
|
return safety
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Logo und Favicon: Standard von Surveybox oder ein eigenes Logo der Instanz.
|
||||||
|
|
||||||
|
Ein hochgeladenes Logo wird wie jedes Bild neu berechnet (ohne Metadaten) und in
|
||||||
|
drei Fassungen unter /data/branding abgelegt: Logo für Kopfzeile und Auswertungen,
|
||||||
|
Favicon (64 x 64) und Icon für den Startbildschirm (180 x 180). SVG-Dateien
|
||||||
|
werden nicht angenommen, weil sie Skripte enthalten können.
|
||||||
|
|
||||||
|
Der Stand steht in branding.json; die Kopfzeile prüft bei jeder Seite nur dessen
|
||||||
|
Änderungszeit. So sehen alle Prozesse ein neues Logo sofort, ohne Datenbankabfrage.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from surveybox.media import images
|
||||||
|
|
||||||
|
STATE_FILE = "branding.json"
|
||||||
|
FILES = {"logo": "logo.png", "favicon": "favicon.png", "touch": "touch.png",
|
||||||
|
"logo_dark": "logo-dark.png"}
|
||||||
|
LOGO_BOX = (800, 240) # größer wird es nie angezeigt
|
||||||
|
FAVICON_SIZE = 64
|
||||||
|
TOUCH_SIZE = 180
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Brand:
|
||||||
|
custom: bool
|
||||||
|
version: str = ""
|
||||||
|
dark: bool = False # eigenes Logo für die dunkle Darstellung
|
||||||
|
|
||||||
|
def url(self, kind: str) -> str | None:
|
||||||
|
"""Adresse des eigenen Bilds; None heißt: Standard aus /static verwenden."""
|
||||||
|
if not self.custom or (kind == "logo_dark" and not self.dark):
|
||||||
|
return None
|
||||||
|
return f"/branding/{FILES[kind]}?v={self.version}"
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT = Brand(custom=False)
|
||||||
|
_cache: dict[Path, tuple[int, Brand]] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def directory(data_dir: Path) -> Path:
|
||||||
|
return data_dir / "branding"
|
||||||
|
|
||||||
|
|
||||||
|
def current(data_dir: Path) -> Brand:
|
||||||
|
state = directory(data_dir) / STATE_FILE
|
||||||
|
try:
|
||||||
|
mtime = state.stat().st_mtime_ns
|
||||||
|
except OSError:
|
||||||
|
return DEFAULT
|
||||||
|
cached = _cache.get(state)
|
||||||
|
if cached is not None and cached[0] == mtime:
|
||||||
|
return cached[1]
|
||||||
|
try:
|
||||||
|
data: dict[str, Any] = json.loads(state.read_text(encoding="utf-8"))
|
||||||
|
brand = Brand(custom=True, version=str(data["version"]),
|
||||||
|
dark=(directory(data_dir) / FILES["logo_dark"]).is_file())
|
||||||
|
except (OSError, ValueError, KeyError, TypeError):
|
||||||
|
brand = DEFAULT
|
||||||
|
_cache[state] = (mtime, brand)
|
||||||
|
return brand
|
||||||
|
|
||||||
|
|
||||||
|
def file_path(data_dir: Path, name: str) -> Path | None:
|
||||||
|
"""Pfad einer ausgelieferten Datei; nur die drei bekannten Namen."""
|
||||||
|
if name not in FILES.values():
|
||||||
|
return None
|
||||||
|
path = directory(data_dir) / name
|
||||||
|
return path if path.is_file() else None
|
||||||
|
|
||||||
|
|
||||||
|
def _square(img: Image.Image, size: int, background: tuple[int, int, int, int]) -> Image.Image:
|
||||||
|
canvas = Image.new("RGBA", (size, size), background)
|
||||||
|
fitted = img.copy()
|
||||||
|
fitted.thumbnail((size, size), Image.Resampling.LANCZOS)
|
||||||
|
canvas.alpha_composite(fitted, ((size - fitted.width) // 2, (size - fitted.height) // 2))
|
||||||
|
return canvas
|
||||||
|
|
||||||
|
|
||||||
|
def _save(img: Image.Image, target: Path) -> None:
|
||||||
|
temp = target.with_suffix(".tmp")
|
||||||
|
img.save(temp, "PNG", optimize=True)
|
||||||
|
os.replace(temp, target)
|
||||||
|
|
||||||
|
|
||||||
|
def _write_state(data_dir: Path) -> None:
|
||||||
|
state = directory(data_dir) / STATE_FILE
|
||||||
|
temp = state.with_suffix(".tmp")
|
||||||
|
temp.write_text(json.dumps({"version": secrets.token_hex(6)}), encoding="utf-8")
|
||||||
|
os.replace(temp, state)
|
||||||
|
|
||||||
|
|
||||||
|
def save_logo(data_dir: Path, source: Path, dark: bool = False) -> Brand:
|
||||||
|
"""Logo übernehmen. Wirft images.ImageError bei ungeeigneten Dateien.
|
||||||
|
|
||||||
|
dark: Fassung für die dunkle Darstellung (nur zusätzlich zum eigenen Logo).
|
||||||
|
"""
|
||||||
|
base = images.load(source).convert("RGBA")
|
||||||
|
# Leere Ränder abschneiden, damit das Logo die verfügbare Höhe nutzt
|
||||||
|
box = base.getbbox()
|
||||||
|
if box is not None:
|
||||||
|
base = base.crop(box)
|
||||||
|
target = directory(data_dir)
|
||||||
|
target.mkdir(parents=True, exist_ok=True)
|
||||||
|
if dark:
|
||||||
|
logo = base.copy()
|
||||||
|
logo.thumbnail(LOGO_BOX, Image.Resampling.LANCZOS)
|
||||||
|
_save(logo, target / FILES["logo_dark"])
|
||||||
|
_write_state(data_dir)
|
||||||
|
return current(data_dir)
|
||||||
|
logo = base.copy()
|
||||||
|
logo.thumbnail(LOGO_BOX, Image.Resampling.LANCZOS)
|
||||||
|
_save(logo, target / FILES["logo"])
|
||||||
|
_save(_square(base, FAVICON_SIZE, (0, 0, 0, 0)), target / FILES["favicon"])
|
||||||
|
_save(_touch(base), target / FILES["touch"])
|
||||||
|
_write_state(data_dir)
|
||||||
|
return current(data_dir)
|
||||||
|
|
||||||
|
|
||||||
|
def _touch(base: Image.Image) -> Image.Image:
|
||||||
|
"""Startbildschirm-Icons brauchen einen deckenden Hintergrund."""
|
||||||
|
canvas = Image.new("RGBA", (TOUCH_SIZE, TOUCH_SIZE), (255, 255, 255, 255))
|
||||||
|
inner = _square(base, TOUCH_SIZE - 24, (255, 255, 255, 0))
|
||||||
|
canvas.alpha_composite(inner, (12, 12))
|
||||||
|
return canvas
|
||||||
|
|
||||||
|
|
||||||
|
def remove_logo(data_dir: Path) -> None:
|
||||||
|
target = directory(data_dir)
|
||||||
|
(target / STATE_FILE).unlink(missing_ok=True)
|
||||||
|
for name in FILES.values():
|
||||||
|
(target / name).unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def remove_dark_logo(data_dir: Path) -> None:
|
||||||
|
(directory(data_dir) / FILES["logo_dark"]).unlink(missing_ok=True)
|
||||||
|
if (directory(data_dir) / FILES["logo"]).is_file():
|
||||||
|
_write_state(data_dir)
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Befehlszeile: `python -m surveybox.cli <befehl>` (im Container der Einstiegspunkt).
|
||||||
|
|
||||||
|
web Datenbank migrieren, dann Webserver starten
|
||||||
|
worker Hintergrund-Worker starten
|
||||||
|
migrate nur die Datenbank auf den aktuellen Stand bringen
|
||||||
|
backup Sicherung jetzt erstellen
|
||||||
|
restore Sicherung zurückspielen (Web und Worker vorher stoppen!)
|
||||||
|
create-admin ersten Administrator anlegen, gibt einen Einrichtungslink aus
|
||||||
|
user-link neuen Anmeldelink für ein Konto ausgeben (z. B. Zugang verloren)
|
||||||
|
healthcheck Zustand prüfen (für Docker)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
EXIT_OK = 0
|
||||||
|
EXIT_ERROR = 1
|
||||||
|
EXIT_DB_UNAVAILABLE = 2
|
||||||
|
|
||||||
|
|
||||||
|
def _setup_logging(level: str) -> None:
|
||||||
|
logging.basicConfig(
|
||||||
|
level=level.upper(),
|
||||||
|
format="%(asctime)s %(levelname)-7s %(name)s: %(message)s",
|
||||||
|
stream=sys.stdout,
|
||||||
|
force=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_migrate() -> int:
|
||||||
|
from surveybox.db import get_engine
|
||||||
|
from surveybox.settings import get_settings
|
||||||
|
from surveybox.upgrade import DatabaseUnavailableError, UpgradeError, run_upgrade
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = run_upgrade(get_settings(), get_engine())
|
||||||
|
except DatabaseUnavailableError as exc:
|
||||||
|
logging.getLogger("surveybox").error("%s", exc)
|
||||||
|
return EXIT_DB_UNAVAILABLE
|
||||||
|
except UpgradeError as exc:
|
||||||
|
logging.getLogger("surveybox").error("%s", exc)
|
||||||
|
return EXIT_ERROR
|
||||||
|
if result.backup_file is not None:
|
||||||
|
logging.getLogger("surveybox").info("Sicherung vor dem Update: %s", result.backup_file)
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
def hold_after_failed_migration() -> int:
|
||||||
|
"""Nach einem gescheiterten Update anhalten, nicht beenden.
|
||||||
|
|
||||||
|
Würde sich der Prozess beenden, startete Docker den Container sofort neu,
|
||||||
|
und jeder Versuch schriebe eine weitere Sicherung. Stattdessen bleibt der
|
||||||
|
Container stehen (als "unhealthy"), bis ihn jemand stoppt oder neu startet.
|
||||||
|
Die Datenbank ist zu diesem Zeitpunkt unverändert.
|
||||||
|
"""
|
||||||
|
import signal
|
||||||
|
import threading
|
||||||
|
|
||||||
|
stop = threading.Event()
|
||||||
|
|
||||||
|
def _stop(_signum: int, _frame: object) -> None:
|
||||||
|
stop.set()
|
||||||
|
|
||||||
|
signal.signal(signal.SIGTERM, _stop)
|
||||||
|
signal.signal(signal.SIGINT, _stop)
|
||||||
|
log = logging.getLogger("surveybox")
|
||||||
|
while True:
|
||||||
|
log.error(
|
||||||
|
"Update fehlgeschlagen, Surveybox startet nicht. Die Datenbank ist unverändert. "
|
||||||
|
"Ursache oben im Log. Danach: Fehler beheben und 'docker compose up -d', "
|
||||||
|
"oder zur vorherigen Version zurückkehren."
|
||||||
|
)
|
||||||
|
if stop.wait(600):
|
||||||
|
return EXIT_ERROR
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_web(skip_migrate: bool) -> int:
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
from surveybox.settings import get_settings
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
|
if not skip_migrate:
|
||||||
|
code = cmd_migrate()
|
||||||
|
if code == EXIT_DB_UNAVAILABLE:
|
||||||
|
return code # nichts versucht: Docker darf neu starten
|
||||||
|
if code != EXIT_OK:
|
||||||
|
return hold_after_failed_migration()
|
||||||
|
uvicorn.run(
|
||||||
|
"surveybox.web.app:create_app",
|
||||||
|
factory=True,
|
||||||
|
host=settings.web_host,
|
||||||
|
port=settings.web_port,
|
||||||
|
workers=settings.web_workers,
|
||||||
|
log_level=settings.log_level,
|
||||||
|
proxy_headers=False, # Adressen kommen aus SURVEYBOX_PUBLIC_URL
|
||||||
|
server_header=False,
|
||||||
|
date_header=True,
|
||||||
|
access_log=False,
|
||||||
|
)
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_worker() -> int:
|
||||||
|
from surveybox.settings import get_settings
|
||||||
|
from surveybox.worker import Worker
|
||||||
|
|
||||||
|
Worker(get_settings()).run()
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_backup() -> int:
|
||||||
|
from surveybox.backup import BackupError, create_backup
|
||||||
|
from surveybox.settings import get_settings
|
||||||
|
|
||||||
|
try:
|
||||||
|
path = create_backup(get_settings(), "manual")
|
||||||
|
except BackupError as exc:
|
||||||
|
logging.getLogger("surveybox").error("%s", exc)
|
||||||
|
return EXIT_ERROR
|
||||||
|
print(path)
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_restore(source: Path, confirmed: bool) -> int:
|
||||||
|
from surveybox.backup import BackupError, restore_backup
|
||||||
|
from surveybox.settings import get_settings
|
||||||
|
|
||||||
|
log = logging.getLogger("surveybox")
|
||||||
|
if not confirmed:
|
||||||
|
log.error(
|
||||||
|
"Die Wiederherstellung überschreibt die Datenbank. "
|
||||||
|
"Web und Worker vorher stoppen und mit --yes bestätigen."
|
||||||
|
)
|
||||||
|
return EXIT_ERROR
|
||||||
|
settings = get_settings()
|
||||||
|
if not source.is_absolute():
|
||||||
|
source = settings.backup_dir / source
|
||||||
|
try:
|
||||||
|
restore_backup(settings, source)
|
||||||
|
except BackupError as exc:
|
||||||
|
log.error("%s", exc)
|
||||||
|
return EXIT_ERROR
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_create_admin(email: str, name: str) -> int:
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.accounts import service
|
||||||
|
from surveybox.accounts.service import AccountError
|
||||||
|
from surveybox.db import get_engine
|
||||||
|
from surveybox.models import Role
|
||||||
|
from surveybox.settings import get_settings
|
||||||
|
|
||||||
|
log = logging.getLogger("surveybox")
|
||||||
|
settings = get_settings()
|
||||||
|
with Session(get_engine()) as db:
|
||||||
|
try:
|
||||||
|
user = service.create_user(db, email, name, Role.ADMIN, created_by_id=None)
|
||||||
|
token, row = service.create_link(db, user, created_by_id=None)
|
||||||
|
except AccountError as exc:
|
||||||
|
log.error("Konto nicht angelegt: %s", exc.code)
|
||||||
|
return EXIT_ERROR
|
||||||
|
db.commit()
|
||||||
|
print(f"Administrator angelegt: {user.email}")
|
||||||
|
print(f"Einrichtungslink (gültig bis {row.expires_at:%Y-%m-%d %H:%M} UTC, einmalig):")
|
||||||
|
print(service.link_url(settings, token))
|
||||||
|
print("Nach dem Setzen des Passworts verlangt Surveybox die Einrichtung "
|
||||||
|
"des zweiten Faktors.")
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_user_link(email: str, reset_2fa: bool) -> int:
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.accounts import service
|
||||||
|
from surveybox.db import get_engine
|
||||||
|
from surveybox.settings import get_settings
|
||||||
|
|
||||||
|
log = logging.getLogger("surveybox")
|
||||||
|
settings = get_settings()
|
||||||
|
with Session(get_engine()) as db:
|
||||||
|
user = service.find_by_email(db, email)
|
||||||
|
if user is None:
|
||||||
|
log.error("Kein Konto mit dieser E-Mail-Adresse.")
|
||||||
|
return EXIT_ERROR
|
||||||
|
if not user.is_active:
|
||||||
|
log.error("Das Konto ist deaktiviert. Erst in der Verwaltung aktivieren.")
|
||||||
|
return EXIT_ERROR
|
||||||
|
if reset_2fa and user.has_second_factor:
|
||||||
|
service.reset_second_factors(db, user, actor_id=None)
|
||||||
|
print("Zweite Faktoren (Authenticator-App, Passkeys) entfernt.")
|
||||||
|
token, row = service.create_link(db, user, created_by_id=None)
|
||||||
|
db.commit()
|
||||||
|
print(f"Anmeldelink für {user.email} (gültig bis {row.expires_at:%Y-%m-%d %H:%M} UTC):")
|
||||||
|
print(service.link_url(settings, token))
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_healthcheck(worker: bool) -> int:
|
||||||
|
if worker:
|
||||||
|
from surveybox.worker import heartbeat_age_seconds
|
||||||
|
|
||||||
|
age = heartbeat_age_seconds()
|
||||||
|
return EXIT_OK if age is not None and age < 120 else EXIT_ERROR
|
||||||
|
|
||||||
|
from surveybox.settings import get_settings
|
||||||
|
|
||||||
|
url = f"http://127.0.0.1:{get_settings().web_port}/health/ready"
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(url, timeout=5) as resp:
|
||||||
|
return EXIT_OK if resp.status == 200 else EXIT_ERROR
|
||||||
|
except (urllib.error.URLError, OSError):
|
||||||
|
return EXIT_ERROR
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
parser = argparse.ArgumentParser(prog="surveybox", description="Surveybox")
|
||||||
|
sub = parser.add_subparsers(dest="command", required=True)
|
||||||
|
|
||||||
|
p_web = sub.add_parser("web", help="migrieren und Webserver starten")
|
||||||
|
p_web.add_argument("--skip-migrate", action="store_true", help="Migration überspringen")
|
||||||
|
sub.add_parser("worker", help="Hintergrund-Worker starten")
|
||||||
|
sub.add_parser("migrate", help="Datenbank auf den aktuellen Stand bringen")
|
||||||
|
sub.add_parser("backup", help="Sicherung jetzt erstellen")
|
||||||
|
p_restore = sub.add_parser("restore", help="Sicherung zurückspielen")
|
||||||
|
p_restore.add_argument("file", type=Path, help="Datei, absolut oder relativ zu /data/backups")
|
||||||
|
p_restore.add_argument("--yes", action="store_true", help="Überschreiben bestätigen")
|
||||||
|
p_admin = sub.add_parser("create-admin", help="ersten Administrator anlegen")
|
||||||
|
p_admin.add_argument("--email", required=True)
|
||||||
|
p_admin.add_argument("--name", required=True)
|
||||||
|
p_link = sub.add_parser("user-link", help="Anmeldelink für ein Konto ausgeben")
|
||||||
|
p_link.add_argument("--email", required=True)
|
||||||
|
p_link.add_argument(
|
||||||
|
"--reset-2fa", action="store_true", help="zweiten Faktor abschalten (Gerät verloren)"
|
||||||
|
)
|
||||||
|
p_health = sub.add_parser("healthcheck", help="Zustand prüfen")
|
||||||
|
p_health.add_argument("--worker", action="store_true", help="Worker statt Web prüfen")
|
||||||
|
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
if args.command == "healthcheck":
|
||||||
|
# Kein Logging-Setup: Docker ruft das alle 30 s auf.
|
||||||
|
return cmd_healthcheck(args.worker)
|
||||||
|
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
try:
|
||||||
|
from surveybox.settings import get_settings
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
|
except ValidationError as exc:
|
||||||
|
print("Konfigurationsfehler in der .env:", file=sys.stderr)
|
||||||
|
for err in exc.errors():
|
||||||
|
field = "SURVEYBOX_" + str(err["loc"][0]).upper() if err["loc"] else "?"
|
||||||
|
print(f" {field}: {err['msg']}", file=sys.stderr)
|
||||||
|
return EXIT_ERROR
|
||||||
|
|
||||||
|
_setup_logging(settings.log_level)
|
||||||
|
|
||||||
|
if args.command == "web":
|
||||||
|
return cmd_web(args.skip_migrate)
|
||||||
|
if args.command == "worker":
|
||||||
|
return cmd_worker()
|
||||||
|
if args.command == "migrate":
|
||||||
|
return cmd_migrate()
|
||||||
|
if args.command == "backup":
|
||||||
|
return cmd_backup()
|
||||||
|
if args.command == "restore":
|
||||||
|
return cmd_restore(args.file, args.yes)
|
||||||
|
if args.command == "create-admin":
|
||||||
|
return cmd_create_admin(args.email, args.name)
|
||||||
|
if args.command == "user-link":
|
||||||
|
return cmd_user_link(args.email, args.reset_2fa)
|
||||||
|
parser.error(f"Unbekannter Befehl {args.command}")
|
||||||
|
return EXIT_ERROR
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Datenbankverbindung (PostgreSQL über psycopg 3)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
from sqlalchemy import URL, Engine, create_engine, text
|
||||||
|
|
||||||
|
from surveybox.settings import Settings, get_settings
|
||||||
|
|
||||||
|
# Eigenes Schema statt "public": Surveybox kann eine vorhandene Datenbank
|
||||||
|
# mitbenutzen, und Sicherung/Wiederherstellung betreffen nur dieses Schema.
|
||||||
|
DB_SCHEMA = "surveybox"
|
||||||
|
|
||||||
|
|
||||||
|
def database_url(settings: Settings) -> URL:
|
||||||
|
query: dict[str, str] = {"sslmode": settings.db_sslmode}
|
||||||
|
if settings.db_sslrootcert is not None:
|
||||||
|
query["sslrootcert"] = str(settings.db_sslrootcert)
|
||||||
|
return URL.create(
|
||||||
|
"postgresql+psycopg",
|
||||||
|
username=settings.db_user,
|
||||||
|
password=settings.db_password.get_secret_value(),
|
||||||
|
host=settings.db_host,
|
||||||
|
port=settings.db_port,
|
||||||
|
database=settings.db_name,
|
||||||
|
query=query,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def get_engine() -> Engine:
|
||||||
|
settings = get_settings()
|
||||||
|
return create_engine(
|
||||||
|
database_url(settings),
|
||||||
|
pool_pre_ping=True,
|
||||||
|
pool_size=5,
|
||||||
|
max_overflow=5,
|
||||||
|
connect_args={
|
||||||
|
"application_name": "surveybox",
|
||||||
|
"connect_timeout": 10,
|
||||||
|
"options": f"-c search_path={DB_SCHEMA}",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def server_major_version(engine: Engine) -> int:
|
||||||
|
"""Hauptversion des PostgreSQL-Servers, z. B. 18."""
|
||||||
|
with engine.connect() as conn:
|
||||||
|
num = int(conn.execute(text("SHOW server_version_num")).scalar_one())
|
||||||
|
return num // 10000
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Löschjournal: gelöschte Personen und Antworten außerhalb der Datenbank.
|
||||||
|
|
||||||
|
Gelöschte Daten bleiben bis zur Rotation in den Sicherungen. Wird eine ältere
|
||||||
|
Sicherung zurückgespielt, kämen sie zurück. Deshalb steht jede Löschung zusätzlich
|
||||||
|
in /data/erasures.jsonl, nur mit Kennungen (UUIDs), ohne Namen oder Adressen.
|
||||||
|
|
||||||
|
Die Wiederherstellung legt eine Marke mit dem Zeitpunkt der Sicherung ab. Sobald
|
||||||
|
das Datenbankschema aktuell ist, wendet der Worker alle Löschungen seit diesem
|
||||||
|
Zeitpunkt erneut an und entfernt die Marke.
|
||||||
|
|
||||||
|
Einträge, die älter als die älteste vorhandene Sicherung sind, werden nicht mehr
|
||||||
|
gebraucht und beim Aufräumen entfernt.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
KINDS = ("user", "guest", "response", "retention")
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def journal_path(settings: Settings) -> Path:
|
||||||
|
return settings.data_dir / "erasures.jsonl"
|
||||||
|
|
||||||
|
|
||||||
|
def marker_path(settings: Settings) -> Path:
|
||||||
|
return settings.data_dir / "erasures.replay"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Entry:
|
||||||
|
at: datetime
|
||||||
|
kind: str
|
||||||
|
id: str
|
||||||
|
extra: dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
def record(settings: Settings, kind: str, public_id: uuid.UUID | str, **extra: Any) -> None:
|
||||||
|
"""Nach dem Commit aufrufen. Ein Fehler hier darf die Löschung nicht rückgängig machen."""
|
||||||
|
if kind not in KINDS:
|
||||||
|
raise ValueError(kind)
|
||||||
|
line = json.dumps({"at": datetime.now(UTC).isoformat(), "kind": kind,
|
||||||
|
"id": str(public_id), **extra}, separators=(",", ":"))
|
||||||
|
path = journal_path(settings)
|
||||||
|
try:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with path.open("a", encoding="utf-8") as handle:
|
||||||
|
handle.write(line + "\n")
|
||||||
|
handle.flush()
|
||||||
|
os.fsync(handle.fileno())
|
||||||
|
except OSError:
|
||||||
|
log.exception("Löschjournal konnte nicht geschrieben werden")
|
||||||
|
|
||||||
|
|
||||||
|
def entries(settings: Settings, since: datetime | None = None) -> list[Entry]:
|
||||||
|
path = journal_path(settings)
|
||||||
|
if not path.is_file():
|
||||||
|
return []
|
||||||
|
found: list[Entry] = []
|
||||||
|
for raw in path.read_text(encoding="utf-8").splitlines():
|
||||||
|
try:
|
||||||
|
data = json.loads(raw)
|
||||||
|
at = datetime.fromisoformat(data.pop("at"))
|
||||||
|
kind, ident = str(data.pop("kind")), str(data.pop("id"))
|
||||||
|
except (ValueError, KeyError, TypeError, AttributeError):
|
||||||
|
continue # angefangene Zeile nach einem Absturz
|
||||||
|
if kind in KINDS and (since is None or at >= since):
|
||||||
|
found.append(Entry(at, kind, ident, data))
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def prune(settings: Settings, before: datetime) -> int:
|
||||||
|
"""Einträge vor `before` entfernen (älter als jede vorhandene Sicherung)."""
|
||||||
|
path = journal_path(settings)
|
||||||
|
if not path.is_file():
|
||||||
|
return 0
|
||||||
|
keep = [e for e in entries(settings) if e.at >= before]
|
||||||
|
removed = len(path.read_text(encoding="utf-8").splitlines()) - len(keep)
|
||||||
|
if removed <= 0:
|
||||||
|
return 0
|
||||||
|
temp = path.with_suffix(".tmp")
|
||||||
|
with temp.open("w", encoding="utf-8") as handle:
|
||||||
|
for e in keep:
|
||||||
|
handle.write(json.dumps({"at": e.at.isoformat(), "kind": e.kind, "id": e.id,
|
||||||
|
**e.extra}, separators=(",", ":")) + "\n")
|
||||||
|
handle.flush()
|
||||||
|
os.fsync(handle.fileno())
|
||||||
|
os.replace(temp, path)
|
||||||
|
return removed
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Nach einer Wiederherstellung
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def mark_restore(settings: Settings, backup_time: datetime) -> None:
|
||||||
|
marker = marker_path(settings)
|
||||||
|
marker.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
marker.write_text(backup_time.astimezone(UTC).isoformat(), encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def pending_since(settings: Settings) -> datetime | None:
|
||||||
|
marker = marker_path(settings)
|
||||||
|
if not marker.is_file():
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return datetime.fromisoformat(marker.read_text(encoding="utf-8").strip())
|
||||||
|
except ValueError:
|
||||||
|
return datetime.min.replace(tzinfo=UTC) # unlesbar: alles erneut anwenden
|
||||||
|
|
||||||
|
|
||||||
|
def clear_marker(settings: Settings) -> None:
|
||||||
|
marker_path(settings).unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def replay(db: Any, settings: Settings, since: datetime) -> int:
|
||||||
|
"""Löschungen seit `since` erneut anwenden. Was es schon nicht mehr gibt, zählt nicht."""
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from surveybox.forms import erasure, retention
|
||||||
|
from surveybox.models import Form, GuestContact, Response, UserAccount
|
||||||
|
|
||||||
|
applied = 0
|
||||||
|
for entry in entries(settings, since):
|
||||||
|
try:
|
||||||
|
pid = uuid.UUID(entry.id)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
with db.begin_nested():
|
||||||
|
if entry.kind == "user":
|
||||||
|
user = db.scalar(select(UserAccount).where(UserAccount.public_id == pid))
|
||||||
|
if user is None:
|
||||||
|
continue
|
||||||
|
targets: dict[int, UserAccount | None] = {}
|
||||||
|
for form_id, target_pid in (entry.extra.get("forms") or {}).items():
|
||||||
|
target = None
|
||||||
|
if target_pid:
|
||||||
|
target = db.scalar(select(UserAccount).where(
|
||||||
|
UserAccount.public_id == uuid.UUID(target_pid)))
|
||||||
|
form = db.scalar(select(Form).where(Form.public_id == uuid.UUID(form_id)))
|
||||||
|
if form is not None:
|
||||||
|
targets[form.id] = target
|
||||||
|
erasure.erase_user(db, settings, user, targets, actor_id=None,
|
||||||
|
allow_last_admin=True)
|
||||||
|
elif entry.kind == "guest":
|
||||||
|
contact = db.scalar(select(GuestContact).where(GuestContact.public_id == pid))
|
||||||
|
if contact is None:
|
||||||
|
continue
|
||||||
|
erasure.erase_guest(db, settings, contact)
|
||||||
|
elif entry.kind == "response":
|
||||||
|
response = db.scalar(select(Response).where(Response.public_id == pid))
|
||||||
|
if response is None:
|
||||||
|
continue
|
||||||
|
erasure.delete_response(db, settings, response)
|
||||||
|
elif entry.kind == "retention":
|
||||||
|
form = db.scalar(select(Form).where(Form.public_id == pid))
|
||||||
|
if form is None:
|
||||||
|
continue
|
||||||
|
retention.apply(db, form, datetime.now(UTC))
|
||||||
|
applied += 1
|
||||||
|
return applied
|
||||||
|
|
||||||
|
|
||||||
|
def oldest_backup_time(settings: Settings) -> datetime | None:
|
||||||
|
"""Zeitpunkt der ältesten vorhandenen Sicherung (aus dem Dateinamen)."""
|
||||||
|
from surveybox.backup import BACKUP_KINDS, backup_time, list_backups
|
||||||
|
|
||||||
|
times = [backup_time(path) for kind in BACKUP_KINDS
|
||||||
|
for path in list_backups(settings.backup_dir / kind)]
|
||||||
|
known = [t for t in times if t is not None]
|
||||||
|
return min(known) if known else None
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Formulare: Fragetypen und Abläufe."""
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Plätze im Teilnahme-Feld vergeben, mit Warteliste.
|
||||||
|
|
||||||
|
Vergabe beim Absenden in derselben Transaktion wie die Antwort. Vorher wird
|
||||||
|
die Zeile der Frage gesperrt (SELECT … FOR UPDATE). Zwei gleichzeitige
|
||||||
|
Buchungen derselben Frage laufen damit nacheinander; der letzte Platz kann
|
||||||
|
nicht doppelt vergeben werden.
|
||||||
|
|
||||||
|
Wird ein Platz frei (Antwort geändert, Option abgewählt, Kapazität erhöht),
|
||||||
|
rückt die am längsten wartende Person nach; `promoted_at` merkt sich, wer
|
||||||
|
nachgerückt ist. Was dabei passiert, sammelt `Events`; die Benachrichtigungen
|
||||||
|
verschickt der Aufrufer (mail.notify.booking_events).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.forms import types
|
||||||
|
from surveybox.models import Booking, BookingStatus, Form, Question, Response
|
||||||
|
|
||||||
|
|
||||||
|
class SlotFull(Exception):
|
||||||
|
def __init__(self, question_id: int, option_id: str) -> None:
|
||||||
|
super().__init__(f"{question_id}:{option_id}")
|
||||||
|
self.question_id = question_id
|
||||||
|
self.option_id = option_id
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Availability:
|
||||||
|
capacity: int | None
|
||||||
|
confirmed: int
|
||||||
|
waiting: int
|
||||||
|
|
||||||
|
@property
|
||||||
|
def free(self) -> int | None:
|
||||||
|
return None if self.capacity is None else max(self.capacity - self.confirmed, 0)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def full(self) -> bool:
|
||||||
|
return self.capacity is not None and self.confirmed >= self.capacity
|
||||||
|
|
||||||
|
|
||||||
|
def _capacity(question: Question, option_id: str) -> int | None:
|
||||||
|
for option in types.options_of(question):
|
||||||
|
if option["id"] == option_id:
|
||||||
|
raw: Any = option.get("capacity")
|
||||||
|
return int(raw) if raw else None
|
||||||
|
return 0 # gelöschte Option: nichts mehr frei
|
||||||
|
|
||||||
|
|
||||||
|
def _lock(db: Session, question: Question) -> None:
|
||||||
|
db.execute(select(Question.id).where(Question.id == question.id).with_for_update())
|
||||||
|
|
||||||
|
|
||||||
|
def _counts(db: Session, question: Question) -> dict[tuple[str, str], int]:
|
||||||
|
rows = db.execute(
|
||||||
|
select(Booking.option_id, Booking.status, func.count())
|
||||||
|
.where(Booking.question_id == question.id)
|
||||||
|
.group_by(Booking.option_id, Booking.status)
|
||||||
|
).all()
|
||||||
|
return {(option, status): int(n) for option, status, n in rows}
|
||||||
|
|
||||||
|
|
||||||
|
def availability(db: Session, question: Question) -> dict[str, Availability]:
|
||||||
|
counts = _counts(db, question)
|
||||||
|
return {
|
||||||
|
o["id"]: Availability(
|
||||||
|
_capacity(question, o["id"]),
|
||||||
|
counts.get((o["id"], BookingStatus.CONFIRMED), 0),
|
||||||
|
counts.get((o["id"], BookingStatus.WAITING), 0),
|
||||||
|
)
|
||||||
|
for o in types.options_of(question)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def form_availability(db: Session, form: Form) -> dict[int, dict[str, Availability]]:
|
||||||
|
return {q.id: availability(db, q) for q in form.questions if q.type == "slots"}
|
||||||
|
|
||||||
|
|
||||||
|
def availability_for(
|
||||||
|
db: Session, form: Form, response_ids: list[int]
|
||||||
|
) -> dict[int, dict[str, Availability]]:
|
||||||
|
"""Belegung nur durch bestimmte Antworten (gefilterte Auswertung)."""
|
||||||
|
rows = db.execute(
|
||||||
|
select(Booking.question_id, Booking.option_id, Booking.status, func.count())
|
||||||
|
.where(Booking.form_id == form.id, Booking.response_id.in_(response_ids))
|
||||||
|
.group_by(Booking.question_id, Booking.option_id, Booking.status)
|
||||||
|
).all() if response_ids else []
|
||||||
|
counts = {(qid, oid, status): int(n) for qid, oid, status, n in rows}
|
||||||
|
return {
|
||||||
|
q.id: {
|
||||||
|
o["id"]: Availability(
|
||||||
|
_capacity(q, o["id"]),
|
||||||
|
counts.get((q.id, o["id"], BookingStatus.CONFIRMED), 0),
|
||||||
|
counts.get((q.id, o["id"], BookingStatus.WAITING), 0),
|
||||||
|
)
|
||||||
|
for o in types.options_of(q)
|
||||||
|
}
|
||||||
|
for q in form.questions if q.type == "slots"
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SlotNames:
|
||||||
|
confirmed: list[str] = field(default_factory=list)
|
||||||
|
waiting: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
def _display_name(full: str, mode: str) -> str:
|
||||||
|
if mode != "short":
|
||||||
|
return full
|
||||||
|
first, _, last = full.rpartition(" ") if " " in full else (full, "", "")
|
||||||
|
return types.short_name(first, last) if last else full
|
||||||
|
|
||||||
|
|
||||||
|
def names_for_form(db: Session, form: Form) -> dict[int, dict[str, SlotNames]]:
|
||||||
|
"""Wer sich schon eingetragen hat, je Teilnahme-Feld und Option (in Reihenfolge).
|
||||||
|
|
||||||
|
Nur, wenn das Formular es so eingestellt hat und nicht anonym ist. Der Name kommt
|
||||||
|
aus dem Feld "Teilnehmer-Name", sonst aus dem Konto; Gäste ohne Namen erscheinen
|
||||||
|
als "Gast". E-Mail-Adressen werden nie angezeigt.
|
||||||
|
"""
|
||||||
|
mode = form.slot_names
|
||||||
|
if mode not in ("full", "short") or form.anonymous:
|
||||||
|
return {}
|
||||||
|
from surveybox.i18n import gettext
|
||||||
|
from surveybox.models import Answer, UserAccount
|
||||||
|
|
||||||
|
name_q = next((q for q in form.questions if q.type == "participant_name"), None)
|
||||||
|
rows = db.execute(
|
||||||
|
select(Booking.question_id, Booking.option_id, Booking.status, Booking.response_id,
|
||||||
|
Response.user_id)
|
||||||
|
.join(Response, Response.id == Booking.response_id)
|
||||||
|
.where(Booking.form_id == form.id)
|
||||||
|
.order_by(Booking.created_at, Booking.id)
|
||||||
|
).all()
|
||||||
|
if not rows:
|
||||||
|
return {}
|
||||||
|
response_ids = {r.response_id for r in rows}
|
||||||
|
given: dict[int, str] = {}
|
||||||
|
if name_q is not None:
|
||||||
|
for answer in db.scalars(select(Answer).where(
|
||||||
|
Answer.question_id == name_q.id, Answer.response_id.in_(response_ids))):
|
||||||
|
parts = types.name_parts({"value_json": answer.value_json})
|
||||||
|
if parts["first"] or parts["last"]:
|
||||||
|
given[answer.response_id] = (
|
||||||
|
types.short_name(parts["first"], parts["last"]) if mode == "short"
|
||||||
|
else f"{parts['first']} {parts['last']}".strip()
|
||||||
|
)
|
||||||
|
user_ids = {r.user_id for r in rows if r.user_id is not None and r.response_id not in given}
|
||||||
|
accounts = dict(db.execute(
|
||||||
|
select(UserAccount.id, UserAccount.display_name).where(UserAccount.id.in_(user_ids))
|
||||||
|
).tuples().all()) if user_ids else {}
|
||||||
|
guest = gettext("Guest")
|
||||||
|
result: dict[int, dict[str, SlotNames]] = {}
|
||||||
|
for row in rows:
|
||||||
|
name = given.get(row.response_id)
|
||||||
|
if name is None:
|
||||||
|
account = accounts.get(row.user_id) if row.user_id is not None else None
|
||||||
|
name = _display_name(account, mode) if account else guest
|
||||||
|
names = result.setdefault(row.question_id, {}).setdefault(row.option_id, SlotNames())
|
||||||
|
(names.waiting if row.status == BookingStatus.WAITING else names.confirmed).append(name)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Events:
|
||||||
|
"""Was beim Buchen passiert ist; daraus entstehen Benachrichtigungen (mail.notify)."""
|
||||||
|
|
||||||
|
promoted: list[tuple[Question, Booking]] = field(default_factory=list)
|
||||||
|
filled: list[tuple[Question, str]] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
def promote(db: Session, question: Question, option_id: str) -> list[Booking]:
|
||||||
|
"""Lässt Wartende nachrücken, solange Plätze frei sind. Gibt die Nachgerückten zurück."""
|
||||||
|
capacity = _capacity(question, option_id)
|
||||||
|
confirmed = db.scalar(
|
||||||
|
select(func.count()).select_from(Booking).where(
|
||||||
|
Booking.question_id == question.id,
|
||||||
|
Booking.option_id == option_id,
|
||||||
|
Booking.status == BookingStatus.CONFIRMED,
|
||||||
|
)
|
||||||
|
) or 0
|
||||||
|
free = None if capacity is None else capacity - confirmed
|
||||||
|
waiting = db.scalars(
|
||||||
|
select(Booking)
|
||||||
|
.where(
|
||||||
|
Booking.question_id == question.id,
|
||||||
|
Booking.option_id == option_id,
|
||||||
|
Booking.status == BookingStatus.WAITING,
|
||||||
|
)
|
||||||
|
.order_by(Booking.created_at, Booking.id)
|
||||||
|
).all()
|
||||||
|
moved: list[Booking] = []
|
||||||
|
for booking in waiting:
|
||||||
|
if free is not None and free <= 0:
|
||||||
|
break
|
||||||
|
booking.status = BookingStatus.CONFIRMED
|
||||||
|
booking.promoted_at = datetime.now(UTC)
|
||||||
|
moved.append(booking)
|
||||||
|
if free is not None:
|
||||||
|
free -= 1
|
||||||
|
return moved
|
||||||
|
|
||||||
|
|
||||||
|
def promote_all(db: Session, question: Question, events: Events | None = None) -> int:
|
||||||
|
"""Nach einer Änderung der Kapazitäten im Designer."""
|
||||||
|
if question.type != "slots":
|
||||||
|
return 0
|
||||||
|
_lock(db, question)
|
||||||
|
count = 0
|
||||||
|
for option in types.options_of(question):
|
||||||
|
moved = promote(db, question, option["id"])
|
||||||
|
count += len(moved)
|
||||||
|
if events is not None:
|
||||||
|
events.promoted.extend((question, b) for b in moved)
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
def book(
|
||||||
|
db: Session,
|
||||||
|
form: Form,
|
||||||
|
response: Response,
|
||||||
|
selections: Mapping[int, list[str]],
|
||||||
|
events: Events | None = None,
|
||||||
|
) -> dict[int, dict[str, str]]:
|
||||||
|
"""Bringt die Buchungen einer Antwort auf den gewünschten Stand.
|
||||||
|
|
||||||
|
selections: je Teilnahme-Frage die gewählten Optionen (auch leer, um alles
|
||||||
|
freizugeben). Ergebnis: je Frage Option -> Status. Ist ein Platz voll und
|
||||||
|
gibt es keine Warteliste, wird SlotFull ausgelöst; der Aufrufer rollt die
|
||||||
|
Transaktion zurück.
|
||||||
|
"""
|
||||||
|
db.flush() # die Antwort braucht ihre ID
|
||||||
|
result: dict[int, dict[str, str]] = {}
|
||||||
|
for question in form.questions:
|
||||||
|
if question.type != "slots":
|
||||||
|
continue
|
||||||
|
wanted = list(dict.fromkeys(selections.get(question.id) or []))
|
||||||
|
existing = {
|
||||||
|
b.option_id: b
|
||||||
|
for b in db.scalars(
|
||||||
|
select(Booking).where(
|
||||||
|
Booking.response_id == response.id, Booking.question_id == question.id
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if not wanted and not existing:
|
||||||
|
continue
|
||||||
|
_lock(db, question)
|
||||||
|
released = [oid for oid in existing if oid not in wanted]
|
||||||
|
for option_id in released:
|
||||||
|
db.delete(existing.pop(option_id))
|
||||||
|
db.flush()
|
||||||
|
statuses: dict[str, str] = {}
|
||||||
|
for option_id in wanted:
|
||||||
|
if option_id in existing:
|
||||||
|
statuses[option_id] = existing[option_id].status
|
||||||
|
continue
|
||||||
|
capacity = _capacity(question, option_id)
|
||||||
|
confirmed = db.scalar(
|
||||||
|
select(func.count()).select_from(Booking).where(
|
||||||
|
Booking.question_id == question.id,
|
||||||
|
Booking.option_id == option_id,
|
||||||
|
Booking.status == BookingStatus.CONFIRMED,
|
||||||
|
)
|
||||||
|
) or 0
|
||||||
|
if capacity is None or confirmed < capacity:
|
||||||
|
status = BookingStatus.CONFIRMED
|
||||||
|
if events is not None and capacity is not None and confirmed + 1 >= capacity:
|
||||||
|
events.filled.append((question, option_id))
|
||||||
|
elif question.config.get("waitlist"):
|
||||||
|
status = BookingStatus.WAITING
|
||||||
|
else:
|
||||||
|
raise SlotFull(question.id, option_id)
|
||||||
|
db.add(
|
||||||
|
Booking(
|
||||||
|
form_id=form.id,
|
||||||
|
question_id=question.id,
|
||||||
|
option_id=option_id,
|
||||||
|
response_id=response.id,
|
||||||
|
status=status,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
statuses[option_id] = status
|
||||||
|
db.flush()
|
||||||
|
for option_id in released:
|
||||||
|
moved = promote(db, question, option_id)
|
||||||
|
if events is not None:
|
||||||
|
events.promoted.extend((question, b) for b in moved)
|
||||||
|
result[question.id] = statuses
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def statuses_for(db: Session, response: Response) -> dict[tuple[int, str], str]:
|
||||||
|
return {
|
||||||
|
(b.question_id, b.option_id): b.status
|
||||||
|
for b in db.scalars(select(Booking).where(Booking.response_id == response.id))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def slots_chosen(form: Form, stored: Mapping[int, Mapping[str, Any]]) -> dict[int, list[str]]:
|
||||||
|
"""Gewählte Optionen je Teilnahme-Frage aus den geprüften Antworten."""
|
||||||
|
result: dict[int, list[str]] = {}
|
||||||
|
for question in form.questions:
|
||||||
|
if question.type == "slots":
|
||||||
|
data = (stored.get(question.id) or {}).get("value_json") or {}
|
||||||
|
result[question.id] = list(data.get("selected") or [])
|
||||||
|
return result
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
# 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"
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Gestrichene Einträge: Teilnehmende benachrichtigen, deren Wahl entfällt.
|
||||||
|
|
||||||
|
Entfernt der Ersteller eine Option einer Abstimmung oder einer Teilnahme mit
|
||||||
|
Plätzen, verlieren Buchungen darauf ihre Grundlage. Die Buchungen werden
|
||||||
|
gelöscht; wer betroffen ist, bekommt eine Mail mit der Bitte, seine Antwort zu
|
||||||
|
prüfen (Ereignis "changed").
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import delete, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.mail import notify
|
||||||
|
from surveybox.models import Answer, Booking, Form, Question, Response
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
|
||||||
|
def removed_options(
|
||||||
|
before: Sequence[dict[str, Any]], after: Sequence[dict[str, Any]]
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
kept = {o.get("id") for o in after}
|
||||||
|
return [dict(o) for o in before if o.get("id") not in kept]
|
||||||
|
|
||||||
|
|
||||||
|
def drop_bookings(db: Session, question: Question, option_ids: Sequence[str]) -> set[int]:
|
||||||
|
"""Buchungen auf entfernte Optionen löschen. Gibt die betroffenen Antworten zurück."""
|
||||||
|
if question.type != "slots" or not option_ids:
|
||||||
|
return set()
|
||||||
|
affected = set(db.scalars(
|
||||||
|
select(Booking.response_id).where(
|
||||||
|
Booking.question_id == question.id, Booking.option_id.in_(list(option_ids))
|
||||||
|
)
|
||||||
|
))
|
||||||
|
db.execute(delete(Booking).where(
|
||||||
|
Booking.question_id == question.id, Booking.option_id.in_(list(option_ids))
|
||||||
|
))
|
||||||
|
return affected
|
||||||
|
|
||||||
|
|
||||||
|
def poll_voters(db: Session, question: Question, option_ids: Sequence[str]) -> set[int]:
|
||||||
|
"""Antworten mit "Ja" oder "Vielleicht" auf eine entfernte Option einer Abstimmung."""
|
||||||
|
if question.type != "poll" or not option_ids:
|
||||||
|
return set()
|
||||||
|
wanted = set(option_ids)
|
||||||
|
found: set[int] = set()
|
||||||
|
for response_id, value in db.execute(
|
||||||
|
select(Answer.response_id, Answer.value_json).where(Answer.question_id == question.id)
|
||||||
|
):
|
||||||
|
votes = (value or {}).get("votes") or {}
|
||||||
|
if any(votes.get(oid) in ("yes", "maybe") for oid in wanted):
|
||||||
|
found.add(int(response_id))
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def notify_affected(
|
||||||
|
db: Session,
|
||||||
|
settings: Settings,
|
||||||
|
form: Form,
|
||||||
|
question: Question,
|
||||||
|
removed: Sequence[dict[str, Any]],
|
||||||
|
response_ids: set[int],
|
||||||
|
) -> int:
|
||||||
|
if form.anonymous or not removed or not response_ids:
|
||||||
|
return 0
|
||||||
|
key = ",".join(sorted(str(o.get("id")) for o in removed))
|
||||||
|
sent = 0
|
||||||
|
seen: set[str] = set()
|
||||||
|
for response in db.scalars(select(Response).where(Response.id.in_(response_ids))):
|
||||||
|
recipient = notify.participant(db, settings, form, response)
|
||||||
|
if recipient is None or recipient.ident in seen:
|
||||||
|
continue
|
||||||
|
seen.add(recipient.ident)
|
||||||
|
if notify.send(
|
||||||
|
db, settings, recipient, kind="changed", event="changed", form=form,
|
||||||
|
context={"question": question.label, "options": list(removed),
|
||||||
|
"link": notify.form_link(settings, form)},
|
||||||
|
dedupe_key=f"changed:{question.id}:{key}:{recipient.ident}",
|
||||||
|
):
|
||||||
|
sent += 1
|
||||||
|
return sent
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Kommentare zu Formularen, auf Wunsch moderiert.
|
||||||
|
|
||||||
|
- Moderiert: Ein neuer oder geänderter Kommentar ist erst sichtbar, wenn ein
|
||||||
|
Verwalter ihn freischaltet. Der Autor sieht ihn vorher mit Hinweis.
|
||||||
|
- Öffentlich: sofort sichtbar.
|
||||||
|
- Anonym veröffentlicht: Andere sehen keinen Namen; Verwalter schon.
|
||||||
|
|
||||||
|
Gäste (ohne Konto) erkennt Surveybox an einem Zufallswert im Cookie; in der
|
||||||
|
Datenbank steht nur dessen Schlüssel-Hash.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.models import Comment, CommentStatus, Form, UserAccount
|
||||||
|
from surveybox.security.tokens import derive_key, keyed_hash
|
||||||
|
|
||||||
|
MAX_BODY = 2000
|
||||||
|
MAX_NAME = 80
|
||||||
|
LIMIT_PER_HOUR = 10
|
||||||
|
|
||||||
|
|
||||||
|
class CommentError(ValueError):
|
||||||
|
def __init__(self, code: str) -> None:
|
||||||
|
super().__init__(code)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Viewer:
|
||||||
|
user_id: int | None
|
||||||
|
guest_hash: bytes | None
|
||||||
|
manager: bool
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ShownComment:
|
||||||
|
comment: Comment
|
||||||
|
author: str # leer bei anonym für andere
|
||||||
|
own: bool
|
||||||
|
pending: bool
|
||||||
|
|
||||||
|
|
||||||
|
def guest_cookie_name(form: Form) -> str:
|
||||||
|
return f"sb_comment_{form.id}"
|
||||||
|
|
||||||
|
|
||||||
|
def guest_hash(secret_key: str, form: Form, cookie_value: str | None) -> bytes | None:
|
||||||
|
if not cookie_value or len(cookie_value) > 64:
|
||||||
|
return None
|
||||||
|
return keyed_hash(derive_key(secret_key, "comment-guest"), f"{form.id}:{cookie_value}")
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_body(body: str) -> str:
|
||||||
|
text = body.replace("\r\n", "\n").strip()
|
||||||
|
if not text:
|
||||||
|
raise CommentError("comment_empty")
|
||||||
|
if len(text) > MAX_BODY:
|
||||||
|
raise CommentError("comment_too_long")
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def _is_own(comment: Comment, viewer: Viewer) -> bool:
|
||||||
|
if viewer.user_id is not None and comment.user_id == viewer.user_id:
|
||||||
|
return True
|
||||||
|
return viewer.guest_hash is not None and comment.author_token == viewer.guest_hash
|
||||||
|
|
||||||
|
|
||||||
|
def recent_count(db: Session, form: Form, viewer: Viewer) -> int:
|
||||||
|
since = datetime.now(UTC).timestamp() - 3600
|
||||||
|
stmt = select(func.count()).select_from(Comment).where(
|
||||||
|
Comment.form_id == form.id,
|
||||||
|
Comment.created_at >= datetime.fromtimestamp(since, UTC),
|
||||||
|
)
|
||||||
|
if viewer.user_id is not None:
|
||||||
|
stmt = stmt.where(Comment.user_id == viewer.user_id)
|
||||||
|
elif viewer.guest_hash is not None:
|
||||||
|
stmt = stmt.where(Comment.author_token == viewer.guest_hash)
|
||||||
|
else:
|
||||||
|
return 0
|
||||||
|
return int(db.scalar(stmt) or 0)
|
||||||
|
|
||||||
|
|
||||||
|
def create(
|
||||||
|
db: Session, form: Form, viewer: Viewer, body: str, guest_name: str = ""
|
||||||
|
) -> Comment:
|
||||||
|
if form.comments_mode == "off":
|
||||||
|
raise CommentError("comments_off")
|
||||||
|
text = _clean_body(body)
|
||||||
|
name = " ".join(guest_name.split())[:MAX_NAME]
|
||||||
|
if viewer.user_id is None and (not name or viewer.guest_hash is None):
|
||||||
|
raise CommentError("comment_name_missing")
|
||||||
|
if recent_count(db, form, viewer) >= LIMIT_PER_HOUR:
|
||||||
|
raise CommentError("comment_limit")
|
||||||
|
comment = Comment(
|
||||||
|
form_id=form.id,
|
||||||
|
user_id=viewer.user_id,
|
||||||
|
guest_name=name if viewer.user_id is None else None,
|
||||||
|
author_token=viewer.guest_hash if viewer.user_id is None else None,
|
||||||
|
body=text,
|
||||||
|
status=CommentStatus.PENDING
|
||||||
|
if form.comments_mode == "moderated" and not viewer.manager
|
||||||
|
else CommentStatus.PUBLISHED,
|
||||||
|
)
|
||||||
|
db.add(comment)
|
||||||
|
db.flush()
|
||||||
|
return comment
|
||||||
|
|
||||||
|
|
||||||
|
def find(db: Session, form: Form, public_id: str) -> Comment | None:
|
||||||
|
try:
|
||||||
|
pid = uuid.UUID(public_id)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return db.scalar(select(Comment).where(Comment.public_id == pid, Comment.form_id == form.id))
|
||||||
|
|
||||||
|
|
||||||
|
def edit(form: Form, comment: Comment, viewer: Viewer, body: str) -> None:
|
||||||
|
if not _is_own(comment, viewer):
|
||||||
|
raise CommentError("comment_not_own")
|
||||||
|
comment.body = _clean_body(body)
|
||||||
|
comment.updated_at = datetime.now(UTC)
|
||||||
|
if form.comments_mode == "moderated" and not viewer.manager:
|
||||||
|
comment.status = CommentStatus.PENDING
|
||||||
|
|
||||||
|
|
||||||
|
def delete(db: Session, comment: Comment, viewer: Viewer) -> None:
|
||||||
|
if not (viewer.manager or _is_own(comment, viewer)):
|
||||||
|
raise CommentError("comment_not_own")
|
||||||
|
db.delete(comment)
|
||||||
|
|
||||||
|
|
||||||
|
def publish(comment: Comment) -> None:
|
||||||
|
comment.status = CommentStatus.PUBLISHED
|
||||||
|
|
||||||
|
|
||||||
|
def _author(comment: Comment, names: dict[int, str]) -> str:
|
||||||
|
if comment.author_deleted:
|
||||||
|
from surveybox.i18n import gettext
|
||||||
|
|
||||||
|
return gettext("Deleted user")
|
||||||
|
if comment.user_id is not None:
|
||||||
|
return names.get(comment.user_id, "")
|
||||||
|
return comment.guest_name or ""
|
||||||
|
|
||||||
|
|
||||||
|
def visible(db: Session, form: Form, viewer: Viewer) -> list[ShownComment]:
|
||||||
|
"""Was der Betrachter sieht: freigeschaltete und eigene; Verwalter alles."""
|
||||||
|
rows = list(
|
||||||
|
db.scalars(
|
||||||
|
select(Comment).where(Comment.form_id == form.id).order_by(Comment.created_at)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
user_ids = {c.user_id for c in rows if c.user_id is not None}
|
||||||
|
names = (
|
||||||
|
dict(db.execute(
|
||||||
|
select(UserAccount.id, UserAccount.display_name).where(UserAccount.id.in_(user_ids))
|
||||||
|
).all())
|
||||||
|
if user_ids
|
||||||
|
else {}
|
||||||
|
)
|
||||||
|
shown: list[ShownComment] = []
|
||||||
|
for comment in rows:
|
||||||
|
own = _is_own(comment, viewer)
|
||||||
|
pending = comment.status == CommentStatus.PENDING
|
||||||
|
if pending and not (own or viewer.manager):
|
||||||
|
continue
|
||||||
|
author = _author(comment, names)
|
||||||
|
if form.comments_anonymous and not viewer.manager and not own:
|
||||||
|
author = ""
|
||||||
|
shown.append(ShownComment(comment, author, own, pending))
|
||||||
|
return shown
|
||||||
|
|
||||||
|
|
||||||
|
def pending_count(db: Session, form: Form) -> int:
|
||||||
|
return int(
|
||||||
|
db.scalar(
|
||||||
|
select(func.count()).select_from(Comment).where(
|
||||||
|
Comment.form_id == form.id, Comment.status == CommentStatus.PENDING
|
||||||
|
)
|
||||||
|
)
|
||||||
|
or 0
|
||||||
|
)
|
||||||
@@ -0,0 +1,480 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Bedingungen: Fragen, Abschnitte und Seiten abhängig von Antworten zeigen.
|
||||||
|
|
||||||
|
Eine Bedingung steht in `question.config["condition"]`:
|
||||||
|
|
||||||
|
{"action": "show" | "hide", "match": "all" | "any",
|
||||||
|
"rules": [{"q": <frühere Frage>, "op": "eq", "value": "…"}]}
|
||||||
|
|
||||||
|
Bei einer Überschrift gilt sie für den ganzen Abschnitt bis zur nächsten
|
||||||
|
Überschrift oder Seite, bei einem Seitenumbruch für die ganze Seite, bei einer
|
||||||
|
Fragengruppe für alle Fragen der Gruppe (siehe forms.groups).
|
||||||
|
|
||||||
|
Der Browser (static/js/fill.js) wertet dieselben Regeln aus, damit die Seite
|
||||||
|
sofort reagiert. Verbindlich ist die Auswertung hier beim Absenden: Was
|
||||||
|
ausgeblendet ist, wird weder geprüft noch gespeichert. Eine Regel darf nur
|
||||||
|
auf frühere Fragen verweisen; damit sind Kreisbezüge ausgeschlossen.
|
||||||
|
|
||||||
|
Das Modul kennt weder Datenbank noch Web.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Iterable, Mapping, Sequence
|
||||||
|
from datetime import date, datetime, time
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
|
from typing import Any, Protocol
|
||||||
|
|
||||||
|
from surveybox.forms import groups, types
|
||||||
|
from surveybox.i18n import N_
|
||||||
|
|
||||||
|
MAX_RULES = 20
|
||||||
|
MAX_VALUE = 200
|
||||||
|
|
||||||
|
OPS: dict[str, str] = {
|
||||||
|
"eq": N_("is"),
|
||||||
|
"ne": N_("is not"),
|
||||||
|
"contains": N_("contains"),
|
||||||
|
"not_contains": N_("does not contain"),
|
||||||
|
"gt": N_("is greater than"),
|
||||||
|
"lt": N_("is less than"),
|
||||||
|
"empty": N_("is not answered"),
|
||||||
|
"not_empty": N_("is answered"),
|
||||||
|
}
|
||||||
|
NO_VALUE = {"empty", "not_empty"}
|
||||||
|
|
||||||
|
# Art des Vergleichs je Fragetyp
|
||||||
|
KIND: dict[str, str] = {
|
||||||
|
"short_text": "text",
|
||||||
|
"long_text": "text",
|
||||||
|
"email": "text",
|
||||||
|
"phone": "text",
|
||||||
|
"number": "number",
|
||||||
|
"rating": "number",
|
||||||
|
"date": "date",
|
||||||
|
"time": "time",
|
||||||
|
"datetime": "datetime",
|
||||||
|
"yes_no": "choice",
|
||||||
|
"single_choice": "choice",
|
||||||
|
"multiple_choice": "multi",
|
||||||
|
"ranking": "presence",
|
||||||
|
"file_upload": "presence",
|
||||||
|
"slots": "multi",
|
||||||
|
"poll": "presence",
|
||||||
|
}
|
||||||
|
OPS_FOR: dict[str, list[str]] = {
|
||||||
|
"text": ["eq", "ne", "contains", "not_contains", "empty", "not_empty"],
|
||||||
|
"number": ["eq", "ne", "gt", "lt", "empty", "not_empty"],
|
||||||
|
"date": ["eq", "ne", "gt", "lt", "empty", "not_empty"],
|
||||||
|
"time": ["eq", "ne", "gt", "lt", "empty", "not_empty"],
|
||||||
|
"datetime": ["eq", "ne", "gt", "lt", "empty", "not_empty"],
|
||||||
|
"choice": ["eq", "ne", "empty", "not_empty"],
|
||||||
|
"multi": ["contains", "not_contains", "empty", "not_empty"],
|
||||||
|
"presence": ["empty", "not_empty"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class QuestionLike(Protocol):
|
||||||
|
id: int
|
||||||
|
position: int
|
||||||
|
type: str
|
||||||
|
label: str
|
||||||
|
required: bool
|
||||||
|
config: dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
class ConditionError(ValueError):
|
||||||
|
def __init__(self, code: str) -> None:
|
||||||
|
super().__init__(code)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Werte normalisieren (gleich wie im Browser)
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: str) -> str:
|
||||||
|
return " ".join(value.split()).lower()
|
||||||
|
|
||||||
|
|
||||||
|
def _number(value: str) -> Decimal | None:
|
||||||
|
raw = value.strip().replace(",", ".").replace(" ", "")
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
number = Decimal(raw)
|
||||||
|
except InvalidOperation:
|
||||||
|
return None
|
||||||
|
return number if number.is_finite() else None
|
||||||
|
|
||||||
|
|
||||||
|
def _temporal(kind: str, value: str) -> str:
|
||||||
|
"""Datum "JJJJ-MM-TT", Zeit "HH:MM", Datum+Zeit "JJJJ-MM-TTTHH:MM"."""
|
||||||
|
raw = value.strip()
|
||||||
|
return raw[: {"date": 10, "time": 5, "datetime": 16}[kind]]
|
||||||
|
|
||||||
|
|
||||||
|
def options_for_rules(question: QuestionLike) -> list[tuple[str, str]]:
|
||||||
|
"""Mögliche Vergleichswerte einer Auswahlfrage: (Wert, Beschriftung)."""
|
||||||
|
if question.type == "yes_no":
|
||||||
|
cfg = question.config
|
||||||
|
return [("yes", cfg.get("label_yes") or "Yes"), ("no", cfg.get("label_no") or "No")]
|
||||||
|
if question.type == "slots" and question.config.get("single"):
|
||||||
|
return [(types.SINGLE_SLOT, "signed up")]
|
||||||
|
result = [(o["id"], o["label"]) for o in types.options_of(question)]
|
||||||
|
if question.config.get("allow_other"):
|
||||||
|
result.append((types.OTHER, "Other"))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def clean_value(question: QuestionLike, op: str, raw: str) -> str:
|
||||||
|
"""Vergleichswert aus dem Designer prüfen und vereinheitlichen."""
|
||||||
|
if op in NO_VALUE:
|
||||||
|
return ""
|
||||||
|
kind = KIND[question.type]
|
||||||
|
value = raw.strip()
|
||||||
|
if kind in ("choice", "multi"):
|
||||||
|
if value not in {v for v, _ in options_for_rules(question)}:
|
||||||
|
raise ConditionError("condition_value_invalid")
|
||||||
|
return value
|
||||||
|
if not value:
|
||||||
|
raise ConditionError("condition_value_invalid")
|
||||||
|
if kind == "text":
|
||||||
|
if len(value) > MAX_VALUE:
|
||||||
|
raise ConditionError("condition_value_invalid")
|
||||||
|
return " ".join(value.split())
|
||||||
|
if kind == "number":
|
||||||
|
number = _number(value)
|
||||||
|
if number is None:
|
||||||
|
raise ConditionError("condition_value_invalid")
|
||||||
|
return str(number.normalize())
|
||||||
|
try:
|
||||||
|
if kind == "date":
|
||||||
|
return date.fromisoformat(value).isoformat()
|
||||||
|
if kind == "time":
|
||||||
|
return time.fromisoformat(value).strftime("%H:%M")
|
||||||
|
return datetime.fromisoformat(value).strftime("%Y-%m-%dT%H:%M")
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ConditionError("condition_value_invalid") from exc
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Bedingung aus dem Designer
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _first(fields: Mapping[str, list[str]], name: str) -> str:
|
||||||
|
values = fields.get(name) or []
|
||||||
|
return values[0] if values else ""
|
||||||
|
|
||||||
|
|
||||||
|
def earlier_inputs(
|
||||||
|
question: QuestionLike | None, questions: Sequence[QuestionLike]
|
||||||
|
) -> list[QuestionLike]:
|
||||||
|
"""Fragen, auf die sich eine Bedingung beziehen darf (Eingabefragen davor)."""
|
||||||
|
limit = question.position if question is not None and question.id else None
|
||||||
|
return [
|
||||||
|
q
|
||||||
|
for q in questions
|
||||||
|
if q.type in KIND and (limit is None or q.position < limit) and q is not question
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def parse(
|
||||||
|
question: QuestionLike | None,
|
||||||
|
fields: Mapping[str, list[str]],
|
||||||
|
questions: Sequence[QuestionLike],
|
||||||
|
) -> dict[str, Any] | None:
|
||||||
|
"""Liest den Bedingungs-Editor. None: keine Bedingung."""
|
||||||
|
candidates = {q.id: q for q in earlier_inputs(question, questions)}
|
||||||
|
refs = fields.get("rule_q") or []
|
||||||
|
ops = fields.get("rule_op") or []
|
||||||
|
texts = fields.get("rule_text") or []
|
||||||
|
options = fields.get("rule_option") or []
|
||||||
|
rules: list[dict[str, Any]] = []
|
||||||
|
for index, raw_ref in enumerate(refs):
|
||||||
|
if not raw_ref.strip():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
ref = candidates[int(raw_ref)]
|
||||||
|
except (ValueError, KeyError) as exc:
|
||||||
|
raise ConditionError("condition_ref_invalid") from exc
|
||||||
|
op = ops[index] if index < len(ops) else ""
|
||||||
|
if op not in OPS_FOR[KIND[ref.type]]:
|
||||||
|
raise ConditionError("condition_op_invalid")
|
||||||
|
kind = KIND[ref.type]
|
||||||
|
source = options if kind in ("choice", "multi") else texts
|
||||||
|
raw = source[index] if index < len(source) else ""
|
||||||
|
rules.append({"q": ref.id, "op": op, "value": clean_value(ref, op, raw)})
|
||||||
|
if not rules:
|
||||||
|
return None
|
||||||
|
if len(rules) > MAX_RULES:
|
||||||
|
raise ConditionError("condition_too_many")
|
||||||
|
return {
|
||||||
|
"action": "hide" if _first(fields, "cond_action") == "hide" else "show",
|
||||||
|
"match": "any" if _first(fields, "cond_match") == "any" else "all",
|
||||||
|
"rules": rules,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Auswertung
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _answer(question: QuestionLike, fields: Mapping[str, list[str]], with_files: set[int]) -> Any:
|
||||||
|
"""Eingabe einer Frage in vergleichbarer Form; None/""/[] bedeutet leer."""
|
||||||
|
name = f"q{question.id}"
|
||||||
|
kind = KIND.get(question.type)
|
||||||
|
raw = _first(fields, name)
|
||||||
|
if kind == "text":
|
||||||
|
return _text(raw)
|
||||||
|
if kind == "number":
|
||||||
|
return _number(raw)
|
||||||
|
if kind in ("date", "time", "datetime"):
|
||||||
|
return _temporal(kind, raw)
|
||||||
|
if kind == "choice":
|
||||||
|
return raw.strip()
|
||||||
|
if kind == "multi":
|
||||||
|
return [v for v in fields.get(name) or [] if v]
|
||||||
|
if question.type == "ranking":
|
||||||
|
prefix = f"{name}_rank_"
|
||||||
|
return any(_first(fields, k) for k in fields if k.startswith(prefix))
|
||||||
|
if question.type == "file_upload":
|
||||||
|
return question.id in with_files
|
||||||
|
if question.type == "poll":
|
||||||
|
prefix = f"{name}_"
|
||||||
|
votes = [k for k in fields if k.startswith(prefix) and "_" not in k[len(prefix) :]]
|
||||||
|
return any(_first(fields, k) for k in votes)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _is_empty(value: Any) -> bool:
|
||||||
|
return value is None or value == "" or value == [] or value is False
|
||||||
|
|
||||||
|
|
||||||
|
def rule_matches(rule: Mapping[str, Any], kind: str, value: Any) -> bool:
|
||||||
|
op = rule.get("op")
|
||||||
|
target = str(rule.get("value", ""))
|
||||||
|
if op == "empty":
|
||||||
|
return _is_empty(value)
|
||||||
|
if op == "not_empty":
|
||||||
|
return not _is_empty(value)
|
||||||
|
if kind == "multi":
|
||||||
|
chosen = value or []
|
||||||
|
return (target in chosen) if op == "contains" else (target not in chosen)
|
||||||
|
if kind == "text":
|
||||||
|
wanted = _text(target)
|
||||||
|
if op == "eq":
|
||||||
|
return value == wanted
|
||||||
|
if op == "ne":
|
||||||
|
return value != wanted
|
||||||
|
if op == "contains":
|
||||||
|
return wanted in (value or "")
|
||||||
|
if op == "not_contains":
|
||||||
|
return wanted not in (value or "")
|
||||||
|
return False
|
||||||
|
if kind == "number":
|
||||||
|
wanted_n = _number(target)
|
||||||
|
if value is None or wanted_n is None:
|
||||||
|
return op == "ne"
|
||||||
|
return {"eq": value == wanted_n, "ne": value != wanted_n,
|
||||||
|
"gt": value > wanted_n, "lt": value < wanted_n}.get(str(op), False)
|
||||||
|
if kind in ("date", "time", "datetime", "choice"):
|
||||||
|
if _is_empty(value):
|
||||||
|
return op == "ne"
|
||||||
|
return {"eq": value == target, "ne": value != target,
|
||||||
|
"gt": value > target, "lt": value < target}.get(str(op), False)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _holds(
|
||||||
|
condition: Mapping[str, Any] | None,
|
||||||
|
by_id: Mapping[int, QuestionLike],
|
||||||
|
values: Mapping[int, Any],
|
||||||
|
) -> bool:
|
||||||
|
"""Ist das Element sichtbar? Ohne Bedingung immer."""
|
||||||
|
if not condition or not condition.get("rules"):
|
||||||
|
return True
|
||||||
|
results = []
|
||||||
|
for rule in condition["rules"]:
|
||||||
|
ref = by_id.get(int(rule.get("q", 0)))
|
||||||
|
if ref is None or ref.type not in KIND:
|
||||||
|
results.append(False) # verwaiste Regel trifft nie zu
|
||||||
|
continue
|
||||||
|
results.append(rule_matches(rule, KIND[ref.type], values.get(ref.id)))
|
||||||
|
matched = any(results) if condition.get("match") == "any" else all(results)
|
||||||
|
return matched if condition.get("action", "show") == "show" else not matched
|
||||||
|
|
||||||
|
|
||||||
|
def visibility(
|
||||||
|
questions: Sequence[QuestionLike],
|
||||||
|
fields: Mapping[str, list[str]],
|
||||||
|
with_files: Iterable[int] = (),
|
||||||
|
) -> dict[int, bool]:
|
||||||
|
"""Sichtbarkeit jeder Frage, in der Reihenfolge des Formulars ausgewertet.
|
||||||
|
|
||||||
|
Antworten auf ausgeblendete Fragen zählen in späteren Regeln als leer.
|
||||||
|
"""
|
||||||
|
files = set(with_files)
|
||||||
|
by_id = {q.id: q for q in questions}
|
||||||
|
in_group = groups.member_of(questions)
|
||||||
|
values: dict[int, Any] = {}
|
||||||
|
visible: dict[int, bool] = {}
|
||||||
|
page_ok = True
|
||||||
|
section_ok = True
|
||||||
|
for question in questions:
|
||||||
|
own = _holds(question.config.get("condition"), by_id, values)
|
||||||
|
if question.type == "page_break":
|
||||||
|
page_ok = own
|
||||||
|
section_ok = True
|
||||||
|
visible[question.id] = page_ok
|
||||||
|
elif question.type == "heading":
|
||||||
|
section_ok = own
|
||||||
|
visible[question.id] = page_ok and section_ok
|
||||||
|
else:
|
||||||
|
group_ok = visible.get(in_group[question.id], True) if question.id in in_group else True
|
||||||
|
visible[question.id] = page_ok and section_ok and group_ok and own
|
||||||
|
if question.type in KIND:
|
||||||
|
values[question.id] = (
|
||||||
|
_answer(question, fields, files) if visible[question.id] else None
|
||||||
|
)
|
||||||
|
return visible
|
||||||
|
|
||||||
|
|
||||||
|
def hidden_ids(
|
||||||
|
questions: Sequence[QuestionLike],
|
||||||
|
fields: Mapping[str, list[str]],
|
||||||
|
with_files: Iterable[int] = (),
|
||||||
|
) -> set[int]:
|
||||||
|
return {qid for qid, shown in visibility(questions, fields, with_files).items() if not shown}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Pflege im Designer
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def references(question: QuestionLike) -> list[int]:
|
||||||
|
condition = question.config.get("condition") or {}
|
||||||
|
return [int(r["q"]) for r in condition.get("rules") or [] if "q" in r]
|
||||||
|
|
||||||
|
|
||||||
|
def order_violations(questions: Sequence[QuestionLike]) -> list[int]:
|
||||||
|
"""Fragen, deren Regeln (in dieser Reihenfolge) nicht auf frühere verweisen."""
|
||||||
|
seen: set[int] = set()
|
||||||
|
broken: list[int] = []
|
||||||
|
for question in questions:
|
||||||
|
if any(ref not in seen for ref in references(question)):
|
||||||
|
broken.append(question.id)
|
||||||
|
seen.add(question.id)
|
||||||
|
return broken
|
||||||
|
|
||||||
|
|
||||||
|
def without_reference(config: dict[str, Any], removed_id: int) -> dict[str, Any] | None:
|
||||||
|
"""Neue Konfiguration ohne Regeln auf `removed_id`; None, wenn unverändert."""
|
||||||
|
condition = config.get("condition") or {}
|
||||||
|
rules = condition.get("rules") or []
|
||||||
|
kept = [r for r in rules if int(r.get("q", 0)) != removed_id]
|
||||||
|
if len(kept) == len(rules):
|
||||||
|
return None
|
||||||
|
result = dict(config)
|
||||||
|
if kept:
|
||||||
|
result["condition"] = {**condition, "rules": kept}
|
||||||
|
else:
|
||||||
|
result.pop("condition", None)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def remap(config: dict[str, Any], mapping: Mapping[int, int]) -> dict[str, Any]:
|
||||||
|
"""Regeln auf neue Fragen-IDs umstellen (beim Kopieren)."""
|
||||||
|
condition = config.get("condition")
|
||||||
|
if not condition:
|
||||||
|
return config
|
||||||
|
rules = [
|
||||||
|
{**r, "q": mapping[int(r["q"])]} for r in condition.get("rules") or []
|
||||||
|
if int(r.get("q", 0)) in mapping
|
||||||
|
]
|
||||||
|
result = dict(config)
|
||||||
|
if rules:
|
||||||
|
result["condition"] = {**condition, "rules": rules}
|
||||||
|
else:
|
||||||
|
result.pop("condition", None)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def layout(questions: Sequence[QuestionLike]) -> list[dict[str, Any]]:
|
||||||
|
"""Seiten > Abschnitte > Fragen, für die Ausfüll-Seite.
|
||||||
|
|
||||||
|
Gruppierte Fragen stehen nicht selbst in `items`, sondern zeigt ihre
|
||||||
|
Gruppe (siehe groups.resolve).
|
||||||
|
"""
|
||||||
|
grouped = set(groups.member_of(questions))
|
||||||
|
pages: list[dict[str, Any]] = [{"break": None, "sections": [{"heading": None, "items": []}]}]
|
||||||
|
for question in questions:
|
||||||
|
if question.id in grouped:
|
||||||
|
continue
|
||||||
|
if question.type == "page_break":
|
||||||
|
pages.append({"break": question, "sections": [{"heading": None, "items": []}]})
|
||||||
|
elif question.type == "heading":
|
||||||
|
pages[-1]["sections"].append({"heading": question, "items": []})
|
||||||
|
else:
|
||||||
|
pages[-1]["sections"][-1]["items"].append(question)
|
||||||
|
# Leere erste Seite (Formular beginnt mit einem Seitenumbruch) weglassen
|
||||||
|
first = pages[0]
|
||||||
|
if len(pages) > 1 and not any(s["items"] or s["heading"] for s in first["sections"]):
|
||||||
|
pages.pop(0)
|
||||||
|
return pages
|
||||||
|
|
||||||
|
|
||||||
|
def describe(question: QuestionLike, questions: Sequence[QuestionLike]) -> dict[str, Any] | None:
|
||||||
|
"""Lesbare Zusammenfassung für den Designer (Texte schon übersetzt)."""
|
||||||
|
from surveybox.i18n import gettext
|
||||||
|
|
||||||
|
condition = question.config.get("condition") or {}
|
||||||
|
rules = condition.get("rules") or []
|
||||||
|
if not rules:
|
||||||
|
return None
|
||||||
|
by_id = {q.id: q for q in questions}
|
||||||
|
lines: list[str] = []
|
||||||
|
broken = False
|
||||||
|
for item in rules:
|
||||||
|
ref = by_id.get(int(item.get("q", 0)))
|
||||||
|
if ref is None or ref.type not in KIND or ref.position >= question.position:
|
||||||
|
broken = True
|
||||||
|
lines.append(gettext(N_("Invalid rule (question missing or not earlier)")))
|
||||||
|
continue
|
||||||
|
value = str(item.get("value", ""))
|
||||||
|
labels = dict(options_for_rules(ref)) if KIND[ref.type] in ("choice", "multi") else {}
|
||||||
|
shown = labels.get(value, value)
|
||||||
|
if ref.type == "yes_no" and value in ("yes", "no") and not ref.config.get(f"label_{value}"):
|
||||||
|
shown = gettext("Yes") if value == "yes" else gettext("No")
|
||||||
|
if ref.type == "slots" and value == types.SINGLE_SLOT and ref.config.get("single"):
|
||||||
|
shown = gettext("signed up")
|
||||||
|
if shown == types.OTHER or (value == types.OTHER and shown == "Other"):
|
||||||
|
shown = gettext("Other")
|
||||||
|
text = f"„{ref.label}“ {gettext(OPS.get(item.get('op', ''), ''))}"
|
||||||
|
if item.get("op") not in NO_VALUE:
|
||||||
|
text += f" „{shown}“"
|
||||||
|
lines.append(text)
|
||||||
|
action = condition.get("action", "show")
|
||||||
|
match = condition.get("match", "all")
|
||||||
|
if action == "show":
|
||||||
|
head = gettext("Shown if all apply:") if match == "all" else gettext(
|
||||||
|
"Shown if at least one applies:"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
head = gettext("Hidden if all apply:") if match == "all" else gettext(
|
||||||
|
"Hidden if at least one applies:"
|
||||||
|
)
|
||||||
|
return {"head": head, "lines": lines, "broken": broken}
|
||||||
|
|
||||||
|
|
||||||
|
def dependents(questions: Sequence[QuestionLike]) -> dict[int, int]:
|
||||||
|
"""Wie viele Bedingungen auf jede Frage verweisen."""
|
||||||
|
counts: dict[int, int] = {}
|
||||||
|
for question in questions:
|
||||||
|
for ref in set(references(question)):
|
||||||
|
counts[ref] = counts.get(ref, 0) + 1
|
||||||
|
return counts
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Tägliche Zusammenfassung neuer und geänderter Antworten für Verwalter.
|
||||||
|
|
||||||
|
Eigentümer und Mitbearbeitende eines Formulars bekommen einmal am Tag eine
|
||||||
|
Mail mit der Zahl neuer und geänderter Antworten je Formular, ohne Inhalte.
|
||||||
|
Abschaltbar im Konto (Ereignis "digest").
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.mail import notify
|
||||||
|
from surveybox.models import Form, Response, UserAccount
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
|
||||||
|
def changes_since(db: Session, since: datetime) -> dict[int, tuple[int, int]]:
|
||||||
|
"""Formular-ID -> (neue, geänderte) Antworten seit `since`."""
|
||||||
|
new = dict(db.execute(
|
||||||
|
select(Response.form_id, func.count())
|
||||||
|
.where(Response.submitted_at >= since)
|
||||||
|
.group_by(Response.form_id)
|
||||||
|
).all())
|
||||||
|
changed = dict(db.execute(
|
||||||
|
select(Response.form_id, func.count())
|
||||||
|
.where(Response.updated_at >= since, Response.submitted_at < since)
|
||||||
|
.group_by(Response.form_id)
|
||||||
|
).all())
|
||||||
|
return {
|
||||||
|
int(fid): (int(new.get(fid, 0)), int(changed.get(fid, 0)))
|
||||||
|
for fid in set(new) | set(changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def run(db: Session, settings: Settings, since: datetime, day: str) -> int:
|
||||||
|
per_user: dict[int, list[tuple[Form, int, int]]] = defaultdict(list)
|
||||||
|
users: dict[int, UserAccount] = {}
|
||||||
|
for form_id, (new, changed) in sorted(changes_since(db, since).items()):
|
||||||
|
form = db.get(Form, form_id)
|
||||||
|
if form is None or form.is_template:
|
||||||
|
continue
|
||||||
|
for user in notify.managers(db, form):
|
||||||
|
users[user.id] = user
|
||||||
|
per_user[user.id].append((form, new, changed))
|
||||||
|
sent = 0
|
||||||
|
for user_id, entries in per_user.items():
|
||||||
|
items = [
|
||||||
|
{"title": form.title, "new": new, "changed": changed,
|
||||||
|
"link": notify.manage_link(settings, form, "/responses")}
|
||||||
|
for form, new, changed in sorted(entries, key=lambda e: e[0].title.lower())
|
||||||
|
]
|
||||||
|
if notify.send(
|
||||||
|
db, settings, users[user_id], kind="digest", event="digest",
|
||||||
|
context={"items": items}, dedupe_key=f"digest:{day}:{user_id}",
|
||||||
|
):
|
||||||
|
sent += 1
|
||||||
|
return sent
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Personen löschen: Benutzerkonten und Gast-Adressen mit allem, was daran hängt.
|
||||||
|
|
||||||
|
Antworten werden je nach Einstellung des Formulars anonymisiert oder gelöscht
|
||||||
|
(siehe retention). Läuft das Formular noch, werden die Plätze freigegeben und
|
||||||
|
Wartende rücken nach; bei beendeten Formularen bleiben die Plätze beim
|
||||||
|
Anonymisieren als anonyme Teilnahme gezählt.
|
||||||
|
|
||||||
|
Jede Löschung landet im Löschjournal (erasure_journal), damit sie nach dem
|
||||||
|
Zurückspielen einer älteren Sicherung erneut angewendet wird.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
from sqlalchemy import delete, select, update
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.accounts import audit
|
||||||
|
from surveybox.forms import booking, retention
|
||||||
|
from surveybox.forms.service import FillState, fill_state, participation_marker
|
||||||
|
from surveybox.models import (
|
||||||
|
Comment,
|
||||||
|
FollowupDelivery,
|
||||||
|
Form,
|
||||||
|
FormMember,
|
||||||
|
FormParticipation,
|
||||||
|
GuestContact,
|
||||||
|
MailMessage,
|
||||||
|
MemberRole,
|
||||||
|
Response,
|
||||||
|
UserAccount,
|
||||||
|
)
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
RUNNING = (FillState.OPEN, FillState.SCHEDULED)
|
||||||
|
|
||||||
|
|
||||||
|
class ErasureError(ValueError):
|
||||||
|
def __init__(self, code: str) -> None:
|
||||||
|
super().__init__(code)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Summary:
|
||||||
|
"""Was beim Löschen passiert; für den Dialog vorher und das Protokoll."""
|
||||||
|
|
||||||
|
anonymized: int = 0
|
||||||
|
deleted: int = 0
|
||||||
|
released: int = 0 # Antworten in laufenden Formularen, deren Plätze frei werden
|
||||||
|
forms: list[Form] = field(default_factory=list) # eigene Formulare (nur Konten)
|
||||||
|
comments: int = 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def responses(self) -> int:
|
||||||
|
return self.anonymized + self.deleted
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Antworten
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _by_form(db: Session, responses: list[Response]) -> dict[int, tuple[Form, list[Response]]]:
|
||||||
|
grouped: dict[int, list[Response]] = defaultdict(list)
|
||||||
|
for response in responses:
|
||||||
|
grouped[response.form_id].append(response)
|
||||||
|
result: dict[int, tuple[Form, list[Response]]] = {}
|
||||||
|
for form_id, rows in grouped.items():
|
||||||
|
form = db.get(Form, form_id)
|
||||||
|
if form is not None:
|
||||||
|
result[form_id] = (form, rows)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _deletes(form: Form) -> bool:
|
||||||
|
return form.deletion_mode == retention.MODE_DELETE
|
||||||
|
|
||||||
|
|
||||||
|
def preview_responses(db: Session, responses: list[Response], summary: Summary) -> None:
|
||||||
|
for form, rows in _by_form(db, responses).values():
|
||||||
|
if _deletes(form):
|
||||||
|
summary.deleted += len(rows)
|
||||||
|
else:
|
||||||
|
summary.anonymized += len(rows)
|
||||||
|
if fill_state(form) in RUNNING and any(q.type == "slots" for q in form.questions):
|
||||||
|
summary.released += len(rows)
|
||||||
|
|
||||||
|
|
||||||
|
def erase_responses(
|
||||||
|
db: Session, settings: Settings, responses: list[Response], now: datetime
|
||||||
|
) -> Summary:
|
||||||
|
"""Antworten einer Person: je Formular anonymisieren oder löschen."""
|
||||||
|
from surveybox.mail import notify
|
||||||
|
|
||||||
|
summary = Summary()
|
||||||
|
for form, rows in _by_form(db, responses).values():
|
||||||
|
if fill_state(form, now) in RUNNING:
|
||||||
|
# Plätze freigeben, Wartende rücken nach und werden benachrichtigt
|
||||||
|
events = booking.Events()
|
||||||
|
empty = {q.id: [] for q in form.questions if q.type == "slots"}
|
||||||
|
if empty:
|
||||||
|
for response in rows:
|
||||||
|
booking.book(db, form, response, empty, events)
|
||||||
|
summary.released += len(rows)
|
||||||
|
notify.safely(db, notify.booking_events, settings, form, events)
|
||||||
|
ids = [r.id for r in rows]
|
||||||
|
if _deletes(form):
|
||||||
|
summary.deleted += retention.delete_responses(db, ids)
|
||||||
|
else:
|
||||||
|
summary.anonymized += retention.anonymize_responses(db, form, ids, now)
|
||||||
|
return summary
|
||||||
|
|
||||||
|
|
||||||
|
def delete_response(db: Session, settings: Settings, response: Response) -> None:
|
||||||
|
"""Einzelne Antwort vollständig löschen (persönlicher Link); Plätze werden frei."""
|
||||||
|
from surveybox.mail import notify
|
||||||
|
|
||||||
|
form = db.get(Form, response.form_id)
|
||||||
|
if form is not None:
|
||||||
|
events = booking.Events()
|
||||||
|
empty = {q.id: [] for q in form.questions if q.type == "slots"}
|
||||||
|
if empty:
|
||||||
|
booking.book(db, form, response, empty, events)
|
||||||
|
notify.safely(db, notify.booking_events, settings, form, events)
|
||||||
|
db.execute(delete(FollowupDelivery).where(FollowupDelivery.response_id == response.id))
|
||||||
|
db.delete(response)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Benutzerkonten
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def owned_forms(db: Session, user: UserAccount) -> list[Form]:
|
||||||
|
return list(db.scalars(
|
||||||
|
select(Form).where(Form.owner_id == user.id).order_by(Form.title)
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
def _user_responses(db: Session, user: UserAccount) -> list[Response]:
|
||||||
|
return list(db.scalars(select(Response).where(Response.user_id == user.id)))
|
||||||
|
|
||||||
|
|
||||||
|
def preview_user(db: Session, user: UserAccount) -> Summary:
|
||||||
|
summary = Summary(forms=owned_forms(db, user))
|
||||||
|
preview_responses(db, _user_responses(db, user), summary)
|
||||||
|
summary.comments = len(db.scalars(select(Comment.id).where(Comment.user_id == user.id)).all())
|
||||||
|
return summary
|
||||||
|
|
||||||
|
|
||||||
|
def team_editors(db: Session, form: Form, exclude: UserAccount) -> list[UserAccount]:
|
||||||
|
"""Wer ein Formular übernehmen kann, wenn sein Eigentümer sich selbst löscht."""
|
||||||
|
return list(db.scalars(
|
||||||
|
select(UserAccount)
|
||||||
|
.join(FormMember, FormMember.user_id == UserAccount.id)
|
||||||
|
.where(FormMember.form_id == form.id, FormMember.role == MemberRole.EDITOR,
|
||||||
|
UserAccount.id != exclude.id, UserAccount.is_active.is_(True))
|
||||||
|
.order_by(UserAccount.display_name)
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
def erase_user(
|
||||||
|
db: Session,
|
||||||
|
settings: Settings,
|
||||||
|
user: UserAccount,
|
||||||
|
form_targets: dict[int, UserAccount | None],
|
||||||
|
*,
|
||||||
|
actor_id: int | None,
|
||||||
|
now: datetime | None = None,
|
||||||
|
allow_last_admin: bool = False,
|
||||||
|
) -> Summary:
|
||||||
|
"""Konto löschen. form_targets: je eigenem Formular der neue Eigentümer oder None
|
||||||
|
(= Formular löschen). Fehlt ein Formular darin, wird es gelöscht."""
|
||||||
|
from surveybox.accounts.service import count_active_admins
|
||||||
|
|
||||||
|
now = now or datetime.now(UTC)
|
||||||
|
if (not allow_last_admin and user.is_admin and user.is_active
|
||||||
|
and count_active_admins(db) <= 1):
|
||||||
|
raise ErasureError("last_admin")
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
summary = erase_responses(db, settings, _user_responses(db, user), now)
|
||||||
|
# Merker gegen doppelte Teilnahme in anonymen Formularen
|
||||||
|
for form in db.scalars(select(Form).where(Form.anonymous.is_(True))):
|
||||||
|
db.execute(delete(FormParticipation).where(
|
||||||
|
FormParticipation.form_id == form.id,
|
||||||
|
FormParticipation.marker == participation_marker(secret, form, user)))
|
||||||
|
transferred = removed = 0
|
||||||
|
for form in owned_forms(db, user):
|
||||||
|
target = form_targets.get(form.id)
|
||||||
|
if target is not None and target.id != user.id:
|
||||||
|
form.owner_id = target.id
|
||||||
|
db.execute(delete(FormMember).where(
|
||||||
|
FormMember.form_id == form.id, FormMember.user_id == target.id))
|
||||||
|
transferred += 1
|
||||||
|
else:
|
||||||
|
db.delete(form)
|
||||||
|
removed += 1
|
||||||
|
summary.comments = int(db.execute(
|
||||||
|
update(Comment).where(Comment.user_id == user.id).values(author_deleted=True)
|
||||||
|
).rowcount or 0) # type: ignore[attr-defined]
|
||||||
|
db.execute(delete(FollowupDelivery).where(
|
||||||
|
FollowupDelivery.recipient == f"u:{user.public_id}"))
|
||||||
|
audit.record(db, "account.deleted", actor_id=actor_id, target_type="user",
|
||||||
|
target_id=user.id, details={
|
||||||
|
"responses": summary.responses, "forms_transferred": transferred,
|
||||||
|
"forms_deleted": removed})
|
||||||
|
# Konto, Passkeys, Sitzungen, Einstellungen und Mailprotokoll hängen per CASCADE daran
|
||||||
|
db.delete(user)
|
||||||
|
db.flush()
|
||||||
|
return summary
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Gast-Adressen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _guest_responses(db: Session, contact: GuestContact) -> list[Response]:
|
||||||
|
return list(db.scalars(select(Response).where(Response.guest_contact_id == contact.id)))
|
||||||
|
|
||||||
|
|
||||||
|
def preview_guest(db: Session, contact: GuestContact) -> Summary:
|
||||||
|
summary = Summary()
|
||||||
|
preview_responses(db, _guest_responses(db, contact), summary)
|
||||||
|
return summary
|
||||||
|
|
||||||
|
|
||||||
|
def erase_guest(
|
||||||
|
db: Session, settings: Settings, contact: GuestContact, now: datetime | None = None
|
||||||
|
) -> Summary:
|
||||||
|
"""Alles, was an einer Gast-Adresse hängt: Antworten, Versandstand, Mailprotokoll."""
|
||||||
|
now = now or datetime.now(UTC)
|
||||||
|
summary = erase_responses(db, settings, _guest_responses(db, contact), now)
|
||||||
|
db.execute(delete(FollowupDelivery).where(
|
||||||
|
FollowupDelivery.recipient == f"g:{contact.public_id}"))
|
||||||
|
db.execute(delete(MailMessage).where(
|
||||||
|
MailMessage.recipient == contact.email, MailMessage.user_id.is_(None)))
|
||||||
|
audit.record(db, "guest.deleted", target_type="guest", target_id=contact.id,
|
||||||
|
details={"responses": summary.responses})
|
||||||
|
db.delete(contact)
|
||||||
|
db.flush()
|
||||||
|
return summary
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Auswertung: Filter nach Zeitraum und Antwort, gefilterte Antworten, Teilnehmerlisten.
|
||||||
|
|
||||||
|
Der Filter steht in der Adresse (?from=…&to=…&answer=<Frage>:<Wert>), damit eine
|
||||||
|
gefilterte Ansicht verlinkt werden kann und die Exporte denselben Filter nutzen.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Mapping, Sequence
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import date, datetime, time, timedelta
|
||||||
|
from typing import Any
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.forms import types
|
||||||
|
from surveybox.i18n import gettext
|
||||||
|
from surveybox.models import Answer, Booking, BookingStatus, Form, Response, UserAccount
|
||||||
|
|
||||||
|
# Fragen, nach deren Antwort sich filtern lässt
|
||||||
|
FILTERABLE = ("yes_no", "single_choice", "multiple_choice", "slots", "rating")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Filter:
|
||||||
|
since: date | None = None
|
||||||
|
until: date | None = None
|
||||||
|
question_id: int | None = None
|
||||||
|
value: str = ""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def active(self) -> bool:
|
||||||
|
return bool(self.since or self.until or self.question_id)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def answer_key(self) -> str:
|
||||||
|
return f"{self.question_id}:{self.value}" if self.question_id else ""
|
||||||
|
|
||||||
|
def query(self) -> dict[str, str]:
|
||||||
|
"""Für Links und versteckte Felder der Exporte."""
|
||||||
|
params: dict[str, str] = {}
|
||||||
|
if self.since:
|
||||||
|
params["from"] = self.since.isoformat()
|
||||||
|
if self.until:
|
||||||
|
params["to"] = self.until.isoformat()
|
||||||
|
if self.question_id:
|
||||||
|
params["answer"] = self.answer_key
|
||||||
|
return params
|
||||||
|
|
||||||
|
|
||||||
|
def _day(raw: str | None) -> date | None:
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(raw) if raw else None
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_filter(form: Form, params: Mapping[str, str]) -> Filter:
|
||||||
|
since, until = _day(params.get("from")), _day(params.get("to"))
|
||||||
|
if since and until and since > until:
|
||||||
|
since, until = until, since
|
||||||
|
question_id, value = None, ""
|
||||||
|
raw = params.get("answer") or ""
|
||||||
|
if ":" in raw:
|
||||||
|
qid_raw, _, value = raw.partition(":")
|
||||||
|
if qid_raw.isdigit() and any(key == raw for key, _ in choices(form)):
|
||||||
|
question_id = int(qid_raw)
|
||||||
|
return Filter(since, until, question_id, value if question_id else "")
|
||||||
|
|
||||||
|
|
||||||
|
def choices(form: Form) -> list[tuple[str, str]]:
|
||||||
|
"""Mögliche Antwortfilter als (Schlüssel, Anzeige) für eine Auswahlliste."""
|
||||||
|
result: list[tuple[str, str]] = []
|
||||||
|
for q in form.questions:
|
||||||
|
if q.type not in FILTERABLE:
|
||||||
|
continue
|
||||||
|
cfg = q.config
|
||||||
|
if q.type == "yes_no":
|
||||||
|
values = [("yes", cfg.get("label_yes") or gettext("Yes")),
|
||||||
|
("no", cfg.get("label_no") or gettext("No"))]
|
||||||
|
elif q.type == "rating":
|
||||||
|
values = [(str(i), str(i)) for i in range(1, int(cfg.get("scale_max") or 5) + 1)]
|
||||||
|
elif q.type == "slots" and cfg.get("single"):
|
||||||
|
values = [("single", gettext("signed up"))]
|
||||||
|
else:
|
||||||
|
values = [(o["id"], types.option_text(o)) for o in types.options_of(q)]
|
||||||
|
result.extend((f"{q.id}:{key}", f"{q.label}: {text}") for key, text in values)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _matches(question: Any, stored: Mapping[str, Any], value: str) -> bool:
|
||||||
|
t = question.type
|
||||||
|
if t == "yes_no":
|
||||||
|
return stored.get("value_bool") is (value == "yes")
|
||||||
|
if t == "rating":
|
||||||
|
number = stored.get("value_number")
|
||||||
|
return number is not None and str(int(number)) == value
|
||||||
|
if t == "single_choice":
|
||||||
|
return stored.get("value_text") == value
|
||||||
|
data = stored.get("value_json") or {}
|
||||||
|
return value in (data.get("selected") or [])
|
||||||
|
|
||||||
|
|
||||||
|
def responses(db: Session, form: Form, flt: Filter, tz: ZoneInfo) -> list[Response]:
|
||||||
|
"""Antworten des Formulars, älteste zuerst, nach Filter."""
|
||||||
|
stmt = select(Response).where(Response.form_id == form.id)
|
||||||
|
if flt.since:
|
||||||
|
stmt = stmt.where(Response.submitted_at >= datetime.combine(flt.since, time(), tz))
|
||||||
|
if flt.until:
|
||||||
|
end = datetime.combine(flt.until + timedelta(days=1), time(), tz)
|
||||||
|
stmt = stmt.where(Response.submitted_at < end)
|
||||||
|
rows = list(db.scalars(stmt.order_by(Response.submitted_at, Response.id)))
|
||||||
|
if not flt.question_id:
|
||||||
|
return rows
|
||||||
|
question = next((q for q in form.questions if q.id == flt.question_id), None)
|
||||||
|
if question is None:
|
||||||
|
return rows
|
||||||
|
answers = {
|
||||||
|
a.response_id: a for a in db.scalars(select(Answer).where(
|
||||||
|
Answer.question_id == question.id, Answer.response_id.in_([r.id for r in rows])))
|
||||||
|
}
|
||||||
|
from surveybox.forms.service import stored_of
|
||||||
|
|
||||||
|
return [r for r in rows if r.id in answers
|
||||||
|
and _matches(question, stored_of(answers[r.id]), flt.value)]
|
||||||
|
|
||||||
|
|
||||||
|
def participant_names(db: Session, rows: Sequence[Response]) -> dict[int, str]:
|
||||||
|
"""Kontoname je Antwort (Gäste: kein Eintrag). Gast-Adressen bleiben verborgen."""
|
||||||
|
user_ids = {r.user_id for r in rows if r.user_id is not None}
|
||||||
|
if not user_ids:
|
||||||
|
return {}
|
||||||
|
names = dict(db.execute(
|
||||||
|
select(UserAccount.id, UserAccount.display_name).where(UserAccount.id.in_(user_ids))
|
||||||
|
).tuples().all())
|
||||||
|
return {r.id: names[r.user_id] for r in rows if r.user_id in names}
|
||||||
|
|
||||||
|
|
||||||
|
def pending_invited(db: Session, form: Form) -> list[UserAccount]:
|
||||||
|
"""Eingeladene (Zugriff "Ausgewählte Benutzer und Gruppen") ohne Antwort, nach Name.
|
||||||
|
|
||||||
|
Bei anonymen Formularen nie: wer teilgenommen hat, bleibt dort offen.
|
||||||
|
"""
|
||||||
|
from surveybox.forms import reminders
|
||||||
|
from surveybox.models import FormAccess
|
||||||
|
|
||||||
|
if form.anonymous or form.access != FormAccess.RESTRICTED:
|
||||||
|
return []
|
||||||
|
answered = set(db.scalars(select(Response.user_id).where(
|
||||||
|
Response.form_id == form.id, Response.user_id.is_not(None))))
|
||||||
|
people = [u for u in reminders.invited(db, form) if u.id not in answered]
|
||||||
|
return sorted(people, key=lambda u: u.display_name.casefold())
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SlotList:
|
||||||
|
"""Teilnehmerliste einer Option (für Verwalter, immer mit vollem Namen)."""
|
||||||
|
|
||||||
|
text: str
|
||||||
|
capacity: int | None
|
||||||
|
confirmed: list[str]
|
||||||
|
waiting: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
def slot_lists(db: Session, form: Form, rows: Sequence[Response]) -> dict[int, list[SlotList]]:
|
||||||
|
"""Je Teilnahme-Feld: Optionen mit Namen der Eingetragenen und der Warteliste."""
|
||||||
|
slots = [q for q in form.questions if q.type == "slots"]
|
||||||
|
if not slots or not rows:
|
||||||
|
return {}
|
||||||
|
ids = [r.id for r in rows]
|
||||||
|
label = display_names(db, form, rows)
|
||||||
|
bookings = db.execute(
|
||||||
|
select(Booking.question_id, Booking.option_id, Booking.status, Booking.response_id)
|
||||||
|
.where(Booking.form_id == form.id, Booking.response_id.in_(ids))
|
||||||
|
.order_by(Booking.created_at, Booking.id)
|
||||||
|
).all()
|
||||||
|
result: dict[int, list[SlotList]] = {}
|
||||||
|
for q in slots:
|
||||||
|
lists = {
|
||||||
|
o["id"]: SlotList(
|
||||||
|
gettext("signed up") if q.config.get("single") else types.option_text(o),
|
||||||
|
int(o["capacity"]) if o.get("capacity") else None, [], [])
|
||||||
|
for o in types.options_of(q)
|
||||||
|
}
|
||||||
|
for b in bookings:
|
||||||
|
if b.question_id != q.id or b.option_id not in lists:
|
||||||
|
continue
|
||||||
|
target = lists[b.option_id]
|
||||||
|
(target.waiting if b.status == BookingStatus.WAITING else target.confirmed).append(
|
||||||
|
label.get(b.response_id, gettext("Guest")))
|
||||||
|
result[q.id] = list(lists.values())
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def display_names(db: Session, form: Form, rows: Sequence[Response]) -> dict[int, str]:
|
||||||
|
"""Name je Antwort für Listen: Teilnehmer-Name, sonst Kontoname."""
|
||||||
|
if form.anonymous:
|
||||||
|
return {}
|
||||||
|
names = participant_names(db, rows)
|
||||||
|
name_q = next((q for q in form.questions if q.type == "participant_name"), None)
|
||||||
|
if name_q is not None:
|
||||||
|
for answer in db.scalars(select(Answer).where(
|
||||||
|
Answer.question_id == name_q.id,
|
||||||
|
Answer.response_id.in_([r.id for r in rows]))):
|
||||||
|
parts = types.name_parts({"value_json": answer.value_json})
|
||||||
|
full = f"{parts['first']} {parts['last']}".strip()
|
||||||
|
if full:
|
||||||
|
names[answer.response_id] = full
|
||||||
|
return names
|
||||||
|
|
||||||
|
|
||||||
|
def pdf_sections(db: Session, form: Form, rows: Sequence[Response]) -> list[Any]:
|
||||||
|
"""Abschnitte für die PDF-Teilnehmerlisten: je Teilnahme-Feld seine Einträge.
|
||||||
|
Ohne Teilnahme-Felder keine (dafür gibt es den Export der Antworten)."""
|
||||||
|
from surveybox.forms.pdf_export import Entry, Section
|
||||||
|
|
||||||
|
lists = slot_lists(db, form, rows)
|
||||||
|
sections = []
|
||||||
|
for q in (q for q in form.questions if q.type == "slots"):
|
||||||
|
found = lists.get(q.id) or [
|
||||||
|
SlotList("", int(o["capacity"]) if o.get("capacity") else None, [], [])
|
||||||
|
for o in types.options_of(q)
|
||||||
|
]
|
||||||
|
if q.config.get("single"):
|
||||||
|
entries = [Entry(gettext("Participants"), s.capacity, s.confirmed, s.waiting)
|
||||||
|
for s in found]
|
||||||
|
else:
|
||||||
|
entries = [
|
||||||
|
Entry(types.option_text(o), s.capacity, s.confirmed, s.waiting)
|
||||||
|
for o, s in zip(types.options_of(q), found, strict=False)
|
||||||
|
]
|
||||||
|
sections.append(Section(q.label, entries))
|
||||||
|
return sections
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Export der Antworten als CSV oder XLSX.
|
||||||
|
|
||||||
|
Eine Zeile je Antwort, eine Spalte je Frage (Teilnehmer-Name: Vorname, Nachname,
|
||||||
|
E-Mail; Abstimmung: eine Spalte je Option). Personenbezogene Fragen und der
|
||||||
|
Kontoname lassen sich weglassen. Adressen von Gästen, die das Formular verborgen
|
||||||
|
hält, erscheinen nie. Der Aufrufer protokolliert jeden Export.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.forms import evaluation, ods, types, xlsx
|
||||||
|
from surveybox.forms.service import stored_of
|
||||||
|
from surveybox.i18n import gettext
|
||||||
|
from surveybox.models import (
|
||||||
|
Answer,
|
||||||
|
Booking,
|
||||||
|
BookingStatus,
|
||||||
|
Form,
|
||||||
|
FormAccess,
|
||||||
|
Response,
|
||||||
|
UserAccount,
|
||||||
|
)
|
||||||
|
|
||||||
|
Cell = str | int | Decimal | None
|
||||||
|
CSV_DELIMITER = ";" # Excel in deutscher Einstellung erwartet Semikolon
|
||||||
|
FORMULA_START = ("=", "+", "-", "@", "\t", "\r")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Table:
|
||||||
|
headers: list[str]
|
||||||
|
rows: list[list[Cell]] = field(default_factory=list)
|
||||||
|
# Je Zeile die Kennung der Antwort; None bei Eingeladenen ohne Rückmeldung
|
||||||
|
row_ids: list[Any] = field(default_factory=list)
|
||||||
|
status_column: bool = False # Spalte "Rückmeldung" (Formulare mit Einladung)
|
||||||
|
|
||||||
|
|
||||||
|
def _local(value: datetime | None, tz: ZoneInfo) -> str:
|
||||||
|
return value.astimezone(tz).strftime("%d.%m.%Y %H:%M") if value else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _columns(form: Form, include_personal: bool) -> list[tuple[Any, str, str]]:
|
||||||
|
"""(Frage, Teil, Überschrift) je Spalte."""
|
||||||
|
columns: list[tuple[Any, str, str]] = []
|
||||||
|
for q in form.questions:
|
||||||
|
qtype = types.TYPES.get(q.type)
|
||||||
|
if qtype is None or not qtype.is_input or (q.personal and not include_personal):
|
||||||
|
continue
|
||||||
|
if q.type == "participant_name":
|
||||||
|
columns.append((q, "first", f"{q.label}: {gettext('First name')}"))
|
||||||
|
columns.append((q, "last", f"{q.label}: {gettext('Last name')}"))
|
||||||
|
if (q.config.get("email") or "optional") != "off":
|
||||||
|
columns.append((q, "email", f"{q.label}: {gettext('Email address')}"))
|
||||||
|
elif q.type == "poll":
|
||||||
|
for option in types.options_of(q):
|
||||||
|
columns.append((q, option["id"], f"{q.label}: {types.option_text(option)}"))
|
||||||
|
else:
|
||||||
|
columns.append((q, "", q.label))
|
||||||
|
return columns
|
||||||
|
|
||||||
|
|
||||||
|
def _value(q: Any, part: str, stored: dict[str, Any], status: dict[str, str],
|
||||||
|
tz: ZoneInfo) -> Cell:
|
||||||
|
if not stored:
|
||||||
|
return None
|
||||||
|
t = q.type
|
||||||
|
if t == "participant_name":
|
||||||
|
return types.name_parts(stored)[part] or None
|
||||||
|
if t == "poll":
|
||||||
|
vote = ((stored.get("value_json") or {}).get("votes") or {}).get(part)
|
||||||
|
names = {"yes": gettext("Yes"), "maybe": gettext("Maybe"), "no": gettext("No")}
|
||||||
|
return names.get(vote) if vote else None
|
||||||
|
if t in ("number", "rating"):
|
||||||
|
value = stored.get("value_number")
|
||||||
|
return Decimal(value) if value is not None else None
|
||||||
|
if t == "slots":
|
||||||
|
selected = (stored.get("value_json") or {}).get("selected") or []
|
||||||
|
texts = []
|
||||||
|
for oid in selected:
|
||||||
|
text = (gettext("signed up") if q.config.get("single")
|
||||||
|
else types.option_label(q, oid) or gettext("(deleted option)"))
|
||||||
|
if status.get(oid) == BookingStatus.WAITING:
|
||||||
|
text += f" ({gettext('waiting list')})"
|
||||||
|
texts.append(text)
|
||||||
|
return ", ".join(texts) or None
|
||||||
|
if t == "file_upload":
|
||||||
|
files = (stored.get("value_json") or {}).get("files") or []
|
||||||
|
return ", ".join(str(f.get("name") or "") for f in files) or None
|
||||||
|
return types.display_answer(q, stored, tz) or None
|
||||||
|
|
||||||
|
|
||||||
|
def build(db: Session, form: Form, responses: Sequence[Response], tz: ZoneInfo,
|
||||||
|
include_personal: bool, pending: Sequence[UserAccount] = ()) -> Table:
|
||||||
|
"""Tabelle der Antworten. `pending`: Eingeladene ohne Rückmeldung (am Ende)."""
|
||||||
|
columns = _columns(form, include_personal)
|
||||||
|
with_person = include_personal and not form.anonymous
|
||||||
|
invitations = with_person and form.access == FormAccess.RESTRICTED
|
||||||
|
headers = [gettext("No."), gettext("Submitted"), gettext("Changed")]
|
||||||
|
if with_person:
|
||||||
|
headers.append(gettext("Participant"))
|
||||||
|
if invitations:
|
||||||
|
headers.append(gettext("Response"))
|
||||||
|
headers += [title for _, _, title in columns]
|
||||||
|
table = Table(headers, status_column=invitations)
|
||||||
|
ids = [r.id for r in responses]
|
||||||
|
answers: dict[tuple[int, int], dict[str, Any]] = {}
|
||||||
|
statuses: dict[tuple[int, int], dict[str, str]] = {}
|
||||||
|
if ids:
|
||||||
|
for a in db.scalars(select(Answer).where(Answer.response_id.in_(ids))):
|
||||||
|
answers[(a.response_id, a.question_id)] = stored_of(a)
|
||||||
|
for b in db.scalars(select(Booking).where(Booking.response_id.in_(ids))):
|
||||||
|
statuses.setdefault((b.response_id, b.question_id), {})[b.option_id] = b.status
|
||||||
|
names = evaluation.participant_names(db, responses) if with_person else {}
|
||||||
|
for number, response in enumerate(responses, 1):
|
||||||
|
row: list[Cell] = [number, _local(response.submitted_at, tz),
|
||||||
|
_local(response.updated_at, tz)]
|
||||||
|
if with_person:
|
||||||
|
row.append(names.get(response.id) or (
|
||||||
|
gettext("anonymized") if response.anonymized_at else gettext("Guest")))
|
||||||
|
if invitations:
|
||||||
|
row.append(gettext("received"))
|
||||||
|
for q, part, _ in columns:
|
||||||
|
row.append(_value(q, part, answers.get((response.id, q.id), {}),
|
||||||
|
statuses.get((response.id, q.id), {}), tz))
|
||||||
|
table.rows.append(row)
|
||||||
|
table.row_ids.append(response.public_id)
|
||||||
|
if invitations:
|
||||||
|
for user in pending:
|
||||||
|
table.rows.append([None, None, None, user.display_name, gettext("no response yet")]
|
||||||
|
+ [None] * len(columns))
|
||||||
|
table.row_ids.append(None)
|
||||||
|
return table
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Dateien
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_csv(value: Cell) -> str:
|
||||||
|
"""Zellen, die eine Tabellenkalkulation als Formel lesen würde, entschärfen."""
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
text = str(value)
|
||||||
|
if isinstance(value, str) and text.startswith(FORMULA_START):
|
||||||
|
return "'" + text
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def to_csv(table: Table) -> bytes:
|
||||||
|
out = io.StringIO()
|
||||||
|
writer = csv.writer(out, delimiter=CSV_DELIMITER, lineterminator="\r\n")
|
||||||
|
writer.writerow([_safe_csv(h) for h in table.headers])
|
||||||
|
for row in table.rows:
|
||||||
|
writer.writerow([_safe_csv(v) for v in row])
|
||||||
|
# BOM, damit Excel die Datei als UTF-8 erkennt
|
||||||
|
return ("" + out.getvalue()).encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _width(values: list[Cell]) -> float:
|
||||||
|
longest = max((len(str(v)) for v in values if v is not None), default=8)
|
||||||
|
return float(min(max(longest, 8), 60)) + 2
|
||||||
|
|
||||||
|
|
||||||
|
def logo_image(data_dir: Path) -> xlsx.Image:
|
||||||
|
"""Eigenes Logo der Instanz, sonst das von Surveybox; 48 Pixel hoch."""
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from surveybox import branding
|
||||||
|
from surveybox.web.templating import STATIC_DIR
|
||||||
|
|
||||||
|
path = branding.file_path(data_dir, "logo.png") if branding.current(data_dir).custom else None
|
||||||
|
path = path or Path(STATIC_DIR) / "img" / "logo-128.png"
|
||||||
|
data = path.read_bytes()
|
||||||
|
with Image.open(io.BytesIO(data)) as img:
|
||||||
|
width, height = img.size
|
||||||
|
scale = 48 / height if height else 1
|
||||||
|
return xlsx.Image(data, max(int(width * scale), 1), 48)
|
||||||
|
|
||||||
|
|
||||||
|
LOGO_ROWS = 3 # Zeilen über dem Titel, die das Logo (48 Pixel hoch) einnimmt
|
||||||
|
|
||||||
|
|
||||||
|
def to_xlsx(table: Table, form: Form, info: list[tuple[str, str]], logo: xlsx.Image) -> bytes:
|
||||||
|
"""Ein Blatt: Logo, Titel und Angaben zum Export oben, darunter die Tabelle.
|
||||||
|
|
||||||
|
Für den Druck: Querformat, alle Spalten auf einer Seitenbreite, Kopfzeile der
|
||||||
|
Tabelle auf jeder Seite, unten mittig "Seite X von Y".
|
||||||
|
"""
|
||||||
|
columns = list(zip(*([table.headers, *table.rows]), strict=False)) if table.rows else [
|
||||||
|
(h,) for h in table.headers]
|
||||||
|
top = _top_rows(form, info)
|
||||||
|
header_index = len(top)
|
||||||
|
footer = "&C" + gettext("Page %(page)s of %(pages)s") % {"page": "&P", "pages": "&N"}
|
||||||
|
sheet = xlsx.Sheet(
|
||||||
|
gettext("Answers"), [*top, table.headers, *table.rows], header=True,
|
||||||
|
header_row=header_index, title_rows={LOGO_ROWS}, freeze=False,
|
||||||
|
widths=[_width(list(col)) for col in columns], image=logo,
|
||||||
|
page=xlsx.PageSetup(landscape=True, margins=(1.0, 1.0, 2.0, 1.2), fit_width=True,
|
||||||
|
footer=footer),
|
||||||
|
)
|
||||||
|
return xlsx.workbook([sheet])
|
||||||
|
|
||||||
|
|
||||||
|
def _footer_parts() -> tuple[str, str]:
|
||||||
|
""""Seite X von Y" zerlegt: Text vor der Seitenzahl, Text zwischen beiden Zahlen."""
|
||||||
|
text = gettext("Page %(page)s of %(pages)s")
|
||||||
|
before, _, rest = text.partition("%(page)s")
|
||||||
|
between, _, _ = rest.partition("%(pages)s")
|
||||||
|
return before, between
|
||||||
|
|
||||||
|
|
||||||
|
def _top_rows(form: Form, info: list[tuple[str, str]]) -> list[list[Cell]]:
|
||||||
|
top: list[list[Cell]] = [[] for _ in range(LOGO_ROWS)]
|
||||||
|
top.append([form.title])
|
||||||
|
top += [[f"{label}: {value}"] for label, value in info if label != gettext("Form")]
|
||||||
|
top.append([])
|
||||||
|
return top
|
||||||
|
|
||||||
|
|
||||||
|
def to_ods(table: Table, form: Form, info: list[tuple[str, str]], logo: xlsx.Image) -> bytes:
|
||||||
|
"""Wie to_xlsx, als OpenDocument-Tabelle (LibreOffice, OpenOffice)."""
|
||||||
|
columns = list(zip(*([table.headers, *table.rows]), strict=False)) if table.rows else [
|
||||||
|
(h,) for h in table.headers]
|
||||||
|
px_to_cm = 2.54 / 96
|
||||||
|
sheet = ods.Sheet(
|
||||||
|
gettext("Answers"), _top_rows(form, info), list(table.headers),
|
||||||
|
[list(r) for r in table.rows], widths=ods.widths_for(columns),
|
||||||
|
title_rows={LOGO_ROWS},
|
||||||
|
image=ods.Image(logo.png, logo.width * px_to_cm, logo.height * px_to_cm),
|
||||||
|
page=ods.PageSetup(landscape=True, margins=(1.0, 1.0, 2.0, 1.2), fit_width=True,
|
||||||
|
footer=_footer_parts()),
|
||||||
|
)
|
||||||
|
return ods.document(sheet, form.title)
|
||||||
|
|
||||||
|
|
||||||
|
def to_pdf(table: Table, form: Form, info: list[tuple[str, str]], logo: xlsx.Image) -> bytes:
|
||||||
|
"""Dieselbe Tabelle als PDF, A4 quer, alle Spalten auf einer Seitenbreite."""
|
||||||
|
from surveybox.forms import pdf_export
|
||||||
|
|
||||||
|
return pdf_export.answers_table(
|
||||||
|
form.title, [str(h) for h in table.headers], table.rows,
|
||||||
|
[(label, value) for label, value in info if label != gettext("Form")], logo.png)
|
||||||
|
|
||||||
|
|
||||||
|
def info_rows(form: Form, flt: evaluation.Filter, count: int, include_personal: bool,
|
||||||
|
tz: ZoneInfo) -> list[tuple[str, str]]:
|
||||||
|
labels = dict(evaluation.choices(form))
|
||||||
|
rows = [
|
||||||
|
(gettext("Form"), form.title),
|
||||||
|
(gettext("Exported"), datetime.now(UTC).astimezone(tz).strftime("%d.%m.%Y %H:%M")),
|
||||||
|
(gettext("Answers"), str(count)),
|
||||||
|
(gettext("Period"), " \u2013 ".join([
|
||||||
|
flt.since.strftime("%d.%m.%Y") if flt.since else "…",
|
||||||
|
flt.until.strftime("%d.%m.%Y") if flt.until else "…",
|
||||||
|
]) if flt.since or flt.until else gettext("all")),
|
||||||
|
(gettext("Answer filter"), labels.get(flt.answer_key, "") or gettext("none")),
|
||||||
|
(gettext("Personal data"), gettext("included") if include_personal
|
||||||
|
else gettext("left out")),
|
||||||
|
]
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def filename(form: Form, extension: str, today: datetime | None = None) -> str:
|
||||||
|
"""Dateiname aus dem Titel, nur mit unbedenklichen Zeichen."""
|
||||||
|
stem = "".join(ch if ch.isascii() and ch.isalnum() else "-" for ch in form.title.lower())
|
||||||
|
stem = "-".join(part for part in stem.split("-") if part)[:60] or "formular"
|
||||||
|
day = (today or datetime.now(UTC)).date().isoformat()
|
||||||
|
return f"{stem}-{day}.{extension}"
|
||||||
@@ -0,0 +1,637 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Folge-Mails mit Dokumenten.
|
||||||
|
|
||||||
|
Eine Folge-Mail gehört zu einem Formular und geht an alle Teilnehmenden mit
|
||||||
|
bekannter Adresse: Konto oder bestätigte Gast-Adresse, wahlweise nur an
|
||||||
|
Personen mit bestätigtem Platz. Zeitpunkt: direkt nach der Teilnahme, beim
|
||||||
|
Schließen des Formulars, zu einem festen Zeitpunkt oder nur von Hand. Jede
|
||||||
|
Person erhält jede Folge-Mail höchstens einmal (Tabelle followup_delivery),
|
||||||
|
auch wenn sie ihre Antwort ändert.
|
||||||
|
|
||||||
|
Die Mail enthält Links statt Anhängen. Jeder Link ist persönlich, signiert und
|
||||||
|
läuft ab (Standard 90 Tage). Surveybox zählt nur, wie oft ein Dokument
|
||||||
|
heruntergeladen wurde, ohne Bezug zur Person. Bei anonymen Formularen gibt es
|
||||||
|
keine Folge-Mails, weil keine Adresse zu einer Antwort gespeichert ist.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, date, datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.forms.service import FillState, fill_state
|
||||||
|
from surveybox.mail import notify
|
||||||
|
from surveybox.media import service as media_service
|
||||||
|
from surveybox.media import sniff
|
||||||
|
from surveybox.models import (
|
||||||
|
Booking,
|
||||||
|
BookingStatus,
|
||||||
|
Followup,
|
||||||
|
FollowupDelivery,
|
||||||
|
FollowupDocument,
|
||||||
|
FollowupTrigger,
|
||||||
|
Form,
|
||||||
|
FormStatus,
|
||||||
|
GuestContact,
|
||||||
|
MailMessage,
|
||||||
|
MediaFile,
|
||||||
|
MediaKind,
|
||||||
|
Response,
|
||||||
|
)
|
||||||
|
from surveybox.security.tokens import constant_time_equal, derive_key, keyed_hash
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
MAX_SUBJECT = 200
|
||||||
|
MAX_BODY = 20000
|
||||||
|
MAX_TITLE = 200
|
||||||
|
MAX_DOCUMENTS = 20
|
||||||
|
MAX_FOLLOWUPS = 20
|
||||||
|
DOCUMENT_KEYS = (
|
||||||
|
sniff.UPLOAD_GROUPS["pdf"]
|
||||||
|
| sniff.UPLOAD_GROUPS["office"]
|
||||||
|
| sniff.UPLOAD_GROUPS["images"]
|
||||||
|
| sniff.UPLOAD_GROUPS["zip"]
|
||||||
|
)
|
||||||
|
TRIGGERS = tuple(t.value for t in FollowupTrigger)
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class FollowupError(ValueError):
|
||||||
|
def __init__(self, code: str) -> None:
|
||||||
|
super().__init__(code)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Pflege
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def list_for(db: Session, form: Form) -> list[Followup]:
|
||||||
|
return list(db.scalars(
|
||||||
|
select(Followup).where(Followup.form_id == form.id).order_by(Followup.id)
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
def find(db: Session, form: Form, public_id: str) -> Followup | None:
|
||||||
|
try:
|
||||||
|
pid = uuid.UUID(public_id)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return db.scalar(select(Followup).where(Followup.public_id == pid,
|
||||||
|
Followup.form_id == form.id))
|
||||||
|
|
||||||
|
|
||||||
|
def documents(db: Session, followup: Followup) -> list[tuple[FollowupDocument, MediaFile]]:
|
||||||
|
rows = db.execute(
|
||||||
|
select(FollowupDocument, MediaFile)
|
||||||
|
.join(MediaFile, MediaFile.id == FollowupDocument.media_id)
|
||||||
|
.where(FollowupDocument.followup_id == followup.id)
|
||||||
|
.order_by(FollowupDocument.position, FollowupDocument.id)
|
||||||
|
).all()
|
||||||
|
return [(doc, media) for doc, media in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def _first(fields: dict[str, list[str]], name: str) -> str:
|
||||||
|
values = fields.get(name) or []
|
||||||
|
return values[0] if values else ""
|
||||||
|
|
||||||
|
|
||||||
|
def apply_fields(followup: Followup, fields: dict[str, list[str]], tz: ZoneInfo) -> None:
|
||||||
|
"""Eingaben des Editors übernehmen. Wirft FollowupError."""
|
||||||
|
subject = " ".join(_first(fields, "subject").split())
|
||||||
|
body = _first(fields, "body").replace("\r\n", "\n").strip()
|
||||||
|
trigger = _first(fields, "trigger")
|
||||||
|
if not subject or len(subject) > MAX_SUBJECT:
|
||||||
|
raise FollowupError("followup_subject_invalid")
|
||||||
|
if not body or len(body) > MAX_BODY:
|
||||||
|
raise FollowupError("followup_body_invalid")
|
||||||
|
if trigger not in TRIGGERS:
|
||||||
|
raise FollowupError("followup_trigger_invalid")
|
||||||
|
send_at = None
|
||||||
|
raw = _first(fields, "send_at").strip()
|
||||||
|
if trigger == FollowupTrigger.AT:
|
||||||
|
try:
|
||||||
|
local = datetime.fromisoformat(raw)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise FollowupError("followup_send_at_invalid") from exc
|
||||||
|
send_at = (local if local.tzinfo else local.replace(tzinfo=tz)).astimezone(UTC)
|
||||||
|
try:
|
||||||
|
link_days = int(_first(fields, "link_days").strip() or 90)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise FollowupError("followup_link_days_invalid") from exc
|
||||||
|
if not 1 <= link_days <= 3650:
|
||||||
|
raise FollowupError("followup_link_days_invalid")
|
||||||
|
catch_up = {"yes": True, "no": False}.get(_first(fields, "catch_up"))
|
||||||
|
if trigger != FollowupTrigger.SUBMIT and catch_up is None:
|
||||||
|
raise FollowupError("followup_catch_up_missing")
|
||||||
|
# Neuer Zeitpunkt: der zeitgesteuerte Versand läuft erneut (nur an noch nicht Beliefert)
|
||||||
|
if trigger != followup.trigger or send_at != followup.send_at:
|
||||||
|
followup.sent_at = None
|
||||||
|
followup.subject = subject
|
||||||
|
followup.body = body
|
||||||
|
followup.trigger = trigger
|
||||||
|
followup.send_at = send_at
|
||||||
|
followup.only_confirmed = _first(fields, "only_confirmed") == "on"
|
||||||
|
followup.link_days = link_days
|
||||||
|
if catch_up is not None:
|
||||||
|
followup.catch_up = catch_up
|
||||||
|
followup.updated_at = datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def create(db: Session, form: Form, fields: dict[str, list[str]], tz: ZoneInfo) -> Followup:
|
||||||
|
if len(list_for(db, form)) >= MAX_FOLLOWUPS:
|
||||||
|
raise FollowupError("followup_too_many")
|
||||||
|
followup = Followup(form_id=form.id, subject="", body="", trigger="manual", link_days=90)
|
||||||
|
apply_fields(followup, fields, tz)
|
||||||
|
db.add(followup)
|
||||||
|
db.flush()
|
||||||
|
return followup
|
||||||
|
|
||||||
|
|
||||||
|
def add_document(
|
||||||
|
db: Session,
|
||||||
|
settings: Settings,
|
||||||
|
form: Form,
|
||||||
|
followup: Followup,
|
||||||
|
incoming: media_service.Incoming,
|
||||||
|
title: str,
|
||||||
|
) -> FollowupDocument:
|
||||||
|
"""Dokument speichern; Bilder werden ohne Metadaten neu berechnet."""
|
||||||
|
if len(documents(db, followup)) >= MAX_DOCUMENTS:
|
||||||
|
media_service.discard(incoming)
|
||||||
|
raise FollowupError("followup_documents_too_many")
|
||||||
|
if incoming.filetype is not None and incoming.filetype.key in sniff.IMAGE_KEYS:
|
||||||
|
media = media_service.store_image(db, settings, form, incoming, kind=MediaKind.DOCUMENT)
|
||||||
|
media.thumb_key = None
|
||||||
|
else:
|
||||||
|
media = media_service.store_file(
|
||||||
|
db, settings, form, incoming, MediaKind.DOCUMENT, DOCUMENT_KEYS
|
||||||
|
)
|
||||||
|
name = " ".join(title.split())[:MAX_TITLE] or (media.original_name or "Dokument")
|
||||||
|
position = 1 + max((d.position for d, _ in documents(db, followup)), default=0)
|
||||||
|
doc = FollowupDocument(followup_id=followup.id, media_id=media.id, title=name,
|
||||||
|
position=position)
|
||||||
|
db.add(doc)
|
||||||
|
db.flush()
|
||||||
|
return doc
|
||||||
|
|
||||||
|
|
||||||
|
def remove_document(db: Session, followup: Followup, public_id: str) -> bool:
|
||||||
|
for doc, media in documents(db, followup):
|
||||||
|
if str(doc.public_id) == public_id:
|
||||||
|
db.delete(doc)
|
||||||
|
db.delete(media) # die Datei räumt der Worker auf
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def delete(db: Session, followup: Followup) -> None:
|
||||||
|
for _, media in documents(db, followup):
|
||||||
|
db.delete(media)
|
||||||
|
db.delete(followup)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Persönliche Download-Links
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _b64(data: bytes) -> str:
|
||||||
|
return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
def _unb64(text: str) -> bytes:
|
||||||
|
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
||||||
|
|
||||||
|
|
||||||
|
def _mac(secret_key: str, payload: str) -> bytes:
|
||||||
|
return keyed_hash(derive_key(secret_key, "followup-document"), payload)[:16]
|
||||||
|
|
||||||
|
|
||||||
|
def document_token(secret_key: str, doc: FollowupDocument, recipient: str, expires: int) -> str:
|
||||||
|
payload = f"{doc.public_id}|{recipient}|{expires}"
|
||||||
|
return f"{_b64(payload.encode())}.{_b64(_mac(secret_key, payload))}"
|
||||||
|
|
||||||
|
|
||||||
|
def parse_document_token(
|
||||||
|
secret_key: str, token: str, now: float | None = None
|
||||||
|
) -> uuid.UUID | None:
|
||||||
|
"""Kennung des Dokuments, wenn der Link echt und nicht abgelaufen ist."""
|
||||||
|
if not token or len(token) > 400 or "." not in token:
|
||||||
|
return None
|
||||||
|
raw, _, mac = token.partition(".")
|
||||||
|
try:
|
||||||
|
payload = _unb64(raw).decode("utf-8")
|
||||||
|
given = _unb64(mac)
|
||||||
|
except (binascii.Error, UnicodeDecodeError, ValueError):
|
||||||
|
return None
|
||||||
|
if not constant_time_equal(_mac(secret_key, payload), given):
|
||||||
|
return None
|
||||||
|
parts = payload.split("|")
|
||||||
|
if len(parts) != 3:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
doc_id, expires = uuid.UUID(parts[0]), int(parts[2])
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
if expires < (now if now is not None else time.time()):
|
||||||
|
return None
|
||||||
|
return doc_id
|
||||||
|
|
||||||
|
|
||||||
|
def document_url(settings: Settings, token: str) -> str:
|
||||||
|
return f"{settings.public_origin}/d/{token}"
|
||||||
|
|
||||||
|
|
||||||
|
def find_document(db: Session, public_id: uuid.UUID) -> tuple[FollowupDocument, MediaFile] | None:
|
||||||
|
row = db.execute(
|
||||||
|
select(FollowupDocument, MediaFile)
|
||||||
|
.join(MediaFile, MediaFile.id == FollowupDocument.media_id)
|
||||||
|
.where(FollowupDocument.public_id == public_id)
|
||||||
|
).first()
|
||||||
|
return (row[0], row[1]) if row is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def count_download(doc: FollowupDocument) -> None:
|
||||||
|
doc.downloads = FollowupDocument.downloads + 1 # type: ignore[assignment]
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Empfänger und Versand
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Target:
|
||||||
|
recipient: notify.Recipient
|
||||||
|
response: Response
|
||||||
|
|
||||||
|
|
||||||
|
def _has_confirmed_place(db: Session, response: Response) -> bool:
|
||||||
|
return bool(db.scalar(
|
||||||
|
select(func.count()).select_from(Booking).where(
|
||||||
|
Booking.response_id == response.id, Booking.status == BookingStatus.CONFIRMED
|
||||||
|
)
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
def _eligible(db: Session, form: Form, followup: Followup, response: Response) -> bool:
|
||||||
|
if not followup.only_confirmed:
|
||||||
|
return True
|
||||||
|
if not any(q.type == "slots" for q in form.questions):
|
||||||
|
return True
|
||||||
|
return _has_confirmed_place(db, response)
|
||||||
|
|
||||||
|
|
||||||
|
def targets(db: Session, settings: Settings, form: Form, followup: Followup) -> list[Target]:
|
||||||
|
"""Alle Empfänger (je Person die neueste Antwort), ohne die schon Belieferten."""
|
||||||
|
if form.anonymous:
|
||||||
|
return []
|
||||||
|
delivered = set(db.scalars(
|
||||||
|
select(FollowupDelivery.recipient).where(FollowupDelivery.followup_id == followup.id)
|
||||||
|
))
|
||||||
|
found: dict[str, Target] = {}
|
||||||
|
for response in db.scalars(
|
||||||
|
select(Response).where(Response.form_id == form.id).order_by(Response.submitted_at)
|
||||||
|
):
|
||||||
|
recipient = notify.participant(db, settings, form, response)
|
||||||
|
if recipient is None or recipient.ident in delivered:
|
||||||
|
continue
|
||||||
|
if not _eligible(db, form, followup, response):
|
||||||
|
continue
|
||||||
|
found[recipient.ident] = Target(recipient, response)
|
||||||
|
return [t for t in found.values() if notify.allowed(db, t.recipient, "followup", form)]
|
||||||
|
|
||||||
|
|
||||||
|
def format_date(day: date, language: str) -> str:
|
||||||
|
from babel.dates import format_date
|
||||||
|
|
||||||
|
text: str = format_date(day, format="long", locale=language)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def personalize(text: str, name: str, form: Form) -> str:
|
||||||
|
"""Platzhalter {name} und {form}; sonst bleibt der Text, wie er ist."""
|
||||||
|
return text.replace("{name}", name).replace("{form}", form.title)
|
||||||
|
|
||||||
|
|
||||||
|
def _dedupe_prefix(followup: Followup) -> str:
|
||||||
|
return f"followup:{followup.id}:"
|
||||||
|
|
||||||
|
|
||||||
|
def deliver(
|
||||||
|
db: Session, settings: Settings, form: Form, followup: Followup, chosen: list[Target],
|
||||||
|
*, again: bool = False,
|
||||||
|
) -> int:
|
||||||
|
"""Folge-Mail eintragen. `again`: auch an Personen, die sie schon bekommen haben."""
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
docs = documents(db, followup)
|
||||||
|
expiry = datetime.now(UTC) + timedelta(days=followup.link_days)
|
||||||
|
sent = 0
|
||||||
|
for target in chosen:
|
||||||
|
ident = target.recipient.ident
|
||||||
|
links = [
|
||||||
|
(doc.title, document_url(settings, document_token(
|
||||||
|
secret, doc, ident, int(expiry.timestamp()))))
|
||||||
|
for doc, _ in docs
|
||||||
|
]
|
||||||
|
ok = notify.send(
|
||||||
|
db, settings, target.recipient, kind="followup", event="followup", form=form,
|
||||||
|
context={
|
||||||
|
"custom_subject": personalize(followup.subject, target.recipient.name, form),
|
||||||
|
"body": personalize(followup.body, target.recipient.name, form),
|
||||||
|
"documents": links,
|
||||||
|
"expires": format_date(expiry.date(), target.recipient.language),
|
||||||
|
},
|
||||||
|
# Erneuter Versand braucht einen eigenen Schlüssel, sonst greift die Sperre
|
||||||
|
# gegen doppelte Mails in der Warteschlange.
|
||||||
|
dedupe_key=f"{_dedupe_prefix(followup)}{ident}"
|
||||||
|
+ (f":r{time.time_ns()}" if again else ""),
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
continue
|
||||||
|
existing = db.get(FollowupDelivery, (followup.id, ident))
|
||||||
|
if existing is None:
|
||||||
|
db.add(FollowupDelivery(followup_id=followup.id, recipient=ident,
|
||||||
|
response_id=target.response.id))
|
||||||
|
else:
|
||||||
|
existing.sent_at = datetime.now(UTC)
|
||||||
|
existing.response_id = target.response.id
|
||||||
|
db.flush()
|
||||||
|
sent += 1
|
||||||
|
return sent
|
||||||
|
|
||||||
|
|
||||||
|
def send_now(db: Session, settings: Settings, form: Form, followup: Followup) -> int:
|
||||||
|
"""Von Hand: an alle, die diese Folge-Mail noch nicht bekommen haben."""
|
||||||
|
return deliver(db, settings, form, followup, targets(db, settings, form, followup))
|
||||||
|
|
||||||
|
|
||||||
|
def planned(db: Session, form: Form) -> bool:
|
||||||
|
"""Ist mindestens eine Folge-Mail eingerichtet, die Teilnehmende noch erreichen kann?
|
||||||
|
|
||||||
|
Davon hängen die Hinweise an Gäste ab, ihre Adresse anzugeben und zu bestätigen.
|
||||||
|
Erledigt ist nur eine Mail "beim Schließen" oder "zu einem festen Zeitpunkt",
|
||||||
|
die schon verschickt wurde.
|
||||||
|
"""
|
||||||
|
if form.anonymous:
|
||||||
|
return False
|
||||||
|
once = (FollowupTrigger.CLOSE, FollowupTrigger.AT)
|
||||||
|
return any(
|
||||||
|
not (f.trigger in once and f.sent_at is not None) for f in list_for(db, form)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Übersicht der Empfänger
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# Zustände einer Zeile, in der Reihenfolge der Anzeige
|
||||||
|
STATE_SENT = "sent" # Folge-Mail eingetragen
|
||||||
|
STATE_OPEN = "open" # kann sie bekommen, hat sie noch nicht
|
||||||
|
STATE_NOT_ELIGIBLE = "not_eligible" # nur Warteliste, Mail ist "nur bestätigte Plätze"
|
||||||
|
STATE_UNCONFIRMED = "unconfirmed" # Gast hat seine Adresse nicht bestätigt
|
||||||
|
STATE_NO_ADDRESS = "no_address" # Gast ohne Adresse
|
||||||
|
STATE_OPTED_OUT = "opted_out" # hat Folge-Mails abbestellt
|
||||||
|
SENDABLE = (STATE_SENT, STATE_OPEN, STATE_NOT_ELIGIBLE)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RecipientRow:
|
||||||
|
key: str # Empfängerkennung (u:… / g:…) oder r:<Antwort> ohne Empfänger
|
||||||
|
label: str # Anzeigename; leer bei Gästen, deren Adresse niemand sehen soll
|
||||||
|
guest: bool
|
||||||
|
submitted_at: datetime
|
||||||
|
state: str
|
||||||
|
delivered_at: datetime | None
|
||||||
|
mail_status: str | None # queued / sent / failed, solange das Mailprotokoll reicht
|
||||||
|
mail_sent_at: datetime | None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def can_send(self) -> bool:
|
||||||
|
return self.state in SENDABLE
|
||||||
|
|
||||||
|
|
||||||
|
def _mail_states(db: Session, followup: Followup) -> dict[str, MailMessage]:
|
||||||
|
"""Neueste Mail je Empfänger aus der Warteschlange (Schlüssel followup:<id>:<ident>…)."""
|
||||||
|
prefix = _dedupe_prefix(followup)
|
||||||
|
latest: dict[str, MailMessage] = {}
|
||||||
|
for mail in db.scalars(
|
||||||
|
select(MailMessage)
|
||||||
|
.where(MailMessage.dedupe_key.like(f"{prefix}%"))
|
||||||
|
.order_by(MailMessage.created_at, MailMessage.id)
|
||||||
|
):
|
||||||
|
rest = (mail.dedupe_key or "")[len(prefix):]
|
||||||
|
ident = ":".join(rest.split(":")[:2]) # "u:<id>" bzw. "g:<id>", ohne ":r…"
|
||||||
|
latest[ident] = mail
|
||||||
|
return latest
|
||||||
|
|
||||||
|
|
||||||
|
def _row(
|
||||||
|
db: Session, settings: Settings, form: Form, followup: Followup, response: Response,
|
||||||
|
deliveries: dict[str, FollowupDelivery], mails: dict[str, MailMessage],
|
||||||
|
) -> RecipientRow | None:
|
||||||
|
recipient = notify.participant(db, settings, form, response)
|
||||||
|
if recipient is None:
|
||||||
|
if response.user_id is not None:
|
||||||
|
return None # Konto gelöscht
|
||||||
|
return RecipientRow(f"r:{response.public_id}", "", True, response.submitted_at,
|
||||||
|
STATE_NO_ADDRESS, None, None, None)
|
||||||
|
guest = recipient.guest is not None
|
||||||
|
if recipient.user is not None:
|
||||||
|
label = recipient.user.display_name
|
||||||
|
elif form.guest_email == "question" and recipient.guest is not None:
|
||||||
|
# Die Adresse steht ohnehin in der Antwort auf die E-Mail-Frage
|
||||||
|
label = recipient.guest.email
|
||||||
|
else:
|
||||||
|
label = "" # Zusage im Formular: Veranstalter sehen die Gast-Adresse nicht
|
||||||
|
delivery = deliveries.get(recipient.ident)
|
||||||
|
if guest and recipient.guest is not None and recipient.guest.confirmed_at is None:
|
||||||
|
state = STATE_UNCONFIRMED
|
||||||
|
elif not notify.allowed(db, recipient, "followup", form):
|
||||||
|
state = STATE_OPTED_OUT
|
||||||
|
elif delivery is not None:
|
||||||
|
state = STATE_SENT
|
||||||
|
elif not _eligible(db, form, followup, response):
|
||||||
|
state = STATE_NOT_ELIGIBLE
|
||||||
|
else:
|
||||||
|
state = STATE_OPEN
|
||||||
|
mail = mails.get(recipient.ident)
|
||||||
|
return RecipientRow(
|
||||||
|
recipient.ident, label, guest, response.submitted_at, state,
|
||||||
|
delivery.sent_at if delivery is not None else None,
|
||||||
|
mail.status if mail is not None else None,
|
||||||
|
mail.sent_at if mail is not None else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def recipients(
|
||||||
|
db: Session, settings: Settings, form: Form, followup: Followup
|
||||||
|
) -> list[RecipientRow]:
|
||||||
|
"""Alle Teilnehmenden (je Person die neueste Antwort) mit Versandstand."""
|
||||||
|
if form.anonymous:
|
||||||
|
return []
|
||||||
|
deliveries = {
|
||||||
|
d.recipient: d for d in db.scalars(
|
||||||
|
select(FollowupDelivery).where(FollowupDelivery.followup_id == followup.id)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
mails = _mail_states(db, followup)
|
||||||
|
rows: dict[str, RecipientRow] = {}
|
||||||
|
for response in db.scalars(
|
||||||
|
select(Response).where(Response.form_id == form.id).order_by(Response.submitted_at)
|
||||||
|
):
|
||||||
|
row = _row(db, settings, form, followup, response, deliveries, mails)
|
||||||
|
if row is not None:
|
||||||
|
rows[row.key] = row # spätere Antwort derselben Person ersetzt die frühere
|
||||||
|
order = {state: i for i, state in enumerate(
|
||||||
|
(STATE_OPEN, STATE_NOT_ELIGIBLE, STATE_UNCONFIRMED, STATE_NO_ADDRESS,
|
||||||
|
STATE_OPTED_OUT, STATE_SENT)
|
||||||
|
)}
|
||||||
|
return sorted(rows.values(), key=lambda r: (order[r.state], r.label.casefold(),
|
||||||
|
r.submitted_at))
|
||||||
|
|
||||||
|
|
||||||
|
def send_to(
|
||||||
|
db: Session, settings: Settings, form: Form, followup: Followup, key: str
|
||||||
|
) -> bool:
|
||||||
|
"""Von Hand an eine Person (erneut) senden, wenn sie Folge-Mails bekommen darf."""
|
||||||
|
if form.anonymous or not key.startswith(("u:", "g:")):
|
||||||
|
return False
|
||||||
|
target: Target | None = None
|
||||||
|
for response in db.scalars(
|
||||||
|
select(Response).where(Response.form_id == form.id).order_by(Response.submitted_at)
|
||||||
|
):
|
||||||
|
recipient = notify.participant(db, settings, form, response)
|
||||||
|
if recipient is not None and recipient.ident == key:
|
||||||
|
target = Target(recipient, response)
|
||||||
|
if target is None or not notify.allowed(db, target.recipient, "followup", form):
|
||||||
|
return False
|
||||||
|
return deliver(db, settings, form, followup, [target], again=True) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def already_sent(db: Session, followup: Followup) -> bool:
|
||||||
|
"""Ist diese Folge-Mail schon an die bisherigen Teilnehmenden gegangen?"""
|
||||||
|
if followup.sent_at is not None:
|
||||||
|
return True
|
||||||
|
if followup.trigger != FollowupTrigger.MANUAL:
|
||||||
|
return False
|
||||||
|
return db.scalar(
|
||||||
|
select(FollowupDelivery.recipient).where(FollowupDelivery.followup_id == followup.id)
|
||||||
|
.limit(1)
|
||||||
|
) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def _due_for_newcomer(db: Session, followup: Followup) -> bool:
|
||||||
|
if followup.trigger == FollowupTrigger.SUBMIT:
|
||||||
|
return True
|
||||||
|
return bool(followup.catch_up) and already_sent(db, followup)
|
||||||
|
|
||||||
|
|
||||||
|
def on_submit(db: Session, settings: Settings, form: Form, response: Response) -> int:
|
||||||
|
"""Folge-Mails für eine neue Antwort (oder eine gerade bestätigte Gast-Adresse).
|
||||||
|
|
||||||
|
"Direkt nach der Teilnahme" immer; die übrigen nur, wenn sie schon verschickt
|
||||||
|
wurden und das Nachholen eingeschaltet ist. Sonst kommt die Mail beim regulären
|
||||||
|
Versand oder von Hand über die Empfängerseite.
|
||||||
|
"""
|
||||||
|
if form.anonymous:
|
||||||
|
return 0
|
||||||
|
recipient = notify.participant(db, settings, form, response)
|
||||||
|
if recipient is None:
|
||||||
|
return 0
|
||||||
|
sent = 0
|
||||||
|
for followup in list_for(db, form):
|
||||||
|
if not _due_for_newcomer(db, followup):
|
||||||
|
continue
|
||||||
|
if not _eligible(db, form, followup, response):
|
||||||
|
continue
|
||||||
|
delivered = db.get(FollowupDelivery, (followup.id, recipient.ident))
|
||||||
|
if delivered is None and notify.allowed(db, recipient, "followup", form):
|
||||||
|
sent += deliver(db, settings, form, followup, [Target(recipient, response)])
|
||||||
|
return sent
|
||||||
|
|
||||||
|
|
||||||
|
def on_confirm(db: Session, settings: Settings, contact: GuestContact) -> int:
|
||||||
|
"""Gast hat seine Adresse bestätigt: ausstehende Folge-Mails nachholen."""
|
||||||
|
sent = 0
|
||||||
|
for response in db.scalars(select(Response).where(Response.guest_contact_id == contact.id)):
|
||||||
|
form = db.get(Form, response.form_id)
|
||||||
|
if form is not None:
|
||||||
|
sent += on_submit(db, settings, form, response)
|
||||||
|
return sent
|
||||||
|
|
||||||
|
|
||||||
|
def run_due(db: Session, settings: Settings, now: datetime) -> int:
|
||||||
|
"""Worker: Folge-Mails "beim Schließen" und "zu einem festen Zeitpunkt"."""
|
||||||
|
sent = 0
|
||||||
|
rows = db.execute(
|
||||||
|
select(Followup, Form)
|
||||||
|
.join(Form, Form.id == Followup.form_id)
|
||||||
|
.where(
|
||||||
|
Followup.sent_at.is_(None),
|
||||||
|
Followup.trigger.in_([FollowupTrigger.CLOSE, FollowupTrigger.AT]),
|
||||||
|
Form.is_template.is_(False),
|
||||||
|
Form.status != FormStatus.DRAFT,
|
||||||
|
)
|
||||||
|
).all()
|
||||||
|
for followup, form in rows:
|
||||||
|
if followup.trigger == FollowupTrigger.AT:
|
||||||
|
due = followup.send_at is not None and followup.send_at <= now
|
||||||
|
else:
|
||||||
|
due = fill_state(form, now) == FillState.CLOSED
|
||||||
|
if not due:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
with db.begin_nested(): # eine fehlerhafte Folge-Mail hält die anderen nicht auf
|
||||||
|
sent += send_now(db, settings, form, followup)
|
||||||
|
followup.sent_at = now
|
||||||
|
except Exception:
|
||||||
|
log.exception("Folge-Mail %s konnte nicht versendet werden", followup.id)
|
||||||
|
return sent
|
||||||
|
|
||||||
|
|
||||||
|
def delivered_documents(
|
||||||
|
db: Session, form: Form, *, recipient: str | None = None, response_id: int | None = None
|
||||||
|
) -> list[tuple[FollowupDocument, MediaFile]]:
|
||||||
|
"""Dokumente aus Folge-Mails, die eine Person zu diesem Formular bekommen hat."""
|
||||||
|
stmt = (
|
||||||
|
select(FollowupDocument, MediaFile)
|
||||||
|
.join(MediaFile, MediaFile.id == FollowupDocument.media_id)
|
||||||
|
.join(FollowupDelivery, FollowupDelivery.followup_id == FollowupDocument.followup_id)
|
||||||
|
.join(Followup, Followup.id == FollowupDocument.followup_id)
|
||||||
|
.where(Followup.form_id == form.id)
|
||||||
|
.order_by(Followup.id, FollowupDocument.position, FollowupDocument.id)
|
||||||
|
)
|
||||||
|
if recipient is not None:
|
||||||
|
stmt = stmt.where(FollowupDelivery.recipient == recipient)
|
||||||
|
elif response_id is not None:
|
||||||
|
stmt = stmt.where(FollowupDelivery.response_id == response_id)
|
||||||
|
else:
|
||||||
|
return []
|
||||||
|
seen: set[int] = set()
|
||||||
|
result: list[tuple[FollowupDocument, MediaFile]] = []
|
||||||
|
for doc, media in db.execute(stmt).all():
|
||||||
|
if doc.id not in seen:
|
||||||
|
seen.add(doc.id)
|
||||||
|
result.append((doc, media))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def stats(db: Session, followup: Followup) -> dict[str, Any]:
|
||||||
|
delivered = db.scalar(
|
||||||
|
select(func.count()).select_from(FollowupDelivery)
|
||||||
|
.where(FollowupDelivery.followup_id == followup.id)
|
||||||
|
) or 0
|
||||||
|
return {"delivered": int(delivered)}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Fragengruppen: mehrere gleichartige Fragen kompakt als Tabelle.
|
||||||
|
|
||||||
|
Eine Gruppe ist ein eigenes Element im Designer (Typ "question_group"). Zu ihr
|
||||||
|
gehören alle direkt folgenden Fragen des in der Gruppe gewählten Typs, solange
|
||||||
|
sie zueinander passen (z. B. dieselbe Skala). Die erste unpassende Frage, eine
|
||||||
|
Überschrift, ein Seitenumbruch oder eine weitere Gruppe beendet sie.
|
||||||
|
|
||||||
|
Die Zugehörigkeit ergibt sich allein aus der Reihenfolge; verschieben genügt,
|
||||||
|
und beim Kopieren eines Formulars bleibt sie ohne weiteres Zutun erhalten.
|
||||||
|
|
||||||
|
`min_select` und `max_select` legen fest, wie viele Einträge eine Person in der
|
||||||
|
Gruppe mindestens bzw. höchstens wählen muss oder darf (0 = keine Pflicht bzw.
|
||||||
|
unbegrenzt): bei "Teilnahme mit Plätzen" die Anmeldungen, bei Ja/Nein die Zahl
|
||||||
|
der "Ja". Verbindlich ist die Prüfung beim Absenden (forms.service.validate).
|
||||||
|
|
||||||
|
Pflicht bei Teilnahme-Gruppen regelt nur die Gruppe: Eine einzelne Schicht als
|
||||||
|
Pflicht hieße "genau diese buchen" und widerspräche schnell der Höchstzahl.
|
||||||
|
Deshalb gilt "Antwort erforderlich" an diesen Fragen nicht, solange sie in einer
|
||||||
|
Gruppe stehen. Bei Ja/Nein, Bewertung und Einfachauswahl bleibt die Pflicht je
|
||||||
|
Zeile sinnvoll ("jede Zeile beantworten") und verträgt sich mit der Höchstzahl,
|
||||||
|
weil "Nein" auch eine Antwort ist.
|
||||||
|
|
||||||
|
Das Modul kennt weder Datenbank noch Web.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Mapping, Sequence
|
||||||
|
from typing import Any, Protocol
|
||||||
|
|
||||||
|
from surveybox.i18n import N_
|
||||||
|
|
||||||
|
GROUP = "question_group"
|
||||||
|
|
||||||
|
# Fragetypen, die sich gruppieren lassen, mit Namen für den Designer
|
||||||
|
MEMBER_TYPES: dict[str, str] = {
|
||||||
|
"slots": N_("Participation with places"),
|
||||||
|
"yes_no": N_("Yes/No"),
|
||||||
|
"rating": N_("Rating scale"),
|
||||||
|
"single_choice": N_("Single choice (same options)"),
|
||||||
|
}
|
||||||
|
# Bei diesen Typen lässt sich die Zahl der Einträge begrenzen
|
||||||
|
COUNTING = ("slots", "yes_no")
|
||||||
|
# Bei diesen Typen bestimmt allein die Gruppe, ob etwas gewählt werden muss
|
||||||
|
REQUIRED_BY_GROUP = ("slots",)
|
||||||
|
MAX_SELECT = 1000
|
||||||
|
|
||||||
|
|
||||||
|
class QuestionLike(Protocol):
|
||||||
|
id: int
|
||||||
|
type: str
|
||||||
|
config: dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
def member_type(group: QuestionLike) -> str:
|
||||||
|
value = str(group.config.get("member_type") or "")
|
||||||
|
return value if value in MEMBER_TYPES else "slots"
|
||||||
|
|
||||||
|
|
||||||
|
def _count_setting(group: QuestionLike, key: str) -> int:
|
||||||
|
if member_type(group) not in COUNTING:
|
||||||
|
return 0
|
||||||
|
try:
|
||||||
|
return max(0, int(group.config.get(key) or 0))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def max_select(group: QuestionLike) -> int:
|
||||||
|
"""0 = unbegrenzt; bei nicht zählenden Typen immer 0."""
|
||||||
|
return _count_setting(group, "max_select")
|
||||||
|
|
||||||
|
|
||||||
|
def min_select(group: QuestionLike) -> int:
|
||||||
|
"""0 = keine Pflicht; bei nicht zählenden Typen immer 0."""
|
||||||
|
return _count_setting(group, "min_select")
|
||||||
|
|
||||||
|
|
||||||
|
def _labels(question: QuestionLike) -> list[str]:
|
||||||
|
return [str(o.get("label", "")) for o in question.config.get("options") or []
|
||||||
|
if isinstance(o, dict)]
|
||||||
|
|
||||||
|
|
||||||
|
def fits(kind: str, first: QuestionLike | None, question: QuestionLike) -> bool:
|
||||||
|
"""Passt die Frage in eine Gruppe vom Typ `kind` mit dem ersten Mitglied `first`?"""
|
||||||
|
if question.type != kind:
|
||||||
|
return False
|
||||||
|
cfg = question.config
|
||||||
|
if kind == "slots":
|
||||||
|
return bool(cfg.get("single"))
|
||||||
|
if first is None:
|
||||||
|
return kind != "single_choice" or not cfg.get("allow_other")
|
||||||
|
ref = first.config
|
||||||
|
if kind == "yes_no":
|
||||||
|
return (cfg.get("label_yes") or "", cfg.get("label_no") or "") == (
|
||||||
|
ref.get("label_yes") or "", ref.get("label_no") or "")
|
||||||
|
if kind == "rating":
|
||||||
|
return int(cfg.get("scale_max") or 5) == int(ref.get("scale_max") or 5)
|
||||||
|
if kind == "single_choice":
|
||||||
|
return not cfg.get("allow_other") and _labels(question) == _labels(first)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def resolve(questions: Sequence[QuestionLike]) -> dict[int, list[Any]]:
|
||||||
|
"""Gruppen-ID -> Mitglieder in Formularreihenfolge (auch leere Gruppen)."""
|
||||||
|
result: dict[int, list[Any]] = {}
|
||||||
|
current: QuestionLike | None = None
|
||||||
|
members: list[Any] = []
|
||||||
|
for question in questions:
|
||||||
|
if question.type == GROUP:
|
||||||
|
current, members = question, []
|
||||||
|
result[question.id] = members
|
||||||
|
continue
|
||||||
|
if current is not None and fits(
|
||||||
|
member_type(current), members[0] if members else None, question
|
||||||
|
):
|
||||||
|
members.append(question)
|
||||||
|
continue
|
||||||
|
current = None
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def member_of(questions: Sequence[QuestionLike]) -> dict[int, int]:
|
||||||
|
"""Frage-ID -> Gruppen-ID für alle gruppierten Fragen."""
|
||||||
|
return {
|
||||||
|
member.id: group_id
|
||||||
|
for group_id, members in resolve(questions).items()
|
||||||
|
for member in members
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def required_by_group(questions: Sequence[QuestionLike]) -> set[int]:
|
||||||
|
"""Fragen, deren eigene Pflicht nicht gilt, weil ihre Gruppe sie regelt."""
|
||||||
|
by_id = {q.id: q for q in questions}
|
||||||
|
return {
|
||||||
|
member.id
|
||||||
|
for group_id, members in resolve(questions).items()
|
||||||
|
if member_type(by_id[group_id]) in REQUIRED_BY_GROUP
|
||||||
|
for member in members
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def is_positive(question: QuestionLike, stored: Mapping[str, Any] | None) -> bool:
|
||||||
|
"""Zählt die gespeicherte Antwort gegen die Höchstzahl der Gruppe?"""
|
||||||
|
if not stored:
|
||||||
|
return False
|
||||||
|
if question.type == "slots":
|
||||||
|
return bool((stored.get("value_json") or {}).get("selected"))
|
||||||
|
if question.type == "yes_no":
|
||||||
|
return stored.get("value_bool") is True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def count_errors(
|
||||||
|
questions: Sequence[QuestionLike],
|
||||||
|
stored: Mapping[int, Mapping[str, Any]],
|
||||||
|
hidden: set[int],
|
||||||
|
) -> dict[int, str]:
|
||||||
|
"""Sichtbare Gruppen mit zu vielen oder zu wenigen Einträgen: ID -> Fehlercode.
|
||||||
|
|
||||||
|
Die Mindestzahl gilt höchstens für so viele Fragen, wie gerade sichtbar sind;
|
||||||
|
blendet eine Bedingung Zeilen aus, wird sie also nie unerfüllbar.
|
||||||
|
"""
|
||||||
|
errors: dict[int, str] = {}
|
||||||
|
by_id = {q.id: q for q in questions}
|
||||||
|
for group_id, members in resolve(questions).items():
|
||||||
|
group = by_id[group_id]
|
||||||
|
if group_id in hidden:
|
||||||
|
continue
|
||||||
|
upper, lower = max_select(group), min_select(group)
|
||||||
|
if not upper and not lower:
|
||||||
|
continue
|
||||||
|
shown = [m for m in members if m.id not in hidden]
|
||||||
|
count = sum(1 for m in shown if is_positive(m, stored.get(m.id)))
|
||||||
|
if upper and count > upper:
|
||||||
|
errors[group_id] = "group_too_many"
|
||||||
|
elif count < min(lower, len(shown)):
|
||||||
|
errors[group_id] = "group_too_few"
|
||||||
|
return errors
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Gäste: Teilnahme ohne Konto mit persönlichem Link.
|
||||||
|
|
||||||
|
- Jede Gast-Antwort bekommt einen persönlichen Link (256 Bit Zufall). In der
|
||||||
|
Datenbank liegt nur sein Hash; wer den Link hat, sieht die Antwort und darf
|
||||||
|
sie ändern oder löschen, soweit das Formular es erlaubt.
|
||||||
|
- Gibt der Gast eine Adresse an, erhält er eine Mail mit dem Link und einem
|
||||||
|
Bestätigungslink. Benachrichtigungen gibt es erst nach der Bestätigung
|
||||||
|
(Double-Opt-in). Unbestätigte Adressen löscht der Worker nach sieben Tagen.
|
||||||
|
- "Meine Links anfordern" erzeugt alle Links einer Adresse neu; die alten
|
||||||
|
werden dabei ungültig.
|
||||||
|
- Legt die Person später ein Konto mit derselben (bestätigten) Adresse an,
|
||||||
|
gehen ihre Gast-Antworten auf das Konto über.
|
||||||
|
|
||||||
|
Bei anonymen Formularen gibt es weder Adresse noch persönlichen Link.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import delete, exists, select, update
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.accounts import ratelimit
|
||||||
|
from surveybox.accounts.service import email_valid, normalize_email
|
||||||
|
from surveybox.models import Form, GuestContact, Question, Response, UserAccount
|
||||||
|
from surveybox.security.client_ip import ip_key
|
||||||
|
from surveybox.security.tokens import (
|
||||||
|
constant_time_equal,
|
||||||
|
derive_key,
|
||||||
|
keyed_hash,
|
||||||
|
new_token,
|
||||||
|
token_hash,
|
||||||
|
)
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
LINK_BYTES = 32 # 256 Bit
|
||||||
|
CONFIRM_VALIDITY = timedelta(days=7)
|
||||||
|
UNCONFIRMED_RETENTION = timedelta(days=7)
|
||||||
|
# Mails an eine Adresse begrenzen (jemand könnte eine fremde Adresse eintragen)
|
||||||
|
RECEIPTS_PER_EMAIL = 10
|
||||||
|
LINKS_PER_EMAIL = 3
|
||||||
|
LINKS_PER_IP = 10
|
||||||
|
LINK_GUESSES_PER_IP = 60
|
||||||
|
WINDOW = timedelta(hours=1)
|
||||||
|
GUESS_WINDOW = timedelta(minutes=15)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Persönlicher Link
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def wants_link(form: Form, user: UserAccount | None) -> bool:
|
||||||
|
"""Bekommt diese Teilnahme einen persönlichen Link?"""
|
||||||
|
return user is None and not form.anonymous
|
||||||
|
|
||||||
|
|
||||||
|
def issue_link(response: Response) -> str:
|
||||||
|
"""Neuer Link für die Antwort; ein früherer wird ungültig."""
|
||||||
|
token = new_token(LINK_BYTES)
|
||||||
|
response.access_hash = token_hash(token)
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def link_url(settings: Settings, token: str) -> str:
|
||||||
|
return f"{settings.public_origin}/r/{token}"
|
||||||
|
|
||||||
|
|
||||||
|
def find_by_link(
|
||||||
|
db: Session, settings: Settings, token: str, client_ip: str
|
||||||
|
) -> Response | None:
|
||||||
|
"""Antwort zum persönlichen Link; Fehlversuche je IP begrenzt."""
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
key = f"guestlink-ip:{ip_key(secret, client_ip)}"
|
||||||
|
if ratelimit.exceeded(db, key, LINK_GUESSES_PER_IP, GUESS_WINDOW):
|
||||||
|
return None
|
||||||
|
row = (
|
||||||
|
db.scalar(select(Response).where(Response.access_hash == token_hash(token)))
|
||||||
|
if token and len(token) <= 128
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
if row is None:
|
||||||
|
ratelimit.hit(db, key, LINK_GUESSES_PER_IP, GUESS_WINDOW)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Adresse
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class EmailField:
|
||||||
|
email: str | None
|
||||||
|
error: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_email(form: Form, user: UserAccount | None, raw: str) -> EmailField:
|
||||||
|
"""Adressfeld beim Ausfüllen, je nach Einstellung des Formulars."""
|
||||||
|
if user is not None or form.anonymous or form.guest_email not in ("optional", "required"):
|
||||||
|
return EmailField(None)
|
||||||
|
value = normalize_email(raw)
|
||||||
|
if not value:
|
||||||
|
return EmailField(None, "required" if form.guest_email == "required" else None)
|
||||||
|
if not email_valid(value):
|
||||||
|
return EmailField(None, "email")
|
||||||
|
return EmailField(value)
|
||||||
|
|
||||||
|
|
||||||
|
def can_collect(form: Form) -> bool:
|
||||||
|
"""Können Gäste in diesem Formular eine Adresse angeben?"""
|
||||||
|
if form.anonymous:
|
||||||
|
return False
|
||||||
|
if form.guest_email in ("optional", "required"):
|
||||||
|
return True
|
||||||
|
return form.guest_email == "question" and email_question(form) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def email_question(form: Form) -> Question | None:
|
||||||
|
"""Erste Frage, die eine Adresse liefert (für die Einstellung "question"): E-Mail-Adresse
|
||||||
|
oder Teilnehmer-Name mit Adressfeld."""
|
||||||
|
return next((q for q in form.questions if q.type == "email" or (
|
||||||
|
q.type == "participant_name" and (q.config.get("email") or "optional") != "off"
|
||||||
|
)), None)
|
||||||
|
|
||||||
|
|
||||||
|
def email_from_answers(
|
||||||
|
form: Form, stored: Mapping[int, Mapping[str, Any]], hidden: set[int]
|
||||||
|
) -> str | None:
|
||||||
|
"""Adresse aus der Antwort auf die E-Mail-Frage, wenn das Formular das so will."""
|
||||||
|
if form.anonymous or form.guest_email != "question":
|
||||||
|
return None
|
||||||
|
for question in form.questions:
|
||||||
|
if question.type not in ("email", "participant_name") or question.id in hidden:
|
||||||
|
continue
|
||||||
|
answer = stored.get(question.id) or {}
|
||||||
|
raw = answer.get("value_text") if question.type == "email" else (
|
||||||
|
(answer.get("value_json") or {}).get("email"))
|
||||||
|
value = normalize_email(str(raw or ""))
|
||||||
|
if value and email_valid(value):
|
||||||
|
return value
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def contact_for(db: Session, email: str, language: str) -> tuple[GuestContact, str | None]:
|
||||||
|
"""Vorhandene oder neue Adresse. Zweiter Wert: neuer Bestätigungslink (unbestätigt)."""
|
||||||
|
contact = db.scalar(select(GuestContact).where(GuestContact.email == email))
|
||||||
|
if contact is None:
|
||||||
|
contact = GuestContact(email=email, language=language)
|
||||||
|
db.add(contact)
|
||||||
|
db.flush()
|
||||||
|
else:
|
||||||
|
contact.language = language
|
||||||
|
if contact.confirmed_at is not None:
|
||||||
|
return contact, None
|
||||||
|
token = new_token(LINK_BYTES)
|
||||||
|
contact.confirm_hash = token_hash(token)
|
||||||
|
return contact, token
|
||||||
|
|
||||||
|
|
||||||
|
def receipt_allowed(db: Session, settings: Settings, email: str) -> bool:
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
key = f"guest-receipt:{ip_key(secret, email)}"
|
||||||
|
if ratelimit.exceeded(db, key, RECEIPTS_PER_EMAIL, WINDOW):
|
||||||
|
return False
|
||||||
|
ratelimit.hit(db, key, RECEIPTS_PER_EMAIL, WINDOW)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def confirm_url(settings: Settings, token: str) -> str:
|
||||||
|
return f"{settings.public_origin}/g/confirm/{token}"
|
||||||
|
|
||||||
|
|
||||||
|
def find_by_confirm(db: Session, token: str) -> GuestContact | None:
|
||||||
|
if not token or len(token) > 128:
|
||||||
|
return None
|
||||||
|
contact = db.scalar(select(GuestContact).where(GuestContact.confirm_hash == token_hash(token)))
|
||||||
|
if contact is None:
|
||||||
|
return None
|
||||||
|
if contact.created_at < datetime.now(UTC) - CONFIRM_VALIDITY:
|
||||||
|
return None
|
||||||
|
return contact
|
||||||
|
|
||||||
|
|
||||||
|
def confirm(contact: GuestContact) -> None:
|
||||||
|
contact.confirmed_at = datetime.now(UTC)
|
||||||
|
contact.confirm_hash = None
|
||||||
|
|
||||||
|
|
||||||
|
def purge_unconfirmed(db: Session, now: datetime) -> int:
|
||||||
|
"""Unbestätigte Adressen nach sieben Tagen löschen (Antworten bleiben)."""
|
||||||
|
result = db.execute(
|
||||||
|
delete(GuestContact).where(
|
||||||
|
GuestContact.confirmed_at.is_(None),
|
||||||
|
GuestContact.created_at < now - UNCONFIRMED_RETENTION,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return int(result.rowcount or 0) # type: ignore[attr-defined]
|
||||||
|
|
||||||
|
|
||||||
|
def purge_orphans(db: Session, now: datetime) -> int:
|
||||||
|
"""Adressen ohne Antwort löschen (etwa nach Ablauf der Löschfrist); Karenz sieben Tage."""
|
||||||
|
result = db.execute(
|
||||||
|
delete(GuestContact).where(
|
||||||
|
GuestContact.created_at < now - UNCONFIRMED_RETENTION,
|
||||||
|
~exists().where(Response.guest_contact_id == GuestContact.id),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return int(result.rowcount or 0) # type: ignore[attr-defined]
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Meine Links anfordern
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def request_links(
|
||||||
|
db: Session, settings: Settings, raw_email: str, client_ip: str
|
||||||
|
) -> tuple[GuestContact, list[tuple[Form, str]]] | None:
|
||||||
|
"""Alle Antworten zu einer Adresse mit neuen Links.
|
||||||
|
|
||||||
|
None bei unbekannter Adresse, ohne Antworten oder zu vielen Anfragen. Der
|
||||||
|
Aufrufer antwortet in jedem Fall gleich.
|
||||||
|
"""
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
ip_limit = f"guest-links-ip:{ip_key(secret, client_ip)}"
|
||||||
|
if ratelimit.exceeded(db, ip_limit, LINKS_PER_IP, WINDOW):
|
||||||
|
return None
|
||||||
|
ratelimit.hit(db, ip_limit, LINKS_PER_IP, WINDOW)
|
||||||
|
email = normalize_email(raw_email)
|
||||||
|
if not email_valid(email):
|
||||||
|
return None
|
||||||
|
mail_limit = f"guest-links-mail:{ip_key(secret, email)}"
|
||||||
|
if ratelimit.exceeded(db, mail_limit, LINKS_PER_EMAIL, WINDOW):
|
||||||
|
return None
|
||||||
|
ratelimit.hit(db, mail_limit, LINKS_PER_EMAIL, WINDOW)
|
||||||
|
contact = db.scalar(select(GuestContact).where(GuestContact.email == email))
|
||||||
|
if contact is None:
|
||||||
|
return None
|
||||||
|
rows = db.execute(
|
||||||
|
select(Response, Form)
|
||||||
|
.join(Form, Form.id == Response.form_id)
|
||||||
|
.where(Response.guest_contact_id == contact.id, Response.user_id.is_(None))
|
||||||
|
.order_by(Response.submitted_at.desc())
|
||||||
|
.limit(100)
|
||||||
|
).all()
|
||||||
|
if not rows:
|
||||||
|
return None
|
||||||
|
return contact, [(form, issue_link(response)) for response, form in rows]
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Meine Daten löschen und herunterladen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
SUBJECT_LINK_VALIDITY = timedelta(hours=24)
|
||||||
|
SUBJECT_PURPOSES = ("erase", "export")
|
||||||
|
|
||||||
|
|
||||||
|
def _subject_mac(secret_key: str, purpose: str, payload: str) -> str:
|
||||||
|
raw = keyed_hash(derive_key(secret_key, f"guest-{purpose}"), payload)[:20]
|
||||||
|
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
def subject_token(
|
||||||
|
secret_key: str, contact: GuestContact, purpose: str, now: float | None = None
|
||||||
|
) -> str:
|
||||||
|
"""Signierter Link (24 Stunden) zum Löschen oder Herunterladen der eigenen Daten."""
|
||||||
|
if purpose not in SUBJECT_PURPOSES:
|
||||||
|
raise ValueError(purpose)
|
||||||
|
expires = int((now if now is not None else time.time())
|
||||||
|
+ SUBJECT_LINK_VALIDITY.total_seconds())
|
||||||
|
payload = f"{contact.public_id.hex}.{expires}"
|
||||||
|
return f"{payload}.{_subject_mac(secret_key, purpose, payload)}"
|
||||||
|
|
||||||
|
|
||||||
|
def find_by_subject_token(
|
||||||
|
db: Session, secret_key: str, token: str, purpose: str, now: float | None = None
|
||||||
|
) -> GuestContact | None:
|
||||||
|
"""Adresse zu einem Link; None, wenn gefälscht, abgelaufen oder schon gelöscht."""
|
||||||
|
parts = token.split(".") if token and len(token) <= 200 else []
|
||||||
|
if len(parts) != 3 or purpose not in SUBJECT_PURPOSES:
|
||||||
|
return None
|
||||||
|
payload = f"{parts[0]}.{parts[1]}"
|
||||||
|
if not constant_time_equal(_subject_mac(secret_key, purpose, payload), parts[2]):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
pid = uuid.UUID(hex=parts[0])
|
||||||
|
expires = int(parts[1])
|
||||||
|
except (ValueError, binascii.Error):
|
||||||
|
return None
|
||||||
|
if expires < (now if now is not None else time.time()):
|
||||||
|
return None
|
||||||
|
return db.scalar(select(GuestContact).where(GuestContact.public_id == pid))
|
||||||
|
|
||||||
|
|
||||||
|
def erase_token(secret_key: str, contact: GuestContact, now: float | None = None) -> str:
|
||||||
|
return subject_token(secret_key, contact, "erase", now)
|
||||||
|
|
||||||
|
|
||||||
|
def find_by_erase_token(
|
||||||
|
db: Session, secret_key: str, token: str, now: float | None = None
|
||||||
|
) -> GuestContact | None:
|
||||||
|
return find_by_subject_token(db, secret_key, token, "erase", now)
|
||||||
|
|
||||||
|
|
||||||
|
def request_subject_link(
|
||||||
|
db: Session, settings: Settings, raw_email: str, client_ip: str, purpose: str
|
||||||
|
) -> GuestContact | None:
|
||||||
|
"""Link anfordern; begrenzt wie "Meine Links". None: keine Mail (gleiche Antwort)."""
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
ip_limit = f"guest-{purpose}-ip:{ip_key(secret, client_ip)}"
|
||||||
|
if ratelimit.exceeded(db, ip_limit, LINKS_PER_IP, WINDOW):
|
||||||
|
return None
|
||||||
|
ratelimit.hit(db, ip_limit, LINKS_PER_IP, WINDOW)
|
||||||
|
email = normalize_email(raw_email)
|
||||||
|
if not email_valid(email):
|
||||||
|
return None
|
||||||
|
mail_limit = f"guest-{purpose}-mail:{ip_key(secret, email)}"
|
||||||
|
if ratelimit.exceeded(db, mail_limit, LINKS_PER_EMAIL, WINDOW):
|
||||||
|
return None
|
||||||
|
ratelimit.hit(db, mail_limit, LINKS_PER_EMAIL, WINDOW)
|
||||||
|
return db.scalar(select(GuestContact).where(GuestContact.email == email))
|
||||||
|
|
||||||
|
|
||||||
|
def request_erase(
|
||||||
|
db: Session, settings: Settings, raw_email: str, client_ip: str
|
||||||
|
) -> GuestContact | None:
|
||||||
|
return request_subject_link(db, settings, raw_email, client_ip, "erase")
|
||||||
|
|
||||||
|
|
||||||
|
def erase_url(settings: Settings, token: str) -> str:
|
||||||
|
return f"{settings.public_origin}/g/erase/{token}"
|
||||||
|
|
||||||
|
|
||||||
|
def export_url(settings: Settings, token: str) -> str:
|
||||||
|
return f"{settings.public_origin}/g/export/{token}"
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Konto
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def confirmed_contact(db: Session, email: str) -> GuestContact | None:
|
||||||
|
contact = db.scalar(select(GuestContact).where(GuestContact.email == normalize_email(email)))
|
||||||
|
return contact if contact is not None and contact.confirmed_at is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def claim_for_user(db: Session, user: UserAccount) -> int:
|
||||||
|
"""Gast-Antworten einer bestätigten Adresse gehen auf das Konto über.
|
||||||
|
|
||||||
|
Danach braucht es keine einzelnen Links mehr; die Adresse wird gelöscht,
|
||||||
|
Benachrichtigungen laufen über das Konto.
|
||||||
|
"""
|
||||||
|
contact = confirmed_contact(db, user.email)
|
||||||
|
if contact is None:
|
||||||
|
return 0
|
||||||
|
result = db.execute(
|
||||||
|
update(Response)
|
||||||
|
.where(Response.guest_contact_id == contact.id, Response.user_id.is_(None))
|
||||||
|
.values(user_id=user.id, access_hash=None, guest_contact_id=None)
|
||||||
|
)
|
||||||
|
if not contact.notify:
|
||||||
|
user.notify_prefs = {**(user.notify_prefs or {}), "promoted": False, "confirmed": False}
|
||||||
|
db.delete(contact)
|
||||||
|
return int(result.rowcount or 0) # type: ignore[attr-defined]
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Vermerke zu Antworten, die ein Verwalter geändert hat.
|
||||||
|
|
||||||
|
Wer eine fremde Antwort ändert, muss begründen, warum. Der Vermerk hält fest, wer wann
|
||||||
|
welche Fragen geändert hat; er ist nur für Verwalter sichtbar und gehört zur Auskunft
|
||||||
|
der betroffenen Person. Mit der Antwort wird er gelöscht, beim Anonymisieren ebenso
|
||||||
|
(er kann Angaben zur Person enthalten).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import delete, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.models import ResponseNote, UserAccount
|
||||||
|
|
||||||
|
MAX_LENGTH = 1000
|
||||||
|
|
||||||
|
Row = tuple[Any, str, list[dict[str, Any]]] # wie service.display_rows
|
||||||
|
|
||||||
|
|
||||||
|
def clean(raw: str) -> str:
|
||||||
|
"""Vermerk wie eingegeben, ohne Steuerzeichen (Zeilenumbrüche bleiben)."""
|
||||||
|
text = "".join(ch for ch in raw if ch in "\n\t" or ch.isprintable())
|
||||||
|
return text.replace("\r", "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def changed_labels(before: Sequence[Row], after: Sequence[Row]) -> list[str]:
|
||||||
|
"""Beschriftungen der Fragen, deren Antwort sich geändert hat."""
|
||||||
|
old = {q.id: (text, [f.get("id") for f in files]) for q, text, files in before}
|
||||||
|
changed = []
|
||||||
|
for question, text, files in after:
|
||||||
|
if old.get(question.id, ("", [])) != (text, [f.get("id") for f in files]):
|
||||||
|
changed.append(question.label)
|
||||||
|
return changed
|
||||||
|
|
||||||
|
|
||||||
|
def add(db: Session, response: Any, author: UserAccount, body: str,
|
||||||
|
changed: list[str]) -> ResponseNote:
|
||||||
|
note = ResponseNote(response_id=response.id, author_id=author.id, body=body,
|
||||||
|
changed=changed)
|
||||||
|
db.add(note)
|
||||||
|
return note
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class NoteView:
|
||||||
|
created_at: datetime
|
||||||
|
author: str | None # None: Konto inzwischen gelöscht
|
||||||
|
body: str
|
||||||
|
changed: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
def for_response(db: Session, response: Any) -> list[NoteView]:
|
||||||
|
rows = db.execute(
|
||||||
|
select(ResponseNote, UserAccount.display_name)
|
||||||
|
.outerjoin(UserAccount, UserAccount.id == ResponseNote.author_id)
|
||||||
|
.where(ResponseNote.response_id == response.id)
|
||||||
|
.order_by(ResponseNote.created_at, ResponseNote.id)
|
||||||
|
).all()
|
||||||
|
return [NoteView(n.created_at, name, n.body, list(n.changed or [])) for n, name in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def delete_for(db: Session, response_ids: Sequence[int]) -> None:
|
||||||
|
"""Beim Anonymisieren: Vermerke können Angaben zur Person enthalten."""
|
||||||
|
if response_ids:
|
||||||
|
db.execute(delete(ResponseNote).where(ResponseNote.response_id.in_(list(response_ids))))
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Minimaler Schreiber für OpenDocument-Tabellen (.ods, ODF 1.3), ohne zusätzliches Paket.
|
||||||
|
|
||||||
|
Ein Blatt mit Logo, Titel, Angaben und darunter der Tabelle: Kopfzeile fett mit 20 %
|
||||||
|
Grau und Autofilter, Spaltenbreiten fest. Für den Druck: Seitenvorlage mit Ausrichtung,
|
||||||
|
Rändern, "alle Spalten auf einer Seitenbreite", Fußzeile "Seite X von Y" und der
|
||||||
|
Kopfzeile der Tabelle als Wiederholungszeile.
|
||||||
|
|
||||||
|
Texte werden immer als Text geschrieben (nie als Formel); Zahlen als Zahl.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
import zipfile
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from decimal import Decimal
|
||||||
|
from xml.sax.saxutils import escape, quoteattr
|
||||||
|
|
||||||
|
Cell = str | int | float | Decimal | None
|
||||||
|
|
||||||
|
MIMETYPE = "application/vnd.oasis.opendocument.spreadsheet"
|
||||||
|
MAX_CELL = 32767
|
||||||
|
_ILLEGAL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
|
||||||
|
|
||||||
|
NS = (
|
||||||
|
'xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" '
|
||||||
|
'xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" '
|
||||||
|
'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" '
|
||||||
|
'xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" '
|
||||||
|
'xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" '
|
||||||
|
'xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" '
|
||||||
|
'xmlns:xlink="http://www.w3.org/1999/xlink" '
|
||||||
|
'xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" '
|
||||||
|
'xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" '
|
||||||
|
'xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" '
|
||||||
|
'office:version="1.3"'
|
||||||
|
)
|
||||||
|
CM_PER_CHAR = 0.21 # Spaltenbreite je Zeichen bei 10 pt
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Image:
|
||||||
|
png: bytes
|
||||||
|
width_cm: float
|
||||||
|
height_cm: float
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PageSetup:
|
||||||
|
landscape: bool = True
|
||||||
|
margins: tuple[float, float, float, float] = (1.0, 1.0, 2.0, 1.2) # links, rechts, oben, unten
|
||||||
|
fit_width: bool = True
|
||||||
|
footer: tuple[str, str] | None = None # Text vor Seitenzahl, zwischen Seitenzahl und Anzahl
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Sheet:
|
||||||
|
name: str
|
||||||
|
top: list[list[Cell]] # Zeilen über der Tabelle
|
||||||
|
header: list[Cell]
|
||||||
|
rows: list[list[Cell]]
|
||||||
|
widths: list[float] = field(default_factory=list) # in Zeichen
|
||||||
|
title_rows: set[int] = field(default_factory=set) # Indizes in `top`
|
||||||
|
image: Image | None = None
|
||||||
|
page: PageSetup = field(default_factory=PageSetup)
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: str) -> str:
|
||||||
|
return escape(_ILLEGAL.sub("", value)[:MAX_CELL])
|
||||||
|
|
||||||
|
|
||||||
|
def _paragraphs(value: str) -> str:
|
||||||
|
return "".join(f"<text:p>{_text(line)}</text:p>" for line in value.split("\n"))
|
||||||
|
|
||||||
|
|
||||||
|
def _cell(value: Cell, style: str = "", force: bool = False, inner: str = "") -> str:
|
||||||
|
attr = f' table:style-name="{style}"' if style else ""
|
||||||
|
if value is None or value == "":
|
||||||
|
if inner:
|
||||||
|
return f"<table:table-cell{attr}>{inner}</table:table-cell>"
|
||||||
|
return f"<table:table-cell{attr}/>" if (style and force) else "<table:table-cell/>"
|
||||||
|
if isinstance(value, bool):
|
||||||
|
value = str(value)
|
||||||
|
if isinstance(value, int | float | Decimal):
|
||||||
|
return (f'<table:table-cell{attr} office:value-type="float" office:value="{value}">'
|
||||||
|
f"<text:p>{value}</text:p>{inner}</table:table-cell>")
|
||||||
|
return (f'<table:table-cell{attr} office:value-type="string">'
|
||||||
|
f"{inner}{_paragraphs(str(value))}</table:table-cell>")
|
||||||
|
|
||||||
|
|
||||||
|
def column_name(index: int) -> str:
|
||||||
|
name = ""
|
||||||
|
index += 1
|
||||||
|
while index:
|
||||||
|
index, rest = divmod(index - 1, 26)
|
||||||
|
name = chr(65 + rest) + name
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def _sheet_name(name: str) -> str:
|
||||||
|
cleaned = re.sub(r"[\[\]*?:/\\'.]", " ", name).strip()[:31]
|
||||||
|
return cleaned or "Sheet1"
|
||||||
|
|
||||||
|
|
||||||
|
def _content(sheet: Sheet) -> str:
|
||||||
|
columns = max([len(sheet.header), *(len(r) for r in sheet.rows)], default=1)
|
||||||
|
widths = list(sheet.widths) + [10.0] * (columns - len(sheet.widths))
|
||||||
|
styles = "".join(
|
||||||
|
f'<style:style style:name="co{i}" style:family="table-column">'
|
||||||
|
f'<style:table-column-properties fo:break-before="auto" '
|
||||||
|
f'style:column-width="{w * CM_PER_CHAR:.2f}cm"/></style:style>'
|
||||||
|
for i, w in enumerate(widths[:columns])
|
||||||
|
)
|
||||||
|
styles += (
|
||||||
|
'<style:style style:name="ta1" style:family="table" style:master-page-name="Surveybox">'
|
||||||
|
'<style:table-properties table:display="true"/></style:style>'
|
||||||
|
'<style:style style:name="ro1" style:family="table-row">'
|
||||||
|
'<style:table-row-properties style:use-optimal-row-height="true"/></style:style>'
|
||||||
|
'<style:style style:name="roTitle" style:family="table-row">'
|
||||||
|
'<style:table-row-properties style:row-height="0.8cm"/></style:style>'
|
||||||
|
'<style:style style:name="ceHead" style:family="table-cell">'
|
||||||
|
'<style:table-cell-properties fo:background-color="#cccccc" fo:wrap-option="wrap" '
|
||||||
|
'style:vertical-align="top"/><style:text-properties fo:font-weight="bold"/>'
|
||||||
|
"</style:style>"
|
||||||
|
'<style:style style:name="ceTitle" style:family="table-cell">'
|
||||||
|
'<style:text-properties fo:font-size="14pt" fo:font-weight="bold"/></style:style>'
|
||||||
|
'<style:style style:name="ceData" style:family="table-cell">'
|
||||||
|
'<style:table-cell-properties fo:wrap-option="wrap" style:vertical-align="top"/>'
|
||||||
|
"</style:style>"
|
||||||
|
)
|
||||||
|
name = _sheet_name(sheet.name)
|
||||||
|
out = [f"<?xml version='1.0' encoding='UTF-8'?><office:document-content {NS}>",
|
||||||
|
f"<office:automatic-styles>{styles}</office:automatic-styles>",
|
||||||
|
"<office:body><office:spreadsheet>",
|
||||||
|
f"<table:table table:name={quoteattr(name)} table:style-name=\"ta1\">"]
|
||||||
|
out += [f'<table:table-column table:style-name="co{i}"/>' for i in range(columns)]
|
||||||
|
for index, row in enumerate(sheet.top):
|
||||||
|
inner = ""
|
||||||
|
if index == 0 and sheet.image is not None:
|
||||||
|
img = sheet.image
|
||||||
|
inner = (f'<draw:frame draw:name="Logo" draw:z-index="0" '
|
||||||
|
f'svg:width="{img.width_cm:.2f}cm" svg:height="{img.height_cm:.2f}cm" '
|
||||||
|
'svg:x="0cm" svg:y="0cm"><draw:image xlink:href="Pictures/logo.png" '
|
||||||
|
'xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/>'
|
||||||
|
"</draw:frame>")
|
||||||
|
title = index in sheet.title_rows
|
||||||
|
cells = [_cell(v, "ceTitle" if title else "") for v in row]
|
||||||
|
if inner:
|
||||||
|
first = row[0] if row else None
|
||||||
|
cells[:1] = [_cell(first, inner=inner)]
|
||||||
|
row_style = "roTitle" if title else "ro1"
|
||||||
|
out.append(f'<table:table-row table:style-name="{row_style}">'
|
||||||
|
f"{''.join(cells) or '<table:table-cell/>'}</table:table-row>")
|
||||||
|
head = "".join(_cell(v, "ceHead", force=True) for v in sheet.header)
|
||||||
|
head += "".join(_cell(None, "ceHead", force=True)
|
||||||
|
for _ in range(columns - len(sheet.header)))
|
||||||
|
out.append('<table:table-header-rows><table:table-row table:style-name="ro1">'
|
||||||
|
f"{head}</table:table-row></table:table-header-rows>")
|
||||||
|
for row in sheet.rows:
|
||||||
|
data = "".join(_cell(v, "ceData") for v in row)
|
||||||
|
out.append(f'<table:table-row table:style-name="ro1">'
|
||||||
|
f"{data or '<table:table-cell/>'}</table:table-row>")
|
||||||
|
out.append("</table:table>")
|
||||||
|
first = len(sheet.top) + 1
|
||||||
|
last = first + max(len(sheet.rows), 1)
|
||||||
|
target = f"{quoteattr(name)[1:-1]}"
|
||||||
|
ref = f"'{target}'" if " " in target else target
|
||||||
|
out.append('<table:database-ranges><table:database-range '
|
||||||
|
'table:name="__Anonymous_Sheet_DB__0" '
|
||||||
|
f'table:target-range-address="{ref}.A{first}:{ref}.'
|
||||||
|
f'{column_name(columns - 1)}{last}" table:display-filter-buttons="true"/>'
|
||||||
|
"</table:database-ranges>")
|
||||||
|
out.append("</office:spreadsheet></office:body></office:document-content>")
|
||||||
|
return "".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
def _styles(page: PageSetup) -> str:
|
||||||
|
left, right, top, bottom = page.margins
|
||||||
|
width, height = ("29.7cm", "21cm") if page.landscape else ("21cm", "29.7cm")
|
||||||
|
orientation = "landscape" if page.landscape else "portrait"
|
||||||
|
scale = ' style:scale-to-X="1" style:scale-to-Y="0" loext:scale-to-X="1" ' \
|
||||||
|
'loext:scale-to-Y="0"' if page.fit_width else ""
|
||||||
|
footer = '<style:footer style:display="false"/>'
|
||||||
|
footer_style = ""
|
||||||
|
if page.footer is not None:
|
||||||
|
before, between = page.footer
|
||||||
|
footer = ("<style:footer><style:region-center><text:p>"
|
||||||
|
f"{_text(before)}<text:page-number>1</text:page-number>{_text(between)}"
|
||||||
|
"<text:page-count>1</text:page-count></text:p></style:region-center>"
|
||||||
|
"</style:footer>")
|
||||||
|
footer_style = ('<style:footer-style><style:header-footer-properties '
|
||||||
|
'fo:min-height="0.4cm" fo:margin-top="0.2cm"/></style:footer-style>')
|
||||||
|
return (
|
||||||
|
f"<?xml version='1.0' encoding='UTF-8'?><office:document-styles {NS}>"
|
||||||
|
"<office:styles>"
|
||||||
|
'<style:default-style style:family="table-cell">'
|
||||||
|
'<style:text-properties fo:font-size="10pt"/></style:default-style>'
|
||||||
|
'<style:style style:name="Default" style:family="table-cell"/>'
|
||||||
|
"</office:styles><office:automatic-styles>"
|
||||||
|
'<style:page-layout style:name="pm1"><style:page-layout-properties '
|
||||||
|
f'fo:page-width="{width}" fo:page-height="{height}" '
|
||||||
|
f'style:print-orientation="{orientation}" fo:margin-top="{top}cm" '
|
||||||
|
f'fo:margin-bottom="{bottom}cm" fo:margin-left="{left}cm" '
|
||||||
|
f'fo:margin-right="{right}cm"{scale} '
|
||||||
|
'style:print="charts drawings objects zero-values"/>'
|
||||||
|
'<style:header-style/>'
|
||||||
|
f"{footer_style}</style:page-layout>"
|
||||||
|
"</office:automatic-styles><office:master-styles>"
|
||||||
|
'<style:master-page style:name="Surveybox" style:page-layout-name="pm1">'
|
||||||
|
f'<style:header style:display="false"/>{footer}</style:master-page>'
|
||||||
|
"</office:master-styles></office:document-styles>"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _manifest(with_image: bool) -> str:
|
||||||
|
entries = [
|
||||||
|
("/", MIMETYPE),
|
||||||
|
("content.xml", "text/xml"),
|
||||||
|
("styles.xml", "text/xml"),
|
||||||
|
("meta.xml", "text/xml"),
|
||||||
|
]
|
||||||
|
if with_image:
|
||||||
|
entries.append(("Pictures/logo.png", "image/png"))
|
||||||
|
files = "".join(
|
||||||
|
f'<manifest:file-entry manifest:full-path="{path}"'
|
||||||
|
+ (' manifest:version="1.3"' if path == "/" else "")
|
||||||
|
+ f' manifest:media-type="{kind}"/>'
|
||||||
|
for path, kind in entries
|
||||||
|
)
|
||||||
|
return ("<?xml version='1.0' encoding='UTF-8'?><manifest:manifest "
|
||||||
|
'xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" '
|
||||||
|
f'manifest:version="1.3">{files}</manifest:manifest>')
|
||||||
|
|
||||||
|
|
||||||
|
def _meta(title: str) -> str:
|
||||||
|
return (f"<?xml version='1.0' encoding='UTF-8'?><office:document-meta {NS}>"
|
||||||
|
"<office:meta><meta:generator>Surveybox</meta:generator>"
|
||||||
|
f'<dc:title xmlns:dc="http://purl.org/dc/elements/1.1/">{_text(title)}</dc:title>'
|
||||||
|
"</office:meta></office:document-meta>")
|
||||||
|
|
||||||
|
|
||||||
|
def document(sheet: Sheet, title: str = "") -> bytes:
|
||||||
|
buffer = io.BytesIO()
|
||||||
|
with zipfile.ZipFile(buffer, "w") as z:
|
||||||
|
# "mimetype" zuerst und unkomprimiert (ODF-Vorgabe)
|
||||||
|
z.writestr(zipfile.ZipInfo("mimetype"), MIMETYPE, compress_type=zipfile.ZIP_STORED)
|
||||||
|
z.writestr("content.xml", _content(sheet), compress_type=zipfile.ZIP_DEFLATED)
|
||||||
|
z.writestr("styles.xml", _styles(sheet.page), compress_type=zipfile.ZIP_DEFLATED)
|
||||||
|
z.writestr("meta.xml", _meta(title), compress_type=zipfile.ZIP_DEFLATED)
|
||||||
|
if sheet.image is not None:
|
||||||
|
z.writestr("Pictures/logo.png", sheet.image.png, compress_type=zipfile.ZIP_STORED)
|
||||||
|
z.writestr("META-INF/manifest.xml", _manifest(sheet.image is not None),
|
||||||
|
compress_type=zipfile.ZIP_DEFLATED)
|
||||||
|
return buffer.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def widths_for(columns: Sequence[Sequence[Cell]]) -> list[float]:
|
||||||
|
"""Breite je Spalte in Zeichen: längster Inhalt (8 bis 50). Die Kopfzelle zählt
|
||||||
|
höchstens mit 25 Zeichen, sie bricht um."""
|
||||||
|
result = []
|
||||||
|
for col in columns:
|
||||||
|
lengths = [max((len(p) for p in str(v).split("\n")), default=0)
|
||||||
|
for v in col[1:] if v is not None]
|
||||||
|
if col:
|
||||||
|
lengths.append(min(len(str(col[0] or "")), 25))
|
||||||
|
result.append(float(min(max(max(lengths, default=8), 8), 50)) + 2)
|
||||||
|
return result
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Teilnehmerlisten als PDF zum Ausdrucken (reportlab).
|
||||||
|
|
||||||
|
A4 hoch, Ränder wie beim XLSX-Export (oben 2 cm, unten 1,2 cm, links und rechts 1 cm).
|
||||||
|
Jede Seite trägt oben Logo und Titel, unten "Seite X von Y". Je Eintrag eines
|
||||||
|
Teilnahme-Feldes eine Tabelle mit Nummer und Name, auf Wunsch mit Spalte für
|
||||||
|
Unterschriften; freie Plätze erscheinen als leere Zeilen, die Warteliste darunter.
|
||||||
|
|
||||||
|
Schrift ist Bitstream Vera aus dem reportlab-Paket (eingebettet, als Teilmenge).
|
||||||
|
Zeichen, die sie nicht kennt, werden auf den Grundbuchstaben zurückgeführt (ř → r),
|
||||||
|
statt als Kästchen zu erscheinen. Texte der Benutzer werden für den Absatz-Parser von
|
||||||
|
reportlab maskiert; Markup aus Antworten wird nie ausgewertet.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import unicodedata
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from functools import cache
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
from xml.sax.saxutils import escape
|
||||||
|
|
||||||
|
from surveybox.i18n import gettext
|
||||||
|
|
||||||
|
DASH = "\N{EN DASH}"
|
||||||
|
MAX_FREE_ROWS = 100 # mehr leere Zeilen für freie Plätze druckt niemand aus
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Entry:
|
||||||
|
title: str
|
||||||
|
capacity: int | None
|
||||||
|
confirmed: list[str] = field(default_factory=list)
|
||||||
|
waiting: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Section:
|
||||||
|
title: str
|
||||||
|
entries: list[Entry]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Options:
|
||||||
|
signature: bool = False
|
||||||
|
page_per_entry: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
FONT = "SurveyboxSans"
|
||||||
|
FONT_BOLD = "SurveyboxSans-Bold"
|
||||||
|
|
||||||
|
|
||||||
|
def available() -> bool:
|
||||||
|
"""reportlab installiert? (Nach dem Update einmal scripts/lock.sh ausführen.)"""
|
||||||
|
import importlib.util
|
||||||
|
|
||||||
|
return importlib.util.find_spec("reportlab") is not None
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def _fonts() -> frozenset[int]:
|
||||||
|
"""Schrift einmal registrieren; liefert die Zeichen, die sie darstellen kann."""
|
||||||
|
import reportlab
|
||||||
|
from reportlab.lib.fonts import addMapping
|
||||||
|
from reportlab.pdfbase import pdfmetrics
|
||||||
|
from reportlab.pdfbase.ttfonts import TTFont
|
||||||
|
|
||||||
|
folder = Path(reportlab.__file__).parent / "fonts"
|
||||||
|
regular = TTFont(FONT, str(folder / "Vera.ttf"))
|
||||||
|
pdfmetrics.registerFont(regular)
|
||||||
|
pdfmetrics.registerFont(TTFont(FONT_BOLD, str(folder / "VeraBd.ttf")))
|
||||||
|
addMapping(FONT, 0, 0, FONT)
|
||||||
|
addMapping(FONT, 1, 0, FONT_BOLD)
|
||||||
|
return frozenset(regular.face.charToGlyph)
|
||||||
|
|
||||||
|
|
||||||
|
def printable(text: str) -> str:
|
||||||
|
"""Text so, dass die Schrift jedes Zeichen kennt (sonst Grundbuchstabe oder '?')."""
|
||||||
|
known = _fonts()
|
||||||
|
out = []
|
||||||
|
for ch in text:
|
||||||
|
if ch in "\r\n\t":
|
||||||
|
out.append(" ")
|
||||||
|
elif ord(ch) in known:
|
||||||
|
out.append(ch)
|
||||||
|
elif unicodedata.category(ch).startswith("C"):
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
base = "".join(c for c in unicodedata.normalize("NFKD", ch)
|
||||||
|
if ord(c) in known and not unicodedata.combining(c))
|
||||||
|
out.append(base or "?")
|
||||||
|
return "".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
def _para(text: str, style: Any) -> Any:
|
||||||
|
from reportlab.platypus import Paragraph
|
||||||
|
|
||||||
|
return Paragraph(escape(printable(text)), style)
|
||||||
|
|
||||||
|
|
||||||
|
def build(form_title: str, sections: Sequence[Section], info: Sequence[tuple[str, str]],
|
||||||
|
logo: bytes | None, options: Options) -> bytes:
|
||||||
|
_fonts()
|
||||||
|
from reportlab.lib import colors
|
||||||
|
from reportlab.lib.pagesizes import A4
|
||||||
|
from reportlab.lib.styles import ParagraphStyle
|
||||||
|
from reportlab.lib.units import cm
|
||||||
|
from reportlab.lib.utils import ImageReader
|
||||||
|
from reportlab.pdfgen import canvas as pdfcanvas
|
||||||
|
from reportlab.platypus import (
|
||||||
|
CondPageBreak,
|
||||||
|
PageBreak,
|
||||||
|
SimpleDocTemplate,
|
||||||
|
Spacer,
|
||||||
|
Table,
|
||||||
|
TableStyle,
|
||||||
|
)
|
||||||
|
|
||||||
|
base = ParagraphStyle("base", fontName=FONT, fontSize=10, leading=13)
|
||||||
|
small = ParagraphStyle("small", parent=base, fontSize=8.5, leading=11,
|
||||||
|
textColor=colors.HexColor("#555555"))
|
||||||
|
h1 = ParagraphStyle("h1", parent=base, fontName=FONT_BOLD, fontSize=15, leading=19,
|
||||||
|
spaceAfter=4)
|
||||||
|
h2 = ParagraphStyle("h2", parent=base, fontName=FONT_BOLD, fontSize=12.5, leading=16,
|
||||||
|
spaceBefore=10, spaceAfter=4, keepWithNext=1)
|
||||||
|
h3 = ParagraphStyle("h3", parent=base, fontName=FONT_BOLD, fontSize=11, leading=14,
|
||||||
|
spaceBefore=8, spaceAfter=3)
|
||||||
|
head = ParagraphStyle("head", parent=base, fontName=FONT_BOLD)
|
||||||
|
|
||||||
|
width, height = A4
|
||||||
|
left = right = 1 * cm
|
||||||
|
top, bottom = 2 * cm, 1.2 * cm
|
||||||
|
usable = width - left - right
|
||||||
|
logo_reader = ImageReader(io.BytesIO(logo)) if logo else None
|
||||||
|
title = printable(form_title)
|
||||||
|
|
||||||
|
def decorate(canvas: Any, page: int, pages: int) -> None:
|
||||||
|
canvas.saveState()
|
||||||
|
x = left
|
||||||
|
if logo_reader is not None:
|
||||||
|
iw, ih = logo_reader.getSize()
|
||||||
|
h = 1.0 * cm
|
||||||
|
w = iw * h / ih if ih else h
|
||||||
|
canvas.drawImage(logo_reader, x, height - top + 0.5 * cm, w, h, mask="auto")
|
||||||
|
x += w + 0.3 * cm
|
||||||
|
canvas.setFont(FONT, 9)
|
||||||
|
canvas.setFillColor(colors.HexColor("#555555"))
|
||||||
|
canvas.drawString(x, height - top + 0.85 * cm, title[:110])
|
||||||
|
canvas.drawCentredString(width / 2, bottom / 2,
|
||||||
|
gettext("Page %(page)s of %(pages)s")
|
||||||
|
% {"page": page, "pages": pages})
|
||||||
|
canvas.restoreState()
|
||||||
|
|
||||||
|
class NumberedCanvas(pdfcanvas.Canvas): # type: ignore[misc]
|
||||||
|
"""Merkt sich die Seiten, um am Ende "Seite X von Y" zu schreiben."""
|
||||||
|
|
||||||
|
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self._pages: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
def showPage(self) -> None:
|
||||||
|
self._pages.append(dict(self.__dict__))
|
||||||
|
self._startPage()
|
||||||
|
|
||||||
|
def save(self) -> None:
|
||||||
|
total = len(self._pages)
|
||||||
|
for number, state in enumerate(self._pages, 1):
|
||||||
|
self.__dict__.update(state)
|
||||||
|
decorate(self, number, total)
|
||||||
|
super().showPage()
|
||||||
|
super().save()
|
||||||
|
|
||||||
|
number_w = 1.2 * cm
|
||||||
|
if options.signature:
|
||||||
|
name_w = (usable - number_w) * 0.55
|
||||||
|
widths = [number_w, name_w, usable - number_w - name_w]
|
||||||
|
header = [gettext("No."), gettext("Name"), gettext("Signature")]
|
||||||
|
else:
|
||||||
|
widths = [number_w, usable - number_w]
|
||||||
|
header = [gettext("No."), gettext("Name")]
|
||||||
|
style = TableStyle([
|
||||||
|
("FONT", (0, 0), (-1, -1), FONT, 10),
|
||||||
|
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#CCCCCC")),
|
||||||
|
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#888888")),
|
||||||
|
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
|
||||||
|
("ALIGN", (0, 0), (0, -1), "RIGHT"),
|
||||||
|
("TOPPADDING", (0, 1), (-1, -1), 5 if options.signature else 3),
|
||||||
|
("BOTTOMPADDING", (0, 1), (-1, -1), 5 if options.signature else 3),
|
||||||
|
])
|
||||||
|
|
||||||
|
def table(names: Sequence[str], free: int) -> Any:
|
||||||
|
rows: list[list[Any]] = [[_para(h, head) for h in header]]
|
||||||
|
for number, name in enumerate(names, 1):
|
||||||
|
rows.append([str(number), _para(name, base)] + ([""] if options.signature else []))
|
||||||
|
for number in range(len(names) + 1, len(names) + free + 1):
|
||||||
|
rows.append([str(number), ""] + ([""] if options.signature else []))
|
||||||
|
result = Table(rows, colWidths=widths, repeatRows=1)
|
||||||
|
result.setStyle(style)
|
||||||
|
return result
|
||||||
|
|
||||||
|
story: list[Any] = [_para(form_title, h1)]
|
||||||
|
story += [_para(f"{label}: {value}", small) for label, value in info]
|
||||||
|
first = True
|
||||||
|
for section in sections:
|
||||||
|
if section.title:
|
||||||
|
story.append(_para(section.title, h2))
|
||||||
|
for entry in section.entries:
|
||||||
|
if options.page_per_entry and not first:
|
||||||
|
story.append(PageBreak())
|
||||||
|
if section.title:
|
||||||
|
story.append(_para(section.title, small))
|
||||||
|
first = False
|
||||||
|
story.append(CondPageBreak(3.5 * cm)) # Überschrift nicht allein am Seitenende
|
||||||
|
if entry.title:
|
||||||
|
count = len(entry.confirmed)
|
||||||
|
taken = (gettext("%(taken)s of %(places)s places taken")
|
||||||
|
% {"taken": count, "places": entry.capacity}
|
||||||
|
if entry.capacity else
|
||||||
|
gettext("%(taken)s signed up") % {"taken": count})
|
||||||
|
story.append(_para(f"{entry.title} {DASH} {taken}", h3))
|
||||||
|
else:
|
||||||
|
story.append(Spacer(1, 6))
|
||||||
|
free = 0
|
||||||
|
if entry.capacity:
|
||||||
|
free = min(max(entry.capacity - len(entry.confirmed), 0), MAX_FREE_ROWS)
|
||||||
|
if entry.confirmed or free:
|
||||||
|
story.append(table(entry.confirmed, free))
|
||||||
|
else:
|
||||||
|
story.append(_para(gettext("Nobody has signed up yet."), small))
|
||||||
|
if entry.waiting:
|
||||||
|
story.append(CondPageBreak(3 * cm))
|
||||||
|
story.append(Spacer(1, 6))
|
||||||
|
story.append(_para(gettext("Waiting list"), head))
|
||||||
|
story.append(Spacer(1, 2))
|
||||||
|
story.append(table(entry.waiting, 0))
|
||||||
|
story.append(Spacer(1, 8))
|
||||||
|
|
||||||
|
buffer = io.BytesIO()
|
||||||
|
doc = SimpleDocTemplate(
|
||||||
|
buffer, pagesize=A4, leftMargin=left, rightMargin=right, topMargin=top,
|
||||||
|
bottomMargin=bottom, title=title, author="Surveybox", creator="Surveybox",
|
||||||
|
subject=gettext("Participant lists"),
|
||||||
|
)
|
||||||
|
doc.build(story, canvasmaker=NumberedCanvas)
|
||||||
|
return buffer.getvalue()
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""PDF-Ausgaben der Auswertung (reportlab).
|
||||||
|
|
||||||
|
- `answers_table`: dieselbe Tabelle wie im XLSX-Export (eine Zeile je Antwort, eine
|
||||||
|
Spalte je Frage), A4 quer, alle Spalten auf einer Seitenbreite: Spalten werden nach
|
||||||
|
Inhalt verteilt, lange Texte umbrochen, bei vielen Spalten wird die Schrift kleiner.
|
||||||
|
- `participant_lists`: je Eintrag eines Teilnahme-Feldes eine Liste mit Nummer und
|
||||||
|
Name (freie Plätze als leere Zeilen, Warteliste darunter), A4 hoch.
|
||||||
|
|
||||||
|
Beide: Ränder oben 2 cm, unten 1,2 cm, links und rechts 1 cm; jede Seite trägt oben
|
||||||
|
Logo und Titel, unten "Seite X von Y"; die Kopfzeile von Tabellen wiederholt sich.
|
||||||
|
|
||||||
|
Schrift ist Bitstream Vera aus dem reportlab-Paket (eingebettet, als Teilmenge).
|
||||||
|
Zeichen, die sie nicht kennt, werden auf den Grundbuchstaben zurückgeführt (ř → r),
|
||||||
|
statt als Kästchen zu erscheinen. Texte der Benutzer werden für den Absatz-Parser von
|
||||||
|
reportlab maskiert; Markup aus Antworten wird nie ausgewertet.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import unicodedata
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from decimal import Decimal
|
||||||
|
from functools import cache
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
from xml.sax.saxutils import escape
|
||||||
|
|
||||||
|
from surveybox.i18n import gettext
|
||||||
|
|
||||||
|
DASH = "\N{EN DASH}"
|
||||||
|
MAX_FREE_ROWS = 100 # mehr leere Zeilen für freie Plätze druckt niemand aus
|
||||||
|
FONT = "SurveyboxSans"
|
||||||
|
FONT_BOLD = "SurveyboxSans-Bold"
|
||||||
|
CM = 72 / 2.54
|
||||||
|
MARGINS = (1 * CM, 1 * CM, 2 * CM, 1.2 * CM) # links, rechts, oben, unten
|
||||||
|
|
||||||
|
Cell = str | int | float | Decimal | None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Entry:
|
||||||
|
title: str
|
||||||
|
capacity: int | None
|
||||||
|
confirmed: list[str] = field(default_factory=list)
|
||||||
|
waiting: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Section:
|
||||||
|
title: str
|
||||||
|
entries: list[Entry]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Options:
|
||||||
|
signature: bool = False
|
||||||
|
page_per_entry: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
def available() -> bool:
|
||||||
|
"""reportlab installiert? (Nach dem Update einmal scripts/lock.sh ausführen.)"""
|
||||||
|
import importlib.util
|
||||||
|
|
||||||
|
return importlib.util.find_spec("reportlab") is not None
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def _fonts() -> frozenset[int]:
|
||||||
|
"""Schrift einmal registrieren; liefert die Zeichen, die sie darstellen kann."""
|
||||||
|
import reportlab
|
||||||
|
from reportlab.lib.fonts import addMapping
|
||||||
|
from reportlab.pdfbase import pdfmetrics
|
||||||
|
from reportlab.pdfbase.ttfonts import TTFont
|
||||||
|
|
||||||
|
folder = Path(reportlab.__file__).parent / "fonts"
|
||||||
|
regular = TTFont(FONT, str(folder / "Vera.ttf"))
|
||||||
|
pdfmetrics.registerFont(regular)
|
||||||
|
pdfmetrics.registerFont(TTFont(FONT_BOLD, str(folder / "VeraBd.ttf")))
|
||||||
|
addMapping(FONT, 0, 0, FONT)
|
||||||
|
addMapping(FONT, 1, 0, FONT_BOLD)
|
||||||
|
return frozenset(regular.face.charToGlyph)
|
||||||
|
|
||||||
|
|
||||||
|
def printable(text: str, keep_lines: bool = False) -> str:
|
||||||
|
"""Text so, dass die Schrift jedes Zeichen kennt (sonst Grundbuchstabe oder '?')."""
|
||||||
|
known = _fonts()
|
||||||
|
out = []
|
||||||
|
for ch in text:
|
||||||
|
if ch == "\n" and keep_lines:
|
||||||
|
out.append(ch)
|
||||||
|
elif ch in "\r\n\t":
|
||||||
|
out.append(" ")
|
||||||
|
elif ord(ch) in known:
|
||||||
|
out.append(ch)
|
||||||
|
elif unicodedata.category(ch).startswith("C"):
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
base = "".join(c for c in unicodedata.normalize("NFKD", ch)
|
||||||
|
if ord(c) in known and not unicodedata.combining(c))
|
||||||
|
out.append(base or "?")
|
||||||
|
return "".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
def _markup(text: str) -> str:
|
||||||
|
"""Für reportlab-Absätze: maskiert, Zeilenumbrüche bleiben erhalten."""
|
||||||
|
return escape(printable(text, keep_lines=True)).replace("\n", "<br/>")
|
||||||
|
|
||||||
|
|
||||||
|
def _para(text: str, style: Any) -> Any:
|
||||||
|
from reportlab.platypus import Paragraph
|
||||||
|
|
||||||
|
return Paragraph(_markup(text), style)
|
||||||
|
|
||||||
|
|
||||||
|
def _styles(size: float = 10) -> dict[str, Any]:
|
||||||
|
from reportlab.lib import colors
|
||||||
|
from reportlab.lib.styles import ParagraphStyle
|
||||||
|
|
||||||
|
base = ParagraphStyle("base", fontName=FONT, fontSize=size, leading=size * 1.25)
|
||||||
|
return {
|
||||||
|
"base": base,
|
||||||
|
"head": ParagraphStyle("head", parent=base, fontName=FONT_BOLD),
|
||||||
|
"small": ParagraphStyle("small", fontName=FONT, fontSize=8.5, leading=11,
|
||||||
|
textColor=colors.HexColor("#555555")),
|
||||||
|
"h1": ParagraphStyle("h1", fontName=FONT_BOLD, fontSize=15, leading=19, spaceAfter=4),
|
||||||
|
"h2": ParagraphStyle("h2", fontName=FONT_BOLD, fontSize=12.5, leading=16,
|
||||||
|
spaceBefore=10, spaceAfter=4, keepWithNext=1),
|
||||||
|
"h3": ParagraphStyle("h3", fontName=FONT_BOLD, fontSize=11, leading=14,
|
||||||
|
spaceBefore=8, spaceAfter=3),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _table_style(size: float, padding: float) -> Any:
|
||||||
|
from reportlab.lib import colors
|
||||||
|
from reportlab.platypus import TableStyle
|
||||||
|
|
||||||
|
return TableStyle([
|
||||||
|
("FONT", (0, 0), (-1, -1), FONT, size),
|
||||||
|
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#CCCCCC")),
|
||||||
|
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#888888")),
|
||||||
|
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
||||||
|
("LEFTPADDING", (0, 0), (-1, -1), 3),
|
||||||
|
("RIGHTPADDING", (0, 0), (-1, -1), 3),
|
||||||
|
("TOPPADDING", (0, 1), (-1, -1), padding),
|
||||||
|
("BOTTOMPADDING", (0, 1), (-1, -1), padding),
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
def _render(story: list[Any], form_title: str, logo: bytes | None, landscape: bool,
|
||||||
|
subject: str) -> bytes:
|
||||||
|
"""Seiten mit Logo und Titel oben, "Seite X von Y" unten."""
|
||||||
|
from reportlab.lib import colors
|
||||||
|
from reportlab.lib.pagesizes import A4
|
||||||
|
from reportlab.lib.pagesizes import landscape as turn
|
||||||
|
from reportlab.lib.utils import ImageReader
|
||||||
|
from reportlab.pdfgen import canvas as pdfcanvas
|
||||||
|
from reportlab.platypus import SimpleDocTemplate
|
||||||
|
|
||||||
|
size = turn(A4) if landscape else A4
|
||||||
|
width, height = size
|
||||||
|
left, right, top, bottom = MARGINS
|
||||||
|
logo_reader = ImageReader(io.BytesIO(logo)) if logo else None
|
||||||
|
title = printable(form_title)
|
||||||
|
|
||||||
|
def decorate(canvas: Any, page: int, pages: int) -> None:
|
||||||
|
canvas.saveState()
|
||||||
|
x = left
|
||||||
|
if logo_reader is not None:
|
||||||
|
iw, ih = logo_reader.getSize()
|
||||||
|
h = 1.0 * CM
|
||||||
|
w = iw * h / ih if ih else h
|
||||||
|
canvas.drawImage(logo_reader, x, height - top + 0.5 * CM, w, h, mask="auto")
|
||||||
|
x += w + 0.3 * CM
|
||||||
|
canvas.setFont(FONT, 9)
|
||||||
|
canvas.setFillColor(colors.HexColor("#555555"))
|
||||||
|
canvas.drawString(x, height - top + 0.85 * CM, title[:150])
|
||||||
|
canvas.drawCentredString(width / 2, bottom / 2,
|
||||||
|
gettext("Page %(page)s of %(pages)s")
|
||||||
|
% {"page": page, "pages": pages})
|
||||||
|
canvas.restoreState()
|
||||||
|
|
||||||
|
class NumberedCanvas(pdfcanvas.Canvas): # type: ignore[misc]
|
||||||
|
"""Merkt sich die Seiten, um am Ende "Seite X von Y" zu schreiben."""
|
||||||
|
|
||||||
|
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self._pages: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
def showPage(self) -> None:
|
||||||
|
self._pages.append(dict(self.__dict__))
|
||||||
|
self._startPage()
|
||||||
|
|
||||||
|
def save(self) -> None:
|
||||||
|
total = len(self._pages)
|
||||||
|
for number, state in enumerate(self._pages, 1):
|
||||||
|
self.__dict__.update(state)
|
||||||
|
decorate(self, number, total)
|
||||||
|
super().showPage()
|
||||||
|
super().save()
|
||||||
|
|
||||||
|
buffer = io.BytesIO()
|
||||||
|
doc = SimpleDocTemplate(
|
||||||
|
buffer, pagesize=size, leftMargin=left, rightMargin=right, topMargin=top,
|
||||||
|
bottomMargin=bottom, title=title, author="Surveybox", creator="Surveybox",
|
||||||
|
subject=subject,
|
||||||
|
)
|
||||||
|
doc.build(story, canvasmaker=NumberedCanvas)
|
||||||
|
return buffer.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _intro(form_title: str, info: Sequence[tuple[str, str]]) -> list[Any]:
|
||||||
|
styles = _styles()
|
||||||
|
return [_para(form_title, styles["h1"]),
|
||||||
|
*[_para(f"{label}: {value}", styles["small"]) for label, value in info]]
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Antworten als Tabelle (wie XLSX)
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _text_of(value: Cell) -> str:
|
||||||
|
return "" if value is None else str(value)
|
||||||
|
|
||||||
|
|
||||||
|
def column_widths(headers: Sequence[str], rows: Sequence[Sequence[Cell]], usable: float,
|
||||||
|
size: float) -> list[float] | None:
|
||||||
|
"""Spaltenbreiten (pt), die zusammen genau die Seitenbreite füllen; None: passt in
|
||||||
|
dieser Schriftgröße nicht, ohne Wörter zu zerreißen."""
|
||||||
|
from reportlab.pdfbase.pdfmetrics import stringWidth
|
||||||
|
|
||||||
|
pad = 6.5
|
||||||
|
count = len(headers)
|
||||||
|
natural, minimum = [0.0] * count, [0.0] * count
|
||||||
|
for index, row in enumerate([list(headers), *rows]):
|
||||||
|
font = FONT_BOLD if index == 0 else FONT
|
||||||
|
for i in range(count):
|
||||||
|
text = printable(_text_of(row[i] if i < len(row) else None), keep_lines=True)
|
||||||
|
for line in text.split("\n"):
|
||||||
|
natural[i] = max(natural[i], stringWidth(line, font, size) + pad)
|
||||||
|
for word in line.split():
|
||||||
|
minimum[i] = max(minimum[i], stringWidth(word, font, size) + pad)
|
||||||
|
cap = usable * 0.4
|
||||||
|
natural = [min(max(n, 1.0 * CM), cap) for n in natural]
|
||||||
|
minimum = [min(max(m, 0.9 * CM), n) for m, n in zip(minimum, natural, strict=True)]
|
||||||
|
if sum(minimum) > usable:
|
||||||
|
return None
|
||||||
|
if sum(natural) <= usable:
|
||||||
|
extra = usable - sum(natural)
|
||||||
|
total = sum(natural)
|
||||||
|
return [n + extra * n / total for n in natural]
|
||||||
|
spare = usable - sum(minimum)
|
||||||
|
wish = [n - m for n, m in zip(natural, minimum, strict=True)]
|
||||||
|
total = sum(wish) or 1.0
|
||||||
|
return [m + spare * w / total for m, w in zip(minimum, wish, strict=True)]
|
||||||
|
|
||||||
|
|
||||||
|
def answers_table(form_title: str, headers: Sequence[str], rows: Sequence[Sequence[Cell]],
|
||||||
|
info: Sequence[tuple[str, str]], logo: bytes | None) -> bytes:
|
||||||
|
"""Alle Antworten als Tabelle, A4 quer, alle Spalten auf einer Seitenbreite."""
|
||||||
|
_fonts()
|
||||||
|
from reportlab.lib.pagesizes import A4
|
||||||
|
from reportlab.platypus import Spacer, Table
|
||||||
|
|
||||||
|
usable = A4[1] - MARGINS[0] - MARGINS[1]
|
||||||
|
size, widths = 9.0, None
|
||||||
|
for size in (9.0, 8.0, 7.0, 6.0, 5.0):
|
||||||
|
widths = column_widths(headers, rows, usable, size)
|
||||||
|
if widths is not None:
|
||||||
|
break
|
||||||
|
styles = _styles(size)
|
||||||
|
breakable = widths is None
|
||||||
|
if widths is None: # sehr viele Spalten: gleichmäßig verteilen, Wörter dürfen brechen
|
||||||
|
widths = [usable / max(len(headers), 1)] * len(headers)
|
||||||
|
cell_style = styles["base"]
|
||||||
|
head_style = styles["head"]
|
||||||
|
if breakable:
|
||||||
|
cell_style.wordWrap = head_style.wordWrap = "CJK"
|
||||||
|
data: list[list[Any]] = [[_para(h, head_style) for h in headers]]
|
||||||
|
for row in rows:
|
||||||
|
data.append([_para(_text_of(row[i] if i < len(row) else None), cell_style)
|
||||||
|
for i in range(len(headers))])
|
||||||
|
table = Table(data, colWidths=widths, repeatRows=1)
|
||||||
|
table.setStyle(_table_style(size, 2))
|
||||||
|
story = [*_intro(form_title, info), Spacer(1, 8), table]
|
||||||
|
return _render(story, form_title, logo, landscape=True, subject=gettext("Answers"))
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Teilnehmerlisten
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def participant_lists(form_title: str, sections: Sequence[Section],
|
||||||
|
info: Sequence[tuple[str, str]], logo: bytes | None,
|
||||||
|
options: Options) -> bytes:
|
||||||
|
_fonts()
|
||||||
|
from reportlab.lib.pagesizes import A4
|
||||||
|
from reportlab.platypus import CondPageBreak, PageBreak, Spacer, Table
|
||||||
|
|
||||||
|
styles = _styles()
|
||||||
|
usable = A4[0] - MARGINS[0] - MARGINS[1]
|
||||||
|
number_w = 1.2 * CM
|
||||||
|
if options.signature:
|
||||||
|
name_w = (usable - number_w) * 0.55
|
||||||
|
widths = [number_w, name_w, usable - number_w - name_w]
|
||||||
|
header = [gettext("No."), gettext("Name"), gettext("Signature")]
|
||||||
|
else:
|
||||||
|
widths = [number_w, usable - number_w]
|
||||||
|
header = [gettext("No."), gettext("Name")]
|
||||||
|
style = _table_style(10, 5 if options.signature else 3)
|
||||||
|
style.add("ALIGN", (0, 0), (0, -1), "RIGHT")
|
||||||
|
style.add("VALIGN", (0, 0), (-1, -1), "MIDDLE")
|
||||||
|
|
||||||
|
def table(names: Sequence[str], free: int) -> Any:
|
||||||
|
rows: list[list[Any]] = [[_para(h, styles["head"]) for h in header]]
|
||||||
|
for number, name in enumerate(names, 1):
|
||||||
|
rows.append([str(number), _para(name, styles["base"])]
|
||||||
|
+ ([""] if options.signature else []))
|
||||||
|
for number in range(len(names) + 1, len(names) + free + 1):
|
||||||
|
rows.append([str(number), ""] + ([""] if options.signature else []))
|
||||||
|
result = Table(rows, colWidths=widths, repeatRows=1)
|
||||||
|
result.setStyle(style)
|
||||||
|
return result
|
||||||
|
|
||||||
|
story: list[Any] = _intro(form_title, info)
|
||||||
|
first = True
|
||||||
|
for section in sections:
|
||||||
|
if section.title:
|
||||||
|
story.append(_para(section.title, styles["h2"]))
|
||||||
|
for entry in section.entries:
|
||||||
|
if options.page_per_entry and not first:
|
||||||
|
story.append(PageBreak())
|
||||||
|
if section.title:
|
||||||
|
story.append(_para(section.title, styles["small"]))
|
||||||
|
first = False
|
||||||
|
story.append(CondPageBreak(3.5 * CM)) # Überschrift nicht allein am Seitenende
|
||||||
|
count = len(entry.confirmed)
|
||||||
|
taken = (gettext("%(taken)s of %(places)s places taken")
|
||||||
|
% {"taken": count, "places": entry.capacity}
|
||||||
|
if entry.capacity else
|
||||||
|
gettext("%(taken)s signed up") % {"taken": count})
|
||||||
|
story.append(_para(f"{entry.title} {DASH} {taken}", styles["h3"]))
|
||||||
|
free = 0
|
||||||
|
if entry.capacity:
|
||||||
|
free = min(max(entry.capacity - len(entry.confirmed), 0), MAX_FREE_ROWS)
|
||||||
|
if entry.confirmed or free:
|
||||||
|
story.append(table(entry.confirmed, free))
|
||||||
|
else:
|
||||||
|
story.append(_para(gettext("Nobody has signed up yet."), styles["small"]))
|
||||||
|
if entry.waiting:
|
||||||
|
story.append(CondPageBreak(3 * CM))
|
||||||
|
story.append(Spacer(1, 6))
|
||||||
|
story.append(_para(gettext("Waiting list"), styles["head"]))
|
||||||
|
story.append(Spacer(1, 2))
|
||||||
|
story.append(table(entry.waiting, 0))
|
||||||
|
story.append(Spacer(1, 8))
|
||||||
|
return _render(story, form_title, logo, landscape=False,
|
||||||
|
subject=gettext("Participant lists"))
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Ergebnisse für Teilnehmende (Einstellung "Teilnehmende sehen die Ergebnisse").
|
||||||
|
|
||||||
|
Gezeigt werden nur Zahlen: Balken, Summen, Durchschnitte, Abstimmungen, Reihenfolgen und
|
||||||
|
die Belegung von Teilnahme-Feldern. Freitexte, Datei-Fragen und als personenbezogen
|
||||||
|
markierte Fragen erscheinen nie. Namen bei Teilnahme-Feldern nur, wenn das Formular sie
|
||||||
|
ohnehin allen zeigt (forms.booking.names_for_form).
|
||||||
|
|
||||||
|
Wer teilgenommen hat, erkennt Surveybox am Konto, am persönlichen Link oder (bei Gästen)
|
||||||
|
an einem Cookie, das nach dem Absenden für eine Woche gesetzt wird. Es enthält nur eine
|
||||||
|
Prüfsumme über das Formular, nichts zur Person.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
from datetime import timedelta
|
||||||
|
from typing import Any
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.forms.service import FillState, fill_state, summary
|
||||||
|
from surveybox.models import Form
|
||||||
|
|
||||||
|
COOKIE_AGE = timedelta(days=7)
|
||||||
|
|
||||||
|
|
||||||
|
def visible(form: Form, participated: bool) -> bool:
|
||||||
|
"""Darf diese Person die Ergebnisse jetzt sehen (Zugang zum Formular vorausgesetzt)?"""
|
||||||
|
if form.results_visibility == "after_submit":
|
||||||
|
return participated
|
||||||
|
if form.results_visibility == "after_close":
|
||||||
|
return fill_state(form) == FillState.CLOSED
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def offered(form: Form) -> bool:
|
||||||
|
return form.results_visibility in ("after_submit", "after_close")
|
||||||
|
|
||||||
|
|
||||||
|
def build(db: Session, form: Form, tz: ZoneInfo) -> list[Any]:
|
||||||
|
"""Auswertung je Frage, ohne Freitexte und personenbezogene Fragen."""
|
||||||
|
result = []
|
||||||
|
for item in summary(db, form, None, tz):
|
||||||
|
if item.question.personal:
|
||||||
|
continue
|
||||||
|
item.texts = []
|
||||||
|
item.more_texts = 0
|
||||||
|
if (item.bars or item.poll_rows or item.slot_rows or item.average is not None
|
||||||
|
or item.total is not None or item.note):
|
||||||
|
result.append(item)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def cookie_name(form: Form) -> str:
|
||||||
|
return f"surveybox_done_{form.share_token[:16]}"
|
||||||
|
|
||||||
|
|
||||||
|
def cookie_value(secret: str, form: Form) -> str:
|
||||||
|
message = f"done:{form.public_id}".encode()
|
||||||
|
return hmac.new(secret.encode(), message, hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def cookie_valid(secret: str, form: Form, value: str | None) -> bool:
|
||||||
|
return bool(value) and hmac.compare_digest(value or "", cookie_value(secret, form))
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Erinnerung vor dem Enddatum an Eingeladene, die noch nicht teilgenommen haben.
|
||||||
|
|
||||||
|
Eingeladen sind die Personen der Zugriffsliste eines Formulars mit Zugriff
|
||||||
|
"Ausgewählte Benutzer und Gruppen" (Gruppen samt Untergruppen). Der Ersteller
|
||||||
|
legt je Formular fest, wie viele Tage vor dem Enddatum erinnert wird; ohne
|
||||||
|
Angabe gibt es keine Erinnerung. Jede Person bekommt sie höchstens einmal je
|
||||||
|
Enddatum.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.accounts import scope
|
||||||
|
from surveybox.forms.service import FillState, fill_state, has_participated
|
||||||
|
from surveybox.mail import notify
|
||||||
|
from surveybox.models import Form, FormAccess, FormAccessEntry, FormStatus, UserAccount
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
MAX_DAYS = 30
|
||||||
|
|
||||||
|
|
||||||
|
def invited(db: Session, form: Form) -> list[UserAccount]:
|
||||||
|
rows = db.execute(
|
||||||
|
select(FormAccessEntry.user_id, FormAccessEntry.group_id)
|
||||||
|
.where(FormAccessEntry.form_id == form.id)
|
||||||
|
).all()
|
||||||
|
ids = {uid for uid, _ in rows if uid is not None}
|
||||||
|
groups = [gid for _, gid in rows if gid is not None]
|
||||||
|
if groups:
|
||||||
|
tree = scope.load_tree(db)
|
||||||
|
ids.update(u.id for u in scope.users_in_groups(db, scope.descendants(tree, groups)))
|
||||||
|
if not ids:
|
||||||
|
return []
|
||||||
|
return list(db.scalars(
|
||||||
|
select(UserAccount)
|
||||||
|
.where(UserAccount.id.in_(ids), UserAccount.is_active.is_(True))
|
||||||
|
.order_by(UserAccount.id)
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
def _closes_text(form: Form, settings: Settings, language: str) -> str:
|
||||||
|
from babel.dates import format_datetime
|
||||||
|
|
||||||
|
assert form.closes_at is not None # noqa: S101 - vom Aufrufer geprüft
|
||||||
|
text: str = format_datetime(form.closes_at.astimezone(settings.tz), format="medium",
|
||||||
|
locale=language)
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def run_due(db: Session, settings: Settings, now: datetime) -> int:
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
forms = db.scalars(
|
||||||
|
select(Form).where(
|
||||||
|
Form.is_template.is_(False),
|
||||||
|
Form.status == FormStatus.OPEN,
|
||||||
|
Form.access == FormAccess.RESTRICTED,
|
||||||
|
Form.reminder_days.is_not(None),
|
||||||
|
Form.closes_at > now,
|
||||||
|
)
|
||||||
|
).all()
|
||||||
|
sent = 0
|
||||||
|
for form in forms:
|
||||||
|
assert form.closes_at is not None and form.reminder_days is not None # noqa: S101
|
||||||
|
if now < form.closes_at - timedelta(days=form.reminder_days):
|
||||||
|
continue
|
||||||
|
if fill_state(form, now) != FillState.OPEN:
|
||||||
|
continue
|
||||||
|
for user in invited(db, form):
|
||||||
|
if has_participated(db, secret, form, user):
|
||||||
|
continue
|
||||||
|
if notify.send(
|
||||||
|
db, settings, user, kind="reminder", event="reminder", form=form,
|
||||||
|
context={"link": notify.form_link(settings, form),
|
||||||
|
"closes": _closes_text(form, settings,
|
||||||
|
notify.language_of(user, settings))},
|
||||||
|
dedupe_key=f"reminder:{form.id}:{form.closes_at.isoformat()}:{user.id}",
|
||||||
|
):
|
||||||
|
sent += 1
|
||||||
|
return sent
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Löschfristen: Antworten nach Ende des Formulars anonymisieren oder löschen.
|
||||||
|
|
||||||
|
Die Frist läuft ab dem Ende des Formulars: dem Enddatum oder dem Zeitpunkt, an dem
|
||||||
|
es von Hand geschlossen wurde. Ohne eigene Frist gilt der Standard der Instanz
|
||||||
|
(2 Jahre, in den Einstellungen änderbar). Was danach passiert, legt das Formular
|
||||||
|
fest (deletion_mode):
|
||||||
|
|
||||||
|
- anonymisieren: Verknüpfung zur Person entfernen (Konto, Gast-Adresse,
|
||||||
|
persönlicher Link), Antworten auf personenbezogene Fragen und deren Dateien
|
||||||
|
löschen. Die übrigen Antworten bleiben für das Ergebnis.
|
||||||
|
- löschen: die Antworten vollständig löschen.
|
||||||
|
|
||||||
|
In beiden Fällen verschwinden die Merker gegen doppelte Teilnahme, der
|
||||||
|
Versandstand der Folge-Mails und die Autorenangaben der Kommentare (beim Löschen
|
||||||
|
die Kommentare selbst).
|
||||||
|
|
||||||
|
Der Eigentümer bekommt 14 Tage vorher eine Mail. Kam der Hinweis später (etwa
|
||||||
|
bei einer kurzen Frist), wartet die Löschung mindestens sieben Tage nach dem
|
||||||
|
Hinweis, damit noch Zeit für einen Export bleibt.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
from sqlalchemy import delete, exists, select, update
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.accounts import audit
|
||||||
|
from surveybox.forms import notes
|
||||||
|
from surveybox.models import (
|
||||||
|
Answer,
|
||||||
|
AppSetting,
|
||||||
|
Comment,
|
||||||
|
Followup,
|
||||||
|
FollowupDelivery,
|
||||||
|
Form,
|
||||||
|
FormParticipation,
|
||||||
|
FormStatus,
|
||||||
|
MediaFile,
|
||||||
|
MediaKind,
|
||||||
|
Response,
|
||||||
|
)
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
KEY = "privacy"
|
||||||
|
DEFAULT_DAYS = 730
|
||||||
|
MIN_DAYS, MAX_DAYS = 1, 3650
|
||||||
|
NOTICE_BEFORE = timedelta(days=14)
|
||||||
|
GRACE_AFTER_NOTICE = timedelta(days=7)
|
||||||
|
MODE_ANONYMIZE = "anonymize"
|
||||||
|
MODE_DELETE = "delete"
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Standardfrist der Instanz
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def default_days(db: Session) -> int:
|
||||||
|
row = db.get(AppSetting, KEY)
|
||||||
|
value = (row.value or {}).get("retention_days") if row is not None else None
|
||||||
|
return value if isinstance(value, int) and MIN_DAYS <= value <= MAX_DAYS else DEFAULT_DAYS
|
||||||
|
|
||||||
|
|
||||||
|
def set_default_days(db: Session, days: int) -> None:
|
||||||
|
if not MIN_DAYS <= days <= MAX_DAYS:
|
||||||
|
raise ValueError("retention_invalid")
|
||||||
|
row = db.get(AppSetting, KEY)
|
||||||
|
if row is None:
|
||||||
|
db.add(AppSetting(key=KEY, value={"retention_days": days}))
|
||||||
|
else:
|
||||||
|
row.value = {**(row.value or {}), "retention_days": days}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Fristen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def ended_at(form: Form, now: datetime) -> datetime | None:
|
||||||
|
"""Ende des Formulars; None, solange es nicht beendet ist (oder Entwurf/Vorlage)."""
|
||||||
|
if form.is_template:
|
||||||
|
return None
|
||||||
|
if form.status == FormStatus.CLOSED:
|
||||||
|
return form.closed_at or form.closes_at or form.updated_at
|
||||||
|
if form.status == FormStatus.OPEN and form.closes_at is not None and form.closes_at <= now:
|
||||||
|
return form.closes_at
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def days_for(db: Session, form: Form) -> int:
|
||||||
|
return form.retention_days or default_days(db)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Schedule:
|
||||||
|
ended: datetime
|
||||||
|
due: datetime # Fristende laut Einstellung
|
||||||
|
mode: str
|
||||||
|
|
||||||
|
def effective(self, notified_at: datetime | None) -> datetime | None:
|
||||||
|
"""Wann tatsächlich gelöscht wird; None, solange der Hinweis noch fehlt."""
|
||||||
|
if notified_at is None or notified_at < self.ended:
|
||||||
|
return None
|
||||||
|
return max(self.due, notified_at + GRACE_AFTER_NOTICE)
|
||||||
|
|
||||||
|
|
||||||
|
def schedule(db: Session, form: Form, now: datetime) -> Schedule | None:
|
||||||
|
ended = ended_at(form, now)
|
||||||
|
if ended is None:
|
||||||
|
return None
|
||||||
|
mode = MODE_DELETE if form.deletion_mode == MODE_DELETE else MODE_ANONYMIZE
|
||||||
|
return Schedule(ended, ended + timedelta(days=days_for(db, form)), mode)
|
||||||
|
|
||||||
|
|
||||||
|
def planned_date(db: Session, form: Form, now: datetime | None = None) -> datetime | None:
|
||||||
|
"""Für die Anzeige: voraussichtlicher Zeitpunkt der Löschung."""
|
||||||
|
now = now or datetime.now(UTC)
|
||||||
|
plan = schedule(db, form, now)
|
||||||
|
if plan is None:
|
||||||
|
return None
|
||||||
|
when = plan.effective(form.retention_notified_at)
|
||||||
|
if when is not None:
|
||||||
|
return when
|
||||||
|
# Der Hinweis steht noch aus; er geht 14 Tage vorher ab, spätestens beim nächsten Lauf
|
||||||
|
notice_at = max(now, plan.due - NOTICE_BEFORE)
|
||||||
|
return max(plan.due, notice_at + GRACE_AFTER_NOTICE)
|
||||||
|
|
||||||
|
|
||||||
|
def _pending(db: Session, form: Form) -> int:
|
||||||
|
"""Antworten, die noch einen Bezug zur Person haben (bzw. überhaupt existieren)."""
|
||||||
|
stmt = select(Response.id).where(Response.form_id == form.id)
|
||||||
|
if form.deletion_mode != MODE_DELETE:
|
||||||
|
stmt = stmt.where(Response.anonymized_at.is_(None))
|
||||||
|
return len(db.scalars(stmt).all())
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Anonymisieren und Löschen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def personal_question_ids(form: Form) -> list[int]:
|
||||||
|
return [q.id for q in form.questions if q.personal]
|
||||||
|
|
||||||
|
|
||||||
|
def anonymize_responses(
|
||||||
|
db: Session, form: Form, response_ids: list[int], now: datetime
|
||||||
|
) -> int:
|
||||||
|
"""Bezug zur Person entfernen; personenbezogene Antworten und ihre Dateien löschen."""
|
||||||
|
if not response_ids:
|
||||||
|
return 0
|
||||||
|
personal = personal_question_ids(form)
|
||||||
|
if personal:
|
||||||
|
db.execute(delete(Answer).where(
|
||||||
|
Answer.response_id.in_(response_ids), Answer.question_id.in_(personal)))
|
||||||
|
db.execute(delete(MediaFile).where(
|
||||||
|
MediaFile.response_id.in_(response_ids), MediaFile.question_id.in_(personal),
|
||||||
|
MediaFile.kind == MediaKind.UPLOAD))
|
||||||
|
notes.delete_for(db, response_ids)
|
||||||
|
result = db.execute(
|
||||||
|
update(Response).where(Response.id.in_(response_ids)).values(
|
||||||
|
user_id=None, guest_contact_id=None, access_hash=None, consent_at=None,
|
||||||
|
anonymized_at=now,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return int(result.rowcount or 0) # type: ignore[attr-defined]
|
||||||
|
|
||||||
|
|
||||||
|
def delete_responses(db: Session, response_ids: list[int]) -> int:
|
||||||
|
"""Antworten vollständig löschen (Antworten, Plätze und Dateien hängen per CASCADE)."""
|
||||||
|
if not response_ids:
|
||||||
|
return 0
|
||||||
|
result = db.execute(delete(Response).where(Response.id.in_(response_ids)))
|
||||||
|
return int(result.rowcount or 0) # type: ignore[attr-defined]
|
||||||
|
|
||||||
|
|
||||||
|
def _clear_form_traces(db: Session, form: Form, mode: str) -> None:
|
||||||
|
"""Merker, Versandstand und Kommentar-Autoren des Formulars entfernen."""
|
||||||
|
db.execute(delete(FormParticipation).where(FormParticipation.form_id == form.id))
|
||||||
|
db.execute(delete(FollowupDelivery).where(FollowupDelivery.followup_id.in_(
|
||||||
|
select(Followup.id).where(Followup.form_id == form.id))))
|
||||||
|
if mode == MODE_DELETE:
|
||||||
|
db.execute(delete(Comment).where(Comment.form_id == form.id))
|
||||||
|
else:
|
||||||
|
db.execute(update(Comment).where(Comment.form_id == form.id).values(
|
||||||
|
user_id=None, guest_name=None, author_token=None))
|
||||||
|
|
||||||
|
|
||||||
|
def apply(db: Session, form: Form, now: datetime) -> int:
|
||||||
|
"""Frist ist abgelaufen: alle Antworten des Formulars behandeln."""
|
||||||
|
mode = MODE_DELETE if form.deletion_mode == MODE_DELETE else MODE_ANONYMIZE
|
||||||
|
stmt = select(Response.id).where(Response.form_id == form.id)
|
||||||
|
if mode == MODE_ANONYMIZE:
|
||||||
|
stmt = stmt.where(Response.anonymized_at.is_(None))
|
||||||
|
ids = list(db.scalars(stmt))
|
||||||
|
count = (
|
||||||
|
delete_responses(db, ids) if mode == MODE_DELETE
|
||||||
|
else anonymize_responses(db, form, ids, now)
|
||||||
|
)
|
||||||
|
_clear_form_traces(db, form, mode)
|
||||||
|
audit.record(db, "form.retention_applied", target_type="form", target_id=str(form.public_id),
|
||||||
|
details={"mode": mode, "responses": count})
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Worker
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _candidates(db: Session, now: datetime) -> list[Form]:
|
||||||
|
"""Beendete Formulare mit Antworten, die noch zu behandeln sind."""
|
||||||
|
unprocessed = exists().where(
|
||||||
|
Response.form_id == Form.id,
|
||||||
|
(Form.deletion_mode == MODE_DELETE) | Response.anonymized_at.is_(None),
|
||||||
|
)
|
||||||
|
return list(db.scalars(
|
||||||
|
select(Form).where(
|
||||||
|
Form.is_template.is_(False),
|
||||||
|
(Form.status == FormStatus.CLOSED)
|
||||||
|
| ((Form.status == FormStatus.OPEN) & (Form.closes_at <= now)),
|
||||||
|
unprocessed,
|
||||||
|
)
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
def run_due(
|
||||||
|
db: Session, settings: Settings, now: datetime, applied: list[str] | None = None
|
||||||
|
) -> tuple[int, int]:
|
||||||
|
"""Hinweise senden und fällige Fristen anwenden. Ergebnis: (Hinweise, Antworten).
|
||||||
|
|
||||||
|
`applied` sammelt die Kennungen der behandelten Formulare für das Löschjournal;
|
||||||
|
der Aufrufer trägt sie nach dem Commit ein.
|
||||||
|
"""
|
||||||
|
from surveybox.mail import notify
|
||||||
|
|
||||||
|
notices = handled = 0
|
||||||
|
for form in _candidates(db, now):
|
||||||
|
plan = schedule(db, form, now)
|
||||||
|
if plan is None:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
with db.begin_nested(): # ein fehlerhaftes Formular hält die anderen nicht auf
|
||||||
|
notified = form.retention_notified_at
|
||||||
|
if plan.due - NOTICE_BEFORE <= now and (notified is None or notified < plan.ended):
|
||||||
|
notify.retention_notice(db, settings, form, plan.mode,
|
||||||
|
max(plan.due, now + GRACE_AFTER_NOTICE),
|
||||||
|
_pending(db, form))
|
||||||
|
form.retention_notified_at = notified = now
|
||||||
|
notices += 1
|
||||||
|
when = plan.effective(notified)
|
||||||
|
if when is not None and when <= now:
|
||||||
|
handled += apply(db, form, now)
|
||||||
|
if applied is not None:
|
||||||
|
applied.append(str(form.public_id))
|
||||||
|
except Exception:
|
||||||
|
log.exception("Löschfrist für Formular %s konnte nicht angewendet werden", form.id)
|
||||||
|
return notices, handled
|
||||||
@@ -0,0 +1,900 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Formulare anlegen, bearbeiten, freigeben, ausfüllen.
|
||||||
|
|
||||||
|
Wie bei den Konten ändern die Funktionen nur die übergebene Datenbanksitzung;
|
||||||
|
committen muss der Aufrufer.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from enum import StrEnum
|
||||||
|
from typing import Any
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from sqlalchemy import func, or_, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.accounts import scope
|
||||||
|
from surveybox.forms import conditions, groups, team, types
|
||||||
|
from surveybox.forms.types import Fields, Stored
|
||||||
|
from surveybox.mail import config as mail_config
|
||||||
|
from surveybox.models import (
|
||||||
|
Answer,
|
||||||
|
Form,
|
||||||
|
FormAccess,
|
||||||
|
FormAccessEntry,
|
||||||
|
FormParticipation,
|
||||||
|
FormStatus,
|
||||||
|
Question,
|
||||||
|
Response,
|
||||||
|
UserAccount,
|
||||||
|
UserGroup,
|
||||||
|
)
|
||||||
|
from surveybox.security import passwords
|
||||||
|
from surveybox.security.tokens import constant_time_equal, derive_key, keyed_hash, new_token
|
||||||
|
|
||||||
|
MAX_QUESTIONS = 300
|
||||||
|
MAX_TITLE = 200
|
||||||
|
MAX_TEXT = 5000
|
||||||
|
ANSWER_COLUMNS = (
|
||||||
|
"value_text",
|
||||||
|
"value_number",
|
||||||
|
"value_bool",
|
||||||
|
"value_date",
|
||||||
|
"value_time",
|
||||||
|
"value_datetime",
|
||||||
|
"value_json",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FormError(ValueError):
|
||||||
|
def __init__(self, code: str) -> None:
|
||||||
|
super().__init__(code)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
class FillAccess(StrEnum):
|
||||||
|
OK = "ok"
|
||||||
|
LOGIN = "login"
|
||||||
|
FORBIDDEN = "forbidden"
|
||||||
|
PASSWORD = "password" # noqa: S105 - Zustand, kein Passwort
|
||||||
|
|
||||||
|
|
||||||
|
class FillState(StrEnum):
|
||||||
|
DRAFT = "draft"
|
||||||
|
SCHEDULED = "scheduled"
|
||||||
|
OPEN = "open"
|
||||||
|
CLOSED = "closed"
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Hilfen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _first(fields: Fields, name: str) -> str:
|
||||||
|
values = fields.get(name) or []
|
||||||
|
return values[0] if values else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _text(fields: Fields, name: str, max_len: int) -> str | None:
|
||||||
|
value = _first(fields, name).replace("\r\n", "\n").strip()
|
||||||
|
if len(value) > max_len:
|
||||||
|
raise FormError("text_too_long")
|
||||||
|
return value or None
|
||||||
|
|
||||||
|
|
||||||
|
def _local_datetime(raw: str, tz: ZoneInfo) -> datetime | None:
|
||||||
|
raw = raw.strip()
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
value = datetime.fromisoformat(raw)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise FormError("datetime_invalid") from exc
|
||||||
|
return value.replace(tzinfo=tz) if value.tzinfo is None else value
|
||||||
|
|
||||||
|
|
||||||
|
def find_form(db: Session, public_id: str) -> Form | None:
|
||||||
|
try:
|
||||||
|
pid = uuid.UUID(public_id)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return db.scalar(select(Form).where(Form.public_id == pid))
|
||||||
|
|
||||||
|
|
||||||
|
def find_by_token(db: Session, token: str) -> Form | None:
|
||||||
|
if not token or len(token) > 64:
|
||||||
|
return None
|
||||||
|
return db.scalar(select(Form).where(Form.share_token == token))
|
||||||
|
|
||||||
|
|
||||||
|
def find_question(form: Form, question_id: int) -> Question | None:
|
||||||
|
return next((q for q in form.questions if q.id == question_id), None)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Formulare
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def create_form(
|
||||||
|
db: Session, owner: UserAccount, title: str, group: UserGroup | None = None,
|
||||||
|
*, restricted_to_group: bool = False,
|
||||||
|
) -> Form:
|
||||||
|
"""Neue Umfrage. Für Gruppenersteller: nur für die Gruppe freigegeben."""
|
||||||
|
title = " ".join(title.split())
|
||||||
|
if not title or len(title) > MAX_TITLE:
|
||||||
|
raise FormError("title_invalid")
|
||||||
|
form = Form(
|
||||||
|
title=title,
|
||||||
|
owner_id=owner.id,
|
||||||
|
share_token=new_token(16),
|
||||||
|
group_id=group.id if group is not None else None,
|
||||||
|
)
|
||||||
|
if restricted_to_group and group is not None:
|
||||||
|
form.access = FormAccess.RESTRICTED
|
||||||
|
db.add(form)
|
||||||
|
db.flush()
|
||||||
|
if restricted_to_group and group is not None:
|
||||||
|
db.add(FormAccessEntry(form_id=form.id, group_id=group.id))
|
||||||
|
return form
|
||||||
|
|
||||||
|
|
||||||
|
def response_count(db: Session, form: Form) -> int:
|
||||||
|
return int(
|
||||||
|
db.scalar(select(func.count()).select_from(Response).where(Response.form_id == form.id))
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def fill_state(form: Form, now: datetime | None = None) -> FillState:
|
||||||
|
now = now or datetime.now(UTC)
|
||||||
|
if form.status == FormStatus.DRAFT:
|
||||||
|
return FillState.DRAFT
|
||||||
|
if form.status == FormStatus.CLOSED:
|
||||||
|
return FillState.CLOSED
|
||||||
|
if form.opens_at is not None and now < form.opens_at:
|
||||||
|
return FillState.SCHEDULED
|
||||||
|
if form.closes_at is not None and now >= form.closes_at:
|
||||||
|
return FillState.CLOSED
|
||||||
|
return FillState.OPEN
|
||||||
|
|
||||||
|
|
||||||
|
def set_status(form: Form, status: str) -> None:
|
||||||
|
if status not in {s.value for s in FormStatus}:
|
||||||
|
raise FormError("status_invalid")
|
||||||
|
if form.is_template and status != FormStatus.DRAFT:
|
||||||
|
raise FormError("template_not_publishable")
|
||||||
|
if status == FormStatus.OPEN and not any(
|
||||||
|
types.TYPES[q.type].is_input for q in form.questions if q.type in types.TYPES
|
||||||
|
):
|
||||||
|
raise FormError("no_questions")
|
||||||
|
if status == FormStatus.OPEN and form.access == FormAccess.LINK_PASSWORD and (
|
||||||
|
form.link_password_hash is None
|
||||||
|
):
|
||||||
|
raise FormError("password_missing")
|
||||||
|
if status == FormStatus.CLOSED and form.status != FormStatus.CLOSED:
|
||||||
|
form.closed_at = datetime.now(UTC) # Beginn der Löschfrist
|
||||||
|
elif status != FormStatus.CLOSED:
|
||||||
|
form.closed_at = None
|
||||||
|
form.status = status
|
||||||
|
|
||||||
|
|
||||||
|
def update_settings(
|
||||||
|
db: Session,
|
||||||
|
form: Form,
|
||||||
|
fields: Fields,
|
||||||
|
tz: ZoneInfo,
|
||||||
|
has_responses: bool,
|
||||||
|
found: scope.Scope | None = None,
|
||||||
|
) -> None:
|
||||||
|
title = " ".join(_first(fields, "title").split())
|
||||||
|
if not title or len(title) > MAX_TITLE:
|
||||||
|
raise FormError("title_invalid")
|
||||||
|
opens_at = _local_datetime(_first(fields, "opens_at"), tz)
|
||||||
|
closes_at = _local_datetime(_first(fields, "closes_at"), tz)
|
||||||
|
if opens_at and closes_at and opens_at >= closes_at:
|
||||||
|
raise FormError("period_invalid")
|
||||||
|
|
||||||
|
access = _first(fields, "access")
|
||||||
|
if access not in {a.value for a in FormAccess}:
|
||||||
|
raise FormError("access_invalid")
|
||||||
|
if (
|
||||||
|
found is not None
|
||||||
|
and not found.global_creator
|
||||||
|
and access == FormAccess.USERS
|
||||||
|
and form.access != FormAccess.USERS
|
||||||
|
):
|
||||||
|
raise FormError("access_not_allowed") # nur Instanzrollen
|
||||||
|
if found is not None and "group" in fields:
|
||||||
|
raw_group = _first(fields, "group")
|
||||||
|
group = _group_by_public_id(db, raw_group) if raw_group else None
|
||||||
|
if raw_group and group is None:
|
||||||
|
raise FormError("group_invalid")
|
||||||
|
new_group_id = group.id if group is not None else None
|
||||||
|
if new_group_id != form.group_id and not found.may_create_in(new_group_id):
|
||||||
|
raise FormError("group_invalid")
|
||||||
|
form.group_id = new_group_id
|
||||||
|
new_password = _first(fields, "link_password")
|
||||||
|
if access == FormAccess.LINK_PASSWORD:
|
||||||
|
if new_password:
|
||||||
|
if len(new_password) < 6 or len(new_password) > 200:
|
||||||
|
raise FormError("link_password_invalid")
|
||||||
|
form.link_password_hash = passwords.hash_password(new_password)
|
||||||
|
elif form.link_password_hash is None:
|
||||||
|
raise FormError("password_missing")
|
||||||
|
else:
|
||||||
|
form.link_password_hash = None
|
||||||
|
|
||||||
|
anonymous = _first(fields, "anonymous") == "on"
|
||||||
|
if has_responses and anonymous != form.anonymous:
|
||||||
|
raise FormError("anonymous_locked")
|
||||||
|
|
||||||
|
retention_raw = _first(fields, "retention_days").strip()
|
||||||
|
retention: int | None = None
|
||||||
|
if retention_raw:
|
||||||
|
try:
|
||||||
|
retention = int(retention_raw)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise FormError("retention_invalid") from exc
|
||||||
|
if not 1 <= retention <= 3650:
|
||||||
|
raise FormError("retention_invalid")
|
||||||
|
|
||||||
|
def choice(name: str, allowed: set[str], default: str) -> str:
|
||||||
|
value = _first(fields, name)
|
||||||
|
return value if value in allowed else default
|
||||||
|
|
||||||
|
form.title = title
|
||||||
|
form.description = _text(fields, "description", MAX_TEXT)
|
||||||
|
form.opens_at = opens_at
|
||||||
|
form.closes_at = closes_at
|
||||||
|
form.access = access
|
||||||
|
form.allow_multiple = _first(fields, "allow_multiple") == "on"
|
||||||
|
form.allow_edit = choice("allow_edit", {"no", "until_close"}, "until_close")
|
||||||
|
form.anonymous = anonymous
|
||||||
|
form.guest_email = choice(
|
||||||
|
"guest_email", {"none", "optional", "required", "question"}, "none"
|
||||||
|
)
|
||||||
|
form.results_visibility = choice(
|
||||||
|
"results_visibility", {"never", "after_submit", "after_close"}, "never"
|
||||||
|
)
|
||||||
|
form.retention_days = retention
|
||||||
|
form.deletion_mode = choice("deletion_mode", {"delete", "anonymize"}, "anonymize")
|
||||||
|
form.calendar_mode = choice("calendar_mode", {"off", "file", "feed"}, "off")
|
||||||
|
if form.calendar_mode == "feed" and not form.calendar_token:
|
||||||
|
form.calendar_token = new_token(24)
|
||||||
|
form.comments_mode = choice("comments_mode", {"off", "moderated", "public"}, "moderated")
|
||||||
|
form.slot_names = choice("slot_names", {"off", "full", "short"}, "off")
|
||||||
|
form.comments_anonymous = _first(fields, "comments_anonymous") == "on"
|
||||||
|
form.comments_notify = _first(fields, "comments_notify") == "on"
|
||||||
|
try:
|
||||||
|
form.reply_to = mail_config.clean_address(_first(fields, "reply_to")) or None
|
||||||
|
except mail_config.MailConfigError as exc:
|
||||||
|
raise FormError("reply_to_invalid") from exc
|
||||||
|
raw_max = _first(fields, "slots_max_per_person").strip()
|
||||||
|
if raw_max:
|
||||||
|
try:
|
||||||
|
max_places = int(raw_max)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise FormError("slots_max_invalid") from exc
|
||||||
|
if not 1 <= max_places <= 1000:
|
||||||
|
raise FormError("slots_max_invalid")
|
||||||
|
form.slots_max_per_person = max_places
|
||||||
|
else:
|
||||||
|
form.slots_max_per_person = None
|
||||||
|
raw_days = _first(fields, "reminder_days").strip()
|
||||||
|
if raw_days:
|
||||||
|
try:
|
||||||
|
days = int(raw_days)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise FormError("reminder_days_invalid") from exc
|
||||||
|
if not 1 <= days <= 30:
|
||||||
|
raise FormError("reminder_days_invalid")
|
||||||
|
form.reminder_days = days
|
||||||
|
else:
|
||||||
|
form.reminder_days = None
|
||||||
|
form.privacy_notice = _text(fields, "privacy_notice", MAX_TEXT)
|
||||||
|
form.require_consent = _first(fields, "require_consent") == "on"
|
||||||
|
form.consent_text = _text(fields, "consent_text", 1000)
|
||||||
|
if form.require_consent and not form.consent_text:
|
||||||
|
raise FormError("consent_text_missing")
|
||||||
|
|
||||||
|
|
||||||
|
def access_entries(db: Session, form: Form) -> tuple[set[int], set[int]]:
|
||||||
|
rows = db.execute(
|
||||||
|
select(FormAccessEntry.user_id, FormAccessEntry.group_id).where(
|
||||||
|
FormAccessEntry.form_id == form.id
|
||||||
|
)
|
||||||
|
).all()
|
||||||
|
users = {u for u, _ in rows if u is not None}
|
||||||
|
groups = {g for _, g in rows if g is not None}
|
||||||
|
return users, groups
|
||||||
|
|
||||||
|
|
||||||
|
def _group_by_public_id(db: Session, value: str) -> UserGroup | None:
|
||||||
|
try:
|
||||||
|
pid = uuid.UUID(value)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return db.scalar(select(UserGroup).where(UserGroup.public_id == pid))
|
||||||
|
|
||||||
|
|
||||||
|
def set_access_entries(
|
||||||
|
db: Session,
|
||||||
|
form: Form,
|
||||||
|
user_public_ids: list[str],
|
||||||
|
group_public_ids: list[str],
|
||||||
|
found: scope.Scope | None = None,
|
||||||
|
) -> None:
|
||||||
|
def parse(ids: list[str]) -> list[uuid.UUID]:
|
||||||
|
result = []
|
||||||
|
for raw in ids:
|
||||||
|
try:
|
||||||
|
result.append(uuid.UUID(raw))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return result
|
||||||
|
|
||||||
|
user_ids = set(
|
||||||
|
db.scalars(select(UserAccount.id).where(UserAccount.public_id.in_(parse(user_public_ids))))
|
||||||
|
)
|
||||||
|
group_ids = set(
|
||||||
|
db.scalars(select(UserGroup.id).where(UserGroup.public_id.in_(parse(group_public_ids))))
|
||||||
|
)
|
||||||
|
if found is not None and not found.global_creator:
|
||||||
|
# Gruppenersteller: nur eigene Gruppen und deren Mitglieder
|
||||||
|
group_ids &= set(found.creating)
|
||||||
|
allowed_users = {u.id for u in scope.users_in_groups(db, found.creating)}
|
||||||
|
user_ids &= allowed_users
|
||||||
|
existing = list(db.scalars(select(FormAccessEntry).where(FormAccessEntry.form_id == form.id)))
|
||||||
|
for entry in existing:
|
||||||
|
db.delete(entry)
|
||||||
|
db.flush()
|
||||||
|
for uid in sorted(user_ids):
|
||||||
|
db.add(FormAccessEntry(form_id=form.id, user_id=uid))
|
||||||
|
for gid in sorted(group_ids):
|
||||||
|
db.add(FormAccessEntry(form_id=form.id, group_id=gid))
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Fragen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_question_fields(question: Question, fields: Fields) -> None:
|
||||||
|
qtype = types.TYPES[question.type]
|
||||||
|
label = _first(fields, "label").replace("\r\n", "\n").strip()
|
||||||
|
if question.type != "info":
|
||||||
|
label = " ".join(label.split())
|
||||||
|
max_label = MAX_TEXT if question.type == "info" else 500
|
||||||
|
if len(label) > max_label:
|
||||||
|
raise FormError("label_too_long")
|
||||||
|
if not label and question.type != "page_break":
|
||||||
|
raise FormError("label_missing")
|
||||||
|
try:
|
||||||
|
config = types.parse_config(question.type, fields)
|
||||||
|
except types.ConfigError as exc:
|
||||||
|
raise FormError(exc.code) from exc
|
||||||
|
question.label = label
|
||||||
|
with_help = qtype.is_input or question.type in types.WITH_HELP_TEXT
|
||||||
|
question.help_text = _text(fields, "help_text", 1000) if with_help else None
|
||||||
|
question.required = qtype.is_input and (
|
||||||
|
question.type == "participant_name" or _first(fields, "required") == "on"
|
||||||
|
)
|
||||||
|
question.personal = qtype.is_input and _first(fields, "personal") == "on"
|
||||||
|
# Medien und Bilder der Antwortmöglichkeiten bleiben beim Speichern erhalten;
|
||||||
|
# sie werden über eigene Formulare bearbeitet.
|
||||||
|
old = question.config or {}
|
||||||
|
if old.get("media"):
|
||||||
|
config["media"] = old["media"]
|
||||||
|
kept_keys = ("image", "proposed")
|
||||||
|
old_options = {o.get("id"): o for o in old.get("options") or []}
|
||||||
|
for option in config.get("options") or []:
|
||||||
|
previous = old_options.get(option["id"]) or {}
|
||||||
|
for key in kept_keys:
|
||||||
|
if previous.get(key):
|
||||||
|
option[key] = previous[key]
|
||||||
|
# Bestätigte Optionen einer Abstimmung bleiben, solange es sie gibt
|
||||||
|
if old.get("confirmed"):
|
||||||
|
ids = {o["id"] for o in config.get("options") or []}
|
||||||
|
config["confirmed"] = [c for c in old["confirmed"] if c in ids]
|
||||||
|
question.config = config
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_condition(form: Form, question: Question, fields: Fields) -> None:
|
||||||
|
try:
|
||||||
|
condition = conditions.parse(question, fields, form.questions)
|
||||||
|
except conditions.ConditionError as exc:
|
||||||
|
raise FormError(exc.code) from exc
|
||||||
|
config = dict(question.config)
|
||||||
|
if condition:
|
||||||
|
config["condition"] = condition
|
||||||
|
else:
|
||||||
|
config.pop("condition", None)
|
||||||
|
question.config = config
|
||||||
|
|
||||||
|
|
||||||
|
def add_question(
|
||||||
|
db: Session, form: Form, type_key: str, fields: Fields, after: Question | None = None
|
||||||
|
) -> Question:
|
||||||
|
"""Neue Frage am Ende oder direkt hinter `after` (z. B. in eine Gruppe)."""
|
||||||
|
if type_key not in types.TYPES:
|
||||||
|
raise FormError("type_invalid")
|
||||||
|
if len(form.questions) >= MAX_QUESTIONS:
|
||||||
|
raise FormError("too_many_questions")
|
||||||
|
position = max((q.position for q in form.questions), default=-1) + 1
|
||||||
|
question = Question(form_id=form.id, position=position, type=type_key, label="", config={})
|
||||||
|
_apply_question_fields(question, fields)
|
||||||
|
_apply_condition(form, question, fields)
|
||||||
|
if after is not None and after in form.questions:
|
||||||
|
index = form.questions.index(after) + 1
|
||||||
|
earlier = {q.id for q in form.questions[:index]}
|
||||||
|
if any(ref not in earlier for ref in conditions.references(question)):
|
||||||
|
raise FormError("order_condition")
|
||||||
|
form.questions.insert(index, question)
|
||||||
|
_renumber(form)
|
||||||
|
else:
|
||||||
|
form.questions.append(question)
|
||||||
|
form.updated_at = datetime.now(UTC)
|
||||||
|
return question
|
||||||
|
|
||||||
|
|
||||||
|
def insert_point(form: Form, group: Question) -> Question:
|
||||||
|
"""Letztes Mitglied der Gruppe, sonst die Gruppe selbst: dahinter einfügen."""
|
||||||
|
members = groups.resolve(form.questions).get(group.id) or []
|
||||||
|
return members[-1] if members else group
|
||||||
|
|
||||||
|
|
||||||
|
def update_question(form: Form, question: Question, fields: Fields) -> None:
|
||||||
|
_apply_question_fields(question, fields)
|
||||||
|
_apply_condition(form, question, fields)
|
||||||
|
form.updated_at = datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_question(form: Form, question: Question) -> int:
|
||||||
|
"""Löscht die Frage; Regeln anderer Fragen auf sie entfallen. Gibt deren Zahl zurück."""
|
||||||
|
affected = 0
|
||||||
|
for other in form.questions:
|
||||||
|
if other is question:
|
||||||
|
continue
|
||||||
|
cleaned = conditions.without_reference(other.config, question.id)
|
||||||
|
if cleaned is not None:
|
||||||
|
other.config = cleaned
|
||||||
|
affected += 1
|
||||||
|
form.questions.remove(question) # delete-orphan; Antworten löscht die Datenbank mit
|
||||||
|
_renumber(form)
|
||||||
|
form.updated_at = datetime.now(UTC)
|
||||||
|
return affected
|
||||||
|
|
||||||
|
|
||||||
|
def _renumber(form: Form) -> None:
|
||||||
|
for index, question in enumerate(form.questions):
|
||||||
|
question.position = index
|
||||||
|
|
||||||
|
|
||||||
|
def move_question(form: Form, question: Question, direction: str) -> bool:
|
||||||
|
"""False, wenn die neue Reihenfolge eine Bedingung brechen würde."""
|
||||||
|
ordered = list(form.questions)
|
||||||
|
index = ordered.index(question)
|
||||||
|
target = index - 1 if direction == "up" else index + 1
|
||||||
|
if not 0 <= target < len(ordered):
|
||||||
|
return True
|
||||||
|
ordered[index], ordered[target] = ordered[target], ordered[index]
|
||||||
|
if conditions.order_violations(ordered):
|
||||||
|
return False
|
||||||
|
for position, item in enumerate(ordered):
|
||||||
|
item.position = position
|
||||||
|
form.updated_at = datetime.now(UTC)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def reorder_questions(form: Form, order: list[int]) -> bool:
|
||||||
|
"""Neue Reihenfolge aus dem Designer; alle Fragen genau einmal, sonst nichts."""
|
||||||
|
by_id = {q.id: q for q in form.questions}
|
||||||
|
if sorted(order) != sorted(by_id):
|
||||||
|
return False
|
||||||
|
if conditions.order_violations([by_id[qid] for qid in order]):
|
||||||
|
return False
|
||||||
|
for position, question_id in enumerate(order):
|
||||||
|
by_id[question_id].position = position
|
||||||
|
form.updated_at = datetime.now(UTC)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def preview_version(form: Form) -> str:
|
||||||
|
"""Ändert sich, sobald sich am Formular etwas Sichtbares ändert."""
|
||||||
|
material = json.dumps(
|
||||||
|
[
|
||||||
|
form.title,
|
||||||
|
form.description,
|
||||||
|
form.privacy_notice,
|
||||||
|
form.require_consent,
|
||||||
|
form.consent_text,
|
||||||
|
[(q.id, q.position, q.type, q.label, q.help_text, q.required, q.config)
|
||||||
|
for q in form.questions],
|
||||||
|
],
|
||||||
|
sort_keys=True,
|
||||||
|
default=str,
|
||||||
|
)
|
||||||
|
return hashlib.sha256(material.encode()).hexdigest()[:16]
|
||||||
|
|
||||||
|
|
||||||
|
def answers_for_question(db: Session, question: Question) -> int:
|
||||||
|
return int(
|
||||||
|
db.scalar(
|
||||||
|
select(func.count()).select_from(Answer).where(Answer.question_id == question.id)
|
||||||
|
)
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Zugriff beim Ausfüllen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _password_cookie_key(secret_key: str) -> bytes:
|
||||||
|
return derive_key(secret_key, "form-link-password")
|
||||||
|
|
||||||
|
|
||||||
|
def password_cookie_name(form: Form) -> str:
|
||||||
|
return f"surveybox_fp_{form.id}"
|
||||||
|
|
||||||
|
|
||||||
|
def password_cookie_value(secret_key: str, form: Form) -> str:
|
||||||
|
# Hängt am Passwort-Hash: Ein neues Passwort macht alte Freigaben ungültig.
|
||||||
|
material = f"{form.id}:{form.link_password_hash or ''}"
|
||||||
|
return keyed_hash(_password_cookie_key(secret_key), material).hex()
|
||||||
|
|
||||||
|
|
||||||
|
def password_cookie_valid(secret_key: str, form: Form, value: str | None) -> bool:
|
||||||
|
return bool(value) and constant_time_equal(password_cookie_value(secret_key, form), value or "")
|
||||||
|
|
||||||
|
|
||||||
|
def check_link_password(form: Form, password: str) -> bool:
|
||||||
|
ok, _ = passwords.verify_password(form.link_password_hash, password)
|
||||||
|
return ok
|
||||||
|
|
||||||
|
|
||||||
|
def user_in_access_list(db: Session, form: Form, user: UserAccount) -> bool:
|
||||||
|
"""Direkt freigegeben oder Mitglied einer freigegebenen Gruppe (auch über Untergruppen)."""
|
||||||
|
groups = scope.member_groups(db, user.id)
|
||||||
|
return bool(
|
||||||
|
db.scalar(
|
||||||
|
select(FormAccessEntry.id)
|
||||||
|
.where(
|
||||||
|
FormAccessEntry.form_id == form.id,
|
||||||
|
or_(FormAccessEntry.user_id == user.id, FormAccessEntry.group_id.in_(groups)),
|
||||||
|
)
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def fill_access(
|
||||||
|
db: Session, form: Form, user: UserAccount | None, password_ok: bool
|
||||||
|
) -> FillAccess:
|
||||||
|
if form.access == FormAccess.LINK:
|
||||||
|
return FillAccess.OK
|
||||||
|
if form.access == FormAccess.LINK_PASSWORD:
|
||||||
|
return FillAccess.OK if password_ok else FillAccess.PASSWORD
|
||||||
|
if user is None:
|
||||||
|
return FillAccess.LOGIN
|
||||||
|
if form.access == FormAccess.USERS:
|
||||||
|
return FillAccess.OK
|
||||||
|
if team.level(db, user, form) >= team.Level.EDIT or user_in_access_list(db, form, user):
|
||||||
|
return FillAccess.OK
|
||||||
|
return FillAccess.FORBIDDEN
|
||||||
|
|
||||||
|
|
||||||
|
def open_forms_for(db: Session, user: UserAccount) -> list[Form]:
|
||||||
|
"""Offene Formulare, die der Benutzer ausfüllen darf (für die Startseite)."""
|
||||||
|
groups = scope.member_groups(db, user.id)
|
||||||
|
in_list = select(FormAccessEntry.form_id).where(
|
||||||
|
or_(FormAccessEntry.user_id == user.id, FormAccessEntry.group_id.in_(groups))
|
||||||
|
)
|
||||||
|
candidates = db.scalars(
|
||||||
|
select(Form)
|
||||||
|
.where(
|
||||||
|
Form.status == FormStatus.OPEN,
|
||||||
|
or_(Form.access == FormAccess.USERS, Form.id.in_(in_list)),
|
||||||
|
)
|
||||||
|
.order_by(Form.closes_at.asc().nulls_last(), Form.title)
|
||||||
|
.limit(100)
|
||||||
|
)
|
||||||
|
return [f for f in candidates if fill_state(f) == FillState.OPEN]
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Teilnahme
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def participation_marker(secret_key: str, form: Form, user: UserAccount) -> bytes:
|
||||||
|
return keyed_hash(derive_key(secret_key, "participation"), f"{form.id}:{user.id}")
|
||||||
|
|
||||||
|
|
||||||
|
def own_response(db: Session, form: Form, user: UserAccount) -> Response | None:
|
||||||
|
if form.anonymous:
|
||||||
|
return None
|
||||||
|
return db.scalar(
|
||||||
|
select(Response)
|
||||||
|
.where(Response.form_id == form.id, Response.user_id == user.id)
|
||||||
|
.order_by(Response.submitted_at.desc())
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def has_participated(db: Session, secret_key: str, form: Form, user: UserAccount) -> bool:
|
||||||
|
if form.anonymous:
|
||||||
|
marker = participation_marker(secret_key, form, user)
|
||||||
|
return db.get(FormParticipation, (form.id, marker)) is not None
|
||||||
|
return own_response(db, form, user) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def can_edit_response(form: Form, response: Response | None) -> bool:
|
||||||
|
return (
|
||||||
|
response is not None
|
||||||
|
and not form.anonymous
|
||||||
|
and form.allow_edit == "until_close"
|
||||||
|
and fill_state(form) == FillState.OPEN
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Validation:
|
||||||
|
stored: dict[int, Stored] = field(default_factory=dict)
|
||||||
|
errors: dict[int, str] = field(default_factory=dict)
|
||||||
|
consent_error: bool = False
|
||||||
|
hidden: set[int] = field(default_factory=set) # durch Bedingungen ausgeblendet
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ok(self) -> bool:
|
||||||
|
return not self.errors and not self.consent_error
|
||||||
|
|
||||||
|
|
||||||
|
def validate(
|
||||||
|
form: Form,
|
||||||
|
fields: Fields,
|
||||||
|
tz: ZoneInfo,
|
||||||
|
*,
|
||||||
|
check_consent: bool,
|
||||||
|
files: Mapping[int, list[dict[str, Any]]] | None = None,
|
||||||
|
file_errors: Mapping[int, str] | None = None,
|
||||||
|
) -> Validation:
|
||||||
|
result = Validation()
|
||||||
|
present = {qid for qid, items in (files or {}).items() if items}
|
||||||
|
result.hidden = conditions.hidden_ids(form.questions, fields, present)
|
||||||
|
by_group = groups.required_by_group(form.questions)
|
||||||
|
for question in form.questions:
|
||||||
|
qtype = types.TYPES.get(question.type)
|
||||||
|
if qtype is None or not qtype.is_input or question.id in result.hidden:
|
||||||
|
continue # Ausgeblendetes wird weder geprüft noch gespeichert
|
||||||
|
if file_errors and question.id in file_errors:
|
||||||
|
result.errors[question.id] = file_errors[question.id]
|
||||||
|
continue
|
||||||
|
parsed = types.parse_answer(
|
||||||
|
question, fields, tz, files,
|
||||||
|
required=False if question.id in by_group else None,
|
||||||
|
)
|
||||||
|
if parsed.error:
|
||||||
|
result.errors[question.id] = parsed.error
|
||||||
|
elif parsed.stored is not None:
|
||||||
|
result.stored[question.id] = parsed.stored
|
||||||
|
if form.slots_max_per_person:
|
||||||
|
chosen = [
|
||||||
|
(q.id, len((result.stored.get(q.id) or {}).get("value_json", {}).get("selected") or []))
|
||||||
|
for q in form.questions
|
||||||
|
if q.type == "slots" and q.id in result.stored
|
||||||
|
]
|
||||||
|
if sum(n for _, n in chosen) > form.slots_max_per_person:
|
||||||
|
result.errors[chosen[-1][0]] = "slots_too_many"
|
||||||
|
result.errors.update(groups.count_errors(form.questions, result.stored, result.hidden))
|
||||||
|
if check_consent and form.require_consent and _first(fields, "consent") != "on":
|
||||||
|
result.consent_error = True
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def apply_proposals(
|
||||||
|
db: Session, form: Form, fields: Fields, validation: Validation
|
||||||
|
) -> dict[int, str]:
|
||||||
|
"""Vorschläge neuer Abstimmungsoptionen übernehmen; der Vorschlag zählt als Ja.
|
||||||
|
|
||||||
|
Gibt Fehler je Frage zurück (dann wird nichts übernommen).
|
||||||
|
"""
|
||||||
|
errors: dict[int, str] = {}
|
||||||
|
for question in form.questions:
|
||||||
|
if question.type != "poll" or question.id in validation.hidden:
|
||||||
|
continue
|
||||||
|
cfg = question.config
|
||||||
|
if not cfg.get("allow_proposals"):
|
||||||
|
continue
|
||||||
|
name = f"q{question.id}_propose"
|
||||||
|
if cfg.get("mode") == "dates":
|
||||||
|
raw = {"option_date": [_first(fields, f"{name}_date")],
|
||||||
|
"option_time": [_first(fields, f"{name}_time")],
|
||||||
|
"option_duration": [""], "date_option_label": [""],
|
||||||
|
"date_option_id": [""]}
|
||||||
|
if not raw["option_date"][0]:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
option = types.parse_date_options(raw)[0]
|
||||||
|
except types.ConfigError:
|
||||||
|
errors[question.id] = "proposal_invalid"
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
text = " ".join(_first(fields, f"{name}_text").split())
|
||||||
|
if not text:
|
||||||
|
continue
|
||||||
|
if len(text) > types.MAX_PROPOSAL:
|
||||||
|
errors[question.id] = "proposal_invalid"
|
||||||
|
continue
|
||||||
|
option = {"id": types.new_option_id(), "label": text}
|
||||||
|
# Frage sperren: gleichzeitige Vorschläge überschreiben sich nicht
|
||||||
|
db.execute(select(Question.id).where(Question.id == question.id).with_for_update())
|
||||||
|
db.refresh(question)
|
||||||
|
options = list(question.config.get("options") or [])
|
||||||
|
if len(options) >= types.MAX_OPTIONS:
|
||||||
|
errors[question.id] = "options_too_many"
|
||||||
|
continue
|
||||||
|
option["proposed"] = True
|
||||||
|
options.append(option)
|
||||||
|
question.config = {**question.config, "options": options}
|
||||||
|
stored = validation.stored.setdefault(question.id, {"value_json": {"votes": {}}})
|
||||||
|
votes = dict((stored.get("value_json") or {}).get("votes") or {})
|
||||||
|
votes[option["id"]] = "yes"
|
||||||
|
stored["value_json"] = {"votes": votes}
|
||||||
|
return errors
|
||||||
|
|
||||||
|
|
||||||
|
def _answers(stored: Mapping[int, Stored]) -> list[Answer]:
|
||||||
|
return [Answer(question_id=qid, **values) for qid, values in stored.items()]
|
||||||
|
|
||||||
|
|
||||||
|
def submit(
|
||||||
|
db: Session,
|
||||||
|
secret_key: str,
|
||||||
|
form: Form,
|
||||||
|
user: UserAccount | None,
|
||||||
|
validation: Validation,
|
||||||
|
) -> Response:
|
||||||
|
if fill_state(form) != FillState.OPEN:
|
||||||
|
raise FormError("form_not_open")
|
||||||
|
if (
|
||||||
|
user is not None
|
||||||
|
and not form.allow_multiple
|
||||||
|
and has_participated(db, secret_key, form, user)
|
||||||
|
):
|
||||||
|
raise FormError("already_submitted")
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
response = Response(
|
||||||
|
form_id=form.id,
|
||||||
|
user_id=None if form.anonymous or user is None else user.id,
|
||||||
|
submitted_at=now,
|
||||||
|
consent_at=now if form.require_consent else None,
|
||||||
|
)
|
||||||
|
response.answers.extend(_answers(validation.stored))
|
||||||
|
db.add(response)
|
||||||
|
if form.anonymous and user is not None and not form.allow_multiple:
|
||||||
|
marker = participation_marker(secret_key, form, user)
|
||||||
|
db.add(FormParticipation(form_id=form.id, marker=marker))
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
def replace_answers(db: Session, response: Response, validation: Validation) -> None:
|
||||||
|
response.answers.clear()
|
||||||
|
db.flush()
|
||||||
|
response.answers.extend(_answers(validation.stored))
|
||||||
|
response.updated_at = datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def stored_of(answer: Answer) -> Stored:
|
||||||
|
return {col: getattr(answer, col) for col in ANSWER_COLUMNS if getattr(answer, col) is not None}
|
||||||
|
|
||||||
|
|
||||||
|
def fields_from_response(form: Form, response: Response, tz: ZoneInfo) -> dict[str, list[str]]:
|
||||||
|
by_question = {a.question_id: a for a in response.answers}
|
||||||
|
fields: dict[str, list[str]] = {}
|
||||||
|
for question in form.questions:
|
||||||
|
answer = by_question.get(question.id)
|
||||||
|
if answer is not None:
|
||||||
|
fields.update(types.raw_from_answer(question, stored_of(answer), tz))
|
||||||
|
return fields
|
||||||
|
|
||||||
|
|
||||||
|
def responses(db: Session, form: Form, limit: int = 500) -> list[tuple[Response, str | None]]:
|
||||||
|
rows = db.execute(
|
||||||
|
select(Response, UserAccount.display_name)
|
||||||
|
.outerjoin(UserAccount, UserAccount.id == Response.user_id)
|
||||||
|
.where(Response.form_id == form.id)
|
||||||
|
.order_by(Response.submitted_at.desc())
|
||||||
|
.limit(limit)
|
||||||
|
).all()
|
||||||
|
return [(r, name) for r, name in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def find_response(db: Session, form: Form, public_id: str) -> Response | None:
|
||||||
|
try:
|
||||||
|
pid = uuid.UUID(public_id)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return db.scalar(
|
||||||
|
select(Response).where(Response.form_id == form.id, Response.public_id == pid)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def display_rows(
|
||||||
|
form: Form, response: Response, tz: ZoneInfo
|
||||||
|
) -> list[tuple[Question, str, list[dict[str, Any]]]]:
|
||||||
|
"""Frage, Antwort als Text und bei Datei-Fragen die Dateien zum Herunterladen."""
|
||||||
|
by_question = {a.question_id: a for a in response.answers}
|
||||||
|
rows: list[tuple[Question, str, list[dict[str, Any]]]] = []
|
||||||
|
for question in form.questions:
|
||||||
|
qtype = types.TYPES.get(question.type)
|
||||||
|
if qtype is None or not qtype.is_input:
|
||||||
|
continue
|
||||||
|
answer = by_question.get(question.id)
|
||||||
|
stored = stored_of(answer) if answer else {}
|
||||||
|
text = types.display_answer(question, stored, tz) if answer else ""
|
||||||
|
files = list((stored.get("value_json") or {}).get("files") or [])
|
||||||
|
if question.type == "file_upload":
|
||||||
|
text = ""
|
||||||
|
rows.append((question, text, files if question.type == "file_upload" else []))
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def delete_form(db: Session, form: Form) -> None:
|
||||||
|
db.delete(form)
|
||||||
|
|
||||||
|
|
||||||
|
def form_summary(form: Form) -> dict[str, Any]:
|
||||||
|
"""Für das Protokoll: keine Inhalte, nur Kennzahlen."""
|
||||||
|
return {"questions": len(form.questions), "access": form.access, "status": form.status}
|
||||||
|
|
||||||
|
|
||||||
|
def summary(
|
||||||
|
db: Session, form: Form, responses: list[Response] | None = None,
|
||||||
|
tz: ZoneInfo | None = None,
|
||||||
|
) -> list[Any]:
|
||||||
|
"""Auswertung je Frage (siehe forms.summary); mit `responses` nur für diese Antworten."""
|
||||||
|
from surveybox.forms import booking
|
||||||
|
from surveybox.forms.summary import summarize
|
||||||
|
|
||||||
|
stmt = (
|
||||||
|
select(Answer)
|
||||||
|
.join(Response, Response.id == Answer.response_id)
|
||||||
|
.where(Response.form_id == form.id)
|
||||||
|
)
|
||||||
|
if responses is None:
|
||||||
|
places = booking.form_availability(db, form)
|
||||||
|
else:
|
||||||
|
ids = [r.id for r in responses]
|
||||||
|
stmt = stmt.where(Answer.response_id.in_(ids))
|
||||||
|
places = booking.availability_for(db, form, ids)
|
||||||
|
rows = db.execute(stmt).scalars()
|
||||||
|
return summarize(form.questions, ((a.question_id, stored_of(a)) for a in rows), places, tz)
|
||||||
|
|
||||||
|
|
||||||
|
def confirm_options(question: Question, option_ids: list[str]) -> None:
|
||||||
|
"""Abstimmung: bestätigte Optionen festlegen (z. B. der gewählte Termin)."""
|
||||||
|
valid = {o["id"] for o in types.options_of(question)}
|
||||||
|
question.config = {**question.config, "confirmed": [o for o in option_ids if o in valid]}
|
||||||
|
|
||||||
|
|
||||||
|
def calendar_events(form: Form) -> list[Any]:
|
||||||
|
from surveybox.forms import calendar
|
||||||
|
|
||||||
|
return calendar.confirmed_events(form.questions)
|
||||||
|
|
||||||
|
|
||||||
|
def find_by_calendar_token(db: Session, token: str) -> Form | None:
|
||||||
|
if not token or len(token) > 64:
|
||||||
|
return None
|
||||||
|
return db.scalar(select(Form).where(Form.calendar_token == token))
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Datenexport für Betroffene (Art. 15 und 20 DSGVO) als JSON.
|
||||||
|
|
||||||
|
Enthalten ist, was einer Person zugeordnet ist: Konto oder Gast-Adresse,
|
||||||
|
Antworten mit Plätzen, Kommentare, erhaltene Folge-Mails und das Mailprotokoll
|
||||||
|
(ohne Inhalte, die nach dem Versand gelöscht werden). Antworten in anonymen
|
||||||
|
Formularen und anonymisierte Antworten sind keiner Person zugeordnet und fehlen
|
||||||
|
deshalb. Hochgeladene Dateien erscheinen mit Name und Größe; den Inhalt gibt es
|
||||||
|
über die Antwort selbst.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from typing import Any
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from sqlalchemy import or_, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.forms import notes, service, types
|
||||||
|
from surveybox.i18n import N_, gettext
|
||||||
|
from surveybox.models import (
|
||||||
|
AuditEvent,
|
||||||
|
Booking,
|
||||||
|
Comment,
|
||||||
|
Followup,
|
||||||
|
FollowupDelivery,
|
||||||
|
Form,
|
||||||
|
FormMute,
|
||||||
|
GroupMember,
|
||||||
|
GuestContact,
|
||||||
|
MailMessage,
|
||||||
|
Response,
|
||||||
|
UserAccount,
|
||||||
|
UserGroup,
|
||||||
|
UserSession,
|
||||||
|
)
|
||||||
|
|
||||||
|
FORMAT_VERSION = 1
|
||||||
|
NOTE = N_(
|
||||||
|
"Answers in anonymous forms and anonymized answers cannot be attributed to a person "
|
||||||
|
"and are therefore not included."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _iso(value: datetime | None) -> str | None:
|
||||||
|
return value.astimezone(UTC).isoformat() if value is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def _response(db: Session, form: Form, response: Response, tz: ZoneInfo) -> dict[str, Any]:
|
||||||
|
answers = []
|
||||||
|
for question, text, files in service.display_rows(form, response, tz):
|
||||||
|
entry: dict[str, Any] = {"question": question.label, "answer": text}
|
||||||
|
if files:
|
||||||
|
entry["files"] = [{"name": f.get("name", ""), "size": f.get("size")} for f in files]
|
||||||
|
answers.append(entry)
|
||||||
|
questions = {q.id: q for q in form.questions}
|
||||||
|
places = []
|
||||||
|
for booking in db.scalars(select(Booking).where(Booking.response_id == response.id)
|
||||||
|
.order_by(Booking.id)):
|
||||||
|
question = questions.get(booking.question_id)
|
||||||
|
option = next((o for o in types.options_of(question) if o["id"] == booking.option_id),
|
||||||
|
None) if question is not None else None
|
||||||
|
places.append({
|
||||||
|
"question": question.label if question is not None else "",
|
||||||
|
"option": types.option_text(option) if option else booking.option_id,
|
||||||
|
"status": booking.status,
|
||||||
|
"since": _iso(booking.created_at),
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
"form": {"id": str(form.public_id), "title": form.title},
|
||||||
|
"id": str(response.public_id),
|
||||||
|
"submitted_at": _iso(response.submitted_at),
|
||||||
|
"updated_at": _iso(response.updated_at),
|
||||||
|
"consent_at": _iso(response.consent_at),
|
||||||
|
"answers": answers,
|
||||||
|
"places": places,
|
||||||
|
# Vermerke der Verwalter zu Änderungen an dieser Antwort (ohne deren Namen)
|
||||||
|
"notes": [{"created_at": _iso(n.created_at), "note": n.body, "changed": n.changed}
|
||||||
|
for n in notes.for_response(db, response)],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _responses(db: Session, rows: list[Response], tz: ZoneInfo) -> list[dict[str, Any]]:
|
||||||
|
result = []
|
||||||
|
for response in rows:
|
||||||
|
form = db.get(Form, response.form_id)
|
||||||
|
if form is not None:
|
||||||
|
result.append(_response(db, form, response, tz))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _followups(db: Session, recipient: str) -> list[dict[str, Any]]:
|
||||||
|
rows = db.execute(
|
||||||
|
select(FollowupDelivery, Followup, Form)
|
||||||
|
.join(Followup, Followup.id == FollowupDelivery.followup_id)
|
||||||
|
.join(Form, Form.id == Followup.form_id)
|
||||||
|
.where(FollowupDelivery.recipient == recipient)
|
||||||
|
.order_by(FollowupDelivery.sent_at)
|
||||||
|
).all()
|
||||||
|
return [{"form": form.title, "subject": followup.subject, "sent_at": _iso(delivery.sent_at)}
|
||||||
|
for delivery, followup, form in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def _mail_log(rows: list[MailMessage]) -> list[dict[str, Any]]:
|
||||||
|
return [{"kind": m.kind, "status": m.status, "created_at": _iso(m.created_at),
|
||||||
|
"sent_at": _iso(m.sent_at)} for m in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def _envelope(subject: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"format": "surveybox-subject-export",
|
||||||
|
"version": FORMAT_VERSION,
|
||||||
|
"created_at": _iso(datetime.now(UTC)),
|
||||||
|
"note": gettext(NOTE),
|
||||||
|
**subject,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def for_user(db: Session, user: UserAccount, tz: ZoneInfo) -> dict[str, Any]:
|
||||||
|
responses = list(db.scalars(select(Response).where(Response.user_id == user.id)
|
||||||
|
.order_by(Response.submitted_at)))
|
||||||
|
comments = db.execute(
|
||||||
|
select(Comment, Form).join(Form, Form.id == Comment.form_id)
|
||||||
|
.where(Comment.user_id == user.id).order_by(Comment.created_at)
|
||||||
|
).all()
|
||||||
|
groups = db.scalars(
|
||||||
|
select(UserGroup.name).join(GroupMember, GroupMember.group_id == UserGroup.id)
|
||||||
|
.where(GroupMember.user_id == user.id).order_by(UserGroup.name)
|
||||||
|
).all()
|
||||||
|
muted = db.scalars(
|
||||||
|
select(Form.title).join(FormMute, FormMute.form_id == Form.id)
|
||||||
|
.where(FormMute.user_id == user.id)
|
||||||
|
).all()
|
||||||
|
owned = db.scalars(select(Form).where(Form.owner_id == user.id).order_by(Form.created_at))
|
||||||
|
sessions = db.scalars(select(UserSession).where(UserSession.user_id == user.id)
|
||||||
|
.order_by(UserSession.created_at))
|
||||||
|
audit = db.scalars(
|
||||||
|
select(AuditEvent).where(or_(
|
||||||
|
AuditEvent.actor_id == user.id,
|
||||||
|
(AuditEvent.target_type == "user") & (AuditEvent.target_id == str(user.id)),
|
||||||
|
)).order_by(AuditEvent.occurred_at)
|
||||||
|
)
|
||||||
|
mails = list(db.scalars(select(MailMessage).where(MailMessage.user_id == user.id)
|
||||||
|
.order_by(MailMessage.created_at)))
|
||||||
|
return _envelope({
|
||||||
|
"account": {
|
||||||
|
"id": str(user.public_id),
|
||||||
|
"email": user.email,
|
||||||
|
"name": user.display_name,
|
||||||
|
"role": user.role,
|
||||||
|
"language": user.language,
|
||||||
|
"active": user.is_active,
|
||||||
|
"created_at": _iso(user.created_at),
|
||||||
|
"last_login_at": _iso(user.last_login_at),
|
||||||
|
"authenticator_app": user.has_totp,
|
||||||
|
"passkeys": [{"name": p.name, "created_at": _iso(p.created_at),
|
||||||
|
"last_used_at": _iso(p.last_used_at)} for p in user.passkeys],
|
||||||
|
"notifications": dict(user.notify_prefs or {}),
|
||||||
|
"muted_forms": list(muted),
|
||||||
|
"groups": list(groups),
|
||||||
|
},
|
||||||
|
"sessions": [{"browser": s.user_agent, "created_at": _iso(s.created_at),
|
||||||
|
"last_seen_at": _iso(s.last_seen_at)} for s in sessions],
|
||||||
|
"responses": _responses(db, responses, tz),
|
||||||
|
"comments": [{"form": form.title, "text": c.body, "status": c.status,
|
||||||
|
"created_at": _iso(c.created_at), "updated_at": _iso(c.updated_at)}
|
||||||
|
for c, form in comments],
|
||||||
|
"own_forms": [{"id": str(f.public_id), "title": f.title, "status": f.status,
|
||||||
|
"created_at": _iso(f.created_at)} for f in owned],
|
||||||
|
"followup_emails": _followups(db, f"u:{user.public_id}"),
|
||||||
|
"email_log": _mail_log(mails),
|
||||||
|
"activity_log": [{"action": e.action, "at": _iso(e.occurred_at)} for e in audit],
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def for_guest(db: Session, contact: GuestContact, tz: ZoneInfo) -> dict[str, Any]:
|
||||||
|
responses = list(db.scalars(select(Response).where(Response.guest_contact_id == contact.id)
|
||||||
|
.order_by(Response.submitted_at)))
|
||||||
|
mails = list(db.scalars(select(MailMessage).where(
|
||||||
|
MailMessage.recipient == contact.email, MailMessage.user_id.is_(None)
|
||||||
|
).order_by(MailMessage.created_at)))
|
||||||
|
return _envelope({
|
||||||
|
"guest": {
|
||||||
|
"email": contact.email,
|
||||||
|
"language": contact.language,
|
||||||
|
"created_at": _iso(contact.created_at),
|
||||||
|
"confirmed_at": _iso(contact.confirmed_at),
|
||||||
|
"notifications": contact.notify,
|
||||||
|
},
|
||||||
|
"responses": _responses(db, responses, tz),
|
||||||
|
"followup_emails": _followups(db, f"g:{contact.public_id}"),
|
||||||
|
"email_log": _mail_log(mails),
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def for_response(db: Session, response: Response, tz: ZoneInfo) -> dict[str, Any]:
|
||||||
|
"""Eine einzelne Antwort (persönlicher Link, auch ohne Adresse)."""
|
||||||
|
return _envelope({"responses": _responses(db, [response], tz)})
|
||||||
|
|
||||||
|
|
||||||
|
def to_json(data: dict[str, Any]) -> bytes:
|
||||||
|
return json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def filename(today: datetime | None = None) -> str:
|
||||||
|
day = (today or datetime.now(UTC)).date().isoformat()
|
||||||
|
return f"surveybox-meine-daten-{day}.json"
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Auswertung je Frage: Anzahlen, Summen, Durchschnitte, Freitexte.
|
||||||
|
|
||||||
|
Das Modul rechnet nur; die (gefilterten) Antworten kommen als Liste herein.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections import Counter
|
||||||
|
from collections.abc import Iterable, Mapping, Sequence
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from decimal import Decimal
|
||||||
|
from typing import Any
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from surveybox.forms import types
|
||||||
|
from surveybox.i18n import gettext
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Bar:
|
||||||
|
label: str
|
||||||
|
count: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class QuestionSummary:
|
||||||
|
question: Any
|
||||||
|
answered: int
|
||||||
|
bars: list[Bar] = field(default_factory=list)
|
||||||
|
total: Decimal | None = None
|
||||||
|
average: Decimal | None = None
|
||||||
|
note: str = ""
|
||||||
|
poll_rows: list[dict[str, Any]] = field(default_factory=list)
|
||||||
|
slot_rows: list[dict[str, Any]] = field(default_factory=list)
|
||||||
|
texts: list[str] = field(default_factory=list) # Freitexte (die ersten MAX_TEXTS)
|
||||||
|
more_texts: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
MAX_TEXTS = 50
|
||||||
|
TEXT_TYPES = ("short_text", "long_text", "email", "phone", "participant_name", "date", "time",
|
||||||
|
"datetime")
|
||||||
|
|
||||||
|
|
||||||
|
def _round(value: Decimal) -> Decimal:
|
||||||
|
return value.quantize(Decimal("0.01")).normalize()
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(
|
||||||
|
questions: Sequence[Any],
|
||||||
|
answers: Iterable[tuple[int, dict[str, Any]]],
|
||||||
|
places: Mapping[int, Mapping[str, Any]] | None = None,
|
||||||
|
tz: ZoneInfo | None = None,
|
||||||
|
) -> list[QuestionSummary]:
|
||||||
|
"""answers: (Fragen-ID, gespeicherte Werte) je Antwort.
|
||||||
|
|
||||||
|
places: je Teilnahme-Frage die Belegung (forms.booking.Availability).
|
||||||
|
"""
|
||||||
|
by_question: dict[int, list[dict[str, Any]]] = {}
|
||||||
|
for qid, stored in answers:
|
||||||
|
by_question.setdefault(qid, []).append(stored)
|
||||||
|
result: list[QuestionSummary] = []
|
||||||
|
for q in questions:
|
||||||
|
qtype = types.TYPES.get(q.type)
|
||||||
|
if qtype is None or not qtype.is_input:
|
||||||
|
continue
|
||||||
|
rows = by_question.get(q.id, [])
|
||||||
|
item = QuestionSummary(q, len(rows))
|
||||||
|
cfg = q.config
|
||||||
|
if q.type == "yes_no":
|
||||||
|
answers_yn = Counter(r.get("value_bool") for r in rows)
|
||||||
|
item.bars = [
|
||||||
|
Bar(cfg.get("label_yes") or gettext("Yes"), answers_yn[True]),
|
||||||
|
Bar(cfg.get("label_no") or gettext("No"), answers_yn[False]),
|
||||||
|
]
|
||||||
|
elif q.type in ("single_choice", "multiple_choice"):
|
||||||
|
counts: Counter[str] = Counter()
|
||||||
|
other = 0
|
||||||
|
for r in rows:
|
||||||
|
if q.type == "single_choice":
|
||||||
|
chosen = [r.get("value_text")]
|
||||||
|
if r.get("value_text") == types.OTHER:
|
||||||
|
chosen = []
|
||||||
|
other += 1
|
||||||
|
else:
|
||||||
|
data = r.get("value_json") or {}
|
||||||
|
chosen = list(data.get("selected") or [])
|
||||||
|
other += 1 if data.get("other") else 0
|
||||||
|
counts.update(c for c in chosen if c)
|
||||||
|
item.bars = [Bar(o["label"], counts[o["id"]]) for o in types.options_of(q)]
|
||||||
|
if cfg.get("allow_other"):
|
||||||
|
item.bars.append(Bar(gettext("Other"), other))
|
||||||
|
elif q.type in ("number", "rating"):
|
||||||
|
values = [Decimal(r["value_number"]) for r in rows if r.get("value_number") is not None]
|
||||||
|
if values:
|
||||||
|
item.total = sum(values, Decimal(0))
|
||||||
|
item.average = _round(item.total / len(values))
|
||||||
|
if q.type == "rating":
|
||||||
|
per_value = Counter(int(v) for v in values)
|
||||||
|
scale = int(cfg.get("scale_max") or 5)
|
||||||
|
item.bars = [Bar(str(i), per_value[i]) for i in range(1, scale + 1)]
|
||||||
|
item.total = None
|
||||||
|
elif q.type == "poll":
|
||||||
|
tally: dict[str, Counter[str]] = {}
|
||||||
|
for r in rows:
|
||||||
|
for oid, vote in ((r.get("value_json") or {}).get("votes") or {}).items():
|
||||||
|
tally.setdefault(oid, Counter())[vote] += 1
|
||||||
|
confirmed = set(cfg.get("confirmed") or [])
|
||||||
|
for option in types.options_of(q):
|
||||||
|
counts_o = tally.get(option["id"], Counter())
|
||||||
|
item.poll_rows.append(
|
||||||
|
{
|
||||||
|
"id": option["id"],
|
||||||
|
"text": types.option_text(option),
|
||||||
|
"yes": counts_o["yes"],
|
||||||
|
"maybe": counts_o["maybe"],
|
||||||
|
"no": counts_o["no"],
|
||||||
|
"proposed": bool(option.get("proposed")),
|
||||||
|
"confirmed": option["id"] in confirmed,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if item.poll_rows:
|
||||||
|
best = max((r["yes"], r["maybe"]) for r in item.poll_rows)
|
||||||
|
if best > (0, 0):
|
||||||
|
for row in item.poll_rows:
|
||||||
|
row["best"] = (row["yes"], row["maybe"]) == best
|
||||||
|
elif q.type == "slots":
|
||||||
|
occupancy = (places or {}).get(q.id, {})
|
||||||
|
for option in types.options_of(q):
|
||||||
|
state = occupancy.get(option["id"])
|
||||||
|
item.slot_rows.append(
|
||||||
|
{
|
||||||
|
"id": option["id"],
|
||||||
|
"text": gettext("signed up") if q.config.get("single") else option["label"],
|
||||||
|
"capacity": option.get("capacity"),
|
||||||
|
"confirmed": state.confirmed if state else 0,
|
||||||
|
"waiting": state.waiting if state else 0,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif q.type in TEXT_TYPES:
|
||||||
|
shown = [types.display_answer(q, r, tz or ZoneInfo("UTC")) for r in rows]
|
||||||
|
shown = [text for text in shown if text]
|
||||||
|
item.texts = shown[:MAX_TEXTS]
|
||||||
|
item.more_texts = max(len(shown) - MAX_TEXTS, 0)
|
||||||
|
elif q.type == "ranking":
|
||||||
|
ranks: dict[str, list[int]] = {}
|
||||||
|
for r in rows:
|
||||||
|
for place, oid in enumerate((r.get("value_json") or {}).get("order") or [], 1):
|
||||||
|
ranks.setdefault(oid, []).append(place)
|
||||||
|
|
||||||
|
def average_place(
|
||||||
|
option: dict[str, str], ranks: dict[str, list[int]] = ranks
|
||||||
|
) -> float:
|
||||||
|
found = ranks.get(option["id"]) or [99]
|
||||||
|
return sum(found) / len(found)
|
||||||
|
|
||||||
|
ranked = sorted(types.options_of(q), key=average_place)
|
||||||
|
item.note = ", ".join(f"{i}. {o['label']}" for i, o in enumerate(ranked, 1))
|
||||||
|
result.append(item)
|
||||||
|
return result
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Wer ein Formular betreuen darf, und Kopien und Vorlagen.
|
||||||
|
|
||||||
|
Stufen: Auswerten (Antworten sehen) < Bearbeiten (Fragen, Einstellungen,
|
||||||
|
Status) < Eigentümer (zusätzlich Team, Vorlagen-Freigabe, Löschen).
|
||||||
|
Administratoren haben überall die höchste Stufe.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from enum import IntEnum
|
||||||
|
|
||||||
|
from sqlalchemy import func, or_, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.accounts import scope
|
||||||
|
from surveybox.forms import conditions
|
||||||
|
from surveybox.media import service as media
|
||||||
|
from surveybox.models import (
|
||||||
|
Form,
|
||||||
|
FormAccessEntry,
|
||||||
|
FormMember,
|
||||||
|
FormStatus,
|
||||||
|
MediaFile,
|
||||||
|
MediaKind,
|
||||||
|
MemberRole,
|
||||||
|
Question,
|
||||||
|
Response,
|
||||||
|
Role,
|
||||||
|
UserAccount,
|
||||||
|
UserGroup,
|
||||||
|
)
|
||||||
|
from surveybox.security.tokens import new_token
|
||||||
|
|
||||||
|
|
||||||
|
class Level(IntEnum):
|
||||||
|
NONE = 0
|
||||||
|
EVALUATE = 1
|
||||||
|
EDIT = 2
|
||||||
|
OWN = 3
|
||||||
|
|
||||||
|
|
||||||
|
ROLE_LEVEL = {MemberRole.EDITOR: Level.EDIT, MemberRole.EVALUATOR: Level.EVALUATE}
|
||||||
|
|
||||||
|
|
||||||
|
def _member_rows(db: Session, user: UserAccount): # type: ignore[no-untyped-def]
|
||||||
|
"""Team-Einträge, die den Benutzer betreffen (auch über übergeordnete Gruppen)."""
|
||||||
|
groups = scope.member_groups(db, user.id)
|
||||||
|
return or_(FormMember.user_id == user.id, FormMember.group_id.in_(groups))
|
||||||
|
|
||||||
|
|
||||||
|
def level(
|
||||||
|
db: Session, user: UserAccount | None, form: Form, found: scope.Scope | None = None
|
||||||
|
) -> Level:
|
||||||
|
if user is None:
|
||||||
|
return Level.NONE
|
||||||
|
if user.role == Role.ADMIN or (form.owner_id is not None and form.owner_id == user.id):
|
||||||
|
return Level.OWN
|
||||||
|
found = found or scope.scope_for(db, user)
|
||||||
|
if form.group_id is not None and form.group_id in found.managed:
|
||||||
|
return Level.OWN # Gruppenadministrator der Gruppe oder einer darüber
|
||||||
|
roles = db.scalars(
|
||||||
|
select(FormMember.role).where(FormMember.form_id == form.id, _member_rows(db, user))
|
||||||
|
)
|
||||||
|
return max((ROLE_LEVEL.get(MemberRole(r), Level.NONE) for r in roles), default=Level.NONE)
|
||||||
|
|
||||||
|
|
||||||
|
def list_forms(db: Session, user: UserAccount) -> list[tuple[Form, int, Level]]:
|
||||||
|
"""Formulare (ohne Vorlagen), die der Benutzer betreut, neueste zuerst."""
|
||||||
|
counts = (
|
||||||
|
select(Response.form_id, func.count().label("n")).group_by(Response.form_id).subquery()
|
||||||
|
)
|
||||||
|
stmt = (
|
||||||
|
select(Form, func.coalesce(counts.c.n, 0))
|
||||||
|
.outerjoin(counts, counts.c.form_id == Form.id)
|
||||||
|
.where(Form.is_template.is_(False))
|
||||||
|
.order_by(Form.updated_at.desc())
|
||||||
|
.limit(1000)
|
||||||
|
)
|
||||||
|
found = scope.scope_for(db, user)
|
||||||
|
if user.role != Role.ADMIN:
|
||||||
|
member_forms = select(FormMember.form_id).where(_member_rows(db, user))
|
||||||
|
stmt = stmt.where(
|
||||||
|
or_(
|
||||||
|
Form.owner_id == user.id,
|
||||||
|
Form.id.in_(member_forms),
|
||||||
|
Form.group_id.in_(found.managed),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
rows = db.execute(stmt).all()
|
||||||
|
return [(f, int(n), level(db, user, f, found)) for f, n in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def list_templates(db: Session, user: UserAccount) -> list[Form]:
|
||||||
|
"""Eigene und freigegebene Vorlagen; Administratoren sehen alle."""
|
||||||
|
stmt = select(Form).where(Form.is_template.is_(True)).order_by(Form.title).limit(500)
|
||||||
|
if user.role != Role.ADMIN:
|
||||||
|
stmt = stmt.where(or_(Form.owner_id == user.id, Form.template_shared.is_(True)))
|
||||||
|
return list(db.scalars(stmt))
|
||||||
|
|
||||||
|
|
||||||
|
def can_use_template(user: UserAccount, form: Form) -> bool:
|
||||||
|
return form.is_template and (
|
||||||
|
user.role == Role.ADMIN or form.owner_id == user.id or form.template_shared
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Team
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def members(db: Session, form: Form) -> list[tuple[FormMember, str]]:
|
||||||
|
rows = db.execute(
|
||||||
|
select(FormMember, UserAccount.display_name, UserGroup.name)
|
||||||
|
.outerjoin(UserAccount, UserAccount.id == FormMember.user_id)
|
||||||
|
.outerjoin(UserGroup, UserGroup.id == FormMember.group_id)
|
||||||
|
.where(FormMember.form_id == form.id)
|
||||||
|
.order_by(FormMember.role, UserGroup.name, UserAccount.display_name)
|
||||||
|
).all()
|
||||||
|
return [(m, user_name or group_name or "") for m, user_name, group_name in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def _parse(value: str) -> uuid.UUID | None:
|
||||||
|
try:
|
||||||
|
return uuid.UUID(value)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def add_member(db: Session, form: Form, target: str, role: str) -> bool:
|
||||||
|
"""Ziel: "u:<public_id>" oder "g:<public_id>". False, wenn unbekannt."""
|
||||||
|
if role not in {r.value for r in MemberRole}:
|
||||||
|
return False
|
||||||
|
kind, _, raw = target.partition(":")
|
||||||
|
pid = _parse(raw)
|
||||||
|
if pid is None:
|
||||||
|
return False
|
||||||
|
if kind == "u":
|
||||||
|
user = db.scalar(select(UserAccount).where(UserAccount.public_id == pid))
|
||||||
|
if user is None or user.id == form.owner_id:
|
||||||
|
return False
|
||||||
|
existing = db.scalar(
|
||||||
|
select(FormMember).where(FormMember.form_id == form.id, FormMember.user_id == user.id)
|
||||||
|
)
|
||||||
|
if existing is None:
|
||||||
|
db.add(FormMember(form_id=form.id, user_id=user.id, role=role))
|
||||||
|
else:
|
||||||
|
existing.role = role
|
||||||
|
return True
|
||||||
|
if kind == "g":
|
||||||
|
group = db.scalar(select(UserGroup).where(UserGroup.public_id == pid))
|
||||||
|
if group is None:
|
||||||
|
return False
|
||||||
|
existing = db.scalar(
|
||||||
|
select(FormMember).where(
|
||||||
|
FormMember.form_id == form.id, FormMember.group_id == group.id
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if existing is None:
|
||||||
|
db.add(FormMember(form_id=form.id, group_id=group.id, role=role))
|
||||||
|
else:
|
||||||
|
existing.role = role
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def remove_member(db: Session, form: Form, member_id: int) -> None:
|
||||||
|
member = db.get(FormMember, member_id)
|
||||||
|
if member is not None and member.form_id == form.id:
|
||||||
|
db.delete(member)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Kopieren und Vorlagen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
COPIED_FIELDS = (
|
||||||
|
"description",
|
||||||
|
"access",
|
||||||
|
"link_password_hash",
|
||||||
|
"allow_multiple",
|
||||||
|
"allow_edit",
|
||||||
|
"anonymous",
|
||||||
|
"guest_email",
|
||||||
|
"results_visibility",
|
||||||
|
"retention_days",
|
||||||
|
"deletion_mode",
|
||||||
|
"privacy_notice",
|
||||||
|
"require_consent",
|
||||||
|
"consent_text",
|
||||||
|
"slots_max_per_person",
|
||||||
|
"slot_names",
|
||||||
|
"calendar_mode",
|
||||||
|
"comments_mode",
|
||||||
|
"comments_anonymous",
|
||||||
|
"comments_notify",
|
||||||
|
"reply_to",
|
||||||
|
"reminder_days",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def copy_form(
|
||||||
|
db: Session,
|
||||||
|
source: Form,
|
||||||
|
owner: UserAccount,
|
||||||
|
title: str,
|
||||||
|
*,
|
||||||
|
as_template: bool,
|
||||||
|
group_id: int | None = None,
|
||||||
|
) -> Form:
|
||||||
|
"""Neues Formular (Entwurf) mit Fragen, Einstellungen, Zugriffsliste und Medien.
|
||||||
|
|
||||||
|
Antworten, Team und Zeitraum werden nicht übernommen.
|
||||||
|
"""
|
||||||
|
clone = Form(
|
||||||
|
title=title[:200],
|
||||||
|
owner_id=owner.id,
|
||||||
|
share_token=new_token(16),
|
||||||
|
status=FormStatus.DRAFT,
|
||||||
|
is_template=as_template,
|
||||||
|
template_shared=False,
|
||||||
|
group_id=group_id if group_id is not None else source.group_id,
|
||||||
|
**{name: getattr(source, name) for name in COPIED_FIELDS},
|
||||||
|
)
|
||||||
|
db.add(clone)
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
for entry in db.scalars(select(FormAccessEntry).where(FormAccessEntry.form_id == source.id)):
|
||||||
|
db.add(FormAccessEntry(form_id=clone.id, user_id=entry.user_id, group_id=entry.group_id))
|
||||||
|
|
||||||
|
id_map: dict[int, int] = {}
|
||||||
|
for question in source.questions:
|
||||||
|
new_q = Question(
|
||||||
|
form_id=clone.id,
|
||||||
|
position=question.position,
|
||||||
|
type=question.type,
|
||||||
|
label=question.label,
|
||||||
|
help_text=question.help_text,
|
||||||
|
required=question.required,
|
||||||
|
personal=question.personal,
|
||||||
|
config={},
|
||||||
|
)
|
||||||
|
clone.questions.append(new_q)
|
||||||
|
db.flush()
|
||||||
|
ids = media.question_media_ids(question.config)
|
||||||
|
found = media.by_ids(db, source, ids)
|
||||||
|
mapping = {
|
||||||
|
old_id: str(media.duplicate(db, row, clone, new_q.id).public_id)
|
||||||
|
for old_id, row in found.items()
|
||||||
|
if row.kind != MediaKind.UPLOAD
|
||||||
|
}
|
||||||
|
new_q.config = media.remap_config(question.config, mapping)
|
||||||
|
id_map[question.id] = new_q.id
|
||||||
|
# Bedingungen verweisen auf Fragen-IDs: auf die Kopien umstellen
|
||||||
|
for new_q in clone.questions:
|
||||||
|
new_q.config = conditions.remap(new_q.config, id_map)
|
||||||
|
db.flush()
|
||||||
|
_copy_followups(db, source, clone)
|
||||||
|
return clone
|
||||||
|
|
||||||
|
|
||||||
|
def _copy_followups(db: Session, source: Form, clone: Form) -> None:
|
||||||
|
"""Folge-Mails samt Dokumenten übernehmen, aber ohne Versandstand."""
|
||||||
|
from surveybox.forms import followups
|
||||||
|
from surveybox.models import Followup, FollowupDocument
|
||||||
|
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
for item in followups.list_for(db, source):
|
||||||
|
trigger, send_at = item.trigger, item.send_at
|
||||||
|
if trigger == "at" and (send_at is None or send_at <= now):
|
||||||
|
trigger, send_at = "manual", None # vergangener Zeitpunkt: nicht sofort senden
|
||||||
|
copy = Followup(
|
||||||
|
form_id=clone.id, subject=item.subject, body=item.body, trigger=trigger,
|
||||||
|
send_at=send_at, only_confirmed=item.only_confirmed, link_days=item.link_days,
|
||||||
|
catch_up=item.catch_up,
|
||||||
|
)
|
||||||
|
db.add(copy)
|
||||||
|
db.flush()
|
||||||
|
for doc, row in followups.documents(db, item):
|
||||||
|
duplicate = media.duplicate(db, row, clone, None)
|
||||||
|
db.add(FollowupDocument(followup_id=copy.id, media_id=duplicate.id,
|
||||||
|
title=doc.title, position=doc.position))
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
|
||||||
|
def form_media(db: Session, form: Form) -> list[MediaFile]:
|
||||||
|
return list(
|
||||||
|
db.scalars(
|
||||||
|
select(MediaFile).where(
|
||||||
|
MediaFile.form_id == form.id, MediaFile.kind != MediaKind.UPLOAD
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,867 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Fragetypen: Einstellungen im Designer, Prüfung der Antworten, Speicherung, Anzeige.
|
||||||
|
|
||||||
|
Jeder Typ legt fest,
|
||||||
|
- welche Einstellungen der Designer anbietet (parse_config),
|
||||||
|
- wie eine Eingabe geprüft und in welcher Spalte sie gespeichert wird (parse_answer),
|
||||||
|
- wie eine gespeicherte Antwort angezeigt (display_answer) und zum Bearbeiten
|
||||||
|
wieder ins Formular gefüllt wird (raw_from_answer).
|
||||||
|
|
||||||
|
Das Modul kennt weder Datenbank noch Web; die Fragen kommen als beliebige
|
||||||
|
Objekte mit den Attributen id, type, label, required und config herein.
|
||||||
|
Formularfelder kommen als dict "Name -> Liste von Werten".
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import date, datetime, time
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
|
from typing import Any, Protocol
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from surveybox.forms import groups
|
||||||
|
from surveybox.i18n import N_, gettext
|
||||||
|
|
||||||
|
Fields = Mapping[str, list[str]]
|
||||||
|
Stored = dict[str, Any] # Spaltenname -> Wert, z. B. {"value_text": "Hallo"}
|
||||||
|
|
||||||
|
OTHER = "__other__"
|
||||||
|
MAX_OPTIONS = 100
|
||||||
|
MAX_OPTION_LABEL = 200
|
||||||
|
MAX_OTHER_TEXT = 500
|
||||||
|
_OPTION_ID = re.compile(r"^[a-z0-9]{6,16}$")
|
||||||
|
_EMAIL = re.compile(r"^[^@\s]{1,64}@[^@\s]{1,252}\.[^@\s]{2,}$")
|
||||||
|
_PHONE = re.compile(r"^\+?[0-9 ()./-]{3,40}$")
|
||||||
|
|
||||||
|
|
||||||
|
class QuestionLike(Protocol):
|
||||||
|
id: int
|
||||||
|
type: str
|
||||||
|
label: str
|
||||||
|
required: bool
|
||||||
|
config: dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class QuestionType:
|
||||||
|
key: str
|
||||||
|
label: str
|
||||||
|
column: str | None # None: keine Eingabe (Überschrift, Hinweis, Seitenumbruch)
|
||||||
|
has_options: bool = False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_input(self) -> bool:
|
||||||
|
return self.column is not None
|
||||||
|
|
||||||
|
|
||||||
|
TYPES: dict[str, QuestionType] = {
|
||||||
|
t.key: t
|
||||||
|
for t in (
|
||||||
|
QuestionType("short_text", N_("Short text"), "value_text"),
|
||||||
|
QuestionType("long_text", N_("Long text"), "value_text"),
|
||||||
|
QuestionType("participant_name", N_("Participant name"), "value_json"),
|
||||||
|
QuestionType("email", N_("Email address"), "value_text"),
|
||||||
|
QuestionType("phone", N_("Phone number"), "value_text"),
|
||||||
|
QuestionType("number", N_("Number"), "value_number"),
|
||||||
|
QuestionType("date", N_("Date"), "value_date"),
|
||||||
|
QuestionType("time", N_("Time"), "value_time"),
|
||||||
|
QuestionType("datetime", N_("Date and time"), "value_datetime"),
|
||||||
|
QuestionType("yes_no", N_("Yes/No"), "value_bool"),
|
||||||
|
QuestionType("single_choice", N_("Single choice"), "value_text", has_options=True),
|
||||||
|
QuestionType("multiple_choice", N_("Multiple choice"), "value_json", has_options=True),
|
||||||
|
QuestionType("ranking", N_("Ranking"), "value_json", has_options=True),
|
||||||
|
QuestionType("rating", N_("Rating scale"), "value_number"),
|
||||||
|
QuestionType("file_upload", N_("File upload"), "value_json"),
|
||||||
|
QuestionType("poll", N_("Poll (yes/no per option)"), "value_json", has_options=True),
|
||||||
|
QuestionType("slots", N_("Participation with places"), "value_json", has_options=True),
|
||||||
|
QuestionType("question_group", N_("Question group"), None),
|
||||||
|
QuestionType("heading", N_("Heading"), None),
|
||||||
|
QuestionType("info", N_("Information text"), None),
|
||||||
|
QuestionType("page_break", N_("Page break"), None),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
# Strukturelemente mit Hilfetext (Gruppe zeigt ihn über der Tabelle)
|
||||||
|
WITH_HELP_TEXT = {"question_group"}
|
||||||
|
|
||||||
|
# "Teilnahme mit Plätzen" mit genau einem Eintrag: feste ID der einen Option,
|
||||||
|
# damit Buchungen beim Bearbeiten erhalten bleiben
|
||||||
|
SINGLE_SLOT = "single"
|
||||||
|
|
||||||
|
# Typen, die als personenbezogen vorbelegt werden
|
||||||
|
PERSONAL_BY_DEFAULT = {"email", "phone", "file_upload", "participant_name"}
|
||||||
|
|
||||||
|
# "Teilnehmer-Name": Vor- und Nachname immer Pflicht, E-Mail je nach Einstellung
|
||||||
|
NAME_PARTS = ("first", "last", "email")
|
||||||
|
NAME_EMAIL_MODES = ("optional", "required", "off")
|
||||||
|
MAX_NAME_PART = 100
|
||||||
|
|
||||||
|
POLL_VOTES = ("yes", "maybe", "no")
|
||||||
|
MAX_PROPOSAL = 200
|
||||||
|
|
||||||
|
# Dateiarten für den Fragetyp "Datei-Upload" (siehe media.sniff.UPLOAD_GROUPS)
|
||||||
|
FILE_GROUPS = ("pdf", "images", "office", "text", "zip")
|
||||||
|
MAX_FILES = 10
|
||||||
|
MAX_FILE_MB = 1024
|
||||||
|
|
||||||
|
|
||||||
|
class ConfigError(ValueError):
|
||||||
|
def __init__(self, code: str) -> None:
|
||||||
|
super().__init__(code)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Hilfen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _first(fields: Fields, name: str) -> str:
|
||||||
|
values = fields.get(name) or []
|
||||||
|
return values[0] if values else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _int(fields: Fields, name: str, default: int, lo: int, hi: int) -> int:
|
||||||
|
raw = _first(fields, name).strip()
|
||||||
|
if not raw:
|
||||||
|
return default
|
||||||
|
try:
|
||||||
|
value = int(raw)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ConfigError("config_number_invalid") from exc
|
||||||
|
if not lo <= value <= hi:
|
||||||
|
raise ConfigError("config_number_invalid")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _decimal(raw: str) -> Decimal | None:
|
||||||
|
raw = raw.strip().replace(",", ".").replace(" ", "")
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
value = Decimal(raw)
|
||||||
|
except InvalidOperation:
|
||||||
|
return None
|
||||||
|
return value if value.is_finite() else None
|
||||||
|
|
||||||
|
|
||||||
|
def _short(fields: Fields, name: str, max_len: int) -> str:
|
||||||
|
return " ".join(_first(fields, name).split())[:max_len]
|
||||||
|
|
||||||
|
|
||||||
|
def _checked(fields: Fields, name: str) -> bool:
|
||||||
|
return _first(fields, name) == "on"
|
||||||
|
|
||||||
|
|
||||||
|
def new_option_id() -> str:
|
||||||
|
return secrets.token_hex(4)
|
||||||
|
|
||||||
|
|
||||||
|
def options_of(question: QuestionLike) -> list[dict[str, str]]:
|
||||||
|
options = question.config.get("options") or []
|
||||||
|
return [o for o in options if isinstance(o, dict) and "id" in o and "label" in o]
|
||||||
|
|
||||||
|
|
||||||
|
def option_label(question: QuestionLike, option_id: str) -> str | None:
|
||||||
|
for option in options_of(question):
|
||||||
|
if option["id"] == option_id:
|
||||||
|
return option["label"]
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def field_name(question: QuestionLike) -> str:
|
||||||
|
return f"q{question.id}"
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Einstellungen aus dem Designer
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _filled_rows(fields: Fields) -> list[int]:
|
||||||
|
"""Zeilen des Optionen-Editors mit Text (leere Zeilen zählen nicht)."""
|
||||||
|
return [i for i, label in enumerate(fields.get("option_label") or []) if label.split()]
|
||||||
|
|
||||||
|
|
||||||
|
def parse_date_options(fields: Fields) -> list[dict[str, Any]]:
|
||||||
|
"""Termin-Optionen: Datum, optional Uhrzeit und Dauer, dazu ein Hinweis."""
|
||||||
|
# Eigene Feldnamen, damit sie sich nicht mit dem Text-Optionen-Editor mischen
|
||||||
|
ids = fields.get("date_option_id") or []
|
||||||
|
dates = fields.get("option_date") or []
|
||||||
|
times = fields.get("option_time") or []
|
||||||
|
durations = fields.get("option_duration") or []
|
||||||
|
labels = fields.get("date_option_label") or []
|
||||||
|
options: list[dict[str, Any]] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
|
||||||
|
def at(values: list[str], index: int) -> str:
|
||||||
|
return values[index].strip() if index < len(values) else ""
|
||||||
|
|
||||||
|
for index, raw_date in enumerate(dates):
|
||||||
|
raw_date = raw_date.strip()
|
||||||
|
if not raw_date:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
day = date.fromisoformat(raw_date)
|
||||||
|
raw_time = at(times, index)
|
||||||
|
moment = time.fromisoformat(raw_time) if raw_time else None
|
||||||
|
raw_duration = at(durations, index)
|
||||||
|
duration = int(raw_duration) if raw_duration else None
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ConfigError("config_date_invalid") from exc
|
||||||
|
if duration is not None and not 1 <= duration <= 60 * 24 * 14:
|
||||||
|
raise ConfigError("config_number_invalid")
|
||||||
|
option_id = at(ids, index)
|
||||||
|
if not _OPTION_ID.match(option_id) or option_id in seen:
|
||||||
|
option_id = new_option_id()
|
||||||
|
seen.add(option_id)
|
||||||
|
options.append(
|
||||||
|
{
|
||||||
|
"id": option_id,
|
||||||
|
"date": day.isoformat(),
|
||||||
|
"time": moment.strftime("%H:%M") if moment else None,
|
||||||
|
"duration": duration,
|
||||||
|
"label": " ".join(at(labels, index).split())[:MAX_OPTION_LABEL],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if len(options) > MAX_OPTIONS:
|
||||||
|
raise ConfigError("options_too_many")
|
||||||
|
if not options:
|
||||||
|
raise ConfigError("options_too_few")
|
||||||
|
options.sort(key=lambda o: (o["date"], o["time"] or ""))
|
||||||
|
return options
|
||||||
|
|
||||||
|
|
||||||
|
def option_text(option: Mapping[str, Any]) -> str:
|
||||||
|
"""Anzeige einer Option; Termine im Format der aktuellen Sprache."""
|
||||||
|
if not option.get("date"):
|
||||||
|
return str(option.get("label", ""))
|
||||||
|
from babel.dates import format_date, format_time
|
||||||
|
|
||||||
|
from surveybox.i18n import get_language
|
||||||
|
|
||||||
|
language = get_language()
|
||||||
|
day = date.fromisoformat(str(option["date"]))
|
||||||
|
text = format_date(day, format="EEE, d. MMM y" if language == "de" else "medium",
|
||||||
|
locale=language)
|
||||||
|
if option.get("time"):
|
||||||
|
moment = time.fromisoformat(str(option["time"]))
|
||||||
|
text += ", " + format_time(moment, format="short", locale=language)
|
||||||
|
if option.get("duration"):
|
||||||
|
text += f" ({option['duration']} min)"
|
||||||
|
if option.get("label"):
|
||||||
|
text += f" · {option['label']}"
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_options(fields: Fields, minimum: int) -> list[dict[str, str]]:
|
||||||
|
ids = fields.get("option_id") or []
|
||||||
|
labels = fields.get("option_label") or []
|
||||||
|
options: list[dict[str, str]] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
for index, raw_label in enumerate(labels):
|
||||||
|
label = " ".join(raw_label.split())[:MAX_OPTION_LABEL]
|
||||||
|
if not label:
|
||||||
|
continue
|
||||||
|
option_id = ids[index] if index < len(ids) else ""
|
||||||
|
if not _OPTION_ID.match(option_id) or option_id in seen:
|
||||||
|
option_id = new_option_id()
|
||||||
|
seen.add(option_id)
|
||||||
|
options.append({"id": option_id, "label": label})
|
||||||
|
if len(options) > MAX_OPTIONS:
|
||||||
|
raise ConfigError("options_too_many")
|
||||||
|
if len(options) < minimum:
|
||||||
|
raise ConfigError("options_too_few")
|
||||||
|
return options
|
||||||
|
|
||||||
|
|
||||||
|
def parse_config(type_key: str, fields: Fields) -> dict[str, Any]:
|
||||||
|
if type_key not in TYPES:
|
||||||
|
raise ConfigError("type_invalid")
|
||||||
|
if type_key == "short_text":
|
||||||
|
return {"max_length": _int(fields, "max_length", 200, 1, 1000)}
|
||||||
|
if type_key == "participant_name":
|
||||||
|
mode = _first(fields, "email_mode")
|
||||||
|
return {"email": mode if mode in NAME_EMAIL_MODES else "optional"}
|
||||||
|
if type_key == "long_text":
|
||||||
|
return {"max_length": _int(fields, "max_length", 5000, 1, 20000)}
|
||||||
|
if type_key == "number":
|
||||||
|
lo = _decimal(_first(fields, "min"))
|
||||||
|
hi = _decimal(_first(fields, "max"))
|
||||||
|
if lo is not None and hi is not None and lo > hi:
|
||||||
|
raise ConfigError("config_range_invalid")
|
||||||
|
return {
|
||||||
|
"min": None if lo is None else str(lo),
|
||||||
|
"max": None if hi is None else str(hi),
|
||||||
|
"decimals": _int(fields, "decimals", 0, 0, 6),
|
||||||
|
"unit": _short(fields, "unit", 20),
|
||||||
|
}
|
||||||
|
if type_key == "date":
|
||||||
|
bounds: dict[str, str | None] = {}
|
||||||
|
for key in ("min_date", "max_date"):
|
||||||
|
raw = _first(fields, key).strip()
|
||||||
|
if raw:
|
||||||
|
try:
|
||||||
|
bounds[key] = date.fromisoformat(raw).isoformat()
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ConfigError("config_date_invalid") from exc
|
||||||
|
else:
|
||||||
|
bounds[key] = None
|
||||||
|
if bounds["min_date"] and bounds["max_date"] and bounds["min_date"] > bounds["max_date"]:
|
||||||
|
raise ConfigError("config_range_invalid")
|
||||||
|
return bounds
|
||||||
|
if type_key == "yes_no":
|
||||||
|
return {
|
||||||
|
"label_yes": _short(fields, "label_yes", 50),
|
||||||
|
"label_no": _short(fields, "label_no", 50),
|
||||||
|
}
|
||||||
|
if type_key == "single_choice":
|
||||||
|
display = _first(fields, "display")
|
||||||
|
return {
|
||||||
|
"options": _parse_options(fields, 2),
|
||||||
|
"display": display if display in ("radio", "dropdown", "images") else "radio",
|
||||||
|
"allow_other": _checked(fields, "allow_other"),
|
||||||
|
}
|
||||||
|
if type_key == "multiple_choice":
|
||||||
|
options = _parse_options(fields, 2)
|
||||||
|
min_select = _int(fields, "min_select", 0, 0, MAX_OPTIONS)
|
||||||
|
max_select = _int(fields, "max_select", 0, 0, MAX_OPTIONS)
|
||||||
|
if max_select and min_select > max_select:
|
||||||
|
raise ConfigError("config_range_invalid")
|
||||||
|
return {
|
||||||
|
"options": options,
|
||||||
|
"display": "images" if _first(fields, "display") == "images" else "list",
|
||||||
|
"min_select": min_select,
|
||||||
|
"max_select": max_select,
|
||||||
|
"allow_other": _checked(fields, "allow_other"),
|
||||||
|
}
|
||||||
|
if type_key == "question_group":
|
||||||
|
kind = _first(fields, "member_type")
|
||||||
|
if kind not in groups.MEMBER_TYPES:
|
||||||
|
raise ConfigError("config_group_type_invalid")
|
||||||
|
if kind not in groups.COUNTING:
|
||||||
|
return {"member_type": kind, "min_select": 0, "max_select": 0}
|
||||||
|
lower = _int(fields, "min_select", 0, 0, groups.MAX_SELECT)
|
||||||
|
upper = _int(fields, "max_select", 0, 0, groups.MAX_SELECT)
|
||||||
|
if upper and lower > upper:
|
||||||
|
raise ConfigError("config_range_invalid")
|
||||||
|
return {"member_type": kind, "min_select": lower, "max_select": upper}
|
||||||
|
if type_key == "slots" and _first(fields, "slot_mode") != "list":
|
||||||
|
capacity_raw = _first(fields, "capacity").strip()
|
||||||
|
capacity: int | None = None
|
||||||
|
if capacity_raw:
|
||||||
|
try:
|
||||||
|
capacity = int(capacity_raw)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ConfigError("config_number_invalid") from exc
|
||||||
|
if not 1 <= capacity <= 100000:
|
||||||
|
raise ConfigError("config_number_invalid")
|
||||||
|
option: dict[str, Any] = {"id": SINGLE_SLOT, "label": _short(fields, "label", 200)}
|
||||||
|
if capacity is not None:
|
||||||
|
option["capacity"] = capacity
|
||||||
|
return {
|
||||||
|
"single": True,
|
||||||
|
"options": [option],
|
||||||
|
"waitlist": _checked(fields, "waitlist"),
|
||||||
|
"hide_full": _checked(fields, "hide_full"),
|
||||||
|
}
|
||||||
|
if type_key == "slots":
|
||||||
|
options = _parse_options(fields, 1)
|
||||||
|
rows = _filled_rows(fields)
|
||||||
|
capacities = fields.get("option_capacity") or []
|
||||||
|
for row, option in zip(rows, options, strict=False):
|
||||||
|
raw = capacities[row].strip() if row < len(capacities) else ""
|
||||||
|
if raw:
|
||||||
|
try:
|
||||||
|
capacity = int(raw)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ConfigError("config_number_invalid") from exc
|
||||||
|
if not 1 <= capacity <= 100000:
|
||||||
|
raise ConfigError("config_number_invalid")
|
||||||
|
option["capacity"] = capacity # type: ignore[assignment]
|
||||||
|
return {
|
||||||
|
"options": options,
|
||||||
|
"multiple": _checked(fields, "multiple"),
|
||||||
|
"waitlist": _checked(fields, "waitlist"),
|
||||||
|
"hide_full": _checked(fields, "hide_full"),
|
||||||
|
}
|
||||||
|
if type_key == "poll":
|
||||||
|
mode = "dates" if _first(fields, "mode") == "dates" else "text"
|
||||||
|
options = parse_date_options(fields) if mode == "dates" else _parse_options(fields, 1)
|
||||||
|
return {
|
||||||
|
"mode": mode,
|
||||||
|
"answers": "ynm" if _first(fields, "answers") == "ynm" else "yn",
|
||||||
|
"allow_proposals": _checked(fields, "allow_proposals"),
|
||||||
|
"options": options,
|
||||||
|
}
|
||||||
|
if type_key == "ranking":
|
||||||
|
return {"options": _parse_options(fields, 2)}
|
||||||
|
if type_key == "file_upload":
|
||||||
|
allowed = [g for g in FILE_GROUPS if _checked(fields, f"allow_{g}")]
|
||||||
|
if not allowed:
|
||||||
|
raise ConfigError("file_groups_missing")
|
||||||
|
return {
|
||||||
|
"groups": allowed,
|
||||||
|
"max_files": _int(fields, "max_files", 1, 1, MAX_FILES),
|
||||||
|
"max_mb": _int(fields, "max_mb", 10, 1, MAX_FILE_MB),
|
||||||
|
}
|
||||||
|
if type_key == "rating":
|
||||||
|
return {
|
||||||
|
"scale_max": _int(fields, "scale_max", 5, 3, 10),
|
||||||
|
"label_min": _short(fields, "label_min", 50),
|
||||||
|
"label_max": _short(fields, "label_max", 50),
|
||||||
|
}
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Antworten prüfen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class AnswerResult:
|
||||||
|
stored: Stored | None = None # None: nicht beantwortet
|
||||||
|
error: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
ERRORS: dict[str, str] = {
|
||||||
|
"required": N_("Please answer this question."),
|
||||||
|
"name_incomplete": N_("Please enter your first and last name."),
|
||||||
|
"name_email_missing": N_("Please enter your email address."),
|
||||||
|
"too_long": N_("The text is too long."),
|
||||||
|
"email": N_("Please enter a valid email address."),
|
||||||
|
"phone": N_("Please enter a valid phone number."),
|
||||||
|
"number": N_("Please enter a number."),
|
||||||
|
"number_min": N_("The number is too small."),
|
||||||
|
"number_max": N_("The number is too large."),
|
||||||
|
"number_decimals": N_("Too many decimal places."),
|
||||||
|
"date": N_("Please enter a valid date."),
|
||||||
|
"date_min": N_("The date is too early."),
|
||||||
|
"date_max": N_("The date is too late."),
|
||||||
|
"time": N_("Please enter a valid time."),
|
||||||
|
"datetime": N_("Please enter a valid date and time."),
|
||||||
|
"choice": N_("Please choose one of the options."),
|
||||||
|
"other_missing": N_("Please fill in the text for “Other”."),
|
||||||
|
"select_min": N_("Please choose more options."),
|
||||||
|
"select_max": N_("Please choose fewer options."),
|
||||||
|
"ranking": N_("Please give every option a different place."),
|
||||||
|
"rating": N_("Please choose a value on the scale."),
|
||||||
|
"files_too_many": N_("Too many files."),
|
||||||
|
"poll_incomplete": N_("Please answer every option."),
|
||||||
|
"slot_full": N_("This place has just been taken. Please choose another option."),
|
||||||
|
"slots_too_many": N_("You have chosen more places than allowed for this form."),
|
||||||
|
"group_too_many": N_("You have chosen more entries than allowed in this group."),
|
||||||
|
"group_too_few": N_("Please choose more entries in this group."),
|
||||||
|
"proposal_invalid": N_("Please check your proposal."),
|
||||||
|
"file_too_large": N_("The file is too large."),
|
||||||
|
"file_type": N_("This file type is not allowed here."),
|
||||||
|
"file_empty": N_("The file is empty."),
|
||||||
|
"image_type": N_("Please upload a JPEG, PNG or WebP image."),
|
||||||
|
"image_invalid": N_("The image could not be read."),
|
||||||
|
"upload_limit": N_("Too many uploads. Please try again later."),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _text_answer(value: str, max_length: int, multiline: bool) -> AnswerResult:
|
||||||
|
value = value.replace("\r\n", "\n").strip() if multiline else " ".join(value.split())
|
||||||
|
if not value:
|
||||||
|
return AnswerResult()
|
||||||
|
if len(value) > max_length:
|
||||||
|
return AnswerResult(error="too_long")
|
||||||
|
return AnswerResult({"value_text": value})
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_single(q: QuestionLike, fields: Fields, name: str) -> AnswerResult:
|
||||||
|
value = _first(fields, name)
|
||||||
|
if not value:
|
||||||
|
return AnswerResult()
|
||||||
|
if value == OTHER and q.config.get("allow_other"):
|
||||||
|
other = " ".join(_first(fields, f"{name}_other").split())
|
||||||
|
if not other:
|
||||||
|
return AnswerResult(error="other_missing")
|
||||||
|
if len(other) > MAX_OTHER_TEXT:
|
||||||
|
return AnswerResult(error="too_long")
|
||||||
|
return AnswerResult({"value_text": OTHER, "value_json": {"other": other}})
|
||||||
|
if option_label(q, value) is None:
|
||||||
|
return AnswerResult(error="choice")
|
||||||
|
return AnswerResult({"value_text": value})
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_multiple(q: QuestionLike, fields: Fields, name: str) -> AnswerResult:
|
||||||
|
chosen = list(dict.fromkeys(fields.get(name) or []))
|
||||||
|
valid = {o["id"] for o in options_of(q)}
|
||||||
|
other: str | None = None
|
||||||
|
if OTHER in chosen and q.config.get("allow_other"):
|
||||||
|
chosen.remove(OTHER)
|
||||||
|
other = " ".join(_first(fields, f"{name}_other").split())
|
||||||
|
if not other:
|
||||||
|
return AnswerResult(error="other_missing")
|
||||||
|
if len(other) > MAX_OTHER_TEXT:
|
||||||
|
return AnswerResult(error="too_long")
|
||||||
|
if any(c not in valid for c in chosen):
|
||||||
|
return AnswerResult(error="choice")
|
||||||
|
count = len(chosen) + (1 if other else 0)
|
||||||
|
if count == 0:
|
||||||
|
return AnswerResult()
|
||||||
|
lo, hi = int(q.config.get("min_select") or 0), int(q.config.get("max_select") or 0)
|
||||||
|
if lo and count < lo:
|
||||||
|
return AnswerResult(error="select_min")
|
||||||
|
if hi and count > hi:
|
||||||
|
return AnswerResult(error="select_max")
|
||||||
|
return AnswerResult({"value_json": {"selected": chosen, "other": other}})
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_ranking(q: QuestionLike, fields: Fields, name: str) -> AnswerResult:
|
||||||
|
options = options_of(q)
|
||||||
|
places: dict[str, int] = {}
|
||||||
|
for option in options:
|
||||||
|
raw = _first(fields, f"{name}_rank_{option['id']}")
|
||||||
|
if not raw:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
places[option["id"]] = int(raw)
|
||||||
|
except ValueError:
|
||||||
|
return AnswerResult(error="ranking")
|
||||||
|
if not places:
|
||||||
|
return AnswerResult()
|
||||||
|
n = len(options)
|
||||||
|
if len(places) != n or sorted(places.values()) != list(range(1, n + 1)):
|
||||||
|
return AnswerResult(error="ranking")
|
||||||
|
order = sorted(places, key=lambda oid: places[oid])
|
||||||
|
return AnswerResult({"value_json": {"order": order}})
|
||||||
|
|
||||||
|
|
||||||
|
def parse_answer(
|
||||||
|
q: QuestionLike,
|
||||||
|
fields: Fields,
|
||||||
|
tz: ZoneInfo,
|
||||||
|
files: Mapping[int, list[dict[str, Any]]] | None = None,
|
||||||
|
*,
|
||||||
|
required: bool | None = None,
|
||||||
|
) -> AnswerResult:
|
||||||
|
"""Prüft die Eingabe zu einer Frage. Pflicht wird hier mit geprüft.
|
||||||
|
|
||||||
|
`files`: für Datei-Fragen die vom Server bereits geprüften Dateien je Frage.
|
||||||
|
`required`: weicht von `q.required` ab, wenn eine Fragengruppe die Pflicht regelt.
|
||||||
|
"""
|
||||||
|
result = _parse_unchecked(q, fields, tz, files or {})
|
||||||
|
must = q.required if required is None else required
|
||||||
|
if result.error is None and result.stored is None and must:
|
||||||
|
return AnswerResult(error="name_incomplete" if q.type == "participant_name" else "required")
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_unchecked(
|
||||||
|
q: QuestionLike, fields: Fields, tz: ZoneInfo, files: Mapping[int, list[dict[str, Any]]]
|
||||||
|
) -> AnswerResult:
|
||||||
|
name = field_name(q)
|
||||||
|
raw = _first(fields, name)
|
||||||
|
cfg = q.config
|
||||||
|
t = q.type
|
||||||
|
|
||||||
|
if t in ("short_text", "long_text"):
|
||||||
|
default = 200 if t == "short_text" else 5000
|
||||||
|
return _text_answer(raw, int(cfg.get("max_length") or default), t == "long_text")
|
||||||
|
if t == "participant_name":
|
||||||
|
return _parse_name(cfg, fields, name)
|
||||||
|
if t == "email":
|
||||||
|
value = raw.strip()
|
||||||
|
if not value:
|
||||||
|
return AnswerResult()
|
||||||
|
if len(value) > 254 or not _EMAIL.match(value):
|
||||||
|
return AnswerResult(error="email")
|
||||||
|
return AnswerResult({"value_text": value})
|
||||||
|
if t == "phone":
|
||||||
|
value = " ".join(raw.split())
|
||||||
|
if not value:
|
||||||
|
return AnswerResult()
|
||||||
|
if not _PHONE.match(value) or sum(ch.isdigit() for ch in value) < 3:
|
||||||
|
return AnswerResult(error="phone")
|
||||||
|
return AnswerResult({"value_text": value})
|
||||||
|
if t == "number":
|
||||||
|
if not raw.strip():
|
||||||
|
return AnswerResult()
|
||||||
|
number = _decimal(raw)
|
||||||
|
if number is None or abs(number) >= Decimal("1e14"):
|
||||||
|
return AnswerResult(error="number")
|
||||||
|
decimals = int(cfg.get("decimals") or 0)
|
||||||
|
exponent = number.normalize().as_tuple().exponent
|
||||||
|
if isinstance(exponent, int) and -exponent > decimals:
|
||||||
|
return AnswerResult(error="number_decimals")
|
||||||
|
lo, hi = cfg.get("min"), cfg.get("max")
|
||||||
|
if lo is not None and number < Decimal(lo):
|
||||||
|
return AnswerResult(error="number_min")
|
||||||
|
if hi is not None and number > Decimal(hi):
|
||||||
|
return AnswerResult(error="number_max")
|
||||||
|
return AnswerResult({"value_number": number})
|
||||||
|
if t == "date":
|
||||||
|
if not raw.strip():
|
||||||
|
return AnswerResult()
|
||||||
|
try:
|
||||||
|
value_d = date.fromisoformat(raw.strip())
|
||||||
|
except ValueError:
|
||||||
|
return AnswerResult(error="date")
|
||||||
|
if cfg.get("min_date") and value_d < date.fromisoformat(cfg["min_date"]):
|
||||||
|
return AnswerResult(error="date_min")
|
||||||
|
if cfg.get("max_date") and value_d > date.fromisoformat(cfg["max_date"]):
|
||||||
|
return AnswerResult(error="date_max")
|
||||||
|
return AnswerResult({"value_date": value_d})
|
||||||
|
if t == "time":
|
||||||
|
if not raw.strip():
|
||||||
|
return AnswerResult()
|
||||||
|
try:
|
||||||
|
value_t = time.fromisoformat(raw.strip())
|
||||||
|
except ValueError:
|
||||||
|
return AnswerResult(error="time")
|
||||||
|
return AnswerResult({"value_time": value_t.replace(second=0, microsecond=0)})
|
||||||
|
if t == "datetime":
|
||||||
|
if not raw.strip():
|
||||||
|
return AnswerResult()
|
||||||
|
try:
|
||||||
|
local = datetime.fromisoformat(raw.strip())
|
||||||
|
except ValueError:
|
||||||
|
return AnswerResult(error="datetime")
|
||||||
|
if local.tzinfo is None:
|
||||||
|
local = local.replace(tzinfo=tz)
|
||||||
|
return AnswerResult({"value_datetime": local})
|
||||||
|
if t == "yes_no":
|
||||||
|
if raw == "yes":
|
||||||
|
return AnswerResult({"value_bool": True})
|
||||||
|
if raw == "no":
|
||||||
|
return AnswerResult({"value_bool": False})
|
||||||
|
return AnswerResult() if not raw else AnswerResult(error="choice")
|
||||||
|
if t == "single_choice":
|
||||||
|
return _parse_single(q, fields, name)
|
||||||
|
if t == "multiple_choice":
|
||||||
|
return _parse_multiple(q, fields, name)
|
||||||
|
if t == "ranking":
|
||||||
|
return _parse_ranking(q, fields, name)
|
||||||
|
if t == "slots":
|
||||||
|
picked = list(dict.fromkeys(v for v in fields.get(name) or [] if v))
|
||||||
|
valid = {o["id"] for o in options_of(q)}
|
||||||
|
if any(p not in valid for p in picked):
|
||||||
|
return AnswerResult(error="choice")
|
||||||
|
if len(picked) > 1 and not cfg.get("multiple"):
|
||||||
|
return AnswerResult(error="choice")
|
||||||
|
return AnswerResult({"value_json": {"selected": picked}}) if picked else AnswerResult()
|
||||||
|
if t == "poll":
|
||||||
|
allowed = POLL_VOTES if cfg.get("answers") == "ynm" else ("yes", "no")
|
||||||
|
votes: dict[str, str] = {}
|
||||||
|
for option in options_of(q):
|
||||||
|
vote = _first(fields, f"{name}_{option['id']}")
|
||||||
|
if not vote:
|
||||||
|
continue
|
||||||
|
if vote not in allowed:
|
||||||
|
return AnswerResult(error="choice")
|
||||||
|
votes[option["id"]] = vote
|
||||||
|
if not votes:
|
||||||
|
return AnswerResult()
|
||||||
|
if q.required and len(votes) < len(options_of(q)):
|
||||||
|
return AnswerResult(error="poll_incomplete")
|
||||||
|
return AnswerResult({"value_json": {"votes": votes}})
|
||||||
|
if t == "file_upload":
|
||||||
|
chosen = [f for f in (_file_descriptor(v) for v in files.get(q.id) or []) if f]
|
||||||
|
if not chosen:
|
||||||
|
return AnswerResult()
|
||||||
|
if len(chosen) > int(cfg.get("max_files") or 1):
|
||||||
|
return AnswerResult(error="files_too_many")
|
||||||
|
return AnswerResult({"value_json": {"files": chosen}})
|
||||||
|
if t == "rating":
|
||||||
|
if not raw:
|
||||||
|
return AnswerResult()
|
||||||
|
try:
|
||||||
|
value_i = int(raw)
|
||||||
|
except ValueError:
|
||||||
|
return AnswerResult(error="rating")
|
||||||
|
if not 1 <= value_i <= int(cfg.get("scale_max") or 5):
|
||||||
|
return AnswerResult(error="rating")
|
||||||
|
return AnswerResult({"value_number": Decimal(value_i)})
|
||||||
|
return AnswerResult()
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_name(cfg: Mapping[str, Any], fields: Fields, name: str) -> AnswerResult:
|
||||||
|
first = " ".join(_first(fields, f"{name}_first").split())
|
||||||
|
last = " ".join(_first(fields, f"{name}_last").split())
|
||||||
|
mode = cfg.get("email") or "optional"
|
||||||
|
email = _first(fields, f"{name}_email").strip() if mode != "off" else ""
|
||||||
|
if not (first or last or email):
|
||||||
|
return AnswerResult()
|
||||||
|
if not first or not last:
|
||||||
|
return AnswerResult(error="name_incomplete")
|
||||||
|
if len(first) > MAX_NAME_PART or len(last) > MAX_NAME_PART:
|
||||||
|
return AnswerResult(error="too_long")
|
||||||
|
if email and (len(email) > 254 or not _EMAIL.match(email)):
|
||||||
|
return AnswerResult(error="email")
|
||||||
|
if mode == "required" and not email:
|
||||||
|
return AnswerResult(error="name_email_missing")
|
||||||
|
data = {"first": first, "last": last}
|
||||||
|
if email:
|
||||||
|
data["email"] = email
|
||||||
|
return AnswerResult({"value_text": f"{first} {last}", "value_json": data})
|
||||||
|
|
||||||
|
|
||||||
|
def name_parts(stored: Mapping[str, Any]) -> dict[str, str]:
|
||||||
|
data = stored.get("value_json") or {}
|
||||||
|
return {part: str(data.get(part) or "") for part in NAME_PARTS}
|
||||||
|
|
||||||
|
|
||||||
|
def short_name(first: str, last: str) -> str:
|
||||||
|
"""Datensparsame Anzeige: Vorname und Anfangsbuchstabe des Nachnamens."""
|
||||||
|
return f"{first} {last[:1]}." if last else first
|
||||||
|
|
||||||
|
|
||||||
|
def _file_descriptor(raw: Any) -> dict[str, Any] | None:
|
||||||
|
"""Vom Server geprüfte Datei (siehe forms.service.attach_uploads)."""
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
return None
|
||||||
|
if not {"id", "name", "size"} <= raw.keys():
|
||||||
|
return None
|
||||||
|
return {"id": str(raw["id"]), "name": str(raw["name"]), "size": int(raw["size"])}
|
||||||
|
|
||||||
|
|
||||||
|
def format_size(size: int) -> str:
|
||||||
|
if size < 1024 * 1024:
|
||||||
|
return f"{max(1, round(size / 1024))} KB"
|
||||||
|
return f"{size / (1024 * 1024):.1f} MB".replace(".", ",")
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Gespeicherte Antworten anzeigen und wieder ins Formular füllen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _fmt_number(value: Decimal, decimals: int) -> str:
|
||||||
|
quantized = value.quantize(Decimal(1).scaleb(-decimals)) if decimals else value.to_integral()
|
||||||
|
return f"{quantized}"
|
||||||
|
|
||||||
|
|
||||||
|
def display_answer(q: QuestionLike, stored: Stored, tz: ZoneInfo) -> str:
|
||||||
|
t, cfg = q.type, q.config
|
||||||
|
if t in ("short_text", "long_text", "email", "phone"):
|
||||||
|
return str(stored.get("value_text") or "")
|
||||||
|
if t == "participant_name":
|
||||||
|
parts = name_parts(stored)
|
||||||
|
text = f"{parts['first']} {parts['last']}".strip()
|
||||||
|
return f"{text} <{parts['email']}>" if parts["email"] else text
|
||||||
|
if t == "number":
|
||||||
|
value = stored.get("value_number")
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
unit = cfg.get("unit") or ""
|
||||||
|
text = _fmt_number(Decimal(value), int(cfg.get("decimals") or 0))
|
||||||
|
return f"{text} {unit}".strip()
|
||||||
|
if t == "rating":
|
||||||
|
value = stored.get("value_number")
|
||||||
|
return "" if value is None else f"{int(value)} / {int(cfg.get('scale_max') or 5)}"
|
||||||
|
if t == "date":
|
||||||
|
d = stored.get("value_date")
|
||||||
|
return d.strftime("%d.%m.%Y") if d else ""
|
||||||
|
if t == "time":
|
||||||
|
tv = stored.get("value_time")
|
||||||
|
return tv.strftime("%H:%M") if tv else ""
|
||||||
|
if t == "datetime":
|
||||||
|
dt = stored.get("value_datetime")
|
||||||
|
return dt.astimezone(tz).strftime("%d.%m.%Y %H:%M") if dt else ""
|
||||||
|
if t == "yes_no":
|
||||||
|
b = stored.get("value_bool")
|
||||||
|
if b is None:
|
||||||
|
return ""
|
||||||
|
if b:
|
||||||
|
return cfg.get("label_yes") or gettext("Yes")
|
||||||
|
return cfg.get("label_no") or gettext("No")
|
||||||
|
deleted = gettext("(deleted option)")
|
||||||
|
if t == "single_choice":
|
||||||
|
value = stored.get("value_text")
|
||||||
|
if value == OTHER:
|
||||||
|
other = (stored.get("value_json") or {}).get("other") or ""
|
||||||
|
return f"{gettext('Other')}: {other}"
|
||||||
|
return (option_label(q, value) or deleted) if value else ""
|
||||||
|
if t == "multiple_choice":
|
||||||
|
data = stored.get("value_json") or {}
|
||||||
|
parts = [option_label(q, oid) or deleted for oid in data.get("selected") or []]
|
||||||
|
if data.get("other"):
|
||||||
|
parts.append(f"{gettext('Other')}: {data['other']}")
|
||||||
|
return ", ".join(parts)
|
||||||
|
if t == "slots" and cfg.get("single"):
|
||||||
|
selected = (stored.get("value_json") or {}).get("selected")
|
||||||
|
return gettext("signed up") if selected else ""
|
||||||
|
if t == "slots":
|
||||||
|
data = stored.get("value_json") or {}
|
||||||
|
return ", ".join(option_label(q, oid) or deleted for oid in data.get("selected") or [])
|
||||||
|
if t == "poll":
|
||||||
|
votes = (stored.get("value_json") or {}).get("votes") or {}
|
||||||
|
names = {"yes": gettext("Yes"), "no": gettext("No"), "maybe": gettext("Maybe")}
|
||||||
|
by_id = {o["id"]: o for o in options_of(q)}
|
||||||
|
return "; ".join(
|
||||||
|
f"{option_text(by_id[oid]) if oid in by_id else deleted}: {names.get(v, v)}"
|
||||||
|
for oid, v in votes.items()
|
||||||
|
)
|
||||||
|
if t == "file_upload":
|
||||||
|
files = (stored.get("value_json") or {}).get("files") or []
|
||||||
|
return ", ".join(f"{f['name']} ({format_size(int(f['size']))})" for f in files)
|
||||||
|
if t == "ranking":
|
||||||
|
data = stored.get("value_json") or {}
|
||||||
|
return ", ".join(
|
||||||
|
f"{i}. {option_label(q, oid) or deleted}"
|
||||||
|
for i, oid in enumerate(data.get("order") or [], start=1)
|
||||||
|
)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def raw_from_answer(q: QuestionLike, stored: Stored, tz: ZoneInfo) -> dict[str, list[str]]:
|
||||||
|
"""Gespeicherte Antwort -> Formularfelder (zum Bearbeiten)."""
|
||||||
|
name = field_name(q)
|
||||||
|
t = q.type
|
||||||
|
if t in ("short_text", "long_text", "email", "phone"):
|
||||||
|
return {name: [stored.get("value_text") or ""]}
|
||||||
|
if t == "participant_name":
|
||||||
|
return {f"{name}_{part}": [value] for part, value in name_parts(stored).items() if value}
|
||||||
|
if t in ("number", "rating"):
|
||||||
|
value = stored.get("value_number")
|
||||||
|
if value is None:
|
||||||
|
return {}
|
||||||
|
if t == "rating":
|
||||||
|
return {name: [str(int(value))]}
|
||||||
|
return {name: [_fmt_number(Decimal(value), int(q.config.get("decimals") or 0))]}
|
||||||
|
if t == "date":
|
||||||
|
d = stored.get("value_date")
|
||||||
|
return {name: [d.isoformat()]} if d else {}
|
||||||
|
if t == "time":
|
||||||
|
tv = stored.get("value_time")
|
||||||
|
return {name: [tv.strftime("%H:%M")]} if tv else {}
|
||||||
|
if t == "datetime":
|
||||||
|
dt = stored.get("value_datetime")
|
||||||
|
return {name: [dt.astimezone(tz).strftime("%Y-%m-%dT%H:%M")]} if dt else {}
|
||||||
|
if t == "yes_no":
|
||||||
|
b = stored.get("value_bool")
|
||||||
|
return {} if b is None else {name: ["yes" if b else "no"]}
|
||||||
|
if t == "single_choice":
|
||||||
|
value = stored.get("value_text")
|
||||||
|
result = {name: [value]} if value else {}
|
||||||
|
if value == OTHER:
|
||||||
|
result[f"{name}_other"] = [(stored.get("value_json") or {}).get("other") or ""]
|
||||||
|
return result
|
||||||
|
if t == "multiple_choice":
|
||||||
|
data = stored.get("value_json") or {}
|
||||||
|
selected = list(data.get("selected") or [])
|
||||||
|
result = {name: selected + ([OTHER] if data.get("other") else [])}
|
||||||
|
if data.get("other"):
|
||||||
|
result[f"{name}_other"] = [data["other"]]
|
||||||
|
return result
|
||||||
|
if t == "slots":
|
||||||
|
return {name: list((stored.get("value_json") or {}).get("selected") or [])}
|
||||||
|
if t == "poll":
|
||||||
|
votes = (stored.get("value_json") or {}).get("votes") or {}
|
||||||
|
return {f"{name}_{oid}": [vote] for oid, vote in votes.items()}
|
||||||
|
if t == "ranking":
|
||||||
|
data = stored.get("value_json") or {}
|
||||||
|
return {
|
||||||
|
f"{name}_rank_{oid}": [str(i)]
|
||||||
|
for i, oid in enumerate(data.get("order") or [], start=1)
|
||||||
|
}
|
||||||
|
return {}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Dateien beim Ausfüllen (Fragetyp "Datei-Upload").
|
||||||
|
|
||||||
|
Ablauf: Eine Datei wird beim Absenden sofort gespeichert, aber nur als
|
||||||
|
"vorläufig" (verfällt nach 24 Stunden). Ist im Formular noch etwas falsch,
|
||||||
|
bekommt die Seite für jede schon gespeicherte Datei eine signierte Kennung
|
||||||
|
zurück; so muss niemand eine Datei zweimal hochladen. Erst mit dem
|
||||||
|
erfolgreichen Absenden gehört die Datei zur Antwort.
|
||||||
|
|
||||||
|
Die Signatur verhindert, dass jemand fremde Dateien in seine Antwort holt.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any, BinaryIO, Protocol
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.forms import types
|
||||||
|
from surveybox.media import service as media_service
|
||||||
|
from surveybox.media import sniff
|
||||||
|
from surveybox.media.service import MediaError
|
||||||
|
from surveybox.models import Form, MediaFile, MediaKind, Question, Response
|
||||||
|
from surveybox.security.tokens import constant_time_equal, derive_key, keyed_hash
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
FIELD_KEEP = "_keep"
|
||||||
|
|
||||||
|
|
||||||
|
class UploadLike(Protocol):
|
||||||
|
filename: str | None
|
||||||
|
file: BinaryIO
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Collected:
|
||||||
|
files: dict[int, list[dict[str, Any]]] = field(default_factory=dict)
|
||||||
|
errors: dict[int, str] = field(default_factory=dict)
|
||||||
|
count_new: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
def token(secret_key: str, form: Form, media_id: str) -> str:
|
||||||
|
sig = keyed_hash(derive_key(secret_key, "upload"), f"{form.id}:{media_id}").hex()[:32]
|
||||||
|
return f"{media_id}.{sig}"
|
||||||
|
|
||||||
|
|
||||||
|
def _verify(secret_key: str, form: Form, value: str) -> str | None:
|
||||||
|
media_id, _, _sig = value.partition(".")
|
||||||
|
if not media_id or not constant_time_equal(token(secret_key, form, media_id), value):
|
||||||
|
return None
|
||||||
|
return media_id
|
||||||
|
|
||||||
|
|
||||||
|
def descriptor(media: MediaFile) -> dict[str, Any]:
|
||||||
|
return {"id": str(media.public_id), "name": media.original_name or "", "size": media.size}
|
||||||
|
|
||||||
|
|
||||||
|
def allowed_keys(question: Question) -> frozenset[str]:
|
||||||
|
keys: set[str] = set()
|
||||||
|
for group in question.config.get("groups") or []:
|
||||||
|
keys |= sniff.UPLOAD_GROUPS.get(group, frozenset())
|
||||||
|
return frozenset(keys)
|
||||||
|
|
||||||
|
|
||||||
|
def accept_attribute(question: Question) -> str:
|
||||||
|
"""Hinweis für den Dateidialog des Browsers (geprüft wird auf dem Server)."""
|
||||||
|
return ",".join(
|
||||||
|
f".{sniff.TYPES[key].extension}" + (",.jpeg" if key == "jpeg" else "")
|
||||||
|
for key in sorted(allowed_keys(question))
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def collect(
|
||||||
|
db: Session,
|
||||||
|
settings: Settings,
|
||||||
|
form: Form,
|
||||||
|
fields: dict[str, list[str]],
|
||||||
|
uploads: dict[str, list[UploadLike]],
|
||||||
|
max_mb: int,
|
||||||
|
response: Response | None = None,
|
||||||
|
) -> Collected:
|
||||||
|
"""Behaltene und neue Dateien je Datei-Frage prüfen und speichern."""
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
result = Collected()
|
||||||
|
for question in form.questions:
|
||||||
|
if question.type != "file_upload":
|
||||||
|
continue
|
||||||
|
name = types.field_name(question)
|
||||||
|
kept_ids = [
|
||||||
|
mid
|
||||||
|
for mid in (_verify(secret, form, v) for v in fields.get(name + FIELD_KEEP) or [])
|
||||||
|
if mid
|
||||||
|
]
|
||||||
|
found = media_service.by_ids(db, form, kept_ids)
|
||||||
|
chosen: list[dict[str, Any]] = []
|
||||||
|
for media_id in dict.fromkeys(kept_ids):
|
||||||
|
media = found.get(media_id)
|
||||||
|
if media is None or media.kind != MediaKind.UPLOAD or media.question_id != question.id:
|
||||||
|
continue
|
||||||
|
# Nur eigene vorläufige Dateien oder Dateien der bearbeiteten Antwort
|
||||||
|
if media.response_id is not None and (
|
||||||
|
response is None or media.response_id != response.id
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
chosen.append(descriptor(media))
|
||||||
|
|
||||||
|
limit = min(max_mb, int(question.config.get("max_mb") or 10))
|
||||||
|
for upload in uploads.get(name) or []:
|
||||||
|
try:
|
||||||
|
incoming = media_service.receive(
|
||||||
|
settings, upload.file, upload.filename or "", limit
|
||||||
|
)
|
||||||
|
media = media_service.store_answer_file(
|
||||||
|
db, settings, form, question, incoming, allowed_keys(question)
|
||||||
|
)
|
||||||
|
except MediaError as exc:
|
||||||
|
result.errors[question.id] = exc.code
|
||||||
|
continue
|
||||||
|
result.count_new += 1
|
||||||
|
chosen.append(descriptor(media))
|
||||||
|
if chosen:
|
||||||
|
result.files[question.id] = chosen
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def keep_fields(
|
||||||
|
secret_key: str, form: Form, files: dict[int, list[dict[str, Any]]]
|
||||||
|
) -> dict[str, list[str]]:
|
||||||
|
"""Signierte Kennungen der gespeicherten Dateien, um sie im Formular zu behalten."""
|
||||||
|
return {
|
||||||
|
f"q{qid}{FIELD_KEEP}": [token(secret_key, form, f["id"]) for f in items]
|
||||||
|
for qid, items in files.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def from_response(response: Response, form: Form) -> dict[int, list[dict[str, Any]]]:
|
||||||
|
by_question = {a.question_id: a for a in response.answers}
|
||||||
|
result: dict[int, list[dict[str, Any]]] = {}
|
||||||
|
for question in form.questions:
|
||||||
|
if question.type != "file_upload":
|
||||||
|
continue
|
||||||
|
answer = by_question.get(question.id)
|
||||||
|
files = ((answer.value_json if answer else None) or {}).get("files") or []
|
||||||
|
if files:
|
||||||
|
result[question.id] = list(files)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def link(
|
||||||
|
db: Session, form: Form, response: Response, files: dict[int, list[dict[str, Any]]]
|
||||||
|
) -> None:
|
||||||
|
"""Dateien gehören jetzt zur Antwort; nicht mehr gewählte verschwinden."""
|
||||||
|
db.flush() # die Antwort braucht ihre ID
|
||||||
|
wanted = {f["id"] for items in files.values() for f in items}
|
||||||
|
rows = media_service.by_ids(db, form, list(wanted))
|
||||||
|
for media in rows.values():
|
||||||
|
media.response_id = response.id
|
||||||
|
media.pending_until = None
|
||||||
|
old = db.scalars(
|
||||||
|
select(MediaFile).where(
|
||||||
|
MediaFile.response_id == response.id, MediaFile.kind == MediaKind.UPLOAD
|
||||||
|
)
|
||||||
|
)
|
||||||
|
for media in old:
|
||||||
|
if str(media.public_id) not in wanted:
|
||||||
|
db.delete(media)
|
||||||
@@ -0,0 +1,298 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Kleiner XLSX-Schreiber (Office Open XML) ohne zusätzliche Abhängigkeit.
|
||||||
|
|
||||||
|
Kann genau, was der Export braucht: Tabellenblätter mit Text und Zahlen, eine
|
||||||
|
hervorgehobene Kopfzeile (fett, grau hinterlegt) mit Autofilter, fette Titelzeilen,
|
||||||
|
Spaltenbreiten, ein Bild (Logo) und die Seiteneinrichtung für den Druck (Format,
|
||||||
|
Ränder, Fußzeile, an Seitenbreite anpassen, Kopfzeile auf jeder Seite). Texte
|
||||||
|
stehen als "inline strings" in den Zellen; Formeln gibt es nicht, deshalb können
|
||||||
|
Antworttexte keine Formeln einschleusen.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
import zipfile
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from decimal import Decimal
|
||||||
|
from xml.sax.saxutils import escape
|
||||||
|
|
||||||
|
Cell = str | int | float | Decimal | None
|
||||||
|
|
||||||
|
# In XML 1.0 verbotene Steuerzeichen (außer Tab, Zeilenumbruch, Wagenrücklauf)
|
||||||
|
_ILLEGAL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
|
||||||
|
MAX_CELL = 32767 # Höchstlänge einer Zelle in Excel
|
||||||
|
EMU_PER_PIXEL = 9525
|
||||||
|
|
||||||
|
NS_MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
|
||||||
|
NS_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
|
||||||
|
NS_PKG = "http://schemas.openxmlformats.org/package/2006/relationships"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Image:
|
||||||
|
png: bytes
|
||||||
|
width: int # Anzeigegröße in Pixel
|
||||||
|
height: int
|
||||||
|
|
||||||
|
|
||||||
|
CM_PER_INCH = 2.54
|
||||||
|
# Stile (Index in cellXfs): normal, fett, Kopfzeile (fett, 20 % grau), großer Titel
|
||||||
|
STYLE_BOLD, STYLE_HEADER, STYLE_TITLE = 1, 2, 3
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PageSetup:
|
||||||
|
landscape: bool = True
|
||||||
|
# Ränder in cm: links, rechts, oben, unten
|
||||||
|
margins: tuple[float, float, float, float] = (1.0, 1.0, 2.0, 1.2)
|
||||||
|
fit_width: bool = True # alle Spalten auf eine Seitenbreite, Höhe beliebig
|
||||||
|
footer: str = "" # Codes wie in Excel, z. B. "&CSeite &P von &N"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Sheet:
|
||||||
|
name: str
|
||||||
|
rows: list[Sequence[Cell]]
|
||||||
|
header: bool = False # Kopfzeile = header_row (Standard: erste Zeile)
|
||||||
|
widths: list[float] = field(default_factory=list)
|
||||||
|
image: Image | None = None
|
||||||
|
first_row: int = 1 # Daten beginnen in dieser Zeile (Platz für das Bild darüber)
|
||||||
|
header_row: int = 0 # Index der Kopfzeile in rows, wenn header gesetzt ist
|
||||||
|
bold_rows: set[int] = field(default_factory=set)
|
||||||
|
title_rows: set[int] = field(default_factory=set)
|
||||||
|
freeze: bool = True # Kopfzeile beim Blättern festhalten
|
||||||
|
page: PageSetup | None = None
|
||||||
|
|
||||||
|
def row_number(self, index: int) -> int:
|
||||||
|
return index + self.first_row
|
||||||
|
|
||||||
|
|
||||||
|
def column_name(index: int) -> str:
|
||||||
|
"""0 -> A, 25 -> Z, 26 -> AA."""
|
||||||
|
name = ""
|
||||||
|
index += 1
|
||||||
|
while index:
|
||||||
|
index, rest = divmod(index - 1, 26)
|
||||||
|
name = chr(65 + rest) + name
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: str) -> str:
|
||||||
|
return escape(_ILLEGAL.sub("", value)[:MAX_CELL])
|
||||||
|
|
||||||
|
|
||||||
|
def _cell(ref: str, value: Cell, style_id: int, force: bool = False) -> str:
|
||||||
|
style = f' s="{style_id}"' if style_id else ""
|
||||||
|
if force and (value is None or value == ""):
|
||||||
|
return f'<c r="{ref}"{style}/>' # leere Kopfzelle trotzdem grau
|
||||||
|
if value is None or value == "":
|
||||||
|
return ""
|
||||||
|
if isinstance(value, bool):
|
||||||
|
value = str(value)
|
||||||
|
if isinstance(value, int | float | Decimal):
|
||||||
|
return f'<c r="{ref}"{style}><v>{value}</v></c>'
|
||||||
|
return (f'<c r="{ref}" t="inlineStr"{style}><is><t xml:space="preserve">'
|
||||||
|
f"{_text(str(value))}</t></is></c>")
|
||||||
|
|
||||||
|
|
||||||
|
def _style(sheet: Sheet, index: int) -> int:
|
||||||
|
if sheet.header and index == sheet.header_row:
|
||||||
|
return STYLE_HEADER
|
||||||
|
if index in sheet.title_rows:
|
||||||
|
return STYLE_TITLE
|
||||||
|
return STYLE_BOLD if index in sheet.bold_rows else 0
|
||||||
|
|
||||||
|
|
||||||
|
def table_range(sheet: Sheet) -> tuple[int, int, int] | None:
|
||||||
|
"""(erste Zeile, letzte Zeile, Spaltenzahl) der Tabelle ab der Kopfzeile."""
|
||||||
|
if not sheet.header or len(sheet.rows) <= sheet.header_row:
|
||||||
|
return None
|
||||||
|
columns = len(sheet.rows[sheet.header_row])
|
||||||
|
return (sheet.row_number(sheet.header_row), sheet.row_number(len(sheet.rows) - 1), columns)
|
||||||
|
|
||||||
|
|
||||||
|
def _page_xml(page: PageSetup) -> str:
|
||||||
|
left, right, top, bottom = (m / CM_PER_INCH for m in page.margins)
|
||||||
|
# Fußzeile mittig im unteren Rand, Kopfzeile ungenutzt
|
||||||
|
parts = [f'<pageMargins left="{left:.4f}" right="{right:.4f}" top="{top:.4f}" '
|
||||||
|
f'bottom="{bottom:.4f}" header="{top / 2:.4f}" footer="{bottom / 2:.4f}"/>']
|
||||||
|
fit = ' fitToWidth="1" fitToHeight="0"' if page.fit_width else ""
|
||||||
|
orientation = "landscape" if page.landscape else "portrait"
|
||||||
|
parts.append(f'<pageSetup paperSize="9" orientation="{orientation}"{fit}/>')
|
||||||
|
if page.footer:
|
||||||
|
parts.append(f"<headerFooter><oddFooter>{_text(page.footer)}</oddFooter></headerFooter>")
|
||||||
|
return "".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _sheet_xml(sheet: Sheet, drawing_rel: str | None) -> str:
|
||||||
|
table = table_range(sheet)
|
||||||
|
rows_xml = []
|
||||||
|
for r, row in enumerate(sheet.rows):
|
||||||
|
number = sheet.row_number(r)
|
||||||
|
style = _style(sheet, r)
|
||||||
|
header = sheet.header and r == sheet.header_row
|
||||||
|
cells = "".join(_cell(f"{column_name(c)}{number}", v, style, header)
|
||||||
|
for c, v in enumerate(row))
|
||||||
|
height = ' ht="22" customHeight="1"' if r in sheet.title_rows else ""
|
||||||
|
rows_xml.append(f'<row r="{number}"{height}>{cells}</row>')
|
||||||
|
parts = [f'<worksheet xmlns="{NS_MAIN}" xmlns:r="{NS_REL}">']
|
||||||
|
if sheet.page is not None and sheet.page.fit_width:
|
||||||
|
parts.append('<sheetPr><pageSetUpPr fitToPage="1"/></sheetPr>')
|
||||||
|
if table and sheet.freeze:
|
||||||
|
top = table[0] + 1
|
||||||
|
parts.append(f'<sheetViews><sheetView workbookViewId="0"><pane ySplit="{top - 1}" '
|
||||||
|
f'topLeftCell="A{top}" activePane="bottomLeft" state="frozen"/>'
|
||||||
|
"</sheetView></sheetViews>")
|
||||||
|
if sheet.widths:
|
||||||
|
cols = "".join(f'<col min="{i + 1}" max="{i + 1}" width="{w:.1f}" customWidth="1"/>'
|
||||||
|
for i, w in enumerate(sheet.widths))
|
||||||
|
parts.append(f"<cols>{cols}</cols>")
|
||||||
|
parts.append(f"<sheetData>{''.join(rows_xml)}</sheetData>")
|
||||||
|
if table and table[1] > table[0] and table[2]:
|
||||||
|
parts.append(f'<autoFilter ref="A{table[0]}:{column_name(table[2] - 1)}{table[1]}"/>')
|
||||||
|
if sheet.page is not None:
|
||||||
|
parts.append(_page_xml(sheet.page))
|
||||||
|
if drawing_rel:
|
||||||
|
parts.append(f'<drawing r:id="{drawing_rel}"/>')
|
||||||
|
parts.append("</worksheet>")
|
||||||
|
return "".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _drawing_xml(image: Image) -> str:
|
||||||
|
cx, cy = image.width * EMU_PER_PIXEL, image.height * EMU_PER_PIXEL
|
||||||
|
return (
|
||||||
|
'<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" '
|
||||||
|
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">'
|
||||||
|
'<xdr:oneCellAnchor><xdr:from><xdr:col>0</xdr:col><xdr:colOff>0</xdr:colOff>'
|
||||||
|
"<xdr:row>0</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from>"
|
||||||
|
f'<xdr:ext cx="{cx}" cy="{cy}"/>'
|
||||||
|
'<xdr:pic><xdr:nvPicPr><xdr:cNvPr id="2" name="Logo"/><xdr:cNvPicPr/></xdr:nvPicPr>'
|
||||||
|
f'<xdr:blipFill><a:blip xmlns:r="{NS_REL}" r:embed="rId1"/>'
|
||||||
|
"<a:stretch><a:fillRect/></a:stretch></xdr:blipFill>"
|
||||||
|
f'<xdr:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="{cx}" cy="{cy}"/></a:xfrm>'
|
||||||
|
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic>'
|
||||||
|
"<xdr:clientData/></xdr:oneCellAnchor></xdr:wsDr>"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
_STYLES = (
|
||||||
|
f'<styleSheet xmlns="{NS_MAIN}">'
|
||||||
|
'<fonts count="3"><font><sz val="11"/><name val="Calibri"/></font>'
|
||||||
|
'<font><b/><sz val="11"/><name val="Calibri"/></font>'
|
||||||
|
'<font><b/><sz val="14"/><name val="Calibri"/></font></fonts>'
|
||||||
|
'<fills count="3"><fill><patternFill patternType="none"/></fill>'
|
||||||
|
'<fill><patternFill patternType="gray125"/></fill>'
|
||||||
|
'<fill><patternFill patternType="solid"><fgColor rgb="FFCCCCCC"/><bgColor indexed="64"/>'
|
||||||
|
"</patternFill></fill></fills>"
|
||||||
|
'<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>'
|
||||||
|
'<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
|
||||||
|
'<cellXfs count="4"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'
|
||||||
|
'<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>'
|
||||||
|
'<xf numFmtId="0" fontId="1" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1"/>'
|
||||||
|
'<xf numFmtId="0" fontId="2" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs>'
|
||||||
|
'<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>'
|
||||||
|
"</styleSheet>"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _sheet_name(name: str, used: set[str]) -> str:
|
||||||
|
"""Excel: höchstens 31 Zeichen, ohne : \\ / ? * [ ], eindeutig."""
|
||||||
|
clean = re.sub(r"[:\\/?*\[\]]", " ", name).strip()[:31] or "Sheet"
|
||||||
|
candidate, n = clean, 2
|
||||||
|
while candidate.lower() in used:
|
||||||
|
suffix = f" ({n})"
|
||||||
|
candidate, n = clean[: 31 - len(suffix)] + suffix, n + 1
|
||||||
|
used.add(candidate.lower())
|
||||||
|
return candidate
|
||||||
|
|
||||||
|
|
||||||
|
def workbook(sheets: Sequence[Sheet]) -> bytes:
|
||||||
|
out = io.BytesIO()
|
||||||
|
used: set[str] = set()
|
||||||
|
names = [_sheet_name(s.name, used) for s in sheets]
|
||||||
|
images = [i for i, s in enumerate(sheets) if s.image is not None]
|
||||||
|
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
|
||||||
|
overrides = "".join(
|
||||||
|
f'<Override PartName="/xl/worksheets/sheet{i + 1}.xml" ContentType="application/'
|
||||||
|
'vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
|
||||||
|
for i in range(len(sheets))
|
||||||
|
) + "".join(
|
||||||
|
f'<Override PartName="/xl/drawings/drawing{i + 1}.xml" ContentType="application/'
|
||||||
|
'vnd.openxmlformats-officedocument.drawing+xml"/>' for i in images
|
||||||
|
)
|
||||||
|
z.writestr("[Content_Types].xml", (
|
||||||
|
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||||
|
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
|
||||||
|
'<Default Extension="rels" ContentType="application/'
|
||||||
|
'vnd.openxmlformats-package.relationships+xml"/>'
|
||||||
|
'<Default Extension="xml" ContentType="application/xml"/>'
|
||||||
|
'<Default Extension="png" ContentType="image/png"/>'
|
||||||
|
'<Override PartName="/xl/workbook.xml" ContentType="application/'
|
||||||
|
'vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
|
||||||
|
'<Override PartName="/xl/styles.xml" ContentType="application/'
|
||||||
|
'vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>'
|
||||||
|
f"{overrides}</Types>"))
|
||||||
|
z.writestr("_rels/.rels", (
|
||||||
|
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||||
|
f'<Relationships xmlns="{NS_PKG}">'
|
||||||
|
f'<Relationship Id="rId1" Type="{NS_REL}/officeDocument" Target="xl/workbook.xml"/>'
|
||||||
|
"</Relationships>"))
|
||||||
|
sheet_entries = "".join(
|
||||||
|
f'<sheet name="{escape(name, {chr(34): """})}" sheetId="{i + 1}" '
|
||||||
|
f'r:id="rId{i + 1}"/>'
|
||||||
|
for i, name in enumerate(names))
|
||||||
|
defined = []
|
||||||
|
for i, (sheet, name) in enumerate(zip(sheets, names, strict=True)):
|
||||||
|
table = table_range(sheet)
|
||||||
|
if table is None:
|
||||||
|
continue
|
||||||
|
quoted = "'" + name.replace("'", "''") + "'"
|
||||||
|
last = column_name(table[2] - 1)
|
||||||
|
# Für den Autofilter (Excel legt den Namen selbst so an) …
|
||||||
|
defined.append(f'<definedName name="_xlnm._FilterDatabase" localSheetId="{i}" '
|
||||||
|
f'hidden="1">{escape(quoted)}!$A${table[0]}:${last}${table[1]}'
|
||||||
|
"</definedName>")
|
||||||
|
# … und Kopfzeile auf jeder gedruckten Seite wiederholen
|
||||||
|
if sheet.page is not None:
|
||||||
|
defined.append(f'<definedName name="_xlnm.Print_Titles" localSheetId="{i}">'
|
||||||
|
f"{escape(quoted)}!${table[0]}:${table[0]}</definedName>")
|
||||||
|
names_xml = f"<definedNames>{''.join(defined)}</definedNames>" if defined else ""
|
||||||
|
z.writestr("xl/workbook.xml", (
|
||||||
|
f'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||||
|
f'<workbook xmlns="{NS_MAIN}" xmlns:r="{NS_REL}"><sheets>{sheet_entries}</sheets>'
|
||||||
|
f"{names_xml}</workbook>"))
|
||||||
|
rels = "".join(
|
||||||
|
f'<Relationship Id="rId{i + 1}" Type="{NS_REL}/worksheet" '
|
||||||
|
f'Target="worksheets/sheet{i + 1}.xml"/>' for i in range(len(sheets)))
|
||||||
|
rels += (f'<Relationship Id="rId{len(sheets) + 1}" Type="{NS_REL}/styles" '
|
||||||
|
'Target="styles.xml"/>')
|
||||||
|
z.writestr("xl/_rels/workbook.xml.rels", (
|
||||||
|
f'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||||
|
f'<Relationships xmlns="{NS_PKG}">{rels}</Relationships>'))
|
||||||
|
z.writestr("xl/styles.xml", '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||||
|
+ _STYLES)
|
||||||
|
for i, sheet in enumerate(sheets):
|
||||||
|
drawing = None
|
||||||
|
if sheet.image is not None:
|
||||||
|
drawing = "rId1"
|
||||||
|
z.writestr(f"xl/worksheets/_rels/sheet{i + 1}.xml.rels", (
|
||||||
|
f'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||||
|
f'<Relationships xmlns="{NS_PKG}"><Relationship Id="rId1" '
|
||||||
|
f'Type="{NS_REL}/drawing" Target="../drawings/drawing{i + 1}.xml"/>'
|
||||||
|
"</Relationships>"))
|
||||||
|
z.writestr(f"xl/drawings/drawing{i + 1}.xml",
|
||||||
|
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||||
|
+ _drawing_xml(sheet.image))
|
||||||
|
z.writestr(f"xl/drawings/_rels/drawing{i + 1}.xml.rels", (
|
||||||
|
f'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||||
|
f'<Relationships xmlns="{NS_PKG}"><Relationship Id="rId1" '
|
||||||
|
f'Type="{NS_REL}/image" Target="../media/image{i + 1}.png"/>'
|
||||||
|
"</Relationships>"))
|
||||||
|
z.writestr(f"xl/media/image{i + 1}.png", sheet.image.png)
|
||||||
|
z.writestr(f"xl/worksheets/sheet{i + 1}.xml",
|
||||||
|
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||||
|
+ _sheet_xml(sheet, drawing))
|
||||||
|
return out.getvalue()
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Übersetzungen (Deutsch, Englisch, Französisch) mit gettext.
|
||||||
|
|
||||||
|
Quelltexte im Code sind englisch; die Kataloge liegen unter
|
||||||
|
surveybox/locale/<sprache>/LC_MESSAGES/messages.po und werden beim Bauen
|
||||||
|
des Images zu .mo-Dateien übersetzt.
|
||||||
|
|
||||||
|
Die Sprache einer Anfrage steht in einer ContextVar. So nutzen Python-Code
|
||||||
|
und Vorlagen dieselbe Funktion `gettext`, ohne die Sprache durchreichen zu
|
||||||
|
müssen.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from contextvars import ContextVar, Token
|
||||||
|
from functools import cache
|
||||||
|
from gettext import NullTranslations
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from babel.support import Translations
|
||||||
|
|
||||||
|
LOCALE_DIR = Path(__file__).parent / "locale"
|
||||||
|
SUPPORTED_LANGUAGES: tuple[str, ...] = ("de", "en", "fr")
|
||||||
|
LANGUAGE_NAMES = {"de": "Deutsch", "en": "English", "fr": "Français"}
|
||||||
|
LANGUAGE_COOKIE = "surveybox_lang"
|
||||||
|
|
||||||
|
_current_language: ContextVar[str] = ContextVar("surveybox_language", default="de")
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def translations(language: str) -> NullTranslations:
|
||||||
|
if language not in SUPPORTED_LANGUAGES:
|
||||||
|
return NullTranslations()
|
||||||
|
loaded: NullTranslations = Translations.load(str(LOCALE_DIR), [language], domain="messages")
|
||||||
|
return loaded
|
||||||
|
|
||||||
|
|
||||||
|
def set_language(language: str) -> Token[str]:
|
||||||
|
return _current_language.set(language if language in SUPPORTED_LANGUAGES else "de")
|
||||||
|
|
||||||
|
|
||||||
|
def reset_language(token: Token[str]) -> None:
|
||||||
|
_current_language.reset(token)
|
||||||
|
|
||||||
|
|
||||||
|
def get_language() -> str:
|
||||||
|
return _current_language.get()
|
||||||
|
|
||||||
|
|
||||||
|
def N_(message: str) -> str:
|
||||||
|
"""Markiert einen Text für die Übersetzung, übersetzt ihn aber noch nicht.
|
||||||
|
|
||||||
|
Für Texte, die in Python festgelegt und erst in der Vorlage übersetzt werden.
|
||||||
|
"""
|
||||||
|
return message
|
||||||
|
|
||||||
|
|
||||||
|
def gettext(message: str) -> str:
|
||||||
|
return translations(get_language()).gettext(message)
|
||||||
|
|
||||||
|
|
||||||
|
def ngettext(singular: str, plural: str, n: int) -> str:
|
||||||
|
return translations(get_language()).ngettext(singular, plural, n)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_accept_language(header: str) -> list[str]:
|
||||||
|
"""Primäre Sprachcodes aus Accept-Language, nach Gewichtung sortiert."""
|
||||||
|
entries: list[tuple[float, int, str]] = []
|
||||||
|
for index, raw in enumerate(header.split(",")):
|
||||||
|
part = raw.strip()
|
||||||
|
if not part:
|
||||||
|
continue
|
||||||
|
tag, _, params = part.partition(";")
|
||||||
|
quality = 1.0
|
||||||
|
for param in params.split(";"):
|
||||||
|
key, _, value = param.strip().partition("=")
|
||||||
|
if key == "q":
|
||||||
|
try:
|
||||||
|
quality = float(value)
|
||||||
|
except ValueError:
|
||||||
|
quality = 0.0
|
||||||
|
if quality <= 0:
|
||||||
|
continue
|
||||||
|
primary = tag.strip().split("-")[0].split("_")[0].lower()
|
||||||
|
if primary and primary != "*":
|
||||||
|
entries.append((-quality, index, primary))
|
||||||
|
return [lang for _, _, lang in sorted(entries)]
|
||||||
|
|
||||||
|
|
||||||
|
def negotiate_language(
|
||||||
|
cookie: str | None, accept_language: str | None, default: str
|
||||||
|
) -> str:
|
||||||
|
"""Gewählte Sprache: Cookie vor Browser-Einstellung vor Standard."""
|
||||||
|
if cookie is not None and cookie in SUPPORTED_LANGUAGES:
|
||||||
|
return cookie
|
||||||
|
if accept_language:
|
||||||
|
for lang in _parse_accept_language(accept_language):
|
||||||
|
if lang in SUPPORTED_LANGUAGES:
|
||||||
|
return lang
|
||||||
|
return default if default in SUPPORTED_LANGUAGES else "de"
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""E-Mail: Einstellungen, Warteschlange, Versand über ein SMTP-Relay, Benachrichtigungen."""
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Einstellungen des SMTP-Relays, die der Administrator in der Oberfläche pflegt.
|
||||||
|
|
||||||
|
Sie stehen als JSON in `app_setting` (Schlüssel "mail"). Das Passwort liegt
|
||||||
|
verschlüsselt darin (security.secretbox, Schlüssel aus SURVEYBOX_SECRET_KEY)
|
||||||
|
und wird nie wieder angezeigt.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import ipaddress
|
||||||
|
import re
|
||||||
|
from dataclasses import asdict, dataclass, replace
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
from surveybox.security import secretbox
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
KEY = "mail"
|
||||||
|
SECURITY_MODES = ("starttls", "tls")
|
||||||
|
PASSWORD_PURPOSE = "smtp-password" # noqa: S105 - Zweck der Schlüsselableitung, kein Passwort
|
||||||
|
|
||||||
|
_LABEL = r"[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?"
|
||||||
|
_HOST = re.compile(rf"^(?=.{{1,253}}$){_LABEL}(\.{_LABEL})*$")
|
||||||
|
_ADDRESS = re.compile(r"^[^@\s<>\"(),;:\\]{1,64}@[a-z0-9.-]{1,252}\.[a-z]{2,63}$", re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
|
class MailConfigError(ValueError):
|
||||||
|
def __init__(self, code: str) -> None:
|
||||||
|
super().__init__(code)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class MailConfig:
|
||||||
|
host: str = ""
|
||||||
|
port: int = 587
|
||||||
|
security: str = "starttls"
|
||||||
|
username: str = ""
|
||||||
|
password_enc: str = "" # base64 des verschlüsselten Passworts
|
||||||
|
from_address: str = ""
|
||||||
|
from_name: str = "Surveybox"
|
||||||
|
reply_to: str = ""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def configured(self) -> bool:
|
||||||
|
return bool(self.host and self.from_address)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def has_password(self) -> bool:
|
||||||
|
return bool(self.password_enc)
|
||||||
|
|
||||||
|
def password(self, secret_key: str) -> str:
|
||||||
|
if not self.password_enc:
|
||||||
|
return ""
|
||||||
|
blob = base64.b64decode(self.password_enc)
|
||||||
|
return secretbox.decrypt(secret_key, PASSWORD_PURPOSE, blob).decode("utf-8")
|
||||||
|
|
||||||
|
def with_password(self, secret_key: str, password: str) -> MailConfig:
|
||||||
|
if not password:
|
||||||
|
return replace(self, password_enc="")
|
||||||
|
blob = secretbox.encrypt(secret_key, PASSWORD_PURPOSE, password.encode("utf-8"))
|
||||||
|
return replace(self, password_enc=base64.b64encode(blob).decode("ascii"))
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Prüfen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def clean_host(raw: str) -> str:
|
||||||
|
"""Hostname oder IP-Adresse des Relays, ohne Schema und Port."""
|
||||||
|
value = raw.strip().lower().rstrip(".")
|
||||||
|
if not value:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
return str(ipaddress.ip_address(value.strip("[]")))
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
if not _HOST.match(value):
|
||||||
|
raise MailConfigError("mail_host_invalid")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def clean_address(raw: str, *, required: bool = False) -> str:
|
||||||
|
"""E-Mail-Adresse ohne Namen; Zeilenumbrüche sind ausgeschlossen."""
|
||||||
|
value = raw.strip()
|
||||||
|
if not value:
|
||||||
|
if required:
|
||||||
|
raise MailConfigError("mail_address_invalid")
|
||||||
|
return ""
|
||||||
|
if len(value) > 254 or not _ADDRESS.match(value):
|
||||||
|
raise MailConfigError("mail_address_invalid")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def clean_name(raw: str) -> str:
|
||||||
|
"""Absendername: eine Zeile, ohne Steuerzeichen."""
|
||||||
|
return " ".join("".join(ch if ch.isprintable() else " " for ch in raw).split())[:100]
|
||||||
|
|
||||||
|
|
||||||
|
def address_valid(raw: str) -> bool:
|
||||||
|
try:
|
||||||
|
return bool(clean_address(raw, required=True))
|
||||||
|
except MailConfigError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Laden und speichern
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def from_dict(data: dict[str, Any]) -> MailConfig:
|
||||||
|
def text(key: str, default: str = "") -> str:
|
||||||
|
value = data.get(key)
|
||||||
|
return value if isinstance(value, str) else default
|
||||||
|
|
||||||
|
try:
|
||||||
|
port = int(data.get("port") or 587)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
port = 587
|
||||||
|
security = text("security", "starttls")
|
||||||
|
return MailConfig(
|
||||||
|
host=text("host"),
|
||||||
|
port=port if 1 <= port <= 65535 else 587,
|
||||||
|
security=security if security in SECURITY_MODES else "starttls",
|
||||||
|
username=text("username"),
|
||||||
|
password_enc=text("password_enc"),
|
||||||
|
from_address=text("from_address"),
|
||||||
|
from_name=text("from_name", "Surveybox"),
|
||||||
|
reply_to=text("reply_to"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def load(db: Session) -> MailConfig:
|
||||||
|
from surveybox.models import AppSetting
|
||||||
|
|
||||||
|
row = db.get(AppSetting, KEY)
|
||||||
|
return from_dict(row.value if row is not None and isinstance(row.value, dict) else {})
|
||||||
|
|
||||||
|
|
||||||
|
def save(db: Session, cfg: MailConfig) -> None:
|
||||||
|
from surveybox.models import AppSetting
|
||||||
|
|
||||||
|
row = db.get(AppSetting, KEY)
|
||||||
|
if row is None:
|
||||||
|
db.add(AppSetting(key=KEY, value=asdict(cfg)))
|
||||||
|
else:
|
||||||
|
row.value = asdict(cfg)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_form(
|
||||||
|
current: MailConfig, fields: dict[str, list[str]], secret_key: str
|
||||||
|
) -> MailConfig:
|
||||||
|
"""Eingaben der Admin-Seite. Leeres Passwortfeld lässt das alte Passwort stehen."""
|
||||||
|
|
||||||
|
def first(name: str) -> str:
|
||||||
|
values = fields.get(name) or []
|
||||||
|
return values[0] if values else ""
|
||||||
|
|
||||||
|
try:
|
||||||
|
port = int(first("port").strip() or 587)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise MailConfigError("mail_port_invalid") from exc
|
||||||
|
if not 1 <= port <= 65535:
|
||||||
|
raise MailConfigError("mail_port_invalid")
|
||||||
|
security = first("security")
|
||||||
|
if security not in SECURITY_MODES:
|
||||||
|
raise MailConfigError("mail_security_invalid")
|
||||||
|
host = clean_host(first("host"))
|
||||||
|
from_address = clean_address(first("from_address"), required=bool(host))
|
||||||
|
username = "".join(ch for ch in first("username").strip() if ch.isprintable())[:200]
|
||||||
|
cfg = MailConfig(
|
||||||
|
host=host,
|
||||||
|
port=port,
|
||||||
|
security=security,
|
||||||
|
username=username,
|
||||||
|
password_enc=current.password_enc,
|
||||||
|
from_address=from_address,
|
||||||
|
from_name=clean_name(first("from_name")) or "Surveybox",
|
||||||
|
reply_to=clean_address(first("reply_to")),
|
||||||
|
)
|
||||||
|
password = first("password")
|
||||||
|
if first("password_remove") == "on" or not username:
|
||||||
|
cfg = cfg.with_password(secret_key, "")
|
||||||
|
elif password:
|
||||||
|
if len(password) > 500 or any(ch in password for ch in "\r\n"):
|
||||||
|
raise MailConfigError("mail_password_invalid")
|
||||||
|
cfg = cfg.with_password(secret_key, password)
|
||||||
|
return cfg
|
||||||
|
|
||||||
|
|
||||||
|
def summary(cfg: MailConfig) -> dict[str, Any]:
|
||||||
|
"""Für das Protokoll: ohne Passwort und ohne E-Mail-Adressen (siehe accounts.audit)."""
|
||||||
|
return {
|
||||||
|
"host": cfg.host,
|
||||||
|
"port": cfg.port,
|
||||||
|
"security": cfg.security,
|
||||||
|
"username_set": bool(cfg.username),
|
||||||
|
"password_set": cfg.has_password,
|
||||||
|
"from_address_set": bool(cfg.from_address),
|
||||||
|
"reply_to_set": bool(cfg.reply_to),
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Eigene Mail-Vorlagen der Instanz (White-Labeling), je Mailart und Sprache.
|
||||||
|
|
||||||
|
Eine eigene Vorlage ist reiner Text mit Platzhaltern in geschweiften Klammern, kein
|
||||||
|
Jinja: Administratoren können damit nichts ausführen. Verfügbar sind
|
||||||
|
- {greeting}: Anrede ("Hallo Erika," oder "Hallo,"),
|
||||||
|
- {details}: der Standardtext der Mail ohne Anrede, also alles, was Surveybox je nach
|
||||||
|
Lage hineinschreibt (Listen, Hinweise für Gäste, Bestätigungslinks),
|
||||||
|
- {app}: Name der Anwendung, {title}: Titel des Formulars,
|
||||||
|
- je Mailart die einfachen Werte der Vorlage, etwa {name}, {link}, {entry}.
|
||||||
|
|
||||||
|
Enthält eine eigene Vorlage {details} nicht, muss sie die Links der Mailart selbst
|
||||||
|
enthalten (z. B. {link}), sonst kommt die Mail ohne den entscheidenden Link an.
|
||||||
|
Unbekannte Platzhalter werden beim Speichern abgelehnt.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from functools import cache
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
from surveybox import i18n
|
||||||
|
from surveybox.i18n import N_
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
SETTING_KEY = "mail_templates"
|
||||||
|
MAX_SUBJECT = 200
|
||||||
|
MAX_BODY = 10_000
|
||||||
|
LANGUAGES = ("de", "en", "fr")
|
||||||
|
_PLACEHOLDER = re.compile(r"\{([a-z_]+)\}")
|
||||||
|
|
||||||
|
# Mailarten, die sich anpassen lassen (Test-Mail und Folge-Mails haben eigene Texte)
|
||||||
|
KINDS: dict[str, str] = {
|
||||||
|
"invite": N_("Invitation to a new account"),
|
||||||
|
"password_reset": N_("Reset password"),
|
||||||
|
"register": N_("Self-registration: confirm address"),
|
||||||
|
"register_exists": N_("Self-registration: account already exists"),
|
||||||
|
"participation": N_("Confirmation of participation (with account)"),
|
||||||
|
"guest_receipt": N_("Confirmation of participation (guest, with personal link)"),
|
||||||
|
"guest_links": N_("Guest: personal links requested again"),
|
||||||
|
"guest_erase": N_("Guest: delete own data"),
|
||||||
|
"guest_export": N_("Guest: download own data"),
|
||||||
|
"promoted": N_("Moved up from the waiting list"),
|
||||||
|
"confirmed": N_("Date confirmed in a poll"),
|
||||||
|
"changed": N_("Chosen entry or date removed"),
|
||||||
|
"reminder": N_("Reminder before the end date"),
|
||||||
|
"comment_published": N_("Comment published"),
|
||||||
|
"comment_new": N_("New comment (managers)"),
|
||||||
|
"slot_full": N_("Entry booked up (owner)"),
|
||||||
|
"deadline": N_("Form has reached its end date (owner)"),
|
||||||
|
"digest": N_("Daily summary (managers)"),
|
||||||
|
"retention_notice": N_("Retention period ends soon (owner)"),
|
||||||
|
}
|
||||||
|
|
||||||
|
# Einfache Werte, die als Platzhalter taugen (Listen und Objekte nur über {details})
|
||||||
|
SCALARS: dict[str, str] = {
|
||||||
|
"name": N_("name of the recipient (may be empty)"),
|
||||||
|
"link": N_("the main link of this email"),
|
||||||
|
"confirm": N_("link to confirm the email address (only if one is needed)"),
|
||||||
|
"entry": N_("the entry concerned"),
|
||||||
|
"closes": N_("end date of the form"),
|
||||||
|
"date": N_("date of the deletion"),
|
||||||
|
"responses": N_("number of answers"),
|
||||||
|
"links_url": N_("page to request personal links again"),
|
||||||
|
"forgot_url": N_("page “Forgot password”"),
|
||||||
|
"login_url": N_("sign-in page"),
|
||||||
|
"settings_link": N_("settings of the form"),
|
||||||
|
}
|
||||||
|
# Links, ohne die eine Mail ihren Zweck verfehlt
|
||||||
|
REQUIRED = ("link", "forgot_url", "login_url", "settings_link")
|
||||||
|
COMMON: dict[str, str] = {
|
||||||
|
"greeting": N_("greeting, e.g. “Hello Erika,”"),
|
||||||
|
"details": N_("the standard text of this email without the greeting"),
|
||||||
|
"app": N_("name of the application"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Custom:
|
||||||
|
subject: str
|
||||||
|
body: str
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def variables(kind: str) -> tuple[str, ...]:
|
||||||
|
"""Variablen, die die Standardvorlage dieser Mailart verwendet."""
|
||||||
|
from jinja2 import Environment, meta
|
||||||
|
|
||||||
|
from surveybox.mail.render import TEMPLATE_DIR
|
||||||
|
|
||||||
|
source = (TEMPLATE_DIR / f"{kind}.txt").read_text(encoding="utf-8")
|
||||||
|
ast = Environment(extensions=["jinja2.ext.i18n"]).parse(source) # noqa: S701 (nur lesen)
|
||||||
|
return tuple(sorted(meta.find_undeclared_variables(ast)))
|
||||||
|
|
||||||
|
|
||||||
|
def placeholders(kind: str) -> dict[str, str]:
|
||||||
|
"""Platzhalter dieser Mailart mit Beschreibung (zum Übersetzen)."""
|
||||||
|
found = dict(COMMON)
|
||||||
|
used = variables(kind)
|
||||||
|
if "form" in used:
|
||||||
|
found["title"] = N_("title of the form")
|
||||||
|
found.update({key: text for key, text in SCALARS.items() if key in used})
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def required(kind: str) -> list[str]:
|
||||||
|
return [key for key in REQUIRED if key in variables(kind)]
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Speichern und Laden (AppSetting "mail_templates": {art: {sprache: {...}}})
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def load(db: Session) -> dict[str, dict[str, Custom]]:
|
||||||
|
from surveybox.models import AppSetting
|
||||||
|
|
||||||
|
row = db.get(AppSetting, SETTING_KEY)
|
||||||
|
raw = row.value if row is not None and isinstance(row.value, dict) else {}
|
||||||
|
result: dict[str, dict[str, Custom]] = {}
|
||||||
|
for kind, by_lang in raw.items():
|
||||||
|
if kind not in KINDS or not isinstance(by_lang, dict):
|
||||||
|
continue
|
||||||
|
for lang, item in by_lang.items():
|
||||||
|
if lang in LANGUAGES and isinstance(item, dict):
|
||||||
|
result.setdefault(kind, {})[lang] = Custom(
|
||||||
|
str(item.get("subject", "")), str(item.get("body", "")))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def for_kind(db: Session, kind: str, language: str) -> Custom | None:
|
||||||
|
if kind not in KINDS:
|
||||||
|
return None
|
||||||
|
return load(db).get(kind, {}).get(language)
|
||||||
|
|
||||||
|
|
||||||
|
def _store(db: Session, data: dict[str, dict[str, Custom]]) -> None:
|
||||||
|
value = {kind: {lang: {"subject": c.subject, "body": c.body} for lang, c in items.items()}
|
||||||
|
for kind, items in data.items() if items}
|
||||||
|
from surveybox.models import AppSetting
|
||||||
|
|
||||||
|
row = db.get(AppSetting, SETTING_KEY)
|
||||||
|
if row is None:
|
||||||
|
db.add(AppSetting(key=SETTING_KEY, value=value))
|
||||||
|
else:
|
||||||
|
row.value = value
|
||||||
|
|
||||||
|
|
||||||
|
def save(db: Session, kind: str, language: str, custom: Custom) -> None:
|
||||||
|
data = load(db)
|
||||||
|
data.setdefault(kind, {})[language] = custom
|
||||||
|
_store(db, data)
|
||||||
|
|
||||||
|
|
||||||
|
def reset(db: Session, kind: str, language: str) -> None:
|
||||||
|
data = load(db)
|
||||||
|
data.get(kind, {}).pop(language, None)
|
||||||
|
_store(db, data)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Prüfen und Anwenden
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
ERRORS = {
|
||||||
|
"subject": N_("Please enter a subject (one line, at most 200 characters)."),
|
||||||
|
"body": N_("Please enter a text (at most 10,000 characters)."),
|
||||||
|
"unknown": N_("Unknown placeholders: %(names)s"),
|
||||||
|
"missing": N_("The text must contain {details} or these placeholders: %(names)s"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def clean(subject: str, body: str) -> Custom:
|
||||||
|
subject = " ".join(subject.replace("\x00", "").split())
|
||||||
|
body = body.replace("\r\n", "\n").replace("\r", "\n").replace("\x00", "").strip()
|
||||||
|
return Custom(subject, body)
|
||||||
|
|
||||||
|
|
||||||
|
def validate(kind: str, custom: Custom) -> list[tuple[str, str]]:
|
||||||
|
"""Fehler als (Schlüssel aus ERRORS, Namen für die Meldung)."""
|
||||||
|
errors: list[tuple[str, str]] = []
|
||||||
|
if not custom.subject or len(custom.subject) > MAX_SUBJECT:
|
||||||
|
errors.append(("subject", ""))
|
||||||
|
if not custom.body or len(custom.body) > MAX_BODY:
|
||||||
|
errors.append(("body", ""))
|
||||||
|
allowed = set(placeholders(kind))
|
||||||
|
used = set(_PLACEHOLDER.findall(custom.subject)) | set(_PLACEHOLDER.findall(custom.body))
|
||||||
|
unknown = sorted(used - allowed)
|
||||||
|
if unknown:
|
||||||
|
errors.append(("unknown", ", ".join(f"{{{name}}}" for name in unknown)))
|
||||||
|
in_body = set(_PLACEHOLDER.findall(custom.body))
|
||||||
|
if "details" not in in_body:
|
||||||
|
missing = [name for name in required(kind) if name not in in_body]
|
||||||
|
if missing:
|
||||||
|
errors.append(("missing", ", ".join(f"{{{name}}}" for name in missing)))
|
||||||
|
return errors
|
||||||
|
|
||||||
|
|
||||||
|
def values(kind: str, context: dict[str, Any], default_text: str) -> dict[str, str]:
|
||||||
|
"""Werte der Platzhalter für eine Mail (im Sprachkontext des Empfängers)."""
|
||||||
|
name = str(context.get("name") or "")
|
||||||
|
greeting = (i18n.gettext("Hello %(name)s,") % {"name": name} if name
|
||||||
|
else i18n.gettext("Hello,"))
|
||||||
|
details = default_text.strip()
|
||||||
|
if details.startswith(greeting):
|
||||||
|
details = details[len(greeting):].strip()
|
||||||
|
found = {"greeting": greeting, "details": details,
|
||||||
|
"app": str(context.get("app_name") or "Surveybox")}
|
||||||
|
form = context.get("form")
|
||||||
|
found["title"] = str(getattr(form, "title", "") or "")
|
||||||
|
for key in SCALARS:
|
||||||
|
value = context.get(key)
|
||||||
|
found[key] = "" if value is None or isinstance(value, bool) else str(value)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def fill(template: str, found: dict[str, str]) -> str:
|
||||||
|
return _PLACEHOLDER.sub(lambda m: found.get(m.group(1), m.group(0)), template)
|
||||||
|
|
||||||
|
|
||||||
|
def apply(kind: str, custom: Custom, context: dict[str, Any], default_text: str
|
||||||
|
) -> tuple[str, str]:
|
||||||
|
"""(Betreff, Text) aus der eigenen Vorlage."""
|
||||||
|
found = values(kind, context, default_text)
|
||||||
|
subject = " ".join(fill(custom.subject, {**found, "details": ""}).split())
|
||||||
|
text = fill(custom.body, found)
|
||||||
|
text = re.sub(r"\n{3,}", "\n\n", text).strip() + "\n"
|
||||||
|
return subject, text
|
||||||
@@ -0,0 +1,635 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Benachrichtigungen per E-Mail.
|
||||||
|
|
||||||
|
Jede Benachrichtigung gehört zu einem Ereignis. Empfänger schalten Ereignisse
|
||||||
|
im Konto ab, bestellen sie für ein einzelnes Formular ab oder nutzen den
|
||||||
|
Abmeldelink in der Mail (auch per Klick im Mailprogramm, RFC 8058).
|
||||||
|
|
||||||
|
Mails enthalten Links statt Antwortinhalten. Bei anonymen Formularen gibt es
|
||||||
|
keine Mails an Teilnehmende: Schon die Mail würde Person und Teilnahme
|
||||||
|
verbinden.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
import logging
|
||||||
|
import uuid
|
||||||
|
from collections.abc import Callable, Iterable, Sequence
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.i18n import N_
|
||||||
|
from surveybox.mail import config as mail_config
|
||||||
|
from surveybox.mail import custom, outbox, render
|
||||||
|
from surveybox.models import (
|
||||||
|
Booking,
|
||||||
|
Comment,
|
||||||
|
Form,
|
||||||
|
FormMember,
|
||||||
|
FormMute,
|
||||||
|
GuestContact,
|
||||||
|
Question,
|
||||||
|
Response,
|
||||||
|
UserAccount,
|
||||||
|
)
|
||||||
|
from surveybox.security.tokens import constant_time_equal, derive_key, keyed_hash
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
APP_NAME = "Surveybox"
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def app_name(settings: Settings) -> str:
|
||||||
|
"""Name der Instanz aus Einstellungen > Gestaltung (Standard: Surveybox)."""
|
||||||
|
from surveybox import appearance
|
||||||
|
|
||||||
|
return appearance.current(settings.data_dir).name
|
||||||
|
|
||||||
|
|
||||||
|
def safely(db: Session, func: Callable[..., Any], *args: Any) -> Any:
|
||||||
|
"""Benachrichtigung in einem Savepoint: Ein Fehler beim Erzeugen einer Mail
|
||||||
|
darf die eigentliche Aktion (z. B. eine Teilnahme) nie verhindern."""
|
||||||
|
try:
|
||||||
|
with db.begin_nested():
|
||||||
|
return func(db, *args)
|
||||||
|
except Exception:
|
||||||
|
log.exception("Benachrichtigung %s fehlgeschlagen", getattr(func, "__name__", func))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Event:
|
||||||
|
label: str
|
||||||
|
audience: str # "participant" oder "manager"
|
||||||
|
default: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
EVENTS: dict[str, Event] = {
|
||||||
|
"participation": Event(N_("Confirmation when I take part in a form"), "participant"),
|
||||||
|
"promoted": Event(N_("I have moved up from a waiting list"), "participant"),
|
||||||
|
"confirmed": Event(N_("A date has been confirmed in a poll I took part in"), "participant"),
|
||||||
|
"comment_published": Event(N_("My comment has been published"), "participant"),
|
||||||
|
"followup": Event(N_("Follow-up emails with documents from forms I took part in"),
|
||||||
|
"participant"),
|
||||||
|
"changed": Event(N_("An entry or date I chose has been removed from a form"),
|
||||||
|
"participant"),
|
||||||
|
"reminder": Event(N_("Reminder before the end date of a form I was invited to"),
|
||||||
|
"participant"),
|
||||||
|
"comment_new": Event(N_("New comments on forms I manage"), "manager"),
|
||||||
|
"slot_full": Event(N_("An entry in a form I own is booked up"), "manager"),
|
||||||
|
"deadline": Event(N_("A form I own has reached its end date"), "manager"),
|
||||||
|
"digest": Event(N_("Daily summary of new and changed answers to forms I manage"),
|
||||||
|
"manager"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Einstellungen der Empfänger
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def wants(user: UserAccount, event: str) -> bool:
|
||||||
|
if not user.is_active or event not in EVENTS:
|
||||||
|
return False
|
||||||
|
prefs = user.notify_prefs or {}
|
||||||
|
value = prefs.get(event)
|
||||||
|
return EVENTS[event].default if value is None else bool(value)
|
||||||
|
|
||||||
|
|
||||||
|
def set_prefs(user: UserAccount, enabled: Iterable[str]) -> None:
|
||||||
|
chosen = set(enabled)
|
||||||
|
user.notify_prefs = {event: event in chosen for event in EVENTS}
|
||||||
|
|
||||||
|
|
||||||
|
def turn_off(user: UserAccount, event: str) -> None:
|
||||||
|
if event in EVENTS:
|
||||||
|
user.notify_prefs = {**(user.notify_prefs or {}), event: False}
|
||||||
|
|
||||||
|
|
||||||
|
def is_muted(db: Session, user_id: int, form_id: int) -> bool:
|
||||||
|
return db.get(FormMute, (user_id, form_id)) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def mute(db: Session, user_id: int, form_id: int) -> None:
|
||||||
|
if not is_muted(db, user_id, form_id):
|
||||||
|
db.add(FormMute(user_id=user_id, form_id=form_id))
|
||||||
|
|
||||||
|
|
||||||
|
def unmute(db: Session, user_id: int, form_id: int) -> None:
|
||||||
|
row = db.get(FormMute, (user_id, form_id))
|
||||||
|
if row is not None:
|
||||||
|
db.delete(row)
|
||||||
|
|
||||||
|
|
||||||
|
def muted_forms(db: Session, user_id: int) -> list[Form]:
|
||||||
|
return list(
|
||||||
|
db.scalars(
|
||||||
|
select(Form)
|
||||||
|
.join(FormMute, FormMute.form_id == Form.id)
|
||||||
|
.where(FormMute.user_id == user_id)
|
||||||
|
.order_by(Form.title)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def language_of(user: UserAccount, settings: Settings) -> str:
|
||||||
|
return user.language or settings.default_language
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Recipient:
|
||||||
|
"""Empfänger einer Mail: Benutzer oder Gast (bestätigte Adresse)."""
|
||||||
|
|
||||||
|
email: str
|
||||||
|
name: str
|
||||||
|
language: str
|
||||||
|
user: UserAccount | None = None
|
||||||
|
guest: GuestContact | None = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ident(self) -> str:
|
||||||
|
if self.user is not None:
|
||||||
|
return f"u:{self.user.public_id}"
|
||||||
|
if self.guest is not None:
|
||||||
|
return f"g:{self.guest.public_id}"
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def for_user(user: UserAccount, settings: Settings) -> Recipient:
|
||||||
|
return Recipient(user.email, user.display_name, language_of(user, settings), user=user)
|
||||||
|
|
||||||
|
|
||||||
|
def for_guest(contact: GuestContact, settings: Settings) -> Recipient:
|
||||||
|
return Recipient(contact.email, "", contact.language or settings.default_language,
|
||||||
|
guest=contact)
|
||||||
|
|
||||||
|
|
||||||
|
def allowed(db: Session, recipient: Recipient, event: str, form: Form | None) -> bool:
|
||||||
|
"""Will der Empfänger diese Benachrichtigung?"""
|
||||||
|
if recipient.user is not None:
|
||||||
|
user = recipient.user
|
||||||
|
return wants(user, event) and not (form is not None and is_muted(db, user.id, form.id))
|
||||||
|
guest = recipient.guest
|
||||||
|
return (
|
||||||
|
guest is not None
|
||||||
|
and guest.confirmed_at is not None # Double-Opt-in
|
||||||
|
and guest.notify
|
||||||
|
and EVENTS.get(event, Event("", "")).audience == "participant"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Abmeldelinks
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _b64(data: bytes) -> str:
|
||||||
|
return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
def _unb64(text: str) -> bytes:
|
||||||
|
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
||||||
|
|
||||||
|
|
||||||
|
def unsubscribe_token(
|
||||||
|
secret_key: str, who: UserAccount | Recipient, event: str, form: Form | None = None
|
||||||
|
) -> str:
|
||||||
|
ident = who.ident if isinstance(who, Recipient) else str(who.public_id)
|
||||||
|
payload = f"{ident}|{event}|{form.public_id if form is not None else ''}"
|
||||||
|
mac = keyed_hash(derive_key(secret_key, "unsubscribe"), payload)[:16]
|
||||||
|
return f"{_b64(payload.encode())}.{_b64(mac)}"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Unsubscribe:
|
||||||
|
public_id: uuid.UUID
|
||||||
|
event: str
|
||||||
|
form_public_id: uuid.UUID | None
|
||||||
|
kind: str = "user" # oder "guest"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def user_public_id(self) -> uuid.UUID:
|
||||||
|
return self.public_id
|
||||||
|
|
||||||
|
|
||||||
|
def parse_unsubscribe(secret_key: str, token: str) -> Unsubscribe | None:
|
||||||
|
if len(token) > 400 or "." not in token:
|
||||||
|
return None
|
||||||
|
raw, _, mac = token.partition(".")
|
||||||
|
try:
|
||||||
|
payload = _unb64(raw).decode("utf-8")
|
||||||
|
given = _unb64(mac)
|
||||||
|
except (binascii.Error, UnicodeDecodeError, ValueError):
|
||||||
|
return None
|
||||||
|
expected = keyed_hash(derive_key(secret_key, "unsubscribe"), payload)[:16]
|
||||||
|
if not constant_time_equal(expected, given):
|
||||||
|
return None
|
||||||
|
parts = payload.split("|")
|
||||||
|
if len(parts) != 3 or parts[1] not in EVENTS:
|
||||||
|
return None
|
||||||
|
kind, ident = "user", parts[0]
|
||||||
|
if ident.startswith(("u:", "g:")):
|
||||||
|
kind = "guest" if ident[0] == "g" else "user"
|
||||||
|
ident = ident[2:]
|
||||||
|
try:
|
||||||
|
public_id = uuid.UUID(ident)
|
||||||
|
form_id = uuid.UUID(parts[2]) if parts[2] else None
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return Unsubscribe(public_id, parts[1], form_id, kind)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Versand
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _reply_to(db: Session, form: Form | None) -> str | None:
|
||||||
|
if form is not None and form.reply_to:
|
||||||
|
return form.reply_to
|
||||||
|
return mail_config.load(db).reply_to or None
|
||||||
|
|
||||||
|
|
||||||
|
def send(
|
||||||
|
db: Session,
|
||||||
|
settings: Settings,
|
||||||
|
to: UserAccount | Recipient,
|
||||||
|
*,
|
||||||
|
kind: str,
|
||||||
|
context: dict[str, Any],
|
||||||
|
event: str | None = None,
|
||||||
|
form: Form | None = None,
|
||||||
|
dedupe_key: str | None = None,
|
||||||
|
) -> bool:
|
||||||
|
"""Mail eintragen. Mit `event`: nur, wenn gewünscht, bestätigt und nicht abbestellt."""
|
||||||
|
recipient = to if isinstance(to, Recipient) else for_user(to, settings)
|
||||||
|
if event is not None and not allowed(db, recipient, event, form):
|
||||||
|
return False
|
||||||
|
secret = settings.secret_key.get_secret_value()
|
||||||
|
origin = settings.public_origin
|
||||||
|
headers: dict[str, str] = {}
|
||||||
|
unsubscribe_url = None
|
||||||
|
if event is not None:
|
||||||
|
token = unsubscribe_token(secret, recipient, event, form)
|
||||||
|
unsubscribe_url = f"{origin}/mail/unsubscribe/{token}"
|
||||||
|
headers["List-Unsubscribe"] = f"<{unsubscribe_url}>"
|
||||||
|
headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click"
|
||||||
|
ctx = {
|
||||||
|
"app_name": app_name(settings),
|
||||||
|
"origin": origin,
|
||||||
|
"name": recipient.name,
|
||||||
|
"form": form,
|
||||||
|
"guest": recipient.guest is not None,
|
||||||
|
"links_url": f"{origin}/links",
|
||||||
|
"unsubscribe_url": unsubscribe_url,
|
||||||
|
"settings_url": f"{origin}/account/notifications",
|
||||||
|
**context,
|
||||||
|
}
|
||||||
|
rendered = render.render(kind, recipient.language, ctx,
|
||||||
|
custom.for_kind(db, kind, recipient.language))
|
||||||
|
return outbox.enqueue(
|
||||||
|
db,
|
||||||
|
secret,
|
||||||
|
kind=kind,
|
||||||
|
recipient=recipient.email,
|
||||||
|
content=outbox.Content(
|
||||||
|
subject=rendered.subject,
|
||||||
|
text=rendered.text,
|
||||||
|
html=rendered.html,
|
||||||
|
reply_to=_reply_to(db, form),
|
||||||
|
headers=headers,
|
||||||
|
),
|
||||||
|
user_id=recipient.user.id if recipient.user is not None else None,
|
||||||
|
form_id=form.id if form is not None else None,
|
||||||
|
dedupe_key=dedupe_key,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def form_link(settings: Settings, form: Form) -> str:
|
||||||
|
return f"{settings.public_origin}/f/{form.share_token}"
|
||||||
|
|
||||||
|
|
||||||
|
def manage_link(settings: Settings, form: Form, page: str = "") -> str:
|
||||||
|
return f"{settings.public_origin}/forms/{form.public_id}{page}"
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Ereignisse für Teilnehmende
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _participant(
|
||||||
|
db: Session, settings: Settings, form: Form, response: Response
|
||||||
|
) -> Recipient | None:
|
||||||
|
"""Benutzer oder Gast hinter einer Antwort (bei anonymen Formularen niemand)."""
|
||||||
|
if form.anonymous:
|
||||||
|
return None
|
||||||
|
if response.user_id is not None:
|
||||||
|
user = db.get(UserAccount, response.user_id)
|
||||||
|
return for_user(user, settings) if user is not None else None
|
||||||
|
if response.guest_contact_id is not None:
|
||||||
|
contact = db.get(GuestContact, response.guest_contact_id)
|
||||||
|
return for_guest(contact, settings) if contact is not None else None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
participant = _participant
|
||||||
|
|
||||||
|
|
||||||
|
def participation_received(
|
||||||
|
db: Session, settings: Settings, form: Form, response: Response
|
||||||
|
) -> bool:
|
||||||
|
"""Bestätigung für Benutzer; Gäste bekommen stattdessen guest_receipt."""
|
||||||
|
if form.anonymous or response.user_id is None:
|
||||||
|
return False
|
||||||
|
user = db.get(UserAccount, response.user_id)
|
||||||
|
if user is None:
|
||||||
|
return False
|
||||||
|
return send(
|
||||||
|
db, settings, user, kind="participation", event="participation", form=form,
|
||||||
|
context={"link": form_link(settings, form)},
|
||||||
|
dedupe_key=f"participation:{response.id}",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def promoted(db: Session, settings: Settings, question: Question, moved: Sequence[Booking]) -> int:
|
||||||
|
"""Nachgerückt von der Warteliste: je Buchung höchstens eine Mail."""
|
||||||
|
count = 0
|
||||||
|
form = db.get(Form, question.form_id)
|
||||||
|
if form is None:
|
||||||
|
return 0
|
||||||
|
from surveybox.forms import types
|
||||||
|
|
||||||
|
for booking in moved:
|
||||||
|
response = db.get(Response, booking.response_id)
|
||||||
|
recipient = _participant(db, settings, form, response) if response is not None else None
|
||||||
|
if recipient is None:
|
||||||
|
continue
|
||||||
|
entry = (
|
||||||
|
question.label
|
||||||
|
if question.config.get("single")
|
||||||
|
else types.option_label(question, booking.option_id) or question.label
|
||||||
|
)
|
||||||
|
stamp = (booking.promoted_at or datetime.now(UTC)).isoformat()
|
||||||
|
if send(
|
||||||
|
db, settings, recipient, kind="promoted", event="promoted", form=form,
|
||||||
|
context={"entry": entry, "link": form_link(settings, form)},
|
||||||
|
dedupe_key=f"promoted:{booking.id}:{stamp}",
|
||||||
|
):
|
||||||
|
count += 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
def dates_confirmed(
|
||||||
|
db: Session, settings: Settings, form: Form, question: Question, new_ids: Sequence[str]
|
||||||
|
) -> int:
|
||||||
|
"""Neu bestätigte Termine einer Abstimmung an alle Teilnehmenden mit Konto."""
|
||||||
|
if form.anonymous or not new_ids:
|
||||||
|
return 0
|
||||||
|
from surveybox.forms import types
|
||||||
|
|
||||||
|
by_id = {o["id"]: o for o in types.options_of(question)}
|
||||||
|
options = [by_id[i] for i in new_ids if i in by_id]
|
||||||
|
if not options:
|
||||||
|
return 0
|
||||||
|
responses = db.scalars(
|
||||||
|
select(Response).where(
|
||||||
|
Response.form_id == form.id,
|
||||||
|
(Response.user_id.is_not(None)) | (Response.guest_contact_id.is_not(None)),
|
||||||
|
)
|
||||||
|
).all()
|
||||||
|
recipients: dict[str, Recipient] = {}
|
||||||
|
for response in responses:
|
||||||
|
found = _participant(db, settings, form, response)
|
||||||
|
if found is not None:
|
||||||
|
recipients.setdefault(found.ident, found)
|
||||||
|
calendar = (
|
||||||
|
f"{settings.public_origin}/f/{form.share_token}/calendar.ics"
|
||||||
|
if form.calendar_mode != "off"
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
count = 0
|
||||||
|
key = ",".join(sorted(o["id"] for o in options))
|
||||||
|
for ident in sorted(recipients):
|
||||||
|
if send(
|
||||||
|
db, settings, recipients[ident], kind="confirmed", event="confirmed", form=form,
|
||||||
|
context={"options": options, "link": form_link(settings, form),
|
||||||
|
"calendar": calendar},
|
||||||
|
dedupe_key=f"confirmed:{question.id}:{key}:{ident}",
|
||||||
|
):
|
||||||
|
count += 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
def booking_events(db: Session, settings: Settings, form: Form, events: Any) -> None:
|
||||||
|
"""Nachgerückte Personen und ausgebuchte Einträge aus forms.booking.Events."""
|
||||||
|
by_question: dict[int, tuple[Question, list[Booking]]] = {}
|
||||||
|
for question, booking in events.promoted:
|
||||||
|
by_question.setdefault(question.id, (question, []))[1].append(booking)
|
||||||
|
for question, moved in by_question.values():
|
||||||
|
promoted(db, settings, question, moved)
|
||||||
|
for question, option_id in events.filled:
|
||||||
|
slot_full(db, settings, form, question, option_id)
|
||||||
|
|
||||||
|
|
||||||
|
def comment_published(db: Session, settings: Settings, form: Form, comment: Comment) -> bool:
|
||||||
|
if comment.user_id is None:
|
||||||
|
return False
|
||||||
|
user = db.get(UserAccount, comment.user_id)
|
||||||
|
if user is None:
|
||||||
|
return False
|
||||||
|
return send(
|
||||||
|
db, settings, user, kind="comment_published", event="comment_published", form=form,
|
||||||
|
context={"link": form_link(settings, form)},
|
||||||
|
dedupe_key=f"comment_published:{comment.id}",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Ereignisse für Verwalter
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def managers(db: Session, form: Form) -> list[UserAccount]:
|
||||||
|
"""Eigentümer und Mitbearbeitende (direkt oder über Gruppen samt Untergruppen)."""
|
||||||
|
from surveybox.accounts import scope
|
||||||
|
|
||||||
|
ids: set[int] = set()
|
||||||
|
if form.owner_id is not None:
|
||||||
|
ids.add(form.owner_id)
|
||||||
|
rows = db.execute(
|
||||||
|
select(FormMember.user_id, FormMember.group_id).where(
|
||||||
|
FormMember.form_id == form.id, FormMember.role == "editor"
|
||||||
|
)
|
||||||
|
).all()
|
||||||
|
ids.update(uid for uid, _ in rows if uid is not None)
|
||||||
|
groups = [gid for _, gid in rows if gid is not None]
|
||||||
|
if groups:
|
||||||
|
tree = scope.load_tree(db)
|
||||||
|
ids.update(u.id for u in scope.users_in_groups(db, scope.descendants(tree, groups)))
|
||||||
|
if not ids:
|
||||||
|
return []
|
||||||
|
return list(
|
||||||
|
db.scalars(
|
||||||
|
select(UserAccount)
|
||||||
|
.where(UserAccount.id.in_(ids), UserAccount.is_active.is_(True))
|
||||||
|
.order_by(UserAccount.id)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def comment_created(
|
||||||
|
db: Session, settings: Settings, form: Form, comment: Comment, author_is_manager: bool
|
||||||
|
) -> int:
|
||||||
|
if not form.comments_notify or author_is_manager:
|
||||||
|
return 0
|
||||||
|
count = 0
|
||||||
|
for user in managers(db, form):
|
||||||
|
if user.id == comment.user_id:
|
||||||
|
continue
|
||||||
|
if send(
|
||||||
|
db, settings, user, kind="comment_new", event="comment_new", form=form,
|
||||||
|
context={"pending": comment.status == "pending",
|
||||||
|
"link": manage_link(settings, form, "/comments")},
|
||||||
|
dedupe_key=f"comment_new:{comment.id}:{user.id}",
|
||||||
|
):
|
||||||
|
count += 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
def _owner(db: Session, form: Form) -> UserAccount | None:
|
||||||
|
return db.get(UserAccount, form.owner_id) if form.owner_id is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def slot_full(
|
||||||
|
db: Session, settings: Settings, form: Form, question: Question, option_id: str
|
||||||
|
) -> bool:
|
||||||
|
owner = _owner(db, form)
|
||||||
|
if owner is None:
|
||||||
|
return False
|
||||||
|
from surveybox.forms import types
|
||||||
|
|
||||||
|
entry = (
|
||||||
|
question.label
|
||||||
|
if question.config.get("single")
|
||||||
|
else types.option_label(question, option_id) or question.label
|
||||||
|
)
|
||||||
|
day = datetime.now(UTC).date().isoformat()
|
||||||
|
return send(
|
||||||
|
db, settings, owner, kind="slot_full", event="slot_full", form=form,
|
||||||
|
context={"entry": entry, "link": manage_link(settings, form, "/responses")},
|
||||||
|
dedupe_key=f"slot_full:{question.id}:{option_id}:{day}",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def deadline_reached(db: Session, settings: Settings, form: Form, responses: int) -> bool:
|
||||||
|
owner = _owner(db, form)
|
||||||
|
if owner is None or form.closes_at is None:
|
||||||
|
return False
|
||||||
|
return send(
|
||||||
|
db, settings, owner, kind="deadline", event="deadline", form=form,
|
||||||
|
context={"responses": responses, "link": manage_link(settings, form, "/responses")},
|
||||||
|
dedupe_key=f"deadline:{form.id}:{form.closes_at.isoformat()}",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Mails ohne Ereignis (immer, nicht abbestellbar)
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def retention_notice(
|
||||||
|
db: Session, settings: Settings, form: Form, mode: str, when: datetime, responses: int
|
||||||
|
) -> bool:
|
||||||
|
"""Eigentümer: Die Löschfrist läuft bald ab (nicht abbestellbar, betrifft Pflichten)."""
|
||||||
|
from babel.dates import format_date
|
||||||
|
|
||||||
|
owner = _owner(db, form)
|
||||||
|
if owner is None:
|
||||||
|
return False
|
||||||
|
language = language_of(owner, settings)
|
||||||
|
return send(
|
||||||
|
db, settings, owner, kind="retention_notice", form=form,
|
||||||
|
context={
|
||||||
|
"mode": mode,
|
||||||
|
"date": format_date(when.astimezone(settings.tz).date(), format="long",
|
||||||
|
locale=language),
|
||||||
|
"responses": responses,
|
||||||
|
"link": manage_link(settings, form, "/responses"),
|
||||||
|
"settings_link": manage_link(settings, form, "/settings"),
|
||||||
|
},
|
||||||
|
dedupe_key=f"retention:{form.id}:{when.date().isoformat()}",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def guest_receipt(
|
||||||
|
db: Session,
|
||||||
|
settings: Settings,
|
||||||
|
form: Form,
|
||||||
|
contact: GuestContact,
|
||||||
|
link: str,
|
||||||
|
confirm: str | None,
|
||||||
|
edited: bool = False,
|
||||||
|
) -> bool:
|
||||||
|
"""Gast: Eingangsbestätigung mit persönlichem Link (und ggf. Bestätigungslink).
|
||||||
|
|
||||||
|
Sind Folge-Mails eingerichtet, sagt die Mail ausdrücklich, dass sie nur nach der
|
||||||
|
Bestätigung der Adresse ankommen.
|
||||||
|
"""
|
||||||
|
from surveybox.forms import followups # followups importiert dieses Modul
|
||||||
|
|
||||||
|
return send(
|
||||||
|
db, settings, for_guest(contact, settings), kind="guest_receipt", form=form,
|
||||||
|
context={"link": link, "confirm": confirm, "edited": edited,
|
||||||
|
"can_edit": form.allow_edit == "until_close",
|
||||||
|
"followups_planned": bool(confirm) and followups.planned(db, form)},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def guest_export(db: Session, settings: Settings, contact: GuestContact, link: str) -> bool:
|
||||||
|
"""Gast: Link zum Herunterladen aller Daten an dieser Adresse."""
|
||||||
|
return send(db, settings, for_guest(contact, settings), kind="guest_export",
|
||||||
|
context={"link": link})
|
||||||
|
|
||||||
|
|
||||||
|
def guest_erase(db: Session, settings: Settings, contact: GuestContact, link: str) -> bool:
|
||||||
|
"""Gast: Link zum Löschen aller Daten an dieser Adresse."""
|
||||||
|
return send(db, settings, for_guest(contact, settings), kind="guest_erase",
|
||||||
|
context={"link": link})
|
||||||
|
|
||||||
|
|
||||||
|
def guest_links(
|
||||||
|
db: Session, settings: Settings, contact: GuestContact, links: list[tuple[Form, str]]
|
||||||
|
) -> bool:
|
||||||
|
return send(
|
||||||
|
db, settings, for_guest(contact, settings), kind="guest_links",
|
||||||
|
context={"links": links},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def registration(
|
||||||
|
db: Session, settings: Settings, email: str, name: str, language: str, link: str | None
|
||||||
|
) -> bool:
|
||||||
|
"""Link zum Anlegen eines Kontos; ohne Link: Hinweis, dass es schon ein Konto gibt."""
|
||||||
|
recipient = Recipient(email, name, language)
|
||||||
|
origin = settings.public_origin
|
||||||
|
return send(
|
||||||
|
db, settings, recipient, kind="register" if link else "register_exists",
|
||||||
|
context={"link": link, "login_url": f"{origin}/login", "forgot_url": f"{origin}/forgot"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def account_link(
|
||||||
|
db: Session, settings: Settings, user: UserAccount, link: str, *, invite: bool
|
||||||
|
) -> bool:
|
||||||
|
"""Einladung oder Link zum Zurücksetzen des Passworts."""
|
||||||
|
return send(
|
||||||
|
db, settings, user, kind="invite" if invite else "password_reset",
|
||||||
|
context={"link": link},
|
||||||
|
)
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Warteschlange: Mails eintragen, im Worker versenden, Protokoll pflegen.
|
||||||
|
|
||||||
|
Eintragen geschieht in derselben Transaktion wie die auslösende Änderung; wird
|
||||||
|
diese zurückgerollt, entsteht auch keine Mail. Der Worker holt fällige Mails
|
||||||
|
mit `FOR UPDATE SKIP LOCKED`, sendet sie über eine Verbindung zum Relay und
|
||||||
|
plant bei vorübergehenden Fehlern neue Versuche ein.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import smtplib
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import Engine, delete, func, select, update
|
||||||
|
from sqlalchemy.dialects.postgresql import insert
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.mail import config as mail_config
|
||||||
|
from surveybox.mail import smtp
|
||||||
|
from surveybox.models import MailMessage, MailStatus
|
||||||
|
from surveybox.security import secretbox
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
CONTENT_PURPOSE = "mail-content"
|
||||||
|
BATCH = 20
|
||||||
|
# Wartezeit vor dem n-ten Wiederholversuch; danach gilt die Mail als gescheitert
|
||||||
|
RETRY_DELAYS = (
|
||||||
|
timedelta(minutes=1),
|
||||||
|
timedelta(minutes=5),
|
||||||
|
timedelta(minutes=15),
|
||||||
|
timedelta(hours=1),
|
||||||
|
timedelta(hours=4),
|
||||||
|
timedelta(hours=12),
|
||||||
|
)
|
||||||
|
LOG_RETENTION = timedelta(days=90)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Content:
|
||||||
|
subject: str
|
||||||
|
text: str
|
||||||
|
html: str | None
|
||||||
|
reply_to: str | None
|
||||||
|
headers: dict[str, str]
|
||||||
|
|
||||||
|
|
||||||
|
def _seal(secret_key: str, content: Content) -> bytes:
|
||||||
|
raw = json.dumps(content.__dict__, ensure_ascii=False).encode("utf-8")
|
||||||
|
return secretbox.encrypt(secret_key, CONTENT_PURPOSE, raw)
|
||||||
|
|
||||||
|
|
||||||
|
def _open(secret_key: str, blob: bytes) -> Content:
|
||||||
|
data = json.loads(secretbox.decrypt(secret_key, CONTENT_PURPOSE, blob))
|
||||||
|
return Content(
|
||||||
|
subject=str(data["subject"]),
|
||||||
|
text=str(data["text"]),
|
||||||
|
html=data.get("html"),
|
||||||
|
reply_to=data.get("reply_to"),
|
||||||
|
headers={str(k): str(v) for k, v in (data.get("headers") or {}).items()},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def enqueue(
|
||||||
|
db: Session,
|
||||||
|
secret_key: str,
|
||||||
|
*,
|
||||||
|
kind: str,
|
||||||
|
recipient: str,
|
||||||
|
content: Content,
|
||||||
|
user_id: int | None = None,
|
||||||
|
form_id: int | None = None,
|
||||||
|
dedupe_key: str | None = None,
|
||||||
|
) -> bool:
|
||||||
|
"""Trägt eine Mail ein. False, wenn die Adresse ungültig ist oder es sie schon gab."""
|
||||||
|
if not mail_config.address_valid(recipient):
|
||||||
|
return False
|
||||||
|
stmt = insert(MailMessage).values(
|
||||||
|
kind=kind,
|
||||||
|
recipient=recipient,
|
||||||
|
user_id=user_id,
|
||||||
|
form_id=form_id,
|
||||||
|
content_enc=_seal(secret_key, content),
|
||||||
|
dedupe_key=dedupe_key,
|
||||||
|
)
|
||||||
|
if dedupe_key is not None:
|
||||||
|
stmt = stmt.on_conflict_do_nothing(index_elements=[MailMessage.dedupe_key])
|
||||||
|
result = db.execute(stmt)
|
||||||
|
return bool(result.rowcount) # type: ignore[attr-defined]
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Versand (Worker)
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _retry(row: MailMessage, error: str, now: datetime) -> None:
|
||||||
|
row.attempts += 1
|
||||||
|
row.last_error = error[:500]
|
||||||
|
if row.attempts > len(RETRY_DELAYS):
|
||||||
|
_fail(row, error)
|
||||||
|
return
|
||||||
|
row.next_attempt_at = now + RETRY_DELAYS[row.attempts - 1]
|
||||||
|
|
||||||
|
|
||||||
|
def _fail(row: MailMessage, error: str) -> None:
|
||||||
|
row.status = MailStatus.FAILED
|
||||||
|
row.last_error = error[:500]
|
||||||
|
row.content_enc = None # Inhalt nicht länger aufbewahren als nötig
|
||||||
|
|
||||||
|
|
||||||
|
def process_due(engine: Engine, secret_key: str, domain: str, now: datetime) -> int:
|
||||||
|
"""Sendet fällige Mails. Gibt die Zahl der versendeten zurück."""
|
||||||
|
with Session(engine) as db:
|
||||||
|
cfg = mail_config.load(db)
|
||||||
|
if not cfg.configured:
|
||||||
|
return 0 # Mails bleiben in der Warteschlange, bis ein Relay eingerichtet ist
|
||||||
|
sent = 0
|
||||||
|
with Session(engine) as db, db.begin():
|
||||||
|
rows = db.scalars(
|
||||||
|
select(MailMessage)
|
||||||
|
.where(MailMessage.status == MailStatus.QUEUED, MailMessage.next_attempt_at <= now)
|
||||||
|
.order_by(MailMessage.id)
|
||||||
|
.limit(BATCH)
|
||||||
|
.with_for_update(skip_locked=True)
|
||||||
|
).all()
|
||||||
|
if not rows:
|
||||||
|
return 0
|
||||||
|
try:
|
||||||
|
password = cfg.password(secret_key)
|
||||||
|
except ValueError: # auch secretbox.DecryptionError
|
||||||
|
for row in rows:
|
||||||
|
_retry(row, "SMTP password cannot be decrypted (secret key changed?)", now)
|
||||||
|
return 0
|
||||||
|
handled: set[int] = set()
|
||||||
|
try:
|
||||||
|
with smtp.Connection(cfg, password) as conn:
|
||||||
|
for row in rows:
|
||||||
|
if _send_one(conn, cfg, row, secret_key, domain, now):
|
||||||
|
sent += 1
|
||||||
|
handled.add(row.id)
|
||||||
|
except (smtplib.SMTPException, OSError) as exc:
|
||||||
|
# Verbindung oder Anmeldung gescheitert: alle noch offenen später erneut
|
||||||
|
error = smtp.describe(exc)
|
||||||
|
log.warning("Mailversand: %s", error)
|
||||||
|
for row in rows:
|
||||||
|
if row.id not in handled:
|
||||||
|
_retry(row, error, now)
|
||||||
|
return sent
|
||||||
|
|
||||||
|
|
||||||
|
def _send_one(
|
||||||
|
conn: smtp.Connection,
|
||||||
|
cfg: mail_config.MailConfig,
|
||||||
|
row: MailMessage,
|
||||||
|
secret_key: str,
|
||||||
|
domain: str,
|
||||||
|
now: datetime,
|
||||||
|
) -> bool:
|
||||||
|
if row.content_enc is None:
|
||||||
|
_fail(row, "content missing")
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
content = _open(secret_key, row.content_enc)
|
||||||
|
except (secretbox.DecryptionError, ValueError, KeyError):
|
||||||
|
_fail(row, "content cannot be decrypted (secret key changed?)")
|
||||||
|
return False
|
||||||
|
out = smtp.Outgoing(
|
||||||
|
recipient=row.recipient,
|
||||||
|
subject=content.subject,
|
||||||
|
text=content.text,
|
||||||
|
html=content.html,
|
||||||
|
reply_to=content.reply_to,
|
||||||
|
headers=content.headers,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
conn.send(smtp.build(cfg, out, domain))
|
||||||
|
except smtp.PermanentError as exc:
|
||||||
|
_fail(row, str(exc))
|
||||||
|
return False
|
||||||
|
except smtplib.SMTPServerDisconnected:
|
||||||
|
raise # Verbindung weg: der Aufrufer plant den Rest neu ein
|
||||||
|
except (smtplib.SMTPException, ValueError) as exc:
|
||||||
|
_retry(row, smtp.describe(exc), now)
|
||||||
|
return False
|
||||||
|
row.status = MailStatus.SENT
|
||||||
|
row.sent_at = now
|
||||||
|
row.attempts += 1
|
||||||
|
row.last_error = None
|
||||||
|
row.content_enc = None
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Verwaltung
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def counts(db: Session) -> dict[str, int]:
|
||||||
|
rows = db.execute(
|
||||||
|
select(MailMessage.status, func.count()).group_by(MailMessage.status)
|
||||||
|
).all()
|
||||||
|
result = {str(status): 0 for status in MailStatus}
|
||||||
|
result.update({str(status): int(n) for status, n in rows})
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def recent(db: Session, limit: int = 50) -> list[MailMessage]:
|
||||||
|
return list(db.scalars(select(MailMessage).order_by(MailMessage.id.desc()).limit(limit)))
|
||||||
|
|
||||||
|
|
||||||
|
def send_queued_now(db: Session) -> int:
|
||||||
|
"""Wartende Mails sofort fällig machen (z. B. nach dem Einrichten des Relays).
|
||||||
|
|
||||||
|
Gescheiterte Mails lassen sich nicht erneut senden: Ihr Inhalt wird beim
|
||||||
|
Scheitern gelöscht.
|
||||||
|
"""
|
||||||
|
result = db.execute(
|
||||||
|
update(MailMessage)
|
||||||
|
.where(MailMessage.status == MailStatus.QUEUED)
|
||||||
|
.values(next_attempt_at=func.now())
|
||||||
|
)
|
||||||
|
return int(result.rowcount or 0) # type: ignore[attr-defined]
|
||||||
|
|
||||||
|
|
||||||
|
def purge_old(db: Session, now: datetime) -> int:
|
||||||
|
"""Protokoll versendeter und gescheiterter Mails nach 90 Tagen löschen."""
|
||||||
|
result = db.execute(
|
||||||
|
delete(MailMessage).where(
|
||||||
|
MailMessage.status != MailStatus.QUEUED,
|
||||||
|
MailMessage.created_at < now - LOG_RETENTION,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return int(result.rowcount or 0) # type: ignore[attr-defined]
|
||||||
|
|
||||||
|
|
||||||
|
def content_of(secret_key: str, row: MailMessage) -> Mapping[str, Any] | None:
|
||||||
|
"""Für Tests und Fehlersuche: entschlüsselter Inhalt einer wartenden Mail."""
|
||||||
|
if row.content_enc is None:
|
||||||
|
return None
|
||||||
|
return _open(secret_key, row.content_enc).__dict__
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Mail-Vorlagen: Text aus Jinja, HTML daraus abgeleitet.
|
||||||
|
|
||||||
|
Jede Vorlage unter web/templates/mail/<name>.txt setzt `subject` und liefert
|
||||||
|
den Text. Die HTML-Fassung entsteht aus dem Text (Absätze, Links), damit beide
|
||||||
|
immer dasselbe sagen und Vorlagen später einfach anpassbar bleiben.
|
||||||
|
Mails enthalten Links, keine Antwortinhalte.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from functools import cache
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from jinja2 import ChainableUndefined, Environment, FileSystemLoader, StrictUndefined
|
||||||
|
from markupsafe import Markup, escape
|
||||||
|
|
||||||
|
from surveybox import i18n
|
||||||
|
|
||||||
|
TEMPLATE_DIR = Path(__file__).resolve().parent.parent / "web" / "templates" / "mail"
|
||||||
|
_URL = re.compile(r"https://[^\s<>\"']+")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Rendered:
|
||||||
|
subject: str
|
||||||
|
text: str
|
||||||
|
html: str
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def _environment(strict: bool = True) -> Environment:
|
||||||
|
"""strict=False nur für Vorschauen mit Beispieldaten: Fehlendes bleibt leer."""
|
||||||
|
env = Environment(
|
||||||
|
loader=FileSystemLoader(TEMPLATE_DIR),
|
||||||
|
autoescape=False, # noqa: S701 - reiner Text; HTML entsteht escaped in to_html
|
||||||
|
extensions=["jinja2.ext.i18n"],
|
||||||
|
trim_blocks=True,
|
||||||
|
lstrip_blocks=True,
|
||||||
|
keep_trailing_newline=False,
|
||||||
|
undefined=StrictUndefined if strict else ChainableUndefined,
|
||||||
|
)
|
||||||
|
env.install_gettext_callables( # type: ignore[attr-defined]
|
||||||
|
gettext=i18n.gettext, ngettext=i18n.ngettext, newstyle=True
|
||||||
|
)
|
||||||
|
from surveybox.forms.types import option_text
|
||||||
|
|
||||||
|
env.globals["option_text"] = option_text
|
||||||
|
return env
|
||||||
|
|
||||||
|
|
||||||
|
def _linkify(line: str) -> Markup:
|
||||||
|
parts: list[Markup] = []
|
||||||
|
last = 0
|
||||||
|
for match in _URL.finditer(line):
|
||||||
|
parts.append(escape(line[last : match.start()]))
|
||||||
|
url = match.group(0).rstrip(".,)")
|
||||||
|
parts.append(Markup('<a href="{0}">{0}</a>').format(url))
|
||||||
|
parts.append(escape(match.group(0)[len(url) :]))
|
||||||
|
last = match.end()
|
||||||
|
parts.append(escape(line[last:]))
|
||||||
|
return Markup("").join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def to_html(text: str, footer: str = "", language: str = "de") -> str:
|
||||||
|
paragraphs = [p for p in re.split(r"\n\s*\n", text.strip()) if p.strip()]
|
||||||
|
def lines(block: str) -> Markup:
|
||||||
|
return Markup("<br>\n").join(_linkify(line) for line in block.splitlines())
|
||||||
|
|
||||||
|
body = Markup("").join(Markup("<p>{}</p>\n").format(lines(p)) for p in paragraphs)
|
||||||
|
style = "color:#666;font-size:12px;border-top:1px solid #ddd;padding-top:8px"
|
||||||
|
foot = Markup('<p style="{}">{}</p>').format(style, lines(footer)) if footer else Markup("")
|
||||||
|
return str(
|
||||||
|
Markup(
|
||||||
|
'<!DOCTYPE html>\n<html lang="{lang}"><head><meta charset="utf-8"></head>'
|
||||||
|
'<body style="font-family:Arial,Helvetica,sans-serif;font-size:15px;line-height:1.5;'
|
||||||
|
'color:#222;max-width:640px;margin:0 auto;padding:16px">\n{body}{foot}</body></html>\n'
|
||||||
|
).format(lang=language, body=body, foot=foot)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def render(name: str, language: str, context: dict[str, Any],
|
||||||
|
custom: Any = None, strict: bool = True) -> Rendered:
|
||||||
|
"""Rendert mail/<name>.txt in der Sprache des Empfängers.
|
||||||
|
|
||||||
|
custom: eigene Vorlage der Instanz (mail.custom.Custom) für diese Mailart und Sprache.
|
||||||
|
"""
|
||||||
|
token = i18n.set_language(language)
|
||||||
|
try:
|
||||||
|
template = _environment(strict).get_template(f"{name}.txt")
|
||||||
|
module = template.make_module(context)
|
||||||
|
text = str(module).strip() + "\n"
|
||||||
|
subject = " ".join(str(getattr(module, "subject", "")).split())
|
||||||
|
if custom is not None:
|
||||||
|
from surveybox.mail import custom as custom_templates
|
||||||
|
|
||||||
|
subject, text = custom_templates.apply(name, custom, context, text)
|
||||||
|
footer_lines = [i18n.gettext("This message was sent automatically by %(app)s.") % {
|
||||||
|
"app": context.get("app_name", "Surveybox")}]
|
||||||
|
if context.get("unsubscribe_url"):
|
||||||
|
footer_lines.append(
|
||||||
|
i18n.gettext("Unsubscribe from these notifications: %(url)s")
|
||||||
|
% {"url": context["unsubscribe_url"]}
|
||||||
|
)
|
||||||
|
footer = "\n".join(footer_lines)
|
||||||
|
return Rendered(
|
||||||
|
subject=subject,
|
||||||
|
text=f"{text}\n-- \n{footer}\n",
|
||||||
|
html=to_html(text, footer, i18n.get_language()),
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
i18n.reset_language(token)
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Mails bauen und über das SMTP-Relay senden.
|
||||||
|
|
||||||
|
Verschlüsselung ist Pflicht (STARTTLS oder TLS), das Zertifikat wird immer
|
||||||
|
geprüft. Absender ist immer die Adresse des Relays, damit SPF, DKIM und DMARC
|
||||||
|
passen; Antworten lenkt die Kopfzeile Reply-To um.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import smtplib
|
||||||
|
import ssl
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from email.message import EmailMessage
|
||||||
|
from email.utils import format_datetime, formataddr, make_msgid
|
||||||
|
from types import TracebackType
|
||||||
|
|
||||||
|
from surveybox.mail.config import MailConfig
|
||||||
|
|
||||||
|
TIMEOUT_SECONDS = 30
|
||||||
|
|
||||||
|
|
||||||
|
class PermanentError(Exception):
|
||||||
|
"""Der Server lehnt die Mail endgültig ab (5xx); ein neuer Versuch hilft nicht."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Outgoing:
|
||||||
|
recipient: str
|
||||||
|
subject: str
|
||||||
|
text: str
|
||||||
|
html: str | None = None
|
||||||
|
reply_to: str | None = None
|
||||||
|
headers: Mapping[str, str] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
def _one_line(value: str) -> str:
|
||||||
|
return " ".join(value.split())
|
||||||
|
|
||||||
|
|
||||||
|
def build(cfg: MailConfig, out: Outgoing, domain: str) -> EmailMessage:
|
||||||
|
msg = EmailMessage()
|
||||||
|
msg["From"] = formataddr((_one_line(cfg.from_name), cfg.from_address))
|
||||||
|
msg["To"] = out.recipient
|
||||||
|
msg["Subject"] = _one_line(out.subject)[:250]
|
||||||
|
msg["Date"] = format_datetime(datetime.now(UTC))
|
||||||
|
msg["Message-ID"] = make_msgid(domain=domain or None)
|
||||||
|
if out.reply_to:
|
||||||
|
msg["Reply-To"] = out.reply_to
|
||||||
|
# Abwesenheitsnotizen und Schleifen vermeiden
|
||||||
|
msg["Auto-Submitted"] = "auto-generated"
|
||||||
|
msg["X-Auto-Response-Suppress"] = "All"
|
||||||
|
for name, value in out.headers.items():
|
||||||
|
msg[name] = _one_line(value)
|
||||||
|
msg.set_content(out.text)
|
||||||
|
if out.html:
|
||||||
|
msg.add_alternative(out.html, subtype="html")
|
||||||
|
return msg
|
||||||
|
|
||||||
|
|
||||||
|
class Connection:
|
||||||
|
"""Eine Verbindung zum Relay für mehrere Mails."""
|
||||||
|
|
||||||
|
def __init__(self, cfg: MailConfig, password: str) -> None:
|
||||||
|
self.cfg = cfg
|
||||||
|
self.password = password
|
||||||
|
self.smtp: smtplib.SMTP | None = None
|
||||||
|
|
||||||
|
def __enter__(self) -> Connection:
|
||||||
|
context = ssl.create_default_context()
|
||||||
|
cfg = self.cfg
|
||||||
|
if cfg.security == "tls":
|
||||||
|
smtp: smtplib.SMTP = smtplib.SMTP_SSL(
|
||||||
|
cfg.host, cfg.port, timeout=TIMEOUT_SECONDS, context=context
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
smtp = smtplib.SMTP(cfg.host, cfg.port, timeout=TIMEOUT_SECONDS)
|
||||||
|
smtp.ehlo()
|
||||||
|
if not smtp.has_extn("starttls"):
|
||||||
|
smtp.close()
|
||||||
|
raise smtplib.SMTPNotSupportedError("STARTTLS is not offered by the server")
|
||||||
|
smtp.starttls(context=context)
|
||||||
|
smtp.ehlo()
|
||||||
|
if cfg.username:
|
||||||
|
smtp.login(cfg.username, self.password)
|
||||||
|
self.smtp = smtp
|
||||||
|
return self
|
||||||
|
|
||||||
|
def send(self, msg: EmailMessage) -> None:
|
||||||
|
if self.smtp is None:
|
||||||
|
raise smtplib.SMTPServerDisconnected("not connected")
|
||||||
|
try:
|
||||||
|
refused = self.smtp.send_message(msg)
|
||||||
|
except smtplib.SMTPRecipientsRefused as exc:
|
||||||
|
codes = [code for code, _ in exc.recipients.values()]
|
||||||
|
if codes and all(code >= 500 for code in codes):
|
||||||
|
raise PermanentError(_describe(exc)) from exc
|
||||||
|
raise
|
||||||
|
except smtplib.SMTPResponseException as exc:
|
||||||
|
if exc.smtp_code >= 500:
|
||||||
|
raise PermanentError(_describe(exc)) from exc
|
||||||
|
raise
|
||||||
|
if refused:
|
||||||
|
raise PermanentError(f"recipient refused: {refused}")
|
||||||
|
|
||||||
|
def __exit__(
|
||||||
|
self,
|
||||||
|
exc_type: type[BaseException] | None,
|
||||||
|
exc: BaseException | None,
|
||||||
|
tb: TracebackType | None,
|
||||||
|
) -> None:
|
||||||
|
if self.smtp is not None:
|
||||||
|
try:
|
||||||
|
self.smtp.quit()
|
||||||
|
except (smtplib.SMTPException, OSError):
|
||||||
|
self.smtp.close()
|
||||||
|
self.smtp = None
|
||||||
|
|
||||||
|
|
||||||
|
def _describe(exc: BaseException) -> str:
|
||||||
|
"""Kurze Fehlerbeschreibung für Protokoll und Admin-Seite (ohne Passwort)."""
|
||||||
|
if isinstance(exc, smtplib.SMTPResponseException):
|
||||||
|
message = exc.smtp_error
|
||||||
|
text = message.decode("utf-8", "replace") if isinstance(message, bytes) else str(message)
|
||||||
|
return f"{exc.smtp_code} {_one_line(text)}"[:500]
|
||||||
|
if isinstance(exc, smtplib.SMTPRecipientsRefused):
|
||||||
|
parts = [f"{code} {_one_line(msg.decode('utf-8', 'replace'))}"
|
||||||
|
for code, msg in exc.recipients.values()]
|
||||||
|
return "; ".join(parts)[:500]
|
||||||
|
return f"{type(exc).__name__}: {_one_line(str(exc))}"[:500]
|
||||||
|
|
||||||
|
|
||||||
|
def describe(exc: BaseException) -> str:
|
||||||
|
return _describe(exc)
|
||||||
|
|
||||||
|
|
||||||
|
def send_now(cfg: MailConfig, password: str, out: Outgoing, domain: str) -> str | None:
|
||||||
|
"""Sofort senden (Testmail). Gibt None oder eine Fehlerbeschreibung zurück."""
|
||||||
|
try:
|
||||||
|
with Connection(cfg, password) as conn:
|
||||||
|
conn.send(build(cfg, out, domain))
|
||||||
|
except (smtplib.SMTPException, OSError, PermanentError, ValueError) as exc:
|
||||||
|
return _describe(exc)
|
||||||
|
return None
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Bilder, Videos und hochgeladene Dateien."""
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Einstellungen für Medien, die der Administrator in der Oberfläche ändert."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import asdict, dataclass, field
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.media.embeds import SOURCE_KINDS, EmbedPolicy, Source, clean_host, clean_source_host
|
||||||
|
from surveybox.models import AppSetting
|
||||||
|
|
||||||
|
KEY = "media"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class MediaConfig:
|
||||||
|
image_max_mb: int = 20
|
||||||
|
video_max_mb: int = 200
|
||||||
|
upload_max_mb: int = 20
|
||||||
|
embed_youtube: bool = False
|
||||||
|
embed_vimeo: bool = False
|
||||||
|
peertube_hosts: list[str] = field(default_factory=list)
|
||||||
|
# Eigene Quellen: {"host": "nas.example.org:5001", "kind": "file", "ask": False}
|
||||||
|
custom_sources: list[dict[str, Any]] = field(default_factory=list)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def policy(self) -> EmbedPolicy:
|
||||||
|
return EmbedPolicy(
|
||||||
|
self.embed_youtube,
|
||||||
|
self.embed_vimeo,
|
||||||
|
tuple(self.peertube_hosts),
|
||||||
|
tuple(Source(s["host"], s["kind"], bool(s["ask"])) for s in self.custom_sources),
|
||||||
|
)
|
||||||
|
|
||||||
|
def capped(self, hard_cap_mb: int) -> MediaConfig:
|
||||||
|
return MediaConfig(
|
||||||
|
min(self.image_max_mb, hard_cap_mb),
|
||||||
|
min(self.video_max_mb, hard_cap_mb),
|
||||||
|
min(self.upload_max_mb, hard_cap_mb),
|
||||||
|
self.embed_youtube,
|
||||||
|
self.embed_vimeo,
|
||||||
|
list(self.peertube_hosts),
|
||||||
|
[dict(s) for s in self.custom_sources],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _int(value: Any, default: int, high: int) -> int:
|
||||||
|
try:
|
||||||
|
number = int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return default
|
||||||
|
return max(1, min(number, high))
|
||||||
|
|
||||||
|
|
||||||
|
def clean_sources(raw: Any) -> list[dict[str, Any]]:
|
||||||
|
sources: dict[str, dict[str, Any]] = {}
|
||||||
|
for item in raw if isinstance(raw, list) else []:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
host = clean_source_host(str(item.get("host", "")))
|
||||||
|
kind = str(item.get("kind", ""))
|
||||||
|
if host and kind in SOURCE_KINDS:
|
||||||
|
sources[host] = {"host": host, "kind": kind, "ask": bool(item.get("ask", True))}
|
||||||
|
return [sources[h] for h in sorted(sources)][:30]
|
||||||
|
|
||||||
|
|
||||||
|
def from_dict(data: dict[str, Any]) -> MediaConfig:
|
||||||
|
hosts = [h for h in (clean_host(str(x)) for x in data.get("peertube_hosts") or []) if h]
|
||||||
|
return MediaConfig(
|
||||||
|
image_max_mb=_int(data.get("image_max_mb"), 20, 4096),
|
||||||
|
video_max_mb=_int(data.get("video_max_mb"), 200, 4096),
|
||||||
|
upload_max_mb=_int(data.get("upload_max_mb"), 20, 4096),
|
||||||
|
embed_youtube=bool(data.get("embed_youtube")),
|
||||||
|
embed_vimeo=bool(data.get("embed_vimeo")),
|
||||||
|
peertube_hosts=sorted(set(hosts))[:20],
|
||||||
|
custom_sources=clean_sources(data.get("custom_sources")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def load(db: Session, hard_cap_mb: int) -> MediaConfig:
|
||||||
|
row = db.get(AppSetting, KEY)
|
||||||
|
config = from_dict(row.value if row is not None and isinstance(row.value, dict) else {})
|
||||||
|
return config.capped(hard_cap_mb)
|
||||||
|
|
||||||
|
|
||||||
|
def save(db: Session, config: MediaConfig) -> None:
|
||||||
|
row = db.get(AppSetting, KEY)
|
||||||
|
if row is None:
|
||||||
|
db.add(AppSetting(key=KEY, value=asdict(config)))
|
||||||
|
else:
|
||||||
|
row.value = asdict(config)
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Externe Videos als Zwei-Klick-Einbettung.
|
||||||
|
|
||||||
|
Feste Anbieter: YouTube, Vimeo, PeerTube. Dazu eigene Quellen, die der
|
||||||
|
Administrator freigibt (MediaCMS, eine Player-Seite oder eine direkte
|
||||||
|
Videodatei, etwa vom eigenen NAS).
|
||||||
|
|
||||||
|
Bei den festen Anbietern und MediaCMS wird aus der eingegebenen Adresse nur
|
||||||
|
die Video-Kennung übernommen; die Player-Adresse baut Surveybox selbst. Bei
|
||||||
|
eigenen Player-Seiten und Videodateien wird die Adresse übernommen, aber nur
|
||||||
|
mit HTTPS, nur vom freigegebenen Host und neu zusammengesetzt.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from urllib.parse import parse_qs, quote, urlsplit, urlunsplit
|
||||||
|
|
||||||
|
_YT_ID = re.compile(r"[A-Za-z0-9_-]{11}")
|
||||||
|
_VIMEO_ID = re.compile(r"\d{1,12}")
|
||||||
|
_VIMEO_HASH = re.compile(r"[0-9a-f]{6,20}")
|
||||||
|
_PT_ID = re.compile(r"[A-Za-z0-9-]{8,40}")
|
||||||
|
_HOST = re.compile(r"(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}")
|
||||||
|
_IPV4 = re.compile(r"(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}")
|
||||||
|
_MEDIACMS_ID = re.compile(r"[A-Za-z0-9_-]{6,64}")
|
||||||
|
MAX_URL = 500
|
||||||
|
SOURCE_KINDS = ("mediacms", "iframe", "file")
|
||||||
|
|
||||||
|
YOUTUBE_HOSTS = {"youtube.com", "www.youtube.com", "m.youtube.com", "youtu.be",
|
||||||
|
"www.youtube-nocookie.com", "youtube-nocookie.com"}
|
||||||
|
VIMEO_HOSTS = {"vimeo.com", "www.vimeo.com", "player.vimeo.com"}
|
||||||
|
PROVIDER_NAMES = {
|
||||||
|
"youtube": "YouTube",
|
||||||
|
"vimeo": "Vimeo",
|
||||||
|
"peertube": "PeerTube",
|
||||||
|
"mediacms": "MediaCMS",
|
||||||
|
}
|
||||||
|
BUILTIN = {"youtube", "vimeo", "peertube"}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Source:
|
||||||
|
"""Eigene Video-Quelle: Host (mit Port), Art, Klick vorab nötig."""
|
||||||
|
|
||||||
|
host: str
|
||||||
|
kind: str # mediacms | iframe | file
|
||||||
|
ask: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class EmbedPolicy:
|
||||||
|
"""Vom Administrator freigegebene Anbieter."""
|
||||||
|
|
||||||
|
youtube: bool = False
|
||||||
|
vimeo: bool = False
|
||||||
|
peertube_hosts: tuple[str, ...] = field(default_factory=tuple)
|
||||||
|
custom: tuple[Source, ...] = field(default_factory=tuple)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def any(self) -> bool:
|
||||||
|
return self.youtube or self.vimeo or bool(self.peertube_hosts) or bool(self.custom)
|
||||||
|
|
||||||
|
def source_for(self, host: str, kind: str | None = None) -> Source | None:
|
||||||
|
for source in self.custom:
|
||||||
|
if source.host == host and (kind is None or source.kind == kind):
|
||||||
|
return source
|
||||||
|
return None
|
||||||
|
|
||||||
|
def frame_sources(self) -> list[str]:
|
||||||
|
sources = []
|
||||||
|
if self.youtube:
|
||||||
|
sources.append("https://www.youtube-nocookie.com")
|
||||||
|
if self.vimeo:
|
||||||
|
sources.append("https://player.vimeo.com")
|
||||||
|
sources.extend(f"https://{h}" for h in self.peertube_hosts)
|
||||||
|
sources.extend(f"https://{c.host}" for c in self.custom if c.kind != "file")
|
||||||
|
return sources
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Embed:
|
||||||
|
provider: str # youtube | vimeo | peertube | mediacms | iframe | file
|
||||||
|
video: str = ""
|
||||||
|
host: str = ""
|
||||||
|
hash: str = ""
|
||||||
|
url: str = ""
|
||||||
|
|
||||||
|
def to_config(self) -> dict[str, str]:
|
||||||
|
data = {"kind": "embed", "provider": self.provider}
|
||||||
|
for key in ("video", "host", "hash", "url"):
|
||||||
|
if getattr(self, key):
|
||||||
|
data[key] = getattr(self, key)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
class EmbedError(ValueError):
|
||||||
|
def __init__(self, code: str) -> None:
|
||||||
|
super().__init__(code)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
def clean_host(value: str) -> str | None:
|
||||||
|
host = value.strip().lower().removeprefix("https://").removeprefix("http://").strip("/")
|
||||||
|
return host if _HOST.fullmatch(host) else None
|
||||||
|
|
||||||
|
|
||||||
|
def clean_source_host(value: str) -> str | None:
|
||||||
|
"""Host einer eigenen Quelle, auch IPv4 und mit Port: "nas.example.org:5001"."""
|
||||||
|
raw = value.strip().lower().removeprefix("https://").strip("/")
|
||||||
|
host, _, port = raw.partition(":")
|
||||||
|
if not (_HOST.fullmatch(host) or _IPV4.fullmatch(host)):
|
||||||
|
return None
|
||||||
|
if port:
|
||||||
|
if not port.isdigit() or not 1 <= int(port) <= 65535:
|
||||||
|
return None
|
||||||
|
return f"{host}:{int(port)}"
|
||||||
|
return host
|
||||||
|
|
||||||
|
|
||||||
|
def _netloc(parts: object) -> str:
|
||||||
|
hostname = getattr(parts, "hostname", None) or ""
|
||||||
|
try:
|
||||||
|
port = getattr(parts, "port", None)
|
||||||
|
except ValueError:
|
||||||
|
return ""
|
||||||
|
return f"{hostname}:{port}" if port and port != 443 else hostname
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_url(url: str, host: str) -> str | None:
|
||||||
|
"""HTTPS-Adresse vom erwarteten Host, neu und sicher zusammengesetzt."""
|
||||||
|
if len(url) > MAX_URL:
|
||||||
|
return None
|
||||||
|
parts = urlsplit(url.strip())
|
||||||
|
if parts.scheme != "https" or parts.username or parts.password:
|
||||||
|
return None
|
||||||
|
if _netloc(parts) != host:
|
||||||
|
return None
|
||||||
|
path = quote(parts.path or "/", safe="/%:@-._~!$&'()*+,;=")
|
||||||
|
query = quote(parts.query, safe="=&%:@-._~!$'()*+,;/?")
|
||||||
|
return urlunsplit(("https", host, path, query, ""))
|
||||||
|
|
||||||
|
|
||||||
|
def parse_url(url: str, policy: EmbedPolicy) -> Embed:
|
||||||
|
parts = urlsplit(url.strip())
|
||||||
|
if parts.scheme not in ("https", "http") or not parts.hostname:
|
||||||
|
raise EmbedError("embed_url_invalid")
|
||||||
|
host = parts.hostname.lower()
|
||||||
|
segments = [s for s in parts.path.split("/") if s]
|
||||||
|
|
||||||
|
if host in YOUTUBE_HOSTS:
|
||||||
|
if not policy.youtube:
|
||||||
|
raise EmbedError("embed_provider_disabled")
|
||||||
|
candidate = ""
|
||||||
|
if host == "youtu.be" and segments:
|
||||||
|
candidate = segments[0]
|
||||||
|
elif segments[:1] == ["watch"] or not segments:
|
||||||
|
candidate = (parse_qs(parts.query).get("v") or [""])[0]
|
||||||
|
elif len(segments) >= 2 and segments[0] in ("embed", "shorts", "live", "v"):
|
||||||
|
candidate = segments[1]
|
||||||
|
if not _YT_ID.fullmatch(candidate):
|
||||||
|
raise EmbedError("embed_url_invalid")
|
||||||
|
return Embed("youtube", candidate)
|
||||||
|
|
||||||
|
if host in VIMEO_HOSTS:
|
||||||
|
if not policy.vimeo:
|
||||||
|
raise EmbedError("embed_provider_disabled")
|
||||||
|
if host == "player.vimeo.com" and segments[:1] == ["video"]:
|
||||||
|
segments = segments[1:]
|
||||||
|
if not segments or not _VIMEO_ID.fullmatch(segments[0]):
|
||||||
|
raise EmbedError("embed_url_invalid")
|
||||||
|
query_hash = (parse_qs(parts.query).get("h") or [""])[0]
|
||||||
|
video_hash = segments[1] if len(segments) > 1 else query_hash
|
||||||
|
if video_hash and not _VIMEO_HASH.fullmatch(video_hash):
|
||||||
|
video_hash = ""
|
||||||
|
return Embed("vimeo", segments[0], hash=video_hash)
|
||||||
|
|
||||||
|
netloc = _netloc(parts)
|
||||||
|
source = policy.source_for(netloc)
|
||||||
|
if source is not None:
|
||||||
|
if source.kind == "mediacms":
|
||||||
|
token = (parse_qs(parts.query).get("m") or [""])[0]
|
||||||
|
if segments not in (["view"], ["embed"]) or not _MEDIACMS_ID.fullmatch(token):
|
||||||
|
raise EmbedError("embed_url_invalid")
|
||||||
|
return Embed("mediacms", token, host=netloc)
|
||||||
|
safe = _safe_url(url, netloc)
|
||||||
|
if safe is None:
|
||||||
|
raise EmbedError("embed_url_invalid")
|
||||||
|
return Embed(source.kind, host=netloc, url=safe)
|
||||||
|
|
||||||
|
if host in policy.peertube_hosts:
|
||||||
|
candidate = ""
|
||||||
|
if len(segments) == 2 and segments[0] == "w":
|
||||||
|
candidate = segments[1]
|
||||||
|
elif len(segments) == 3 and segments[0] == "videos" and segments[1] in ("watch", "embed"):
|
||||||
|
candidate = segments[2]
|
||||||
|
if not _PT_ID.fullmatch(candidate):
|
||||||
|
raise EmbedError("embed_url_invalid")
|
||||||
|
return Embed("peertube", candidate, host=host)
|
||||||
|
|
||||||
|
raise EmbedError("embed_provider_disabled")
|
||||||
|
|
||||||
|
|
||||||
|
def from_config(data: dict[str, object]) -> Embed | None:
|
||||||
|
provider = str(data.get("provider", ""))
|
||||||
|
video = str(data.get("video", ""))
|
||||||
|
host = str(data.get("host", ""))
|
||||||
|
video_hash = str(data.get("hash", ""))
|
||||||
|
if provider == "youtube" and _YT_ID.fullmatch(video):
|
||||||
|
return Embed(provider, video)
|
||||||
|
if provider == "vimeo" and _VIMEO_ID.fullmatch(video):
|
||||||
|
return Embed(provider, video, hash=video_hash if _VIMEO_HASH.fullmatch(video_hash) else "")
|
||||||
|
if provider == "peertube" and _PT_ID.fullmatch(video) and clean_host(host) == host:
|
||||||
|
return Embed(provider, video, host=host)
|
||||||
|
if provider == "mediacms" and _MEDIACMS_ID.fullmatch(video) and clean_source_host(host) == host:
|
||||||
|
return Embed(provider, video, host=host)
|
||||||
|
if provider in ("iframe", "file") and clean_source_host(host) == host:
|
||||||
|
safe = _safe_url(str(data.get("url", "")), host)
|
||||||
|
if safe is not None:
|
||||||
|
return Embed(provider, host=host, url=safe)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def player_url(embed: Embed) -> str:
|
||||||
|
if embed.provider == "mediacms":
|
||||||
|
return f"https://{embed.host}/embed?m={embed.video}"
|
||||||
|
if embed.provider in ("iframe", "file"):
|
||||||
|
return embed.url
|
||||||
|
if embed.provider == "youtube":
|
||||||
|
return f"https://www.youtube-nocookie.com/embed/{embed.video}?rel=0"
|
||||||
|
if embed.provider == "vimeo":
|
||||||
|
extra = f"&h={embed.hash}" if embed.hash else ""
|
||||||
|
return f"https://player.vimeo.com/video/{embed.video}?dnt=1{extra}"
|
||||||
|
return f"https://{embed.host}/videos/embed/{embed.video}?peertubeLink=0&warningTitle=0"
|
||||||
|
|
||||||
|
|
||||||
|
def watch_url(embed: Embed) -> str:
|
||||||
|
if embed.provider == "mediacms":
|
||||||
|
return f"https://{embed.host}/view?m={embed.video}"
|
||||||
|
if embed.provider in ("iframe", "file"):
|
||||||
|
return embed.url
|
||||||
|
if embed.provider == "youtube":
|
||||||
|
return f"https://www.youtube.com/watch?v={embed.video}"
|
||||||
|
if embed.provider == "vimeo":
|
||||||
|
return f"https://vimeo.com/{embed.video}" + (f"/{embed.hash}" if embed.hash else "")
|
||||||
|
return f"https://{embed.host}/w/{embed.video}"
|
||||||
|
|
||||||
|
|
||||||
|
def allowed(embed: Embed, policy: EmbedPolicy) -> bool:
|
||||||
|
if embed.provider == "youtube":
|
||||||
|
return policy.youtube
|
||||||
|
if embed.provider == "vimeo":
|
||||||
|
return policy.vimeo
|
||||||
|
if embed.provider == "peertube":
|
||||||
|
return embed.host in policy.peertube_hosts
|
||||||
|
return policy.source_for(embed.host, embed.provider) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def needs_consent(embed: Embed, policy: EmbedPolicy) -> bool:
|
||||||
|
"""Feste Anbieter immer; eigene Quellen, wie der Administrator es einstellt."""
|
||||||
|
if embed.provider in BUILTIN:
|
||||||
|
return True
|
||||||
|
source = policy.source_for(embed.host, embed.provider)
|
||||||
|
return source is None or source.ask
|
||||||
|
|
||||||
|
|
||||||
|
def provider_label(embed: Embed) -> str:
|
||||||
|
if embed.provider in ("iframe", "file"):
|
||||||
|
return embed.host
|
||||||
|
return PROVIDER_NAMES[embed.provider] + (f" ({embed.host})" if embed.host else "")
|
||||||
|
|
||||||
|
|
||||||
|
def csp_sources(embeds: list[Embed]) -> tuple[list[str], list[str]]:
|
||||||
|
"""(frame-src, media-src) für die Videos einer Seite."""
|
||||||
|
frames = sorted({f"https://{urlsplit(player_url(e)).netloc}" for e in embeds
|
||||||
|
if e.provider != "file"})
|
||||||
|
media = sorted({f"https://{e.host}" for e in embeds if e.provider == "file"})
|
||||||
|
return frames, media
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Bilder neu berechnen: ohne Metadaten, richtig gedreht, begrenzte Größe.
|
||||||
|
|
||||||
|
Gespeichert wird nie das Original. Die neu berechnete Fassung enthält weder
|
||||||
|
Standort noch Kameradaten, und manipulierte Dateien erreichen keinen Browser.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import warnings
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||||
|
|
||||||
|
MAX_PIXELS = 40_000_000 # größere Bilder werden abgelehnt (Schutz vor "Bildbomben")
|
||||||
|
FULL_SIZE = 2560
|
||||||
|
THUMB_SIZE = 640
|
||||||
|
ALLOWED_FORMATS = {"JPEG", "PNG", "WEBP"}
|
||||||
|
|
||||||
|
|
||||||
|
class ImageError(ValueError):
|
||||||
|
"""Die Datei ist kein verwendbares Bild."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ProcessedImage:
|
||||||
|
width: int
|
||||||
|
height: int
|
||||||
|
size: int
|
||||||
|
thumb_size: int
|
||||||
|
|
||||||
|
|
||||||
|
def _flatten(img: Image.Image) -> Image.Image:
|
||||||
|
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
|
||||||
|
return img.convert("RGBA")
|
||||||
|
return img.convert("RGB")
|
||||||
|
|
||||||
|
|
||||||
|
def load(source: Path) -> Image.Image:
|
||||||
|
"""Bild sicher öffnen: nur JPEG/PNG/WebP, begrenzte Größe, richtig gedreht."""
|
||||||
|
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||||
|
try:
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||||
|
with Image.open(source) as img:
|
||||||
|
if img.format not in ALLOWED_FORMATS:
|
||||||
|
raise ImageError("format")
|
||||||
|
if img.width * img.height > MAX_PIXELS:
|
||||||
|
raise ImageError("too_large")
|
||||||
|
img.seek(0) # bei animierten Bildern nur das erste Bild
|
||||||
|
rotated = ImageOps.exif_transpose(img)
|
||||||
|
base = _flatten(rotated)
|
||||||
|
except (UnidentifiedImageError, Image.DecompressionBombError, Image.DecompressionBombWarning,
|
||||||
|
OSError, SyntaxError) as exc:
|
||||||
|
raise ImageError("invalid") from exc
|
||||||
|
return base
|
||||||
|
|
||||||
|
|
||||||
|
def process(source: Path, full: Path, thumb: Path) -> ProcessedImage:
|
||||||
|
"""Schreibt eine große Fassung und ein Vorschaubild als WebP."""
|
||||||
|
base = load(source)
|
||||||
|
big = base.copy()
|
||||||
|
big.thumbnail((FULL_SIZE, FULL_SIZE), Image.Resampling.LANCZOS)
|
||||||
|
big.save(full, "WEBP", quality=85, method=4)
|
||||||
|
small = base.copy()
|
||||||
|
small.thumbnail((THUMB_SIZE, THUMB_SIZE), Image.Resampling.LANCZOS)
|
||||||
|
small.save(thumb, "WEBP", quality=80, method=4)
|
||||||
|
return ProcessedImage(big.width, big.height, full.stat().st_size, thumb.stat().st_size)
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Medien speichern, kopieren und den Fragen zuordnen."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import copy
|
||||||
|
import uuid
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, BinaryIO
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from surveybox.media import images, sniff, storage
|
||||||
|
from surveybox.models import Form, MediaFile, MediaKind, Question
|
||||||
|
from surveybox.settings import Settings
|
||||||
|
|
||||||
|
MB = 1024 * 1024
|
||||||
|
PENDING_HOURS = 24
|
||||||
|
MAX_GALLERY = 12
|
||||||
|
MAX_ALT = 300
|
||||||
|
MAX_CAPTIONS_BYTES = 1 * MB
|
||||||
|
|
||||||
|
|
||||||
|
class MediaError(ValueError):
|
||||||
|
def __init__(self, code: str) -> None:
|
||||||
|
super().__init__(code)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Incoming:
|
||||||
|
"""Ein angenommener Upload in einer temporären Datei."""
|
||||||
|
|
||||||
|
temp: Path
|
||||||
|
filetype: sniff.FileType | None
|
||||||
|
size: int
|
||||||
|
name: str
|
||||||
|
|
||||||
|
|
||||||
|
def receive(settings: Settings, source: BinaryIO, name: str, max_mb: int) -> Incoming:
|
||||||
|
temp = storage.temp_path(settings.tmp_dir)
|
||||||
|
try:
|
||||||
|
size = storage.receive(source, temp, max_mb * MB)
|
||||||
|
except storage.TooLarge as exc:
|
||||||
|
raise MediaError("file_too_large") from exc
|
||||||
|
if size == 0:
|
||||||
|
temp.unlink(missing_ok=True)
|
||||||
|
raise MediaError("file_empty")
|
||||||
|
return Incoming(temp, sniff.detect_file(temp, name), size, name)
|
||||||
|
|
||||||
|
|
||||||
|
def discard(incoming: Incoming) -> None:
|
||||||
|
incoming.temp.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _record(db: Session, form: Form, kind: str, **values: Any) -> MediaFile:
|
||||||
|
media = MediaFile(form_id=form.id, kind=kind, **values)
|
||||||
|
db.add(media)
|
||||||
|
db.flush()
|
||||||
|
return media
|
||||||
|
|
||||||
|
|
||||||
|
def store_image(
|
||||||
|
db: Session,
|
||||||
|
settings: Settings,
|
||||||
|
form: Form,
|
||||||
|
incoming: Incoming,
|
||||||
|
kind: str = MediaKind.IMAGE,
|
||||||
|
**values: Any,
|
||||||
|
) -> MediaFile:
|
||||||
|
"""Berechnet ein Bild neu und speichert große Fassung und Vorschau."""
|
||||||
|
if incoming.filetype is None or incoming.filetype.key not in sniff.IMAGE_KEYS:
|
||||||
|
discard(incoming)
|
||||||
|
raise MediaError("image_type")
|
||||||
|
full = storage.temp_path(settings.tmp_dir)
|
||||||
|
thumb = storage.temp_path(settings.tmp_dir)
|
||||||
|
try:
|
||||||
|
result = images.process(incoming.temp, full, thumb)
|
||||||
|
except images.ImageError as exc:
|
||||||
|
full.unlink(missing_ok=True)
|
||||||
|
thumb.unlink(missing_ok=True)
|
||||||
|
raise MediaError("image_invalid") from exc
|
||||||
|
finally:
|
||||||
|
discard(incoming)
|
||||||
|
root = settings.media_dir
|
||||||
|
return _record(
|
||||||
|
db,
|
||||||
|
form,
|
||||||
|
kind,
|
||||||
|
storage_key=storage.commit(root, full),
|
||||||
|
thumb_key=storage.commit(root, thumb),
|
||||||
|
content_type="image/webp",
|
||||||
|
size=result.size,
|
||||||
|
original_name=sniff.safe_filename(incoming.name, "webp"),
|
||||||
|
width=result.width,
|
||||||
|
height=result.height,
|
||||||
|
**values,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def store_file(
|
||||||
|
db: Session,
|
||||||
|
settings: Settings,
|
||||||
|
form: Form,
|
||||||
|
incoming: Incoming,
|
||||||
|
kind: str,
|
||||||
|
allowed: frozenset[str],
|
||||||
|
**values: Any,
|
||||||
|
) -> MediaFile:
|
||||||
|
"""Speichert eine Datei unverändert, wenn ihr Inhalt zu `allowed` passt."""
|
||||||
|
filetype = incoming.filetype
|
||||||
|
if filetype is None or filetype.key not in allowed:
|
||||||
|
discard(incoming)
|
||||||
|
raise MediaError("file_type")
|
||||||
|
if filetype.key == "vtt" and incoming.size > MAX_CAPTIONS_BYTES:
|
||||||
|
discard(incoming)
|
||||||
|
raise MediaError("file_too_large")
|
||||||
|
return _record(
|
||||||
|
db,
|
||||||
|
form,
|
||||||
|
kind,
|
||||||
|
storage_key=storage.commit(settings.media_dir, incoming.temp),
|
||||||
|
content_type=filetype.content_type,
|
||||||
|
size=incoming.size,
|
||||||
|
original_name=sniff.safe_filename(incoming.name, filetype.extension),
|
||||||
|
**values,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def store_answer_file(
|
||||||
|
db: Session,
|
||||||
|
settings: Settings,
|
||||||
|
form: Form,
|
||||||
|
question: Question,
|
||||||
|
incoming: Incoming,
|
||||||
|
allowed: frozenset[str],
|
||||||
|
) -> MediaFile:
|
||||||
|
"""Datei aus dem Fragetyp "Datei-Upload". Bilder verlieren ihre Metadaten."""
|
||||||
|
pending = datetime.now(UTC) + timedelta(hours=PENDING_HOURS)
|
||||||
|
values = {"question_id": question.id, "pending_until": pending}
|
||||||
|
if incoming.filetype is not None and incoming.filetype.key in sniff.IMAGE_KEYS:
|
||||||
|
if not allowed & sniff.IMAGE_KEYS:
|
||||||
|
discard(incoming)
|
||||||
|
raise MediaError("file_type")
|
||||||
|
media = store_image(db, settings, form, incoming, kind=MediaKind.UPLOAD, **values)
|
||||||
|
media.thumb_key = None # Vorschaubild wird nicht gebraucht
|
||||||
|
return media
|
||||||
|
return store_file(db, settings, form, incoming, MediaKind.UPLOAD, allowed, **values)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Nachschlagen
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def find(db: Session, form: Form, public_id: str) -> MediaFile | None:
|
||||||
|
try:
|
||||||
|
pid = uuid.UUID(public_id)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return db.scalar(
|
||||||
|
select(MediaFile).where(MediaFile.public_id == pid, MediaFile.form_id == form.id)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def by_ids(db: Session, form: Form, ids: list[str]) -> dict[str, MediaFile]:
|
||||||
|
parsed = []
|
||||||
|
for raw in ids:
|
||||||
|
try:
|
||||||
|
parsed.append(uuid.UUID(raw))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if not parsed:
|
||||||
|
return {}
|
||||||
|
rows = db.scalars(
|
||||||
|
select(MediaFile).where(MediaFile.form_id == form.id, MediaFile.public_id.in_(parsed))
|
||||||
|
)
|
||||||
|
return {str(m.public_id): m for m in rows}
|
||||||
|
|
||||||
|
|
||||||
|
def referenced_keys(db: Session) -> set[str]:
|
||||||
|
keys = set(db.scalars(select(MediaFile.storage_key)))
|
||||||
|
keys.update(k for k in db.scalars(select(MediaFile.thumb_key)) if k)
|
||||||
|
return keys
|
||||||
|
|
||||||
|
|
||||||
|
def file_path(settings: Settings, key: str) -> Path:
|
||||||
|
return storage.path_for(settings.media_dir, key)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Medien einer Frage (in question.config["media"])
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def question_media_ids(config: dict[str, Any]) -> list[str]:
|
||||||
|
"""Alle Medien-Kennungen, auf die eine Frage verweist."""
|
||||||
|
ids: list[str] = []
|
||||||
|
media = config.get("media") or {}
|
||||||
|
if media.get("kind") == "images":
|
||||||
|
ids.extend(str(item.get("id")) for item in media.get("items") or [])
|
||||||
|
elif media.get("kind") == "video":
|
||||||
|
ids.extend(str(media[k]) for k in ("id", "poster", "captions") if media.get(k))
|
||||||
|
ids.extend(str(o["image"]) for o in config.get("options") or [] if o.get("image"))
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def remap_config(config: dict[str, Any], mapping: dict[str, str]) -> dict[str, Any]:
|
||||||
|
"""Kopie der Konfiguration mit neuen Medien-Kennungen (beim Kopieren)."""
|
||||||
|
result = copy.deepcopy(config)
|
||||||
|
media = result.get("media") or {}
|
||||||
|
if media.get("kind") == "images":
|
||||||
|
media["items"] = [
|
||||||
|
{**item, "id": mapping[str(item["id"])]}
|
||||||
|
for item in media.get("items") or []
|
||||||
|
if str(item.get("id")) in mapping
|
||||||
|
]
|
||||||
|
elif media.get("kind") == "video":
|
||||||
|
for key in ("id", "poster", "captions"):
|
||||||
|
if media.get(key):
|
||||||
|
media[key] = mapping.get(str(media[key]))
|
||||||
|
if not media.get("id"):
|
||||||
|
result.pop("media", None)
|
||||||
|
for option in result.get("options") or []:
|
||||||
|
if option.get("image"):
|
||||||
|
new = mapping.get(str(option["image"]))
|
||||||
|
if new:
|
||||||
|
option["image"] = new
|
||||||
|
else:
|
||||||
|
option.pop("image")
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def duplicate(db: Session, media: MediaFile, form: Form, question_id: int | None) -> MediaFile:
|
||||||
|
"""Neuer Eintrag mit demselben (unveränderlichen) Inhalt."""
|
||||||
|
clone = MediaFile(
|
||||||
|
form_id=form.id,
|
||||||
|
question_id=question_id,
|
||||||
|
kind=media.kind,
|
||||||
|
storage_key=media.storage_key,
|
||||||
|
thumb_key=media.thumb_key,
|
||||||
|
content_type=media.content_type,
|
||||||
|
size=media.size,
|
||||||
|
original_name=media.original_name,
|
||||||
|
width=media.width,
|
||||||
|
height=media.height,
|
||||||
|
)
|
||||||
|
db.add(clone)
|
||||||
|
db.flush()
|
||||||
|
return clone
|
||||||
|
|
||||||
|
|
||||||
|
def unused_question_media(db: Session, question: Question) -> list[MediaFile]:
|
||||||
|
"""Medien der Frage, auf die ihre Konfiguration nicht mehr verweist."""
|
||||||
|
used = set(question_media_ids(question.config))
|
||||||
|
rows = db.scalars(
|
||||||
|
select(MediaFile).where(
|
||||||
|
MediaFile.question_id == question.id, MediaFile.kind != MediaKind.UPLOAD
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return [m for m in rows if str(m.public_id) not in used]
|
||||||
|
|
||||||
|
|
||||||
|
def drop_unused(db: Session, question: Question) -> None:
|
||||||
|
for media in unused_question_media(db, question):
|
||||||
|
db.delete(media)
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Dateityp am Inhalt erkennen, nie an Endung oder Angabe des Browsers allein.
|
||||||
|
|
||||||
|
Die Endung zählt nur dort, wo der Inhalt mehrdeutig ist: Office-Dateien sind
|
||||||
|
ZIP-Archive; welches Format genau vorliegt, steht in einer Datei im Archiv.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import zipfile
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class FileType:
|
||||||
|
key: str
|
||||||
|
content_type: str
|
||||||
|
extension: str
|
||||||
|
|
||||||
|
|
||||||
|
TYPES: dict[str, FileType] = {
|
||||||
|
t.key: t
|
||||||
|
for t in (
|
||||||
|
FileType("jpeg", "image/jpeg", "jpg"),
|
||||||
|
FileType("png", "image/png", "png"),
|
||||||
|
FileType("webp", "image/webp", "webp"),
|
||||||
|
FileType("mp4", "video/mp4", "mp4"),
|
||||||
|
FileType("webm", "video/webm", "webm"),
|
||||||
|
FileType("vtt", "text/vtt", "vtt"),
|
||||||
|
FileType("pdf", "application/pdf", "pdf"),
|
||||||
|
FileType("zip", "application/zip", "zip"),
|
||||||
|
FileType(
|
||||||
|
"docx",
|
||||||
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
"docx",
|
||||||
|
),
|
||||||
|
FileType(
|
||||||
|
"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx"
|
||||||
|
),
|
||||||
|
FileType(
|
||||||
|
"pptx",
|
||||||
|
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||||
|
"pptx",
|
||||||
|
),
|
||||||
|
FileType("odt", "application/vnd.oasis.opendocument.text", "odt"),
|
||||||
|
FileType("ods", "application/vnd.oasis.opendocument.spreadsheet", "ods"),
|
||||||
|
FileType("odp", "application/vnd.oasis.opendocument.presentation", "odp"),
|
||||||
|
FileType("txt", "text/plain", "txt"),
|
||||||
|
FileType("csv", "text/csv", "csv"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
IMAGE_KEYS = frozenset({"jpeg", "png", "webp"})
|
||||||
|
VIDEO_KEYS = frozenset({"mp4", "webm"})
|
||||||
|
|
||||||
|
# Gruppen für den Fragetyp "Datei-Upload"
|
||||||
|
UPLOAD_GROUPS: dict[str, frozenset[str]] = {
|
||||||
|
"pdf": frozenset({"pdf"}),
|
||||||
|
"images": IMAGE_KEYS,
|
||||||
|
"office": frozenset({"docx", "xlsx", "pptx", "odt", "ods", "odp"}),
|
||||||
|
"text": frozenset({"txt", "csv"}),
|
||||||
|
"zip": frozenset({"zip"}),
|
||||||
|
}
|
||||||
|
|
||||||
|
_OOXML = {"word/": "docx", "xl/": "xlsx", "ppt/": "pptx"}
|
||||||
|
_ODF = {
|
||||||
|
"application/vnd.oasis.opendocument.text": "odt",
|
||||||
|
"application/vnd.oasis.opendocument.spreadsheet": "ods",
|
||||||
|
"application/vnd.oasis.opendocument.presentation": "odp",
|
||||||
|
}
|
||||||
|
HEAD_SIZE = 64 * 1024
|
||||||
|
# MP4-Varianten, die Browser abspielen; QuickTime (.mov) gehört nicht dazu
|
||||||
|
_MP4_BRANDS = {b"isom", b"iso2", b"iso4", b"iso5", b"iso6", b"mp41", b"mp42", b"avc1", b"dash",
|
||||||
|
b"M4V ", b"MSNV"}
|
||||||
|
|
||||||
|
|
||||||
|
def _is_text(head: bytes) -> bool:
|
||||||
|
if b"\x00" in head:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
head.decode("utf-8")
|
||||||
|
except UnicodeDecodeError as exc:
|
||||||
|
# Am Ende abgeschnittenes Zeichen ist kein Fehler
|
||||||
|
if exc.start < len(head) - 4:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def from_head(head: bytes, filename: str = "") -> str | None:
|
||||||
|
"""Erkennt den Typ aus den ersten Bytes. ZIP-Formate liefern "zip"."""
|
||||||
|
name = filename.lower()
|
||||||
|
if head.startswith(b"\xff\xd8\xff"):
|
||||||
|
return "jpeg"
|
||||||
|
if head.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||||
|
return "png"
|
||||||
|
if len(head) >= 12 and head[:4] == b"RIFF" and head[8:12] == b"WEBP":
|
||||||
|
return "webp"
|
||||||
|
if len(head) >= 12 and head[4:8] == b"ftyp" and head[8:12] in _MP4_BRANDS:
|
||||||
|
return "mp4"
|
||||||
|
if head.startswith(b"\x1a\x45\xdf\xa3") and b"webm" in head[:64]:
|
||||||
|
return "webm"
|
||||||
|
if head.startswith(b"%PDF-"):
|
||||||
|
return "pdf"
|
||||||
|
if head.startswith(b"PK\x03\x04"):
|
||||||
|
return "zip"
|
||||||
|
text = head.removeprefix(b"\xef\xbb\xbf")
|
||||||
|
if text.startswith(b"WEBVTT") and _is_text(text):
|
||||||
|
return "vtt"
|
||||||
|
if _is_text(head) and head.strip():
|
||||||
|
return "csv" if name.endswith(".csv") else "txt"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _zip_kind(path: Path) -> str:
|
||||||
|
"""Unterscheidet Office-Formate von gewöhnlichen ZIP-Archiven."""
|
||||||
|
try:
|
||||||
|
with zipfile.ZipFile(path) as archive:
|
||||||
|
names = archive.namelist()
|
||||||
|
if "mimetype" in names:
|
||||||
|
mime = archive.read("mimetype")[:100].decode("ascii", "replace").strip()
|
||||||
|
if mime in _ODF:
|
||||||
|
return _ODF[mime]
|
||||||
|
if "[Content_Types].xml" in names:
|
||||||
|
for prefix, key in _OOXML.items():
|
||||||
|
if any(n.startswith(prefix) for n in names):
|
||||||
|
return key
|
||||||
|
except (zipfile.BadZipFile, OSError, KeyError):
|
||||||
|
return ""
|
||||||
|
return "zip"
|
||||||
|
|
||||||
|
|
||||||
|
def detect_file(path: Path, filename: str = "") -> FileType | None:
|
||||||
|
with path.open("rb") as handle:
|
||||||
|
head = handle.read(HEAD_SIZE)
|
||||||
|
key = from_head(head, filename)
|
||||||
|
if key == "zip":
|
||||||
|
key = _zip_kind(path) or None
|
||||||
|
return TYPES.get(key) if key else None
|
||||||
|
|
||||||
|
|
||||||
|
def safe_filename(name: str, extension: str) -> str:
|
||||||
|
"""Anzeigename für Downloads: ohne Pfad, ohne Steuerzeichen, passende Endung."""
|
||||||
|
base = name.replace("\\", "/").rsplit("/", 1)[-1]
|
||||||
|
base = "".join(ch for ch in base if ch.isprintable() and ch not in '"<>:|?*')
|
||||||
|
stem = base.rsplit(".", 1)[0].strip(" .")[:120] or "datei"
|
||||||
|
return f"{stem}.{extension}"
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Dateien im Volume ablegen, ausliefern und aufräumen.
|
||||||
|
|
||||||
|
Ablage unter `<data>/media/<aa>/<zufall>`; der Schlüssel enthält nichts aus
|
||||||
|
dem Dateinamen. Uploads werden zuerst in `<data>/tmp` geschrieben und dann
|
||||||
|
mit einer atomaren Umbenennung an ihren Platz gelegt.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import time
|
||||||
|
from collections.abc import Iterable
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import BinaryIO
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_KEY = re.compile(r"[0-9a-f]{2}/[0-9a-f]{32}")
|
||||||
|
CHUNK = 1024 * 1024
|
||||||
|
ORPHAN_MIN_AGE = 24 * 3600 # Sekunden; siehe models.MediaFile
|
||||||
|
TMP_MAX_AGE = 24 * 3600
|
||||||
|
|
||||||
|
|
||||||
|
class TooLarge(ValueError):
|
||||||
|
"""Die Datei überschreitet die erlaubte Größe."""
|
||||||
|
|
||||||
|
|
||||||
|
def new_key() -> str:
|
||||||
|
token = secrets.token_hex(16)
|
||||||
|
return f"{token[:2]}/{token}"
|
||||||
|
|
||||||
|
|
||||||
|
def path_for(root: Path, key: str) -> Path:
|
||||||
|
if not _KEY.fullmatch(key):
|
||||||
|
raise ValueError("ungültiger Speicherschlüssel")
|
||||||
|
return root / key
|
||||||
|
|
||||||
|
|
||||||
|
def temp_path(tmp_dir: Path) -> Path:
|
||||||
|
tmp_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
return tmp_dir / f"upload-{secrets.token_hex(12)}"
|
||||||
|
|
||||||
|
|
||||||
|
def receive(source: BinaryIO, target: Path, max_bytes: int) -> int:
|
||||||
|
"""Kopiert einen Upload in eine temporäre Datei, höchstens `max_bytes`."""
|
||||||
|
size = 0
|
||||||
|
try:
|
||||||
|
with target.open("wb") as out:
|
||||||
|
while chunk := source.read(CHUNK):
|
||||||
|
size += len(chunk)
|
||||||
|
if size > max_bytes:
|
||||||
|
raise TooLarge()
|
||||||
|
out.write(chunk)
|
||||||
|
except BaseException:
|
||||||
|
target.unlink(missing_ok=True)
|
||||||
|
raise
|
||||||
|
return size
|
||||||
|
|
||||||
|
|
||||||
|
def commit(root: Path, temp: Path) -> str:
|
||||||
|
"""Legt eine fertige temporäre Datei unter einem neuen Schlüssel ab."""
|
||||||
|
key = new_key()
|
||||||
|
final = path_for(root, key)
|
||||||
|
final.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
os.replace(temp, final)
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
def stored_keys(root: Path) -> Iterable[str]:
|
||||||
|
if not root.is_dir():
|
||||||
|
return
|
||||||
|
for sub in root.iterdir():
|
||||||
|
if not sub.is_dir():
|
||||||
|
continue
|
||||||
|
for item in sub.iterdir():
|
||||||
|
key = f"{sub.name}/{item.name}"
|
||||||
|
if _KEY.fullmatch(key) and item.is_file():
|
||||||
|
yield key
|
||||||
|
|
||||||
|
|
||||||
|
def sweep(root: Path, referenced: set[str], min_age: int = ORPHAN_MIN_AGE) -> int:
|
||||||
|
"""Löscht Dateien ohne Verweis, die älter als `min_age` Sekunden sind."""
|
||||||
|
now = time.time()
|
||||||
|
removed = 0
|
||||||
|
for key in list(stored_keys(root)):
|
||||||
|
if key in referenced:
|
||||||
|
continue
|
||||||
|
path = root / key
|
||||||
|
try:
|
||||||
|
if now - path.stat().st_mtime < min_age:
|
||||||
|
continue
|
||||||
|
path.unlink()
|
||||||
|
removed += 1
|
||||||
|
except FileNotFoundError:
|
||||||
|
continue
|
||||||
|
if removed:
|
||||||
|
log.info("%d verwaiste Dateien gelöscht", removed)
|
||||||
|
return removed
|
||||||
|
|
||||||
|
|
||||||
|
def clean_tmp(tmp_dir: Path, max_age: int = TMP_MAX_AGE) -> None:
|
||||||
|
if not tmp_dir.is_dir():
|
||||||
|
return
|
||||||
|
now = time.time()
|
||||||
|
for item in tmp_dir.iterdir():
|
||||||
|
try:
|
||||||
|
if item.is_file() and now - item.stat().st_mtime > max_age:
|
||||||
|
item.unlink()
|
||||||
|
except FileNotFoundError:
|
||||||
|
continue
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Alembic-Umgebung.
|
||||||
|
|
||||||
|
Alle ausstehenden Migrationen eines Updates laufen in EINER Transaktion.
|
||||||
|
PostgreSQL kann Strukturänderungen zurückrollen, also gilt: ganz oder gar
|
||||||
|
nicht. Ein abgebrochenes Update hinterlässt keine halb umgebaute Datenbank.
|
||||||
|
|
||||||
|
Normalerweise übergibt surveybox.upgrade die Verbindung (sie hält die
|
||||||
|
Migrationssperre). Für die Entwicklung funktioniert auch `alembic upgrade head`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
from sqlalchemy.engine import Connection
|
||||||
|
|
||||||
|
from surveybox.models import Base
|
||||||
|
|
||||||
|
config = context.config
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
|
||||||
|
def _run(connection: Connection) -> None:
|
||||||
|
context.configure(
|
||||||
|
connection=connection,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
compare_type=True,
|
||||||
|
transaction_per_migration=False,
|
||||||
|
)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
connection = config.attributes.get("connection")
|
||||||
|
if connection is not None:
|
||||||
|
_run(connection)
|
||||||
|
return
|
||||||
|
|
||||||
|
from surveybox.db import get_engine
|
||||||
|
|
||||||
|
with get_engine().connect() as conn:
|
||||||
|
_run(conn)
|
||||||
|
if conn.in_transaction():
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
raise SystemExit("Offline-Migrationen (SQL-Ausgabe) werden nicht unterstützt.")
|
||||||
|
|
||||||
|
run_migrations_online()
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision: ${up_revision}
|
||||||
|
Vorgänger: ${down_revision | comma,n}
|
||||||
|
Erstellt: ${create_date}
|
||||||
|
|
||||||
|
Regeln (siehe README, Abschnitt Migrationen):
|
||||||
|
- kleine Schritte, mehrfach ausführbar ohne Schaden
|
||||||
|
- Daten bereinigen, bevor eine Spalte verkleinert oder eindeutig wird
|
||||||
|
- kein CREATE INDEX CONCURRENTLY und kein autocommit_block: alles muss
|
||||||
|
in der gemeinsamen Transaktion des Updates laufen
|
||||||
|
- aufwändige Datenpflege als Hintergrundjob, nicht hier
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: str | None = ${repr(down_revision)}
|
||||||
|
branch_labels: str | Sequence[str] | None = ${repr(branch_labels)}
|
||||||
|
depends_on: str | Sequence[str] | None = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Grundtabellen: Einstellungen der Instanz und Zustand von Hintergrundaufgaben.
|
||||||
|
|
||||||
|
Revision: 0001_initial
|
||||||
|
Vorgänger: -
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "0001_initial"
|
||||||
|
down_revision: str | None = None
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"app_setting",
|
||||||
|
sa.Column("key", sa.Text(), nullable=False),
|
||||||
|
sa.Column("value", postgresql.JSONB(astext_type=sa.Text()), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"updated_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("now()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("key", name=op.f("pk_app_setting")),
|
||||||
|
)
|
||||||
|
op.create_table(
|
||||||
|
"job_state",
|
||||||
|
sa.Column("name", sa.Text(), nullable=False),
|
||||||
|
sa.Column("last_started_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column("last_finished_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column("last_success_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column("last_status", sa.Text(), nullable=True),
|
||||||
|
sa.Column("last_message", sa.Text(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint("name", name=op.f("pk_job_state")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("job_state")
|
||||||
|
op.drop_table("app_setting")
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Benutzerkonten, Sitzungen, Wiederherstellungscodes, Einmal-Links, Protokoll, Ratenbegrenzung.
|
||||||
|
|
||||||
|
Revision: 0002_accounts
|
||||||
|
Vorgänger: 0001_initial
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "0002_accounts"
|
||||||
|
down_revision: str | None = "0001_initial"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
TS = sa.DateTime(timezone=True)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"user_account",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"public_id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
server_default=sa.text("gen_random_uuid()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("email", sa.Text(), nullable=False),
|
||||||
|
sa.Column("email_verified_at", TS, nullable=True),
|
||||||
|
sa.Column("display_name", sa.Text(), nullable=False),
|
||||||
|
sa.Column("role", sa.Text(), nullable=False),
|
||||||
|
sa.Column("is_active", sa.Boolean(), server_default=sa.text("true"), nullable=False),
|
||||||
|
sa.Column("language", sa.Text(), nullable=True),
|
||||||
|
sa.Column("password_hash", sa.Text(), nullable=True),
|
||||||
|
sa.Column("password_changed_at", TS, nullable=True),
|
||||||
|
sa.Column("totp_secret_enc", postgresql.BYTEA(), nullable=True),
|
||||||
|
sa.Column("totp_enabled_at", TS, nullable=True),
|
||||||
|
sa.Column("totp_last_step", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("failed_logins", sa.Integer(), server_default=sa.text("0"), nullable=False),
|
||||||
|
sa.Column("locked_until", TS, nullable=True),
|
||||||
|
sa.Column("last_login_at", TS, nullable=True),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("updated_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"role IN ('admin', 'creator', 'participant')",
|
||||||
|
name=op.f("ck_user_account_role_valid"),
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("email = lower(email)", name=op.f("ck_user_account_email_lowercase")),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_user_account")),
|
||||||
|
sa.UniqueConstraint("email", name=op.f("uq_user_account_email")),
|
||||||
|
sa.UniqueConstraint("public_id", name=op.f("uq_user_account_public_id")),
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"user_session",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("token_hash", postgresql.BYTEA(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("state", sa.Text(), nullable=False),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("last_seen_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("expires_at", TS, nullable=False),
|
||||||
|
sa.Column("reauth_at", TS, nullable=True),
|
||||||
|
sa.Column("mfa_attempts", sa.Integer(), server_default=sa.text("0"), nullable=False),
|
||||||
|
sa.Column("user_agent", sa.Text(), nullable=True),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"state IN ('active', 'pending_mfa')", name=op.f("ck_user_session_state_valid")
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_user_session_user_id_user_account"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_user_session")),
|
||||||
|
sa.UniqueConstraint("token_hash", name=op.f("uq_user_session_token_hash")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_user_session_user_id"), "user_session", ["user_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"recovery_code",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("code_hash", postgresql.BYTEA(), nullable=False),
|
||||||
|
sa.Column("used_at", TS, nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_recovery_code_user_id_user_account"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_recovery_code")),
|
||||||
|
sa.UniqueConstraint("code_hash", name=op.f("uq_recovery_code_code_hash")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_recovery_code_user_id"), "recovery_code", ["user_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"action_token",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("token_hash", postgresql.BYTEA(), nullable=False),
|
||||||
|
sa.Column("purpose", sa.Text(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("created_by_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("expires_at", TS, nullable=False),
|
||||||
|
sa.Column("used_at", TS, nullable=True),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"purpose IN ('invite', 'reset')", name=op.f("ck_action_token_purpose_valid")
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["created_by_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_action_token_created_by_id_user_account"),
|
||||||
|
ondelete="SET NULL",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_action_token_user_id_user_account"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_action_token")),
|
||||||
|
sa.UniqueConstraint("token_hash", name=op.f("uq_action_token_token_hash")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_action_token_user_id"), "action_token", ["user_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"audit_event",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("occurred_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("actor_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("action", sa.Text(), nullable=False),
|
||||||
|
sa.Column("target_type", sa.Text(), nullable=True),
|
||||||
|
sa.Column("target_id", sa.Text(), nullable=True),
|
||||||
|
sa.Column("details", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["actor_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_audit_event_actor_id_user_account"),
|
||||||
|
ondelete="SET NULL",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_audit_event")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_audit_event_occurred_at"), "audit_event", ["occurred_at"])
|
||||||
|
op.create_index(op.f("ix_audit_event_actor_id"), "audit_event", ["actor_id"])
|
||||||
|
op.create_index(op.f("ix_audit_event_action"), "audit_event", ["action"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"rate_limit",
|
||||||
|
sa.Column("key", sa.Text(), nullable=False),
|
||||||
|
sa.Column("window_start", TS, nullable=False),
|
||||||
|
sa.Column("count", sa.Integer(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("key", name=op.f("pk_rate_limit")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("rate_limit")
|
||||||
|
op.drop_index(op.f("ix_audit_event_action"), table_name="audit_event")
|
||||||
|
op.drop_index(op.f("ix_audit_event_actor_id"), table_name="audit_event")
|
||||||
|
op.drop_index(op.f("ix_audit_event_occurred_at"), table_name="audit_event")
|
||||||
|
op.drop_table("audit_event")
|
||||||
|
op.drop_index(op.f("ix_action_token_user_id"), table_name="action_token")
|
||||||
|
op.drop_table("action_token")
|
||||||
|
op.drop_index(op.f("ix_recovery_code_user_id"), table_name="recovery_code")
|
||||||
|
op.drop_table("recovery_code")
|
||||||
|
op.drop_index(op.f("ix_user_session_user_id"), table_name="user_session")
|
||||||
|
op.drop_table("user_session")
|
||||||
|
op.drop_table("user_account")
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Passkeys (WebAuthn), Einmal-Challenges und Benutzergruppen.
|
||||||
|
|
||||||
|
Revision: 0003_passkeys_groups
|
||||||
|
Vorgänger: 0002_accounts
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "0003_passkeys_groups"
|
||||||
|
down_revision: str | None = "0002_accounts"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
TS = sa.DateTime(timezone=True)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("user_account", sa.Column("webauthn_user_id", postgresql.BYTEA(), nullable=True))
|
||||||
|
op.create_unique_constraint(
|
||||||
|
op.f("uq_user_account_webauthn_user_id"), "user_account", ["webauthn_user_id"]
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"webauthn_credential",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("credential_id", postgresql.BYTEA(), nullable=False),
|
||||||
|
sa.Column("public_key", postgresql.BYTEA(), nullable=False),
|
||||||
|
sa.Column("sign_count", sa.BigInteger(), server_default=sa.text("0"), nullable=False),
|
||||||
|
sa.Column("transports", postgresql.ARRAY(sa.Text()), nullable=True),
|
||||||
|
sa.Column("name", sa.Text(), nullable=False),
|
||||||
|
sa.Column("backed_up", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("last_used_at", TS, nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_webauthn_credential_user_id_user_account"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_webauthn_credential")),
|
||||||
|
sa.UniqueConstraint("credential_id", name=op.f("uq_webauthn_credential_credential_id")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_webauthn_credential_user_id"), "webauthn_credential", ["user_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"auth_challenge",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("handle_hash", postgresql.BYTEA(), nullable=False),
|
||||||
|
sa.Column("purpose", sa.Text(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("challenge", postgresql.BYTEA(), nullable=False),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("expires_at", TS, nullable=False),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"purpose IN ('register', 'login', 'mfa')", name=op.f("ck_auth_challenge_purpose_valid")
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_auth_challenge_user_id_user_account"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_auth_challenge")),
|
||||||
|
sa.UniqueConstraint("handle_hash", name=op.f("uq_auth_challenge_handle_hash")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_auth_challenge_user_id"), "auth_challenge", ["user_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"user_group",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"public_id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
server_default=sa.text("gen_random_uuid()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("name", sa.Text(), nullable=False),
|
||||||
|
sa.Column("description", sa.Text(), nullable=True),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_user_group")),
|
||||||
|
sa.UniqueConstraint("name", name=op.f("uq_user_group_name")),
|
||||||
|
sa.UniqueConstraint("public_id", name=op.f("uq_user_group_public_id")),
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"group_member",
|
||||||
|
sa.Column("group_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("added_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["group_id"],
|
||||||
|
["user_group.id"],
|
||||||
|
name=op.f("fk_group_member_group_id_user_group"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_group_member_user_id_user_account"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("group_id", "user_id", name=op.f("pk_group_member")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_group_member_user_id"), "group_member", ["user_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index(op.f("ix_group_member_user_id"), table_name="group_member")
|
||||||
|
op.drop_table("group_member")
|
||||||
|
op.drop_table("user_group")
|
||||||
|
op.drop_index(op.f("ix_auth_challenge_user_id"), table_name="auth_challenge")
|
||||||
|
op.drop_table("auth_challenge")
|
||||||
|
op.drop_index(op.f("ix_webauthn_credential_user_id"), table_name="webauthn_credential")
|
||||||
|
op.drop_table("webauthn_credential")
|
||||||
|
op.drop_constraint(op.f("uq_user_account_webauthn_user_id"), "user_account", type_="unique")
|
||||||
|
op.drop_column("user_account", "webauthn_user_id")
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Formulare, Zugriffsliste, Fragen, Antworten (typisiert), Teilnahme-Merker.
|
||||||
|
|
||||||
|
Revision: 0004_forms
|
||||||
|
Vorgänger: 0003_passkeys_groups
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "0004_forms"
|
||||||
|
down_revision: str | None = "0003_passkeys_groups"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
TS = sa.DateTime(timezone=True)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"form",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"public_id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
server_default=sa.text("gen_random_uuid()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("share_token", sa.Text(), nullable=False),
|
||||||
|
sa.Column("owner_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("title", sa.Text(), nullable=False),
|
||||||
|
sa.Column("description", sa.Text(), nullable=True),
|
||||||
|
sa.Column("status", sa.Text(), server_default=sa.text("'draft'"), nullable=False),
|
||||||
|
sa.Column("opens_at", TS, nullable=True),
|
||||||
|
sa.Column("closes_at", TS, nullable=True),
|
||||||
|
sa.Column("access", sa.Text(), server_default=sa.text("'users'"), nullable=False),
|
||||||
|
sa.Column("link_password_hash", sa.Text(), nullable=True),
|
||||||
|
sa.Column("allow_multiple", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
||||||
|
sa.Column("allow_edit", sa.Text(), server_default=sa.text("'until_close'"), nullable=False),
|
||||||
|
sa.Column("anonymous", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
||||||
|
sa.Column("guest_email", sa.Text(), server_default=sa.text("'none'"), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"results_visibility", sa.Text(), server_default=sa.text("'never'"), nullable=False
|
||||||
|
),
|
||||||
|
sa.Column("retention_days", sa.Integer(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"deletion_mode", sa.Text(), server_default=sa.text("'anonymize'"), nullable=False
|
||||||
|
),
|
||||||
|
sa.Column("privacy_notice", sa.Text(), nullable=True),
|
||||||
|
sa.Column("require_consent", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
||||||
|
sa.Column("consent_text", sa.Text(), nullable=True),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("updated_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"status IN ('draft', 'open', 'closed')", name=op.f("ck_form_status_valid")
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"access IN ('users', 'restricted', 'link', 'link_password')",
|
||||||
|
name=op.f("ck_form_access_valid"),
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"allow_edit IN ('no', 'until_close')", name=op.f("ck_form_allow_edit_valid")
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"guest_email IN ('none', 'optional', 'required')",
|
||||||
|
name=op.f("ck_form_guest_email_valid"),
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"results_visibility IN ('never', 'after_submit', 'after_close')",
|
||||||
|
name=op.f("ck_form_results_visibility_valid"),
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"deletion_mode IN ('delete', 'anonymize')", name=op.f("ck_form_deletion_mode_valid")
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["owner_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_form_owner_id_user_account"),
|
||||||
|
ondelete="SET NULL",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_form")),
|
||||||
|
sa.UniqueConstraint("public_id", name=op.f("uq_form_public_id")),
|
||||||
|
sa.UniqueConstraint("share_token", name=op.f("uq_form_share_token")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_form_owner_id"), "form", ["owner_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"form_access",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("form_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("group_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"(user_id IS NULL) <> (group_id IS NULL)",
|
||||||
|
name=op.f("ck_form_access_exactly_one_target"),
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["form_id"], ["form.id"], name=op.f("fk_form_access_form_id_form"), ondelete="CASCADE"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["group_id"],
|
||||||
|
["user_group.id"],
|
||||||
|
name=op.f("fk_form_access_group_id_user_group"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_form_access_user_id_user_account"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_form_access")),
|
||||||
|
sa.UniqueConstraint("form_id", "group_id", name="uq_form_access_group"),
|
||||||
|
sa.UniqueConstraint("form_id", "user_id", name="uq_form_access_user"),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_form_access_user_id"), "form_access", ["user_id"])
|
||||||
|
op.create_index(op.f("ix_form_access_group_id"), "form_access", ["group_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"question",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("form_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("position", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("type", sa.Text(), nullable=False),
|
||||||
|
sa.Column("label", sa.Text(), nullable=False),
|
||||||
|
sa.Column("help_text", sa.Text(), nullable=True),
|
||||||
|
sa.Column("required", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
||||||
|
sa.Column("personal", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"config",
|
||||||
|
postgresql.JSONB(astext_type=sa.Text()),
|
||||||
|
server_default=sa.text("'{}'::jsonb"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["form_id"], ["form.id"], name=op.f("fk_question_form_id_form"), ondelete="CASCADE"
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_question")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_question_form_id"), "question", ["form_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"response",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"public_id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
server_default=sa.text("gen_random_uuid()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("form_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("submitted_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("updated_at", TS, nullable=True),
|
||||||
|
sa.Column("consent_at", TS, nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["form_id"], ["form.id"], name=op.f("fk_response_form_id_form"), ondelete="CASCADE"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_response_user_id_user_account"),
|
||||||
|
ondelete="SET NULL",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_response")),
|
||||||
|
sa.UniqueConstraint("public_id", name=op.f("uq_response_public_id")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_response_form_id"), "response", ["form_id"])
|
||||||
|
op.create_index(op.f("ix_response_user_id"), "response", ["user_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"answer",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("response_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("question_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("value_text", sa.Text(), nullable=True),
|
||||||
|
sa.Column("value_number", sa.Numeric(20, 6), nullable=True),
|
||||||
|
sa.Column("value_bool", sa.Boolean(), nullable=True),
|
||||||
|
sa.Column("value_date", sa.Date(), nullable=True),
|
||||||
|
sa.Column("value_time", sa.Time(), nullable=True),
|
||||||
|
sa.Column("value_datetime", TS, nullable=True),
|
||||||
|
sa.Column("value_json", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["question_id"],
|
||||||
|
["question.id"],
|
||||||
|
name=op.f("fk_answer_question_id_question"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["response_id"],
|
||||||
|
["response.id"],
|
||||||
|
name=op.f("fk_answer_response_id_response"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_answer")),
|
||||||
|
sa.UniqueConstraint("response_id", "question_id", name="uq_answer_question"),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_answer_question_id"), "answer", ["question_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"form_participation",
|
||||||
|
sa.Column("form_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("marker", postgresql.BYTEA(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["form_id"],
|
||||||
|
["form.id"],
|
||||||
|
name=op.f("fk_form_participation_form_id_form"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("form_id", "marker", name=op.f("pk_form_participation")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("form_participation")
|
||||||
|
op.drop_index(op.f("ix_answer_question_id"), table_name="answer")
|
||||||
|
op.drop_table("answer")
|
||||||
|
op.drop_index(op.f("ix_response_user_id"), table_name="response")
|
||||||
|
op.drop_index(op.f("ix_response_form_id"), table_name="response")
|
||||||
|
op.drop_table("response")
|
||||||
|
op.drop_index(op.f("ix_question_form_id"), table_name="question")
|
||||||
|
op.drop_table("question")
|
||||||
|
op.drop_index(op.f("ix_form_access_group_id"), table_name="form_access")
|
||||||
|
op.drop_index(op.f("ix_form_access_user_id"), table_name="form_access")
|
||||||
|
op.drop_table("form_access")
|
||||||
|
op.drop_index(op.f("ix_form_owner_id"), table_name="form")
|
||||||
|
op.drop_table("form")
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Medien (Bilder, Videos, Uploads), Mitbearbeitende und Auswertende, Vorlagen.
|
||||||
|
|
||||||
|
Revision: 0005_media_team
|
||||||
|
Vorgänger: 0004_forms
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "0005_media_team"
|
||||||
|
down_revision: str | None = "0004_forms"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
TS = sa.DateTime(timezone=True)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column(
|
||||||
|
"form",
|
||||||
|
sa.Column("is_template", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
||||||
|
)
|
||||||
|
op.add_column(
|
||||||
|
"form",
|
||||||
|
sa.Column(
|
||||||
|
"template_shared", sa.Boolean(), server_default=sa.text("false"), nullable=False
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"form_member",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("form_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("group_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("role", sa.Text(), nullable=False),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"(user_id IS NULL) <> (group_id IS NULL)",
|
||||||
|
name=op.f("ck_form_member_exactly_one_target"),
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"role IN ('editor', 'evaluator')", name=op.f("ck_form_member_role_valid")
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["form_id"], ["form.id"], name=op.f("fk_form_member_form_id_form"), ondelete="CASCADE"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_form_member_user_id_user_account"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["group_id"],
|
||||||
|
["user_group.id"],
|
||||||
|
name=op.f("fk_form_member_group_id_user_group"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_form_member")),
|
||||||
|
sa.UniqueConstraint("form_id", "user_id", name="uq_form_member_user"),
|
||||||
|
sa.UniqueConstraint("form_id", "group_id", name="uq_form_member_group"),
|
||||||
|
)
|
||||||
|
for col in ("form_id", "user_id", "group_id"):
|
||||||
|
op.create_index(op.f(f"ix_form_member_{col}"), "form_member", [col])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"media_file",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"public_id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
server_default=sa.text("gen_random_uuid()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("form_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("question_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("response_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("kind", sa.Text(), nullable=False),
|
||||||
|
sa.Column("storage_key", sa.Text(), nullable=False),
|
||||||
|
sa.Column("thumb_key", sa.Text(), nullable=True),
|
||||||
|
sa.Column("content_type", sa.Text(), nullable=False),
|
||||||
|
sa.Column("size", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("original_name", sa.Text(), nullable=True),
|
||||||
|
sa.Column("width", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("height", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("pending_until", TS, nullable=True),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"kind IN ('image', 'video', 'captions', 'document', 'upload')",
|
||||||
|
name=op.f("ck_media_file_kind_valid"),
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["form_id"], ["form.id"], name=op.f("fk_media_file_form_id_form"), ondelete="CASCADE"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["question_id"],
|
||||||
|
["question.id"],
|
||||||
|
name=op.f("fk_media_file_question_id_question"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["response_id"],
|
||||||
|
["response.id"],
|
||||||
|
name=op.f("fk_media_file_response_id_response"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_media_file")),
|
||||||
|
sa.UniqueConstraint("public_id", name=op.f("uq_media_file_public_id")),
|
||||||
|
)
|
||||||
|
for col in ("form_id", "question_id", "response_id", "storage_key", "thumb_key"):
|
||||||
|
op.create_index(op.f(f"ix_media_file_{col}"), "media_file", [col])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for col in ("form_id", "question_id", "response_id", "storage_key", "thumb_key"):
|
||||||
|
op.drop_index(op.f(f"ix_media_file_{col}"), table_name="media_file")
|
||||||
|
op.drop_table("media_file")
|
||||||
|
for col in ("form_id", "user_id", "group_id"):
|
||||||
|
op.drop_index(op.f(f"ix_form_member_{col}"), table_name="form_member")
|
||||||
|
op.drop_table("form_member")
|
||||||
|
op.drop_column("form", "template_shared")
|
||||||
|
op.drop_column("form", "is_template")
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Gruppen: für welche Benutzertypen sie passen (NULL = alle).
|
||||||
|
|
||||||
|
Revision: 0006_group_roles
|
||||||
|
Vorgänger: 0005_media_team
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "0006_group_roles"
|
||||||
|
down_revision: str | None = "0005_media_team"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("user_group", sa.Column("roles", postgresql.ARRAY(sa.Text()), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("user_group", "roles")
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Gruppenhierarchie, Gruppenrollen (Administrator, Ersteller), Gruppe einer Umfrage.
|
||||||
|
|
||||||
|
Revision: 0007_group_hierarchy
|
||||||
|
Vorgänger: 0006_group_roles
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "0007_group_hierarchy"
|
||||||
|
down_revision: str | None = "0006_group_roles"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("user_group", sa.Column("parent_id", sa.BigInteger(), nullable=True))
|
||||||
|
op.create_foreign_key(
|
||||||
|
op.f("fk_user_group_parent_id_user_group"),
|
||||||
|
"user_group",
|
||||||
|
"user_group",
|
||||||
|
["parent_id"],
|
||||||
|
["id"],
|
||||||
|
ondelete="SET NULL",
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_user_group_parent_id"), "user_group", ["parent_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"group_role",
|
||||||
|
sa.Column("group_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("role", sa.Text(), nullable=False),
|
||||||
|
sa.CheckConstraint("role IN ('admin', 'creator')", name=op.f("ck_group_role_role_valid")),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["group_id"],
|
||||||
|
["user_group.id"],
|
||||||
|
name=op.f("fk_group_role_group_id_user_group"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_group_role_user_id_user_account"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("group_id", "user_id", "role", name=op.f("pk_group_role")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_group_role_user_id"), "group_role", ["user_id"])
|
||||||
|
|
||||||
|
op.add_column("form", sa.Column("group_id", sa.BigInteger(), nullable=True))
|
||||||
|
op.create_foreign_key(
|
||||||
|
op.f("fk_form_group_id_user_group"),
|
||||||
|
"form",
|
||||||
|
"user_group",
|
||||||
|
["group_id"],
|
||||||
|
["id"],
|
||||||
|
ondelete="SET NULL",
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_form_group_id"), "form", ["group_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index(op.f("ix_form_group_id"), table_name="form")
|
||||||
|
op.drop_constraint(op.f("fk_form_group_id_user_group"), "form", type_="foreignkey")
|
||||||
|
op.drop_column("form", "group_id")
|
||||||
|
op.drop_index(op.f("ix_group_role_user_id"), table_name="group_role")
|
||||||
|
op.drop_table("group_role")
|
||||||
|
op.drop_index(op.f("ix_user_group_parent_id"), table_name="user_group")
|
||||||
|
op.drop_constraint(
|
||||||
|
op.f("fk_user_group_parent_id_user_group"), "user_group", type_="foreignkey"
|
||||||
|
)
|
||||||
|
op.drop_column("user_group", "parent_id")
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Teilnahme-Plätze (Buchungen), Kalender, Kommentare.
|
||||||
|
|
||||||
|
Revision: 0008_polls_slots_comments
|
||||||
|
Vorgänger: 0007_group_hierarchy
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "0008_polls_slots_comments"
|
||||||
|
down_revision: str | None = "0007_group_hierarchy"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
TS = sa.DateTime(timezone=True)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("form", sa.Column("slots_max_per_person", sa.Integer(), nullable=True))
|
||||||
|
op.add_column(
|
||||||
|
"form",
|
||||||
|
sa.Column("calendar_mode", sa.Text(), server_default=sa.text("'off'"), nullable=False),
|
||||||
|
)
|
||||||
|
op.add_column("form", sa.Column("calendar_token", sa.Text(), nullable=True))
|
||||||
|
op.create_unique_constraint(op.f("uq_form_calendar_token"), "form", ["calendar_token"])
|
||||||
|
op.add_column(
|
||||||
|
"form",
|
||||||
|
sa.Column(
|
||||||
|
"comments_mode", sa.Text(), server_default=sa.text("'moderated'"), nullable=False
|
||||||
|
),
|
||||||
|
)
|
||||||
|
op.add_column(
|
||||||
|
"form",
|
||||||
|
sa.Column(
|
||||||
|
"comments_anonymous", sa.Boolean(), server_default=sa.text("false"), nullable=False
|
||||||
|
),
|
||||||
|
)
|
||||||
|
op.add_column(
|
||||||
|
"form",
|
||||||
|
sa.Column("comments_notify", sa.Boolean(), server_default=sa.text("true"), nullable=False),
|
||||||
|
)
|
||||||
|
op.create_check_constraint(
|
||||||
|
op.f("ck_form_calendar_mode_valid"), "form", "calendar_mode IN ('off', 'file', 'feed')"
|
||||||
|
)
|
||||||
|
op.create_check_constraint(
|
||||||
|
op.f("ck_form_comments_mode_valid"),
|
||||||
|
"form",
|
||||||
|
"comments_mode IN ('off', 'moderated', 'public')",
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"booking",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("form_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("question_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("option_id", sa.Text(), nullable=False),
|
||||||
|
sa.Column("response_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("status", sa.Text(), nullable=False),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("promoted_at", TS, nullable=True),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"status IN ('confirmed', 'waiting')", name=op.f("ck_booking_status_valid")
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["form_id"], ["form.id"], name=op.f("fk_booking_form_id_form"), ondelete="CASCADE"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["question_id"],
|
||||||
|
["question.id"],
|
||||||
|
name=op.f("fk_booking_question_id_question"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["response_id"],
|
||||||
|
["response.id"],
|
||||||
|
name=op.f("fk_booking_response_id_response"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_booking")),
|
||||||
|
sa.UniqueConstraint(
|
||||||
|
"response_id", "question_id", "option_id", name="uq_booking_option"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
for col in ("form_id", "question_id", "response_id"):
|
||||||
|
op.create_index(op.f(f"ix_booking_{col}"), "booking", [col])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"comment",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"public_id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
server_default=sa.text("gen_random_uuid()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("form_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("guest_name", sa.Text(), nullable=True),
|
||||||
|
sa.Column("author_token", postgresql.BYTEA(), nullable=True),
|
||||||
|
sa.Column("body", sa.Text(), nullable=False),
|
||||||
|
sa.Column("status", sa.Text(), nullable=False),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("updated_at", TS, nullable=True),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"status IN ('pending', 'published')", name=op.f("ck_comment_status_valid")
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["form_id"], ["form.id"], name=op.f("fk_comment_form_id_form"), ondelete="CASCADE"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_comment_user_id_user_account"),
|
||||||
|
ondelete="SET NULL",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_comment")),
|
||||||
|
sa.UniqueConstraint("public_id", name=op.f("uq_comment_public_id")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_comment_form_id"), "comment", ["form_id"])
|
||||||
|
op.create_index(op.f("ix_comment_user_id"), "comment", ["user_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index(op.f("ix_comment_user_id"), table_name="comment")
|
||||||
|
op.drop_index(op.f("ix_comment_form_id"), table_name="comment")
|
||||||
|
op.drop_table("comment")
|
||||||
|
for col in ("form_id", "question_id", "response_id"):
|
||||||
|
op.drop_index(op.f(f"ix_booking_{col}"), table_name="booking")
|
||||||
|
op.drop_table("booking")
|
||||||
|
op.drop_constraint(op.f("ck_form_comments_mode_valid"), "form", type_="check")
|
||||||
|
op.drop_constraint(op.f("ck_form_calendar_mode_valid"), "form", type_="check")
|
||||||
|
for col in ("comments_notify", "comments_anonymous", "comments_mode"):
|
||||||
|
op.drop_column("form", col)
|
||||||
|
op.drop_constraint(op.f("uq_form_calendar_token"), "form", type_="unique")
|
||||||
|
for col in ("calendar_token", "calendar_mode", "slots_max_per_person"):
|
||||||
|
op.drop_column("form", col)
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""E-Mail-Warteschlange, Benachrichtigungseinstellungen, Antwort-an-Adresse.
|
||||||
|
|
||||||
|
Revision: 0009_mail
|
||||||
|
Vorgänger: 0008_polls_slots_comments
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "0009_mail"
|
||||||
|
down_revision: str | None = "0008_polls_slots_comments"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
TS = sa.DateTime(timezone=True)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column(
|
||||||
|
"user_account",
|
||||||
|
sa.Column(
|
||||||
|
"notify_prefs",
|
||||||
|
postgresql.JSONB(astext_type=sa.Text()),
|
||||||
|
server_default=sa.text("'{}'::jsonb"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
op.add_column("form", sa.Column("reply_to", sa.Text(), nullable=True))
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"mail_message",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("kind", sa.Text(), nullable=False),
|
||||||
|
sa.Column("recipient", sa.Text(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("form_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("content_enc", postgresql.BYTEA(), nullable=True),
|
||||||
|
sa.Column("status", sa.Text(), server_default=sa.text("'queued'"), nullable=False),
|
||||||
|
sa.Column("attempts", sa.Integer(), server_default=sa.text("0"), nullable=False),
|
||||||
|
sa.Column("next_attempt_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("sent_at", TS, nullable=True),
|
||||||
|
sa.Column("last_error", sa.Text(), nullable=True),
|
||||||
|
sa.Column("dedupe_key", sa.Text(), nullable=True),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"status IN ('queued', 'sent', 'failed')", name=op.f("ck_mail_message_status_valid")
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_mail_message_user_id_user_account"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["form_id"], ["form.id"], name=op.f("fk_mail_message_form_id_form"),
|
||||||
|
ondelete="SET NULL",
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_mail_message")),
|
||||||
|
sa.UniqueConstraint("dedupe_key", name=op.f("uq_mail_message_dedupe_key")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_mail_message_user_id"), "mail_message", ["user_id"])
|
||||||
|
op.create_index(op.f("ix_mail_message_form_id"), "mail_message", ["form_id"])
|
||||||
|
op.create_index("ix_mail_message_due", "mail_message", ["status", "next_attempt_at"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"form_mute",
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("form_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["user_account.id"],
|
||||||
|
name=op.f("fk_form_mute_user_id_user_account"),
|
||||||
|
ondelete="CASCADE",
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["form_id"], ["form.id"], name=op.f("fk_form_mute_form_id_form"), ondelete="CASCADE"
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("user_id", "form_id", name=op.f("pk_form_mute")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_form_mute_form_id"), "form_mute", ["form_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index(op.f("ix_form_mute_form_id"), table_name="form_mute")
|
||||||
|
op.drop_table("form_mute")
|
||||||
|
op.drop_index("ix_mail_message_due", table_name="mail_message")
|
||||||
|
op.drop_index(op.f("ix_mail_message_form_id"), table_name="mail_message")
|
||||||
|
op.drop_index(op.f("ix_mail_message_user_id"), table_name="mail_message")
|
||||||
|
op.drop_table("mail_message")
|
||||||
|
op.drop_column("form", "reply_to")
|
||||||
|
op.drop_column("user_account", "notify_prefs")
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Gäste: Adressen mit Double-Opt-in, persönliche Links zu Antworten.
|
||||||
|
|
||||||
|
Revision: 0010_guests
|
||||||
|
Vorgänger: 0009_mail
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "0010_guests"
|
||||||
|
down_revision: str | None = "0009_mail"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
TS = sa.DateTime(timezone=True)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"guest_contact",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"public_id",
|
||||||
|
postgresql.UUID(as_uuid=True),
|
||||||
|
server_default=sa.text("gen_random_uuid()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("email", sa.Text(), nullable=False),
|
||||||
|
sa.Column("language", sa.Text(), nullable=True),
|
||||||
|
sa.Column("confirmed_at", TS, nullable=True),
|
||||||
|
sa.Column("confirm_hash", postgresql.BYTEA(), nullable=True),
|
||||||
|
sa.Column("notify", sa.Boolean(), server_default=sa.text("true"), nullable=False),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_guest_contact")),
|
||||||
|
sa.UniqueConstraint("public_id", name=op.f("uq_guest_contact_public_id")),
|
||||||
|
sa.UniqueConstraint("email", name=op.f("uq_guest_contact_email")),
|
||||||
|
sa.UniqueConstraint("confirm_hash", name=op.f("uq_guest_contact_confirm_hash")),
|
||||||
|
)
|
||||||
|
op.add_column("response", sa.Column("guest_contact_id", sa.BigInteger(), nullable=True))
|
||||||
|
op.add_column("response", sa.Column("access_hash", postgresql.BYTEA(), nullable=True))
|
||||||
|
op.create_foreign_key(
|
||||||
|
op.f("fk_response_guest_contact_id_guest_contact"),
|
||||||
|
"response",
|
||||||
|
"guest_contact",
|
||||||
|
["guest_contact_id"],
|
||||||
|
["id"],
|
||||||
|
ondelete="SET NULL",
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_response_guest_contact_id"), "response", ["guest_contact_id"])
|
||||||
|
op.create_unique_constraint(op.f("uq_response_access_hash"), "response", ["access_hash"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_constraint(op.f("uq_response_access_hash"), "response", type_="unique")
|
||||||
|
op.drop_index(op.f("ix_response_guest_contact_id"), table_name="response")
|
||||||
|
op.drop_constraint(
|
||||||
|
op.f("fk_response_guest_contact_id_guest_contact"), "response", type_="foreignkey"
|
||||||
|
)
|
||||||
|
op.drop_column("response", "access_hash")
|
||||||
|
op.drop_column("response", "guest_contact_id")
|
||||||
|
op.drop_table("guest_contact")
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Gast-Adresse wahlweise aus der Frage "E-Mail-Adresse".
|
||||||
|
|
||||||
|
Revision: 0011_guest_email_question
|
||||||
|
Vorgänger: 0010_guests
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "0011_guest_email_question"
|
||||||
|
down_revision: str | None = "0010_guests"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.drop_constraint(op.f("ck_form_guest_email_valid"), "form", type_="check")
|
||||||
|
op.create_check_constraint(
|
||||||
|
op.f("ck_form_guest_email_valid"),
|
||||||
|
"form",
|
||||||
|
"guest_email IN ('none', 'optional', 'required', 'question')",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.execute("UPDATE form SET guest_email = 'none' WHERE guest_email = 'question'")
|
||||||
|
op.drop_constraint(op.f("ck_form_guest_email_valid"), "form", type_="check")
|
||||||
|
op.create_check_constraint(
|
||||||
|
op.f("ck_form_guest_email_valid"),
|
||||||
|
"form",
|
||||||
|
"guest_email IN ('none', 'optional', 'required')",
|
||||||
|
)
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Folge-Mails mit Dokumenten, Erinnerung vor dem Enddatum.
|
||||||
|
|
||||||
|
Revision: 0012_followups
|
||||||
|
Vorgänger: 0011_guest_email_question
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = "0012_followups"
|
||||||
|
down_revision: str | None = "0011_guest_email_question"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
TS = sa.DateTime(timezone=True)
|
||||||
|
UUID_DEFAULT = sa.text("gen_random_uuid()")
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("form", sa.Column("reminder_days", sa.Integer(), nullable=True))
|
||||||
|
op.create_table(
|
||||||
|
"followup",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("public_id", postgresql.UUID(as_uuid=True), server_default=UUID_DEFAULT,
|
||||||
|
nullable=False),
|
||||||
|
sa.Column("form_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("subject", sa.Text(), nullable=False),
|
||||||
|
sa.Column("body", sa.Text(), nullable=False),
|
||||||
|
sa.Column("trigger", sa.Text(), nullable=False),
|
||||||
|
sa.Column("send_at", TS, nullable=True),
|
||||||
|
sa.Column("only_confirmed", sa.Boolean(), server_default=sa.text("false"),
|
||||||
|
nullable=False),
|
||||||
|
sa.Column("link_days", sa.Integer(), server_default=sa.text("90"), nullable=False),
|
||||||
|
sa.Column("sent_at", TS, nullable=True),
|
||||||
|
sa.Column("created_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.Column("updated_at", TS, nullable=True),
|
||||||
|
sa.CheckConstraint("trigger IN ('submit', 'close', 'at', 'manual')",
|
||||||
|
name=op.f("ck_followup_trigger_valid")),
|
||||||
|
sa.CheckConstraint("link_days BETWEEN 1 AND 3650",
|
||||||
|
name=op.f("ck_followup_link_days_valid")),
|
||||||
|
sa.ForeignKeyConstraint(["form_id"], ["form.id"], name=op.f("fk_followup_form_id_form"),
|
||||||
|
ondelete="CASCADE"),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_followup")),
|
||||||
|
sa.UniqueConstraint("public_id", name=op.f("uq_followup_public_id")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_followup_form_id"), "followup", ["form_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"followup_document",
|
||||||
|
sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("public_id", postgresql.UUID(as_uuid=True), server_default=UUID_DEFAULT,
|
||||||
|
nullable=False),
|
||||||
|
sa.Column("followup_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("media_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("title", sa.Text(), nullable=False),
|
||||||
|
sa.Column("position", sa.Integer(), server_default=sa.text("0"), nullable=False),
|
||||||
|
sa.Column("downloads", sa.Integer(), server_default=sa.text("0"), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["followup_id"], ["followup.id"],
|
||||||
|
name=op.f("fk_followup_document_followup_id_followup"),
|
||||||
|
ondelete="CASCADE"),
|
||||||
|
sa.ForeignKeyConstraint(["media_id"], ["media_file.id"],
|
||||||
|
name=op.f("fk_followup_document_media_id_media_file"),
|
||||||
|
ondelete="CASCADE"),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_followup_document")),
|
||||||
|
sa.UniqueConstraint("public_id", name=op.f("uq_followup_document_public_id")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_followup_document_followup_id"), "followup_document",
|
||||||
|
["followup_id"])
|
||||||
|
op.create_index(op.f("ix_followup_document_media_id"), "followup_document", ["media_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"followup_delivery",
|
||||||
|
sa.Column("followup_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("recipient", sa.Text(), nullable=False),
|
||||||
|
sa.Column("response_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("sent_at", TS, server_default=sa.text("now()"), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["followup_id"], ["followup.id"],
|
||||||
|
name=op.f("fk_followup_delivery_followup_id_followup"),
|
||||||
|
ondelete="CASCADE"),
|
||||||
|
sa.ForeignKeyConstraint(["response_id"], ["response.id"],
|
||||||
|
name=op.f("fk_followup_delivery_response_id_response"),
|
||||||
|
ondelete="SET NULL"),
|
||||||
|
sa.PrimaryKeyConstraint("followup_id", "recipient", name=op.f("pk_followup_delivery")),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_followup_delivery_response_id"), "followup_delivery",
|
||||||
|
["response_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index(op.f("ix_followup_delivery_response_id"), table_name="followup_delivery")
|
||||||
|
op.drop_table("followup_delivery")
|
||||||
|
op.drop_index(op.f("ix_followup_document_media_id"), table_name="followup_document")
|
||||||
|
op.drop_index(op.f("ix_followup_document_followup_id"), table_name="followup_document")
|
||||||
|
op.drop_table("followup_document")
|
||||||
|
op.drop_index(op.f("ix_followup_form_id"), table_name="followup")
|
||||||
|
op.drop_table("followup")
|
||||||
|
op.drop_column("form", "reminder_days")
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Folge-Mails: später Hinzukommende automatisch beliefern (nachholen).
|
||||||
|
|
||||||
|
Revision: 0013_followup_catch_up
|
||||||
|
Vorgänger: 0012_followups
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "0013_followup_catch_up"
|
||||||
|
down_revision: str | None = "0012_followups"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# NULL: noch nicht entschieden; der Editor fragt beim nächsten Speichern nach
|
||||||
|
op.add_column("followup", sa.Column("catch_up", sa.Boolean(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("followup", "catch_up")
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Löschfristen: Ende des Formulars, Hinweis an den Eigentümer, anonymisierte Antworten.
|
||||||
|
|
||||||
|
Revision: 0014_retention
|
||||||
|
Vorgänger: 0013_followup_catch_up
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "0014_retention"
|
||||||
|
down_revision: str | None = "0013_followup_catch_up"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
TS = sa.DateTime(timezone=True)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("form", sa.Column("closed_at", TS, nullable=True))
|
||||||
|
op.add_column("form", sa.Column("retention_notified_at", TS, nullable=True))
|
||||||
|
op.add_column("response", sa.Column("anonymized_at", TS, nullable=True))
|
||||||
|
# Bereits geschlossene Formulare: Ende ist das Enddatum oder die letzte Änderung.
|
||||||
|
# Gelöscht wird trotzdem erst nach einem Hinweis an den Eigentümer und frühestens
|
||||||
|
# sieben Tage danach.
|
||||||
|
op.execute(
|
||||||
|
"UPDATE form SET closed_at = COALESCE(closes_at, updated_at) WHERE status = 'closed'"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("response", "anonymized_at")
|
||||||
|
op.drop_column("form", "retention_notified_at")
|
||||||
|
op.drop_column("form", "closed_at")
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
"""Personen löschen: Kommentare gelöschter Konten kennzeichnen.
|
||||||
|
|
||||||
|
Revision: 0015_erasure
|
||||||
|
Vorgänger: 0014_retention
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "0015_erasure"
|
||||||
|
down_revision: str | None = "0014_retention"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("comment", sa.Column("author_deleted", sa.Boolean(),
|
||||||
|
server_default=sa.text("false"), nullable=False))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("comment", "author_deleted")
|
||||||
Loaded 100 of 286 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user