Major updates to core

This commit is contained in:
Logan Cusano
2024-02-10 15:10:35 -05:00
parent d563021866
commit 9c46792959
22 changed files with 977 additions and 156 deletions

View File

@@ -1,11 +0,0 @@
import { Client, GatewayIntentBits } from 'discord.js';
//import { deployActiveCommands } from '../discordBot/modules/deployCommands.mjs'
import dotenv from 'dotenv';
dotenv.config()
export const serverClient = new Client({ intents: [GatewayIntentBits.Guilds] });
serverClient.on('ready', () => {
console.log(`Logged in as ${serverClient.user.tag}!`);
});

View File

@@ -0,0 +1,53 @@
// Import necessary modules
import { MongoClient } from 'mongodb';
import dotenv from 'dotenv';
dotenv.config()
// MongoDB connection URI
const uri = process.env.MONGO_URL;
// Function to connect to the database
export const connectToDatabase = async () => {
try {
const client = await MongoClient.connect(uri);
return client;
} catch (error) {
console.error('Error connecting to the database:', error);
throw error;
}
};
// Function to insert a document into the collection
export const insertDocument = async (collectionName, document) => {
const db = await connectToDatabase();
try {
const collection = db.db().collection(collectionName);
const result = await collection.insertOne(document);
console.log('Document inserted:', result.insertedId);
return result.insertedId;
} catch (error) {
console.error('Error inserting document:', error);
throw error;
} finally {
// Close the connection
await db.close();
}
};
// Function to retrieve documents from the collection
export const getDocuments = async (collectionName) => {
const db = await connectToDatabase();
try {
const collection = db.db().collection(collectionName);
const documents = await collection.find({}).toArray();
console.log('Documents retrieved:', documents);
return documents;
} catch (error) {
console.error('Error retrieving documents:', error);
throw error;
} finally {
// Close the connection
await db.close();
}
};

View File

@@ -0,0 +1,75 @@
import { insertDocument, getDocuments, connectToDatabase } from "./mongoHandler.mjs";
const collectionName = 'nodes';
// Wrapper for inserting a node
export const createNode = async (node) => {
try {
const insertedId = await insertDocument(collectionName, node);
return insertedId;
} catch (error) {
console.error('Error creating node:', error);
throw error;
}
};
// Wrapper for retrieving all nodes
export const getAllNodes = async () => {
try {
const nodes = await getDocuments(collectionName);
return nodes;
} catch (error) {
console.error('Error getting all nodes:', error);
throw error;
}
};
// Wrapper for retrieving a node by NUID
export const getNodeByNuid = async (nuid) => {
const db = await connectToDatabase();
try {
const collection = db.db().collection(collectionName);
const node = await collection.findOne({ nuid });
return node;
} catch (error) {
console.error('Error getting node by NUID:', error);
throw error;
} finally {
// Close the connection
await db.close();
}
};
// Wrapper for updating a node by NUID
export const updateNodeByNuid = async (nuid, updatedFields) => {
const db = await connectToDatabase();
try {
const collection = db.db().collection(collectionName);
const result = await collection.updateOne({ nuid }, { $set: updatedFields });
console.log('Node updated:', result.modifiedCount);
return result.modifiedCount;
} catch (error) {
console.error('Error updating node by NUID:', error);
throw error;
} finally {
// Close the connection
await db.close();
}
};
// Wrapper for deleting a node by NUID
export const deleteNodeByNuid = async (nuid) => {
const db = await connectToDatabase();
try {
const collection = db.db().collection(collectionName);
const result = await collection.deleteOne({ nuid });
console.log('Node deleted:', result.deletedCount);
return result.deletedCount;
} catch (error) {
console.error('Error deleting node by NUID:', error);
throw error;
} finally {
// Close the connection
await db.close();
}
};

View File

@@ -0,0 +1,111 @@
import { insertDocument, getDocuments, connectToDatabase } from "./mongoHandler.mjs";
const collectionName = 'radio-systems';
// Local wrapper to remove any local files from radio systems
const removeLocalFilesFromsystem = async (system) => {
if (system.trunkFile) delete system.trunkFile;
if (system.whitelistFile) delete system.whitelistFile;
}
// Wrapper for inserting a system
export const createSystem = async (name, system, nuid) => {
try {
// Remove any local files
await removeLocalFilesFromsystem(system);
// Add the NUID of the node that created this system
system.nodes = [nuid];
// Add the name of the system
system.name = name
const insertedId = await insertDocument(collectionName, system);
return insertedId;
} catch (error) {
console.error('Error creating system:', error);
throw error;
}
};
// Wrapper for retrieving all systems
export const getAllSystems = async () => {
try {
const systems = await getDocuments(collectionName);
return systems;
} catch (error) {
console.error('Error getting all systems:', error);
throw error;
}
};
// Wrapper for retrieving a system by name
export const getSystemByName = async (name) => {
const db = await connectToDatabase();
try {
const collection = db.db().collection(collectionName);
const system = await collection.findOne({ name });
return system;
} catch (error) {
console.error('Error getting system by name:', error);
throw error;
} finally {
// Close the connection
await db.close();
}
};
// Wrapper to get all systems from a given node
export const getSystemsByNuid = async (nuid) => {
const db = await connectToDatabase();
try {
const collection = db.db().collection(collectionName);
// Query for documents where the 'nodes' array contains the given nodeID
const query = { nodes: nuid };
const systems = await collection.find(query).toArray();
return systems;
} catch (error) {
console.error('Error finding entries:', error);
throw error;
} finally {
// Close the connection
await db.close();
}
};
// Wrapper for updating a system by name
export const updateSystemByName = async (name, updatedSystem) => {
// Remove any local files
await removeLocalFilesFromsystem(updatedSystem);
const db = await connectToDatabase();
try {
const collection = db.db().collection(collectionName);
const result = await collection.updateOne({ name }, { $set: updatedSystem });
console.log('System updated:', result.modifiedCount);
return result.modifiedCount;
} catch (error) {
console.error('Error updating system by name:', error);
throw error;
} finally {
// Close the connection
await db.close();
}
};
// Wrapper for deleting a system by name
export const deleteSystemByName = async (name) => {
const db = await connectToDatabase();
try {
const collection = db.db().collection(collectionName);
const result = await collection.deleteOne({ name });
console.log('System deleted:', result.deletedCount);
return result.deletedCount;
} catch (error) {
console.error('Error deleting system by name:', error);
throw error;
} finally {
// Close the connection
await db.close();
}
};

View File

@@ -2,6 +2,7 @@ import express from 'express';
import { createServer } from 'node:http';
import { Server } from 'socket.io';
import morgan from 'morgan';
import { nodeLoginWrapper, nodeUpdateWrapper, nodeDisconnectWrapper, nearbySystemsUpdateWraper } from "./socketServerWrappers.mjs";
export const app = express();
export const server = createServer(app);
@@ -17,48 +18,21 @@ nodeIo.on('connection', (socket) => {
console.log('a user connected', socket.id);
socket.on('node-login', (data) => {
nodeLoginWrapper(data);
nodeLoginWrapper(data, socket);
})
socket.on('node-update', (data) => {
updateNodeData(data);
nodeUpdateWrapper(data.node);
nearbySystemsUpdateWraper(data.node.nuid, data.nearbySystems)
})
socket.on('disconnect', () => {
console.log('user disconnected');
nodeDisconnectWrapper(socket.id);
});
// Test commands
setTimeout(() => {
const joinData = {
'clientID': "MTE5NjAwNTM2ODYzNjExMjk3Nw.GuCMXg.24iNNofNNumq46FIj68zMe9RmQgugAgfrvelEA",
'channelID': "367396189529833476",
'preset': ""
}
sendNodeCommand(socket, "node-join", joinData);
}, 2500)
//setTimeout(() => { sendNodeCommand(socket, "node-leave", {}); }, 3500)
});
function sendNodeCommand(socket, command, data) {
// TODO - Check to see if the command exists
// TODO - Check to see if the socket is alive?
// TODO - Validate the given data
socket.emit(command, data);
}
function loginNode() {
}
function registerNode() {
}
function updateNodeData(data) {
console.log("Data update sent by node: ", data);
}
function nodeLoginWrapper(data) {
console.log(`Login requested from node: ${data.id}`, data);
}
// Startup the node server
server.listen(3000, () => {
console.log('server running at http://localhost:3000');
});

View File

@@ -0,0 +1,167 @@
import { createNode, getNodeByNuid, updateNodeByNuid } from "./mongoNodesWrappers.mjs"
import { createSystem, getSystemByName, updateSystemByName, getSystemsByNuid, deleteSystemByName } from "./mongoSystemsWrappers.mjs"
/**
* Description
* @param {any} socket
* @param {any} command
* @param {any} data
* @returns {any}
*/
const sendNodeCommand = async (socket, command, data) => {
// TODO - Check to see if the command exists
// TODO - Check to see if the socket is alive?
// TODO - Validate the given data
socket.emit(command, data);
}
/**
* Log the node into the network
* @param {object} data The data sent from the node
* @param {any} socket The socket the node is connected from
* @returns {any}
*/
export const nodeLoginWrapper = async (data, socket) => {
console.log(`Login requested from node: ${data.nuid}`, data);
// Check to see if node exists
var node = await getNodeByNuid(data.nuid);
console.log("After grabbing", node);
if (!node) {
const insertedId = await createNode(data);
node = await getNodeByNuid(data.nuid);
console.log("Added new node to the database:", insertedId);
}
// Check for updates if so
// Check for System updates
// Add the socket/node connection
socket.node = node;
socket.id = node.nuid;
return;
}
/**
* Disconnect the client from the server
* @param {string} socketId The socket ID that was disconnected
* @returns {any}
*/
export const nodeDisconnectWrapper = async (socketId) => {
return;
}
/**
* Update node data in the database
* @param {object} nodeData The data object sent from the node
* @returns {any}
*/
export const nodeUpdateWrapper = async (nodeData) => {
console.log("Data update sent by node: ", nodeData);
const updateResults = await updateNodeByNuid(nodeData.nuid, nodeData);
return;
}
/**
* Wrapper to update the systems from the nearbySystems object passed from clients
* @param {string} nuid The NUID of the node that sent the update
* @param {object} nearbySystems The nearby systems object passed from the node to be updated
* @returns {any}
*/
export const nearbySystemsUpdateWraper = async (nuid, nearbySystems) => {
console.log("System updates sent by node: ", nuid, nearbySystems);
// Check to see if the node removed any systems
const existingSystems = await getSystemsByNuid(nuid);
console.log("Existing systems:", existingSystems);
if (existingSystems !== nearbySystems) {
for (const existingSystem of existingSystems) {
if (existingSystem.name in nearbySystems) {
// Skip this system if it's in the given systems update
continue;
}
console.log("System exists that was not given by node", existingSystem);
// Check if this node was the only node on this system
if (existingSystem.nodes.filter(node => node !== nuid).length === 0) {
// Remove the system if so
console.log("Given node was the only node on this system, removing the system...");
await deleteSystemByName(existingSystem.name);
} else {
// Remove the node from the array if there are other nodes with this system
console.log("Other nodes found on this system, removing the given NUID");
existingSystem.nodes = existingSystem.nodes.filter(node => node !== nuid);
console.log(existingSystem);
await updateSystemByName(existingSystem.name, existingSystem);
}
}
}
// Add and update the given systems
for (const nearbySystem in nearbySystems) {
// Check if the system exists already on another node
const existingSystem = await getSystemByName(nearbySystem);
if (existingSystem) {
// Verify the frequencies match (to make sure the name isn't just the same)
console.log(existingSystem.frequencies, nearbySystems[nearbySystem].frequencies, (JSON.stringify(existingSystem.frequencies) === JSON.stringify(nearbySystems[nearbySystem].frequencies)));
if (JSON.stringify(existingSystem.frequencies) === JSON.stringify(nearbySystems[nearbySystem].frequencies)) {
// The systems are the same
// Check if the current node is listed in the nodes, if not add it
if (!existingSystem.nodes.includes(nuid)) {
existingSystem.nodes.push(nuid);
// Update the system with the added node
const updateResults = await updateSystemByName(nearbySystem, existingSystem);
if (updateResults) console.log("System updated", nearbySystem);
}
} else {
// 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
// Check if the current node is listed in the nodes, if not add it
if (!existingSystem.nodes.includes(nuid)) {
existingSystem.nodes.push(nuid);
nearbySystems[nearbySystem].nodes = existingSystem.nodes;
}
// Update the system with the added node
const updateResults = await updateSystemByName(nearbySystem, nearbySystems[nearbySystem]);
if (updateResults) console.log("System updated", nearbySystem);
}
}
else {
// Create a new system
const newSystem = await createSystem(nearbySystem, nearbySystems[nearbySystem], nuid);
console.log("New system created", nearbySystem, newSystem);
}
}
return;
}
/**
* Get the open socket connection ID for a node from the NUID
* @param {string} nuid The NUID to find within the open sockets
* @returns {string|null} Will return the open socket ID or NULL
*/
const getSocketIdByNuid = async (nuid) => {
for (const openSocket in openSockets) {
if (openSockets[openSocket] == nuid)
return openSocket;
}
return null;
}
const requestNodeJoinPreset = async () => {
// Check for System updates
// Test commands
setTimeout(() => {
const joinData = {
'clientID': "MTE5NjAwNTM2ODYzNjExMjk3Nw.GuCMXg.24iNNofNNumq46FIj68zMe9RmQgugAgfrvelEA",
'channelID': "367396189529833476",
'preset': ""
}
sendNodeCommand(socket, "node-join", joinData);
}, 2500)
}