dsql-admin/dsql-app/utils/socket.ts

109 lines
3.7 KiB
TypeScript
Raw Normal View History

2024-11-05 11:12:42 +00:00
// @ts-check
2025-01-13 08:00:21 +00:00
import { Server as HttpServer } from "http";
import path from "path";
import fs from "fs";
import { Server } from "socket.io";
import { parse } from "url";
import suSocketAuth from "../package-shared/functions/backend/suSocketAuth";
import parseCookies from "@/package-shared/utils/backend/parseCookies";
export default async function serverSocket(server: HttpServer) {
2024-11-05 11:12:42 +00:00
const io = new Server(server);
io.on("connection", async (socket) => {
const req = socket.request;
const parsedUrl = parse(req.url || "", true);
const { pathname, query, href, search } = parsedUrl;
const cookie = req.headers.cookie;
const paradigm = req.headers["x-socket-paradigm"];
const parsedCookies = parseCookies({ request: req });
const suAdminUser = await suSocketAuth(req);
const logPath = path.resolve(__dirname, "../log.log");
if (!suAdminUser) return;
switch (paradigm) {
case "Console":
try {
socket.emit("console", "Welcome");
process.stdin.on("data", (data) => {
2025-01-13 08:00:21 +00:00
console.log("STDOUT data =>", data.toString());
2024-11-05 11:12:42 +00:00
});
const originalConsoleLog = console.log;
console.log = function (...args) {
const logMessage = args
.map((arg) =>
typeof arg === "object"
? JSON.stringify(arg)
: arg
)
.join(" ");
socket.emit("console", logMessage + "\n\r");
originalConsoleLog.apply(console, args);
};
socket.on("log", (log) => {
console.log(log);
});
socket.on("get-log", (log) => {
if (fs.existsSync(logPath)) {
socket.emit(
"console-log",
fs.readFileSync(logPath, "utf-8")
);
}
});
//////////////////////////////////////////
//////////////////////////////////////////
//////////////////////////////////////////
if (process.env.NEXT_PUBLIC_DSQL_LOCAL) {
const PAUSE = "\x13";
const CANCEL = "\x03";
const RESUME = "\x11";
2025-01-13 08:00:21 +00:00
// const ptyProcess = pty.spawn("bash", [], {
// name: "xterm-color",
// });
2024-11-05 11:12:42 +00:00
2025-01-13 08:00:21 +00:00
// socket.on("shell", (message) => {
// ptyProcess.write(message);
// });
2024-11-05 11:12:42 +00:00
2025-01-13 08:00:21 +00:00
// ptyProcess.onData((data) => {
// socket.emit("shell", data);
// });
2024-11-05 11:12:42 +00:00
2025-01-13 08:00:21 +00:00
// socket.on("disconnect", () => {
// ptyProcess.kill("SIGTERM");
// });
2024-11-05 11:12:42 +00:00
}
socket.on("clear-log", (message) => {
if (fs.existsSync(logPath))
fs.writeFileSync(logPath, "", "utf-8");
});
2025-01-13 08:00:21 +00:00
} catch (error: any) {
2024-11-05 11:12:42 +00:00
console.log("Error in Console socket =>", error.message);
}
break;
default:
break;
}
});
io.on("error", (err) => {
console.log("Socket Server Error =>", err);
});
2025-01-13 08:00:21 +00:00
}