Mobile Views jetzt als PWA

This commit is contained in:
concierge committed 2026-10-29 08:08:23 +01:00
1 parent d8692ab20e
commit b41c3bc3a6
11 files changed
+785 -37

No files matched your search

+12
View File
@@ -96,6 +96,18 @@ def create_app(config_name=None):
app.static_folder, 'favicon.ico', mimetype='image/vnd.microsoft.icon' app.static_folder, 'favicon.ico', mimetype='image/vnd.microsoft.icon'
) )
# Service Worker für die PWA. Er wird bewusst an der App-Wurzel
# ausgeliefert, damit er auch die statischen Assets unter /static
# kontrollieren kann. Der Pfad berücksichtigt ein gesetztes SCRIPT_NAME
# (Reverse-Proxy-Prefix) automatisch.
@app.route('/sw.js')
def service_worker():
response = send_from_directory(
app.static_folder, 'js/sw.js', mimetype='application/javascript'
)
response.headers['Cache-Control'] = 'no-cache'
return response
# Root redirect # Root redirect
@app.route('/') @app.route('/')
def index(): def index():
+66 -1
View File
@@ -1,7 +1,10 @@
""" """
Haupt-Views Haupt-Views
""" """
from flask import Blueprint, render_template, g, redirect, url_for, request from flask import (
Blueprint, render_template, g, redirect, url_for, request, jsonify,
make_response, session
)
from cmbnet.auth import login_required, role_required from cmbnet.auth import login_required, role_required
views_bp = Blueprint('views', __name__) views_bp = Blueprint('views', __name__)
@@ -57,6 +60,68 @@ def gruppen(**kwargs):
return render_template('gruppen.html') return render_template('gruppen.html')
@views_bp.route('/manifest.webmanifest')
def manifest(tenant=None, **kwargs):
"""Liefert das Web-App-Manifest für die mobilen Views."""
account = getattr(g, 'current_account', None)
role = account['role'] if account else session.get('role')
if role == 'Dispatcher':
start_url = url_for('views.dispatcher_mobil', tenant=tenant)
name = 'CMBNet Dispatcher'
short_name = 'CMB Dispo'
elif role == 'Gruppe':
start_url = url_for('views.gruppen', tenant=tenant)
name = 'CMBNet Gruppe'
short_name = 'CMB Gruppe'
else:
start_url = url_for('views.index', tenant=tenant)
name = 'CMBNet'
short_name = 'CMBNet'
icon_192 = url_for('static', filename='img/icon-192.png')
icon_512 = url_for('static', filename='img/icon-512.png')
payload = {
'id': start_url,
'name': name,
'short_name': short_name,
'description': 'CMBNet – mobile Einsatzansicht',
'lang': 'de',
'start_url': start_url,
'scope': url_for('views.index', tenant=tenant),
'display': 'standalone',
'display_override': ['standalone', 'minimal-ui'],
'background_color': '#f7f9fc',
'theme_color': '#2563eb',
'icons': [
{
'src': icon_192,
'sizes': '192x192',
'type': 'image/png',
'purpose': 'any'
},
{
'src': icon_512,
'sizes': '512x512',
'type': 'image/png',
'purpose': 'any'
},
{
'src': icon_512,
'sizes': '512x512',
'type': 'image/png',
'purpose': 'maskable'
}
]
}
response = make_response(jsonify(payload))
response.headers['Content-Type'] = 'application/manifest+json'
response.headers['Cache-Control'] = 'no-cache'
return response
@views_bp.route('/praesentation') @views_bp.route('/praesentation')
@login_required @login_required
def praesentation(**kwargs): def praesentation(**kwargs):
+48 -6
View File
@@ -25,6 +25,17 @@ body.mobile-page {
background: var(--mobile-bg); background: var(--mobile-bg);
color: var(--mobile-text); color: var(--mobile-text);
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif; font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
overflow: hidden;
overscroll-behavior: none;
}
/* Die Basis-Template-Hülle (main.container) darf bei den mobilen Views
keinen Rand und keine Innenabstände belegen. */
body.mobile-page main.container {
width: 100%;
max-width: none;
margin: 0;
padding: 0;
} }
.mobile-app { .mobile-app {
@@ -39,6 +50,7 @@ body.mobile-page {
background: var(--mobile-card); background: var(--mobile-card);
border-bottom: 1px solid var(--mobile-border); border-bottom: 1px solid var(--mobile-border);
padding: 0.4rem 0.6rem; padding: 0.4rem 0.6rem;
padding-top: calc(0.4rem + env(safe-area-inset-top));
} }
.mobile-header-row { .mobile-header-row {
@@ -132,7 +144,7 @@ body.mobile-page {
.mobile-fab { .mobile-fab {
position: absolute; position: absolute;
right: 0.7rem; right: 0.7rem;
bottom: 5.5rem; bottom: calc(5.5rem + env(safe-area-inset-bottom));
width: 3rem; width: 3rem;
height: 3rem; height: 3rem;
border-radius: 50%; border-radius: 50%;
@@ -149,7 +161,7 @@ body.mobile-page {
} }
.mobile-fab-secondary { .mobile-fab-secondary {
bottom: 9rem; bottom: calc(9rem + env(safe-area-inset-bottom));
background: var(--mobile-card); background: var(--mobile-card);
color: var(--mobile-text); color: var(--mobile-text);
border: 1px solid var(--mobile-border); border: 1px solid var(--mobile-border);
@@ -160,7 +172,7 @@ body.mobile-page {
position: absolute; position: absolute;
left: 50%; left: 50%;
transform: translateX(-50%); transform: translateX(-50%);
bottom: 1rem; bottom: calc(1rem + env(safe-area-inset-bottom));
border-radius: 999px; border-radius: 999px;
background: var(--mobile-card); background: var(--mobile-card);
color: var(--mobile-text); color: var(--mobile-text);
@@ -219,6 +231,7 @@ html[data-theme="dark"] .mobile-chat-card.own {
display: flex; display: flex;
gap: 0.4rem; gap: 0.4rem;
padding: 0.5rem 0.6rem; padding: 0.5rem 0.6rem;
padding-bottom: calc(0.5rem + env(safe-area-inset-bottom));
background: var(--mobile-card); background: var(--mobile-card);
border-top: 1px solid var(--mobile-border); border-top: 1px solid var(--mobile-border);
} }
@@ -270,6 +283,28 @@ html[data-theme="dark"] .mobile-chat-card.own {
font-size: 0.85rem; font-size: 0.85rem;
} }
.mobile-settings-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.6rem;
margin-bottom: 0.6rem;
}
.mobile-settings-button {
width: auto;
margin: 0;
padding: 0.35rem 0.8rem;
border-radius: 999px;
font-size: 0.85rem;
}
.mobile-settings-button.is-active {
background: var(--mobile-accent);
border-color: var(--mobile-accent);
color: #fff;
}
.mobile-user-marker { .mobile-user-marker {
position: relative; position: relative;
width: 16px; width: 16px;
@@ -315,12 +350,19 @@ html[data-theme="dark"] .mobile-chat-card.own {
@media (max-width: 420px) { @media (max-width: 420px) {
.mobile-work-btn { .mobile-work-btn {
bottom: 0.8rem; bottom: calc(0.8rem + env(safe-area-inset-bottom));
} }
.mobile-fab { .mobile-fab {
bottom: 5.2rem; bottom: calc(5.2rem + env(safe-area-inset-bottom));
} }
.mobile-fab-secondary { .mobile-fab-secondary {
bottom: 8.6rem; bottom: calc(8.6rem + env(safe-area-inset-bottom));
}
}
/* Im installierten Standalone-Modus keine Browserleisten berücksichtigen. */
@media (display-mode: standalone) {
body.mobile-page {
height: 100dvh;
} }
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

+257
View File
@@ -0,0 +1,257 @@
/*
* CMBNet Service Worker
*
* Wird an der App-Wurzel ausgeliefert (z. B. /sw.js oder /cmbnet/sw.js),
* damit er sowohl die mobilen Views als auch die statischen Assets
* kontrolliert. Der Cache-Name wird pro App-Wurzel gebildet.
*/
const VERSION = 'cmbnet-pwa-v1';
const BASE = new URL('./', self.location).href;
const SHELL_CACHE = `${VERSION}-shell`;
const TILE_CACHE = `${VERSION}-tiles`;
const MAX_TILES = 400;
const PRECACHE_PATHS = [
'static/css/pico.min.css',
'static/css/leaflet.css',
'static/css/style.css',
'static/css/admin.css',
'static/css/mobile.css',
'static/js/leaflet.js',
'static/js/str2pl.js',
'static/js/views/mobile.js',
'static/img/logo.png',
'static/img/icon-192.png',
'static/img/icon-512.png',
'static/img/apple-touch-icon.png',
'favicon.ico'
];
const PRECACHE_URLS = PRECACHE_PATHS.map(path => new URL(path, BASE).href);
const TILE_HOSTS = new Set([
'tile.openstreetmap.org',
'a.tile.openstreetmap.org',
'b.tile.openstreetmap.org',
'c.tile.openstreetmap.org',
'server.arcgisonline.com',
'services.arcgisonline.com'
]);
/* ------------------------------------------------------------------ */
/* Installation und Aktivierung */
/* ------------------------------------------------------------------ */
self.addEventListener('install', event => {
event.waitUntil((async () => {
const cache = await caches.open(SHELL_CACHE);
await Promise.allSettled(
PRECACHE_URLS.map(async url => {
try {
const response = await fetch(new Request(url, {cache: 'reload'}));
if (response && (response.ok || response.type === 'opaque')) {
await cache.put(url, response);
}
} catch (error) {
// Einzelne fehlende Assets dürfen die Installation nicht
// verhindern.
}
})
);
await self.skipWaiting();
})());
});
self.addEventListener('activate', event => {
event.waitUntil((async () => {
const keys = await caches.keys();
await Promise.all(
keys
.filter(key => key !== SHELL_CACHE && key !== TILE_CACHE)
.map(key => caches.delete(key))
);
await self.clients.claim();
})());
});
self.addEventListener('message', event => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
/* ------------------------------------------------------------------ */
/* Fetch-Strategien */
/* ------------------------------------------------------------------ */
self.addEventListener('fetch', event => {
const request = event.request;
if (request.method !== 'GET') return;
const url = new URL(request.url);
// API- und WebSocket-Aufrufe nie cachen.
if (url.pathname.includes('/api/') || url.pathname.includes('/ws')) {
return;
}
// Das Manifest wird immer frisch vom Server geladen.
if (url.pathname.endsWith('/manifest.webmanifest')) {
return;
}
if (isTileRequest(url)) {
event.respondWith(handleTile(request));
return;
}
if (request.mode === 'navigate') {
event.respondWith(handleNavigation(request));
return;
}
if (url.origin === self.location.origin) {
event.respondWith(handleAsset(request));
}
});
function isTileRequest(url) {
if (TILE_HOSTS.has(url.hostname)) return true;
return /\/tile\/\d+\/\d+\/\d+/.test(url.pathname)
|| /\/MapServer\/tile\//.test(url.pathname);
}
async function handleNavigation(request) {
const cache = await caches.open(SHELL_CACHE);
try {
const response = await fetch(request);
if (response && response.ok) {
cache.put(request, response.clone()).catch(() => {});
}
return response;
} catch (error) {
const cached = await cache.match(request, {ignoreSearch: true});
if (cached) return cached;
return new Response(offlineHtml(), {
status: 503,
headers: {'Content-Type': 'text/html; charset=utf-8'}
});
}
}
async function handleAsset(request) {
const cache = await caches.open(SHELL_CACHE);
const cached = await cache.match(request);
const network = fetch(request)
.then(response => {
if (response && (response.ok || response.type === 'opaque')) {
cache.put(request, response.clone()).catch(() => {});
}
return response;
})
.catch(() => null);
if (cached) {
// Im Hintergrund aktualisieren (stale-while-revalidate).
network.catch(() => {});
return cached;
}
const response = await network;
if (response) return response;
return new Response('', {
status: 504,
statusText: 'Offline'
});
}
async function handleTile(request) {
const cache = await caches.open(TILE_CACHE);
const cached = await cache.match(request);
if (cached) return cached;
try {
const response = await fetch(request);
if (response && (response.ok || response.type === 'opaque')) {
await cache.put(request, response.clone());
trimTileCache(cache);
}
return response;
} catch (error) {
return new Response('', {
status: 504,
statusText: 'Offline'
});
}
}
async function trimTileCache(cache) {
try {
const keys = await cache.keys();
if (keys.length <= MAX_TILES) return;
const excess = keys.length - MAX_TILES;
for (let i = 0; i < excess; i += 1) {
await cache.delete(keys[i]);
}
} catch (error) {
// Cache-Bereinigung ist optional.
}
}
function offlineHtml() {
return `<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CMBNet – offline</title>
<style>
body{font-family:system-ui,-apple-system,sans-serif;margin:0;min-height:100dvh;
display:flex;align-items:center;justify-content:center;background:#f7f9fc;color:#1f2937}
main{max-width:22rem;padding:2rem;text-align:center}
h1{font-size:1.2rem;margin:0 0 .5rem}
p{margin:0;color:#4b5563;font-size:.95rem}
</style>
</head>
<body>
<main>
<h1>Keine Verbindung</h1>
<p>CMBNet ist offline nicht erreichbar. Bitte prüfe die Netzwerkverbindung und lade die Seite erneut.</p>
</main>
</body>
</html>`;
}
/* ------------------------------------------------------------------ */
/* Benachrichtigungen */
/* ------------------------------------------------------------------ */
self.addEventListener('notificationclick', event => {
event.notification.close();
const target = event.notification.data && event.notification.data.url
? event.notification.data.url
: BASE;
event.waitUntil((async () => {
const clientList = await self.clients.matchAll({
type: 'window',
includeUncontrolled: true
});
for (const client of clientList) {
if (client.url.startsWith(BASE) && 'focus' in client) {
return client.focus();
}
}
if (self.clients.openWindow) {
return self.clients.openWindow(target);
}
return null;
})());
});
+349 -30
View File
@@ -28,6 +28,9 @@ const state = {
streetById: new Map(), streetById: new Map(),
groups: [], groups: [],
groupById: new Map(), groupById: new Map(),
accounts: [],
accountById: new Map(),
me: null,
currentGroupId: null, currentGroupId: null,
polylinesByStreetId: new Map(), polylinesByStreetId: new Map(),
groupMarkers: new Map(), groupMarkers: new Map(),
@@ -55,12 +58,22 @@ async function initMobile() {
initMap(); initMap();
bindTabs(); bindTabs();
bindButtons(); bindButtons();
registerServiceWorker();
initPwaInstall();
initNotifications();
if (viewMode === 'mobile_dispatcher') { if (viewMode === 'mobile_dispatcher') {
try { try {
const groups = await fetchJson(`${apiBase}/init/groups`); const [groups, accounts, me] = await Promise.all([
fetchJson(`${apiBase}/init/groups`),
fetchJson(`${apiBase}/init/accounts`).catch(() => []),
fetchJson(`${apiBase}/init/me`).catch(() => null)
]);
state.groups = Array.isArray(groups) ? groups : []; state.groups = Array.isArray(groups) ? groups : [];
state.accounts = Array.isArray(accounts) ? accounts : [];
state.me = me;
indexGroups(); indexGroups();
indexAccounts();
buildGroupSelect(); buildGroupSelect();
const firstGroup = state.groups[0]; const firstGroup = state.groups[0];
if (firstGroup) { if (firstGroup) {
@@ -71,13 +84,20 @@ async function initMobile() {
} }
} else if (viewMode === 'mobile_group') { } else if (viewMode === 'mobile_group') {
try { try {
const group = await fetchJson(`${apiBase}/groups/me`); const [group, accounts, me] = await Promise.all([
fetchJson(`${apiBase}/groups/me`),
fetchJson(`${apiBase}/init/accounts`).catch(() => []),
fetchJson(`${apiBase}/init/me`).catch(() => null)
]);
state.accounts = Array.isArray(accounts) ? accounts : [];
state.me = me;
indexAccounts();
if (group && group.id) { if (group && group.id) {
state.groups = [group]; state.groups = [group];
state.currentGroupId = group.id; state.currentGroupId = group.id;
indexGroups(); indexGroups();
const nameEl = document.getElementById('groupNameDisplay'); const nameEl = document.getElementById('groupNameDisplay');
if (nameEl) nameEl.textContent = group.aliasname || group.id || 'Gruppe'; if (nameEl) nameEl.textContent = groupDisplayName(group);
await loadGroupData(group.id); await loadGroupData(group.id);
} }
} catch (e) { } catch (e) {
@@ -102,6 +122,143 @@ function fetchJson(url, options={}) {
}); });
} }
/* ------------------------------------------------------------------ */
/* Progressive Web App */
/* ------------------------------------------------------------------ */
let deferredInstallPrompt = null;
function isStandaloneMode() {
return window.matchMedia('(display-mode: standalone)').matches
|| window.navigator.standalone === true;
}
function isIosDevice() {
return /iphone|ipad|ipod/i.test(navigator.userAgent)
|| (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
}
function registerServiceWorker() {
if (!('serviceWorker' in navigator)) return;
const swUrl = window.CMBNET_SW_URL || '/sw.js';
window.addEventListener('load', () => {
navigator.serviceWorker.register(swUrl).catch(error => {
console.warn('Service Worker konnte nicht registriert werden.', error);
});
});
}
function initPwaInstall() {
const button = document.getElementById('mobileInstallBtn');
if (!button) return;
if (isStandaloneMode()) {
button.hidden = true;
return;
}
// Unter iOS gibt es kein beforeinstallprompt. Dort zeigen wir den Button
// dauerhaft an und erklären die Installation über das Teilen-Menü.
if (isIosDevice()) button.hidden = false;
window.addEventListener('beforeinstallprompt', event => {
event.preventDefault();
deferredInstallPrompt = event;
button.hidden = false;
});
window.addEventListener('appinstalled', () => {
deferredInstallPrompt = null;
button.hidden = true;
});
button.addEventListener('click', async () => {
if (deferredInstallPrompt) {
const prompt = deferredInstallPrompt;
deferredInstallPrompt = null;
prompt.prompt();
try {
const choice = await prompt.userChoice;
if (choice.outcome === 'accepted') button.hidden = true;
} catch (error) {
// Der Dialog kann abgelehnt oder geschlossen werden.
}
return;
}
const dialog = document.getElementById('mobileInstallDialog');
const iosHint = document.getElementById('mobileInstallIosHint');
const genericHint = document.getElementById('mobileInstallGenericHint');
if (iosHint) iosHint.hidden = !isIosDevice();
if (genericHint) genericHint.hidden = isIosDevice();
if (dialog && typeof dialog.showModal === 'function') {
dialog.showModal();
} else if (dialog) {
dialog.show();
}
});
}
function closeMobileInstall() {
const dialog = document.getElementById('mobileInstallDialog');
if (dialog && dialog.open) dialog.close();
}
function initNotifications() {
const button = document.getElementById('mobileNotifyBtn');
if (!button) return;
button.addEventListener('click', requestNotifications);
updateNotificationUi();
}
function updateNotificationUi() {
const button = document.getElementById('mobileNotifyBtn');
if (!button) return;
if (!('Notification' in window)) {
button.textContent = 'Nicht verfügbar';
button.disabled = true;
return;
}
const permission = Notification.permission;
button.classList.toggle('is-active', permission === 'granted');
button.disabled = permission === 'denied';
if (permission === 'granted') {
button.textContent = 'Aktiv';
} else if (permission === 'denied') {
button.textContent = 'Blockiert';
} else {
button.textContent = 'Aktivieren';
}
}
async function requestNotifications() {
if (!('Notification' in window)) return;
try {
const permission = await Notification.requestPermission();
updateNotificationUi();
if (permission === 'granted' && navigator.serviceWorker) {
const registration = await navigator.serviceWorker.getRegistration();
if (registration && registration.showNotification) {
await registration.showNotification('CMBNet', {
body: 'Benachrichtigungen sind aktiviert.',
icon: window.CMBNET_ICON_URL || undefined,
tag: 'cmbnet-permission'
});
}
}
} catch (error) {
console.warn('Benachrichtigungen konnten nicht aktiviert werden.', error);
}
}
function loadSettings() { function loadSettings() {
try { try {
const raw = localStorage.getItem(storageKey); const raw = localStorage.getItem(storageKey);
@@ -219,6 +376,130 @@ function indexGroups() {
}); });
} }
function indexAccounts() {
state.accountById.clear();
state.accounts.forEach(account => {
const id = Number(account.id);
if (!Number.isFinite(id)) return;
account.id = id;
state.accountById.set(id, account);
});
}
function groupDisplayName(group) {
if (!group) return 'Gruppe';
const alias = group.aliasname && String(group.aliasname).trim();
return alias || 'Gruppe';
}
function findGroupForAccount(accountId) {
const id = Number(accountId);
return state.groups.find(group => Number(group.account_id) === id) || null;
}
/**
* Formatiert "Accountname" bzw. "Accountname (Gruppe: Alias)".
*/
function formatPersonName(name, role, groupAlias) {
const base = String(name || '').trim() || 'Unbekannt';
const alias = groupAlias && String(groupAlias).trim();
if (alias) return `${base} (Gruppe: ${alias})`;
if (role === 'Gruppe') return `${base} (Gruppe)`;
return base;
}
function getAccount(accountId) {
const id = Number(accountId);
if (!Number.isFinite(id)) return null;
return state.accountById.get(id) || null;
}
function getAccountDisplayName(accountId) {
const id = Number(accountId);
if (!Number.isFinite(id)) return null;
const account = getAccount(id);
if (account) {
const group = findGroupForAccount(id);
return formatPersonName(account.name, account.role, group ? group.aliasname : null);
}
if (state.me && Number(state.me.id) === id) {
const group = findGroupForAccount(id);
return formatPersonName(
state.me.name,
state.me.role,
group ? group.aliasname : null
);
}
return null;
}
function getSenderName(message, payload) {
const payloadSender = payload && typeof payload.sender === 'object'
? payload.sender
: null;
if (payloadSender && payloadSender.name) {
return formatPersonName(
payloadSender.name,
payloadSender.role,
payloadSender.group_alias
);
}
const senderId = Number(message.sender_id);
const known = getAccountDisplayName(senderId);
if (known) return known;
if (state.me && senderId === Number(state.me.id)) {
return formatPersonName(state.me.name, state.me.role, null);
}
return 'Unbekannt';
}
function getReceiverName(message, payload) {
const code = Number(message.code);
if (code === 1000 || (payload && payload.broadcast)) return 'alle';
const payloadSender = payload && typeof payload.sender === 'object'
? payload.sender
: null;
const senderRole = payloadSender?.role || getAccount(message.sender_id)?.role;
if (code === 2000 && senderRole === 'Gruppe') {
// Gruppen senden mit Code 2000 an Dispatcher und Beobachter.
return 'Dispatcher';
}
let receiverId = Number(message.receiver_id);
if (!Number.isFinite(receiverId) || receiverId <= 0) {
if (payload && payload.group_id !== undefined) {
receiverId = Number(payload.group_id);
} else if (payload && payload.receiver_id !== undefined) {
receiverId = Number(payload.receiver_id);
}
}
if (!Number.isFinite(receiverId) || receiverId <= 0) return 'alle';
let group = state.groupById.get(receiverId);
if (!group && receiverId === Number(state.currentGroupId) && state.groups.length) {
group = state.groups[0];
}
if (group) {
const accountName = getAccountDisplayName(group.account_id);
return accountName || groupDisplayName(group) || 'Gruppe';
}
const accountName = getAccountDisplayName(receiverId);
if (accountName) return accountName;
return 'Unbekannt';
}
function buildGroupSelect() { function buildGroupSelect() {
const sel = document.getElementById('mobileGroupSelect'); const sel = document.getElementById('mobileGroupSelect');
if (!sel) return; if (!sel) return;
@@ -599,7 +880,11 @@ function renderChat() {
meta.textContent = new Date(entry.ts).toLocaleString('de-DE'); meta.textContent = new Date(entry.ts).toLocaleString('de-DE');
const fromto = document.createElement('div'); const fromto = document.createElement('div');
fromto.className = 'mobile-chat-fromto'; fromto.className = 'mobile-chat-fromto';
fromto.textContent = entry.senderName || `ID ${entry.sender_id}`; const fromName = entry.fromName
|| getSenderName({sender_id: entry.sender_id}, null);
const toName = entry.toName
|| (Number(entry.code) === 1000 ? 'alle' : 'Unbekannt');
fromto.textContent = `${fromName} -> ${toName}`;
const text = document.createElement('div'); const text = document.createElement('div');
text.className = 'mobile-chat-text'; text.className = 'mobile-chat-text';
text.textContent = entry.text; text.textContent = entry.text;
@@ -625,12 +910,29 @@ function playSound() {
} catch(e) {} } catch(e) {}
} }
function showChatPopup(text) { async function showChatPopup(text, senderName) {
// Try to show notification if possible if (!('Notification' in window) || Notification.permission !== 'granted') return;
if ('Notification' in window && Notification.permission === 'granted') {
try { new Notification('CMBNet Nachricht', {body: text}); } catch(e) {} const options = {
} else if ('Notification' in window && Notification.permission !== 'denied') { body: text,
Notification.requestPermission(); icon: window.CMBNET_ICON_URL || undefined,
badge: window.CMBNET_ICON_URL || undefined,
tag: 'cmbnet-chat',
renotify: true,
data: {url: window.location.href}
};
try {
if (navigator.serviceWorker) {
const registration = await navigator.serviceWorker.getRegistration();
if (registration && registration.showNotification) {
await registration.showNotification(senderName || 'CMBNet', options);
return;
}
}
new Notification(senderName || 'CMBNet', options);
} catch (error) {
// Benachrichtigungen sind optional.
} }
} }
@@ -653,6 +955,23 @@ function extractText(msg) {
return String(msg); return String(msg);
} }
function parseMessagePayload(value) {
if (value && typeof value === 'object') return value;
if (typeof value !== 'string') return null;
try {
const parsed = JSON.parse(value);
return parsed && typeof parsed === 'object' ? parsed : null;
} catch (e) {
return null;
}
}
function normalizeTs(value) {
const number = Number(value);
if (!Number.isFinite(number) || number <= 0) return null;
return number < 1e12 ? number * 1000 : number;
}
function handleWs(event) { function handleWs(event) {
let message; let message;
try { message = JSON.parse(event.data); } catch(e) { return; } try { message = JSON.parse(event.data); } catch(e) { return; }
@@ -692,31 +1011,30 @@ function handleWs(event) {
} catch(e) {} } catch(e) {}
} else if (message.code === 2000 || message.code === 1000 || message.code === 1100) { } else if (message.code === 2000 || message.code === 1000 || message.code === 1100) {
// Chat messages // Chat messages
const text = extractText(message.msg); const payload = parseMessagePayload(message.msg);
const entry = { const text = extractText(payload ?? message.msg);
// Im Gruppen-View nur Nachrichten an alle oder an die eigene Gruppe.
if (viewMode === 'mobile_group') {
const gid = Number(payload?.group_id ?? message.receiver_id);
const ownGroupId = Number(state.currentGroupId);
if (Number.isFinite(gid) && gid > 0 && ownGroupId && gid !== ownGroupId) {
return;
}
}
addChatEntry({
sender_id: message.sender_id, sender_id: message.sender_id,
code: message.code, code: message.code,
ts: message.ts || Date.now(), ts: normalizeTs(message.ts) || Date.now(),
text, text,
senderName: undefined fromName: getSenderName(message, payload),
}; toName: getReceiverName(message, payload)
// For gruppe view, broker should only send relevant messages; still check });
if (viewMode === 'mobile_group') {
const p = typeof message.msg === 'string' ? JSON.parse(message.msg) : message.msg;
const gid = Number(p?.group_id || message.receiver_id);
if (message.code === 1100 && gid && gid !== state.currentGroupId) {
return; // should not happen if broker filters, but be safe
}
if (message.code === 2000 && gid && gid !== state.currentGroupId && message.sender_id !== currentAccountId) {
// Check if it's from our group
const isFromOurGroup = state.groups.some(g => g.account_id && false); // simplified
}
}
const wasEmpty = state.chatMessages.length === 0;
addChatEntry(entry);
if (Number(message.sender_id) !== currentAccountId) { if (Number(message.sender_id) !== currentAccountId) {
playSound(); playSound();
showChatPopup(text); showChatPopup(text, getSenderName(message, payload));
// Switch to chat tab // Switch to chat tab
document.querySelectorAll('.mobile-tab').forEach(b => { document.querySelectorAll('.mobile-tab').forEach(b => {
if (b.dataset.tab === 'chat') b.click(); if (b.dataset.tab === 'chat') b.click();
@@ -730,3 +1048,4 @@ window.closeMobileStreetSelect = closeMobileStreetSelect;
window.closeMobileStreetState = closeMobileStreetState; window.closeMobileStreetState = closeMobileStreetState;
window.saveMobileStreetState = saveMobileStreetState; window.saveMobileStreetState = saveMobileStreetState;
window.closeMobileSettings = closeMobileSettings; window.closeMobileSettings = closeMobileSettings;
window.closeMobileInstall = closeMobileInstall;
+21
View File
@@ -0,0 +1,21 @@
<dialog id="mobileInstallDialog">
<article>
<header>
<h3>App installieren</h3>
</header>
<div class="dialog-body">
<p>Installiere CMBNet als App auf dem Home-Bildschirm:</p>
<p class="mobile-dialog-hint" id="mobileInstallGenericHint">
Öffne das Browsermenü und wähle „App installieren“ bzw.
„Zum Home-Bildschirm hinzufügen“.
</p>
<p class="mobile-dialog-hint" id="mobileInstallIosHint" hidden>
iPhone/iPad (Safari): Teilen-Symbol antippen und
„Zum Home-Bildschirm“ wählen.
</p>
</div>
<footer>
<button type="button" onclick="closeMobileInstall()">Schließen</button>
</footer>
</article>
</dialog>
+16
View File
@@ -6,6 +6,13 @@
{% block head %} {% block head %}
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="manifest" href="{{ url_for('views.manifest', tenant=session.tenant_code) }}">
<meta name="theme-color" content="#2563eb">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<meta name="apple-mobile-web-app-title" content="CMBNet">
<link rel="apple-touch-icon" href="{{ url_for('static', filename='img/apple-touch-icon.png') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/pico.min.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='css/pico.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/leaflet.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='css/leaflet.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/mobile.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='css/mobile.css') }}">
@@ -18,6 +25,7 @@
<header class="mobile-header"> <header class="mobile-header">
<div class="mobile-header-row"> <div class="mobile-header-row">
<select id="mobileGroupSelect" class="mobile-group-select" aria-label="Gruppe auswählen"></select> <select id="mobileGroupSelect" class="mobile-group-select" aria-label="Gruppe auswählen"></select>
<button type="button" id="mobileInstallBtn" class="mobile-icon-btn" aria-label="App installieren" title="App installieren" hidden>📲</button>
<button type="button" id="mobileLogout" class="mobile-icon-btn" aria-label="Abmelden" title="Abmelden">⏻</button> <button type="button" id="mobileLogout" class="mobile-icon-btn" aria-label="Abmelden" title="Abmelden">⏻</button>
</div> </div>
</header> </header>
@@ -102,12 +110,17 @@
<option value="aerial">Luftbild</option> <option value="aerial">Luftbild</option>
</select> </select>
</label> </label>
<div class="mobile-settings-row">
<span>Benachrichtigungen</span>
<button type="button" id="mobileNotifyBtn" class="secondary mobile-settings-button">Aktivieren</button>
</div>
</div> </div>
<footer> <footer>
<button type="button" onclick="closeMobileSettings()">Schließen</button> <button type="button" onclick="closeMobileSettings()">Schließen</button>
</footer> </footer>
</article> </article>
</dialog> </dialog>
{% include "_pwa_install_dialog.html" %}
{% endblock %} {% endblock %}
{% block scripts %} {% block scripts %}
@@ -116,6 +129,9 @@
window.CMBNET_ACCOUNT_ID = {{ session.account_id|tojson }}; window.CMBNET_ACCOUNT_ID = {{ session.account_id|tojson }};
window.CMBNET_ROLE = {{ session.role|tojson }}; window.CMBNET_ROLE = {{ session.role|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_SW_URL = {{ url_for('service_worker')|tojson }};
window.CMBNET_MANIFEST_URL = {{ url_for('views.manifest', tenant=session.tenant_code)|tojson }};
window.CMBNET_ICON_URL = {{ url_for('static', filename='img/icon-192.png')|tojson }};
window.CMBNET_VIEW_MODE = 'mobile_dispatcher'; window.CMBNET_VIEW_MODE = 'mobile_dispatcher';
</script> </script>
<script src="{{ url_for('static', filename='js/leaflet.js') }}"></script> <script src="{{ url_for('static', filename='js/leaflet.js') }}"></script>
+16
View File
@@ -6,6 +6,13 @@
{% block head %} {% block head %}
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="manifest" href="{{ url_for('views.manifest', tenant=session.tenant_code) }}">
<meta name="theme-color" content="#2563eb">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<meta name="apple-mobile-web-app-title" content="CMBNet">
<link rel="apple-touch-icon" href="{{ url_for('static', filename='img/apple-touch-icon.png') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/pico.min.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='css/pico.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/leaflet.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='css/leaflet.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/mobile.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='css/mobile.css') }}">
@@ -18,6 +25,7 @@
<header class="mobile-header"> <header class="mobile-header">
<div class="mobile-header-row"> <div class="mobile-header-row">
<div class="mobile-group-name" id="groupNameDisplay">Gruppe</div> <div class="mobile-group-name" id="groupNameDisplay">Gruppe</div>
<button type="button" id="mobileInstallBtn" class="mobile-icon-btn" aria-label="App installieren" title="App installieren" hidden>📲</button>
<button type="button" id="mobileLogout" class="mobile-icon-btn" aria-label="Abmelden" title="Abmelden">⏻</button> <button type="button" id="mobileLogout" class="mobile-icon-btn" aria-label="Abmelden" title="Abmelden">⏻</button>
</div> </div>
</header> </header>
@@ -102,12 +110,17 @@
<option value="aerial">Luftbild</option> <option value="aerial">Luftbild</option>
</select> </select>
</label> </label>
<div class="mobile-settings-row">
<span>Benachrichtigungen</span>
<button type="button" id="mobileNotifyBtn" class="secondary mobile-settings-button">Aktivieren</button>
</div>
</div> </div>
<footer> <footer>
<button type="button" onclick="closeMobileSettings()">Schließen</button> <button type="button" onclick="closeMobileSettings()">Schließen</button>
</footer> </footer>
</article> </article>
</dialog> </dialog>
{% include "_pwa_install_dialog.html" %}
{% endblock %} {% endblock %}
{% block scripts %} {% block scripts %}
@@ -116,6 +129,9 @@
window.CMBNET_ACCOUNT_ID = {{ session.account_id|tojson }}; window.CMBNET_ACCOUNT_ID = {{ session.account_id|tojson }};
window.CMBNET_ROLE = {{ session.role|tojson }}; window.CMBNET_ROLE = {{ session.role|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_SW_URL = {{ url_for('service_worker')|tojson }};
window.CMBNET_MANIFEST_URL = {{ url_for('views.manifest', tenant=session.tenant_code)|tojson }};
window.CMBNET_ICON_URL = {{ url_for('static', filename='img/icon-192.png')|tojson }};
window.CMBNET_VIEW_MODE = 'mobile_group'; window.CMBNET_VIEW_MODE = 'mobile_group';
</script> </script>
<script src="{{ url_for('static', filename='js/leaflet.js') }}"></script> <script src="{{ url_for('static', filename='js/leaflet.js') }}"></script>