Compare commits
2
Commits
999ecc1a61
...
b7bbce7374
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7bbce7374 | ||
|
|
21c30393fc |
+30
-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 && i.isAuthenticated);
|
||||
if (sock) return sock;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -131,6 +153,7 @@ function handleWhatsAppMessage(ws: WebSocket, data: string) {
|
||||
console.log("[WhatsApp event]", event, data);
|
||||
|
||||
if (event === "ready") {
|
||||
ws.isAuthenticated = data.authenticated || false;
|
||||
ws.deviceId = data.deviceId;
|
||||
ws.deviceName = data.deviceName;
|
||||
}
|
||||
@@ -223,11 +246,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 +278,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
+3
-1
@@ -2,8 +2,10 @@ import "ws";
|
||||
|
||||
declare module "ws" {
|
||||
interface WebSocket {
|
||||
lastAlive?: number;
|
||||
isAuthenticated?: boolean;
|
||||
deviceId?: string;
|
||||
deviceName?: string;
|
||||
lastAlive?: number;
|
||||
lastSuccessfulCall?: number;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user