Updates to join (server/client)

- Check if the available nodes are connected to a vc in the given guild
This commit is contained in:
Logan Cusano
2024-02-11 04:32:58 -05:00
parent b78fa8307d
commit ed33654b8c
4 changed files with 103 additions and 23 deletions

View File

@@ -7,6 +7,7 @@ import {
AudioPlayerStatus, AudioPlayerStatus,
VoiceConnectionStatus, VoiceConnectionStatus,
joinVoiceChannel, joinVoiceChannel,
getVoiceConnection,
} from '@discordjs/voice'; } from '@discordjs/voice';
import { GatewayIntentBits } from 'discord-api-types/v10'; import { GatewayIntentBits } from 'discord-api-types/v10';
@@ -90,6 +91,12 @@ export async function getVoiceChannelFromID(client, channelID) {
return client.channels.cache.get(channelID) return client.channels.cache.get(channelID)
} }
export async function checkIfConnectedToVC(guildId) {
const connection = getVoiceConnection(guildId)
console.log("Connection!", connection);
return connection
}
export async function initDiscordBotClient(token, readyCallback){ export async function initDiscordBotClient(token, readyCallback){
const client = new Client({ const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.MessageContent], intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.MessageContent],

View File

@@ -1,5 +1,5 @@
import { io } from "socket.io-client"; import { io } from "socket.io-client";
import { connectToChannel, initDiscordBotClient, getVoiceChannelFromID } from '../discordAudioBot/dab.mjs'; import { connectToChannel, initDiscordBotClient, getVoiceChannelFromID, checkIfConnectedToVC } from '../discordAudioBot/dab.mjs';
import { logIntoServerWrapper, sendNodeUpdateWrapper } from "./socketClientWrappers.mjs"; import { logIntoServerWrapper, sendNodeUpdateWrapper } from "./socketClientWrappers.mjs";
export const initSocketConnection = async (localNodeConfig) => { export const initSocketConnection = async (localNodeConfig) => {
@@ -25,8 +25,23 @@ export const initSocketConnection = async (localNodeConfig) => {
}); });
}); });
socket.on('node-leave', () => { socket.on('node-leave', async () => {
console.log("Leave requested"); console.log("Leave requested");
const connection = await getVoiceConnection(myVoiceChannel.guild.id);
if (connection) {
console.log("There is an open VC connection, closing it now");
connection.destroy();
}
});
socket.on('node-check-connected-status', async (guildId, socketCallback) => {
console.log("Requested status check");
if (await checkIfConnectedToVC(guildId)) {
console.log("There is an open VC connection");
socketCallback(true);
} else {
socketCallback(false);
}
}); });
socket.on('disconnect', () => { socket.on('disconnect', () => {

View File

@@ -1,5 +1,5 @@
import { SlashCommandBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js'; import { SlashCommandBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js';
import { requestNodeJoinSystem } from '../../modules/socketServerWrappers.mjs'; import { requestNodeJoinSystem, checkIfNodeIsConnectedToVC } from '../../modules/socketServerWrappers.mjs';
import { getSystemsByNuid, getAllSystems, getSystemByName } from '../../modules/mongoSystemsWrappers.mjs'; import { getSystemsByNuid, getAllSystems, getSystemByName } from '../../modules/mongoSystemsWrappers.mjs';
// Exporting data property // Exporting data property
@@ -39,32 +39,35 @@ export async function execute(nodeIo, interaction) {
const selectedSystem = interaction.options.getString('system'); const selectedSystem = interaction.options.getString('system');
try { try {
// Get all open socket nodes
const openSockets = await nodeIo.allSockets(); // TODO - Filter the returned nodes to only nodes that have the radio capability
console.log("All open sockets: ", openSockets);
// Get the selected system object from the DB // Get the selected system object from the DB
const system = await getSystemByName(selectedSystem); const system = await getSystemByName(selectedSystem);
// Function wrapper to request the selected/only node to join the selected system // Function wrapper to request the selected/only node to join the selected system
const joinSelectedNode = async (selectedNodeSocketId) => { const joinSelectedNode = async (selectedNodeSocketId) => {
const openSocket = await nodeIo.sockets.sockets.get(selectedNodeSocketId); const openSocket = await nodeIo.sockets.sockets.get(selectedNodeSocketId);
console.log("Joining selected open socket:", openSocket.id, system.name, channelToJoin.id, openSocket.node.name); console.log("Joining selected open socket:", selectedNodeSocketId, system.name, channelToJoin.id, openSocket.node.name);
// Ask the node to join the selected channel and system // Ask the node to join the selected channel and system
await requestNodeJoinSystem(openSocket, system.name, channelToJoin.id); await requestNodeJoinSystem(openSocket, system.name, channelToJoin.id);
} }
// Get all open socket nodes
const openSockets = [...await nodeIo.allSockets()]; // TODO - Filter the returned nodes to only nodes that have the radio capability
console.log("All open sockets: ", openSockets);
var availableNodes = []; var availableNodes = [];
// Check each open socket to see if the ID is included in the selected system // Check each open socket to see if the node has the requested system
await openSockets.forEach(openSocket => { await Promise.all(openSockets.map(async openSocket => {
openSocket = nodeIo.sockets.sockets.get(openSocket); openSocket = await nodeIo.sockets.sockets.get(openSocket);
// TODO - Determine if the node is already connected elsewhere const connected = await checkIfNodeIsConnectedToVC(nodeIo, interaction.guild.id, openSocket.node.nuid);
// Check if this node has the requested system, if so add it to the availble array console.log("Connected:", connected);
if (system.nodes.includes(openSocket.node.nuid)) { if (!connected) {
availableNodes.push(openSocket); // Check if this node has the requested system, if so add it to the availble array
if (system.nodes.includes(openSocket.node.nuid)) {
availableNodes.push(openSocket);
}
} }
}); }));
console.log("Availble nodes:", availableNodes, availableNodes.map(socket => socket.node.name)); console.log("Availble nodes:", availableNodes, availableNodes.map(socket => socket.node.name));
@@ -77,7 +80,7 @@ export async function execute(nodeIo, interaction) {
// Request the node to join // Request the node to join
await joinSelectedNode(availableNodes[0].id); await joinSelectedNode(availableNodes[0].id);
// Let the user know // Let the user know
await interaction.editReply({ content: `Ok ${interaction.member.id}, a bot will join your channel listening to *'${system.name}'* shortly`, components: [] }); await interaction.editReply({ content: `Ok <@${interaction.member.id}>, a bot will join your channel listening to *'${system.name}'* shortly`, components: [] });
} else if (availableNodes.length > 1) { } else if (availableNodes.length > 1) {
// There is more than one node availble for the requested system // There is more than one node availble for the requested system
const nodeSelectionButtons = [] const nodeSelectionButtons = []
@@ -104,7 +107,7 @@ export async function execute(nodeIo, interaction) {
// Run the local wrapper to listen to the selected node // Run the local wrapper to listen to the selected node
await joinSelectedNode(selectedNode.customId); await joinSelectedNode(selectedNode.customId);
// Let the user know // Let the user know
await selectedNodeConfirmation.update({ content: `Ok ${interaction.member.id}, a bot will join your channel listening to *'${system.name}'*`, components: [] }); await selectedNodeConfirmation.update({ content: `Ok <@${interaction.member.id}>, a bot will join your channel listening to *'${system.name}'*`, components: [] });
} catch (e) { } catch (e) {
console.error(e); console.error(e);
// Timeout the prompt if the user doesn't interact with it // Timeout the prompt if the user doesn't interact with it

View File

@@ -114,7 +114,7 @@ export const nearbySystemsUpdateWraper = async (nuid, nearbySystems) => {
} else { } else {
// The systems are not the same // The systems are not the same
// TODO - Implement logic to handle if system names match, but they are for different frequencies or have additional freqs // TODO - Implement logic to handle if system names match, but they are for different frequencies or have additional freqs
// Check if the current node is listed in the nodes, if not add it // Check if the current node is listed in the nodes, if not add it
if (!existingSystem.nodes.includes(nuid)) { if (!existingSystem.nodes.includes(nuid)) {
existingSystem.nodes.push(nuid); existingSystem.nodes.push(nuid);
@@ -141,23 +141,78 @@ export const nearbySystemsUpdateWraper = async (nuid, nearbySystems) => {
* @param {string} nuid The NUID to find within the open sockets * @param {string} nuid The NUID to find within the open sockets
* @returns {string|null} Will return the open socket ID or NULL * @returns {string|null} Will return the open socket ID or NULL
*/ */
const getSocketIdByNuid = async (nuid) => { const getSocketIdByNuid = async (nodeIo, nuid) => {
for (const openSocket in openSockets) { for (const openSocket in await nodeIo.allSockets()) {
if (openSockets[openSocket] == nuid) if (openSockets[openSocket] == nuid)
return openSocket; return openSocket;
} }
return null; return null;
} }
/**
* Get all nodes that are connected to a voice channel
* @param {any} nodeIo
* @param {any} guildId The guild ID string for the guild we are looking in
* @returns {any}
*/
export const getAllSocketsConnectedToVC = async (nodeIo, guildId) => {
// Get all open socket nodes
// TODO - require a server guild to filter the results, ie this would be able to check what server the VCs the nodes are connected are in
const openSockets = [...await nodeIo.allSockets()]; // TODO - Filter the returned nodes to only nodes that have the radio capability
// Check each open socket to see if the node has the requested system
const socketsConnectedToVC = []
await Promise.all(openSockets.map(async openSocket => {
openSocket = await nodeIo.sockets.sockets.get(openSocket);
await new Promise((res) => {
openSocket.emit('node-check-connected-status', guildId, (status) => {
if (status) {
console.log("Socket is connected to VC:", openSocket.node.name);
socketsConnectedToVC.push(openSocket);
} else {
console.log("Socket is NOT connected to VC:", openSocket.node.name);
}
res();
})
});
}));
return socketsConnectedToVC;
}
/**
* Wrapper to check if the given NUID is connected to a VC
* @param {any} nodeIo The nodeIo object that contains the IO server
* @param {any} nuid The NUID string that we would like to find in the open socket connections
* @returns {any}
*/
export const checkIfNodeIsConnectedToVC = async (nodeIo, guildId, nuid) => {
const socketsConnectedToVC = await getAllSocketsConnectedToVC(nodeIo, guildId);
for (const socket of socketsConnectedToVC) {
if (socket.node.nuid === nuid) {
return true;
}
}
return false;
}
/**
* Request a given socket node to join a given voice channel
* @param {any} socket The socket object of the node the request should be sent to
* @param {any} systemName The system preset name that we would like to listen to
* @param {any} discordChanelId The Discord channel ID to join the listening bot to
* @returns {any}
*/
export const requestNodeJoinSystem = async (socket, systemName, discordChanelId) => { export const requestNodeJoinSystem = async (socket, systemName, discordChanelId) => {
// Check for System updates
// Check for open client IDs // Check for open client IDs
const joinData = { const joinData = {
'clientID': "MTE5NjAwNTM2ODYzNjExMjk3Nw.GuCMXg.24iNNofNNumq46FIj68zMe9RmQgugAgfrvelEA", 'clientID': "MTE5NjAwNTM2ODYzNjExMjk3Nw.GuCMXg.24iNNofNNumq46FIj68zMe9RmQgugAgfrvelEA",
'channelID': discordChanelId, 'channelID': discordChanelId,
'preset': systemName 'preset': systemName
} }
sendNodeCommand(socket, "node-join", joinData); // Send the command to the node
await sendNodeCommand(socket, "node-join", joinData);
}
export const requestBotLeave = async () => {
} }