Nachrichten klappen jetzt einigermassen
This commit is contained in:
1 parent
518248ca00
commit
ffdb399f9e
5 files changed
+551
-69
No files matched your search
@@ -4,12 +4,28 @@ API Endpunkte für Initialdaten
|
|||||||
from flask import Blueprint, jsonify, g, request
|
from flask import Blueprint, jsonify, g, request
|
||||||
from cmbnet.auth import login_required
|
from cmbnet.auth import login_required
|
||||||
from cmbnet.db import get_db
|
from cmbnet.db import get_db
|
||||||
|
from cmbnet.models.accounts import AccountModel
|
||||||
from cmbnet.services.streets_service import StreetsService
|
from cmbnet.services.streets_service import StreetsService
|
||||||
from cmbnet.services.groups_service import GroupsService
|
from cmbnet.services.groups_service import GroupsService
|
||||||
|
|
||||||
api_init_bp = Blueprint('api_init', __name__)
|
api_init_bp = Blueprint('api_init', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
@api_init_bp.route('/init/accounts')
|
||||||
|
@login_required
|
||||||
|
def init_accounts(**kwargs):
|
||||||
|
"""Liefert alle Accounts für den Tenant (für Senderdarstellung)"""
|
||||||
|
accounts = AccountModel.get_all_by_tenant(g.tenant_id)
|
||||||
|
result = []
|
||||||
|
for account in accounts:
|
||||||
|
result.append({
|
||||||
|
'id': account['id'],
|
||||||
|
'name': account['name'],
|
||||||
|
'role': account['role']
|
||||||
|
})
|
||||||
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
@api_init_bp.route('/init/streets')
|
@api_init_bp.route('/init/streets')
|
||||||
@login_required
|
@login_required
|
||||||
def init_streets(**kwargs):
|
def init_streets(**kwargs):
|
||||||
|
|||||||
@@ -557,30 +557,103 @@ class WebSocketBroker:
|
|||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
print(f'Transaction log error: {exc}')
|
print(f'Transaction log error: {exc}')
|
||||||
|
|
||||||
|
def _get_sender_info(self, tenant_id, sender):
|
||||||
|
"""Liefert Sender-Informationen inkl. Accountname und ggf. Gruppen-Alias."""
|
||||||
|
db = get_db()
|
||||||
|
info = {
|
||||||
|
'account_id': sender['id'] if sender else None,
|
||||||
|
'account_name': sender['name'] if sender else None,
|
||||||
|
'role': sender['role'] if sender else None,
|
||||||
|
'group_id': None,
|
||||||
|
'group_alias': None
|
||||||
|
}
|
||||||
|
if sender and sender['role'] == 'Gruppe':
|
||||||
|
group = db.execute(
|
||||||
|
'SELECT id, aliasname FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||||
|
(sender['id'], tenant_id)
|
||||||
|
).fetchone()
|
||||||
|
if group:
|
||||||
|
info['group_id'] = group['id']
|
||||||
|
info['group_alias'] = group['aliasname']
|
||||||
|
else:
|
||||||
|
# Auch für andere Rollen kann ein verknüpfter Gruppen-Account Kontext
|
||||||
|
# liefern; für Dispatcher reicht der Accountname.
|
||||||
|
pass
|
||||||
|
return info
|
||||||
|
|
||||||
|
def _normalize_chat_message(self, tenant_id, message, sender, payload):
|
||||||
|
"""Normalisiert Chat-Nachrichten (Code >= 1000) auf einheitliches JSON."""
|
||||||
|
sender_info = self._get_sender_info(tenant_id, sender)
|
||||||
|
text = ''
|
||||||
|
if isinstance(payload, dict):
|
||||||
|
if payload.get('text') is not None:
|
||||||
|
text = str(payload.get('text') or '')
|
||||||
|
elif payload.get('msg') is not None:
|
||||||
|
inner = payload.get('msg')
|
||||||
|
if isinstance(inner, dict) and inner.get('text') is not None:
|
||||||
|
text = str(inner.get('text') or '')
|
||||||
|
elif isinstance(inner, str):
|
||||||
|
text = inner
|
||||||
|
else:
|
||||||
|
text = str(inner or '')
|
||||||
|
else:
|
||||||
|
# Fallback: falls nur andere Felder, versuche text
|
||||||
|
text = str(payload.get('message') or '')
|
||||||
|
elif isinstance(message.msg, str):
|
||||||
|
text = message.msg
|
||||||
|
else:
|
||||||
|
text = str(message.msg or '')
|
||||||
|
|
||||||
|
text = str(text).strip()
|
||||||
|
normalized = {
|
||||||
|
'text': text,
|
||||||
|
'sender': {
|
||||||
|
'account_id': sender_info['account_id'],
|
||||||
|
'name': sender_info['account_name'],
|
||||||
|
'role': sender_info['role'],
|
||||||
|
'group_id': sender_info['group_id'],
|
||||||
|
'group_alias': sender_info['group_alias']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if message.code == 1100:
|
||||||
|
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
||||||
|
if group_id is not None:
|
||||||
|
try:
|
||||||
|
message.receiver_id = int(group_id)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
message.receiver_id = group_id
|
||||||
|
normalized['group_id'] = message.receiver_id
|
||||||
|
elif message.code == 1000:
|
||||||
|
normalized['broadcast'] = True
|
||||||
|
else:
|
||||||
|
if message.receiver_id is not None:
|
||||||
|
normalized['receiver_id'] = message.receiver_id
|
||||||
|
|
||||||
|
message.msg = json.dumps(normalized, ensure_ascii=False)
|
||||||
|
return message
|
||||||
|
|
||||||
def _prepare_message(self, tenant_id, message, sender):
|
def _prepare_message(self, tenant_id, message, sender):
|
||||||
"""Ergänzt Nachrichten um serverseitig abgeleitete Informationen."""
|
"""Ergänzt Nachrichten um serverseitig abgeleitete Informationen."""
|
||||||
db = get_db()
|
db = get_db()
|
||||||
payload = self._payload(message)
|
payload = self._payload(message)
|
||||||
|
code = message.code
|
||||||
|
|
||||||
|
if code >= 1000:
|
||||||
|
return self._normalize_chat_message(tenant_id, message, sender, payload)
|
||||||
|
|
||||||
if message.code == 1100:
|
if message.code == 1100:
|
||||||
# Empfänger ist eine spezielle Gruppe. Die Gruppen-ID wird aus dem
|
|
||||||
# Payload oder dem receiver_id-Feld gelesen.
|
|
||||||
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
||||||
group = self._fetch_group(tenant_id, group_id)
|
group = self._fetch_group(tenant_id, group_id)
|
||||||
message.receiver_id = group_id
|
message.receiver_id = group_id
|
||||||
|
|
||||||
# Spezifikation: Dem Freitext wird der Aliasname der Gruppe
|
|
||||||
# vorangestellt. Ein bereits vorhandenes Präfix wird nicht doppelt
|
|
||||||
# gesetzt.
|
|
||||||
if group:
|
if group:
|
||||||
alias = group['aliasname'] or str(group['id'])
|
alias = group['aliasname'] or str(group['id'])
|
||||||
prefix = f'{alias}: '
|
prefix = f'{alias}: '
|
||||||
text = message.msg if isinstance(message.msg, str) else json.dumps(message.msg)
|
text = message.msg if isinstance(message.msg, str) else json.dumps(message.msg)
|
||||||
if not text.startswith(prefix):
|
if not text.startswith(prefix):
|
||||||
message.msg = prefix + text
|
message.msg = prefix + text
|
||||||
|
return self._normalize_chat_message(tenant_id, message, sender, payload)
|
||||||
|
|
||||||
elif message.code == 2000:
|
elif message.code == 2000:
|
||||||
# Spezifikation: Inhalt ist JSON mit Gruppen-ID und Freitext.
|
|
||||||
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
||||||
message.receiver_id = group_id
|
message.receiver_id = group_id
|
||||||
if isinstance(payload, dict):
|
if isinstance(payload, dict):
|
||||||
@@ -592,6 +665,7 @@ class WebSocketBroker:
|
|||||||
{'group_id': group_id, 'text': message.msg},
|
{'group_id': group_id, 'text': message.msg},
|
||||||
ensure_ascii=False
|
ensure_ascii=False
|
||||||
)
|
)
|
||||||
|
return self._normalize_chat_message(tenant_id, message, sender, payload)
|
||||||
|
|
||||||
return message
|
return message
|
||||||
|
|
||||||
|
|||||||
@@ -648,11 +648,40 @@ dialog.group-streets-dialog.is-dragging article header {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#chatModal article,
|
#chatModal article,
|
||||||
.chat-dialog {
|
.chat-dialog,
|
||||||
|
#broadcastModal article,
|
||||||
|
.broadcast-dialog {
|
||||||
width: min(44rem, 94vw);
|
width: min(44rem, 94vw);
|
||||||
max-width: 94vw;
|
max-width: 94vw;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.chat-dialog > footer.chat-input-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: stretch;
|
||||||
|
gap: 0.5rem;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-input {
|
||||||
|
flex: 1 1 0%;
|
||||||
|
min-width: 0;
|
||||||
|
margin: 0;
|
||||||
|
height: 2.4rem;
|
||||||
|
align-self: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-send-button {
|
||||||
|
flex: 0 0 2.4rem;
|
||||||
|
width: 2.4rem;
|
||||||
|
height: 2.4rem;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
border-radius: 0.55rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
align-self: stretch;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
.chat-messages {
|
.chat-messages {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
@@ -37,6 +37,12 @@ const dispatcherState = {
|
|||||||
streetById: new Map(),
|
streetById: new Map(),
|
||||||
groups: [],
|
groups: [],
|
||||||
groupById: new Map(),
|
groupById: new Map(),
|
||||||
|
accounts: [],
|
||||||
|
accountById: new Map(),
|
||||||
|
lastCode0ReceivedAt: Date.now(),
|
||||||
|
heartbeatTimeoutId: null,
|
||||||
|
heartbeatWarningShown: false,
|
||||||
|
groupMessageTargetId: null,
|
||||||
polylinesByStreetId: new Map(),
|
polylinesByStreetId: new Map(),
|
||||||
markersByGroupId: new Map(),
|
markersByGroupId: new Map(),
|
||||||
browserLatLng: null,
|
browserLatLng: null,
|
||||||
@@ -72,12 +78,14 @@ async function initDispatcher() {
|
|||||||
setInterval(updateClock, 1000);
|
setInterval(updateClock, 1000);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const [streets, groups] = await Promise.all([
|
const [streets, groups, accounts] = await Promise.all([
|
||||||
fetchJson(`${apiBase}/init/streets`),
|
fetchJson(`${apiBase}/init/streets`),
|
||||||
fetchJson(`${apiBase}/init/groups`)
|
fetchJson(`${apiBase}/init/groups`),
|
||||||
|
fetchJson(`${apiBase}/init/accounts`).catch(() => [])
|
||||||
]);
|
]);
|
||||||
dispatcherState.streets = Array.isArray(streets) ? streets : [];
|
dispatcherState.streets = Array.isArray(streets) ? streets : [];
|
||||||
dispatcherState.groups = Array.isArray(groups) ? groups : [];
|
dispatcherState.groups = Array.isArray(groups) ? groups : [];
|
||||||
|
dispatcherState.accounts = Array.isArray(accounts) ? accounts : [];
|
||||||
indexData();
|
indexData();
|
||||||
buildPolylines();
|
buildPolylines();
|
||||||
buildGroupAccordion();
|
buildGroupAccordion();
|
||||||
@@ -205,6 +213,12 @@ function indexData() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
dispatcherState.groups.sort((a, b) => a.id - b.id);
|
dispatcherState.groups.sort((a, b) => a.id - b.id);
|
||||||
|
|
||||||
|
dispatcherState.accountById.clear();
|
||||||
|
dispatcherState.accounts.forEach(account => {
|
||||||
|
account.id = Number(account.id);
|
||||||
|
dispatcherState.accountById.set(account.id, account);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ */
|
/* ------------------------------------------------------------------ */
|
||||||
@@ -772,6 +786,28 @@ function createGroupElement(group) {
|
|||||||
return details;
|
return details;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function updateGroupLastMessagePreview(groupId) {
|
||||||
|
const item = document.querySelector(`.group-item[data-group-id="${groupId}"]`);
|
||||||
|
if (!item) return;
|
||||||
|
const input = item.querySelector('.group-message');
|
||||||
|
if (!input) return;
|
||||||
|
const entries = dispatcherState.chatByGroup.get(Number(groupId)) || [];
|
||||||
|
if (!entries.length) {
|
||||||
|
input.value = '';
|
||||||
|
input.placeholder = 'Noch keine Gruppennachricht';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const last = entries.slice().sort((a, b) => a.ts - b.ts).pop();
|
||||||
|
if (!last) {
|
||||||
|
input.value = '';
|
||||||
|
input.placeholder = 'Noch keine Gruppennachricht';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
input.placeholder = 'Chatverlauf öffnen';
|
||||||
|
const preview = extractMessageText(last.text);
|
||||||
|
input.value = `${getSenderDisplay(last.sender_id, last).name}: ${String(preview || '').replace(/\s+/g, ' ')}`;
|
||||||
|
}
|
||||||
|
|
||||||
function refreshGroupControls(now = Date.now()) {
|
function refreshGroupControls(now = Date.now()) {
|
||||||
dispatcherState.groups.forEach(group => {
|
dispatcherState.groups.forEach(group => {
|
||||||
updateGroupMarkerOpacity(group, now);
|
updateGroupMarkerOpacity(group, now);
|
||||||
@@ -1040,6 +1076,46 @@ function handleMapClick(event) {
|
|||||||
cancelCrosshair();
|
cancelCrosshair();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function startHeartbeatMonitoring() {
|
||||||
|
if (dispatcherState.heartbeatTimeoutId) {
|
||||||
|
clearTimeout(dispatcherState.heartbeatTimeoutId);
|
||||||
|
}
|
||||||
|
dispatcherState.heartbeatTimeoutId = setTimeout(checkHeartbeatTimeout, 95000);
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkHeartbeatTimeout() {
|
||||||
|
const now = Date.now();
|
||||||
|
if (dispatcherState.lastCode0ReceivedAt
|
||||||
|
&& now - dispatcherState.lastCode0ReceivedAt > 90000) {
|
||||||
|
setConnectionStatus('Nicht verbunden', 'disconnected');
|
||||||
|
if (!dispatcherState.heartbeatWarningShown) {
|
||||||
|
dispatcherState.heartbeatWarningShown = true;
|
||||||
|
showHeartbeatWarning();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
dispatcherState.heartbeatWarningShown = false;
|
||||||
|
}
|
||||||
|
startHeartbeatMonitoring();
|
||||||
|
}
|
||||||
|
|
||||||
|
function showHeartbeatWarning() {
|
||||||
|
const dialog = document.getElementById('heartbeatWarningModal');
|
||||||
|
if (!dialog) {
|
||||||
|
alert('Keine Nachrichten mit Code 0 seit mehr als 90 Sekunden erhalten.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (typeof dialog.showModal === 'function') {
|
||||||
|
dialog.showModal();
|
||||||
|
} else {
|
||||||
|
dialog.show();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeHeartbeatWarningModal() {
|
||||||
|
const dialog = document.getElementById('heartbeatWarningModal');
|
||||||
|
if (dialog && dialog.open) dialog.close();
|
||||||
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ */
|
/* ------------------------------------------------------------------ */
|
||||||
/* Straßen einer Gruppe */
|
/* Straßen einer Gruppe */
|
||||||
/* ------------------------------------------------------------------ */
|
/* ------------------------------------------------------------------ */
|
||||||
@@ -1683,11 +1759,33 @@ function saveStreetState() {
|
|||||||
function openChat(groupId) {
|
function openChat(groupId) {
|
||||||
dispatcherState.chatGroupId = Number(groupId);
|
dispatcherState.chatGroupId = Number(groupId);
|
||||||
renderChat();
|
renderChat();
|
||||||
document.getElementById('chatModal').showModal();
|
const dialog = document.getElementById('chatModal');
|
||||||
|
if (dialog && typeof dialog.showModal === 'function') {
|
||||||
|
dialog.showModal();
|
||||||
|
} else if (dialog) {
|
||||||
|
dialog.show();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeChatModal() {
|
function closeChatModal() {
|
||||||
document.getElementById('chatModal').close();
|
const dialog = document.getElementById('chatModal');
|
||||||
|
if (dialog && dialog.open) dialog.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendChatMessageFromModal() {
|
||||||
|
const groupId = dispatcherState.chatGroupId;
|
||||||
|
const group = groupId !== null ? dispatcherState.groupById.get(Number(groupId)) : null;
|
||||||
|
const input = document.getElementById('chatInput');
|
||||||
|
if (!group || !input) return;
|
||||||
|
const text = String(input.value).trim();
|
||||||
|
if (!text) return;
|
||||||
|
sendWs({
|
||||||
|
code: 1100,
|
||||||
|
receiver_id: group.id,
|
||||||
|
msg: JSON.stringify({group_id: group.id, text})
|
||||||
|
});
|
||||||
|
input.value = '';
|
||||||
|
input.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderChat() {
|
function renderChat() {
|
||||||
@@ -1706,48 +1804,99 @@ function renderChat() {
|
|||||||
empty.className = 'chat-empty';
|
empty.className = 'chat-empty';
|
||||||
empty.textContent = 'Noch keine Nachrichten.';
|
empty.textContent = 'Noch keine Nachrichten.';
|
||||||
container.appendChild(empty);
|
container.appendChild(empty);
|
||||||
return;
|
} else {
|
||||||
|
entries
|
||||||
|
.slice()
|
||||||
|
.sort((a, b) => a.ts - b.ts)
|
||||||
|
.forEach(entry => {
|
||||||
|
const message = document.createElement('div');
|
||||||
|
message.className = 'chat-message';
|
||||||
|
const senderInfo = getSenderDisplay(entry.sender_id, entry);
|
||||||
|
if (senderInfo.isMe) {
|
||||||
|
message.classList.add('own');
|
||||||
|
}
|
||||||
|
|
||||||
|
const header = document.createElement('div');
|
||||||
|
header.className = 'chat-message-header';
|
||||||
|
|
||||||
|
const sender = document.createElement('span');
|
||||||
|
sender.textContent = senderInfo.name;
|
||||||
|
|
||||||
|
const time = document.createElement('span');
|
||||||
|
time.textContent = formatChatTime(entry.ts);
|
||||||
|
|
||||||
|
header.append(sender, time);
|
||||||
|
|
||||||
|
const text = document.createElement('div');
|
||||||
|
text.className = 'chat-message-text';
|
||||||
|
const textContent = extractMessageText(entry.text);
|
||||||
|
text.textContent = textContent;
|
||||||
|
|
||||||
|
message.append(header, text);
|
||||||
|
container.appendChild(message);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
entries
|
|
||||||
.slice()
|
|
||||||
.sort((a, b) => a.ts - b.ts)
|
|
||||||
.forEach(entry => {
|
|
||||||
const message = document.createElement('div');
|
|
||||||
message.className = 'chat-message';
|
|
||||||
if (Number(entry.sender_id) === currentAccountId) {
|
|
||||||
message.classList.add('own');
|
|
||||||
}
|
|
||||||
|
|
||||||
const header = document.createElement('div');
|
|
||||||
header.className = 'chat-message-header';
|
|
||||||
|
|
||||||
const sender = document.createElement('span');
|
|
||||||
sender.textContent = senderLabel(entry.sender_id);
|
|
||||||
|
|
||||||
const time = document.createElement('span');
|
|
||||||
time.textContent = formatChatTime(entry.ts);
|
|
||||||
|
|
||||||
header.append(sender, time);
|
|
||||||
|
|
||||||
const text = document.createElement('div');
|
|
||||||
text.className = 'chat-message-text';
|
|
||||||
text.textContent = entry.text;
|
|
||||||
|
|
||||||
message.append(header, text);
|
|
||||||
container.appendChild(message);
|
|
||||||
});
|
|
||||||
|
|
||||||
container.scrollTop = container.scrollHeight;
|
container.scrollTop = container.scrollHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
function senderLabel(senderId) {
|
function getSenderDisplay(senderId, messageOrPayload = null) {
|
||||||
const id = Number(senderId);
|
let payload = null;
|
||||||
if (id === currentAccountId) return 'Ich';
|
if (messageOrPayload && typeof messageOrPayload === 'object') {
|
||||||
|
payload = extractMessagePayload(messageOrPayload.msg ?? messageOrPayload);
|
||||||
|
if (!payload && (messageOrPayload.sender || messageOrPayload.group_id)) {
|
||||||
|
payload = messageOrPayload;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const payloadSender = payload && typeof payload.sender === 'object' ? payload.sender : null;
|
||||||
|
const id = Number(
|
||||||
|
payloadSender?.account_id
|
||||||
|
?? (typeof senderId === 'object' ? senderId.sender_id : senderId)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (payloadSender && payloadSender.name) {
|
||||||
|
const name = payloadSender.name;
|
||||||
|
const alias = payloadSender.group_alias || payload?.group_alias;
|
||||||
|
if (alias && payloadSender.role === 'Gruppe') {
|
||||||
|
const display = `${name} (Gruppe: ${alias})`;
|
||||||
|
return {name: display, isMe: id === currentAccountId};
|
||||||
|
}
|
||||||
|
if (alias) {
|
||||||
|
const display = `${name} (Gruppe: ${alias})`;
|
||||||
|
return {name: display, isMe: id === currentAccountId};
|
||||||
|
}
|
||||||
|
if (payloadSender.role === 'Gruppe') {
|
||||||
|
return {name: `${name} (Gruppe)`, isMe: id === currentAccountId};
|
||||||
|
}
|
||||||
|
return {name, isMe: id === currentAccountId};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Number.isFinite(id) || id <= 0) {
|
||||||
|
return {name: 'System', isMe: false};
|
||||||
|
}
|
||||||
|
if (id === currentAccountId) {
|
||||||
|
return {name: 'Ich', isMe: true};
|
||||||
|
}
|
||||||
|
|
||||||
|
const account = dispatcherState.accountById.get(id);
|
||||||
const group = dispatcherState.groups.find(item => Number(item.account_id) === id);
|
const group = dispatcherState.groups.find(item => Number(item.account_id) === id);
|
||||||
if (group) return groupDisplayName(group);
|
const accountName = account && account.name ? account.name : `Account ${id}`;
|
||||||
return id ? `Account ${id}` : 'System';
|
if (group) {
|
||||||
|
const alias = group.aliasname && String(group.aliasname).trim();
|
||||||
|
if (alias) {
|
||||||
|
return {name: `${accountName} (Gruppe: ${alias})`, isMe: false};
|
||||||
|
}
|
||||||
|
return {name: `${accountName} (Gruppe ${group.id})`, isMe: false};
|
||||||
|
}
|
||||||
|
if (account && account.role === 'Gruppe') {
|
||||||
|
return {name: `${accountName} (Gruppe)`, isMe: false};
|
||||||
|
}
|
||||||
|
return {name: accountName, isMe: false};
|
||||||
|
}
|
||||||
|
|
||||||
|
function senderLabel(senderId) {
|
||||||
|
return getSenderDisplay(senderId).name;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatChatTime(timestamp) {
|
function formatChatTime(timestamp) {
|
||||||
@@ -1775,12 +1924,21 @@ function addChatMessage(groupId, entry) {
|
|||||||
dispatcherState.chatKeysByGroup.set(id, new Set());
|
dispatcherState.chatKeysByGroup.set(id, new Set());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const textForKey = extractMessageText(entry.text ?? entry.msg ?? entry);
|
||||||
const keys = dispatcherState.chatKeysByGroup.get(id);
|
const keys = dispatcherState.chatKeysByGroup.get(id);
|
||||||
const key = `${entry.code}|${entry.sender_id}|${entry.ts}|${entry.text}`;
|
const key = `${entry.code}|${entry.sender_id}|${entry.ts}|${textForKey}`;
|
||||||
if (keys.has(key)) return;
|
if (keys.has(key)) {
|
||||||
|
updateGroupLastMessagePreview(id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
keys.add(key);
|
keys.add(key);
|
||||||
dispatcherState.chatByGroup.get(id).push(entry);
|
dispatcherState.chatByGroup.get(id).push({
|
||||||
|
...entry,
|
||||||
|
text: textForKey,
|
||||||
|
msg: entry.msg ?? textForKey
|
||||||
|
});
|
||||||
|
updateGroupLastMessagePreview(id);
|
||||||
|
|
||||||
if (dispatcherState.chatGroupId === id
|
if (dispatcherState.chatGroupId === id
|
||||||
&& document.getElementById('chatModal').open) {
|
&& document.getElementById('chatModal').open) {
|
||||||
@@ -1788,14 +1946,113 @@ function addChatMessage(groupId, entry) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function addBroadcastChatMessage(entry) {
|
function showInfoMessage(message) {
|
||||||
dispatcherState.groups.forEach(group => addChatMessage(group.id, entry));
|
const dialog = document.getElementById('infoMessageModal');
|
||||||
|
if (!dialog) return;
|
||||||
|
|
||||||
|
const code = Number(message.code);
|
||||||
|
const senderInfo = getSenderDisplay(message.sender_id, message);
|
||||||
|
const sender = senderInfo.name;
|
||||||
|
const payload = extractMessagePayload(message.msg);
|
||||||
|
let receiverId = Number(message.receiver_id);
|
||||||
|
if (!Number.isFinite(receiverId) && payload && payload.group_id !== undefined) {
|
||||||
|
receiverId = Number(payload.group_id);
|
||||||
|
}
|
||||||
|
if (!Number.isFinite(receiverId) && payload && payload.receiver_id !== undefined) {
|
||||||
|
receiverId = Number(payload.receiver_id);
|
||||||
|
}
|
||||||
|
let receiver = '';
|
||||||
|
if (Number.isFinite(receiverId) && receiverId > 0) {
|
||||||
|
const group = dispatcherState.groupById.get(receiverId);
|
||||||
|
const account = dispatcherState.accountById.get(receiverId);
|
||||||
|
if (group) {
|
||||||
|
receiver = `Gruppe ${groupDisplayName(group)}`;
|
||||||
|
} else if (account) {
|
||||||
|
receiver = account.name;
|
||||||
|
} else {
|
||||||
|
receiver = `ID ${receiverId}`;
|
||||||
|
}
|
||||||
|
} else if (code === 1000 || (payload && payload.broadcast)) {
|
||||||
|
receiver = 'alle';
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('infoMessageCode').textContent = Number.isFinite(code) ? code : '';
|
||||||
|
document.getElementById('infoMessageSender').textContent = receiver ? `${sender} -> ${receiver}` : sender;
|
||||||
|
document.getElementById('infoMessageTime').textContent = formatChatTime(
|
||||||
|
normalizeTimestamp(message.ts) || Date.now()
|
||||||
|
);
|
||||||
|
document.getElementById('infoMessageText').textContent = extractMessageText(message.msg);
|
||||||
|
|
||||||
|
if (typeof dialog.showModal === 'function') {
|
||||||
|
dialog.showModal();
|
||||||
|
} else {
|
||||||
|
dialog.show();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeInfoMessageModal() {
|
||||||
|
const dialog = document.getElementById('infoMessageModal');
|
||||||
|
if (dialog && dialog.open) dialog.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractMessagePayload(value) {
|
||||||
|
if (value === null || value === undefined) return null;
|
||||||
|
if (typeof value === 'object') {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
let text = value;
|
||||||
|
const trimmed = text.trim();
|
||||||
|
if (!trimmed) return null;
|
||||||
|
const colonIndex = trimmed.indexOf(':');
|
||||||
|
if (colonIndex > 0 && colonIndex < 80) {
|
||||||
|
const afterColon = trimmed.slice(colonIndex + 1).trim();
|
||||||
|
if ((afterColon.startsWith('{') && afterColon.endsWith('}'))
|
||||||
|
|| (afterColon.startsWith('[') && afterColon.endsWith(']'))) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(afterColon);
|
||||||
|
if (parsed && typeof parsed === 'object') return parsed;
|
||||||
|
} catch (error) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ((trimmed.startsWith('{') && trimmed.endsWith('}'))
|
||||||
|
|| (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(trimmed);
|
||||||
|
if (parsed && typeof parsed === 'object') return parsed;
|
||||||
|
} catch (error) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function extractMessageText(value) {
|
function extractMessageText(value) {
|
||||||
if (typeof value === 'string') return value;
|
const payload = extractMessagePayload(value);
|
||||||
|
if (payload && typeof payload === 'object') {
|
||||||
|
if (Object.prototype.hasOwnProperty.call(payload, 'text')) {
|
||||||
|
return String(payload.text ?? '');
|
||||||
|
}
|
||||||
|
if (Object.prototype.hasOwnProperty.call(payload, 'msg')) {
|
||||||
|
return extractMessageText(payload.msg);
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
if (value === null || value === undefined) return '';
|
if (value === null || value === undefined) return '';
|
||||||
if (typeof value === 'object') return JSON.stringify(value);
|
if (typeof value === 'string') {
|
||||||
|
let text = value;
|
||||||
|
const trimmed = text.trim();
|
||||||
|
if (!trimmed) return '';
|
||||||
|
const colonIndex = trimmed.indexOf(':');
|
||||||
|
if (colonIndex > 0 && colonIndex < 80) {
|
||||||
|
const afterColon = trimmed.slice(colonIndex + 1).trim();
|
||||||
|
if (afterColon) return afterColon;
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
return String(value);
|
return String(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1853,6 +2110,9 @@ async function connectWebSocket() {
|
|||||||
ws.send(JSON.stringify({code: 0, msg: token}));
|
ws.send(JSON.stringify({code: 0, msg: token}));
|
||||||
dispatcherState.authenticated = true;
|
dispatcherState.authenticated = true;
|
||||||
setConnectionStatus('Verbunden', 'connected');
|
setConnectionStatus('Verbunden', 'connected');
|
||||||
|
dispatcherState.lastCode0ReceivedAt = Date.now();
|
||||||
|
dispatcherState.heartbeatWarningShown = false;
|
||||||
|
startHeartbeatMonitoring();
|
||||||
});
|
});
|
||||||
|
|
||||||
ws.addEventListener('message', handleWsMessage);
|
ws.addEventListener('message', handleWsMessage);
|
||||||
@@ -1911,8 +2171,19 @@ function handleWsMessage(event) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.debug('[WS RX]', message);
|
||||||
|
console.log('[WS RX]', JSON.stringify(message));
|
||||||
|
|
||||||
switch (Number(message.code)) {
|
switch (Number(message.code)) {
|
||||||
|
case 0:
|
||||||
|
dispatcherState.lastCode0ReceivedAt = Date.now();
|
||||||
|
dispatcherState.heartbeatWarningShown = false;
|
||||||
|
setConnectionStatus('Verbunden', 'connected');
|
||||||
|
startHeartbeatMonitoring();
|
||||||
|
break;
|
||||||
case 1:
|
case 1:
|
||||||
|
dispatcherState.lastCode0ReceivedAt = Date.now();
|
||||||
|
dispatcherState.heartbeatWarningShown = false;
|
||||||
// Heartbeat des Servers beantworten.
|
// Heartbeat des Servers beantworten.
|
||||||
if (dispatcherState.ws && dispatcherState.ws.readyState === WebSocket.OPEN) {
|
if (dispatcherState.ws && dispatcherState.ws.readyState === WebSocket.OPEN) {
|
||||||
dispatcherState.ws.send(JSON.stringify({code: 2, msg: 'pong'}));
|
dispatcherState.ws.send(JSON.stringify({code: 2, msg: 'pong'}));
|
||||||
@@ -1929,29 +2200,74 @@ function handleWsMessage(event) {
|
|||||||
break;
|
break;
|
||||||
case 1000: {
|
case 1000: {
|
||||||
const text = extractMessageText(message.msg);
|
const text = extractMessageText(message.msg);
|
||||||
addBroadcastChatMessage({
|
dispatcherState.groups.forEach(group => {
|
||||||
sender_id: message.sender_id,
|
addChatMessage(group.id, {
|
||||||
code: message.code,
|
sender_id: message.sender_id,
|
||||||
ts: normalizeTimestamp(message.ts) || Date.now(),
|
code: message.code,
|
||||||
text
|
ts: normalizeTimestamp(message.ts) || Date.now(),
|
||||||
|
text
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
if (Number(message.sender_id) !== currentAccountId) {
|
||||||
|
showInfoMessage({
|
||||||
|
code: message.code,
|
||||||
|
sender_id: message.sender_id,
|
||||||
|
receiver_id: message.receiver_id,
|
||||||
|
msg: text,
|
||||||
|
ts: message.ts
|
||||||
|
});
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 1100: {
|
case 1100: {
|
||||||
const groupId = Number(message.receiver_id);
|
const groupId = Number(message.receiver_id) || Number((message.msg && typeof message.msg === 'object' && message.msg.group_id));
|
||||||
const text = extractMessageText(message.msg);
|
const text = extractMessageText(message.msg);
|
||||||
addChatMessage(groupId, {
|
if (groupId) {
|
||||||
sender_id: message.sender_id,
|
addChatMessage(groupId, {
|
||||||
code: message.code,
|
sender_id: message.sender_id,
|
||||||
ts: normalizeTimestamp(message.ts) || Date.now(),
|
code: message.code,
|
||||||
text
|
ts: normalizeTimestamp(message.ts) || Date.now(),
|
||||||
});
|
text
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (Number(message.sender_id) !== currentAccountId) {
|
||||||
|
showInfoMessage({
|
||||||
|
code: message.code,
|
||||||
|
sender_id: message.sender_id,
|
||||||
|
receiver_id: groupId || message.receiver_id,
|
||||||
|
msg: text,
|
||||||
|
ts: message.ts
|
||||||
|
});
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 2000:
|
case 2000:
|
||||||
handleGroupChatMessage(message);
|
handleGroupChatMessage(message);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
|
if (Number(message.code) >= 1000) {
|
||||||
|
const text = extractMessageText(message.msg);
|
||||||
|
if (Number(message.code) === 1000) {
|
||||||
|
dispatcherState.groups.forEach(group => {
|
||||||
|
addChatMessage(group.id, {
|
||||||
|
sender_id: message.sender_id,
|
||||||
|
code: message.code,
|
||||||
|
ts: normalizeTimestamp(message.ts) || Date.now(),
|
||||||
|
text
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (Number(message.sender_id) !== currentAccountId) {
|
||||||
|
showInfoMessage({
|
||||||
|
code: message.code,
|
||||||
|
sender_id: message.sender_id,
|
||||||
|
receiver_id: message.receiver_id,
|
||||||
|
msg: text,
|
||||||
|
ts: message.ts
|
||||||
|
});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2166,12 +2482,16 @@ function sendSpeakerMessage() {
|
|||||||
const text = input.value.trim();
|
const text = input.value.trim();
|
||||||
if (!text) return;
|
if (!text) return;
|
||||||
|
|
||||||
if (sendWs({code: 1000, msg: text})) {
|
if (sendWs({code: 1000, msg: JSON.stringify({text})})) {
|
||||||
input.value = '';
|
input.value = '';
|
||||||
closeSpeakerModal();
|
closeSpeakerModal();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function openGroupMessageModal() {}
|
||||||
|
function closeGroupMessageModal() {}
|
||||||
|
function sendGroupMessageFromDialog() {}
|
||||||
|
|
||||||
function showAccordionError(text) {
|
function showAccordionError(text) {
|
||||||
const container = document.getElementById('groupAccordion');
|
const container = document.getElementById('groupAccordion');
|
||||||
container.innerHTML = '';
|
container.innerHTML = '';
|
||||||
|
|||||||
@@ -174,11 +174,54 @@
|
|||||||
<h3 id="chatTitle">Chat</h3>
|
<h3 id="chatTitle">Chat</h3>
|
||||||
</header>
|
</header>
|
||||||
<div class="chat-messages dialog-body" id="chatMessages"></div>
|
<div class="chat-messages dialog-body" id="chatMessages"></div>
|
||||||
<footer>
|
<footer class="chat-input-row">
|
||||||
<button type="button" onclick="closeChatModal()">Schließen</button>
|
<input type="text" id="chatInput" class="chat-input" placeholder="Nachricht an Gruppe senden …"
|
||||||
|
autocomplete="off" onkeydown="if(event.key==='Enter'){event.preventDefault();sendChatMessageFromModal();}">
|
||||||
|
<button type="button" class="chat-send-button" onclick="sendChatMessageFromModal()"
|
||||||
|
aria-label="Nachricht senden">➤</button>
|
||||||
|
<button type="button" class="secondary" onclick="closeChatModal()">Schließen</button>
|
||||||
</footer>
|
</footer>
|
||||||
</article>
|
</article>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
|
<!-- Info-Dialog für Nachrichten mit Code >= 1000 -->
|
||||||
|
<dialog id="infoMessageModal">
|
||||||
|
<article>
|
||||||
|
<header>
|
||||||
|
<button class="close" type="button" aria-label="Schließen" onclick="closeInfoMessageModal()"></button>
|
||||||
|
<h3>Nachricht</h3>
|
||||||
|
</header>
|
||||||
|
<div class="dialog-body">
|
||||||
|
<div class="info-message-meta">
|
||||||
|
<div><strong>Absender:</strong> <span id="infoMessageSender"></span></div>
|
||||||
|
<div><strong>Zeit:</strong> <span id="infoMessageTime"></span></div>
|
||||||
|
<div><strong>Code:</strong> <span id="infoMessageCode"></span></div>
|
||||||
|
</div>
|
||||||
|
<div class="info-message-text" id="infoMessageText"></div>
|
||||||
|
</div>
|
||||||
|
<footer>
|
||||||
|
<button type="button" onclick="closeInfoMessageModal()">OK</button>
|
||||||
|
</footer>
|
||||||
|
</article>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<!-- Warnung bei ausbleibenden Heartbeats -->
|
||||||
|
<dialog id="heartbeatWarningModal">
|
||||||
|
<article>
|
||||||
|
<header>
|
||||||
|
<button class="close" type="button" aria-label="Schließen" onclick="closeHeartbeatWarningModal()"></button>
|
||||||
|
<h3>Verbindungswarnung</h3>
|
||||||
|
</header>
|
||||||
|
<div class="dialog-body">
|
||||||
|
<p>Es wurden länger als 90 Sekunden keine Nachrichten mit Code 0 empfangen.</p>
|
||||||
|
</div>
|
||||||
|
<footer>
|
||||||
|
<button type="button" onclick="closeHeartbeatWarningModal()">OK</button>
|
||||||
|
</footer>
|
||||||
|
</article>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}
|
{% block scripts %}
|
||||||
|
|||||||
Reference in new issue
Block a user