File size: 2,571 Bytes
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 | import path from "path";
import schedule from "node-schedule";
import fs from "fs";
import { formatTime } from "./format-util.js";
const loggingMessageJsonPath = path.join(process.cwd(), "logs", "message.json");
let messageCache = {};
let hasChanges = false;
export const getMessageCache = () => messageCache;
export function getMessageCacheByMsgId(msgId) {
return Object.values(messageCache).find((message) => message.msgId === msgId);
}
function loadMessageCache() {
messageCache = readMessageJson();
}
function saveMessageCache() {
if (hasChanges) {
writeMessageJson(messageCache);
hasChanges = false;
}
}
export function readMessageJson() {
try {
const data = fs.readFileSync(loggingMessageJsonPath, "utf-8");
return JSON.parse(data);
} catch (error) {
console.error("Lỗi khi đọc file message.json:", error);
return {};
}
}
export function writeMessageJson(data) {
try {
fs.writeFileSync(loggingMessageJsonPath, JSON.stringify(data, null, 2), "utf-8");
} catch (error) {
console.error("Lỗi khi ghi file message.json:", error);
}
}
function cleanOldMessages() {
const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
let hasDeleted = false;
Object.keys(messageCache).forEach((key) => {
if (messageCache[key].timestamp < oneDayAgo) {
delete messageCache[key];
hasDeleted = true;
}
});
if (hasDeleted) {
hasChanges = true;
}
}
loadMessageCache();
schedule.scheduleJob("*/5 * * * * *", () => {
saveMessageCache();
if (new Date().getSeconds() === 0) {
cleanOldMessages();
}
});
const listSaveLogMess = [
"webchat",
"chat.photo",
"chat.gif",
"chat.video.msg",
"chat.recommended",
"chat.sticker",
"chat.voice",
"share.file",
];
export function updateMessageCache(data) {
try {
// if (listSaveLogMess.includes(data.data.msgType)) {
const timestamp = formatTime(new Date());
const filterData = {
timestamp: data.data.ts,
timestampString: timestamp,
msgId: data.data.msgId,
cliMsgId: data.data.cliMsgId,
msgType: data.data.msgType,
uidFrom: data.data.uidFrom,
idTo: data.data.idTo,
dName: data.data.dName,
content: data.data.content,
threadId: data.threadId,
type: data.type,
isUndo: false,
};
messageCache[data.data.cliMsgId] = {
...filterData,
};
hasChanges = true;
// }
} catch {
}
} |