Backup/Restore + Nadel mit QR, Debug Firebase

This commit is contained in:
concierge committed 2026-11-09 05:33:39 +01:00
1 parent 4c8b11c4d5
commit c51ef02f88
16 files changed
+634 -7

No files matched your search

+24
View File
@@ -18,6 +18,30 @@ flask --app cmbnet run --debug --host 127.0.0.1 --port 5000
Öffne http://127.0.0.1:5000 und wähle einen Mandanten (BV, RV, SV). Öffne http://127.0.0.1:5000 und wähle einen Mandanten (BV, RV, SV).
## Administrator-Dashboard
Das Dashboard unter `/<tenant>/admin/dashboard` bietet zusätzlich:
- **Datenbank-Backup herunterladen:** erzeugt über die SQLite-Backup-API
einen konsistenten Snapshot der laufenden Datenbank (`.sqlite3`).
- **Backup wiederherstellen:** lädt eine solche Datei hoch, prüft Integrität
und Grundschema und ersetzt anschließend die Live-Datenbank. Währenddessen
sollten keine anderen Benutzer aktiv arbeiten.
- **Konfiguration anzeigen/herunterladen:** listet alle
Konfigurationsparameter als `Key: Value` und exportiert sie als Textdatei.
Geheimnisse wie `SECRET_KEY` und `FCM_SERVICE_ACCOUNT_JSON` werden maskiert.
Die maximale Upload-Größe wird über `CMBNET_BACKUP_MAX_UPLOAD_MB`
(Default `256`) festgelegt.
## Dispatcher: Gruppenposition teilen
Der Nadel-Button (📍) einer Gruppe zentriert die Karte auf die letzte
Gruppenposition. Die Zoomstufe ist über `CMBNET_GROUP_POSITION_ZOOM`
(Default `18`) konfigurierbar. Zusätzlich öffnet der Button ein Karten-Popup
mit einem QR-Code. Der QR-Code verweist auf einen WhatsApp-Deep-Link, der die
Position als Google-Maps-Link teilt.
## Mandantenspezifische Straßen-Polylines ## Mandantenspezifische Straßen-Polylines
Die Karten-Views laden `static/js/str2pl-<tenant>.js`, sofern diese Datei Die Karten-Views laden `static/js/str2pl-<tenant>.js`, sofern diese Datei
+2
View File
@@ -149,6 +149,7 @@ def create_app(config_name=None):
from cmbnet.admin.gruppen import admin_gruppen_bp from cmbnet.admin.gruppen import admin_gruppen_bp
from cmbnet.admin.strassen import admin_strassen_bp from cmbnet.admin.strassen import admin_strassen_bp
from cmbnet.admin.api import admin_api_bp from cmbnet.admin.api import admin_api_bp
from cmbnet.admin.backup import admin_backup_bp
from cmbnet.api.init import api_init_bp from cmbnet.api.init import api_init_bp
from cmbnet.api.auth import api_auth_bp from cmbnet.api.auth import api_auth_bp
from cmbnet.api.groups import api_groups_bp from cmbnet.api.groups import api_groups_bp
@@ -164,6 +165,7 @@ def create_app(config_name=None):
app.register_blueprint(admin_gruppen_bp, url_prefix='/<tenant>/admin') app.register_blueprint(admin_gruppen_bp, url_prefix='/<tenant>/admin')
app.register_blueprint(admin_strassen_bp, url_prefix='/<tenant>/admin') app.register_blueprint(admin_strassen_bp, url_prefix='/<tenant>/admin')
app.register_blueprint(admin_api_bp, url_prefix='/<tenant>/admin/api') app.register_blueprint(admin_api_bp, url_prefix='/<tenant>/admin/api')
app.register_blueprint(admin_backup_bp, url_prefix='/<tenant>/admin')
app.register_blueprint(api_init_bp, url_prefix='/<tenant>/api') app.register_blueprint(api_init_bp, url_prefix='/<tenant>/api')
app.register_blueprint(api_auth_bp, url_prefix='/<tenant>/api') app.register_blueprint(api_auth_bp, url_prefix='/<tenant>/api')
app.register_blueprint(api_groups_bp, url_prefix='/<tenant>/api') app.register_blueprint(api_groups_bp, url_prefix='/<tenant>/api')
+1
View File
@@ -2,5 +2,6 @@ from .accounts import admin_accounts_bp
from .gruppen import admin_gruppen_bp from .gruppen import admin_gruppen_bp
from .strassen import admin_strassen_bp from .strassen import admin_strassen_bp
from .api import admin_api_bp from .api import admin_api_bp
from .backup import admin_backup_bp
admin_bp = admin_accounts_bp admin_bp = admin_accounts_bp
+3 -1
View File
@@ -5,6 +5,7 @@ from flask import Blueprint, make_response, render_template, g
from cmbnet.auth import role_required from cmbnet.auth import role_required
from cmbnet.db import get_db from cmbnet.db import get_db
from cmbnet.services.api_token_service import ApiTokenService from cmbnet.services.api_token_service import ApiTokenService
from cmbnet.admin.backup import collect_config_items
admin_accounts_bp = Blueprint('admin', __name__) admin_accounts_bp = Blueprint('admin', __name__)
@@ -15,7 +16,8 @@ def dashboard(**kwargs):
"""Admin Dashboard""" """Admin Dashboard"""
response = make_response(render_template( response = make_response(render_template(
'admin/dashboard.html', 'admin/dashboard.html',
api_tokens=ApiTokenService.list_for_tenant(g.tenant_id) api_tokens=ApiTokenService.list_for_tenant(g.tenant_id),
config_items=collect_config_items()
)) ))
# Die Seite enthält Zugriffstoken und darf nicht im Browser-Cache landen. # Die Seite enthält Zugriffstoken und darf nicht im Browser-Cache landen.
response.headers['Cache-Control'] = 'no-store' response.headers['Cache-Control'] = 'no-store'
+253
View File
@@ -0,0 +1,253 @@
"""Datenbank-Backup, Wiederherstellung und Konfigurationsexport.
Die Backup-Datei ist eine vollständige SQLite-Datenbank. Sie wird über die
SQLite-Backup-API erzeugt und kann deshalb auch bei aktivem WAL-Modus
konsistent heruntergeladen werden. Beim Hochladen wird die Datei vor dem
Ersetzen der Live-Datenbank auf Integrität und die wichtigsten Tabellen
geprüft.
"""
from __future__ import annotations
import json
import sqlite3
import tempfile
from datetime import datetime
from pathlib import Path
from flask import (
Blueprint,
Response,
abort,
after_this_request,
current_app,
flash,
redirect,
request,
send_file,
url_for,
)
from cmbnet.auth import role_required
from cmbnet.db import get_db
from cmbnet.db.database import ensure_schema
from cmbnet.services.groups_service import GroupsService
from cmbnet.utils.helpers import notify_reload
admin_backup_bp = Blueprint('admin_backup', __name__)
# Mindestens diese Tabellen muss ein gültiges CMBNet-Backup enthalten. Ältere
# Backups werden nach der Wiederherstellung durch ``ensure_schema`` ergänzt.
REQUIRED_TABLES = frozenset({'tenants', 'accounts', 'groups', 'streets'})
# Werte dieser Schlüssel werden in der Konfigurationsanzeige und im Export
# maskiert. Der Administrator sieht alle Schlüssel, aber keine Geheimnisse,
# mit denen sich Sessions oder FCM-Zugänge übernehmen lassen.
SECRET_CONFIG_KEYS = frozenset({
'SECRET_KEY',
'FCM_SERVICE_ACCOUNT_JSON',
})
def _format_config_value(value):
if isinstance(value, bool):
return 'true' if value else 'false'
if value is None:
return ''
if isinstance(value, (dict, list, tuple, set)):
return json.dumps(value, ensure_ascii=False, default=str, sort_keys=True)
return str(value)
def _is_secret_config_key(key):
upper = str(key).upper()
return upper in SECRET_CONFIG_KEYS or 'PASSWORD' in upper
def collect_config_items():
"""Liefert alle Konfigurationswerte als sortierte ``(Key, Value)``-Liste.
Geheimnisse werden maskiert, damit ein versehentlich weitergegebener
Export keine Session- oder Service-Account-Schlüssel enthält. Der
Schlüssel selbst bleibt sichtbar, sodass die Liste vollständig ist.
"""
items = []
for key in sorted(current_app.config):
if _is_secret_config_key(key):
value = '*** maskiert ***'
else:
value = _format_config_value(current_app.config[key])
items.append((key, value))
return items
@admin_backup_bp.route('/backup/download')
@role_required('Administrator')
def download_backup(**kwargs):
"""Erzeugt einen konsistenten SQLite-Snapshot und liefert ihn als Datei."""
source = get_db()
source.commit()
temp = tempfile.NamedTemporaryFile(
prefix='cmbnet-backup-',
suffix='.sqlite3',
delete=False,
)
temp_path = Path(temp.name)
temp.close()
destination = None
try:
destination = sqlite3.connect(str(temp_path))
source.backup(destination)
destination.commit()
except Exception:
current_app.logger.exception('Datenbank-Backup konnte nicht erstellt werden.')
try:
destination.close()
except Exception:
pass
try:
temp_path.unlink()
except OSError:
pass
abort(500, 'Backup konnte nicht erstellt werden.')
try:
destination.close()
except Exception:
pass
@after_this_request
def remove_temp_file(response):
try:
temp_path.unlink()
except OSError:
pass
return response
filename = f'cmbnet-backup-{datetime.now():%Y%m%d-%H%M%S}.sqlite3'
return send_file(
temp_path,
mimetype='application/vnd.sqlite3',
as_attachment=True,
download_name=filename,
max_age=0,
)
def _validate_backup_file(path):
"""Prüft Integrität und Grundschema einer hochgeladenen SQLite-Datei."""
conn = sqlite3.connect(str(path))
try:
result = conn.execute('PRAGMA integrity_check').fetchone()
if not result or str(result[0]).lower() != 'ok':
raise ValueError('Die Datei ist keine gültige SQLite-Datenbank.')
tables = {
str(row[0])
for row in conn.execute(
"SELECT name FROM sqlite_master WHERE type = 'table'"
).fetchall()
}
missing = REQUIRED_TABLES - tables
if missing:
raise ValueError(
'Das Backup ist unvollständig. Fehlende Tabellen: '
+ ', '.join(sorted(missing))
)
finally:
conn.close()
@admin_backup_bp.route('/backup/restore', methods=['POST'])
@role_required('Administrator')
def restore_backup(**kwargs):
"""Ersetzt die Live-Datenbank durch ein hochgeladenes Backup."""
upload = request.files.get('backup')
if upload is None or not upload.filename:
flash('Bitte eine Backup-Datei auswählen.', 'error')
return redirect(url_for('admin.dashboard', tenant=kwargs.get('tenant')))
max_bytes = int(current_app.config.get(
'BACKUP_MAX_UPLOAD_BYTES', 256 * 1024 * 1024
))
if request.content_length and request.content_length > max_bytes:
flash('Die Backup-Datei ist zu groß.', 'error')
return redirect(url_for('admin.dashboard', tenant=kwargs.get('tenant')))
temp = tempfile.NamedTemporaryFile(
prefix='cmbnet-restore-',
suffix='.sqlite3',
delete=False,
)
temp_path = Path(temp.name)
temp.close()
source = None
destination = None
try:
upload.save(temp_path)
if temp_path.stat().st_size > max_bytes:
raise ValueError('Die Backup-Datei ist zu groß.')
if temp_path.stat().st_size < 512:
raise ValueError('Die Backup-Datei ist leer oder beschädigt.')
_validate_backup_file(temp_path)
destination = get_db()
destination.commit()
source = sqlite3.connect(str(temp_path))
source.backup(destination)
destination.commit()
# Die Backup-Datei kann im DELETE-Journalmodus erzeugt worden sein.
# Für den Mehr-Worker-Betrieb wird die Live-Datenbank wieder auf WAL
# umgestellt.
destination.execute('PRAGMA journal_mode = WAL')
destination.execute('PRAGMA synchronous = NORMAL')
destination.commit()
# Nach dem Einspielen fehlende Spalten/Tabellen älterer Backups
# ergänzen und alle prozesslokalen Caches verwerfen.
ensure_schema()
GroupsService.invalidate_all()
except Exception as exc:
current_app.logger.exception('Datenbank-Wiederherstellung fehlgeschlagen.')
try:
if destination is not None:
destination.rollback()
except Exception:
pass
flash(f'Wiederherstellung fehlgeschlagen: {exc}', 'error')
return redirect(url_for('admin.dashboard', tenant=kwargs.get('tenant')))
finally:
try:
if source is not None:
source.close()
except Exception:
pass
try:
temp_path.unlink()
except OSError:
pass
try:
notify_reload('Administration: Die Datenbank wurde aus einem Backup wiederhergestellt.')
except Exception:
current_app.logger.warning('Reload-Hinweis nach Restore fehlgeschlagen.', exc_info=True)
flash('Datenbank wurde erfolgreich wiederhergestellt.', 'success')
return redirect(url_for('admin.dashboard', tenant=kwargs.get('tenant')))
@admin_backup_bp.route('/config/export')
@role_required('Administrator')
def export_config(**kwargs):
"""Liefert alle Konfigurationsparameter als Key:Value-Textdatei."""
lines = [f'{key}: {value}' for key, value in collect_config_items()]
body = '\n'.join(lines) + '\n'
filename = f'cmbnet-config-{datetime.now():%Y%m%d-%H%M%S}.txt'
response = Response(body, mimetype='text/plain; charset=utf-8')
response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
response.headers['Cache-Control'] = 'no-store'
return response
+13
View File
@@ -47,6 +47,19 @@ class Config:
WS_WORKER_ID = os.environ.get('CMBNET_WS_WORKER_ID', '') WS_WORKER_ID = os.environ.get('CMBNET_WS_WORKER_ID', '')
LATE_ENTRY_MAX_AGE_HOURS = int(os.environ.get('CMBNET_LATE_ENTRY_MAX_AGE_HOURS', '8')) LATE_ENTRY_MAX_AGE_HOURS = int(os.environ.get('CMBNET_LATE_ENTRY_MAX_AGE_HOURS', '8'))
# Zoomstufe, auf die der Nadel-Button im Dispatcher eine Gruppenposition
# zentriert. Der Wert wird clientseitig auf den gültigen Leaflet-Bereich
# begrenzt.
GROUP_POSITION_ZOOM = int(os.environ.get(
'CMBNET_GROUP_POSITION_ZOOM', '18'
))
# Maximale Größe eines hochgeladenen Datenbank-Backups. Schützt vor
# versehentlich großen Uploads; der Download ist davon nicht betroffen.
BACKUP_MAX_UPLOAD_BYTES = int(os.environ.get(
'CMBNET_BACKUP_MAX_UPLOAD_MB', '256'
)) * 1024 * 1024
# ------------------------------------------------------------------ # ------------------------------------------------------------------
# Firebase Cloud Messaging (nur Aufwachsignal, keine Nutzdaten) # Firebase Cloud Messaging (nur Aufwachsignal, keine Nutzdaten)
# ------------------------------------------------------------------ # ------------------------------------------------------------------
+28
View File
@@ -16,6 +16,34 @@ table td {
font-size: 0.82rem; font-size: 0.82rem;
} }
.config-table-wrapper {
max-height: 28rem;
overflow: auto;
border: 1px solid var(--pico-muted-border-color, #d6d9dd);
border-radius: 0.5rem;
}
.config-table-wrapper table {
margin: 0;
}
#configTable {
width: 100%;
}
#configTable td:first-child {
white-space: nowrap;
vertical-align: top;
}
.config-value {
display: inline-block;
max-width: 42rem;
white-space: pre-wrap;
overflow-wrap: anywhere;
font-size: 0.82rem;
}
dialog article { dialog article {
max-width: 600px; max-width: 600px;
width: min(90vw, 600px); width: min(90vw, 600px);
+46
View File
@@ -1002,6 +1002,52 @@ dialog.group-streets-dialog.is-dragging article header {
/* Leaflet setzt role="button"; Pico würde sonst Button-Padding und Zeilenhöhe /* Leaflet setzt role="button"; Pico würde sonst Button-Padding und Zeilenhöhe
anwenden und den Marker gegenüber der gesetzten Position verschieben. */ anwenden und den Marker gegenüber der gesetzten Position verschieben. */
.group-position-share {
text-align: center;
}
.group-position-share-title {
font-weight: 600;
font-size: 0.95rem;
}
.group-position-share-coords {
margin-top: 0.15rem;
font-size: 0.78rem;
opacity: 0.75;
font-variant-numeric: tabular-nums;
}
.group-position-share-qr {
display: block;
width: 200px;
height: 200px;
max-width: 100%;
margin: 0.55rem auto 0.25rem;
image-rendering: pixelated;
background: #fff;
}
.group-position-share-links {
font-size: 0.8rem;
line-height: 1.5;
}
.group-position-share-links a {
color: var(--primary, #2f6fdb);
}
html[data-theme="dark"] .leaflet-popup-content-wrapper,
html[data-theme="dark"] .leaflet-popup-tip {
background: #141e26;
color: var(--color, #c8d1d8);
box-shadow: 0 1px 8px rgba(0, 0, 0, 0.6);
}
html[data-theme="dark"] .group-position-share-links a {
color: var(--primary, #35b9e0);
}
.group-marker-icon { .group-marker-icon {
display: flex; display: flex;
align-items: center; align-items: center;
+11
View File
@@ -274,6 +274,17 @@ html[data-theme="dark"] .mobile-ws-status.is-error {
background: rgba(153, 27, 27, 0.96); background: rgba(153, 27, 27, 0.96);
} }
.firebase-debug-payload {
max-height: 16rem;
overflow: auto;
padding: 0.6rem;
border-radius: 0.45rem;
background: rgba(15, 23, 42, 0.06);
font-size: 0.75rem;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.mobile-work-btn { .mobile-work-btn {
position: absolute; position: absolute;
left: 50%; left: 50%;
+1 -1
View File
@@ -5,7 +5,7 @@
* damit er sowohl die mobilen Views als auch die statischen Assets * damit er sowohl die mobilen Views als auch die statischen Assets
* kontrolliert. Der Cache-Name wird pro App-Wurzel gebildet. * kontrolliert. Der Cache-Name wird pro App-Wurzel gebildet.
*/ */
const VERSION = 'cmbnet-pwa-v23'; const VERSION = 'cmbnet-pwa-v24';
const BASE = new URL('./', self.location).href; const BASE = new URL('./', self.location).href;
const SHELL_CACHE = `${VERSION}-shell`; const SHELL_CACHE = `${VERSION}-shell`;
const TILE_CACHE = `${VERSION}-tiles`; const TILE_CACHE = `${VERSION}-tiles`;
+11
View File
@@ -85,5 +85,16 @@ if (createApiTokenBtn) {
createApiTokenBtn.addEventListener('click', createApiToken); createApiTokenBtn.addEventListener('click', createApiToken);
} }
const restoreBackupForm = document.getElementById('restoreBackupForm');
if (restoreBackupForm) {
restoreBackupForm.addEventListener('submit', event => {
const confirmed = confirm(
'Die aktuelle Datenbank wird vollständig durch das Backup ersetzt. '
+ 'Dabei gehen alle Änderungen seit dem Backup verloren. Fortfahren?'
);
if (!confirmed) event.preventDefault();
});
}
loadBrokerStatus(); loadBrokerStatus();
setInterval(loadBrokerStatus, 5000); setInterval(loadBrokerStatus, 5000);
+113 -1
View File
@@ -26,6 +26,9 @@ const DEFAULT_SETTINGS = {
const STREET_STATES = ['unbearbeitet', 'zugewiesen', 'erledigt']; const STREET_STATES = ['unbearbeitet', 'zugewiesen', 'erledigt'];
const GROUP_STATES = ['offen', 'unterwegs', 'online', 'pausierend', 'fertig']; const GROUP_STATES = ['offen', 'unterwegs', 'online', 'pausierend', 'fertig'];
const GROUP_MARKER_MAX_AGE_SECONDS = 30 * 60; const GROUP_MARKER_MAX_AGE_SECONDS = 30 * 60;
const GROUP_POSITION_ZOOM_DEFAULT = 18;
const GROUP_POSITION_ZOOM_MIN = 1;
const GROUP_POSITION_ZOOM_MAX = 22;
const GROUP_STREET_HOVER_COLOR = '#f5c518'; const GROUP_STREET_HOVER_COLOR = '#f5c518';
const STREET_COLORS = { const STREET_COLORS = {
unbearbeitet: '#1f6feb', unbearbeitet: '#1f6feb',
@@ -1417,10 +1420,119 @@ async function saveGroupAssignments() {
} }
} }
function groupPositionZoomLevel() {
const configured = Number(window.CMBNET_GROUP_POSITION_ZOOM);
if (!Number.isFinite(configured)) return GROUP_POSITION_ZOOM_DEFAULT;
return Math.min(
GROUP_POSITION_ZOOM_MAX,
Math.max(GROUP_POSITION_ZOOM_MIN, Math.round(configured))
);
}
function buildGroupPositionShare(group) {
const lat = Number(group.last_lat);
const lon = Number(group.last_lon);
const mapsUrl = `https://www.google.com/maps?q=${lat.toFixed(6)},${lon.toFixed(6)}`;
const text = `Position von ${groupDisplayName(group)}: ${mapsUrl}`;
return {
lat,
lon,
mapsUrl,
whatsappUrl: `https://api.whatsapp.com/send?text=${encodeURIComponent(text)}`
};
}
function openGroupPositionSharePopup(group) {
let marker = dispatcherState.markersByGroupId.get(Number(group.id));
if (!marker) {
marker = createGroupMarker(group, [
Number(group.last_lat),
Number(group.last_lon)
]);
}
if (!marker) return;
const share = buildGroupPositionShare(group);
const container = document.createElement('div');
container.className = 'group-position-share';
const title = document.createElement('div');
title.className = 'group-position-share-title';
title.textContent = groupDisplayName(group);
const coordinates = document.createElement('div');
coordinates.className = 'group-position-share-coords';
coordinates.textContent = `${share.lat.toFixed(5)}, ${share.lon.toFixed(5)}`;
const canvas = document.createElement('canvas');
canvas.className = 'group-position-share-qr';
canvas.width = 200;
canvas.height = 200;
canvas.setAttribute(
'aria-label',
`QR-Code zum Teilen der Position von ${groupDisplayName(group)} über WhatsApp`
);
let qrRendered = false;
if (typeof QRious !== 'undefined') {
try {
new QRious({
element: canvas,
value: share.whatsappUrl,
size: 200,
level: 'M'
});
qrRendered = true;
} catch (error) {
console.error('QRious error', error);
}
}
const links = document.createElement('div');
links.className = 'group-position-share-links';
const whatsappLink = document.createElement('a');
whatsappLink.href = share.whatsappUrl;
whatsappLink.target = '_blank';
whatsappLink.rel = 'noopener';
whatsappLink.textContent = 'Per WhatsApp teilen';
const separator = document.createTextNode(' · ');
const mapsLink = document.createElement('a');
mapsLink.href = share.mapsUrl;
mapsLink.target = '_blank';
mapsLink.rel = 'noopener';
mapsLink.textContent = 'Kartenlink';
links.append(whatsappLink, separator, mapsLink);
container.append(title, coordinates);
if (qrRendered) {
container.appendChild(canvas);
} else {
const fallback = document.createElement('p');
fallback.textContent = 'QR-Code nicht verfügbar.';
container.appendChild(fallback);
}
container.appendChild(links);
marker.bindPopup(container, {
className: 'group-position-share-popup',
minWidth: 210,
maxWidth: 250,
autoClose: false,
closeOnClick: false,
closeButton: true,
offset: [0, -6]
});
marker.openPopup();
}
function locateGroup(groupId) { function locateGroup(groupId) {
const group = dispatcherState.groupById.get(Number(groupId)); const group = dispatcherState.groupById.get(Number(groupId));
if (!group || !hasPosition(group)) return; if (!group || !hasPosition(group)) return;
map.setView([Number(group.last_lat), Number(group.last_lon)], 15); map.setView(
[Number(group.last_lat), Number(group.last_lon)],
groupPositionZoomLevel()
);
openGroupPositionSharePopup(group);
} }
function toggleCrosshair(groupId) { function toggleCrosshair(groupId) {
+68 -3
View File
@@ -19,7 +19,9 @@ const DEFAULT_SETTINGS = {
opacity: 0.7, opacity: 0.7,
weight: 20, weight: 20,
baseLayer: 'osm', baseLayer: 'osm',
autoSendPosition: true // Die automatische Übertragung der Eigenposition ist bewusst opt-in.
// Bestehende gespeicherte Einstellungen bleiben unverändert.
autoSendPosition: false
}; };
const AUTO_POSITION_INTERVAL_MS = 30000; const AUTO_POSITION_INTERVAL_MS = 30000;
@@ -386,6 +388,9 @@ async function initFirebasePush(registration = null, force = false) {
&& payload.data.reason && payload.data.reason
? payload.data.reason ? payload.data.reason
: 'wake'; : 'wake';
// Debugging: Jede im Vordergrund empfangene Firebase-Nachricht
// wird sichtbar angezeigt, bevor die Synchronisierung läuft.
showFirebaseDebugPopup(reason, payload);
handlePushWake(reason); handlePushWake(reason);
}); });
} }
@@ -438,10 +443,70 @@ function initPushWakeListener() {
navigator.serviceWorker.addEventListener('message', event => { navigator.serviceWorker.addEventListener('message', event => {
if (!event.data || event.data.type !== 'cmbnet-wake') return; if (!event.data || event.data.type !== 'cmbnet-wake') return;
const port = event.ports && event.ports[0]; const port = event.ports && event.ports[0];
handlePushWake(event.data.reason || 'wake', port); const reason = event.data.reason || 'wake';
// Ein Klick auf eine Benachrichtigung ist kein neuer Firebase-Empfang.
if (reason !== 'notification') {
showFirebaseDebugPopup(reason, event.data);
}
handlePushWake(reason, port);
}); });
} }
function showFirebaseDebugPopup(reason, payload) {
let dialog = document.getElementById('firebaseDebugDialog');
if (!dialog) {
dialog = document.createElement('dialog');
dialog.id = 'firebaseDebugDialog';
dialog.setAttribute('aria-labelledby', 'firebaseDebugTitle');
const article = document.createElement('article');
const header = document.createElement('header');
const title = document.createElement('h3');
title.id = 'firebaseDebugTitle';
title.textContent = 'Firebase-Nachricht';
header.appendChild(title);
const body = document.createElement('div');
body.className = 'dialog-body';
const reasonEl = document.createElement('p');
reasonEl.id = 'firebaseDebugReason';
const payloadEl = document.createElement('pre');
payloadEl.id = 'firebaseDebugPayload';
payloadEl.className = 'firebase-debug-payload';
body.append(reasonEl, payloadEl);
const footer = document.createElement('footer');
const closeButton = document.createElement('button');
closeButton.type = 'button';
closeButton.className = 'secondary';
closeButton.textContent = 'Schließen';
closeButton.addEventListener('click', () => dialog.close());
footer.appendChild(closeButton);
article.append(header, body, footer);
dialog.appendChild(article);
document.body.appendChild(dialog);
}
const reasonEl = dialog.querySelector('#firebaseDebugReason');
const payloadEl = dialog.querySelector('#firebaseDebugPayload');
if (reasonEl) reasonEl.textContent = `Grund: ${reason || 'wake'}`;
if (payloadEl) {
let text = '';
try {
text = payload ? JSON.stringify(payload, null, 2) : '';
} catch (error) {
text = String(payload || '');
}
payloadEl.textContent = text;
}
if (!dialog.open) {
if (typeof dialog.showModal === 'function') dialog.showModal();
else if (typeof dialog.show === 'function') dialog.show();
}
}
function waitForWsAuthentication(timeoutMs = PUSH_WAKE_AUTH_TIMEOUT_MS) { function waitForWsAuthentication(timeoutMs = PUSH_WAKE_AUTH_TIMEOUT_MS) {
if (state.authenticated) return Promise.resolve(true); if (state.authenticated) return Promise.resolve(true);
return new Promise(resolve => { return new Promise(resolve => {
@@ -586,7 +651,7 @@ function loadSettings() {
state.settings.opacity = typeof saved.opacity === 'number' ? saved.opacity : DEFAULT_SETTINGS.opacity; state.settings.opacity = typeof saved.opacity === 'number' ? saved.opacity : DEFAULT_SETTINGS.opacity;
state.settings.weight = typeof saved.weight === 'number' ? saved.weight : DEFAULT_SETTINGS.weight; state.settings.weight = typeof saved.weight === 'number' ? saved.weight : DEFAULT_SETTINGS.weight;
state.settings.baseLayer = saved.baseLayer === 'aerial' ? 'aerial' : 'osm'; state.settings.baseLayer = saved.baseLayer === 'aerial' ? 'aerial' : 'osm';
state.settings.autoSendPosition = saved.autoSendPosition !== false; state.settings.autoSendPosition = saved.autoSendPosition === true;
} }
} catch(e) {} } catch(e) {}
} }
+58
View File
@@ -13,6 +13,64 @@
</ul> </ul>
</nav> </nav>
<section>
<h2>Datenbank-Backup</h2>
<p>
Das Backup enthält eine vollständige, konsistente Kopie der
SQLite-Datenbank. Es kann später über die Schaltfläche unten wieder
eingespielt werden. Während der Wiederherstellung sollten keine
anderen Benutzer aktiv arbeiten.
</p>
<p>
<a href="{{ url_for('admin_backup.download_backup', tenant=session.tenant_code) }}"
role="button">Backup herunterladen</a>
</p>
<form id="restoreBackupForm" method="post" enctype="multipart/form-data"
action="{{ url_for('admin_backup.restore_backup', tenant=session.tenant_code) }}">
<label for="backupFile">Backup-Datei auswählen</label>
<input type="file" id="backupFile" name="backup"
accept=".sqlite3,.sqlite,.db,application/vnd.sqlite3" required>
<button type="submit" class="secondary">Backup wiederherstellen</button>
</form>
<p>
<small>
Die Wiederherstellung ersetzt alle aktuellen Daten durch den
Inhalt der Backup-Datei. Die Datei wird vor dem Einspielen auf
Integrität und das CMBNet-Grundschema geprüft.
</small>
</p>
</section>
<section>
<h2>Konfiguration</h2>
<p>
Alle Konfigurationsparameter als Key:Value-Liste. Geheimnisse wie
<code>SECRET_KEY</code> und Service-Account-Inhalte werden maskiert.
</p>
<p>
<a href="{{ url_for('admin_backup.export_config', tenant=session.tenant_code) }}"
role="button" class="secondary">Konfiguration herunterladen</a>
</p>
<div class="config-table-wrapper">
<table id="configTable">
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for key, value in config_items %}
<tr>
<td><code>{{ key }}</code></td>
<td><code class="config-value">{{ value }}</code></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</section>
<section> <section>
<h2>API-Zugriffstoken</h2> <h2>API-Zugriffstoken</h2>
<p> <p>
+1
View File
@@ -318,6 +318,7 @@
window.CMBNET_TENANT = {{ session.tenant_code|tojson }}; window.CMBNET_TENANT = {{ session.tenant_code|tojson }};
window.CMBNET_ACCOUNT_ID = {{ session.account_id|tojson }}; window.CMBNET_ACCOUNT_ID = {{ session.account_id|tojson }};
window.CMBNET_LOGOUT_URL = {{ url_for('auth.logout', tenant=session.tenant_code)|tojson }}; window.CMBNET_LOGOUT_URL = {{ url_for('auth.logout', tenant=session.tenant_code)|tojson }};
window.CMBNET_GROUP_POSITION_ZOOM = {{ config.GROUP_POSITION_ZOOM|tojson }};
</script> </script>
<script src="{{ url_for('static', filename='js/qrious.min.js') }}"></script> <script src="{{ url_for('static', filename='js/qrious.min.js') }}"></script>
<script src="{{ url_for('static', filename=str2pl_asset()) }}?v={{ str2pl_asset_version() }}"></script> <script src="{{ url_for('static', filename=str2pl_asset()) }}?v={{ str2pl_asset_version() }}"></script>
+1 -1
View File
@@ -124,7 +124,7 @@
<div class="mobile-settings-row"> <div class="mobile-settings-row">
<span>Eigenposition automatisch senden</span> <span>Eigenposition automatisch senden</span>
<input type="checkbox" id="mobileAutoPositionToggle" role="switch" <input type="checkbox" id="mobileAutoPositionToggle" role="switch"
aria-label="Eigenposition automatisch senden" checked> aria-label="Eigenposition automatisch senden">
</div> </div>
<p class="mobile-dialog-hint"> <p class="mobile-dialog-hint">
Ist die automatische Versendung deaktiviert, kann die Position Ist die automatische Versendung deaktiviert, kann die Position