feat: server update
This commit is contained in:
+29
-9
@@ -28,15 +28,37 @@ function requestId() {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
|
||||
function getDevices() {
|
||||
return [
|
||||
...new Map(
|
||||
[...bridgeSockets].reverse().map((ws) => [
|
||||
ws.deviceId,
|
||||
{
|
||||
id: ws.deviceId,
|
||||
name: ws.deviceName,
|
||||
lastAlive: ws.lastAlive,
|
||||
lastSuccessfulCall: ws.lastSuccessfulCall,
|
||||
},
|
||||
]),
|
||||
).values(),
|
||||
];
|
||||
}
|
||||
|
||||
function getWhatsApp(deviceId?: string): WebSocket | null {
|
||||
if (deviceId) {
|
||||
for (const ws of [...bridgeSockets].reverse()) {
|
||||
if (
|
||||
ws.readyState === WebSocket.OPEN &&
|
||||
(!deviceId || ws.deviceId === deviceId)
|
||||
) {
|
||||
if (ws.readyState === WebSocket.OPEN && ws.deviceId === deviceId) {
|
||||
return ws;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// find the most recent active bridge
|
||||
const sock = [...bridgeSockets]
|
||||
.sort((a, b) => (b.lastSuccessfulCall || 0) - (a.lastSuccessfulCall || 0))
|
||||
.find((i) => i.readyState === WebSocket.OPEN);
|
||||
if (sock) return sock;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -223,11 +245,7 @@ wss.on("connection", (ws) => {
|
||||
|
||||
switch (method) {
|
||||
case "listDevices":
|
||||
result = [...bridgeSockets].map((ws) => ({
|
||||
id: ws.deviceId,
|
||||
name: ws.deviceName,
|
||||
lastAlive: ws.lastAlive,
|
||||
}));
|
||||
result = getDevices();
|
||||
break;
|
||||
|
||||
// cached
|
||||
@@ -259,6 +277,8 @@ wss.on("connection", (ws) => {
|
||||
throw new Error(`Unsupported method: ${(request as any).method}`);
|
||||
}
|
||||
|
||||
ws.lastSuccessfulCall = Date.now();
|
||||
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "response",
|
||||
|
||||
Vendored
+2
-1
@@ -2,8 +2,9 @@ import "ws";
|
||||
|
||||
declare module "ws" {
|
||||
interface WebSocket {
|
||||
lastAlive?: number;
|
||||
deviceId?: string;
|
||||
deviceName?: string;
|
||||
lastAlive?: number;
|
||||
lastSuccessfulCall?: number;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user