Firebase Cloud Messaging 1. Versuch
This commit is contained in:
1 parent
f1fb926c2f
commit
4c8b11c4d5
25 files changed
+2111
-31
No files matched your search
+247
-7
@@ -47,12 +47,17 @@ def client_is_connected(tenant_id, client_id):
|
||||
return bool(row and row['disconnected_at'] is None)
|
||||
|
||||
|
||||
def ensure_client(tenant_id, client_id, account_id, worker_id=None):
|
||||
def ensure_client(tenant_id, client_id, account_id, worker_id=None,
|
||||
client_type=None):
|
||||
"""Registriert eine Client-ID bzw. aktualisiert ihren Verbindungsstatus.
|
||||
|
||||
Gibt ``False`` zurück, wenn die Client-ID bereits einem anderen Account
|
||||
gehört. Ein solcher Wechsel wäre ein Hinweis auf eine manipulierte
|
||||
Zuordnung und wird vom Broker abgelehnt.
|
||||
|
||||
``client_type`` wird bei jedem Reconnect aktualisiert. ``None`` lässt
|
||||
einen bereits bekannten Typ unverändert, damit ältere Clients ohne
|
||||
Typangabe ihre FCM-Berechtigung nicht verlieren.
|
||||
"""
|
||||
db = get_db()
|
||||
row = get_client(tenant_id, client_id)
|
||||
@@ -63,19 +68,20 @@ def ensure_client(tenant_id, client_id, account_id, worker_id=None):
|
||||
return False
|
||||
db.execute(
|
||||
'UPDATE ws_clients SET worker_id = ?, connected_at = ?, '
|
||||
'disconnected_at = NULL, authenticated = 0 '
|
||||
'disconnected_at = NULL, authenticated = 0, '
|
||||
'client_type = COALESCE(?, client_type) '
|
||||
'WHERE tenant_id = ? AND client_id = ?',
|
||||
(worker_id, current, tenant_id, client_id)
|
||||
(worker_id, current, client_type, tenant_id, client_id)
|
||||
)
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
db.execute(
|
||||
'INSERT INTO ws_clients '
|
||||
'(tenant_id, client_id, account_id, worker_id, connected_at, '
|
||||
' authenticated, last_seq) '
|
||||
'VALUES (?, ?, ?, ?, ?, 0, 0)',
|
||||
(tenant_id, client_id, account_id, worker_id, current)
|
||||
'(tenant_id, client_id, account_id, client_type, worker_id, '
|
||||
' connected_at, authenticated, last_seq) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?, 0, 0)',
|
||||
(tenant_id, client_id, account_id, client_type, worker_id, current)
|
||||
)
|
||||
db.commit()
|
||||
return True
|
||||
@@ -207,6 +213,236 @@ def client_ids_for_accounts(tenant_id, account_ids):
|
||||
return result
|
||||
|
||||
|
||||
def set_client_wake_sent(tenant_id, client_id, reason=None, timestamp=None):
|
||||
"""Vermerkt ein erfolgreich abgesetztes FCM-Aufwachsignal."""
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'UPDATE ws_clients SET last_wake_at = ?, last_wake_reason = ? '
|
||||
'WHERE tenant_id = ? AND client_id = ?',
|
||||
(timestamp if timestamp is not None else now(), reason, tenant_id, client_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def upsert_push_token(tenant_id, client_id, account_id, token, client_type,
|
||||
platform=None, auto_position=False):
|
||||
"""Speichert bzw. aktualisiert ein FCM-Token.
|
||||
|
||||
Das Token ist projektweit eindeutig. Meldet sich derselbe Browser nach
|
||||
einem Neuladen mit einer neuen Client-ID an, wird der bestehende Eintrag
|
||||
verschoben, statt ein zweites Token anzulegen. Ältere Tokens derselben
|
||||
Client-ID werden entfernt, damit nach einer Token-Rotation keine doppelten
|
||||
Wake-Signale entstehen.
|
||||
"""
|
||||
db = get_db()
|
||||
current = now()
|
||||
db.execute(
|
||||
'DELETE FROM ws_push_tokens '
|
||||
'WHERE tenant_id = ? AND client_id = ? AND token <> ?',
|
||||
(tenant_id, client_id, token)
|
||||
)
|
||||
db.execute(
|
||||
'''INSERT INTO ws_push_tokens
|
||||
(tenant_id, client_id, account_id, token, client_type,
|
||||
platform, auto_position, invalid, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)
|
||||
ON CONFLICT(token) DO UPDATE SET
|
||||
tenant_id = excluded.tenant_id,
|
||||
client_id = excluded.client_id,
|
||||
account_id = excluded.account_id,
|
||||
client_type = excluded.client_type,
|
||||
platform = excluded.platform,
|
||||
auto_position = excluded.auto_position,
|
||||
invalid = 0,
|
||||
updated_at = excluded.updated_at''',
|
||||
(tenant_id, client_id, account_id, token, client_type,
|
||||
platform, 1 if auto_position else 0, current, current)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def delete_push_token(tenant_id, token=None, client_id=None, account_id=None):
|
||||
"""Entfernt ein FCM-Token gezielt über Token oder Client-ID."""
|
||||
clauses = ['tenant_id = ?']
|
||||
params = [tenant_id]
|
||||
if token:
|
||||
clauses.append('token = ?')
|
||||
params.append(token)
|
||||
if client_id:
|
||||
clauses.append('client_id = ?')
|
||||
params.append(client_id)
|
||||
if account_id is not None:
|
||||
clauses.append('account_id = ?')
|
||||
params.append(account_id)
|
||||
if len(clauses) == 1:
|
||||
return
|
||||
db = get_db()
|
||||
db.execute(
|
||||
f'DELETE FROM ws_push_tokens WHERE {" AND ".join(clauses)}',
|
||||
tuple(params)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_push_token(tenant_id, client_id):
|
||||
"""Liefert das zuletzt aktualisierte, gültige Token eines Clients."""
|
||||
return get_db().execute(
|
||||
'''SELECT * FROM ws_push_tokens
|
||||
WHERE tenant_id = ? AND client_id = ? AND invalid = 0
|
||||
ORDER BY updated_at DESC, id DESC LIMIT 1''',
|
||||
(tenant_id, client_id)
|
||||
).fetchone()
|
||||
|
||||
|
||||
def mark_push_token_invalid(token):
|
||||
"""Markiert ein von FCM abgelehntes Token als ungültig."""
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'UPDATE ws_push_tokens SET invalid = 1, updated_at = ? WHERE token = ?',
|
||||
(now(), token)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def _offline_mobile_wake_query(tenant_id, disconnected_before,
|
||||
re_wake_before=None, group_id=None,
|
||||
auto_position_only=False, client_id=None,
|
||||
limit=500):
|
||||
sql = [
|
||||
'''SELECT c.tenant_id, c.client_id, c.account_id, c.client_type,
|
||||
c.disconnected_at, c.last_wake_at, c.last_wake_reason,
|
||||
p.token, p.platform, p.auto_position
|
||||
FROM ws_clients c
|
||||
JOIN ws_push_tokens p
|
||||
ON p.id = (
|
||||
SELECT p2.id FROM ws_push_tokens p2
|
||||
WHERE p2.tenant_id = c.tenant_id
|
||||
AND p2.client_id = c.client_id
|
||||
AND p2.invalid = 0
|
||||
ORDER BY p2.updated_at DESC, p2.id DESC
|
||||
LIMIT 1
|
||||
)
|
||||
WHERE c.tenant_id = ?
|
||||
AND c.client_type IN ('group_view', 'dispatcher_mobile')
|
||||
AND c.disconnected_at IS NOT NULL
|
||||
AND c.disconnected_at <= ?'''
|
||||
]
|
||||
params = [tenant_id, disconnected_before]
|
||||
|
||||
if client_id is not None:
|
||||
sql.append('AND c.client_id = ?')
|
||||
params.append(client_id)
|
||||
|
||||
if re_wake_before is not None:
|
||||
sql.append(
|
||||
'AND (c.last_wake_at IS NULL OR c.last_wake_at <= ?)'
|
||||
)
|
||||
params.append(re_wake_before)
|
||||
|
||||
if auto_position_only:
|
||||
sql.append("AND (c.client_type = 'dispatcher_mobile' OR p.auto_position = 1)")
|
||||
|
||||
if group_id is not None:
|
||||
sql.append(
|
||||
'''AND EXISTS (
|
||||
SELECT 1 FROM group_accounts ga
|
||||
WHERE ga.tenant_id = c.tenant_id
|
||||
AND ga.account_id = c.account_id
|
||||
AND ga.group_id = ?
|
||||
)'''
|
||||
)
|
||||
params.append(group_id)
|
||||
|
||||
sql.append('ORDER BY c.disconnected_at ASC LIMIT ?')
|
||||
params.append(max(1, int(limit)))
|
||||
return ' '.join(sql), tuple(params)
|
||||
|
||||
|
||||
def offline_mobile_wake_candidates(tenant_id, disconnected_before,
|
||||
re_wake_before=None, group_id=None,
|
||||
auto_position_only=False, client_id=None,
|
||||
limit=500):
|
||||
"""Liefert offline mobile Clients mit gültigem FCM-Token.
|
||||
|
||||
``disconnected_before`` ist der Spätzeitpunkt, zu dem die Trennung
|
||||
eingetreten sein muss (für den regulären Offline-Timeout).
|
||||
``re_wake_before`` verhindert zu häufige Wiederholungen; ``None`` hebt
|
||||
die Sperre auf (manueller Aufruf).
|
||||
``auto_position_only`` berücksichtigt nur Gruppen-Views, bei denen die
|
||||
automatische Positionsübertragung aktiviert ist.
|
||||
"""
|
||||
sql, params = _offline_mobile_wake_query(
|
||||
tenant_id,
|
||||
disconnected_before,
|
||||
re_wake_before=re_wake_before,
|
||||
group_id=group_id,
|
||||
auto_position_only=auto_position_only,
|
||||
client_id=client_id,
|
||||
limit=limit,
|
||||
)
|
||||
return get_db().execute(sql, params).fetchall()
|
||||
|
||||
|
||||
def claim_offline_mobile_wakes(tenant_id, disconnected_before,
|
||||
re_wake_before=None, group_id=None,
|
||||
auto_position_only=False, client_id=None,
|
||||
reason='offline', limit=500):
|
||||
"""Reserviert fällige Wake-Kandidaten prozessübergreifend.
|
||||
|
||||
Mehrere WSGI-Worker dürfen nicht dasselbe FCM-Signal senden. Deshalb
|
||||
werden die Kandidaten in einer ``BEGIN IMMEDIATE``-Transaktion gelesen
|
||||
und ihr ``last_wake_at`` sofort gesetzt. Der tatsächliche FCM-Versand
|
||||
erfolgt erst nach dem Commit.
|
||||
"""
|
||||
db = get_db()
|
||||
if db.in_transaction:
|
||||
db.commit()
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
try:
|
||||
sql, params = _offline_mobile_wake_query(
|
||||
tenant_id,
|
||||
disconnected_before,
|
||||
re_wake_before=re_wake_before,
|
||||
group_id=group_id,
|
||||
auto_position_only=auto_position_only,
|
||||
client_id=client_id,
|
||||
limit=limit,
|
||||
)
|
||||
rows = db.execute(sql, params).fetchall()
|
||||
current = now()
|
||||
for row in rows:
|
||||
db.execute(
|
||||
'UPDATE ws_clients SET last_wake_at = ?, last_wake_reason = ? '
|
||||
'WHERE tenant_id = ? AND client_id = ?',
|
||||
(current, reason, tenant_id, row['client_id'])
|
||||
)
|
||||
db.commit()
|
||||
return rows
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def cleanup_orphan_push_tokens(max_age_seconds):
|
||||
"""Entfernt ungültige sowie verwaiste, lange nicht aktualisierte Tokens."""
|
||||
db = get_db()
|
||||
cutoff = now() - max_age_seconds
|
||||
db.execute(
|
||||
'DELETE FROM ws_push_tokens WHERE invalid = 1'
|
||||
)
|
||||
db.execute(
|
||||
'''DELETE FROM ws_push_tokens
|
||||
WHERE updated_at < ?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM ws_clients c
|
||||
WHERE c.tenant_id = ws_push_tokens.tenant_id
|
||||
AND c.client_id = ws_push_tokens.client_id
|
||||
)''',
|
||||
(cutoff,)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def describe_connections(tenant_id):
|
||||
"""Liefert alle aktuell verbundenen Clients inklusive Account und Gruppe."""
|
||||
rows = get_db().execute(
|
||||
@@ -477,6 +713,10 @@ def cleanup_clients(retention_seconds):
|
||||
'DELETE FROM ws_client_queue WHERE tenant_id = ? AND client_id = ?',
|
||||
(tenant_id, client_id)
|
||||
)
|
||||
db.execute(
|
||||
'DELETE FROM ws_push_tokens WHERE tenant_id = ? AND client_id = ?',
|
||||
(tenant_id, client_id)
|
||||
)
|
||||
db.execute(
|
||||
'DELETE FROM ws_clients WHERE tenant_id = ? AND client_id = ?',
|
||||
(tenant_id, client_id)
|
||||
|
||||
Reference in new issue
Block a user