chat drin
This commit is contained in:
1 parent
ef238f3b9c
commit
988a5410f7
12 files changed
+1115
-4
No files matched your search
@@ -0,0 +1,249 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Chat Plugin: backend.
|
||||
*
|
||||
* Local message cache + thin proxy over the relays /api/chat routes.
|
||||
* The plugin keeps a local SQLite table so the UI can render conversation
|
||||
* history without re-polling on every open. Reuses the existing relay_url /
|
||||
* relay_username / relay_key settings (no new credentials).
|
||||
*
|
||||
* Routes:
|
||||
* GET /api/chat/conversations → peer list with last msg + unread
|
||||
* GET /api/chat/messages?peer=X → all messages with one peer (asc)
|
||||
* POST /api/chat/send {peer,body} → encrypts + pushes via relay, stores local
|
||||
* POST /api/chat/poll → pulls new from relay, returns count
|
||||
* POST /api/chat/read {peer} → mark all incoming from peer as read
|
||||
* GET /api/chat/recipients → proxy of relays /api/tenants
|
||||
*/
|
||||
|
||||
(function () {
|
||||
$db = Database::connect();
|
||||
$db->exec("
|
||||
CREATE TABLE IF NOT EXISTS chat_messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
peer TEXT NOT NULL,
|
||||
direction TEXT NOT NULL CHECK(direction IN ('in','out')),
|
||||
body TEXT NOT NULL,
|
||||
relay_id INTEGER,
|
||||
sent_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
is_read INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
");
|
||||
$db->exec("CREATE INDEX IF NOT EXISTS idx_chat_peer ON chat_messages(peer, sent_at)");
|
||||
$db->exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_chat_relay_id ON chat_messages(relay_id) WHERE relay_id IS NOT NULL");
|
||||
// Track the largest relay msg id we've ever seen (so the next poll uses since=that)
|
||||
$db->exec("
|
||||
CREATE TABLE IF NOT EXISTS chat_state (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT
|
||||
)
|
||||
");
|
||||
})();
|
||||
|
||||
function chatJson($data, int $code = 200): void {
|
||||
http_response_code($code);
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode($data);
|
||||
exit;
|
||||
}
|
||||
|
||||
function chatRelaySettings(): array {
|
||||
$db = Database::connect();
|
||||
return [
|
||||
'url' => $db->query("SELECT value FROM settings WHERE key = 'relay_url'")->fetchColumn() ?: '',
|
||||
'user' => $db->query("SELECT value FROM settings WHERE key = 'relay_username'")->fetchColumn() ?: '',
|
||||
'key' => $db->query("SELECT value FROM settings WHERE key = 'relay_key'")->fetchColumn() ?: '',
|
||||
];
|
||||
}
|
||||
|
||||
/** Same envelope format as the existing relay sync (HYPRCRD-RELAY-V1). */
|
||||
function chatEncrypt(string $plain, string $relayKey): string {
|
||||
$encKey = substr(hash('sha256', $relayKey), 0, 32);
|
||||
$iv = random_bytes(16);
|
||||
$cipher = openssl_encrypt($plain, 'aes-256-cbc', $encKey, OPENSSL_RAW_DATA, $iv);
|
||||
return "HYPRCRD-RELAY-V1\n" . base64_encode($iv . $cipher);
|
||||
}
|
||||
|
||||
function chatDecrypt(string $envelope, string $relayKey): string {
|
||||
if (!str_starts_with($envelope, 'HYPRCRD-RELAY-V1')) return '';
|
||||
$b64 = trim(substr($envelope, strlen('HYPRCRD-RELAY-V1') + 1));
|
||||
$raw = base64_decode($b64);
|
||||
if (!$raw || strlen($raw) < 17) return '';
|
||||
$encKey = substr(hash('sha256', $relayKey), 0, 32);
|
||||
$iv = substr($raw, 0, 16);
|
||||
$cipher = substr($raw, 16);
|
||||
$result = openssl_decrypt($cipher, 'aes-256-cbc', $encKey, OPENSSL_RAW_DATA, $iv);
|
||||
return $result !== false ? $result : '';
|
||||
}
|
||||
|
||||
function chatGetState(string $key, $default = null) {
|
||||
$db = Database::connect();
|
||||
$stmt = $db->prepare('SELECT value FROM chat_state WHERE key = :k');
|
||||
$stmt->execute(['k' => $key]);
|
||||
$v = $stmt->fetchColumn();
|
||||
return $v === false ? $default : $v;
|
||||
}
|
||||
|
||||
function chatSetState(string $key, $value): void {
|
||||
$db = Database::connect();
|
||||
$db->prepare('INSERT OR REPLACE INTO chat_state (key, value) VALUES (:k, :v)')
|
||||
->execute(['k' => $key, 'v' => (string)$value]);
|
||||
}
|
||||
|
||||
PluginManager::instance()->onApiRoute(function (string $route, string $method) {
|
||||
|
||||
if ($route === '/api/chat/conversations' && $method === 'GET') {
|
||||
$db = Database::connect();
|
||||
// Latest message per peer + unread count, single query
|
||||
$rows = $db->query("
|
||||
SELECT
|
||||
peer,
|
||||
MAX(sent_at) AS last_at,
|
||||
(SELECT body FROM chat_messages c2 WHERE c2.peer = c1.peer ORDER BY id DESC LIMIT 1) AS last_body,
|
||||
(SELECT direction FROM chat_messages c3 WHERE c3.peer = c1.peer ORDER BY id DESC LIMIT 1) AS last_direction,
|
||||
SUM(CASE WHEN direction = 'in' AND is_read = 0 THEN 1 ELSE 0 END) AS unread
|
||||
FROM chat_messages c1
|
||||
GROUP BY peer
|
||||
ORDER BY last_at DESC
|
||||
")->fetchAll();
|
||||
$totalUnread = array_sum(array_map(fn($r) => (int)$r['unread'], $rows));
|
||||
chatJson(['conversations' => $rows, 'total_unread' => $totalUnread]);
|
||||
}
|
||||
|
||||
if ($route === '/api/chat/messages' && $method === 'GET') {
|
||||
$peer = trim((string)($_GET['peer'] ?? ''));
|
||||
if ($peer === '') chatJson(['error' => 'peer required'], 400);
|
||||
$db = Database::connect();
|
||||
$stmt = $db->prepare('SELECT id, direction, body, sent_at, is_read FROM chat_messages WHERE peer = :p ORDER BY id ASC LIMIT 500');
|
||||
$stmt->execute(['p' => $peer]);
|
||||
chatJson(['messages' => $stmt->fetchAll()]);
|
||||
}
|
||||
|
||||
if ($route === '/api/chat/send' && $method === 'POST') {
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$peer = trim((string)($input['peer'] ?? ''));
|
||||
$body = (string)($input['body'] ?? '');
|
||||
if ($peer === '' || $body === '') chatJson(['error' => 'peer and body required'], 400);
|
||||
|
||||
$r = chatRelaySettings();
|
||||
if (!$r['url'] || !$r['user'] || !$r['key']) {
|
||||
chatJson(['error' => 'relay not configured (set URL, username, and secret in settings)'], 400);
|
||||
}
|
||||
|
||||
$envelope = chatEncrypt($body, $r['key']);
|
||||
$ch = curl_init(rtrim($r['url'], '/') . '/api/chat');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => json_encode(['recipient' => $peer, 'body' => $envelope]),
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-Type: application/json',
|
||||
'X-Relay-User: ' . $r['user'],
|
||||
'X-Relay-Key: ' . $r['key'],
|
||||
],
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
]);
|
||||
$response = curl_exec($ch);
|
||||
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($status !== 200) {
|
||||
$relayErr = '';
|
||||
$decoded = json_decode($response, true);
|
||||
if (is_array($decoded) && !empty($decoded['error'])) $relayErr = ' — ' . $decoded['error'];
|
||||
chatJson(['ok' => false, 'error' => "relay returned HTTP $status$relayErr"]);
|
||||
}
|
||||
|
||||
$resData = json_decode($response, true);
|
||||
$relayId = isset($resData['id']) ? (int)$resData['id'] : null;
|
||||
|
||||
// Store the outgoing message locally so the UI can render it immediately
|
||||
$db = Database::connect();
|
||||
$db->prepare('INSERT INTO chat_messages (peer, direction, body, relay_id, sent_at, is_read) VALUES (:p, "out", :b, NULL, datetime("now"), 1)')
|
||||
->execute(['p' => $peer, 'b' => $body]);
|
||||
chatJson(['ok' => true, 'id' => (int)$db->lastInsertId()]);
|
||||
}
|
||||
|
||||
if ($route === '/api/chat/poll' && $method === 'POST') {
|
||||
$r = chatRelaySettings();
|
||||
if (!$r['url'] || !$r['user'] || !$r['key']) {
|
||||
chatJson(['ok' => true, 'new' => 0, 'note' => 'relay not configured']);
|
||||
}
|
||||
$since = (int)chatGetState('last_relay_id', 0);
|
||||
|
||||
$ch = curl_init(rtrim($r['url'], '/') . '/api/chat?since=' . $since);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'X-Relay-User: ' . $r['user'],
|
||||
'X-Relay-Key: ' . $r['key'],
|
||||
],
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
]);
|
||||
$response = curl_exec($ch);
|
||||
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($status !== 200) {
|
||||
$relayErr = '';
|
||||
$decoded = json_decode($response, true);
|
||||
if (is_array($decoded) && !empty($decoded['error'])) $relayErr = ' — ' . $decoded['error'];
|
||||
chatJson(['ok' => false, 'error' => "relay returned HTTP $status$relayErr"]);
|
||||
}
|
||||
|
||||
$data = json_decode($response, true) ?: [];
|
||||
$messages = $data['messages'] ?? [];
|
||||
$maxId = (int)($data['max_id'] ?? $since);
|
||||
|
||||
$db = Database::connect();
|
||||
$newCount = 0;
|
||||
$insert = $db->prepare('INSERT OR IGNORE INTO chat_messages (peer, direction, body, relay_id, sent_at, is_read) VALUES (:p, "in", :b, :rid, :ts, 0)');
|
||||
foreach ($messages as $m) {
|
||||
$plain = chatDecrypt($m['body'] ?? '', $r['key']);
|
||||
if ($plain === '') continue;
|
||||
$insert->execute([
|
||||
'p' => $m['sender_username'] ?? '?',
|
||||
'b' => $plain,
|
||||
'rid' => (int)$m['id'],
|
||||
'ts' => $m['created_at'] ?? date('Y-m-d H:i:s'),
|
||||
]);
|
||||
if ($insert->rowCount() > 0) $newCount++;
|
||||
}
|
||||
if ($maxId > $since) chatSetState('last_relay_id', $maxId);
|
||||
|
||||
chatJson(['ok' => true, 'new' => $newCount]);
|
||||
}
|
||||
|
||||
if ($route === '/api/chat/read' && $method === 'POST') {
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$peer = trim((string)($input['peer'] ?? ''));
|
||||
if ($peer === '') chatJson(['error' => 'peer required'], 400);
|
||||
$db = Database::connect();
|
||||
$db->prepare('UPDATE chat_messages SET is_read = 1 WHERE peer = :p AND direction = "in" AND is_read = 0')
|
||||
->execute(['p' => $peer]);
|
||||
chatJson(['ok' => true]);
|
||||
}
|
||||
|
||||
if ($route === '/api/chat/recipients' && $method === 'GET') {
|
||||
$r = chatRelaySettings();
|
||||
if (!$r['url'] || !$r['user'] || !$r['key']) {
|
||||
chatJson(['ok' => false, 'error' => 'relay not configured']);
|
||||
}
|
||||
$ch = curl_init(rtrim($r['url'], '/') . '/api/tenants');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'X-Relay-User: ' . $r['user'],
|
||||
'X-Relay-Key: ' . $r['key'],
|
||||
],
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
]);
|
||||
$response = curl_exec($ch);
|
||||
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
if ($status !== 200) chatJson(['ok' => false, 'error' => "relay returned HTTP $status"]);
|
||||
$data = json_decode($response, true) ?: [];
|
||||
chatJson(['ok' => true, 'tenants' => $data['tenants'] ?? [], 'self' => $data['self'] ?? $r['user']]);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user