bug fix für Nachrichtenversand vom mobilen Client
This commit is contained in:
1 parent
c793e8b16d
commit
c477a05f03
8 files changed
+132
-31
No files matched your search
@@ -64,7 +64,9 @@ Die beiden Zeitfenster lassen sich über Umgebungsvariablen konfigurieren:
|
|||||||
|
|
||||||
Die Sitzungs-Queues liegen im Arbeitsspeicher des Broker-Prozesses. Sie
|
Die Sitzungs-Queues liegen im Arbeitsspeicher des Broker-Prozesses. Sie
|
||||||
überstehen damit WebSocket-Unterbrechungen und Seiten-Reloads, nicht aber einen
|
überstehen damit WebSocket-Unterbrechungen und Seiten-Reloads, nicht aber einen
|
||||||
Neustart des Servers.
|
Neustart des Servers. Der mobile Client puffert zusätzlich ausgehende
|
||||||
|
fachliche Nachrichten kurzzeitig lokal und sendet sie nach erfolgreicher
|
||||||
|
Authentifizierung automatisch nach.
|
||||||
|
|
||||||
## Erste Einrichtung
|
## Erste Einrichtung
|
||||||
|
|
||||||
|
|||||||
@@ -573,6 +573,10 @@ class WebSocketBroker:
|
|||||||
# einem Neuladen der Seite wieder sichtbar.
|
# einem Neuladen der Seite wieder sichtbar.
|
||||||
if apply_business and code in (100, 200, 300):
|
if apply_business and code in (100, 200, 300):
|
||||||
if not self._apply_business_change(tenant_id, message, sender):
|
if not self._apply_business_change(tenant_id, message, sender):
|
||||||
|
current_app.logger.warning(
|
||||||
|
'WebSocket-Nachricht abgelehnt: code=%s sender=%s tenant=%s msg=%s',
|
||||||
|
code, sender['id'], tenant_id, str(message.msg)[:300]
|
||||||
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
message = self._prepare_message(tenant_id, message, sender)
|
message = self._prepare_message(tenant_id, message, sender)
|
||||||
@@ -721,7 +725,7 @@ class WebSocketBroker:
|
|||||||
|
|
||||||
def _apply_street_change(self, tenant_id, message, sender, payload):
|
def _apply_street_change(self, tenant_id, message, sender, payload):
|
||||||
"""Wendet einen Straßen-State-Wechsel aus einer Code-100-Nachricht an."""
|
"""Wendet einen Straßen-State-Wechsel aus einer Code-100-Nachricht an."""
|
||||||
if sender['role'] not in ('Dispatcher', 'Administrator'):
|
if sender['role'] not in ('Dispatcher', 'Administrator', 'Gruppe'):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
db = get_db()
|
db = get_db()
|
||||||
@@ -746,6 +750,24 @@ class WebSocketBroker:
|
|||||||
if not street:
|
if not street:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
# Gruppen-Accounts dürfen nur Straßen bearbeiten, die ihrer eigenen
|
||||||
|
# Gruppe zugewiesen sind. Die Zuordnung darf dabei nicht auf eine
|
||||||
|
# andere Gruppe verschoben werden.
|
||||||
|
own_group_id = None
|
||||||
|
if sender['role'] == 'Gruppe':
|
||||||
|
group = db.execute(
|
||||||
|
'''SELECT g.id FROM groups g
|
||||||
|
JOIN group_accounts ga
|
||||||
|
ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id
|
||||||
|
WHERE ga.account_id = ? AND g.tenant_id = ?''',
|
||||||
|
(sender['id'], tenant_id)
|
||||||
|
).fetchone()
|
||||||
|
if not group:
|
||||||
|
return False
|
||||||
|
own_group_id = group['id']
|
||||||
|
if street['group_id'] != own_group_id:
|
||||||
|
return False
|
||||||
|
|
||||||
new_state = payload.get('state')
|
new_state = payload.get('state')
|
||||||
if new_state not in ('unbearbeitet', 'zugewiesen', 'erledigt'):
|
if new_state not in ('unbearbeitet', 'zugewiesen', 'erledigt'):
|
||||||
return False
|
return False
|
||||||
@@ -769,6 +791,15 @@ class WebSocketBroker:
|
|||||||
elif new_state == 'zugewiesen' and group_id is None:
|
elif new_state == 'zugewiesen' and group_id is None:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
if sender['role'] == 'Gruppe':
|
||||||
|
# Eine Gruppe darf ihre eigene Straße freigeben (unbearbeitet),
|
||||||
|
# aber nicht einer anderen Gruppe zuweisen.
|
||||||
|
if new_state != 'unbearbeitet':
|
||||||
|
if new_state == 'erledigt' and group_id is None:
|
||||||
|
group_id = own_group_id
|
||||||
|
if group_id != own_group_id:
|
||||||
|
return False
|
||||||
|
|
||||||
if group_id is not None:
|
if group_id is not None:
|
||||||
group = db.execute(
|
group = db.execute(
|
||||||
'SELECT id FROM groups WHERE id = ? AND tenant_id = ?',
|
'SELECT id FROM groups WHERE id = ? AND tenant_id = ?',
|
||||||
|
|||||||
@@ -6,12 +6,15 @@ from datetime import datetime
|
|||||||
|
|
||||||
|
|
||||||
class WSMessage:
|
class WSMessage:
|
||||||
def __init__(self, sender_id=None, receiver_id=None, code=0, msg="", ts=None):
|
def __init__(self, sender_id=None, receiver_id=None, code=0, msg="", ts=None, session_id=None):
|
||||||
self.sender_id = sender_id
|
self.sender_id = sender_id
|
||||||
self.receiver_id = receiver_id
|
self.receiver_id = receiver_id
|
||||||
self.code = code
|
self.code = code
|
||||||
self.msg = msg
|
self.msg = msg
|
||||||
self.ts = ts or int(datetime.now().timestamp() * 1000)
|
self.ts = ts or int(datetime.now().timestamp() * 1000)
|
||||||
|
# Nur für den Code-0-Handshake. Wird nicht an andere Clients
|
||||||
|
# weitergegeben und deshalb auch nicht in to_dict() serialisiert.
|
||||||
|
self.session_id = session_id
|
||||||
|
|
||||||
def to_dict(self):
|
def to_dict(self):
|
||||||
return {
|
return {
|
||||||
@@ -32,7 +35,8 @@ class WSMessage:
|
|||||||
receiver_id=data.get('receiver_id'),
|
receiver_id=data.get('receiver_id'),
|
||||||
code=data.get('code', 0),
|
code=data.get('code', 0),
|
||||||
msg=data.get('msg', ''),
|
msg=data.get('msg', ''),
|
||||||
ts=data.get('ts')
|
ts=data.get('ts'),
|
||||||
|
session_id=data.get('session_id')
|
||||||
)
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ Ablauf einer Verbindung:
|
|||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from flask import session
|
from flask import session, current_app
|
||||||
from cmbnet.extensions import sock
|
from cmbnet.extensions import sock
|
||||||
from cmbnet.ws import broker
|
from cmbnet.ws import broker
|
||||||
from cmbnet.ws.protocol import WSMessage
|
from cmbnet.ws.protocol import WSMessage
|
||||||
@@ -74,11 +74,24 @@ def ws(ws, tenant):
|
|||||||
# Code 0: Authentifizierung über den Einmal-Token.
|
# Code 0: Authentifizierung über den Einmal-Token.
|
||||||
if msg.code == 0:
|
if msg.code == 0:
|
||||||
token, session_id = _parse_auth_payload(msg.msg)
|
token, session_id = _parse_auth_payload(msg.msg)
|
||||||
|
if not session_id:
|
||||||
|
session_id = getattr(msg, 'session_id', None)
|
||||||
if not token or not broker.authenticate(
|
if not token or not broker.authenticate(
|
||||||
tenant_id, account_id, token, session_id
|
tenant_id, account_id, token, session_id
|
||||||
):
|
):
|
||||||
|
current_app.logger.warning(
|
||||||
|
'WebSocket-Authentifizierung fehlgeschlagen: tenant=%s account=%s',
|
||||||
|
tenant_id, account_id
|
||||||
|
)
|
||||||
ws.close()
|
ws.close()
|
||||||
break
|
break
|
||||||
|
# Bestätigt dem Client den erfolgreichen Handshake. Erst jetzt
|
||||||
|
# darf er gepufferte fachliche Nachrichten senden.
|
||||||
|
broker.send_to_connection(
|
||||||
|
tenant_id,
|
||||||
|
account_id,
|
||||||
|
WSMessage(sender_id=0, code=0, msg='authenticated').to_json()
|
||||||
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Fachliche Nachrichten sind erst nach erfolgreicher
|
# Fachliche Nachrichten sind erst nach erfolgreicher
|
||||||
|
|||||||
@@ -127,10 +127,8 @@
|
|||||||
ws.addEventListener('open', () => {
|
ws.addEventListener('open', () => {
|
||||||
ws.send(JSON.stringify({
|
ws.send(JSON.stringify({
|
||||||
code: 0,
|
code: 0,
|
||||||
msg: {
|
msg: data.token,
|
||||||
token: data.token,
|
session_id: window.CMBNET_CLIENT_SESSION_ID || ''
|
||||||
session_id: window.CMBNET_CLIENT_SESSION_ID || ''
|
|
||||||
}
|
|
||||||
}));
|
}));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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-v7';
|
const VERSION = 'cmbnet-pwa-v8';
|
||||||
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`;
|
||||||
|
|||||||
@@ -2703,10 +2703,8 @@ async function connectWebSocket() {
|
|||||||
ws.addEventListener('open', () => {
|
ws.addEventListener('open', () => {
|
||||||
ws.send(JSON.stringify({
|
ws.send(JSON.stringify({
|
||||||
code: 0,
|
code: 0,
|
||||||
msg: {
|
msg: token,
|
||||||
token,
|
session_id: window.CMBNET_CLIENT_SESSION_ID || ''
|
||||||
session_id: window.CMBNET_CLIENT_SESSION_ID || ''
|
|
||||||
}
|
|
||||||
}));
|
}));
|
||||||
dispatcherState.authenticated = true;
|
dispatcherState.authenticated = true;
|
||||||
setConnectionStatus('Verbunden', 'connected');
|
setConnectionStatus('Verbunden', 'connected');
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ const DEFAULT_SETTINGS = {
|
|||||||
const AUTO_POSITION_INTERVAL_MS = 30000;
|
const AUTO_POSITION_INTERVAL_MS = 30000;
|
||||||
const NAVIGATION_MAX_AGE_MS = 30 * 60 * 1000;
|
const NAVIGATION_MAX_AGE_MS = 30 * 60 * 1000;
|
||||||
const NAVIGATION_REFRESH_MS = 15000;
|
const NAVIGATION_REFRESH_MS = 15000;
|
||||||
|
const WS_OUTBOX_LIMIT = 200;
|
||||||
|
|
||||||
const STREET_STATES = ['unbearbeitet', 'zugewiesen', 'erledigt'];
|
const STREET_STATES = ['unbearbeitet', 'zugewiesen', 'erledigt'];
|
||||||
const STREET_COLORS = {
|
const STREET_COLORS = {
|
||||||
@@ -45,6 +46,7 @@ const state = {
|
|||||||
currentStreetId: null,
|
currentStreetId: null,
|
||||||
ws: null,
|
ws: null,
|
||||||
authenticated: false,
|
authenticated: false,
|
||||||
|
outbox: [],
|
||||||
reconnectTimer: null,
|
reconnectTimer: null,
|
||||||
chatMessages: [],
|
chatMessages: [],
|
||||||
chatKeys: new Set(),
|
chatKeys: new Set(),
|
||||||
@@ -309,13 +311,54 @@ function updatePositionSharingUi() {
|
|||||||
button.textContent = 'Position senden';
|
button.textContent = 'Position senden';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function canSendWs() {
|
||||||
|
return Boolean(state.ws
|
||||||
|
&& state.ws.readyState === WebSocket.OPEN
|
||||||
|
&& state.authenticated);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendWsMessage(message, queueWhenOffline = true) {
|
||||||
|
const data = JSON.stringify(message);
|
||||||
|
|
||||||
|
if (canSendWs()) {
|
||||||
|
try {
|
||||||
|
state.ws.send(data);
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
// Nach einem Sendefehler wird die Nachricht unten gepuffert.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (queueWhenOffline) {
|
||||||
|
state.outbox.push(data);
|
||||||
|
if (state.outbox.length > WS_OUTBOX_LIMIT) {
|
||||||
|
state.outbox.splice(0, state.outbox.length - WS_OUTBOX_LIMIT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function flushWsOutbox() {
|
||||||
|
if (!canSendWs() || !state.outbox.length) return;
|
||||||
|
|
||||||
|
const pending = state.outbox;
|
||||||
|
state.outbox = [];
|
||||||
|
for (let index = 0; index < pending.length; index += 1) {
|
||||||
|
try {
|
||||||
|
state.ws.send(pending[index]);
|
||||||
|
} catch (error) {
|
||||||
|
state.outbox = pending.slice(index).concat(state.outbox);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function sendOwnPosition(lat, lon, automatic = false) {
|
function sendOwnPosition(lat, lon, automatic = false) {
|
||||||
if (viewMode !== 'mobile_group' || currentRole !== 'Gruppe') return false;
|
if (viewMode !== 'mobile_group' || currentRole !== 'Gruppe') return false;
|
||||||
if (!state.currentGroupId) return false;
|
if (!state.currentGroupId) return false;
|
||||||
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return false;
|
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return false;
|
||||||
if (!state.ws || state.ws.readyState !== WebSocket.OPEN || !state.authenticated) return false;
|
|
||||||
|
|
||||||
state.ws.send(JSON.stringify({
|
const sent = sendWsMessage({
|
||||||
code: 300,
|
code: 300,
|
||||||
msg: JSON.stringify({
|
msg: JSON.stringify({
|
||||||
group_id: state.currentGroupId,
|
group_id: state.currentGroupId,
|
||||||
@@ -325,7 +368,9 @@ function sendOwnPosition(lat, lon, automatic = false) {
|
|||||||
actor: currentAccountId,
|
actor: currentAccountId,
|
||||||
automatic: automatic === true
|
automatic: automatic === true
|
||||||
})
|
})
|
||||||
}));
|
}, !automatic);
|
||||||
|
|
||||||
|
if (!sent && automatic) return false;
|
||||||
state.lastPositionSentAt = Date.now();
|
state.lastPositionSentAt = Date.now();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -869,12 +914,10 @@ function saveMobileStreetState() {
|
|||||||
} else if (newState === 'erledigt' && street.group_id) {
|
} else if (newState === 'erledigt' && street.group_id) {
|
||||||
groupId = Number(street.group_id);
|
groupId = Number(street.group_id);
|
||||||
}
|
}
|
||||||
if (state.ws && state.ws.readyState === WebSocket.OPEN && state.authenticated) {
|
sendWsMessage({
|
||||||
state.ws.send(JSON.stringify({
|
code: 100,
|
||||||
code: 100,
|
msg: JSON.stringify({name: street.name, state: newState, actor: currentAccountId, street_id: street.id, group_id: groupId})
|
||||||
msg: JSON.stringify({name: street.name, state: newState, actor: currentAccountId, street_id: street.id, group_id: groupId})
|
});
|
||||||
}));
|
|
||||||
}
|
|
||||||
closeMobileStreetState();
|
closeMobileStreetState();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1105,14 +1148,26 @@ function connectWebSocket() {
|
|||||||
const ws = new WebSocket(wsUrl);
|
const ws = new WebSocket(wsUrl);
|
||||||
state.ws = ws;
|
state.ws = ws;
|
||||||
ws.addEventListener('open', () => {
|
ws.addEventListener('open', () => {
|
||||||
|
// Der Server bestätigt den Handshake mit Code 0. Bis dahin werden
|
||||||
|
// fachliche Nachrichten im Outbox-Puffer gesammelt.
|
||||||
|
state.authenticated = false;
|
||||||
ws.send(JSON.stringify({
|
ws.send(JSON.stringify({
|
||||||
code: 0,
|
code: 0,
|
||||||
msg: {
|
msg: token,
|
||||||
token,
|
session_id: window.CMBNET_CLIENT_SESSION_ID || ''
|
||||||
session_id: window.CMBNET_CLIENT_SESSION_ID || ''
|
|
||||||
}
|
|
||||||
}));
|
}));
|
||||||
state.authenticated = true;
|
|
||||||
|
// Fallback für ältere Server, die noch keine Code-0-Bestätigung
|
||||||
|
// senden. Die Code-0-Nachricht wurde bereits als erstes gesendet,
|
||||||
|
// daher ist die Reihenfolge auf dem Socket weiterhin korrekt.
|
||||||
|
setTimeout(() => {
|
||||||
|
if (state.ws === ws
|
||||||
|
&& ws.readyState === WebSocket.OPEN
|
||||||
|
&& !state.authenticated) {
|
||||||
|
state.authenticated = true;
|
||||||
|
flushWsOutbox();
|
||||||
|
}
|
||||||
|
}, 1500);
|
||||||
});
|
});
|
||||||
ws.addEventListener('message', handleWs);
|
ws.addEventListener('message', handleWs);
|
||||||
ws.addEventListener('close', () => {
|
ws.addEventListener('close', () => {
|
||||||
@@ -1129,13 +1184,12 @@ function sendChat() {
|
|||||||
if (!input) return;
|
if (!input) return;
|
||||||
const text = input.value.trim();
|
const text = input.value.trim();
|
||||||
if (!text) return;
|
if (!text) return;
|
||||||
if (!state.ws || state.ws.readyState !== WebSocket.OPEN || !state.authenticated) return;
|
|
||||||
|
|
||||||
if (viewMode === 'mobile_group' && state.currentGroupId) {
|
if (viewMode === 'mobile_group' && state.currentGroupId) {
|
||||||
state.ws.send(JSON.stringify({code: 2000, msg: JSON.stringify({group_id: state.currentGroupId, text})}));
|
sendWsMessage({code: 2000, msg: JSON.stringify({group_id: state.currentGroupId, text})});
|
||||||
} else if (viewMode === 'mobile_dispatcher') {
|
} else if (viewMode === 'mobile_dispatcher') {
|
||||||
// For dispatcher mobile, could send 1000 broadcast or 1100 - follow general behavior
|
// For dispatcher mobile, could send 1000 broadcast or 1100 - follow general behavior
|
||||||
state.ws.send(JSON.stringify({code: 1000, msg: JSON.stringify({text})}));
|
sendWsMessage({code: 1000, msg: JSON.stringify({text})});
|
||||||
}
|
}
|
||||||
input.value = '';
|
input.value = '';
|
||||||
}
|
}
|
||||||
@@ -1275,6 +1329,7 @@ function handleWs(event) {
|
|||||||
|
|
||||||
if (message.code === 0) {
|
if (message.code === 0) {
|
||||||
state.authenticated = true;
|
state.authenticated = true;
|
||||||
|
flushWsOutbox();
|
||||||
} else if (message.code === 1) {
|
} else if (message.code === 1) {
|
||||||
if (state.ws && state.ws.readyState === WebSocket.OPEN) {
|
if (state.ws && state.ws.readyState === WebSocket.OPEN) {
|
||||||
state.ws.send(JSON.stringify({code: 2, msg: 'pong'}));
|
state.ws.send(JSON.stringify({code: 2, msg: 'pong'}));
|
||||||
|
|||||||
Reference in new issue
Block a user