File size: 10,298 Bytes
183a3de e20a993 183a3de | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";
import path from "path";
import { fileURLToPath } from "url";
import multer from "multer";
import chalk from "chalk";
import { getDataAllGroup } from "../service-dqt/info-service/group-info.js";
import fs from "fs/promises";
import { readGroupSettings, readWebConfig, writeWebConfig } from "../utils/io-json.js";
import { MessageType } from "../api-zalo/models/Message.js";
import { sendBulkMessage, stopBulkMessage } from "./bulk-message.js";
import { changeStatusConfig } from "./change-status-config.js";
import { getCommandConfig } from "../index.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Cấu hình multer để xử lý tải lên file
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, "../../assets/resources/"));
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
const upload = multer({ storage: storage });
let io;
let cachedFriends = null;
let lastFriendsFetchTime = 0;
const CACHE_DURATION = 10000; // 10 giây
let cachedGroups = null;
let lastGroupsFetchTime = 0;
const GROUPS_CACHE_DURATION = 10000; // 10 giây
export async function startWebServer(api) {
const app = express();
const httpServer = createServer(app);
io = new Server(httpServer);
let filePaths = [];
app.use(express.static(path.join(__dirname, "../../public")));
app.post("/upload", upload.array("files"), (req, res) => {
filePaths = req.files.map((file) => file.path);
res.json({ message: "Tải lên thành công", filePaths });
});
io.on("connection", (socket) => {
console.log(chalk.green("Một client đã kết nối tới web socket"));
socket.on("getAllFriends", async () => {
try {
const currentTime = Date.now();
if (!cachedFriends || currentTime - lastFriendsFetchTime > CACHE_DURATION) {
cachedFriends = await api.getAllFriends();
lastFriendsFetchTime = currentTime;
}
socket.emit("friendsList", cachedFriends);
} catch (error) {
console.error(chalk.red("Lỗi khi lấy danh sách bạn bè:"), error);
socket.emit("error", "Không thể lấy danh sách bạn bè");
}
});
socket.on("getAllGroups", async () => {
try {
const currentTime = Date.now();
if (!cachedGroups || currentTime - lastGroupsFetchTime > GROUPS_CACHE_DURATION) {
const groups = await getDataAllGroup(api);
const groupSettings = readGroupSettings();
cachedGroups = groups.map((group) => ({
...group,
settings: groupSettings[group.groupId] || {},
}));
lastGroupsFetchTime = currentTime;
}
socket.emit("groupsList", cachedGroups);
} catch (error) {
console.error(chalk.red("Lỗi khi lấy danh sách nhóm:"), error);
socket.emit("error", "Không thể lấy danh sách nhóm");
}
});
socket.on("sendMessageToSingle", async (data) => {
const { id, type, message, delay } = data;
let messageType = type === "friend" ? MessageType.DirectMessage : MessageType.GroupMessage;
try {
await api.sendMessagev1(
{
msg: message,
attachments: filePaths,
ttl: delay ? delay : 0,
linkOn: false,
},
id,
messageType
);
await deleteFiles(filePaths);
filePaths = [];
} catch (error) { }
});
socket.on("sendMessageAll", async (data) => {
try {
const { message, messageType, delay } = data;
const type = messageType === "DirectMessage" ? MessageType.DirectMessage : MessageType.GroupMessage;
const allDataList = type === MessageType.DirectMessage ? await api.getAllFriends() : await getDataAllGroup(api);
for (const data of allDataList) {
try {
if (data) {
await api.sendMessagev1(
{
msg: message,
attachments: filePaths,
ttl: delay ? delay : 0,
linkOn: false,
},
type === MessageType.DirectMessage ? data.userId : data.groupId,
type
);
}
} catch (error) { }
}
socket.emit("messageSent", "Tin nhắn đã được gửi thành công");
await deleteFiles(filePaths);
filePaths = [];
} catch (error) {
console.error("Lỗi khi gửi tin nhắn:", error);
socket.emit("error", "Không thể gửi tin nhắn");
}
});
socket.on("sendMessageForSelected", async (data) => {
try {
const { message, delay } = data;
const webConfig = readWebConfig();
const selectedFriends = webConfig.selectedFriends;
const selectedGroups = webConfig.selectedGroups;
for (const friendId in selectedFriends) {
try {
await api.sendMessagev1(
{
msg: message,
attachments: filePaths,
ttl: delay ? delay : 0,
linkOn: false,
},
friendId,
MessageType.DirectMessage
);
} catch (error) { }
}
for (const groupId in selectedGroups) {
try {
await api.sendMessagev1(
{
msg: message,
attachments: filePaths,
ttl: delay ? delay : 0,
linkOn: false,
},
groupId,
MessageType.GroupMessage
);
} catch (error) { }
}
socket.emit("messageSent", "Tin nhắn đã được gửi thành công");
await deleteFiles(filePaths);
filePaths = [];
} catch (error) {
console.error("Lỗi khi gửi tin nhắn:", error);
socket.emit("error", "Không thể gửi tin nhắn");
}
});
socket.on("updateSelectedGroups", (selectedGroups) => {
const configPath = path.join(process.cwd(), "assets", "web-config", "web-config.json");
let config = JSON.parse(fs.readFileSync(configPath, "utf8"));
config.selectedGroups = selectedGroups;
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
});
socket.on("updateSelected", (selected) => {
try {
const webConfig = readWebConfig();
webConfig.selectedGroups = selected.groups;
webConfig.selectedFriends = selected.friends;
writeWebConfig(webConfig);
socket.emit("configUpdated", { success: true, message: "Cập nhật cấu hình từ websocket thành công" });
} catch (error) {
console.error("Lỗi khi cập nhật file config:", error);
socket.emit("configUpdated", { success: false, message: "Lỗi khi cập nhật cấu hình" });
}
});
socket.on("getSelectedData", () => {
try {
const webConfig = readWebConfig();
socket.emit("selectedData", {
selectedGroups: webConfig.selectedGroups || {},
selectedFriends: webConfig.selectedFriends || {},
});
} catch (error) {
console.error("Lỗi khi đọc file config:", error);
socket.emit("error", "Không thể đọc dữ liệu đã chọn");
}
});
socket.on("updateActiveBotStatus", async ({ groupId, groupName, isActive }) => {
try {
await changeStatusConfig({ api, groupId, groupName, command: "activeBot", isActive });
} catch (error) {
console.error("Lỗi khi cập nhật trạng thái Active Bot:", error);
}
});
socket.on("updateFutureStatus", async ({ groupId, groupName, command, isActive }) => {
try {
await changeStatusConfig({ api, groupId, groupName, command, isActive });
} catch (error) {
console.error(`Lỗi khi cập nhật trạng thái ${command}:`, error);
}
});
socket.on("getInitialData", async () => {
try {
const webConfig = readWebConfig();
const groupSettings = readGroupSettings();
socket.emit("initialData", { ...webConfig, groupSettings });
} catch (error) {
console.error("Lỗi khi đọc dữ liệu ban đầu:", error);
socket.emit("initialData", {});
}
});
socket.on("disconnect", () => {
console.log(chalk.red("Một client đã ngắt kết nối tới web socket"));
});
socket.on("startBulkMessage", async (data) => {
try {
await sendBulkMessage(api, socket, data);
} catch (error) {
console.error("Lỗi khi bắt đầu gửi tin nhắn hàng loạt:", error);
socket.emit("error", "Không thể bắt đầu gửi tin nhắn hàng loạt");
}
});
socket.on("stopBulkMessage", async () => {
try {
await stopBulkMessage();
socket.emit("bulkMessageStatus", "stopped");
} catch (error) {
console.error("Lỗi khi dừng gửi tin nhắn hàng loạt:", error);
socket.emit("error", "Không thể dừng gửi tin nhắn hàng loạt");
}
});
socket.on("getCommands", () => {
try {
const commandConfig = getCommandConfig();
socket.emit("commandList", commandConfig);
} catch (error) {
socket.emit("error", "Không thể lấy danh sách lệnh");
}
});
});
const PORT = 7860;
httpServer.listen(PORT, () => {
console.log(chalk.yellow(`Web server đã khởi tạo thành công trên port ${PORT}`));
});
}
export function getIO() {
return io;
}
async function deleteFiles(paths) {
for (const path of paths) {
try {
await fs.unlink(path);
} catch (error) {
console.error(`Lỗi khi xóa file ${path}:`, error);
}
}
}
|