This commit is contained in:
joseph le 2023-10-20 09:53:53 +07:00
commit 8e051c269a
14 changed files with 2242 additions and 594 deletions

View File

@ -2,31 +2,31 @@ import fs from 'fs';
import moment from "moment"; import moment from "moment";
const shortenStringsInObject = (obj, maxLength) => { // const shortenStringsInObject = (obj, maxLength) => {
// Kiểm tra nếu obj không phải là một đối tượng hoặc maxLength không phải là một số // // Kiểm tra nếu obj không phải là một đối tượng hoặc maxLength không phải là một số
if (typeof obj !== 'object' || typeof maxLength !== 'number') { // if (typeof obj !== 'object' || typeof maxLength !== 'number') {
return obj; // return obj;
} // }
// Duyệt qua các thuộc tính của đối tượng // // Duyệt qua các thuộc tính của đối tượng
for (const key in obj) { // for (const key in obj) {
if (obj.hasOwnProperty(key)) { // if (obj.hasOwnProperty(key)) {
// Kiểm tra nếu thuộc tính là một chuỗi và độ dài của chuỗi lớn hơn maxLength // // Kiểm tra nếu thuộc tính là một chuỗi và độ dài của chuỗi lớn hơn maxLength
if (typeof obj[key] === 'string' && obj[key].length > maxLength) { // if (typeof obj[key] === 'string' && obj[key].length > maxLength) {
// Rút ngắn chuỗi lại maxLength ký tự // // Rút ngắn chuỗi lại maxLength ký tự
obj[key] = obj[key].substring(0, maxLength); // obj[key] = obj[key].substring(0, maxLength);
} // }
} // }
} // }
if (Array.isArray(obj) && obj.length > 10) { // if (Array.isArray(obj) && obj.length > 10) {
// Rút ngắn chuỗi lại maxLength ký tự // // Rút ngắn chuỗi lại maxLength ký tự
obj = "[Array:"+obj.length+"]\n"+obj.slice(0,15) // obj = "[Array:"+obj.length+"]\n"+obj.slice(0,15)
} // }
return obj; // return obj;
} // }
export function loggerAPI(req, res, location) { export function loggerAPI(req, res, location) {
let old_data = ""; let old_data = "";

View File

@ -0,0 +1,34 @@
import fs from "fs";
import moment from "moment";
export const addLogFunction = async (fileName, data, functionName) => {
try {
fs.exists(fileName, async (exists) => {
if (exists) {
let old_data = await fs.readFileSync(fileName, "utf8");
fs.writeFileSync(
fileName,
old_data +
"\n\n[" +
moment(Date.now()).format("D/M/YY-HH:mm:ss") +
"] - " +
functionName +
"\n" +
data +
"\n\n======================================================================"
);
} else {
fs.writeFileSync(
fileName,
"\n\n[" +
moment(Date.now()).format("D/M/YY-HH:mm:ss") +
"] - System Logs" +
data +
"\n\n======================================================================"
);
}
});
} catch (error) {
console.log(error);
}
};

View File

@ -0,0 +1,36 @@
const fs = require("fs");
const moment = require("moment");
const addLogFunction = async (fileName, data, functionName) => {
try {
fs.exists(fileName, async (exists) => {
if (exists) {
let old_data = await fs.readFileSync(fileName, "utf8");
fs.writeFileSync(
fileName,
old_data +
"\n\n[" +
moment(Date.now()).format("D/M/YY-HH:mm:ss") +
"] - " +
functionName +
"\n" +
data +
"\n\n======================================================================"
);
} else {
fs.writeFileSync(
fileName,
"\n\n[" +
moment(Date.now()).format("D/M/YY-HH:mm:ss") +
"] - System Logs" +
data +
"\n\n======================================================================"
);
}
});
} catch (error) {
console.log(error);
}
};
module.exports.addLogFunction = addLogFunction;

View File

@ -3,6 +3,8 @@ import Env from "@ioc:Adonis/Core/Env";
// import fs from "fs"; // import fs from "fs";
import axios from "axios"; import axios from "axios";
import { addLogFunction } from "./addLogFunction";
import moment from "moment";
export const checkIndexSN = async (content, beginLine, nameF) => { export const checkIndexSN = async (content, beginLine, nameF) => {
try { try {
@ -195,6 +197,11 @@ export const checkIndexSN = async (content, beginLine, nameF) => {
); );
console.log(nameF + " response\n", response_int.data); console.log(nameF + " response\n", response_int.data);
const fileName =
"./app/store/logsAPI/" +
moment(Date.now()).format("DD_MM_YYYY").toString() +
".log";
addLogFunction(fileName, "URL: https://int.ipsupply.com.au/api/transferPostData\n"+ response_int.data, "Update SN index to int.ipsupply.com.au");
} }
} }
} }

View File

@ -1,5 +1,6 @@
const puppeteer = require("puppeteer"); const puppeteer = require("puppeteer");
const zulip = require("zulip-js"); const zulip = require("zulip-js");
const { addLogFunction } = require("./addLogFunctionJS");
(async () => { (async () => {
// Launch a headless browser // Launch a headless browser
@ -60,8 +61,8 @@ const zulip = require("zulip-js");
) { ) {
let params = { let params = {
type: "stream", type: "stream",
to: "Result test - auto.nswteam.net", to: "APAC Tech Bão",
topic: "Lịch cúp điện", topic: "Thông báo chung",
content: content:
":warning: :date: :warning:\n\n" + ":warning: :date: :warning:\n\n" +
tableData tableData
@ -72,4 +73,9 @@ const zulip = require("zulip-js");
client.messages.send(params); client.messages.send(params);
} }
}, 5000); }, 5000);
const fileName =
"./app/store/logsAPI/" +
moment(Date.now()).format("DD_MM_YYYY").toString() +
".log";
addLogFunction(fileName, JSON.stringify(params, null, 2), "powerSchedule")
})(); })();

View File

@ -73,8 +73,8 @@ export async function runtimeCheckLogs(folderPath) {
if ( if (
filePath?.split(".")[filePath.split(".").length - 1] === "log" && filePath?.split(".")[filePath.split(".").length - 1] === "log" &&
filePath.split("/")[filePath.split("/").length - 1]?.split("-")[0] === filePath.split("/")[filePath.split("/").length - 1]?.split("-")[0] ===
//localhost //localhost
// filePath.split("\\")[filePath.split("\\").length - 1]?.split("-")[0] === // filePath.split("\\")[filePath.split("\\").length - 1]?.split("-")[0] ===
moment(Date.now()).format("YYYYMMDD").toString() moment(Date.now()).format("YYYYMMDD").toString()
) { ) {
//add information file to database //add information file to database
@ -99,86 +99,163 @@ export async function runtimeCheckLogs(folderPath) {
// Watch for changes in the files listed // Watch for changes in the files listed
async function watchFilesInList() { async function watchFilesInList() {
//only check new file ---> fileList - fileList_old = new file try {
let listFileWatch = fileList //only check new file ---> fileList - fileList_old = new file
?.filter((i) => fileList_old.includes(i) === false) let listFileWatch = fileList
.map((file) => folderPath + "/" + file); ?.filter((i) => fileList_old.includes(i) === false && i.includes(".log"))
const watcher = chokidar.watch(listFileWatch, { .map((file) => folderPath + "/" + file);
persistent: true, const watcher = chokidar.watch(listFileWatch, {
usePolling: true, persistent: true,
interval: 300000, usePolling: true,
}); interval: 300000,
});
watcher.setMaxListeners(200); watcher.setMaxListeners(200);
watcher.on("change", async (path) => { watcher.on("change", async (path) => {
// fs.watchFile(filePath,{ interval: 15000 }, // fs.watchFile(filePath,{ interval: 15000 },
// async (eventType) => { // async (eventType) => {
//check special item, extra RAM, error in log //check special item, extra RAM, error in log
const fileName = path.split("/")[path.split("/").length - 1]; const fileName = path.split("/")[path.split("/").length - 1];
// const fileName = path.split("\\")[path.split("\\").length - 1]; // const fileName = path.split("\\")[path.split("\\").length - 1];
const filePath = path; const filePath = path;
let lines = []; let lines = [];
const today = DateTime.now().toFormat("yyyy-MM-dd"); const today = DateTime.now().toFormat("yyyy-MM-dd");
let allFile = await LogDetectFile.query().whereRaw( let allFile = await LogDetectFile.query().whereRaw(
`DATE(created_at) = ?`, `DATE(created_at) = ?`,
[today] [today]
); );
// let allReport = await LogReport.all(); // let allReport = await LogReport.all();
let allValue = await KeyValue.all(); let allValue = await KeyValue.all();
const allReport = await LogReport.query().whereRaw( const allReport = await LogReport.query().whereRaw(
`DATE(created_at) = ?`, `DATE(created_at) = ?`,
[today] [today]
); );
//get information file //get information file
let fileDetect = allFile?.filter( let fileDetect = allFile?.filter(
(i) => i.$original.file_name === fileName (i) => i.$original.file_name === fileName
)[0]; )[0];
let logsDetect = allReport?.filter( let logsDetect = allReport?.filter(
(i) => i.$original.id_file === fileDetect?.id_ldf (i) => i.$original.id_file === fileDetect?.id_ldf
); );
//get the last line detected //get the last line detected
let lastLine = Math.max(...logsDetect.map((obj) => obj.line)); let lastLine = Math.max(...logsDetect.map((obj) => obj.line));
//get content file in local //get content file in local
let contentFile = await fs let contentFile = await fs
.readFileSync(filePath) .readFileSync(filePath)
.toString() .toString()
?.split("\n"); ?.split("\n");
//get index SN and send to ERP //get index SN and send to ERP
checkIndexSN(contentFile, lastLine, fileName); checkIndexSN(contentFile, lastLine, fileName);
//get list item to check //get list item to check
let listKeyValues = allValue.filter( let listKeyValues = allValue.filter(
(i) => (i) =>
i.$original.key === "MODEL_SPECIAL" || i.$original.key === "MODEL_SPECIAL" ||
i.$original.key === "CATCH_FAULTY" i.$original.key === "CATCH_FAULTY"
); );
//get list exclude error //get list exclude error
let listExcludeErr = allValue let listExcludeErr = allValue
.filter((i) => i.$original.key === "EXCLUDE_ERR") .filter((i) => i.$original.key === "EXCLUDE_ERR")
.map((obj) => obj.$original.value); .map((obj) => obj.$original.value);
//get list item special //get list item special
let listExtraItem = allValue let listExtraItem = allValue
.filter((i) => i.$original.key === "MODEL_SPECIAL") .filter((i) => i.$original.key === "MODEL_SPECIAL")
.map((obj) => obj.$original.value); .map((obj) => obj.$original.value);
//Process file content //Process file content
if (contentFile.length > 50000) { if (contentFile.length > 50000) {
for (let i = 0; i < contentFile.length; i += 1000) { for (let i = 0; i < contentFile.length; i += 1000) {
const chunk = contentFile.slice(i, i + 1000); const chunk = contentFile.slice(i, i + 1000);
chunk.map(async (line, index) => { chunk.map(async (line, index) => {
//check line the line with errors and exclude errors
listKeyValues
.map((obj) => obj.$original.value)
.map(async (value) => {
if (
line.includes(value) &&
listExcludeErr.filter((err) => line.includes(err))
.length === 0
) {
let log = allFile?.filter(
(i) => i.$original.file_name === fileName
)[0];
let checkLog = allReport?.filter(
(report) =>
report.$original.id_file === log?.id_ldf &&
report.$original.line === index + 1 &&
report.$original.detected_content === value
);
if (
log?.id_ldf === "" ||
log?.id_ldf === null ||
log?.id_ldf === undefined
) {
console.log("ERROR CHECK ", fileName)
}
if (checkLog?.length === 0) {
await LogReport.create({
detected_content: value,
line: index + 1,
id_file: log?.id_ldf,
});
lines.push(index + 1);
}
}
});
if (
checkSpecialVersion(line) !== "" &&
listExcludeErr.filter((err) => line.includes(err)).length ===
0
) {
let checkVersion = checkSpecialVersion(line);
let log = allFile?.filter(
(i) => i.$original.file_name === fileName
)[0];
if (
log?.id_ldf === "" ||
log?.id_ldf === null ||
log?.id_ldf === undefined
) {
console.log("ERROR CHECK ", fileName)
}
let checkLog = allReport?.filter(
(report) =>
report.$original.id_file === log?.id_ldf &&
report.$original.line === index + 1 &&
report.$original.detected_content === checkVersion
);
if (checkLog?.length === 0) {
await LogReport.create({
detected_content: checkVersion,
line: index + 1,
id_file: log?.id_ldf,
});
lines.push(index + 1);
}
}
});
}
} else {
contentFile.map(async (line, index) => {
//check line the line with errors and exclude errors //check line the line with errors and exclude errors
listKeyValues listKeyValues
.map((obj) => obj.$original.value) .map((obj) => obj.$original.value)
.map(async (value) => { .map(async (value) => {
if ( if (
line.includes(value) && line.includes(value) &&
listExcludeErr.filter((err) => line.includes(err)) listExcludeErr.filter((err) => line.includes(err))
@ -187,7 +264,13 @@ export async function runtimeCheckLogs(folderPath) {
let log = allFile?.filter( let log = allFile?.filter(
(i) => i.$original.file_name === fileName (i) => i.$original.file_name === fileName
)[0]; )[0];
if (
log?.id_ldf === "" ||
log?.id_ldf === null ||
log?.id_ldf === undefined
) {
console.log("ERROR CHECK ", fileName)
}
let checkLog = allReport?.filter( let checkLog = allReport?.filter(
(report) => (report) =>
report.$original.id_file === log?.id_ldf && report.$original.id_file === log?.id_ldf &&
@ -216,7 +299,13 @@ export async function runtimeCheckLogs(folderPath) {
let log = allFile?.filter( let log = allFile?.filter(
(i) => i.$original.file_name === fileName (i) => i.$original.file_name === fileName
)[0]; )[0];
if (
log?.id_ldf === "" ||
log?.id_ldf === null ||
log?.id_ldf === undefined
) {
console.log("ERROR CHECK ", fileName)
}
let checkLog = allReport?.filter( let checkLog = allReport?.filter(
(report) => (report) =>
report.$original.id_file === log?.id_ldf && report.$original.id_file === log?.id_ldf &&
@ -235,189 +324,117 @@ export async function runtimeCheckLogs(folderPath) {
} }
}); });
} }
} else {
contentFile.map(async (line, index) => {
//check line the line with errors and exclude errors
listKeyValues
.map((obj) => obj.$original.value)
.map(async (value) => {
// console.log({line:Array(line), value:Array(value)})
if (
line.includes(value) &&
listExcludeErr.filter((err) => line.includes(err)).length ===
0
) {
let log = allFile?.filter(
(i) => i.$original.file_name === fileName
)[0];
let checkLog = allReport?.filter( //true: import log to log_report table, send report to Zulip
(report) => setTimeout(async () => {
report.$original.id_file === log?.id_ldf && if (lines.length === 0) {
report.$original.line === index + 1 && console.log(
report.$original.detected_content === value fileName + "has changed(" + contentFile.length + ") ---Good"
); );
} else {
console.log(
fileName +
"has changed(" +
contentFile.length +
") ---SOS---" +
lines.length
);
let allReport_new = await LogReport.query().whereRaw(
`DATE(created_at) = ?`,
[today]
);
if (checkLog?.length === 0) { let fileDetect = allFile?.filter(
await LogReport.create({
detected_content: value,
line: index + 1,
id_file: log?.id_ldf,
});
lines.push(index + 1);
}
}
// if(checkSpecialVersion())
});
if (
checkSpecialVersion(line) !== "" &&
listExcludeErr.filter((err) => line.includes(err)).length === 0
) {
let checkVersion = checkSpecialVersion(line);
let log = allFile?.filter(
(i) => i.$original.file_name === fileName (i) => i.$original.file_name === fileName
)[0]; )[0];
let checkLog = allReport?.filter( let logsDetect = allReport_new?.filter(
(report) => (i) => i.$original.id_file === fileDetect?.id_ldf
report.$original.id_file === log?.id_ldf && );
report.$original.line === index + 1 &&
report.$original.detected_content === checkVersion //Get all report newest
let listReport = await getListLineByItem(
logsDetect
.map((obj) => obj.$original)
.filter((l) => l.line > lastLine)
); );
if (checkLog?.length === 0) { let content =
await LogReport.create({ "| |Last updated at | Item/error | Line | Report \n|---|:---:|:---|:---|:-----------:\n";
detected_content: checkVersion, let spoiler = "";
line: index + 1, let issueFound = "";
id_file: log?.id_ldf, let important = [
"Vxx",
"V00",
"(CAT3K_CAA-UNIVERSALK9-M), Version",
];
listReport.map((log, index) => {
let item = listExtraItem.includes(log.detected_content)
? ":medal: **" + log.detected_content + "**"
: ":small_orange_diamond: " + log.detected_content;
log.line?.map((line) => {
issueFound =
issueFound +
"\n`" +
line +
"` " +
contentFile[line - 1]?.replace(
log.detected_content,
"[" +
log.detected_content +
"](https://logs.danielvu.com/logs/" +
fileName +
"#" +
line +
")"
);
}); });
lines.push(index + 1); content =
} content +
} "|" +
}); (index + 1) +
} "|**" +
moment(Date.now()).format("HH:mm - DD/MM") +
//true: import log to log_report table, send report to Zulip "**|" +
setTimeout(async () => { item +
if (lines.length === 0) { "|" +
console.log( log.line +
fileName + "has changed(" + contentFile.length + ") ---Good" "|[View](https://logs.danielvu.com/logs/" +
);
} else {
console.log(
fileName +
"has changed(" +
contentFile.length +
") ---SOS---" +
lines.length
);
let allReport_new = await LogReport.query().whereRaw(
`DATE(created_at) = ?`,
[today]
);
let fileDetect = allFile?.filter(
(i) => i.$original.file_name === fileName
)[0];
let logsDetect = allReport_new?.filter(
(i) => i.$original.id_file === fileDetect?.id_ldf
);
// console.log(logsDetect)
// await Database.rawQuery(
// "select * from log_reports where id_file = " +
// fileDetect?.id_ldf
// );
//Get all report newest
let listReport = await getListLineByItem(
logsDetect
.map((obj) => obj.$original)
.filter((l) => l.line > lastLine)
);
let content =
"| |Last updated at | Item/error | Line | Report \n|---|:---:|:---|:---|:-----------:\n";
let spoiler = "";
let issueFound = "";
let important = [
"Vxx",
"V00",
"(CAT3K_CAA-UNIVERSALK9-M), Version",
];
listReport.map((log, index) => {
let item = listExtraItem.includes(log.detected_content)
? ":medal: **" + log.detected_content + "**"
: ":small_orange_diamond: " + log.detected_content;
log.line?.map((line) => {
issueFound =
issueFound +
"\n`" +
line +
"` " +
contentFile[line - 1]?.replace(
log.detected_content,
"[" +
log.detected_content +
"](https://logs.danielvu.com/logs/" +
fileName +
"#" +
line +
")"
);
});
content =
content +
"|" +
(index + 1) +
"|**" +
moment(Date.now()).format("HH:mm - DD/MM") +
"**|" +
item +
"|" +
log.line +
"|[View](https://logs.danielvu.com/logs/" +
fileName +
"#" +
log.line +
")\n";
});
let icon =
important.filter((i) => content.includes(i)).length > 0
? "------------\n\n:no_entry: :no_entry:**" +
fileName + fileName +
"**:no_entry: :no_entry:" "#" +
: "------------\n\n:warning: :warning: **" + fileName + "**"; log.line +
sendMessToZulip( ")\n";
"stream", });
Env.get("ZULIP_STREAM_ALERT"),
Env.get("ZULIP_TOPIC_ALERT"),
icon +
"\n\n" +
content +
"\n\n" +
spoiler +
"\n\n***Issue found:***\n" +
issueFound
);
}
}, 3000);
// console.log(path + " change")
});
watcher.on("error", (error) => { let icon =
console.error(`Watcher error: ${error}`); important.filter((i) => content.includes(i)).length > 0
}); ? "------------\n\n:no_entry: :no_entry:**" +
// await fileList.slice(0,40) fileName +
// ?.filter((i) => fileList_old.includes(i) === false) "**:no_entry: :no_entry:"
// ?.forEach((fileName) => { : "------------\n\n:warning: :warning: **" + fileName + "**";
// //path file sendMessToZulip(
// const filePath = `${folderPath}/${fileName}`; "stream",
Env.get("ZULIP_STREAM_ALERT"),
Env.get("ZULIP_TOPIC_ALERT"),
icon +
"\n\n" +
content +
"\n\n" +
spoiler +
"\n\n***Issue found:***\n" +
issueFound
);
}
}, 3000);
});
// }); watcher.on("error", (error) => {
console.error(`Watcher error: ${error}`);
});
} catch (error) {
console.log(error);
}
} }
} catch (error) { } catch (error) {
console.log(error); console.log(error);

Binary file not shown.

Before

Width:  |  Height:  |  Size: 304 KiB

View File

@ -5,6 +5,7 @@ import nodeMailer from "nodemailer";
import LogDetectFile from "App/Models/LogDetectFile"; import LogDetectFile from "App/Models/LogDetectFile";
import InfoDevice from "App/Models/InfoDevice"; import InfoDevice from "App/Models/InfoDevice";
import KeyValue from "App/Models/KeyValue"; import KeyValue from "App/Models/KeyValue";
import { addLogFunction } from "./addLogFunction";
export const sendDeviceInfora = async () => { export const sendDeviceInfora = async () => {
try { try {
@ -14,10 +15,11 @@ export const sendDeviceInfora = async () => {
const regexVersion = /sh.*? ver.*/; const regexVersion = /sh.*? ver.*/;
const regexMemory = /(\d+)K/g; const regexMemory = /(\d+)K/g;
const date = moment(Date.now()).format("YYYYMMDD"); const date = moment(Date.now()).format("YYYYMMDD");
const memDefault = (await KeyValue.all()) const allKeyValue = await KeyValue.all();
const memDefault = allKeyValue
.filter((i) => i.$attributes.key === "MEMORY_DEFAULT") .filter((i) => i.$attributes.key === "MEMORY_DEFAULT")
.map((obj) => obj.$attributes.value); .map((obj) => obj.$attributes.value);
const listInformation = []; let listInformation = [];
let dataFile = await LogDetectFile.all(); let dataFile = await LogDetectFile.all();
let html = ""; let html = "";
@ -38,300 +40,283 @@ export const sendDeviceInfora = async () => {
}); });
//Read file in listFile //Read file in listFile
await listFile.map(async (file) => { const filePromises = listFile.map((file, index) => {
fs.readFile( return new Promise((resolve, reject) => {
Env.get("FOLDER_LOGS") + "/" + file, fs.readFile(
"utf8", Env.get("FOLDER_LOGS") + "/" + file,
async (err, data) => { "utf8",
if (err) { async (err, data) => {
console.log(`Error reading file: ${err}`); if (err) {
} else { console.log(`Error reading file: ${err}`);
//Array line
const lines = data?.split("\n");
const linesInventory = [];
let DBFileCheck = dataFile.filter(
(i) => i.$attributes.file_name === file
)[0];
if (DBFileCheck !== undefined) {
if (lines.length > DBFileCheck?.$extras.last_check_SN) {
const DBFile = await LogDetectFile.find(
DBFileCheck?.$attributes.id_ldf
);
// console.log(DBFile)
DBFile.last_check_SN = lines.length;
await DBFile.save();
}
} else { } else {
await LogDetectFile.firstOrCreate( //Array line
{ file_name: file }, const lines = data?.split("\n");
{ file_name: file } const linesInventory = [];
); let DBFileCheck = dataFile.filter(
dataFile = await LogDetectFile.all();
DBFileCheck = dataFile.filter(
(i) => i.$attributes.file_name === file (i) => i.$attributes.file_name === file
)[0]; )[0];
} if (DBFileCheck !== undefined) {
if (lines.length > DBFileCheck?.$extras.last_check_SN) {
//Get index of "lines" with show inv const DBFile = await LogDetectFile.find(
lines DBFileCheck?.$attributes.id_ldf
?.slice(DBFileCheck?.$extras.last_check_SN, lines.length - 1)
.map((line, index) => {
if (line.match(regexInventory) !== null) {
linesInventory.push(index);
}
});
//cut content with content1 = [linesInventory[index],linesInventory[index+1]] ...
linesInventory?.map((line, index) => {
const deviceContent = lines?.slice(
linesInventory[index],
linesInventory[index + 1]
);
let backgroundColor = "rgb(200 200 200 / 30%)";
const showInventory = [];
let check = true;
let begin = 0;
let end = 4;
//get showInventory content
while (check === true) {
if (
deviceContent
.slice(begin, end)
.filter(
(i) =>
i.includes("PID:") &&
i.includes("VID:") &&
i.includes("SN:")
).length > 0
) {
showInventory.push(
deviceContent.slice(begin, end).join("\n")
); );
begin = end;
end = end + 4; // console.log(DBFile)
} else {
check = false; DBFile.last_check_SN = lines.length;
await DBFile.save();
} }
} else {
await LogDetectFile.firstOrCreate(
{ file_name: file },
{ file_name: file }
);
dataFile = await LogDetectFile.all();
DBFileCheck = dataFile.filter(
(i) => i.$attributes.file_name === file
)[0];
} }
const showInventoryContent = showInventory //Get index of "lines" with show inv
.join("\n") lines
.split("\n") ?.slice(DBFileCheck?.$extras.last_check_SN, lines.length - 1)
.filter( .map((line, index) => {
(i) => if (line.match(regexInventory) !== null) {
i.includes("PID:") && linesInventory.push(index);
i.includes("VID:") && }
i.includes("SN:") });
//cut content with content1 = [linesInventory[index],linesInventory[index+1]] ...
linesInventory?.map((line, index) => {
const deviceContent = lines?.slice(
linesInventory[index],
linesInventory[index + 1]
); );
//show version exists let backgroundColor = "rgb(200 200 200 / 30%)";
if ( const showInventory = [];
deviceContent.filter( let check = true;
(line) => line.match(regexVersion) !== null let begin = 0;
).length > 0 let end = 4;
) {
const lineShowver = deviceContent.indexOf( //get showInventory content
while (check === true) {
if (
deviceContent
.slice(begin, end)
.filter(
(i) =>
i.includes("PID:") &&
i.includes("VID:") &&
i.includes("SN:")
).length > 0
) {
showInventory.push(
deviceContent.slice(begin, end).join("\n")
);
begin = end;
end = end + 4;
} else {
check = false;
}
}
const showInventoryContent = showInventory
.join("\n")
.split("\n")
.filter(
(i) =>
i.includes("PID:") &&
i.includes("VID:") &&
i.includes("SN:")
);
//show version exists
if (
deviceContent.filter( deviceContent.filter(
(line) => line.match(regexVersion) !== null (line) => line.match(regexVersion) !== null
)[0] ).length > 0
); ) {
const lineShowver = deviceContent.indexOf(
const showVersion = deviceContent.slice(
lineShowver,
deviceContent.indexOf(
deviceContent.filter( deviceContent.filter(
(line) => line.search("Configuration register") !== -1 (line) => line.match(regexVersion) !== null
)[0] )[0]
) + 1 );
);
showInventoryContent.map((u, index) => { const showVersion = deviceContent.slice(
const PID = u lineShowver,
?.split("VID:")[0] deviceContent.indexOf(
?.split("PID:")[1] deviceContent.filter(
?.replace(/,/g, "") (line) => line.search("Configuration register") !== -1
.trim(); )[0]
const VID = u ) + 1
?.split("VID:")[1] );
?.split("SN:")[0]
?.replace(/,/g, "")
.trim();
const SN = u?.split("SN:")[1]?.replace(/,/g, "").trim();
// let memory =
if (index > 0) {
if (PID !== "" && SN !== "") {
listInformation.push({
PID: PID,
VID: VID,
SN: SN,
RAM: "",
flash: "",
extra_item: "yes",
});
html += `<tr><td>${PID}</td> showInventoryContent.map((u, index) => {
<td>${VID}</td> const PID = u
<td>${SN}</td> ?.split("VID:")[0]
<td></td> ?.split("PID:")[1]
<td></td> ?.replace(/,/g, "")
<td>yes</td></tr>`; .trim();
} const VID = u
} else { ?.split("VID:")[1]
if (PID !== "" && SN !== "") { ?.split("SN:")[0]
const memDefaultForPID = ?.replace(/,/g, "")
memDefault.filter((i) => .trim();
PID.includes(i.split(":")[0]) const SN = u?.split("SN:")[1]?.replace(/,/g, "").trim();
)[0] !== undefined if (index > 0) {
? memDefault.filter((i) => if (PID !== "" && SN !== "") {
PID.includes(i.split(":")[0]) listInformation.push({
)[0] PID: PID,
: PID + ":N/A:N/A"; VID: VID,
let RAM = SN: SN,
showVersion RAM: "",
.filter( flash: "",
(line) => extra_item: "yes",
line.includes("bytes of memory") || });
line.includes("bytes of physical memory") }
) } else {
.join("<br>") if (PID !== "" && SN !== "") {
.match(regexMemory) !== null const memDefaultForPID =
? ( memDefault.filter((i) =>
parseInt( PID.includes(i.split(":")[0])
showVersion )[0] !== undefined
.filter( ? memDefault.filter((i) =>
(line) => PID.includes(i.split(":")[0])
line.includes("bytes of memory") || )[0]
line.includes("bytes of physical memory") : PID + ":N/A:N/A";
) let RAM =
.join("<br>") showVersion
.match(regexMemory)[0] .filter(
) / (line) =>
1024 / line.includes("bytes of memory") ||
1024 line.includes("bytes of physical memory")
).toFixed(2) + )
"G (D: " + .join("<br>")
memDefaultForPID.split(":")[1] + .match(regexMemory) !== null
")"
: "";
let flash = showVersion
.filter((line) =>
line.toLocaleLowerCase().includes("compactflash")
)
.join("<br>");
listInformation.push({
PID: PID,
VID: VID,
SN: SN,
RAM: RAM,
flash:
flash.match(regexMemory) !== null
? ( ? (
parseInt(flash.match(regexMemory)[0]) / parseInt(
showVersion
.filter(
(line) =>
line.includes("bytes of memory") ||
line.includes(
"bytes of physical memory"
)
)
.join("<br>")
.match(regexMemory)[0]
) /
1024 / 1024 /
1024 1024
).toFixed(2) + ).toFixed(2) +
"G (D: " + "G (D: " +
memDefaultForPID.split(":")[2] + memDefaultForPID.split(":")[1] +
")" ")"
: "", : "";
extra_item: "no",
});
html += `<tr style='background-color:${backgroundColor}'><td>${PID}</td> let flash = showVersion
<td>${VID}</td> .filter((line) =>
<td>${SN}</td> line.toLocaleLowerCase().includes("compactflash")
<td>${RAM}</td> )
<td>${ .join("<br>");
flash.match(regexMemory) !== null listInformation.push({
? ( PID: PID,
parseInt(flash.match(regexMemory)[0]) / VID: VID,
1024 / SN: SN,
1024 RAM: RAM,
).toFixed(2) + flash:
"G (D: " + flash.match(regexMemory) !== null
memDefaultForPID.split(":")[2] + ? (
")" parseInt(flash.match(regexMemory)[0]) /
: "" 1024 /
}</td> 1024
<td>no</td></tr>`; ).toFixed(2) +
"G (D: " +
memDefaultForPID.split(":")[2] +
")"
: "",
extra_item: "no",
});
}
} }
} });
}); } else {
} else { //show version not exists --> RAM = N/A, Flash = N/A
//show version not exists --> RAM = N/A, Flash = N/A showInventoryContent.map((u, index) => {
showInventoryContent.map((u, index) => { const PID = u
const PID = u ?.split("VID:")[0]
?.split("VID:")[0] ?.split("PID:")[1]
?.split("PID:")[1] ?.replace(/,/g, "")
?.replace(/,/g, "") .trim();
.trim(); const VID = u
const VID = u ?.split("VID:")[1]
?.split("VID:")[1] ?.split("SN:")[0]
?.split("SN:")[0] ?.replace(/,/g, "")
?.replace(/,/g, "") .trim();
.trim(); const SN = u?.split("SN:")[1]?.replace(/,/g, "").trim();
const SN = u?.split("SN:")[1]?.replace(/,/g, "").trim();
if (index > 0) { if (index > 0) {
if (PID !== "" && SN !== "") { if (PID !== "" && SN !== "") {
listInformation.push({ listInformation.push({
PID: PID, PID: PID,
VID: VID, VID: VID,
SN: SN, SN: SN,
RAM: "", RAM: "",
flash: "", flash: "",
extra_item: "yes", extra_item: "yes",
}); });
}
html += `<tr><td>${PID}</td> } else {
<td>${VID}</td> if (PID !== "" && SN !== "") {
<td>${SN}</td> listInformation.push({
<td></td> PID: PID,
<td></td> VID: VID,
<td>yes</td></tr>`; SN: SN,
RAM: "",
flash: "",
extra_item: "no",
});
}
} }
} else { });
if (PID !== "" && SN !== "") { }
listInformation.push({ });
PID: PID, }
VID: VID, resolve(0);
SN: SN,
RAM: "",
flash: "",
extra_item: "no",
});
html += `<tr style='background-color:${backgroundColor}'><td>${PID}</td>
<td>${VID}</td>
<td>${SN}</td>
<td></td>
<td></td>
<td>no</td></tr>`;
}
}
});
}
});
} }
} );
); });
}); });
setTimeout(async () => { await Promise.all(filePromises);
if (listInformation.length > 0) { let specialModel = allKeyValue
console.log(listInformation); .filter((i) => i.key === "MODEL_SPECIAL")
const options = { .map((obj) => obj.$attributes.value);
from: "admin@apactech.io", listInformation = listInformation.filter(
to: "joseph@apactech.io, ips@ipsupply.com.au", (i) =>
subject: "(AUTO-REPORT) SERIAL NUMBER", i.RAM !== "" ||
html: i.flash !== "" ||
"<table border='1'>\ specialModel.filter((m) => i.PID.includes(m)).length > 0
);
if (listInformation.length > 0) {
console.log(listInformation);
listInformation.map((inf) => {
html += `<tr><td>${inf.PID}</td>
<td>${inf.VID}</td>
<td>${inf.SN}</td>
<td>${inf.RAM}</td>
<td>${inf.flash}</td>
<td>${inf.extra_item}</td></tr>`;
});
const options = {
from: "admin@apactech.io",
// to: "joseph@apactech.io, ips@ipsupply.com.au",
to: "joseph@apactech.io",
subject: "(AUTO-REPORT) SERIAL NUMBER",
html:
"<table border='1'>\
<thead>\ <thead>\
<tr>\ <tr>\
<th>PID</th>\ <th>PID</th>\
@ -343,15 +328,26 @@ export const sendDeviceInfora = async () => {
</tr>\ </tr>\
</thead>\ </thead>\
<tbody>" + <tbody>" +
html + html +
"</tbody>\ "</tbody>\
</table>", </table>",
}; };
transporter.sendMail(options); transporter.sendMail(options);
await InfoDevice.createMany(listInformation);
const fileName =
"./app/store/logsAPI/" +
moment(Date.now()).format("DD_MM_YYYY").toString() +
".log";
await InfoDevice.createMany(listInformation); addLogFunction(
} fileName,
}, 5000); JSON.stringify(listInformation[0], null, 2),
"Get-Send devices info"
);
} else {
console.log("listInformation", listInformation);
}
} catch (error) { } catch (error) {
console.log(error); console.log(error);
} }

File diff suppressed because it is too large Load Diff

109
package-lock.json generated
View File

@ -17,6 +17,7 @@
"axios": "^1.4.0", "axios": "^1.4.0",
"child_process": "^1.0.2", "child_process": "^1.0.2",
"chokidar": "^3.5.3", "chokidar": "^3.5.3",
"crypto": "^1.0.1",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"fs": "^0.0.1-security", "fs": "^0.0.1-security",
"helpers": "^0.0.6", "helpers": "^0.0.6",
@ -1366,9 +1367,9 @@
"dev": true "dev": true
}, },
"node_modules/@types/node": { "node_modules/@types/node": {
"version": "20.7.1", "version": "20.8.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.7.1.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.2.tgz",
"integrity": "sha512-LT+OIXpp2kj4E2S/p91BMe+VgGX2+lfO+XTpfXhh+bCk2LkQtHZSub8ewFBMGP5ClysPjTDFa4sMI8Q3n4T0wg==" "integrity": "sha512-Vvycsc9FQdwhxE3y3DzeIxuEJbWGDsnrxvMADzTDF/lcdR9/K+AQIeAghTQsHtotg/q0j3WEOYS/jQgSdWue3w=="
}, },
"node_modules/@types/pino": { "node_modules/@types/pino": {
"version": "6.3.12", "version": "6.3.12",
@ -2860,6 +2861,12 @@
"node": "*" "node": "*"
} }
}, },
"node_modules/crypto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/crypto/-/crypto-1.0.1.tgz",
"integrity": "sha512-VxBKmeNcqQdiUQUW2Tzq0t377b54N2bMtXO/qiLa+6eRRmmC4qT3D4OnTGoT/U6O9aklQ/jTwbOtRMTTY8G0Ig==",
"deprecated": "This package is no longer supported. It's now a built-in Node module. If you've depended on crypto, you should switch to the one that's built-in."
},
"node_modules/cuid": { "node_modules/cuid": {
"version": "2.1.8", "version": "2.1.8",
"resolved": "https://registry.npmjs.org/cuid/-/cuid-2.1.8.tgz", "resolved": "https://registry.npmjs.org/cuid/-/cuid-2.1.8.tgz",
@ -2873,9 +2880,9 @@
"dev": true "dev": true
}, },
"node_modules/data-uri-to-buffer": { "node_modules/data-uri-to-buffer": {
"version": "5.0.1", "version": "6.0.1",
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-5.0.1.tgz", "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.1.tgz",
"integrity": "sha512-a9l6T1qqDogvvnw0nKlfZzqsyikEBZBClF39V3TFoKhDtGBqHu2HkuomJc02j5zft8zrUaXEuoicLeW54RkzPg==", "integrity": "sha512-MZd3VlchQkp8rdend6vrx7MmVDJzSNTBvghvKjirLkD+WTChA3KUf0jkE68Q4UyctNqI11zZO9/x2Yx+ub5Cvg==",
"engines": { "engines": {
"node": ">= 14" "node": ">= 14"
} }
@ -4121,12 +4128,12 @@
} }
}, },
"node_modules/get-uri": { "node_modules/get-uri": {
"version": "6.0.1", "version": "6.0.2",
"resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.1.tgz", "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.2.tgz",
"integrity": "sha512-7ZqONUVqaabogsYNWlYj0t3YZaL6dhuEueZXGF+/YVmf6dHmaFg8/6psJKqhx9QykIDKzpGcy2cn4oV4YC7V/Q==", "integrity": "sha512-5KLucCJobh8vBY1K07EFV4+cPZH3mrV9YeAruUseCQKHB58SGjjT2l9/eA9LD082IiuMjSlFJEcdJ27TXvbZNw==",
"dependencies": { "dependencies": {
"basic-ftp": "^5.0.2", "basic-ftp": "^5.0.2",
"data-uri-to-buffer": "^5.0.1", "data-uri-to-buffer": "^6.0.0",
"debug": "^4.3.4", "debug": "^4.3.4",
"fs-extra": "^8.1.0" "fs-extra": "^8.1.0"
}, },
@ -4427,12 +4434,9 @@
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="
}, },
"node_modules/has": { "node_modules/has": {
"version": "1.0.3", "version": "1.0.4",
"resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz",
"integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==",
"dependencies": {
"function-bind": "^1.1.1"
},
"engines": { "engines": {
"node": ">= 0.4.0" "node": ">= 0.4.0"
} }
@ -6370,9 +6374,12 @@
} }
}, },
"node_modules/on-exit-leak-free": { "node_modules/on-exit-leak-free": {
"version": "2.1.0", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.0.tgz", "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
"integrity": "sha512-VuCaZZAjReZ3vUwgOB8LxAosIurDiAW0s13rI1YwmaP++jvcxP77AWoQvenZebpCA2m8WC1/EosPYPMjnRAp/w==" "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==",
"engines": {
"node": ">=14.0.0"
}
}, },
"node_modules/on-finished": { "node_modules/on-finished": {
"version": "2.4.1", "version": "2.4.1",
@ -6847,9 +6854,9 @@
} }
}, },
"node_modules/pino-pretty": { "node_modules/pino-pretty": {
"version": "10.2.0", "version": "10.2.2",
"resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.2.0.tgz", "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.2.2.tgz",
"integrity": "sha512-tRvpyEmGtc2D+Lr3FulIZ+R1baggQ4S3xD2Ar93KixFEDx6SEAUP3W5aYuEw1C73d6ROrNcB2IXLteW8itlwhA==", "integrity": "sha512-RvAdCQAU51MdVsJdvXX4Bipb52wwldXtOzlva1NT8q2d7tmgYWFIMLhoSnfx2Sr+Hi7BLGpR/n8wgrcq5G/ykA==",
"dependencies": { "dependencies": {
"colorette": "^2.0.7", "colorette": "^2.0.7",
"dateformat": "^4.6.3", "dateformat": "^4.6.3",
@ -6871,9 +6878,9 @@
} }
}, },
"node_modules/pino-pretty/node_modules/sonic-boom": { "node_modules/pino-pretty/node_modules/sonic-boom": {
"version": "3.4.0", "version": "3.5.0",
"resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.4.0.tgz", "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.5.0.tgz",
"integrity": "sha512-zSe9QQW30nPzjkSJ0glFQO5T9lHsk39tz+2bAAwCj8CNgEG8ItZiX7Wb2ZgA8I04dwRGCcf1m3ABJa8AYm12Fw==", "integrity": "sha512-02A0wEmj4d3aEIW/Sp6LMP1dNcG5cYmQPjhgtytIXa9tNmFZx3ragUPFmyBdgdM0yJJVSWwlLLEVHgrYfA0wtQ==",
"dependencies": { "dependencies": {
"atomic-sleep": "^1.0.0" "atomic-sleep": "^1.0.0"
} }
@ -10369,9 +10376,9 @@
"dev": true "dev": true
}, },
"@types/node": { "@types/node": {
"version": "20.7.1", "version": "20.8.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.7.1.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.2.tgz",
"integrity": "sha512-LT+OIXpp2kj4E2S/p91BMe+VgGX2+lfO+XTpfXhh+bCk2LkQtHZSub8ewFBMGP5ClysPjTDFa4sMI8Q3n4T0wg==" "integrity": "sha512-Vvycsc9FQdwhxE3y3DzeIxuEJbWGDsnrxvMADzTDF/lcdR9/K+AQIeAghTQsHtotg/q0j3WEOYS/jQgSdWue3w=="
}, },
"@types/pino": { "@types/pino": {
"version": "6.3.12", "version": "6.3.12",
@ -11520,6 +11527,11 @@
"integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==", "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==",
"dev": true "dev": true
}, },
"crypto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/crypto/-/crypto-1.0.1.tgz",
"integrity": "sha512-VxBKmeNcqQdiUQUW2Tzq0t377b54N2bMtXO/qiLa+6eRRmmC4qT3D4OnTGoT/U6O9aklQ/jTwbOtRMTTY8G0Ig=="
},
"cuid": { "cuid": {
"version": "2.1.8", "version": "2.1.8",
"resolved": "https://registry.npmjs.org/cuid/-/cuid-2.1.8.tgz", "resolved": "https://registry.npmjs.org/cuid/-/cuid-2.1.8.tgz",
@ -11532,9 +11544,9 @@
"dev": true "dev": true
}, },
"data-uri-to-buffer": { "data-uri-to-buffer": {
"version": "5.0.1", "version": "6.0.1",
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-5.0.1.tgz", "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.1.tgz",
"integrity": "sha512-a9l6T1qqDogvvnw0nKlfZzqsyikEBZBClF39V3TFoKhDtGBqHu2HkuomJc02j5zft8zrUaXEuoicLeW54RkzPg==" "integrity": "sha512-MZd3VlchQkp8rdend6vrx7MmVDJzSNTBvghvKjirLkD+WTChA3KUf0jkE68Q4UyctNqI11zZO9/x2Yx+ub5Cvg=="
}, },
"dateformat": { "dateformat": {
"version": "4.6.3", "version": "4.6.3",
@ -12487,12 +12499,12 @@
"dev": true "dev": true
}, },
"get-uri": { "get-uri": {
"version": "6.0.1", "version": "6.0.2",
"resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.1.tgz", "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.2.tgz",
"integrity": "sha512-7ZqONUVqaabogsYNWlYj0t3YZaL6dhuEueZXGF+/YVmf6dHmaFg8/6psJKqhx9QykIDKzpGcy2cn4oV4YC7V/Q==", "integrity": "sha512-5KLucCJobh8vBY1K07EFV4+cPZH3mrV9YeAruUseCQKHB58SGjjT2l9/eA9LD082IiuMjSlFJEcdJ27TXvbZNw==",
"requires": { "requires": {
"basic-ftp": "^5.0.2", "basic-ftp": "^5.0.2",
"data-uri-to-buffer": "^5.0.1", "data-uri-to-buffer": "^6.0.0",
"debug": "^4.3.4", "debug": "^4.3.4",
"fs-extra": "^8.1.0" "fs-extra": "^8.1.0"
}, },
@ -12742,12 +12754,9 @@
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="
}, },
"has": { "has": {
"version": "1.0.3", "version": "1.0.4",
"resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz",
"integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ=="
"requires": {
"function-bind": "^1.1.1"
}
}, },
"has-ansi": { "has-ansi": {
"version": "2.0.0", "version": "2.0.0",
@ -14214,9 +14223,9 @@
} }
}, },
"on-exit-leak-free": { "on-exit-leak-free": {
"version": "2.1.0", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.0.tgz", "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
"integrity": "sha512-VuCaZZAjReZ3vUwgOB8LxAosIurDiAW0s13rI1YwmaP++jvcxP77AWoQvenZebpCA2m8WC1/EosPYPMjnRAp/w==" "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="
}, },
"on-finished": { "on-finished": {
"version": "2.4.1", "version": "2.4.1",
@ -14594,9 +14603,9 @@
} }
}, },
"pino-pretty": { "pino-pretty": {
"version": "10.2.0", "version": "10.2.2",
"resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.2.0.tgz", "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.2.2.tgz",
"integrity": "sha512-tRvpyEmGtc2D+Lr3FulIZ+R1baggQ4S3xD2Ar93KixFEDx6SEAUP3W5aYuEw1C73d6ROrNcB2IXLteW8itlwhA==", "integrity": "sha512-RvAdCQAU51MdVsJdvXX4Bipb52wwldXtOzlva1NT8q2d7tmgYWFIMLhoSnfx2Sr+Hi7BLGpR/n8wgrcq5G/ykA==",
"requires": { "requires": {
"colorette": "^2.0.7", "colorette": "^2.0.7",
"dateformat": "^4.6.3", "dateformat": "^4.6.3",
@ -14615,9 +14624,9 @@
}, },
"dependencies": { "dependencies": {
"sonic-boom": { "sonic-boom": {
"version": "3.4.0", "version": "3.5.0",
"resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.4.0.tgz", "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.5.0.tgz",
"integrity": "sha512-zSe9QQW30nPzjkSJ0glFQO5T9lHsk39tz+2bAAwCj8CNgEG8ItZiX7Wb2ZgA8I04dwRGCcf1m3ABJa8AYm12Fw==", "integrity": "sha512-02A0wEmj4d3aEIW/Sp6LMP1dNcG5cYmQPjhgtytIXa9tNmFZx3ragUPFmyBdgdM0yJJVSWwlLLEVHgrYfA0wtQ==",
"requires": { "requires": {
"atomic-sleep": "^1.0.0" "atomic-sleep": "^1.0.0"
} }

View File

@ -30,6 +30,7 @@
"axios": "^1.4.0", "axios": "^1.4.0",
"child_process": "^1.0.2", "child_process": "^1.0.2",
"chokidar": "^3.5.3", "chokidar": "^3.5.3",
"crypto": "^1.0.1",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"fs": "^0.0.1-security", "fs": "^0.0.1-security",
"helpers": "^0.0.6", "helpers": "^0.0.6",

View File

@ -1,10 +1,39 @@
const regex = /(\d+)K/g; const axios = require('axios');
const md5 = require('md5');
console.log( // Tạo dữ liệu JSON bạn muốn gửi đi
"1000944K bytes of ATA System CompactFlash 0 (Read/Write) " const dataToSend = {
.match(regex) // Đặt dữ liệu của bạn ở đây
.map((obj) => (parseInt(obj.replace("K", ""))/1024/1024).toFixed(2)+"G") };
);
// Tạo tiêu đề
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'loginid': null,
'Code': 'chuoi ngau nhiên',
'AccessToken': md5(Code + '24feca0508b52d34b51db4b40964e7fff12edf71208a4607126f75cb5d504f7f')
};
// Gửi POST request bằng Axios
axios.post('https://disti.danielvu.com/api/sendBuyerOrderToERP', dataToSend, { headers })
.then(response => {
// Xử lý response ở đây
console.log('Response:', response.data);
})
.catch(error => {
// Xử lý lỗi ở đây
console.error('Error:', error);
});
// const regex = /(\d+)K/g;
// console.log(
// "1000944K bytes of ATA System CompactFlash 0 (Read/Write) "
// .match(regex)
// .map((obj) => (parseInt(obj.replace("K", ""))/1024/1024).toFixed(2)+"G")
// );
// let a = [1,2,3] // let a = [1,2,3]

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

299
start/routes.ts Normal file
View File

@ -0,0 +1,299 @@
import axios from "axios";
/*
|--------------------------------------------------------------------------
| Routes
|--------------------------------------------------------------------------
|
| This file is dedicated for defining HTTP routes. A single file is enough
| for majority of projects, however you can define routes in different
| files and just make sure to import them inside this file. For example
|
| Define routes in following two files
| start/routes/cart.ts
| start/routes/customer.ts
|
| and then import them inside `start/routes.ts` as follows
|
| import './routes/cart'
| import './routes/customer'
|
*/
import Route from "@ioc:Adonis/Core/Route";
import { runtimeCheckLogs } from "App/utils/runtimeCheckLogs";
import Env from "@ioc:Adonis/Core/Env";
import { sendMessToZulip } from "App/utils/sendMessToZulip";
import moment from "moment";
import Product from "App/Models/Product";
import { sendDeviceInfora } from "App/utils/sendDeviceInfor";
runtimeCheckLogs(Env.get("FOLDER_LOGS"));
// setTimeout(async() => {
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// LogDetectFile.all()
// console.log("first")
// }, 2000);
//ERP get index serial number
Route.post("/api/getIndexSerialNumber", "ErpsController.getIndexSerialNumber")
.middleware("checkToken").middleware(
"writeLog"
);
// .middleware("writeLog");
Route.post("/api/getParagraph", "ErpsController.getParagraph")
.middleware("checkToken")
.middleware("writeLog")
//Users
Route.post("/api/account/createUser", "UsersController.create").middleware(
"writeLog"
);
Route.post("/api/account/checkLogin", "UsersController.checkLogin").middleware(
"writeLog"
);
//Log
Route.get("/api/log/showLog/:name?", "LogsController.showLog").middleware(
"writeLog"
);
Route.get("/api/getAllLogDetect", "LogsController.getAllLogDetect")
//Key-Value
Route.post("/api/getKeyValue", "ValuesController.getKeyValue")
Route.post("/api/deleteValue", "ValuesController.destroy").middleware(
"writeLog"
);
Route.post("/api/editValue", "ValuesController.edit").middleware(
"writeLog"
);
Route.post("/api/addValue", "ValuesController.create").middleware("writeLog");
Route.post("/api/backupProduct", async ({ request, response }) => {
try {
const date = moment(Date.now()).format("YYYYMMDD");
const res = await axios.post(
"https://logs.danielvu.com/api/getIndexSerialNumber",
{ from: date, to: date },
{
headers: {
Authorization: request.headers().authorization?.replace(/"/g, ""),
},
}
);
res.data.map((obj, index) => {
res.data[index] = {
PID: res.data[index].PID,
SN: res.data[index].SN,
VID: res.data[index].VID,
line: res.data[index].line.join(","),
file: res.data[index].fileName,
warehouse: res.data[index].warehouse,
};
});
const addProduct = await Product.createMany(res.data);
// console.log(addProduct)
response.status(200).send("Add " + res.data.length + " success!");
await sendMessToZulip(
"stream",
"networkToolBot",
"Log service",
"Backup product " +
date +
" success with " +
res.data.length +
" products"
);
} catch (error) {
response.status(500).send(error);
await sendMessToZulip(
"stream",
"networkToolBot",
"Log service",
"Backup product fail. Please check!"
);
}
}).middleware("writeLog");
Route.post("/api/sendMailInforDevice", async () => {
try {
sendDeviceInfora()
} catch (error) {
console.log(error)
}
}).middleware("checkToken").middleware(
"writeLog"
);