opencode ergebnis V0.1
This commit is contained in:
1 parent
61d86a3d83
commit
7e498ebc3f
71 files changed
+28982
-46
No files matched your search
@@ -0,0 +1,79 @@
|
||||
import os
|
||||
from flask import Flask, g, session
|
||||
from config import config
|
||||
from cmbnet.extensions import sock
|
||||
|
||||
|
||||
def create_app(config_name=None):
|
||||
if config_name is None:
|
||||
config_name = os.environ.get('FLASK_ENV', 'development')
|
||||
|
||||
app = Flask(__name__,
|
||||
template_folder='../templates',
|
||||
static_folder='../static')
|
||||
app.config.from_object(config[config_name])
|
||||
|
||||
# Stelle sicher, dass instance Verzeichnis existiert
|
||||
os.makedirs(app.instance_path, exist_ok=True)
|
||||
os.makedirs(app.config['LOG_DIR'], exist_ok=True)
|
||||
|
||||
# Sock initialisieren
|
||||
sock.init_app(app)
|
||||
|
||||
# Datenbank-Setup
|
||||
from cmbnet.db import close_db, init_db_command
|
||||
app.teardown_appcontext(close_db)
|
||||
app.cli.add_command(init_db_command)
|
||||
|
||||
# Tenant und Account für Requests laden
|
||||
@app.before_request
|
||||
def load_current_account():
|
||||
if 'account_id' in session:
|
||||
from cmbnet.db import get_db
|
||||
db = get_db()
|
||||
account = db.execute('SELECT a.*, t.code as tenant_code FROM accounts a JOIN tenants t ON a.tenant_id = t.id WHERE a.id = ?', (session['account_id'],)).fetchone()
|
||||
if account:
|
||||
g.current_account = account
|
||||
g.tenant_id = account['tenant_id']
|
||||
g.tenant_code = account['tenant_code']
|
||||
else:
|
||||
session.clear()
|
||||
|
||||
# Blueprints registrieren
|
||||
from cmbnet.views import auth_bp, views_bp
|
||||
from cmbnet.admin.accounts import admin_accounts_bp
|
||||
from cmbnet.admin.gruppen import admin_gruppen_bp
|
||||
from cmbnet.admin.strassen import admin_strassen_bp
|
||||
from cmbnet.admin.api import admin_api_bp
|
||||
from cmbnet.api.init import api_init_bp
|
||||
from cmbnet.api.auth import api_auth_bp
|
||||
|
||||
app.register_blueprint(auth_bp, url_prefix='/<tenant>')
|
||||
app.register_blueprint(views_bp, url_prefix='/<tenant>')
|
||||
# Admin-Views immer unter /<tenant>/admin/..., damit sie nicht mit den
|
||||
# rollenspezifischen Views (z. B. views.gruppen unter /<tenant>/gruppen)
|
||||
# kollidieren.
|
||||
app.register_blueprint(admin_accounts_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_api_bp, url_prefix='/<tenant>/admin/api')
|
||||
app.register_blueprint(api_init_bp, url_prefix='/<tenant>/api')
|
||||
app.register_blueprint(api_auth_bp, url_prefix='/<tenant>/api')
|
||||
|
||||
# WebSocket Routes laden
|
||||
from cmbnet.ws import routes
|
||||
|
||||
# Heartbeat starten (Code 1 jede Minute, Aufräumen alter Nachrichten)
|
||||
from cmbnet.ws.heartbeat import heartbeat_manager
|
||||
heartbeat_manager.start(
|
||||
app,
|
||||
interval=app.config.get('WS_HEARTBEAT_INTERVAL', 60)
|
||||
)
|
||||
|
||||
# Root redirect
|
||||
@app.route('/')
|
||||
def index():
|
||||
from flask import redirect, url_for
|
||||
return redirect(url_for('auth.login_select'))
|
||||
|
||||
return app
|
||||
@@ -0,0 +1,6 @@
|
||||
from .accounts import admin_accounts_bp
|
||||
from .gruppen import admin_gruppen_bp
|
||||
from .strassen import admin_strassen_bp
|
||||
from .api import admin_api_bp
|
||||
|
||||
admin_bp = admin_accounts_bp
|
||||
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
Accountverwaltung
|
||||
"""
|
||||
from flask import Blueprint, render_template, g
|
||||
from cmbnet.auth import role_required
|
||||
from cmbnet.db import get_db
|
||||
|
||||
admin_accounts_bp = Blueprint('admin', __name__)
|
||||
|
||||
|
||||
@admin_accounts_bp.route('/accounts')
|
||||
@role_required('Administrator')
|
||||
def accounts(**kwargs):
|
||||
"""Accountverwaltung"""
|
||||
db = get_db()
|
||||
accounts = db.execute(
|
||||
'SELECT a.*, t.code as tenant_code FROM accounts a JOIN tenants t ON a.tenant_id = t.id WHERE a.tenant_id = ? ORDER BY a.id',
|
||||
(g.tenant_id,)
|
||||
).fetchall()
|
||||
return render_template('admin/accounts.html', accounts=accounts)
|
||||
@@ -0,0 +1,365 @@
|
||||
"""
|
||||
Admin API Endpunkte
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, g, session
|
||||
from cmbnet.auth import role_required
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.auth import hash_password
|
||||
from cmbnet.models.accounts import AccountModel
|
||||
from cmbnet.models.groups import GroupModel
|
||||
from cmbnet.models.streets import StreetModel
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
from cmbnet.services.history_service import HistoryService
|
||||
from cmbnet.utils.helpers import log_transaction
|
||||
from cmbnet.utils.csv_utils import parse_streets_csv
|
||||
from cmbnet.ws import broker
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
import json
|
||||
|
||||
admin_api_bp = Blueprint('admin_api', __name__)
|
||||
|
||||
|
||||
# === ACCOUNTS ===
|
||||
@admin_api_bp.route('/accounts', methods=['POST'])
|
||||
@role_required('Administrator')
|
||||
def create_account(**kwargs):
|
||||
data = request.get_json()
|
||||
name = data.get('name', '').strip()
|
||||
password = data.get('password', '')
|
||||
role = data.get('role', 'Gast')
|
||||
|
||||
if not name or not password:
|
||||
return jsonify({'error': 'Name und Passwort erforderlich'}), 400
|
||||
|
||||
existing = AccountModel.get_by_name_and_tenant(name, g.tenant_id)
|
||||
if existing:
|
||||
return jsonify({'error': 'Account existiert bereits'}), 400
|
||||
|
||||
password_hash = hash_password(password)
|
||||
account_id = AccountModel.create(g.tenant_id, name, password_hash, role)
|
||||
log_transaction('account.create', 'account', account_id, {'name': name, 'role': role})
|
||||
|
||||
return jsonify({'success': True, 'id': account_id})
|
||||
|
||||
|
||||
@admin_api_bp.route('/accounts/<int:account_id>/role', methods=['POST'])
|
||||
@role_required('Administrator')
|
||||
def update_account_role(account_id, **kwargs):
|
||||
data = request.get_json()
|
||||
role = data.get('role')
|
||||
AccountModel.update_role(account_id, g.tenant_id, role)
|
||||
log_transaction('account.role_change', 'account', account_id, {'role': role})
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/accounts/<int:account_id>/password', methods=['POST'])
|
||||
@role_required('Administrator')
|
||||
def reset_password(account_id, **kwargs):
|
||||
data = request.get_json()
|
||||
password = data.get('password', '')
|
||||
if not password:
|
||||
return jsonify({'error': 'Passwort erforderlich'}), 400
|
||||
password_hash = hash_password(password)
|
||||
AccountModel.set_password(account_id, g.tenant_id, password_hash)
|
||||
log_transaction('account.password_reset', 'account', account_id, {})
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/accounts/<int:account_id>', methods=['DELETE'])
|
||||
@role_required('Administrator')
|
||||
def delete_account(account_id, **kwargs):
|
||||
AccountModel.delete(account_id, g.tenant_id)
|
||||
log_transaction('account.delete', 'account', account_id, {})
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
# === GRUPPEN ===
|
||||
@admin_api_bp.route('/gruppen', methods=['POST'])
|
||||
@role_required('Administrator')
|
||||
def create_group(**kwargs):
|
||||
data = request.get_json() or {}
|
||||
aliasname = str(data.get('aliasname') or '').strip()
|
||||
account_id = data.get('account_id')
|
||||
db = get_db()
|
||||
|
||||
if account_id == '' or account_id is None:
|
||||
account_id = None
|
||||
else:
|
||||
try:
|
||||
account_id = int(account_id)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'error': 'Ungültiger Account'}), 400
|
||||
|
||||
account = AccountModel.get_by_id(account_id, g.tenant_id)
|
||||
if not account or account['role'] != 'Gruppe':
|
||||
return jsonify({'error': 'Account muss die Rolle "Gruppe" haben'}), 400
|
||||
|
||||
linked = db.execute(
|
||||
'SELECT id FROM groups WHERE tenant_id = ? AND account_id = ?',
|
||||
(g.tenant_id, account_id)
|
||||
).fetchone()
|
||||
if linked:
|
||||
return jsonify({'error': 'Dieser Account ist bereits mit einer Gruppe verknüpft'}), 400
|
||||
|
||||
group_id = GroupModel.create(g.tenant_id, aliasname, account_id, 'offen')
|
||||
db.execute(
|
||||
'INSERT INTO group_state_history (tenant_id, group_id, from_state, to_state, actor_account_id) VALUES (?, ?, ?, ?, ?)',
|
||||
(g.tenant_id, group_id, None, 'offen', session['account_id'])
|
||||
)
|
||||
db.commit()
|
||||
log_transaction('group.create', 'group', group_id, {'aliasname': aliasname, 'account_id': account_id})
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
GroupsService.load_from_db(g.tenant_id)
|
||||
return jsonify({'success': True, 'id': group_id})
|
||||
|
||||
|
||||
@admin_api_bp.route('/gruppen/<int:group_id>', methods=['POST'])
|
||||
@role_required('Administrator')
|
||||
def update_group(group_id, **kwargs):
|
||||
data = request.get_json() or {}
|
||||
db = get_db()
|
||||
old = GroupModel.get_by_id(group_id, g.tenant_id)
|
||||
if not old:
|
||||
return jsonify({'error': 'Gruppe nicht gefunden'}), 404
|
||||
|
||||
updates = {}
|
||||
if 'aliasname' in data:
|
||||
updates['aliasname'] = data['aliasname']
|
||||
|
||||
if 'account_id' in data:
|
||||
account_id = data['account_id']
|
||||
if account_id in ('', None):
|
||||
account_id = None
|
||||
else:
|
||||
try:
|
||||
account_id = int(account_id)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'error': 'Ungültiger Account'}), 400
|
||||
|
||||
account = AccountModel.get_by_id(account_id, g.tenant_id)
|
||||
if not account or account['role'] != 'Gruppe':
|
||||
return jsonify({'error': 'Account muss die Rolle "Gruppe" haben'}), 400
|
||||
|
||||
linked = db.execute(
|
||||
'SELECT id FROM groups WHERE tenant_id = ? AND account_id = ? AND id != ?',
|
||||
(g.tenant_id, account_id, group_id)
|
||||
).fetchone()
|
||||
if linked:
|
||||
return jsonify({'error': 'Dieser Account ist bereits mit einer Gruppe verknüpft'}), 400
|
||||
|
||||
if account_id != old['account_id']:
|
||||
updates['account_id'] = account_id
|
||||
|
||||
allowed_states = {'offen', 'unterwegs', 'online', 'pausierend', 'fertig'}
|
||||
state_changed = False
|
||||
if 'state' in data:
|
||||
new_state = data['state']
|
||||
if new_state not in allowed_states:
|
||||
return jsonify({'error': 'Ungültiger State'}), 400
|
||||
if new_state != old['state']:
|
||||
updates['state'] = new_state
|
||||
state_changed = True
|
||||
|
||||
if not updates:
|
||||
return jsonify({'success': True})
|
||||
|
||||
GroupModel.update(group_id, g.tenant_id, **updates)
|
||||
|
||||
if state_changed:
|
||||
db.execute(
|
||||
'INSERT INTO group_state_history (tenant_id, group_id, from_state, to_state, actor_account_id) VALUES (?, ?, ?, ?, ?)',
|
||||
(g.tenant_id, group_id, old['state'], updates['state'], session['account_id'])
|
||||
)
|
||||
db.commit()
|
||||
msg = WSMessage(sender_id=session['account_id'], code=200,
|
||||
msg=json.dumps({'group_id': group_id, 'state': updates['state'], 'actor': session['account_id']}))
|
||||
try:
|
||||
broker.route_message(g.tenant_id, msg)
|
||||
except Exception as e:
|
||||
print(f'Broker error: {e}')
|
||||
|
||||
log_transaction('group.update', 'group', group_id, updates)
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
GroupsService.load_from_db(g.tenant_id)
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/gruppen/<int:group_id>', methods=['DELETE'])
|
||||
@role_required('Administrator')
|
||||
def delete_group(group_id, **kwargs):
|
||||
GroupModel.delete(group_id, g.tenant_id)
|
||||
log_transaction('group.delete', 'group', group_id, {})
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/gruppen/<int:group_id>/history')
|
||||
@role_required('Administrator')
|
||||
def group_history(group_id, **kwargs):
|
||||
db = get_db()
|
||||
history = db.execute(
|
||||
'SELECT h.*, a.name as actor_name FROM group_state_history h LEFT JOIN accounts a ON h.actor_account_id = a.id WHERE h.group_id = ? AND h.tenant_id = ? ORDER BY h.created_at DESC',
|
||||
(group_id, g.tenant_id)
|
||||
).fetchall()
|
||||
return jsonify([dict(row) for row in history])
|
||||
|
||||
|
||||
@admin_api_bp.route('/gruppen/<int:group_id>/history/<int:hist_id>/revert', methods=['POST'])
|
||||
@role_required('Administrator')
|
||||
def revert_group_hist(group_id, hist_id, **kwargs):
|
||||
success, msg = HistoryService.revert_group(g.tenant_id, group_id, hist_id, session['account_id'])
|
||||
if not success:
|
||||
return jsonify({'error': msg}), 400
|
||||
return jsonify({'success': True, 'message': msg})
|
||||
|
||||
|
||||
@admin_api_bp.route('/gruppen/<int:group_id>/position/history/<int:hist_id>', methods=['POST'])
|
||||
@role_required('Administrator')
|
||||
def set_group_position_from_history(group_id, hist_id, **kwargs):
|
||||
success, msg = HistoryService.set_group_position_from_history(
|
||||
g.tenant_id, group_id, hist_id, session['account_id']
|
||||
)
|
||||
if not success:
|
||||
return jsonify({'error': msg}), 400
|
||||
return jsonify({'success': True, 'message': msg})
|
||||
|
||||
|
||||
@admin_api_bp.route('/gruppen/<int:group_id>/position', methods=['DELETE'])
|
||||
@role_required('Administrator')
|
||||
def clear_group_position(group_id, **kwargs):
|
||||
success, msg = HistoryService.clear_group_position(
|
||||
g.tenant_id, group_id, session['account_id']
|
||||
)
|
||||
if not success:
|
||||
return jsonify({'error': msg}), 400
|
||||
return jsonify({'success': True, 'message': msg})
|
||||
|
||||
|
||||
# === STRASSEN ===
|
||||
@admin_api_bp.route('/strassen', methods=['POST'])
|
||||
@role_required('Administrator')
|
||||
def create_street(**kwargs):
|
||||
data = request.get_json()
|
||||
name = data.get('name', '').strip()
|
||||
if not name:
|
||||
return jsonify({'error': 'Name erforderlich'}), 400
|
||||
street_id = StreetModel.create(g.tenant_id, name,
|
||||
hn_min=data.get('hn_min'),
|
||||
hn_max=data.get('hn_max'),
|
||||
bbox=data.get('bbox'),
|
||||
state='unbearbeitet',
|
||||
group_id=None)
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'INSERT INTO street_state_history (tenant_id, street_id, from_state, to_state, group_id, actor_account_id) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(g.tenant_id, street_id, None, 'unbearbeitet', None, session['account_id'])
|
||||
)
|
||||
db.commit()
|
||||
log_transaction('street.create', 'street', street_id, {'name': name})
|
||||
return jsonify({'success': True, 'id': street_id})
|
||||
|
||||
|
||||
@admin_api_bp.route('/strassen/<int:street_id>', methods=['POST'])
|
||||
@role_required('Administrator')
|
||||
def update_street(street_id, **kwargs):
|
||||
data = request.get_json()
|
||||
db = get_db()
|
||||
old = StreetModel.get_by_id(street_id, g.tenant_id)
|
||||
if not old:
|
||||
return jsonify({'error': 'Straße nicht gefunden'}), 404
|
||||
|
||||
changes = {}
|
||||
for key in ['name', 'hn_min', 'hn_max', 'bbox', 'group_id']:
|
||||
if key in data:
|
||||
if key == 'group_id' and (data[key] == '' or data[key] is None):
|
||||
changes[key] = None
|
||||
elif key in ['hn_min', 'hn_max'] and data[key] != '' and data[key] is not None:
|
||||
try:
|
||||
changes[key] = int(data[key])
|
||||
except:
|
||||
changes[key] = data[key]
|
||||
else:
|
||||
changes[key] = data[key]
|
||||
|
||||
if 'state' in data and data['state'] != old['state']:
|
||||
changes['state'] = data['state']
|
||||
if data['state'] == 'unbearbeitet':
|
||||
changes['group_id'] = None
|
||||
db.execute(
|
||||
'INSERT INTO street_state_history (tenant_id, street_id, from_state, to_state, group_id, actor_account_id) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(g.tenant_id, street_id, old['state'], data['state'], changes.get('group_id', old['group_id']), session['account_id'])
|
||||
)
|
||||
# Code 100
|
||||
msg = WSMessage(sender_id=session['account_id'], code=100,
|
||||
msg=json.dumps({'name': old['name'], 'state': data['state'], 'actor': session['account_id'],
|
||||
'street_id': street_id, 'group_id': changes.get('group_id', old['group_id'])}))
|
||||
try:
|
||||
broker.route_message(g.tenant_id, msg)
|
||||
except:
|
||||
pass
|
||||
|
||||
if changes:
|
||||
StreetModel.update(street_id, g.tenant_id, **changes)
|
||||
log_transaction('street.update', 'street', street_id, changes)
|
||||
|
||||
db.commit()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/strassen/<int:street_id>', methods=['DELETE'])
|
||||
@role_required('Administrator')
|
||||
def delete_street(street_id, **kwargs):
|
||||
StreetModel.delete(street_id, g.tenant_id)
|
||||
log_transaction('street.delete', 'street', street_id, {})
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/strassen/<int:street_id>/history')
|
||||
@role_required('Administrator')
|
||||
def street_history(street_id, **kwargs):
|
||||
db = get_db()
|
||||
history = db.execute(
|
||||
'SELECT h.*, a.name as actor_name FROM street_state_history h LEFT JOIN accounts a ON h.actor_account_id = a.id WHERE h.street_id = ? AND h.tenant_id = ? ORDER BY h.created_at DESC',
|
||||
(street_id, g.tenant_id)
|
||||
).fetchall()
|
||||
return jsonify([dict(row) for row in history])
|
||||
|
||||
|
||||
@admin_api_bp.route('/strassen/<int:street_id>/history/<int:hist_id>/revert', methods=['POST'])
|
||||
@role_required('Administrator')
|
||||
def revert_street_hist(street_id, hist_id, **kwargs):
|
||||
success, msg = HistoryService.revert_street(g.tenant_id, street_id, hist_id, session['account_id'])
|
||||
if not success:
|
||||
return jsonify({'error': msg}), 400
|
||||
return jsonify({'success': True, 'message': msg})
|
||||
|
||||
|
||||
@admin_api_bp.route('/strassen/import', methods=['POST'])
|
||||
@role_required('Administrator')
|
||||
def import_streets(**kwargs):
|
||||
if 'file' not in request.files:
|
||||
return jsonify({'error': 'Keine Datei'}), 400
|
||||
file = request.files['file']
|
||||
if file.filename == '':
|
||||
return jsonify({'error': 'Keine Datei ausgewählt'}), 400
|
||||
|
||||
content = file.read()
|
||||
if len(content) > 5_000_000:
|
||||
return jsonify({'error': 'Datei zu groß'}), 400
|
||||
|
||||
streets_data = parse_streets_csv(content)
|
||||
db = get_db()
|
||||
count = 0
|
||||
for s in streets_data:
|
||||
street_id = StreetModel.create(g.tenant_id, s['name'], s['hn_min'], s['hn_max'], s['bbox'], 'unbearbeitet', None)
|
||||
db.execute(
|
||||
'INSERT INTO street_state_history (tenant_id, street_id, from_state, to_state, group_id, actor_account_id) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(g.tenant_id, street_id, None, 'unbearbeitet', None, session['account_id'])
|
||||
)
|
||||
log_transaction('street.import', 'street', street_id, {'name': s['name']})
|
||||
count += 1
|
||||
|
||||
db.commit()
|
||||
return jsonify({'success': True, 'count': count})
|
||||
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
Gruppenverwaltung
|
||||
"""
|
||||
from flask import Blueprint, render_template, g
|
||||
from cmbnet.auth import role_required
|
||||
from cmbnet.db import get_db
|
||||
|
||||
admin_gruppen_bp = Blueprint('admin_gruppen', __name__)
|
||||
|
||||
|
||||
@admin_gruppen_bp.route('/gruppen')
|
||||
@role_required('Administrator')
|
||||
def gruppen(**kwargs):
|
||||
"""Gruppenverwaltung"""
|
||||
db = get_db()
|
||||
gruppen = db.execute(
|
||||
'SELECT g.*, a.name as account_name FROM groups g LEFT JOIN accounts a ON g.account_id = a.id WHERE g.tenant_id = ? ORDER BY g.id',
|
||||
(g.tenant_id,)
|
||||
).fetchall()
|
||||
accounts = db.execute(
|
||||
"SELECT * FROM accounts WHERE tenant_id = ? AND role = 'Gruppe'",
|
||||
(g.tenant_id,)
|
||||
).fetchall()
|
||||
return render_template('admin/gruppen.html', gruppen=gruppen, accounts=accounts)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
Straßenverwaltung
|
||||
"""
|
||||
from flask import Blueprint, render_template, g
|
||||
from cmbnet.auth import role_required
|
||||
from cmbnet.db import get_db
|
||||
|
||||
admin_strassen_bp = Blueprint('admin_strassen', __name__)
|
||||
|
||||
|
||||
@admin_strassen_bp.route('/strassen')
|
||||
@role_required('Administrator')
|
||||
def strassen(**kwargs):
|
||||
"""Straßenverwaltung"""
|
||||
db = get_db()
|
||||
strassen = db.execute(
|
||||
'SELECT s.*, g.aliasname as group_name FROM streets s LEFT JOIN groups g ON s.group_id = g.id WHERE s.tenant_id = ? ORDER BY s.name',
|
||||
(g.tenant_id,)
|
||||
).fetchall()
|
||||
gruppen = db.execute(
|
||||
'SELECT * FROM groups WHERE tenant_id = ? ORDER BY id',
|
||||
(g.tenant_id,)
|
||||
).fetchall()
|
||||
return render_template('admin/strassen.html', strassen=strassen, gruppen=gruppen)
|
||||
@@ -0,0 +1,4 @@
|
||||
from .init import api_init_bp
|
||||
from .auth import api_auth_bp
|
||||
|
||||
api_bp = api_init_bp
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
API Auth Endpunkte
|
||||
"""
|
||||
from flask import Blueprint, jsonify, g, session
|
||||
from cmbnet.auth import login_required
|
||||
from cmbnet.db import get_db
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
api_auth_bp = Blueprint('api_auth', __name__)
|
||||
|
||||
|
||||
@api_auth_bp.route('/auth/ws-token', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def ws_token(**kwargs):
|
||||
"""Erzeugt ein Zugriffstoken für WebSocket-Authentifizierung"""
|
||||
db = get_db()
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.now() + timedelta(hours=1)
|
||||
|
||||
db.execute(
|
||||
'INSERT INTO ws_tokens (tenant_id, account_id, token, expires_at) VALUES (?, ?, ?, ?)',
|
||||
(g.tenant_id, session['account_id'], token, expires_at)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
return jsonify({'token': token})
|
||||
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
API Endpunkte für Initialdaten
|
||||
"""
|
||||
from flask import Blueprint, jsonify, g
|
||||
from cmbnet.auth import login_required
|
||||
from cmbnet.services.streets_service import StreetsService
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
|
||||
api_init_bp = Blueprint('api_init', __name__)
|
||||
|
||||
|
||||
@api_init_bp.route('/init/streets')
|
||||
@login_required
|
||||
def init_streets(**kwargs):
|
||||
"""Liefert alle Straßen für den Initialload"""
|
||||
streets = StreetsService.get_all_for_init(g.tenant_id)
|
||||
return jsonify(streets)
|
||||
|
||||
|
||||
@api_init_bp.route('/init/groups')
|
||||
@login_required
|
||||
def init_groups(**kwargs):
|
||||
"""Liefert alle Gruppen für den Initialload (aus Cache)"""
|
||||
groups_dict = GroupsService.get_all(g.tenant_id)
|
||||
groups_list = list(groups_dict.values())
|
||||
return jsonify(groups_list)
|
||||
@@ -0,0 +1,2 @@
|
||||
from .decorators import login_required, role_required, tenant_required
|
||||
from .utils import verify_password, hash_password
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
Authentifizierungs-Decoratoren
|
||||
"""
|
||||
from functools import wraps
|
||||
from flask import session, redirect, url_for, request, g, abort, flash
|
||||
|
||||
|
||||
def _get_tenant_for_redirect():
|
||||
"""Hilfsfunktion um Tenant für Redirect zu ermitteln"""
|
||||
if hasattr(g, 'tenant_code') and g.tenant_code:
|
||||
return g.tenant_code
|
||||
if 'tenant_code' in session:
|
||||
return session['tenant_code']
|
||||
# Versuche aus URL
|
||||
tenant = request.view_args.get('tenant') if request.view_args else None
|
||||
if tenant:
|
||||
return tenant
|
||||
return 'RV'
|
||||
|
||||
|
||||
def login_required(f):
|
||||
"""Decorator für routes die einen eingeloggten Account erfordern"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if 'account_id' not in session:
|
||||
return redirect(url_for('auth.login', tenant=_get_tenant_for_redirect()))
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
|
||||
def role_required(roles):
|
||||
"""Decorator für routes die bestimmte Rollen erfordern"""
|
||||
if isinstance(roles, str):
|
||||
roles = [roles]
|
||||
|
||||
def decorator(f):
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if 'account_id' not in session:
|
||||
return redirect(url_for('auth.login', tenant=_get_tenant_for_redirect()))
|
||||
|
||||
account_role = session.get('role')
|
||||
if account_role not in roles:
|
||||
abort(403)
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
return decorator
|
||||
|
||||
|
||||
def tenant_required(f):
|
||||
"""Decorator für tenant-spezifische Routes"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
# Tenant wird bereits in der Route über URL extrahiert
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
@@ -0,0 +1,14 @@
|
||||
"""
|
||||
Authentifizierungs-Hilfsfunktionen
|
||||
"""
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
"""Erstellt einen Passwort-Hash"""
|
||||
return generate_password_hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash, password):
|
||||
"""Überprüft ein Passwort gegen den Hash"""
|
||||
return check_password_hash(password_hash, password)
|
||||
Whitespace-only changes.
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
Transaktionslogging für CMBNet
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from flask import current_app
|
||||
|
||||
|
||||
def write_transaction_log(tenant_id, actor_id, actor_name, action, entity_type, entity_id, details=None):
|
||||
"""
|
||||
Schreibt einen lesbaren Eintrag ins tägliche Logfile
|
||||
"""
|
||||
log_dir = Path(current_app.config['LOG_DIR'])
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
date_str = datetime.now().strftime('%Y-%m-%d')
|
||||
log_file = log_dir / f'cmbnet-{date_str}.log'
|
||||
|
||||
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
|
||||
actor_str = f"{actor_id}({actor_name})" if actor_id and actor_name else "SYSTEM"
|
||||
|
||||
if isinstance(details, dict):
|
||||
details_str = str(details)
|
||||
elif details is None:
|
||||
details_str = "{}"
|
||||
else:
|
||||
details_str = str(details)
|
||||
|
||||
log_line = f"{timestamp} [TENANT:{get_tenant_code(tenant_id)}] [ACTOR:{actor_str}] ACTION:{action} ENTITY:{entity_type}:{entity_id} DETAILS:{details_str}\n"
|
||||
|
||||
with open(log_file, 'a', encoding='utf-8') as f:
|
||||
f.write(log_line)
|
||||
|
||||
|
||||
def get_tenant_code(tenant_id):
|
||||
"""Holt den Tenant-Code für die Logausgabe"""
|
||||
from cmbnet.db import get_db
|
||||
db = get_db()
|
||||
tenant = db.execute('SELECT code FROM tenants WHERE id = ?', (tenant_id,)).fetchone()
|
||||
return tenant['code'] if tenant else str(tenant_id)
|
||||
@@ -0,0 +1 @@
|
||||
from .database import get_db, close_db, init_db_command
|
||||
@@ -0,0 +1,39 @@
|
||||
import sqlite3
|
||||
import os
|
||||
from pathlib import Path
|
||||
from flask import current_app, g
|
||||
import click
|
||||
|
||||
|
||||
def get_db():
|
||||
"""Stellt eine Datenbankverbindung für den aktuellen Request bereit"""
|
||||
if 'db' not in g:
|
||||
db_path = current_app.config['DATABASE_PATH']
|
||||
# Stelle sicher, dass das instance Verzeichnis existiert
|
||||
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
g.db = sqlite3.connect(db_path)
|
||||
g.db.row_factory = sqlite3.Row
|
||||
return g.db
|
||||
|
||||
|
||||
def close_db(e=None):
|
||||
"""Schließt die Datenbankverbindung am Ende des Requests"""
|
||||
db = g.pop('db', None)
|
||||
if db is not None:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
"""Initialisiert die Datenbank mit dem Schema"""
|
||||
db = get_db()
|
||||
schema_path = Path(current_app.root_path).parent / 'migrations' / 'schema.sql'
|
||||
with open(schema_path, 'r', encoding='utf-8') as f:
|
||||
db.executescript(f.read())
|
||||
db.commit()
|
||||
|
||||
|
||||
@click.command('init-db')
|
||||
def init_db_command():
|
||||
"""CLI-Befehl zum Initialisieren der Datenbank"""
|
||||
init_db()
|
||||
click.echo('Datenbank wurde initialisiert.')
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
Erweiterungen für die CMBNet Anwendung
|
||||
|
||||
Hier liegen gemeinsame Instanzen, die von mehreren Modulen benötigt werden.
|
||||
Wichtig ist eine einzige Sock-Instanz: Routen werden auf diesem Objekt
|
||||
registriert und es muss anschließend mit der Flask-App initialisiert werden.
|
||||
"""
|
||||
from flask_sock import Sock
|
||||
|
||||
sock = Sock()
|
||||
@@ -0,0 +1,3 @@
|
||||
from .accounts import AccountModel
|
||||
from .groups import GroupModel
|
||||
from .streets import StreetModel
|
||||
@@ -0,0 +1,66 @@
|
||||
"""
|
||||
Account Model - Abstraktionsschicht für Datenbankzugriffe
|
||||
"""
|
||||
from cmbnet.db import get_db
|
||||
|
||||
|
||||
class AccountModel:
|
||||
@staticmethod
|
||||
def get_all_by_tenant(tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM accounts WHERE tenant_id = ? ORDER BY id',
|
||||
(tenant_id,)
|
||||
).fetchall()
|
||||
|
||||
@staticmethod
|
||||
def get_by_id(account_id, tenant_id=None):
|
||||
db = get_db()
|
||||
if tenant_id:
|
||||
return db.execute(
|
||||
'SELECT * FROM accounts WHERE id = ? AND tenant_id = ?',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
return db.execute('SELECT * FROM accounts WHERE id = ?', (account_id,)).fetchone()
|
||||
|
||||
@staticmethod
|
||||
def get_by_name_and_tenant(name, tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM accounts WHERE name = ? AND tenant_id = ?',
|
||||
(name, tenant_id)
|
||||
).fetchone()
|
||||
|
||||
@staticmethod
|
||||
def create(tenant_id, name, password_hash, role):
|
||||
db = get_db()
|
||||
cursor = db.execute(
|
||||
'INSERT INTO accounts (tenant_id, name, password_hash, role) VALUES (?, ?, ?, ?)',
|
||||
(tenant_id, name, password_hash, role)
|
||||
)
|
||||
db.commit()
|
||||
return cursor.lastrowid
|
||||
|
||||
@staticmethod
|
||||
def update_role(account_id, tenant_id, role):
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'UPDATE accounts SET role = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND tenant_id = ?',
|
||||
(role, account_id, tenant_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
@staticmethod
|
||||
def set_password(account_id, tenant_id, password_hash):
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'UPDATE accounts SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND tenant_id = ?',
|
||||
(password_hash, account_id, tenant_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
@staticmethod
|
||||
def delete(account_id, tenant_id):
|
||||
db = get_db()
|
||||
db.execute('DELETE FROM accounts WHERE id = ? AND tenant_id = ?', (account_id, tenant_id))
|
||||
db.commit()
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
Group Model - Abstraktionsschicht für Datenbankzugriffe
|
||||
"""
|
||||
from cmbnet.db import get_db
|
||||
|
||||
|
||||
class GroupModel:
|
||||
@staticmethod
|
||||
def get_all_by_tenant(tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM groups WHERE tenant_id = ? ORDER BY id',
|
||||
(tenant_id,)
|
||||
).fetchall()
|
||||
|
||||
@staticmethod
|
||||
def get_by_id(group_id, tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
|
||||
@staticmethod
|
||||
def get_by_account_id(account_id, tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
|
||||
@staticmethod
|
||||
def create(tenant_id, aliasname, account_id=None, state='offen'):
|
||||
db = get_db()
|
||||
cursor = db.execute(
|
||||
'INSERT INTO groups (tenant_id, aliasname, account_id, state) VALUES (?, ?, ?, ?)',
|
||||
(tenant_id, aliasname, account_id, state)
|
||||
)
|
||||
db.commit()
|
||||
return cursor.lastrowid
|
||||
|
||||
@staticmethod
|
||||
def update(group_id, tenant_id, **kwargs):
|
||||
db = get_db()
|
||||
allowed = ['aliasname', 'state', 'account_id', 'last_lat', 'last_lon', 'last_pos_at']
|
||||
updates = []
|
||||
values = []
|
||||
for k, v in kwargs.items():
|
||||
if k in allowed:
|
||||
updates.append(f'{k} = ?')
|
||||
values.append(v)
|
||||
if not updates:
|
||||
return
|
||||
updates.append('updated_at = CURRENT_TIMESTAMP')
|
||||
values.extend([group_id, tenant_id])
|
||||
db.execute(f'UPDATE groups SET {", ".join(updates)} WHERE id = ? AND tenant_id = ?', values)
|
||||
db.commit()
|
||||
|
||||
@staticmethod
|
||||
def delete(group_id, tenant_id):
|
||||
db = get_db()
|
||||
db.execute('DELETE FROM groups WHERE id = ? AND tenant_id = ?', (group_id, tenant_id))
|
||||
db.commit()
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
Street Model - Abstraktionsschicht für Datenbankzugriffe
|
||||
"""
|
||||
from cmbnet.db import get_db
|
||||
|
||||
|
||||
class StreetModel:
|
||||
@staticmethod
|
||||
def get_all_by_tenant(tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM streets WHERE tenant_id = ? ORDER BY name',
|
||||
(tenant_id,)
|
||||
).fetchall()
|
||||
|
||||
@staticmethod
|
||||
def get_by_id(street_id, tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM streets WHERE id = ? AND tenant_id = ?',
|
||||
(street_id, tenant_id)
|
||||
).fetchone()
|
||||
|
||||
@staticmethod
|
||||
def get_by_group_id(group_id, tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM streets WHERE group_id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchall()
|
||||
|
||||
@staticmethod
|
||||
def create(tenant_id, name, hn_min=None, hn_max=None, bbox=None, state='unbearbeitet', group_id=None):
|
||||
db = get_db()
|
||||
cursor = db.execute(
|
||||
'INSERT INTO streets (tenant_id, name, hn_min, hn_max, bbox, state, group_id) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
(tenant_id, name, hn_min, hn_max, bbox, state, group_id)
|
||||
)
|
||||
db.commit()
|
||||
return cursor.lastrowid
|
||||
|
||||
@staticmethod
|
||||
def update(street_id, tenant_id, **kwargs):
|
||||
db = get_db()
|
||||
allowed = ['name', 'state', 'group_id', 'hn_min', 'hn_max', 'bbox']
|
||||
updates = []
|
||||
values = []
|
||||
for k, v in kwargs.items():
|
||||
if k in allowed:
|
||||
updates.append(f'{k} = ?')
|
||||
values.append(v)
|
||||
if not updates:
|
||||
return
|
||||
updates.append('updated_at = CURRENT_TIMESTAMP')
|
||||
values.extend([street_id, tenant_id])
|
||||
db.execute(f'UPDATE streets SET {", ".join(updates)} WHERE id = ? AND tenant_id = ?', values)
|
||||
db.commit()
|
||||
|
||||
@staticmethod
|
||||
def delete(street_id, tenant_id):
|
||||
db = get_db()
|
||||
db.execute('DELETE FROM streets WHERE id = ? AND tenant_id = ?', (street_id, tenant_id))
|
||||
db.commit()
|
||||
@@ -0,0 +1,3 @@
|
||||
from .groups_service import GroupsService
|
||||
from .streets_service import StreetsService
|
||||
from .accounts_service import AccountsService
|
||||
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
Accounts Service - Geschäftslogik für Accounts
|
||||
"""
|
||||
from cmbnet.models.accounts import AccountModel
|
||||
from cmbnet.auth import verify_password, hash_password
|
||||
|
||||
|
||||
class AccountsService:
|
||||
@staticmethod
|
||||
def verify_account_password(account, password):
|
||||
"""Überprüft Passwort gegen Account"""
|
||||
if not account:
|
||||
return False
|
||||
return verify_password(account['password_hash'], password)
|
||||
|
||||
@staticmethod
|
||||
def has_role(account, roles):
|
||||
"""Prüft, ob Account eine der angegebenen Rollen hat"""
|
||||
if isinstance(roles, str):
|
||||
roles = [roles]
|
||||
if not account:
|
||||
return False
|
||||
return account['role'] in roles
|
||||
|
||||
@staticmethod
|
||||
def create_account(tenant_id, name, password, role):
|
||||
"""Erstellt einen neuen Account"""
|
||||
password_hash = hash_password(password)
|
||||
return AccountModel.create(tenant_id, name, password_hash, role)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""
|
||||
Groups Service - Geschäftslogik für Gruppen mit In-Memory-Caching
|
||||
"""
|
||||
from cmbnet.models.groups import GroupModel
|
||||
from cmbnet.models.streets import StreetModel
|
||||
from cmbnet.models.accounts import AccountModel
|
||||
from cmbnet.db import get_db
|
||||
|
||||
|
||||
class GroupsService:
|
||||
# In-Memory Cache: groups_cache[tenant_id][group_id] = group_dict
|
||||
_cache = {}
|
||||
|
||||
@classmethod
|
||||
def load_from_db(cls, tenant_id):
|
||||
"""Lädt alle Gruppen eines Mandanten aus der Datenbank in den Cache"""
|
||||
groups = GroupModel.get_all_by_tenant(tenant_id)
|
||||
if tenant_id not in cls._cache:
|
||||
cls._cache[tenant_id] = {}
|
||||
|
||||
for group in groups:
|
||||
cls._cache[tenant_id][group['id']] = {
|
||||
'id': group['id'],
|
||||
'tenant_id': group['tenant_id'],
|
||||
'aliasname': group['aliasname'],
|
||||
'state': group['state'],
|
||||
'last_lat': group['last_lat'],
|
||||
'last_lon': group['last_lon'],
|
||||
'last_pos_at': group['last_pos_at'],
|
||||
'account_id': group['account_id'],
|
||||
'created_at': group['created_at'],
|
||||
'updated_at': group['updated_at']
|
||||
}
|
||||
return cls._cache[tenant_id]
|
||||
|
||||
@classmethod
|
||||
def get_all(cls, tenant_id, force_reload=False):
|
||||
"""Gibt alle Gruppen für einen Mandanten zurück (aus Cache)"""
|
||||
if force_reload or tenant_id not in cls._cache or not cls._cache[tenant_id]:
|
||||
cls.load_from_db(tenant_id)
|
||||
return cls._cache.get(tenant_id, {})
|
||||
|
||||
@classmethod
|
||||
def get_by_id(cls, tenant_id, group_id):
|
||||
"""Gibt eine spezifische Gruppe aus dem Cache zurück"""
|
||||
if tenant_id not in cls._cache:
|
||||
cls.load_from_db(tenant_id)
|
||||
return cls._cache.get(tenant_id, {}).get(group_id)
|
||||
|
||||
@classmethod
|
||||
def invalidate(cls, tenant_id):
|
||||
"""Invalidiert den Cache für einen Mandanten (erzwingt Neuladen)"""
|
||||
if tenant_id in cls._cache:
|
||||
cls._cache[tenant_id] = {}
|
||||
|
||||
@classmethod
|
||||
def invalidate_all(cls):
|
||||
"""Invalidiert den gesamten Cache"""
|
||||
cls._cache = {}
|
||||
|
||||
@classmethod
|
||||
def is_account_linked(cls, account_id, group_id, tenant_id):
|
||||
"""Prüft, ob ein Account mit einer Gruppe verknüpft ist"""
|
||||
group = cls.get_by_id(tenant_id, group_id)
|
||||
if not group:
|
||||
return False
|
||||
return group.get('account_id') == account_id
|
||||
|
||||
@classmethod
|
||||
def get_accounts_for_group(cls, group_id, tenant_id):
|
||||
"""Gibt alle mit einer Gruppe verknüpften Accounts zurück"""
|
||||
group = cls.get_by_id(tenant_id, group_id)
|
||||
if not group or not group.get('account_id'):
|
||||
return []
|
||||
account = AccountModel.get_by_id(group['account_id'], tenant_id)
|
||||
return [account] if account else []
|
||||
|
||||
@classmethod
|
||||
def get_streets_for_group(cls, group_id, tenant_id):
|
||||
"""Gibt alle mit einer Gruppe verknüpften Straßen zurück"""
|
||||
return StreetModel.get_by_group_id(group_id, tenant_id)
|
||||
|
||||
@classmethod
|
||||
def update_cache_entry(cls, tenant_id, group_id, data):
|
||||
"""Aktualisiert einen Eintrag im Cache.
|
||||
|
||||
Der Cache wird vor dem Aktualisieren vollständig geladen, damit ein
|
||||
gezieltes Update (z. B. nach Code 200/300) keinen Teil-Cache erzeugt,
|
||||
der anschließend beim Initialload unvollständige Gruppendaten liefert.
|
||||
"""
|
||||
if tenant_id not in cls._cache or not cls._cache[tenant_id]:
|
||||
cls.load_from_db(tenant_id)
|
||||
if group_id not in cls._cache[tenant_id]:
|
||||
cls._cache[tenant_id][group_id] = {}
|
||||
cls._cache[tenant_id][group_id].update(data)
|
||||
@@ -0,0 +1,276 @@
|
||||
"""
|
||||
History Service für Revert von States
|
||||
"""
|
||||
import json
|
||||
from datetime import datetime
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.models.streets import StreetModel
|
||||
from cmbnet.models.groups import GroupModel
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
from cmbnet.utils.helpers import log_transaction
|
||||
from cmbnet.ws import broker
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
|
||||
class HistoryService:
|
||||
@staticmethod
|
||||
def revert_street(tenant_id, street_id, hist_id, actor_account_id):
|
||||
db = get_db()
|
||||
history = db.execute(
|
||||
'SELECT * FROM street_state_history WHERE id = ? AND tenant_id = ? AND street_id = ?',
|
||||
(hist_id, tenant_id, street_id)
|
||||
).fetchone()
|
||||
if not history:
|
||||
return False, 'Historieneintrag nicht gefunden'
|
||||
|
||||
street = StreetModel.get_by_id(street_id, tenant_id)
|
||||
if not street:
|
||||
return False, 'Straße nicht gefunden'
|
||||
|
||||
old_state = street['state']
|
||||
target_state = history['to_state']
|
||||
target_group_id = history['group_id']
|
||||
|
||||
if target_state == 'unbearbeitet':
|
||||
target_group_id = None
|
||||
|
||||
# Update Straße
|
||||
StreetModel.update(street_id, tenant_id, state=target_state, group_id=target_group_id)
|
||||
|
||||
# Neuen History-Eintrag für den Revert
|
||||
db.execute(
|
||||
'''INSERT INTO street_state_history
|
||||
(tenant_id, street_id, from_state, to_state, group_id, actor_account_id, reason)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, street_id, old_state, target_state, target_group_id, actor_account_id, f'revert_from_hist_{hist_id}')
|
||||
)
|
||||
db.commit()
|
||||
|
||||
log_transaction('street.revert', 'street', street_id, {
|
||||
'from': old_state,
|
||||
'to': target_state,
|
||||
'group_id': target_group_id,
|
||||
'hist_id': hist_id
|
||||
})
|
||||
|
||||
# Code 100 verschicken
|
||||
msg = WSMessage(
|
||||
sender_id=actor_account_id,
|
||||
code=100,
|
||||
msg=json.dumps({
|
||||
'name': street['name'],
|
||||
'state': target_state,
|
||||
'actor': actor_account_id,
|
||||
'street_id': street_id,
|
||||
'group_id': target_group_id
|
||||
})
|
||||
)
|
||||
try:
|
||||
broker.route_message(tenant_id, msg)
|
||||
except Exception as e:
|
||||
print(f'Broker error: {e}')
|
||||
|
||||
return True, 'Zustand wiederhergestellt'
|
||||
|
||||
@staticmethod
|
||||
def revert_group(tenant_id, group_id, hist_id, actor_account_id):
|
||||
db = get_db()
|
||||
history = db.execute(
|
||||
'SELECT * FROM group_state_history WHERE id = ? AND tenant_id = ? AND group_id = ?',
|
||||
(hist_id, tenant_id, group_id)
|
||||
).fetchone()
|
||||
if not history:
|
||||
return False, 'Historieneintrag nicht gefunden'
|
||||
|
||||
group = GroupModel.get_by_id(group_id, tenant_id)
|
||||
if not group:
|
||||
return False, 'Gruppe nicht gefunden'
|
||||
|
||||
old_state = group['state']
|
||||
target_state = history['to_state']
|
||||
target_lat = history['last_lat']
|
||||
target_lon = history['last_lon']
|
||||
target_pos_at = history['last_pos_at']
|
||||
|
||||
GroupModel.update(group_id, tenant_id,
|
||||
state=target_state,
|
||||
last_lat=target_lat,
|
||||
last_lon=target_lon,
|
||||
last_pos_at=target_pos_at)
|
||||
|
||||
# Neuen History-Eintrag
|
||||
db.execute(
|
||||
'''INSERT INTO group_state_history
|
||||
(tenant_id, group_id, from_state, to_state, last_lat, last_lon, last_pos_at, actor_account_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, group_id, old_state, target_state, target_lat, target_lon, target_pos_at, actor_account_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# Cache aktualisieren
|
||||
GroupsService.update_cache_entry(tenant_id, group_id, {
|
||||
'state': target_state,
|
||||
'last_lat': target_lat,
|
||||
'last_lon': target_lon,
|
||||
'last_pos_at': target_pos_at
|
||||
})
|
||||
|
||||
log_transaction('group.revert', 'group', group_id, {
|
||||
'from': old_state,
|
||||
'to': target_state,
|
||||
'hist_id': hist_id
|
||||
})
|
||||
|
||||
# Code 200
|
||||
msg200 = WSMessage(
|
||||
sender_id=actor_account_id,
|
||||
code=200,
|
||||
msg=json.dumps({
|
||||
'group_id': group_id,
|
||||
'state': target_state,
|
||||
'actor': actor_account_id
|
||||
})
|
||||
)
|
||||
try:
|
||||
broker.route_message(tenant_id, msg200)
|
||||
except:
|
||||
pass
|
||||
|
||||
# Code 300 wenn Position vorhanden
|
||||
if target_lat is not None and target_lon is not None:
|
||||
msg300 = WSMessage(
|
||||
sender_id=actor_account_id,
|
||||
code=300,
|
||||
msg=json.dumps({
|
||||
'group_id': group_id,
|
||||
'lat': target_lat,
|
||||
'lon': target_lon,
|
||||
'ts': target_pos_at,
|
||||
'actor': actor_account_id
|
||||
})
|
||||
)
|
||||
try:
|
||||
broker.route_message(tenant_id, msg300)
|
||||
except:
|
||||
pass
|
||||
|
||||
return True, 'Gruppe wiederhergestellt'
|
||||
|
||||
@staticmethod
|
||||
def _send_group_position(tenant_id, group_id, lat, lon, pos_at, actor_account_id):
|
||||
"""Meldet eine Positionsänderung an die berechtigten Clients (Code 300)."""
|
||||
msg = WSMessage(
|
||||
sender_id=actor_account_id,
|
||||
code=300,
|
||||
msg=json.dumps({
|
||||
'group_id': group_id,
|
||||
'lat': lat,
|
||||
'lon': lon,
|
||||
'ts': pos_at,
|
||||
'actor': actor_account_id
|
||||
})
|
||||
)
|
||||
try:
|
||||
broker.route_message(tenant_id, msg)
|
||||
except Exception as e:
|
||||
print(f'Broker error: {e}')
|
||||
|
||||
@staticmethod
|
||||
def set_group_position_from_history(tenant_id, group_id, hist_id, actor_account_id):
|
||||
"""Übernimmt ausschließlich die Position eines Historieneintrags.
|
||||
|
||||
Der State der Gruppe bleibt unverändert; die Übernahme wird selbst als
|
||||
neuer Historieneintrag festgehalten.
|
||||
"""
|
||||
db = get_db()
|
||||
history = db.execute(
|
||||
'SELECT * FROM group_state_history WHERE id = ? AND tenant_id = ? AND group_id = ?',
|
||||
(hist_id, tenant_id, group_id)
|
||||
).fetchone()
|
||||
if not history:
|
||||
return False, 'Historieneintrag nicht gefunden'
|
||||
|
||||
target_lat = history['last_lat']
|
||||
target_lon = history['last_lon']
|
||||
if target_lat is None or target_lon is None:
|
||||
return False, 'Historieneintrag enthält keine Position'
|
||||
|
||||
group = GroupModel.get_by_id(group_id, tenant_id)
|
||||
if not group:
|
||||
return False, 'Gruppe nicht gefunden'
|
||||
|
||||
target_pos_at = history['last_pos_at']
|
||||
GroupModel.update(
|
||||
group_id, tenant_id,
|
||||
last_lat=target_lat,
|
||||
last_lon=target_lon,
|
||||
last_pos_at=target_pos_at
|
||||
)
|
||||
|
||||
db.execute(
|
||||
'''INSERT INTO group_state_history
|
||||
(tenant_id, group_id, from_state, to_state, last_lat, last_lon, last_pos_at, actor_account_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, group_id, group['state'], group['state'],
|
||||
target_lat, target_lon, target_pos_at, actor_account_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
GroupsService.update_cache_entry(tenant_id, group_id, {
|
||||
'last_lat': target_lat,
|
||||
'last_lon': target_lon,
|
||||
'last_pos_at': target_pos_at
|
||||
})
|
||||
|
||||
log_transaction('group.position_from_history', 'group', group_id, {
|
||||
'hist_id': hist_id,
|
||||
'lat': target_lat,
|
||||
'lon': target_lon
|
||||
})
|
||||
HistoryService._send_group_position(
|
||||
tenant_id, group_id, target_lat, target_lon, target_pos_at, actor_account_id
|
||||
)
|
||||
|
||||
return True, 'Position übernommen'
|
||||
|
||||
@staticmethod
|
||||
def clear_group_position(tenant_id, group_id, actor_account_id):
|
||||
"""Löscht die aktuelle Position einer Gruppe."""
|
||||
group = GroupModel.get_by_id(group_id, tenant_id)
|
||||
if not group:
|
||||
return False, 'Gruppe nicht gefunden'
|
||||
|
||||
if group['last_lat'] is None and group['last_lon'] is None:
|
||||
return True, 'Position ist bereits unbekannt'
|
||||
|
||||
GroupModel.update(
|
||||
group_id, tenant_id,
|
||||
last_lat=None,
|
||||
last_lon=None,
|
||||
last_pos_at=None
|
||||
)
|
||||
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'''INSERT INTO group_state_history
|
||||
(tenant_id, group_id, from_state, to_state, last_lat, last_lon, last_pos_at, actor_account_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, group_id, group['state'], group['state'],
|
||||
None, None, None, actor_account_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
GroupsService.update_cache_entry(tenant_id, group_id, {
|
||||
'last_lat': None,
|
||||
'last_lon': None,
|
||||
'last_pos_at': None
|
||||
})
|
||||
|
||||
log_transaction('group.position_clear', 'group', group_id, {})
|
||||
|
||||
# Null-Koordinaten signalisieren den Clients, die Markierung zu entfernen.
|
||||
HistoryService._send_group_position(
|
||||
tenant_id, group_id, None, None, None, actor_account_id
|
||||
)
|
||||
|
||||
return True, 'Position gelöscht'
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
Streets Service - Geschäftslogik für Straßen
|
||||
"""
|
||||
from cmbnet.models.streets import StreetModel
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.utils.helpers import log_transaction
|
||||
import json
|
||||
|
||||
|
||||
class StreetsService:
|
||||
@staticmethod
|
||||
def get_all_for_init(tenant_id):
|
||||
"""Gibt alle Straßen für den AJAX-Initialload zurück"""
|
||||
streets = StreetModel.get_all_by_tenant(tenant_id)
|
||||
result = []
|
||||
for street in streets:
|
||||
result.append({
|
||||
'id': street['id'],
|
||||
'name': street['name'],
|
||||
'state': street['state'],
|
||||
'group_id': street['group_id'],
|
||||
'hn_min': street['hn_min'],
|
||||
'hn_max': street['hn_max'],
|
||||
'bbox': json.loads(street['bbox']) if street['bbox'] else None
|
||||
})
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def update_street(street_id, tenant_id, changes, actor_account_id=None):
|
||||
"""Aktualisiert eine Straße und schreibt History/Log"""
|
||||
db = get_db()
|
||||
old_street = StreetModel.get_by_id(street_id, tenant_id)
|
||||
if not old_street:
|
||||
return False
|
||||
|
||||
StreetModel.update(street_id, tenant_id, **changes)
|
||||
|
||||
# History bei State-Wechsel
|
||||
if 'state' in changes and changes['state'] != old_street['state']:
|
||||
db.execute(
|
||||
'''INSERT INTO street_state_history
|
||||
(tenant_id, street_id, from_state, to_state, group_id, actor_account_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, street_id, old_street['state'], changes['state'],
|
||||
changes.get('group_id', old_street['group_id']), actor_account_id)
|
||||
)
|
||||
db.commit()
|
||||
log_transaction('street.state_change', 'street', street_id,
|
||||
{'from': old_street['state'], 'to': changes['state']})
|
||||
else:
|
||||
log_transaction('street.update', 'street', street_id, changes)
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
CSV Import Utils für Straßen
|
||||
"""
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
|
||||
|
||||
def parse_streets_csv(file_content):
|
||||
"""
|
||||
Parst CSV mit Delimiter ';'
|
||||
Erwartete Spalten: Name, Hausnummer minimal, Hausnummer maximal, Bounding Box
|
||||
"""
|
||||
streets = []
|
||||
# Versuche mit verschiedenen Encodings
|
||||
try:
|
||||
text = file_content.decode('utf-8')
|
||||
except:
|
||||
try:
|
||||
text = file_content.decode('latin-1')
|
||||
except:
|
||||
text = file_content.decode('cp1252')
|
||||
|
||||
f = io.StringIO(text)
|
||||
reader = csv.DictReader(f, delimiter=';')
|
||||
|
||||
for row in reader:
|
||||
name = row.get('Name') or row.get('name') or row.get('Strasse') or row.get('Straße')
|
||||
hn_min = row.get('Hausnummer minimal') or row.get('hn_min') or row.get('Hausnummer_minimal')
|
||||
hn_max = row.get('Hausnummer maximal') or row.get('hn_max') or row.get('Hausnummer_maximal')
|
||||
bbox = row.get('Bounding Box') or row.get('bbox') or row.get('BoundingBox')
|
||||
|
||||
if not name:
|
||||
continue
|
||||
|
||||
try:
|
||||
hn_min_int = int(hn_min) if hn_min and hn_min.strip() else None
|
||||
except:
|
||||
hn_min_int = None
|
||||
|
||||
try:
|
||||
hn_max_int = int(hn_max) if hn_max and hn_max.strip() else None
|
||||
except:
|
||||
hn_max_int = None
|
||||
|
||||
streets.append({
|
||||
'name': name.strip(),
|
||||
'hn_min': hn_min_int,
|
||||
'hn_max': hn_max_int,
|
||||
'bbox': bbox.strip() if bbox else None
|
||||
})
|
||||
|
||||
return streets
|
||||
@@ -0,0 +1,39 @@
|
||||
"""
|
||||
Hilfsfunktionen für CMBNet
|
||||
"""
|
||||
from flask import g
|
||||
import json
|
||||
|
||||
|
||||
def get_tenant_id():
|
||||
"""Gibt die aktuelle Tenant-ID aus dem Request-Kontext zurück"""
|
||||
return getattr(g, 'tenant_id', None)
|
||||
|
||||
|
||||
def get_current_account():
|
||||
"""Gibt den aktuellen Account aus dem Request-Kontext zurück"""
|
||||
return getattr(g, 'current_account', None)
|
||||
|
||||
|
||||
def log_transaction(action, entity_type, entity_id, details=None):
|
||||
"""
|
||||
Schreibt einen Eintrag ins Transaktionslog
|
||||
"""
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.core.logging import write_transaction_log
|
||||
|
||||
db = get_db()
|
||||
tenant_id = get_tenant_id()
|
||||
account = get_current_account()
|
||||
actor_id = account['id'] if account else None
|
||||
|
||||
details_json = json.dumps(details) if details else None
|
||||
|
||||
db.execute(
|
||||
'INSERT INTO transaction_log (tenant_id, actor_account_id, action, entity_type, entity_id, details) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(tenant_id, actor_id, action, entity_type, entity_id, details_json)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# Auch ins Logfile schreiben
|
||||
write_transaction_log(tenant_id, actor_id, account['name'] if account else None, action, entity_type, entity_id, details)
|
||||
@@ -0,0 +1,2 @@
|
||||
from .auth import auth_bp
|
||||
from .main import views_bp
|
||||
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
Authentifizierungs-Views
|
||||
"""
|
||||
from flask import Blueprint, render_template, request, redirect, url_for, session, flash, g
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.auth import verify_password
|
||||
|
||||
auth_bp = Blueprint('auth', __name__)
|
||||
|
||||
|
||||
@auth_bp.before_request
|
||||
def load_tenant():
|
||||
"""Lädt Tenant aus URL"""
|
||||
tenant_code = request.view_args.get('tenant')
|
||||
if tenant_code:
|
||||
db = get_db()
|
||||
tenant = db.execute('SELECT * FROM tenants WHERE code = ?', (tenant_code,)).fetchone()
|
||||
if not tenant:
|
||||
flash('Ungültiger Mandant', 'error')
|
||||
return redirect(url_for('auth.login_select'))
|
||||
g.tenant_id = tenant['id']
|
||||
g.tenant_code = tenant['code']
|
||||
|
||||
|
||||
@auth_bp.route('/login', methods=['GET', 'POST'])
|
||||
def login(**kwargs):
|
||||
"""Login-View"""
|
||||
tenant_code = g.tenant_code
|
||||
next_url = request.args.get('next')
|
||||
|
||||
if request.method == 'POST':
|
||||
username = request.form.get('username', '').strip()
|
||||
password = request.form.get('password', '')
|
||||
tenant_selected = request.form.get('tenant', tenant_code)
|
||||
|
||||
db = get_db()
|
||||
# Überprüfe Account für den Tenant
|
||||
account = db.execute(
|
||||
'SELECT a.*, t.code as tenant_code FROM accounts a JOIN tenants t ON a.tenant_id = t.id WHERE a.name = ? AND t.code = ?',
|
||||
(username, tenant_selected)
|
||||
).fetchone()
|
||||
|
||||
if account and verify_password(account['password_hash'], password):
|
||||
# Login erfolgreich
|
||||
session['account_id'] = account['id']
|
||||
session['tenant_id'] = account['tenant_id']
|
||||
session['tenant_code'] = account['tenant_code']
|
||||
session['role'] = account['role']
|
||||
session['username'] = account['name']
|
||||
|
||||
# Weiterleitung
|
||||
if next_url:
|
||||
return redirect(next_url)
|
||||
|
||||
# Rollenbasierte Weiterleitung
|
||||
role = account['role']
|
||||
if role == 'Administrator':
|
||||
return redirect(url_for('admin.accounts', tenant=tenant_selected))
|
||||
elif role == 'Dispatcher':
|
||||
return redirect(url_for('views.dispatcher', tenant=tenant_selected))
|
||||
elif role == 'Beobachter':
|
||||
return redirect(url_for('views.praesentation', tenant=tenant_selected))
|
||||
elif role == 'Gruppe':
|
||||
return redirect(url_for('views.gruppen', tenant=tenant_selected))
|
||||
else:
|
||||
return redirect(url_for('views.oeffentlich', tenant=tenant_selected))
|
||||
else:
|
||||
flash('Ungültiger Benutzername oder Passwort', 'error')
|
||||
|
||||
return render_template('login.html', tenant_code=tenant_code)
|
||||
|
||||
|
||||
@auth_bp.route('/login/select')
|
||||
def login_select(**kwargs):
|
||||
"""Mandantenauswahl für Login"""
|
||||
return render_template('login_select.html')
|
||||
|
||||
|
||||
@auth_bp.route('/logout')
|
||||
def logout(**kwargs):
|
||||
"""Logout"""
|
||||
session.clear()
|
||||
tenant_code = g.get('tenant_code') or request.args.get('tenant') or 'RV'
|
||||
return redirect(url_for('auth.login', tenant=tenant_code))
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
Haupt-Views
|
||||
"""
|
||||
from flask import Blueprint, render_template, g, redirect, url_for
|
||||
from cmbnet.auth import login_required
|
||||
|
||||
views_bp = Blueprint('views', __name__)
|
||||
|
||||
|
||||
@views_bp.route('/')
|
||||
@login_required
|
||||
def index(**kwargs):
|
||||
"""Startseite - Weiterleitung je nach Rolle"""
|
||||
role = g.current_account['role'] if hasattr(g, 'current_account') else None
|
||||
tenant = g.tenant_code
|
||||
|
||||
if role == 'Administrator':
|
||||
return redirect(url_for('admin.accounts', tenant=tenant))
|
||||
elif role == 'Dispatcher':
|
||||
return redirect(url_for('views.dispatcher', tenant=tenant))
|
||||
elif role == 'Beobachter':
|
||||
return redirect(url_for('views.praesentation', tenant=tenant))
|
||||
elif role == 'Gruppe':
|
||||
return redirect(url_for('views.gruppen', tenant=tenant))
|
||||
else:
|
||||
return redirect(url_for('views.oeffentlich', tenant=tenant))
|
||||
|
||||
|
||||
@views_bp.route('/dispatcher')
|
||||
@login_required
|
||||
def dispatcher(**kwargs):
|
||||
"""Dispatcher-View"""
|
||||
return render_template('dispatcher.html')
|
||||
|
||||
|
||||
@views_bp.route('/dispatcher_mobil')
|
||||
@login_required
|
||||
def dispatcher_mobil(**kwargs):
|
||||
"""Dispatcher-Mobil-View"""
|
||||
return render_template('dispatcher_mobil.html')
|
||||
|
||||
|
||||
@views_bp.route('/gruppen')
|
||||
@login_required
|
||||
def gruppen(**kwargs):
|
||||
"""Gruppen-View"""
|
||||
return render_template('gruppen.html')
|
||||
|
||||
|
||||
@views_bp.route('/praesentation')
|
||||
@login_required
|
||||
def praesentation(**kwargs):
|
||||
"""Präsentations-View"""
|
||||
return render_template('praesentation.html')
|
||||
|
||||
|
||||
@views_bp.route('/oeffentlich')
|
||||
def oeffentlich(**kwargs):
|
||||
"""Öffentlicher-View"""
|
||||
return render_template('oeffentlich.html')
|
||||
@@ -0,0 +1,4 @@
|
||||
from .broker import WebSocketBroker
|
||||
from .protocol import WSMessage
|
||||
|
||||
broker = WebSocketBroker()
|
||||
@@ -0,0 +1,754 @@
|
||||
"""
|
||||
WebSocket Broker - Kernkomponente für Realtime-Kommunikation
|
||||
|
||||
Der Broker nimmt Nachrichten aus WebSocket-Verbindungen (und aus HTTP-Handlern)
|
||||
entgegen, wertet den Code aus, bestimmt den erlaubten Empfängerkreis und stellt
|
||||
die Nachricht zu.
|
||||
|
||||
Wichtige Regeln aus der Spezifikation:
|
||||
- Code < 100: rein interne Nachrichten (z. B. Authentifizierung, Heartbeat).
|
||||
- Code 100/200/300: State- bzw. Positionsänderungen an Dispatcher, Beobachter
|
||||
und die jeweils betroffene Gruppe.
|
||||
- Code 1000/1100/2000: Chat-/Broadcast-Nachrichten. Diese werden persistiert,
|
||||
damit sie bei einer späteren Anmeldung als "Late Entry" nachgeliefert werden
|
||||
können. Nachrichten, die älter als LATE_ENTRY_MAX_AGE_HOURS (Default 8h) sind,
|
||||
werden gelöscht.
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from flask import current_app
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
|
||||
class WebSocketBroker:
|
||||
def __init__(self):
|
||||
# connections[tenant_id][account_id] = {
|
||||
# 'ws': <WebSocket-Objekt>,
|
||||
# 'role': <Rolle des Accounts>,
|
||||
# 'group_id': <verknüpfte Gruppe oder None>,
|
||||
# }
|
||||
self.connections = {}
|
||||
# authenticated[tenant_id][account_id] = True
|
||||
# Erst nach erfolgreichem Code-0-Handshake darf ein Client Nachrichten
|
||||
# über die Verbindung senden.
|
||||
self.authenticated = {}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Verbindungen und Authentifizierung
|
||||
# ------------------------------------------------------------------
|
||||
def register_connection(self, tenant_id, account_id, ws, role=None, group_id=None):
|
||||
"""Registriert eine neue, noch nicht authentifizierte Verbindung.
|
||||
|
||||
Rolle und Gruppenzuordnung werden direkt mitgespeichert. Sie werden
|
||||
später für die Empfängerermittlung und für das Cleanup benötigt.
|
||||
"""
|
||||
db = get_db()
|
||||
account = db.execute(
|
||||
'SELECT role FROM accounts WHERE id = ? AND tenant_id = ?',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
if not account:
|
||||
return False
|
||||
|
||||
if role is None:
|
||||
role = account['role']
|
||||
|
||||
# Für Gruppen-Accounts die zugehörige Gruppe ermitteln. Ein Account der
|
||||
# Rolle "Gruppe" ist genau einer Gruppe zugeordnet.
|
||||
if group_id is None and role == 'Gruppe':
|
||||
group = db.execute(
|
||||
'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
group_id = group['id'] if group else None
|
||||
|
||||
if tenant_id not in self.connections:
|
||||
self.connections[tenant_id] = {}
|
||||
|
||||
# Eine neue Verbindung muss den Token-Handshake erneut durchlaufen.
|
||||
# Ein eventuell noch gesetzter Auth-Status einer älteren Verbindung
|
||||
# desselben Accounts darf nicht übernommen werden.
|
||||
authenticated = self.authenticated.get(tenant_id)
|
||||
if authenticated:
|
||||
authenticated.pop(account_id, None)
|
||||
|
||||
self.connections[tenant_id][account_id] = {
|
||||
'ws': ws,
|
||||
'role': role,
|
||||
'group_id': group_id,
|
||||
'last_ping': datetime.now()
|
||||
}
|
||||
return True
|
||||
|
||||
def is_authenticated(self, tenant_id, account_id):
|
||||
"""Prüft, ob eine Verbindung den Code-0-Handshake erfolgreich absolviert hat."""
|
||||
return self.authenticated.get(tenant_id, {}).get(account_id, False)
|
||||
|
||||
def authenticate(self, tenant_id, account_id, token):
|
||||
"""Authentifiziert eine Verbindung anhand des Einmal-Tokens (Code 0)."""
|
||||
db = get_db()
|
||||
token_row = db.execute(
|
||||
'SELECT * FROM ws_tokens WHERE token = ? AND tenant_id = ? '
|
||||
'AND account_id = ? AND used = 0',
|
||||
(token, tenant_id, account_id)
|
||||
).fetchone()
|
||||
|
||||
if not token_row:
|
||||
return False
|
||||
|
||||
# Ablaufzeit prüfen (Tokens sind nur kurzzeitig gültig).
|
||||
if token_row['expires_at']:
|
||||
try:
|
||||
expires = datetime.fromisoformat(token_row['expires_at'].replace('Z', '+00:00'))
|
||||
# SQLite liefert naive Zeitstempel; ein Vergleich mit einer
|
||||
# zeitzonenbehafteten Zeit wäre nicht möglich.
|
||||
if expires.tzinfo is not None:
|
||||
expires = expires.astimezone().replace(tzinfo=None)
|
||||
if expires < datetime.now():
|
||||
return False
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
# Token darf nur einmal verwendet werden.
|
||||
db.execute('UPDATE ws_tokens SET used = 1 WHERE id = ?', (token_row['id'],))
|
||||
db.commit()
|
||||
|
||||
if tenant_id not in self.authenticated:
|
||||
self.authenticated[tenant_id] = {}
|
||||
self.authenticated[tenant_id][account_id] = True
|
||||
|
||||
# Nach erfolgreicher Authentifizierung dürfen die gespeicherten
|
||||
# Nachrichten der letzten 8 Stunden nachgeliefert werden.
|
||||
self.send_late_entries(tenant_id, account_id)
|
||||
return True
|
||||
|
||||
def remove_connection(self, tenant_id, account_id, ws=None):
|
||||
"""Entfernt eine Verbindung.
|
||||
|
||||
Wenn ein Account mehrere Tabs/Verbindungen öffnet, wird nur die
|
||||
tatsächlich beendete Verbindung entfernt (ws-Vergleich), nicht die
|
||||
zuletzt registrierte.
|
||||
"""
|
||||
connections = self.connections.get(tenant_id)
|
||||
if connections and account_id in connections:
|
||||
if ws is None or connections[account_id].get('ws') is ws:
|
||||
del connections[account_id]
|
||||
# Nur wenn die tatsächlich beendete Verbindung die aktuelle
|
||||
# war, darf auch der Authentifizierungsstatus entfernt werden.
|
||||
authenticated = self.authenticated.get(tenant_id)
|
||||
if authenticated and account_id in authenticated:
|
||||
del authenticated[account_id]
|
||||
|
||||
def _get_connection(self, tenant_id, account_id):
|
||||
return self.connections.get(tenant_id, {}).get(account_id)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Late Entry
|
||||
# ------------------------------------------------------------------
|
||||
def send_late_entries(self, tenant_id, account_id):
|
||||
"""Sendet gespeicherte Nachrichten (Code >= 1000) der letzten 8 Stunden.
|
||||
|
||||
Es werden ausschließlich Nachrichten zugestellt, für die der Account
|
||||
laut Protokoll berechtigt ist. Die Zustellung erfolgt chronologisch.
|
||||
Anschließend werden abgelaufene Nachrichten gelöscht.
|
||||
"""
|
||||
db = get_db()
|
||||
cutoff = self._late_entry_cutoff()
|
||||
|
||||
messages = db.execute(
|
||||
'SELECT * FROM ws_messages_store WHERE tenant_id = ? AND ts >= ? '
|
||||
'ORDER BY ts ASC, id ASC',
|
||||
(tenant_id, cutoff)
|
||||
).fetchall()
|
||||
|
||||
conn = self._get_connection(tenant_id, account_id)
|
||||
if not conn:
|
||||
return
|
||||
|
||||
for msg_row in messages:
|
||||
if not self._is_allowed_for_client(tenant_id, account_id, msg_row):
|
||||
continue
|
||||
|
||||
msg = WSMessage(
|
||||
sender_id=msg_row['sender_id'],
|
||||
receiver_id=msg_row['receiver_id'],
|
||||
code=msg_row['code'],
|
||||
msg=msg_row['msg'],
|
||||
ts=msg_row['ts']
|
||||
)
|
||||
self._send(tenant_id, account_id, msg)
|
||||
|
||||
# Abgelaufene Nachrichten werden bei jeder Anmeldung aufgeräumt.
|
||||
self.cleanup_old_messages(tenant_id)
|
||||
|
||||
def _late_entry_cutoff(self):
|
||||
"""Zeitstempel (ms), ab dem gespeicherte Nachrichten noch zustellbar sind."""
|
||||
max_age_hours = current_app.config.get('LATE_ENTRY_MAX_AGE_HOURS', 8)
|
||||
return int((datetime.now() - timedelta(hours=max_age_hours)).timestamp() * 1000)
|
||||
|
||||
def cleanup_old_messages(self, tenant_id=None):
|
||||
"""Löscht persistierte Nachrichten, die älter als die Late-Entry-Frist sind."""
|
||||
db = get_db()
|
||||
cutoff = self._late_entry_cutoff()
|
||||
|
||||
if tenant_id is None:
|
||||
db.execute('DELETE FROM ws_messages_store WHERE ts < ?', (cutoff,))
|
||||
else:
|
||||
db.execute(
|
||||
'DELETE FROM ws_messages_store WHERE tenant_id = ? AND ts < ?',
|
||||
(tenant_id, cutoff)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
def _is_allowed_for_client(self, tenant_id, account_id, msg_row):
|
||||
"""Prüft, ob eine persistierte Nachricht für diesen Client bestimmt ist."""
|
||||
db = get_db()
|
||||
account = db.execute(
|
||||
'SELECT * FROM accounts WHERE id = ? AND tenant_id = ?',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
if not account:
|
||||
return False
|
||||
|
||||
role = account['role']
|
||||
code = msg_row['code']
|
||||
|
||||
# Code 1000: Broadcast an Dispatcher, Beobachter und alle Gruppen.
|
||||
if code == 1000:
|
||||
return role in ('Dispatcher', 'Beobachter', 'Gruppe')
|
||||
|
||||
# Code 1100: Dispatcher, Beobachter und die angesprochene Gruppe.
|
||||
if code == 1100:
|
||||
if role in ('Dispatcher', 'Beobachter'):
|
||||
return True
|
||||
if role == 'Gruppe':
|
||||
group = db.execute(
|
||||
'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
return bool(group and msg_row['receiver_id'] == group['id'])
|
||||
return False
|
||||
|
||||
# Code 2000: nur Dispatcher und Beobachter.
|
||||
if code == 2000:
|
||||
return role in ('Dispatcher', 'Beobachter')
|
||||
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Nachrichtenverarbeitung
|
||||
# ------------------------------------------------------------------
|
||||
def route_message(self, tenant_id, message, apply_business=False):
|
||||
"""Wertet den Code aus, persistiert ggf. und stellt die Nachricht zu.
|
||||
|
||||
``apply_business`` wird nur für Nachrichten verwendet, die direkt über
|
||||
die WebSocket-Route eingehen. Serverintern erzeugte Nachrichten (z. B.
|
||||
aus der Admin-API) haben die Datenbank bereits aktualisiert und dürfen
|
||||
deshalb nicht ein zweites Mal angewendet werden.
|
||||
"""
|
||||
db = get_db()
|
||||
|
||||
# Absender muss zum Mandanten gehören. Die Absender-ID wird in der
|
||||
# WebSocket-Route aus der Session gesetzt und kann nicht gefälscht
|
||||
# werden.
|
||||
sender = db.execute(
|
||||
'SELECT * FROM accounts WHERE id = ? AND tenant_id = ?',
|
||||
(message.sender_id, tenant_id)
|
||||
).fetchone()
|
||||
if not sender:
|
||||
return
|
||||
|
||||
code = message.code
|
||||
|
||||
# Code 0 wird ausschließlich in der WebSocket-Route (Handshake)
|
||||
# verarbeitet und niemals weitergeleitet.
|
||||
if code <= 0:
|
||||
return
|
||||
|
||||
# Code 1 sendet ausschließlich der Server (Heartbeat-Routine).
|
||||
# Nachrichten dieses Typs von Clients werden ignoriert.
|
||||
if code == 1:
|
||||
return
|
||||
|
||||
# Code 2 ist die Antwort eines Clients auf den Heartbeat. Sie wird nur
|
||||
# an Dispatcher-Views weitergeleitet und nicht gespeichert.
|
||||
if code == 2:
|
||||
self._deliver(tenant_id, message, sender)
|
||||
return
|
||||
|
||||
# Sonstige interne Codes (< 100) werden nicht an die Oberfläche gegeben.
|
||||
if code < 100:
|
||||
return
|
||||
|
||||
# Ab hier: fachliche Nachrichten (>= 100).
|
||||
# Zustandsänderungen, die ein Client per WebSocket meldet, werden vor
|
||||
# der Zustellung in der Datenbank persistiert. So sind sie auch nach
|
||||
# einem Neuladen der Seite wieder sichtbar.
|
||||
if apply_business and code in (100, 200, 300):
|
||||
if not self._apply_business_change(tenant_id, message, sender):
|
||||
return
|
||||
|
||||
message = self._prepare_message(tenant_id, message, sender)
|
||||
|
||||
# Ab Code 1000 werden Nachrichten für die Late-Entry-Funktion
|
||||
# gespeichert. Gespeichert wird die bereits aufbereitete Nachricht
|
||||
# (bei Code 1100 inklusive Aliasname-Präfix).
|
||||
if code >= 1000:
|
||||
self._persist_message(tenant_id, message)
|
||||
|
||||
self._deliver(tenant_id, message, sender)
|
||||
|
||||
def _apply_business_change(self, tenant_id, message, sender):
|
||||
"""Persistiert Code 100/200/300 aus einer WebSocket-Nachricht.
|
||||
|
||||
Gibt ``False`` zurück, wenn die Nachricht ungültig oder für den
|
||||
Absender nicht erlaubt ist. In diesem Fall wird sie nicht zugestellt.
|
||||
"""
|
||||
payload = self._payload(message)
|
||||
if not isinstance(payload, dict):
|
||||
return False
|
||||
|
||||
if message.code == 100:
|
||||
return self._apply_street_change(tenant_id, message, sender, payload)
|
||||
if message.code == 200:
|
||||
return self._apply_group_state_change(tenant_id, message, sender, payload)
|
||||
if message.code == 300:
|
||||
return self._apply_group_position_change(tenant_id, message, sender, payload)
|
||||
return False
|
||||
|
||||
def _apply_street_change(self, tenant_id, message, sender, payload):
|
||||
"""Wendet einen Straßen-State-Wechsel aus einer Code-100-Nachricht an."""
|
||||
if sender['role'] not in ('Dispatcher', 'Administrator'):
|
||||
return False
|
||||
|
||||
db = get_db()
|
||||
street = None
|
||||
street_id = payload.get('street_id')
|
||||
if street_id is not None:
|
||||
try:
|
||||
street_id = int(street_id)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
street = db.execute(
|
||||
'SELECT * FROM streets WHERE id = ? AND tenant_id = ?',
|
||||
(street_id, tenant_id)
|
||||
).fetchone()
|
||||
|
||||
if not street and payload.get('name'):
|
||||
street = db.execute(
|
||||
'SELECT * FROM streets WHERE name = ? AND tenant_id = ?',
|
||||
(str(payload['name']), tenant_id)
|
||||
).fetchone()
|
||||
|
||||
if not street:
|
||||
return False
|
||||
|
||||
new_state = payload.get('state')
|
||||
if new_state not in ('unbearbeitet', 'zugewiesen', 'erledigt'):
|
||||
return False
|
||||
|
||||
if 'group_id' in payload:
|
||||
group_id = payload['group_id']
|
||||
if group_id in ('', None):
|
||||
group_id = None
|
||||
else:
|
||||
try:
|
||||
group_id = int(group_id)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
else:
|
||||
group_id = street['group_id']
|
||||
|
||||
# Unbearbeitet bedeutet immer "keine Gruppe". Für "zugewiesen" ist
|
||||
# dagegen eine gültige Gruppe erforderlich.
|
||||
if new_state == 'unbearbeitet':
|
||||
group_id = None
|
||||
elif new_state == 'zugewiesen' and group_id is None:
|
||||
return False
|
||||
|
||||
if group_id is not None:
|
||||
group = db.execute(
|
||||
'SELECT id FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
if not group:
|
||||
return False
|
||||
|
||||
old_state = street['state']
|
||||
old_group_id = street['group_id']
|
||||
changed = old_state != new_state or old_group_id != group_id
|
||||
|
||||
if changed:
|
||||
db.execute(
|
||||
'UPDATE streets SET state = ?, group_id = ?, updated_at = CURRENT_TIMESTAMP '
|
||||
'WHERE id = ? AND tenant_id = ?',
|
||||
(new_state, group_id, street['id'], tenant_id)
|
||||
)
|
||||
db.execute(
|
||||
'''INSERT INTO street_state_history
|
||||
(tenant_id, street_id, from_state, to_state, group_id, actor_account_id, reason)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, street['id'], old_state, new_state,
|
||||
group_id, sender['id'], 'ws_code_100')
|
||||
)
|
||||
db.commit()
|
||||
self._log_business(tenant_id, sender['id'], 'street.state_change', 'street',
|
||||
street['id'], {'from': old_state, 'to': new_state,
|
||||
'group_id': group_id})
|
||||
|
||||
# Für die Empfängerermittlung muss die alte Gruppe bekannt bleiben:
|
||||
# Bei einem Gruppenwechsel erhält sowohl die alte als auch die neue
|
||||
# Gruppe die Code-100-Nachricht.
|
||||
message._old_group_id = old_group_id
|
||||
message.msg = json.dumps({
|
||||
'name': street['name'],
|
||||
'state': new_state,
|
||||
'actor': sender['id'],
|
||||
'street_id': street['id'],
|
||||
'group_id': group_id
|
||||
}, ensure_ascii=False)
|
||||
return True
|
||||
|
||||
def _apply_group_state_change(self, tenant_id, message, sender, payload):
|
||||
"""Wendet einen Gruppen-State-Wechsel aus einer Code-200-Nachricht an."""
|
||||
if sender['role'] not in ('Dispatcher', 'Administrator', 'Gruppe'):
|
||||
return False
|
||||
|
||||
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
||||
if not group_id:
|
||||
return False
|
||||
|
||||
db = get_db()
|
||||
group = db.execute(
|
||||
'SELECT * FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
if not group:
|
||||
return False
|
||||
|
||||
# Ein Gruppen-Account darf nur den Zustand seiner eigenen Gruppe ändern.
|
||||
if sender['role'] == 'Gruppe' and group['account_id'] != sender['id']:
|
||||
return False
|
||||
|
||||
new_state = payload.get('state')
|
||||
if new_state not in ('offen', 'unterwegs', 'online', 'pausierend', 'fertig'):
|
||||
return False
|
||||
|
||||
if new_state != group['state']:
|
||||
db.execute(
|
||||
'UPDATE groups SET state = ?, updated_at = CURRENT_TIMESTAMP '
|
||||
'WHERE id = ? AND tenant_id = ?',
|
||||
(new_state, group_id, tenant_id)
|
||||
)
|
||||
db.execute(
|
||||
'''INSERT INTO group_state_history
|
||||
(tenant_id, group_id, from_state, to_state, last_lat, last_lon,
|
||||
last_pos_at, actor_account_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, group_id, group['state'], new_state,
|
||||
group['last_lat'], group['last_lon'], group['last_pos_at'], sender['id'])
|
||||
)
|
||||
db.commit()
|
||||
GroupsService.update_cache_entry(tenant_id, group_id, {'state': new_state})
|
||||
self._log_business(tenant_id, sender['id'], 'group.state_change', 'group',
|
||||
group_id, {'from': group['state'], 'to': new_state})
|
||||
|
||||
message.receiver_id = group_id
|
||||
message.msg = json.dumps({
|
||||
'group_id': group_id,
|
||||
'state': new_state,
|
||||
'actor': sender['id']
|
||||
}, ensure_ascii=False)
|
||||
return True
|
||||
|
||||
def _apply_group_position_change(self, tenant_id, message, sender, payload):
|
||||
"""Wendet eine Positionsänderung aus einer Code-300-Nachricht an."""
|
||||
if sender['role'] not in ('Dispatcher', 'Administrator', 'Gruppe'):
|
||||
return False
|
||||
|
||||
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
||||
if not group_id:
|
||||
return False
|
||||
|
||||
db = get_db()
|
||||
group = db.execute(
|
||||
'SELECT * FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
if not group:
|
||||
return False
|
||||
|
||||
if sender['role'] == 'Gruppe' and group['account_id'] != sender['id']:
|
||||
return False
|
||||
|
||||
try:
|
||||
lat = float(payload.get('lat'))
|
||||
lon = float(payload.get('lon'))
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
||||
return False
|
||||
|
||||
# Der Server setzt den Zeitstempel, damit die Progressbar nicht durch
|
||||
# manipulierbare Client-Zeitangaben verfälscht wird.
|
||||
pos_at = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
|
||||
ts_ms = int(time.time() * 1000)
|
||||
|
||||
db.execute(
|
||||
'UPDATE groups SET last_lat = ?, last_lon = ?, last_pos_at = ?, '
|
||||
'updated_at = CURRENT_TIMESTAMP WHERE id = ? AND tenant_id = ?',
|
||||
(lat, lon, pos_at, group_id, tenant_id)
|
||||
)
|
||||
db.execute(
|
||||
'''INSERT INTO group_state_history
|
||||
(tenant_id, group_id, from_state, to_state, last_lat, last_lon,
|
||||
last_pos_at, actor_account_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, group_id, group['state'], group['state'],
|
||||
lat, lon, pos_at, sender['id'])
|
||||
)
|
||||
db.commit()
|
||||
GroupsService.update_cache_entry(tenant_id, group_id, {
|
||||
'last_lat': lat,
|
||||
'last_lon': lon,
|
||||
'last_pos_at': pos_at
|
||||
})
|
||||
self._log_business(tenant_id, sender['id'], 'group.position_change', 'group',
|
||||
group_id, {'lat': lat, 'lon': lon})
|
||||
|
||||
message.receiver_id = group_id
|
||||
# Auch der Nachrichten-Zeitstempel wird serverseitig gesetzt, damit
|
||||
# die Progressbar nicht von einer manipulierten Client-Uhr abhängt.
|
||||
message.ts = ts_ms
|
||||
message.msg = json.dumps({
|
||||
'group_id': group_id,
|
||||
'lat': lat,
|
||||
'lon': lon,
|
||||
'ts': ts_ms,
|
||||
'actor': sender['id']
|
||||
}, ensure_ascii=False)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _log_business(tenant_id, actor_id, action, entity_type, entity_id, details):
|
||||
"""Schreibt eine per WebSocket ausgelöste Änderung ins Transaktionslog."""
|
||||
try:
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'INSERT INTO transaction_log '
|
||||
'(tenant_id, actor_account_id, action, entity_type, entity_id, details) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(tenant_id, actor_id, action, entity_type, entity_id,
|
||||
json.dumps(details, ensure_ascii=False))
|
||||
)
|
||||
db.commit()
|
||||
|
||||
from cmbnet.core.logging import write_transaction_log
|
||||
actor = db.execute(
|
||||
'SELECT name FROM accounts WHERE id = ? AND tenant_id = ?',
|
||||
(actor_id, tenant_id)
|
||||
).fetchone()
|
||||
write_transaction_log(tenant_id, actor_id, actor['name'] if actor else None,
|
||||
action, entity_type, entity_id, details)
|
||||
except Exception as exc:
|
||||
print(f'Transaction log error: {exc}')
|
||||
|
||||
def _prepare_message(self, tenant_id, message, sender):
|
||||
"""Ergänzt Nachrichten um serverseitig abgeleitete Informationen."""
|
||||
db = get_db()
|
||||
payload = self._payload(message)
|
||||
|
||||
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 = self._fetch_group(tenant_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:
|
||||
alias = group['aliasname'] or str(group['id'])
|
||||
prefix = f'{alias}: '
|
||||
text = message.msg if isinstance(message.msg, str) else json.dumps(message.msg)
|
||||
if not text.startswith(prefix):
|
||||
message.msg = prefix + text
|
||||
|
||||
elif message.code == 2000:
|
||||
# Spezifikation: Inhalt ist JSON mit Gruppen-ID und Freitext.
|
||||
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
||||
message.receiver_id = group_id
|
||||
if isinstance(payload, dict):
|
||||
if group_id and not payload.get('group_id'):
|
||||
payload['group_id'] = group_id
|
||||
message.msg = json.dumps(payload, ensure_ascii=False)
|
||||
elif group_id:
|
||||
message.msg = json.dumps(
|
||||
{'group_id': group_id, 'text': message.msg},
|
||||
ensure_ascii=False
|
||||
)
|
||||
|
||||
return message
|
||||
|
||||
def _deliver(self, tenant_id, message, sender):
|
||||
"""Stellt eine Nachricht an alle berechtigten, verbundenen Clients zu."""
|
||||
for recipient_id in self._get_recipients(tenant_id, message, sender):
|
||||
self._send(tenant_id, recipient_id, message)
|
||||
|
||||
def _send(self, tenant_id, account_id, message):
|
||||
"""Sendet eine Nachricht, falls für den Account eine Verbindung besteht."""
|
||||
# Erst nach erfolgreicher Token-Authentifizierung dürfen Nachrichten
|
||||
# an einen Client zugestellt werden.
|
||||
if not self.is_authenticated(tenant_id, account_id):
|
||||
return
|
||||
conn = self._get_connection(tenant_id, account_id)
|
||||
if not conn:
|
||||
return
|
||||
try:
|
||||
conn['ws'].send(message.to_json())
|
||||
except Exception:
|
||||
# Eine fehlerhafte Verbindung darf den Versand an andere Clients
|
||||
# nicht verhindern. Das Aufräumen übernimmt die Route beim
|
||||
# Schließen der Verbindung.
|
||||
pass
|
||||
|
||||
def _get_recipients(self, tenant_id, message, sender):
|
||||
"""Bestimmt den Empfängerkreis abhängig vom Nachrichtencode."""
|
||||
db = get_db()
|
||||
recipients = set()
|
||||
code = message.code
|
||||
payload = self._payload(message)
|
||||
|
||||
def add_accounts(roles):
|
||||
placeholders = ','.join('?' for _ in roles)
|
||||
rows = db.execute(
|
||||
f'SELECT id FROM accounts WHERE tenant_id = ? AND role IN ({placeholders})',
|
||||
(tenant_id, *roles)
|
||||
).fetchall()
|
||||
recipients.update(row['id'] for row in rows)
|
||||
|
||||
def add_group_account(group_id):
|
||||
if not group_id:
|
||||
return
|
||||
group = db.execute(
|
||||
'SELECT account_id FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
if group and group['account_id']:
|
||||
recipients.add(group['account_id'])
|
||||
|
||||
if code == 100:
|
||||
# Dispatcher, Gast, Beobachter + die mit der Straße verknüpfte
|
||||
# Gruppe. Bei einem Gruppenwechsel werden sowohl die alte als auch
|
||||
# die neue Gruppe benachrichtigt.
|
||||
add_accounts(('Dispatcher', 'Beobachter', 'Gast'))
|
||||
|
||||
group_ids = set()
|
||||
group_id = payload.get('group_id') if isinstance(payload, dict) else None
|
||||
if group_id not in (None, ''):
|
||||
group_ids.add(group_id)
|
||||
old_group_id = getattr(message, '_old_group_id', None)
|
||||
if old_group_id is not None:
|
||||
group_ids.add(old_group_id)
|
||||
|
||||
street_id = payload.get('street_id') if isinstance(payload, dict) else None
|
||||
# Das Payload stammt aus dem vertrauenswürdigen Server-Code. Nur
|
||||
# wenn keine Gruppen-ID enthalten ist, wird die Straße aus der
|
||||
# Datenbank gelesen.
|
||||
if street_id and not (isinstance(payload, dict) and 'group_id' in payload):
|
||||
street = db.execute(
|
||||
'SELECT group_id FROM streets WHERE id = ? AND tenant_id = ?',
|
||||
(street_id, tenant_id)
|
||||
).fetchone()
|
||||
if street and street['group_id'] is not None:
|
||||
group_ids.add(street['group_id'])
|
||||
|
||||
for group_id in group_ids:
|
||||
add_group_account(group_id)
|
||||
|
||||
elif code in (200, 300):
|
||||
# Dispatcher, Beobachter + die betroffene Gruppe.
|
||||
add_accounts(('Dispatcher', 'Beobachter'))
|
||||
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
||||
add_group_account(group_id)
|
||||
|
||||
elif code == 1000:
|
||||
# Broadcast an Dispatcher, Beobachter und alle Gruppen.
|
||||
add_accounts(('Dispatcher', 'Beobachter', 'Gruppe'))
|
||||
|
||||
elif code == 1100:
|
||||
# Dispatcher, Beobachter + die spezielle Gruppe.
|
||||
add_accounts(('Dispatcher', 'Beobachter'))
|
||||
add_group_account(message.receiver_id)
|
||||
|
||||
elif code == 2000:
|
||||
# Eine Gruppe sendet an Dispatcher und Beobachter.
|
||||
add_accounts(('Dispatcher', 'Beobachter'))
|
||||
|
||||
elif code == 2:
|
||||
# Heartbeat-Antworten werden nur an Dispatcher-Views weitergegeben.
|
||||
add_accounts(('Dispatcher',))
|
||||
|
||||
return recipients
|
||||
|
||||
def _persist_message(self, tenant_id, message):
|
||||
"""Speichert Nachrichten mit Code >= 1000 für die Late-Entry-Funktion."""
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'INSERT INTO ws_messages_store '
|
||||
'(tenant_id, sender_id, receiver_id, code, ts, msg) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(tenant_id, message.sender_id, message.receiver_id,
|
||||
message.code, message.ts, message.msg)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Hilfsfunktionen
|
||||
# ------------------------------------------------------------------
|
||||
@staticmethod
|
||||
def _payload(message):
|
||||
"""Liefert den JSON-Payload einer Nachricht oder None."""
|
||||
if isinstance(message.msg, dict):
|
||||
return message.msg
|
||||
if not isinstance(message.msg, str):
|
||||
return None
|
||||
try:
|
||||
data = json.loads(message.msg)
|
||||
return data if isinstance(data, dict) else None
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
def _resolve_group_id(self, tenant_id, message, sender, payload):
|
||||
"""Ermittelt die betroffene Gruppen-ID aus Payload, receiver_id oder Absender."""
|
||||
group_id = payload.get('group_id') if isinstance(payload, dict) else None
|
||||
if group_id is None:
|
||||
group_id = message.receiver_id
|
||||
if group_id is None and sender is not None and message.code in (200, 300, 2000):
|
||||
# Bei Gruppen-Nachrichten ist der Absender die Gruppe selbst.
|
||||
group = get_db().execute(
|
||||
'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
(sender['id'], tenant_id)
|
||||
).fetchone()
|
||||
group_id = group['id'] if group else None
|
||||
if group_id is not None:
|
||||
try:
|
||||
group_id = int(group_id)
|
||||
except (TypeError, ValueError):
|
||||
group_id = None
|
||||
return group_id
|
||||
|
||||
@staticmethod
|
||||
def _fetch_group(tenant_id, group_id):
|
||||
"""Lädt eine Gruppe mandantenspezifisch."""
|
||||
if not group_id:
|
||||
return None
|
||||
return get_db().execute(
|
||||
'SELECT id, aliasname FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
Heartbeat-Routine für WebSocket-Verbindungen
|
||||
|
||||
Der Server sendet jede Minute eine Nachricht mit Code 1 an alle
|
||||
authentifizierten Clients. Die Clients antworten mit Code 2; diese Antwort
|
||||
wird vom Broker ausschließlich an Dispatcher-Views weitergeleitet.
|
||||
|
||||
Zusätzlich räumt die Routine abgelaufene Late-Entry-Nachrichten auf, damit die
|
||||
Tabelle ws_messages_store nicht unbegrenzt wächst.
|
||||
"""
|
||||
from threading import Timer
|
||||
from cmbnet.ws import broker
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
|
||||
class HeartbeatManager:
|
||||
def __init__(self, interval=60):
|
||||
self.interval = interval
|
||||
self.running = False
|
||||
self.app = None
|
||||
self._timer = None
|
||||
|
||||
def start(self, app=None, interval=None):
|
||||
"""Startet die zyklische Heartbeat-Routine."""
|
||||
# Die App-Referenz wird benötigt, um im Hintergrund-Thread einen
|
||||
# Flask-App-Kontext für Datenbankzugriffe öffnen zu können.
|
||||
if app is not None:
|
||||
self.app = app
|
||||
if interval is not None:
|
||||
self.interval = interval
|
||||
|
||||
if self.running:
|
||||
return
|
||||
self.running = True
|
||||
self._send_heartbeat()
|
||||
|
||||
def stop(self):
|
||||
"""Stoppt die Heartbeat-Routine."""
|
||||
self.running = False
|
||||
if self._timer is not None:
|
||||
self._timer.cancel()
|
||||
self._timer = None
|
||||
|
||||
def _send_heartbeat(self):
|
||||
if not self.running:
|
||||
return
|
||||
|
||||
msg = WSMessage(sender_id=0, code=1, msg='ping')
|
||||
|
||||
# Nur authentifizierte Verbindungen erhalten einen Heartbeat.
|
||||
for tenant_id, connections in list(broker.connections.items()):
|
||||
for account_id, conn_info in list(connections.items()):
|
||||
if not broker.is_authenticated(tenant_id, account_id):
|
||||
continue
|
||||
try:
|
||||
conn_info['ws'].send(msg.to_json())
|
||||
except Exception:
|
||||
# Defekte Verbindungen werden beim Schließen durch die
|
||||
# WebSocket-Route entfernt.
|
||||
pass
|
||||
|
||||
# Abgelaufene persistierte Nachrichten löschen.
|
||||
if self.app is not None:
|
||||
try:
|
||||
with self.app.app_context():
|
||||
broker.cleanup_old_messages()
|
||||
except Exception as exc:
|
||||
print(f'Heartbeat cleanup error: {exc}')
|
||||
|
||||
# Nächsten Heartbeat planen. Der Timer läuft als Daemon, damit er den
|
||||
# Prozess beim Beenden nicht blockiert.
|
||||
self._timer = Timer(self.interval, self._send_heartbeat)
|
||||
self._timer.daemon = True
|
||||
self._timer.start()
|
||||
|
||||
|
||||
heartbeat_manager = HeartbeatManager()
|
||||
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
WebSocket Protokoll Definition
|
||||
"""
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class WSMessage:
|
||||
def __init__(self, sender_id=None, receiver_id=None, code=0, msg="", ts=None):
|
||||
self.sender_id = sender_id
|
||||
self.receiver_id = receiver_id
|
||||
self.code = code
|
||||
self.msg = msg
|
||||
self.ts = ts or int(datetime.now().timestamp() * 1000)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'sender_id': self.sender_id,
|
||||
'receiver_id': self.receiver_id,
|
||||
'code': self.code,
|
||||
'ts': self.ts,
|
||||
'msg': self.msg
|
||||
}
|
||||
|
||||
def to_json(self):
|
||||
return json.dumps(self.to_dict())
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data):
|
||||
return cls(
|
||||
sender_id=data.get('sender_id'),
|
||||
receiver_id=data.get('receiver_id'),
|
||||
code=data.get('code', 0),
|
||||
msg=data.get('msg', ''),
|
||||
ts=data.get('ts')
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str):
|
||||
try:
|
||||
data = json.loads(json_str)
|
||||
return cls.from_dict(data)
|
||||
except:
|
||||
return None
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
WebSocket Routes
|
||||
|
||||
Ablauf einer Verbindung:
|
||||
1. Client verbindet sich mit /<tenant>/ws.
|
||||
2. Client sendet Code 0 mit dem zuvor über die API geholten Einmal-Token.
|
||||
3. Erst nach erfolgreicher Prüfung dürfen fachliche Nachrichten gesendet
|
||||
werden. Vorher wird die Verbindung geschlossen.
|
||||
"""
|
||||
from flask import session
|
||||
from cmbnet.extensions import sock
|
||||
from cmbnet.ws import broker
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
|
||||
@sock.route('/<tenant>/ws')
|
||||
def ws(ws, tenant):
|
||||
"""WebSocket Endpoint"""
|
||||
from cmbnet.db import get_db
|
||||
|
||||
db = get_db()
|
||||
tenant_row = db.execute('SELECT * FROM tenants WHERE code = ?', (tenant,)).fetchone()
|
||||
if not tenant_row:
|
||||
ws.close()
|
||||
return
|
||||
|
||||
tenant_id = tenant_row['id']
|
||||
account_id = session.get('account_id')
|
||||
if not account_id:
|
||||
ws.close()
|
||||
return
|
||||
|
||||
# Verbindung registrieren, aber noch nicht als authentifiziert markieren.
|
||||
if not broker.register_connection(tenant_id, account_id, ws):
|
||||
ws.close()
|
||||
return
|
||||
|
||||
try:
|
||||
while True:
|
||||
data = ws.receive()
|
||||
if data is None:
|
||||
break
|
||||
|
||||
msg = WSMessage.from_json(data)
|
||||
if not msg:
|
||||
continue
|
||||
|
||||
# Die Absender-ID stammt immer aus der Session und kann vom Client
|
||||
# nicht gefälscht werden.
|
||||
msg.sender_id = account_id
|
||||
|
||||
# Code 0: Authentifizierung über den Einmal-Token.
|
||||
if msg.code == 0:
|
||||
if not broker.authenticate(tenant_id, account_id, msg.msg):
|
||||
ws.close()
|
||||
break
|
||||
continue
|
||||
|
||||
# Fachliche Nachrichten sind erst nach erfolgreicher
|
||||
# Authentifizierung erlaubt.
|
||||
if not broker.is_authenticated(tenant_id, account_id):
|
||||
ws.close()
|
||||
break
|
||||
|
||||
broker.route_message(tenant_id, msg, apply_business=True)
|
||||
|
||||
except Exception as exc:
|
||||
print(f'WebSocket error: {exc}')
|
||||
finally:
|
||||
broker.remove_connection(tenant_id, account_id, ws)
|
||||
Reference in new issue
Block a user