import moment from "moment"; import { Server } from "socket.io"; import zulip from "zulip-js"; import { exec, spawn } from "child_process"; import nodeMailer from "nodemailer"; import net from "net"; import { log, timeStamp } from "console"; import fs from "fs"; import dotenv from "dotenv"; import EventEmitter from "events"; // Set the maximum number of listeners to a higher value dotenv.config(); // Telnet connection options // const host = '172.16.20.17'; // const port = 2023; // Create a TCP socket // const emitter = new EventEmitter(); emitter.setMaxListeners(30); const io = new Server({ cors: { origin: "*", }, }); const sendMail = (to, subject, htmlContent) => { const adminEmail = process.env.ADMIN_EMAIL; const adminPassword = process.env.ADMIN_EMAIL_PASSWORD; const mailHost = process.env.EMAIL_HOST; const mailPort = process.env.EMAIL_PORT; const transporter = nodeMailer.createTransport({ pool: true, host: mailHost, port: mailPort, secure: true, auth: { user: adminEmail, pass: adminPassword, }, }); const options = { from: adminEmail, to: to, subject: subject, html: htmlContent, }; return transporter.sendMail(options); }; let onlineUsers = []; let listLineRun = []; let listLineTimer = []; let listProcess = []; let listLineUpdate = []; let listStationUpdate = []; let listLineUse = []; let listStationUse = []; let listDeviceOn = []; let listDeviceOff = []; let listDeviceOn_old = []; let listDeviceOff_old = []; let listTesting = []; let listCheckTime = []; let listInterUP = []; fs.readFile("./users", "utf8", (err, data) => { if (err) { console.log(err); return; } console.log(data); if (data !== "") { let temp = JSON.parse(data); (listLineRun = temp.listLineRun ? temp.listLineRun : []), (listLineTimer = temp.listLineTimer ? temp.listLineTimer : []), (listTesting = temp.listTesting ? temp.listTesting : []), (listDeviceOff = temp.listDeviceOff ? temp.listDeviceOff : []), (listProcess = temp.listProcess ? temp.listProcess : []), (listLineUpdate = temp.listLineUpdate ? temp.listLineUpdate : []), (listStationUpdate = temp.listStationUpdate ? temp.listStationUpdate : []), (listLineUse = temp.listLineUse ? temp.listLineUse : []), (listStationUse = temp.listStationUse ? temp.listStationUse : []), (listDeviceOn = temp.listDeviceOn ? temp.listDeviceOn : []), (listDeviceOn_old = temp.listDeviceOn_old ? temp.listDeviceOn_old : []), (listDeviceOff_old = temp.listDeviceOff_old ? temp.listDeviceOff_old : []), (listCheckTime = temp.listCheckTime ? temp.listCheckTime : []), (listInterUP = temp.listInterUP ? temp.listInterUP : []); } }); const sendMessageToZulip = async (data, name, sta_name, items) => { const config = { username: "networktool-bot@zulip.ipsupply.com.au", apiKey: "0jMAmOuhfLvBqKJikv5oAkyNM4RIEoAM", realm: "https://zulip.ipsupply.com.au", }; const client = await zulip(config); let title = "**Line " + data.line + ": Equipment detected**\n"; switch (data.status) { case "PASSWORD": title = title + "**(On-site tester) Please repower and hold mode button**"; break; case "Fault": title = title + "**(Remote tester) Please check**"; break; case "Error": title = title + "**(Remote tester) Please check**"; break; case "DPEL": title = title + "**(On-site tester) Please test LED/Ports**"; break; case "DPELP": title = title + "**(On-site tester) Please test LED/Ports**"; break; case "ERROR": title = title + "**(Remote tester) Error loading IOS. Please install IOS image**"; break; case "Wait": title = title + "**Wait for automatic test**"; break; } let extra_items = data?.output?.split("\n")?.filter((i) => i.search("Extra items:") !== -1) .length > 0 ? ":check: " + data?.output ?.split("\n") ?.filter((i) => i.search("Extra items:") !== -1)[0] ?.split(":")[1] : "Not Found"; let status = data.status === "Faulty" ? "Issue found" : data.status; let params0 = { type: "stream", to: "Result test - auto.nswteam.net", topic: "AU-dev", content: title + "\n\n| Line | PID-SN | Extra items | Status | Date | Report\n|---|:---:|:---:|:---:|-----------:|------:\n|" + data.line + " | " + data?.output ?.split("\n") ?.filter((i) => i.search("PID:") !== -1 && i.search("SN:") !== -1)[0] ?.replace(/\r/g, "") + " | " + extra_items + "|" + status + "|" + moment(Date.now()).format("DD/MM") + "|[View](" + process.env.DOMAIN_SERVER + "/api/log?name=" + name?.split("filesTest/")[1] + ") \n|**Note:**|", }; let params = { type: "stream", to: process.env.RESULT_STREAM_ZULIP, topic: sta_name.search("US") !== -1 && sta_name.search("A") === -1 ? "US Station" : sta_name.search("AU") !== -1 ? "AU Station" : sta_name, content: title + "\n\n| Line | PID-SN | Extra items | Status | Date | Report\n|---|:---:|:---:|:---:|-----------:|------:\n|" + data.line + " | " + data?.output ?.split("\n") ?.filter((i) => i.search("PID:") !== -1 && i.search("SN:") !== -1)[0] ?.replace(/\r/g, "") + " | " + extra_items + "|" + status + "|" + moment(Date.now()).format("DD/MM") + "|[View](" + process.env.DOMAIN_SERVER + "/api/log?name=" + name?.split("filesTest/")[1] + ") \n|**Note:**|", }; let params1 = { type: "stream", to: "AUS_VN_Test", topic: "Status Line", content: title + "\n\n| Line | PID-SN | Extra items | Status | Date | Report\n|---|:---:|:---:|:---:|-----------:|------:\n|" + data.line + " | " + data?.output ?.split("\n") ?.filter((i) => i.search("PID:") !== -1 && i.search("SN:") !== -1)[0] ?.replace(/\r/g, "") + " | " + extra_items + "|" + status + "|" + moment(Date.now()).format("DD/MM") + "|[View](" + process.env.DOMAIN_SERVER + "/api/log?name=" + name?.split("filesTest/")[1] + ") \n|**Note:**|", }; let params2 = { type: "stream", to: "US Auto-test", topic: "Notifications", content: title + "\n\n| Line | PID-SN | Extra items | Status | Date | Report\n|---|:---:|:---:|:---:|-----------:|------:\n|" + data.line + " | " + data?.output ?.split("\n") ?.filter((i) => i.search("PID:") !== -1 && i.search("SN:") !== -1)[0] ?.replace(/\r/g, "") + " | " + extra_items + "|" + status + "|" + moment(Date.now()).format("DD/MM") + "|[View](" + process.env.DOMAIN_SERVER + "/api/log?name=" + name?.split("filesTest/")[1] + ") \n|**Note:**|", }; // const result = await client.messages.send(params); // await client.messages.send(params1); // if (sta_name.search("US") !== -1 && sta_name.search("A") === -1) { // await client.messages.send(params2); // } await client.messages.send(params0); }; const addNewUser = (email, socketId, socketTerminal, time) => { !onlineUsers.some((user) => user.email === email) && onlineUsers.push({ email, socketId, socketTerminal, time }); }; const removeUser = (socketId) => { onlineUsers = onlineUsers.filter((user) => user.socketId !== socketId); }; const getUser = (email) => { return onlineUsers.find((user) => user.email === email); }; const getUserByIdSocket = (socketId) => { return onlineUsers.find((user) => user.socketId === socketId); }; let respon = []; setInterval(() => { if (respon.length > 0) { console.log(respon.toString()); respon = []; } // if(moment(Date.now()).format("HH:mm:ss")==="08:30:00"){ // sendMail("joseph@apactech.io", "REPORT "+moment(Date.now()).format("DD/MM/YYYY"), "
\ // - US1 log

\ // - US2 log

\ // - AUS-1 log

\ // - AUS-2 log

\ // - AUS-dev log

\ //
") // } let temp = { listLineRun: listLineRun, listLineTimer: listLineTimer, listTesting: listTesting, listDeviceOff: listDeviceOff, listProcess: listProcess, listLineUpdate: listLineUpdate, listStationUpdate: listStationUpdate, listLineUse: listLineUse, listStationUse: listStationUse, listDeviceOn: listDeviceOn, listDeviceOn_old: listDeviceOn_old, listDeviceOff_old: listDeviceOff_old, listCheckTime: listCheckTime, listInterUP: listInterUP, }; fs.writeFile("./users", JSON.stringify(temp), function (err) { if (err) { return console.log(err); } }); }, 1000); // console.log("heheh") io.on("connection", (socket) => { socket.on("newUser", (data) => { const socket1 = new net.Socket(); socket1.setMaxListeners(200); // console.log(getUser(data.email)?.time); // console.log(data.time); let user = getUser(data.email); if (user?.time !== data.time) { if (user?.email !== data.email) { addNewUser(data.email, socket.id, socket1, data.time); io.to([socket.id]).emit("updateListRun", listLineRun); io.to([socket.id]).emit("updateListTimer", listLineTimer); io.to([socket.id]).emit("sendListTesting", listTesting); io.to([socket.id]).emit("sendListDeviceOff", listDeviceOff); let temp = []; onlineUsers.map((u) => { temp.push(u.email); }); console.log(temp); console.log("----------list-------------"); } else { io.to([socket.id]).emit("refuseNewUser", {}); } } else { io.to([socket.id]).emit("updateListRun", listLineRun); io.to([socket.id]).emit("updateListTimer", listLineTimer); io.to([socket.id]).emit("sendListTesting", listTesting); io.to([socket.id]).emit("sendListDeviceOff", listDeviceOff); let temp = []; onlineUsers.map((u) => { temp.push(u.email); }); console.log(temp); console.log("----------list-------------"); } }); socket.on("disconnect", () => { const user = onlineUsers.filter((i) => i.socketId === socket.id)[0]; if (user !== undefined) { user.socketTerminal.end(); } removeUser(socket.id); let temp = []; onlineUsers.map((u) => { temp.push(u.email); }); console.log(temp); console.log("----------list-------------"); }); socket.on("createTelnet", (data) => { try { const user = getUser(data.email); if (user !== undefined) { const socket2 = new net.Socket(); socket2.connect(data.port, data.host, () => { console.log(`Connected to ${data.host}:${data.port}`); socket2.setEncoding("utf-8"); socket2.write("clear line " + data.clear_line + "\n"); socket2.write("\r\n"); socket2.write("\r\n"); socket2.write("clear line " + data.clear_line + "\n"); socket2.write("\r\n"); socket2.write("\r\n"); // user.socketTerminal.write("p" + data.line_number); // user.socketTerminal.write("\n"); // user.socketTerminal.write("\n"); // user.socketTerminal.write("\n"); // user.socketTerminal.write("p" + data.line_number); // user.socketTerminal.write("\n"); // user.socketTerminal.write("\n"); // user.socketTerminal.write("\n"); }); setTimeout(() => { socket2.end(); user.socketTerminal.connect(data.line_port, data.host, () => { console.log(`Connected to ${data.host}:${data.line_port}`); user.socketTerminal.setEncoding("UTF-8"); // user.socketTerminal.write("p" + data.line_number); user.socketTerminal.write("\r\n"); // user.socketTerminal.write("p" + data.line_number); // user.socketTerminal.write("enable\n"); // setTimeout(() => { // user.socketTerminal.write("\r\n"); // user.socketTerminal.write("\r\n"); // user.socketTerminal.write("\r\n"); // user.socketTerminal.write("p" + data.line_number); // user.socketTerminal.write("enable\n"); // }, 3000); // user.socketTerminal.write("\n"); // user.socketTerminal.write("\n"); }); user.socketTerminal.on("error", (error) => { console.log("Connection error:", error); setTimeout(() => { io.to([user.socketId]).emit("sendLogs", { data: "Connect error", }); }, 500); }); }, 2000); socket2.on("error", (error) => { console.log("Connection error:", error); setTimeout(() => { io.to([user.socketId]).emit("sendLogs", { data: "Connect error" }); }, 500); }); } } catch (error) { console.log(error); } }); socket.on("closeTelnet", (data) => { try { const user = getUser(data.email); if (user !== undefined) { user.socketTerminal.removeAllListeners(); user.socketTerminal.end(); } } catch (error) { console.log(error); } }); socket.on("sendNoteToZulip", async (data) => { try { const config = { username: "networktool-bot@zulip.ipsupply.com.au", apiKey: "0jMAmOuhfLvBqKJikv5oAkyNM4RIEoAM", realm: "https://zulip.ipsupply.com.au", }; const client = await zulip(config); let title = "**Line " + data.line + ": Equipment detected**\n"; switch (data.status) { case "PASSWORD": title = title + "**(On-site tester) Please repower and hold mode button**"; break; case "Fault": title = title + "**(Remote tester) Please check**"; break; case "Error": title = title + "**(Remote tester) Please check**"; break; case "DPEL": title = title + "**(On-site tester) Please test LED/Ports**"; break; case "DPELP": title = title + "**(On-site tester) Please test LED/Ports**"; break; case "ERROR": title = title + "**(Remote tester) Error loading IOS. Please install IOS image**"; break; case "Wait": title = title + "**Wait for automatic test**"; break; } let status = data.status === "Faulty" ? "Issue found" : data.status; let extra_items = data.output?.split("\n")?.filter((i) => i.search("Extra items") !== -1) .length > 0 ? ":check: " + data?.output ?.split("\n") ?.filter((i) => i.search("Extra items:") !== -1)[0] ?.split(":")[1] : "Not Found"; let params = { type: "stream", to: process.env.RESULT_STREAM_ZULIP, topic: data.sta_name.search("US") !== -1 && data.sta_name.search("A") === -1 ? "US Station" : data.sta_name.search("AUS") !== -1 ? "AU Station" : data.sta_name, content: title + "\n\nNote updated: \n\n| Line | PID-SN | Extra items | Status | Date | Report\n|---|:---|:---|:---:|:---:|:---:\n|" + data.line + " | " + data.PID_SN + "|" + extra_items + " | " + status + "|" + data.time + "|[View](" + process.env.DOMAIN_SERVER + "/api/log?name=" + data.file + ")\n|**Note:**|**" + data.note + "**|", }; let params1 = { type: "stream", to: "AUS_VN_Test", topic: "Status Line", content: title + "\n\nNote updated: \n\n| Line | PID-SN | Extra items | Status | Date | Report\n|---|:---|:---|:---:|:---:|:---:\n|" + data.line + " | " + data.PID_SN + "|" + extra_items + " | " + status + "|" + data.time + "|[View](" + process.env.DOMAIN_SERVER + "/api/log?name=" + data.file + ")\n|**Note:**|**" + data.note + "**|", }; let params2 = { type: "stream", to: "US Auto-test", topic: "Notifications", content: title + "\n\nNote updated: \n\n| Line | PID-SN | Extra items | Status | Date | Report\n|---|:---|:---|:---:|:---:|:---:\n|" + data.line + " | " + data.PID_SN + "|" + extra_items + " | " + status + "|" + data.time + "|[View](" + process.env.DOMAIN_SERVER + "/api/log?name=" + data.file + ")\n|**Note:**|**" + data.note + "**|", }; const result = await client.messages.send(params); await client.messages.send(params1); if ( data.sta_name.search("US") !== -1 && data.sta_name.search("A") === -1 ) { await client.messages.send(params2); } } catch (error) { console.log(error); } }); socket.on("sendReportToZulip", (data) => { // console.log(data) try { const config = { username: "networktool-bot@zulip.ipsupply.com.au", apiKey: "0jMAmOuhfLvBqKJikv5oAkyNM4RIEoAM", realm: "https://zulip.ipsupply.com.au", }; (async () => { // console.log(data.content?.slice(data.content.search("Faulty:"),100)) const client = await zulip(config); let status = data.status === "Faulty" ? "Issue found" : data.status; const fail = data.content?.search("Faulty:") !== -1 ? data.content.slice( data.content.search("Faulty:") + 7, data.content.search( "======================================================================" ) ) : "not found"; const content = "**Line " + data.line + ":**\n" + data.content .split("\n") .filter( (i) => i.search("PID:") !== -1 && i.search("VID:") !== -1 && i.search("SN:") !== -1 )[0] + "\n" + data.content.split("\n").filter((i) => i.search("RAM: ") !== -1)[0] + " - " + data.content .split("\n") ?.filter((i) => i.search("Flash: ") !== -1)[0] + "\nExtra item: " + data.extraItem + "\nAuto detect issue: \n" + fail + "\nShorten log: - [View](" + process.env.DOMAIN_SERVER + "/api/log?name=" + data.file + ")\n```\n" + data.content.slice( data.content.search("show inv"), data.content.length ); // console.log(content) let params = { type: "stream", to: data.stream, topic: data.topic, content: content, }; const result = await client.messages.send(params); console.log(result); })(); } catch (error) { console.log(error); } }); socket.on("receiverCommand", (data) => { try { const user = getUser(data.email); if (user !== undefined) { let temp = data.command + "\r"; user.socketTerminal.write(temp); user.socketTerminal.on("data", (data) => { if (respon.includes(data) === false) { respon.push(data); console.log(data); onlineUsers.map((u, index) => { if (u.email === user.email) { if (onlineUsers[index].log) { onlineUsers[index].log = onlineUsers[index].log + data; } else { onlineUsers[index].log = data; } } }); io.to([user.socketId]).emit("sendLogs", { data: user.log }); if (data.search("--More--") !== -1) { user.socketTerminal.write(" \r"); } } }); // Handle connection error user.socketTerminal.on("error", (error) => { console.log("Connection error:", error); setTimeout(() => { io.to([user.socketId]).emit("sendLogs", { data: "Connect error" }); }, 500); }); } } catch (error) { console.log(error); } }); socket.on("send-process", (data) => { if ( listLineRun.filter((line) => line.id_line === data.id).length > 0 && data.result[0].status.search("boot") === -1 && data.result[0].status.search("PASSWORD_ROUTER") === -1 ) { listLineRun = listLineRun.filter((line) => line.id_line !== data.id); listLineTimer = listLineTimer.filter((line) => line.id_line !== data.id); listProcess = listProcess.filter((line) => line.id !== data.id); listInterUP = listInterUP.filter((line) => line.id !== data.id); io.emit("updateCommand", { type: "test" }); io.emit("sendListTesting", listTesting); // listTesting = listTesting.filter((line) => line.id_line !== data.id) // if (data.result[0].status.toLocaleLowerCase() === "error") { // } fs.access( "../netmiko_Api/public/dailyLogs/" + moment(Date.now()).format("YYYYMMDD") + "-AUTO-Session." + data.result[0].sta_name.replace(" ", "-") + ".log", fs.constants.F_OK, (err) => { if (err) { fs.writeFile( "../netmiko_Api/public/dailyLogs/" + moment(Date.now()).format("YYYYMMDD") + "-AUTO-Session." + data.result[0].sta_name.replace(" ", "-") + ".log", "\n\n\n=============================================================" + data.result[0].status + "=============================================================\n" + data.result[0].output, function (err) { if (err) { return console.log(err); } console.log("Write log !"); } ); } else { const old_data = fs.readFileSync( "../netmiko_Api/public/dailyLogs/" + moment(Date.now()).format("YYYYMMDD") + "-AUTO-Session." + data.result[0].sta_name.replace(" ", "-") + ".log", "utf8" ); fs.writeFile( "../netmiko_Api/public/dailyLogs/" + moment(Date.now()).format("YYYYMMDD") + "-AUTO-Session." + data.result[0].sta_name.replace(" ", "-") + ".log", old_data + "\n\n\n=============================================================" + data.result[0].status + "=============================================================\n" + data.result[0].output, function (err) { if (err) { return console.log(err); } console.log("Write log !"); } ); } } ); let subject = ""; let items = ""; if (data.result[0].PID !== undefined) { subject = subject + data.result[0].sta_name + " - Line " + data.result[0].line + " - " + data.result[0].status + " - " + data.result[0].PID + " - " + data.result[0].SN; } else { subject = subject + data.result[0].sta_name + " - Line " + data.result[0].line + " - " + data.result[0].status; } if ( data.result[0].output .split("\n") .filter((i) => i.search("PID: ") !== -1).length > 1 ) { let temp = []; let listKeyValue = data.specialItem.filter( (i) => i.key === "MODEL_SPECIAL" ); let listItemSpecial = []; listKeyValue.map((u) => { listItemSpecial.push(u.value); }); data.result[0].output.split("\n").map((u) => { if (u.search("NAME: ") !== -1 || u.search("PID: ") !== -1) { temp.push(u + "\n"); } }); temp.slice(2).map((u, index) => { if ( listItemSpecial.filter((i) => u.search(i) !== -1).length > 0 && u.search("PID:") !== -1 ) { items = items + temp.slice(2)[index - 1]; items = items + u; } }); if (items !== "") { items = "

Additional items found:

"; } else { items = ""; } } sendMessageToZulip( data.result[0], data.nameFile, data.result[0].sta_name, items ); if ( data.result[0].status.toLocaleLowerCase() !== "wait" && data.checkSendMail === "true" ) { switch (data.result[0].status.toLocaleLowerCase()) { case "dpel": sendMail( "group1@apactech.io, frank@ipsupply.com.au, kay@ipsupply.com.au", "[Admin] " + subject, "

----------This is an automated message please do not reply----------

" + subject + "

" + items + "

Output:

" ); sendMail( "group2@apactech.io, frank@ipsupply.com.au, kay@ipsupply.com.au", "[Tester] " + subject, "

----------This is an automated message please do not reply----------

" + subject + "

" + items + "

The device is GOOD. Please check ports + mode button + POE ,...

" ); break; case "dpelp": sendMail( "group1@apactech.io, frank@ipsupply.com.au, kay@ipsupply.com.au", "[Admin] " + subject, "

----------This is an automated message please do not reply----------

" + subject + "

" + items + "

Output:

" ); sendMail( "group2@apactech.io, frank@ipsupply.com.au, kay@ipsupply.com.au", "[Tester] " + subject, "

----------This is an automated message please do not reply----------

" + subject + "

" + items + "

The device is GOOD. Please check ports + mode button + POE ,...

" ); break; case "password": sendMail( "group1@apactech.io, frank@ipsupply.com.au, kay@ipsupply.com.au", "[Admin] " + subject, "

----------This is an automated message please do not reply----------

" + subject + "

This line has password

" + data.result[0].output.split("\n")[0] + "

" + data.result[0].output.split("\n")[1] + "

Output:

" ); // sendMail("group2@apactech.io", subject, "

----------This is an automated message please do not reply----------

This line has password. Please repower and hold mode button. Please email group1 once you are done.

") let noti = data.result[0].output.split("\n")[1].search("Switche") !== -1 ? "

This line has password. Please repower and hold mode button.

" + data.result[0].output.split("\n")[0] + "

" + data.result[0].output.split("\n")[1] + "

" : "

This line has password.

" + data.result[0].output.split("\n")[0] + "

" + data.result[0].output.split("\n")[1] + "

"; sendMail( "group2@apactech.io, frank@ipsupply.com.au, kay@ipsupply.com.au", "[Tester] " + subject, "

----------This is an automated message please do not reply----------

" + subject + "

" + noti ); break; case "faulty": sendMail( "group1@apactech.io, frank@ipsupply.com.au, kay@ipsupply.com.au", "[Admin] " + subject, "

----------This is an automated message please do not reply----------

" + subject + "

" + items + "

This line is faulty, please check and email group 2 to check port + poe + button ... once you are done checking

Output:

" ); break; case "switch:": sendMail( "group1@apactech.io, frank@ipsupply.com.au, kay@ipsupply.com.au", "[Admin] " + subject, "

----------This is an automated message please do not reply----------

" + subject + "

please check - " + data.result[0].output.split("\n")[1].split("|||")[1] + " can't boot

Output:

" ); break; case "rommon:": sendMail( "group1@apactech.io, frank@ipsupply.com.au, kay@ipsupply.com.au", "[Admin] " + subject, "

----------This is an automated message please do not reply----------

" + subject + "

please check - " + data.result[0].output.split("\n")[1].split("|||")[1] + " can't boot

Output:

" ); break; case "error": sendMail( "group1@apactech.io, frank@ipsupply.com.au, kay@ipsupply.com.au", "[Admin] " + subject, "

----------This is an automated message please do not reply----------

This line is error(s), please check

Output:

" ); break; } } listTesting.map((item, index) => { if (item.id === data.id) { listTesting[index].status = data.result[0].status.toLocaleLowerCase(); // if(listTesting[index].SN!==undefined){ listTesting[index].SN = data.result[0].SN; // } } }); io.emit("send-response", data); io.emit("updateListRun", listLineRun); io.emit("updateListTimer", listLineTimer); } if (data.result[0].status === "PASSWORD_ROUTER") { listTesting.map((item, index) => { if (item.id === data.id) { listTesting[index].status = "password"; // if(listTesting[index].SN!==undefined){ // listTesting[index].SN = data.result[0].SN; // } } }); } }); socket.on("cancelAction", (data) => { listLineRun = listLineRun.filter((line) => line.id_line !== data.id); listLineTimer = listLineTimer.filter((line) => line.id_line !== data.id); // listTesting = listTesting.filter((line) => line.id_line !== data.id) io.emit("updateListRun", listLineRun); io.emit("updateListTimer", listLineTimer); console.log("after delete: ", listLineRun); }); socket.on("changeCommand", ({}) => { io.emit("updateCommand", { type: "input" }); io.emit("updateListTimer", listLineTimer); }); socket.on("sendListRun", (listRun) => { listRun.map((u) => { listLineRun.push(u); }); io.emit("updateListRun", listLineRun); // console.log(listLineRun); }); socket.on("sendListTimer", (listTimer) => { listTimer.map((u) => { listLineTimer.push(u); }); io.emit("updateListTimer", listLineTimer); // console.log(listLineTimer); }); socket.on("getListTimer", () => { io.to([socket.id]).emit("updateListTimer", listLineTimer); // console.log(listLineTimer); }); socket.on("changeAction", (listTimer) => { listLineTimer.map((t, index) => { if (t.id_line === listTimer.id_line) { listLineTimer.fill( { id_line: listTimer.id_line, time: t.time, action: listTimer.action, }, index, index + 1 ); } }); io.emit("updateListTimer", listLineTimer); }); socket.on("listenInfoStation", (data) => { listStationUpdate = data; // console.log("listStation", listStationUpdate); }); socket.on("listenListLine", (data) => { listLineUpdate = data; // console.log("listLine", listLineUpdate); }); socket.on("updateListTesting", (data) => { if (data.status === undefined) { if (listTesting.filter((i) => i.id === data.id_line).length > 0) { if ( listTesting.filter((i) => i.id === data.id_line)[0].status === "edit" ) { listTesting = listTesting.filter((t) => t.id !== data.id_line); io.emit("sendListTesting", listTesting); } else { listTesting.map((t, index) => { if (t.id === data.id_line) { listTesting[index].status = "edit"; } }); io.emit("sendListTesting", listTesting); } } else { listTesting.push({ id: data.id_line, infoLine: data, status: "edit" }); io.emit("sendListTesting", listTesting); } } else { if (data.status === "enable") { data.allLine.map((u) => { listTesting = listTesting.filter((t) => t.id !== u.id_line); }); io.emit("sendListTesting", listTesting); } if (data.status === "disable") { data.allLine.map((u) => { if (listTesting.filter((i) => i.id === u.id_line).length > 0) { listTesting = listTesting.filter((t) => t.id !== u.id_line); listTesting.push({ id: u.id_line, infoLine: u, status: "edit" }); } else { listTesting.push({ id: u.id_line, infoLine: u, status: "edit" }); } }); io.emit("sendListTesting", listTesting); } } }); socket.on("updateListTestingFromManualTest", (data) => { if (listTesting.filter((i) => i.id === data.id_line).length > 0) { listTesting.map((t, index) => { if (t.id === data.id_line) { listTesting[index].status = "edit"; } }); listDeviceOn = listDeviceOn.filter((i) => i.id !== data.id_line); io.emit("sendListTesting", listTesting); } else { listTesting.push({ id: data.id_line, infoLine: data, status: "edit" }); io.emit("sendListTesting", listTesting); listDeviceOn = listDeviceOn.filter((i) => i.id !== data.id_line); } }); }); setInterval(() => { listLineUse = listLineUpdate; listStationUse = listStationUpdate; // console.log("listline", listTesting); if ( listDeviceOn.length > 0 && onlineUsers.filter((i) => i.email.search("api") === -1).length > 0 ) { console.log("Send list on"); // console.log(listTesting); listTesting = listTesting.concat(listDeviceOn); console.log(listDeviceOn); io.to(onlineUsers.filter((i) => i.email !== "api")[0].socketId).emit( "sendListDeviceOn", listDeviceOn ); io.emit("sendListTesting", listTesting); } io.emit("sendListDeviceOff", listDeviceOff); listDeviceOff_old = listDeviceOff; listDeviceOn_old = listDeviceOn; console.log("LIST ON: ", listDeviceOn.length); console.log("*****************LISTTESTING: ", listTesting.length); // console.log("LIST OFF: ", listDeviceOff.filter((obj, index, self) => // index === self.findIndex((t) => t.id === obj.id) // )); listDeviceOff = []; listDeviceOn = []; console.log("==========================================="); for (let i = 0; i < listStationUse.length; i++) { let listLineOfStation = []; // console.log("STATION: ", listStationUse[i]); for (let j = 0; j < listLineUse.length; j++) { if ( listLineUse[j][0] !== undefined && listLineUse[j][0].station_id === listStationUse[i].id_station ) { for (let k = 0; k < listLineUse[j].length; k++) { // if (listTesting.length > 0) { // console.log(listLineUse[j][k]) if ( listTesting.filter((obj) => obj.id === listLineUse[j][k].id_line) .length === 0 || (listTesting.filter( (obj) => obj.id === listLineUse[j][k].id_line )[0]?.status === "wait" && listTesting.filter((obj) => obj.id === listLineUse[j][k].id_line) .length === 1) ) { console.log("-------------------------", listLineUse[j][k].id_line); const checkPort = spawn( "python3", [ "./checkPort.py", "", listStationUse[i].sta_ip, listStationUse[i].sta_port_telnet, listLineUse[j][k].line_clear, listLineUse[j][k].line_number, ], { timeout: 25000 } ); // console.log("listLineUse[j][k]", listLineUse[j][k]) checkPort.stdout.on("data", (data) => { data = data.toString()?.split("===")[0]; console.log("data scan: ", data); if (data.search("Open") !== -1) { if ( data.search("show abc") !== -1 && data.search("switch:") === -1 && data.search("rommon") === -1 // && // data.search("foreign host") === -1 && // data.search("refuse") === -1 ) { if (data.search("show abc") + 10 < data.length) { if ( data.search("Username:") !== -1 || data.search("Password:") !== -1 ) { if ( data .slice(data.search("Password:"), data.length - 2) .search("#") !== -1 && data.search("foreign host") === -1 ) { if (data.search("SRW")!==-1) { console.log("----SRW----"); listDeviceOn.push({ id: listLineUse[j][k].id_line, line: listLineUse[j][k].line_number, station: listStationUse[i], status: "on", infoLine: listLineUse[j][k], mode: "SRW", }); } else { console.log("----GOOD----"); listDeviceOn.push({ id: listLineUse[j][k].id_line, line: listLineUse[j][k].line_number, station: listStationUse[i], status: "on", infoLine: listLineUse[j][k], mode: "good", }); } if ( listTesting.filter( (obj) => obj.id === listLineUse[j][k].id_line )[0]?.status === "wait" ) { listTesting = listTesting.filter( (i) => i.id !== listLineUse[j][k].id_line ); } } else { console.log("----PASSWORD----"); listDeviceOn.push({ id: listLineUse[j][k].id_line, line: listLineUse[j][k].line_number, station: listStationUse[i], status: "on", infoLine: listLineUse[j][k], mode: "password", }); if ( listTesting.filter( (obj) => obj.id === listLineUse[j][k].id_line )[0]?.status === "wait" ) { listTesting = listTesting.filter( (i) => i.id !== listLineUse[j][k].id_line ); } } } else { if ( data .slice(data.search("show abc"), data.length - 2) .search("#") !== -1 && data.search("foreign host") === -1 ) { if (data.search("SRW")!==-1) { console.log("----SRW----"); listDeviceOn.push({ id: listLineUse[j][k].id_line, line: listLineUse[j][k].line_number, station: listStationUse[i], status: "on", infoLine: listLineUse[j][k], mode: "SRW", }); } else { console.log("----GOOD----"); listDeviceOn.push({ id: listLineUse[j][k].id_line, line: listLineUse[j][k].line_number, station: listStationUse[i], status: "on", infoLine: listLineUse[j][k], mode: "good", }); } if ( listTesting.filter( (obj) => obj.id === listLineUse[j][k].id_line )[0]?.status === "wait" ) { listTesting = listTesting.filter( (i) => i.id !== listLineUse[j][k].id_line ); } } else { if ( listTesting.filter( (obj) => obj.id === listLineUse[j][k].id_line ).length === 0 ) { listDeviceOff.push({ id: listLineUse[j][k].id_line, line: listLineUse[j][k].line_number, station: listStationUse[i], status: "off", message: "Mode not found", }); } } } } } if ( data.search("show abc") !== -1 && data.search("switch:") !== -1 ) { console.log("----SWITCH:----"); listDeviceOn.push({ id: listLineUse[j][k].id_line, line: listLineUse[j][k].line_number, station: listStationUse[i], status: "on", infoLine: listLineUse[j][k], mode: "switch:", }); if ( listTesting.filter( (obj) => obj.id === listLineUse[j][k].id_line )[0]?.status === "wait" ) { listTesting = listTesting.filter( (i) => i.id !== listLineUse[j][k].id_line ); } } if ( data.search("show abc") !== -1 && data.search("rommon") !== -1 ) { console.log("----ROMMON----"); listDeviceOn.push({ id: listLineUse[j][k].id_line, line: listLineUse[j][k].line_number, station: listStationUse[i], status: "on", infoLine: listLineUse[j][k], mode: "rommon", }); if ( listTesting.filter( (obj) => obj.id === listLineUse[j][k].id_line )[0]?.status === "wait" ) { listTesting = listTesting.filter( (i) => i.id !== listLineUse[j][k].id_line ); } } if ( data.search("Password:") !== -1 || data.search("Username:") !== -1 ) { if ( listDeviceOn.filter( (i) => i.id === listLineUse[j][k].id_line ).length === 0 ) { console.log("----PASSWORD----"); listDeviceOn.push({ id: listLineUse[j][k].id_line, line: listLineUse[j][k].line_number, station: listStationUse[i], status: "on", infoLine: listLineUse[j][k], mode: "password", }); if ( listTesting.filter( (obj) => obj.id === listLineUse[j][k].id_line )[0]?.status === "wait" ) { listTesting = listTesting.filter( (i) => i.id !== listLineUse[j][k].id_line ); } } } else { if ( listTesting.filter( (obj) => obj.id === listLineUse[j][k].id_line ).length === 0 ) { listDeviceOff.push({ id: listLineUse[j][k].id_line, line: listLineUse[j][k].line_number, station: listStationUse[i], status: "off", message: "Device is booting", }); } } } else { if ( listTesting.filter( (obj) => obj.id === listLineUse[j][k].id_line ).length === 0 ) { listDeviceOff.push({ id: listLineUse[j][k].id_line, line: listLineUse[j][k].line_number, station: listStationUse[i], status: "off", message: "No connection to device", }); } } }); checkPort.stderr.on("data", (data) => { data = data.toString(); console.log("scan erro: ", data); if ( listTesting.filter( (obj) => obj.id === listLineUse[j][k].id_line ).length === 0 ) { listDeviceOff.push({ id: listLineUse[j][k].id_line, line: listLineUse[j][k].line_number, station: listStationUse[i], status: "off", message: "No connection to station", }); } }); } } } } } // setTimeout(() => { let listWaiting = listTesting.filter( (i) => i.status.search("dpel") !== -1 || i.status === "faulty" || i.status === "password" || i.status === "wait" // || // i.status === "loadingios" ); // console.log("WAITING",listWaiting); for (let i = 0; i < listWaiting.length; i++) { if ( listWaiting[i].status === "wait" || listWaiting[i].status === "loadingios" ) { // if(listTesting.filter((t) => t.id !== listWaiting[i].id && t.mode === "good").length>0){ // listTesting = listTesting.filter((t) => t.id !== listWaiting[i].id && t.status !== "wait"); // } } if ( listWaiting[i].status === "password" && listWaiting[i].station !== undefined ) { const checkPort = spawn( "python3", [ "./checkPort.py", "", listWaiting[i].station.sta_ip, listWaiting[i].station.sta_port_telnet, listWaiting[i].infoLine.line_clear, listWaiting[i].infoLine.line_number, ], { timeout: 30000 } ); checkPort.stdout.on("data", (data) => { data = data.toString(); if (data.search("switch:") !== -1) { let temp = []; temp.push({ id: listWaiting[i].id, line: listWaiting[i].line, station: listWaiting[i].station, status: "on", infoLine: listWaiting[i].infoLine, mode: "switch:", }); listTesting = listTesting.filter((t) => t.id !== listWaiting[i].id); if ( temp.length > 0 && onlineUsers.filter((i) => i.email !== "api")[0] !== undefined ) { listTesting = listTesting.concat(temp); io.to( onlineUsers.filter((i) => i.email !== "api")[0].socketId ).emit("sendListDeviceOn", temp); io.emit("sendListTesting", listTesting); } } if (data.search("rommon") !== -1) { let temp = []; temp.push({ id: listWaiting[i].id, line: listWaiting[i].line, station: listWaiting[i].station, status: "on", infoLine: listWaiting[i].infoLine, mode: "rommon", }); listTesting = listTesting.filter((t) => t.id !== listWaiting[i].id); if ( temp.length > 0 && onlineUsers.filter((i) => i.email !== "api")[0] !== undefined ) { listTesting = listTesting.concat(temp); io.to( onlineUsers.filter((i) => i.email !== "api")[0].socketId ).emit("sendListDeviceOn", temp); io.emit("sendListTesting", listTesting); } } }); } else { if ( listWaiting[i].station !== undefined && listWaiting[i].status !== "wait" ) { console.log(listWaiting[i]) const getSN = spawn( "python3", [ "./getSN.py", "", listWaiting[i].station.sta_ip, listWaiting[i].station.sta_port_telnet, listWaiting[i].infoLine.line_clear, listWaiting[i].infoLine.line_number, listWaiting[i].infoLine.line_port, listWaiting[i].mode ], { timeout: 150000 } ); getSN.stdout.on("data", (data) => { data = data.toString(); //check interface let interfaces = data ?.split("===")[1] ?.split("\n") ?.filter((i) => i.search("up") !== -1 || i.search("down") !== -1); let listInterDetect = []; let listInterDown = []; let interFinal = []; // console.log("**********************", listInterUP); interfaces?.map((int) => { let temp = int?.split(" ")[0]; interFinal.push( temp?.slice(0, 4) + ".." + temp?.slice(temp?.length - 6, temp?.length) ); if (int?.split("up").length - 1 >= 2) { listInterDetect.push( temp?.slice(0, 4) + ".." + temp?.slice(temp?.length - 6, temp?.length) ); if ( listInterUP.filter( (t) => t.id !== undefined && t.id === listWaiting[i].id ).length > 0 ) { // console.log("tontai"); listInterUP.map((u, index) => { if (u.id === listWaiting[i].id) { if ( listInterUP[index].inter.includes( temp?.slice(0, 4) + ".." + temp?.slice(temp?.length - 6, temp?.length) ) === false ) { listInterUP[index].inter.push( temp?.slice(0, 4) + ".." + temp?.slice(temp?.length - 6, temp?.length) ); } } }); } else { // console.log("kotontai");/ listInterUP.push({ id: listWaiting[i].id, inter: [ temp?.slice(0, 4) + ".." + temp?.slice(temp?.length - 6, temp?.length), ], }); } } }); listTesting.map((u, index) => { if (u.id === listWaiting[i].id) { listTesting[index].interfaceCheck = { interUp: listInterDetect, interDown: interFinal.filter( (x) => listInterUP .filter((t) => t.id === listWaiting[i].id)[0] ?.inter?.includes(x) === false ).length > 0 ? interFinal.filter( (x) => listInterUP .filter((t) => t.id === listWaiting[i].id)[0] ?.inter?.includes(x) === false ) : interFinal, interUpFinal: listInterUP.filter((t) => t.id === listWaiting[i].id)[0] ?.inter !== undefined ? listInterUP.filter((t) => t.id === listWaiting[i].id)[0] ?.inter : [], }; } }); io.emit("sendListTesting", listTesting); let SN0 = data.split("\n").filter((i) => i.search("SN:") !== -1)[0]; if (SN0 !== undefined && listWaiting[i].mode === "fail") { listWaiting[i].mode = "good"; console.log( SN0.slice(SN0.search("SN:") + 3, SN0.length).trim() + "--line--" + listWaiting[i].infoLine.line_number + "--station--" + listWaiting[i].station.sta_name ); if ( listWaiting.filter( (item) => item.SN === SN0.slice(SN0.search("SN:") + 3, SN0.length).trim() ).length === 0 ) { listTesting = listTesting.filter( (t) => t.id !== listWaiting[i].id ); io.emit("sendListTesting", listTesting); console.log("new deivce!\n", data); } else { console.log("old device"); } } else { if ( data.search("xxError") !== -1 && listWaiting[i].mode === "fail" ) { console.log("===============\n", data + "\n============="); console.log( "undefine--line--" + listWaiting[i].infoLine.line_number + "--station--" + listWaiting[i].station.sta_name ); listTesting = listTesting.filter( (t) => t.id !== listWaiting[i].id ); io.emit("sendListTesting", listTesting); console.log("new deivce!\n", data); } else { if (listWaiting[i].mode === "fail") { listWaiting[i].mode = "good"; // listTesting = listTesting.filter( // (t) => t.id !== listWaiting[i].id // ); // io.emit("sendListTesting", listTesting); // console.log("new deivce!\n", data); } // else { // listWaiting[i].mode = "fail"; // console.log("======Fail=========", data + "=============") // } if (data.search("xxError") !== -1) { listWaiting[i].mode = "fail"; console.log("======Fail========="); } } } }); getSN.stderr.on("data", (data) => { data = data.toString(); console.log("error: ", data); listTesting = listTesting.filter((t) => t.id !== listWaiting[i].id); io.emit("sendListTesting", listTesting); // console.log("======error=========", data + "=============") }); } } } }, 26000); io.listen(5000); console.log("Socket running....");