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