Update function sendDeviceInfor to mail

This commit is contained in:
joseph le 2023-10-10 10:26:00 +07:00
parent ca18146b23
commit 297ca11585
4 changed files with 355 additions and 224 deletions

34
app/Models/InfoDevice.ts Normal file
View File

@ -0,0 +1,34 @@
import { DateTime } from 'luxon'
import { BaseModel, column } from '@ioc:Adonis/Lucid/Orm'
export default class InfoDevice extends BaseModel {
public static table = 'info_devices'
@column({ isPrimary: true })
public id_info: number
@column()
public PID: string
@column()
public SN: string
@column()
public VID: string
@column()
public RAM: string
@column()
public flash: string
@column()
public extraItem: string
@column.dateTime({ autoCreate: true })
public created_at: DateTime
@column.dateTime({ autoCreate: true, autoUpdate: true })
public updated_at: DateTime
}

View File

@ -11,6 +11,9 @@ export default class LogDetectFile extends BaseModel {
@column() @column()
public file_name: string public file_name: string
@column()
public last_check_SN: number
@column.dateTime({ autoCreate: true }) @column.dateTime({ autoCreate: true })
public created_at: DateTime public created_at: DateTime

View File

@ -3,6 +3,9 @@ import fs from "fs";
import moment from "moment/moment"; import moment from "moment/moment";
import dotenv from "dotenv"; import dotenv from "dotenv";
import nodeMailer from "nodemailer"; import nodeMailer from "nodemailer";
import LogDetectFile from "App/Models/LogDetectFile";
import InfoDevice from "App/Models/InfoDevice";
import KeyValue from "App/Models/KeyValue";
dotenv.config(); dotenv.config();
export const sendDeviceInfora = async () => { export const sendDeviceInfora = async () => {
@ -13,11 +16,16 @@ 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())
.filter((i) => i.$attributes.key === "MEMORY_DEFAULT")
.map((obj) => obj.$attributes.value);
const listInformation = []; const listInformation = [];
let dataFile = await LogDetectFile.all();
// console.log(dataFile)
// console.log(dataFile)
let html = ""; let html = "";
//List file today //List file today
const listFile = fs const listFile = fs.readdirSync(Env.get("FOLDER_LOGS"));
.readdirSync(Env.get("FOLDER_LOGS"))
//Configure mail //Configure mail
const transporter = nodeMailer.createTransport({ const transporter = nodeMailer.createTransport({
@ -32,179 +40,236 @@ export const sendDeviceInfora = async () => {
}); });
//Read file in listFile //Read file in listFile
await listFile.map((file) => { await listFile.map(async (file) => {
fs.readFile(Env.get("FOLDER_LOGS") + "/" + file, "utf8", (err, data) => { fs.readFile(
if (err) { Env.get("FOLDER_LOGS") + "/" + file,
console.log(`Error reading file: ${err}`); "utf8",
} else { async (err, data) => {
//Array line if (err) {
const lines = data?.split("\n"); console.log(`Error reading file: ${err}`);
const linesInventory = []; } else {
//Get index of "lines" with show inv //Array line
lines?.map((line, index) => { const lines = data?.split("\n");
if (line.match(regexInventory) !== null) { const linesInventory = [];
linesInventory.push(index); let DBFileCheck = dataFile.filter(
} (i) => i.$attributes.file_name === file
}); )[0];
// console.log(linesInventory); if (DBFileCheck !== undefined) {
//cut content with content1 = [linesInventory[index],linesInventory[index+1]] ... if (lines.length > DBFileCheck?.$extras.last_check_SN) {
linesInventory?.map((line, index) => { const DBFile = await LogDetectFile.find(
const deviceContent = lines?.slice( DBFileCheck?.$attributes.id_ldf
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 // console.log(DBFile)
while (check === true) {
if ( DBFile.last_check_SN = lines.length;
deviceContent await DBFile.save();
.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;
} }
} } else {
await LogDetectFile.firstOrCreate(
const showInventoryContent = showInventory { file_name: file },
.join("\n") { file_name: file }
.split("\n")
.filter(
(i) =>
i.includes("PID:") && i.includes("VID:") && i.includes("SN:")
); );
//show version exists dataFile = await LogDetectFile.all();
if ( DBFileCheck = dataFile.filter(
deviceContent.filter((line) => line.match(regexVersion) !== null) (i) => i.$attributes.file_name === file
.length > 0 )[0];
) { }
const lineShowver = deviceContent.indexOf(
//Get index of "lines" with show inv
lines
?.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;
} 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 !== "") {
// let RAM =
// showVersion
// .filter((line) => line.includes("bytes of memory"))
// .join("<br>")
// .match(regexMemory) !== null
// ? (
// parseInt(
// showVersion
// .filter((line) =>
// line.includes("bytes of memory")
// )
// .join("<br>")
// .match(regexMemory)[0]
// ) /
// 1024 /
// 1024
// ).toFixed(2) + "G"
// : "";
// let flash = showVersion showInventoryContent.map((u, index) => {
// .filter((line) => const PID = u
// line.toLocaleLowerCase().includes("compactflash") ?.split("VID:")[0]
// ) ?.split("PID:")[1]
// .join("<br>"); ?.replace(/,/g, "")
listInformation.push({ .trim();
PID: PID, const VID = u
VID: VID, ?.split("VID:")[1]
SN: SN, ?.split("SN:")[0]
RAM: "", ?.replace(/,/g, "")
flash: "", .trim();
extraItem: "yes", const SN = u?.split("SN:")[1]?.replace(/,/g, "").trim();
}); // let memory =
if (index > 0) {
if (PID !== "" && SN !== "") {
// let RAM =
// showVersion
// .filter((line) => line.includes("bytes of memory"))
// .join("<br>")
// .match(regexMemory) !== null
// ? (
// parseInt(
// showVersion
// .filter((line) =>
// line.includes("bytes of memory")
// )
// .join("<br>")
// .match(regexMemory)[0]
// ) /
// 1024 /
// 1024
// ).toFixed(2) + "G"
// : "";
html += `<tr><td>${PID}</td> // let flash = showVersion
// .filter((line) =>
// line.toLocaleLowerCase().includes("compactflash")
// )
// .join("<br>");
listInformation.push({
PID: PID,
VID: VID,
SN: SN,
RAM: "",
flash: "",
extra_item: "yes",
});
html += `<tr><td>${PID}</td>
<td>${VID}</td> <td>${VID}</td>
<td>${SN}</td> <td>${SN}</td>
<td></td> <td></td>
<td></td> <td></td>
<td>yes</td></tr>`; <td>yes</td></tr>`;
} }
} else { } else {
if (PID !== "" && SN !== "") { if (PID !== "" && SN !== "") {
let RAM = const memDefaultForPID =
showVersion memDefault.filter((i) =>
.filter((line) => line.includes("bytes of memory") || line.includes("bytes of physical memory")) PID.includes(i.split(":")[0])
.join("<br>") )[0] !== undefined
.match(regexMemory) !== null ? memDefault.filter((i) =>
? ( PID.includes(i.split(":")[0])
parseInt( )[0]
showVersion : PID + ":N/A:N/A";
.filter((line) => let RAM =
line.includes("bytes of memory") || line.includes("bytes of physical memory") showVersion
) .filter(
.join("<br>") (line) =>
.match(regexMemory)[0] line.includes("bytes of memory") ||
) / line.includes("bytes of physical memory")
1024 / )
1024 .join("<br>")
).toFixed(2) + "G" .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) + "G" ).toFixed(2) +
: "", "G (D: " +
extraItem: "no", memDefaultForPID.split(":")[1] +
}); ")"
: "";
html += `<tr style='background-color:${backgroundColor}'><td>${PID}</td> 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]) /
1024 /
1024
).toFixed(2) +
"G (D: " +
memDefaultForPID.split(":")[2] +
")"
: "",
extra_item: "no",
});
html += `<tr style='background-color:${backgroundColor}'><td>${PID}</td>
<td>${VID}</td> <td>${VID}</td>
<td>${SN}</td> <td>${SN}</td>
<td>${RAM}</td> <td>${RAM}</td>
@ -214,96 +279,104 @@ export const sendDeviceInfora = async () => {
parseInt(flash.match(regexMemory)[0]) / parseInt(flash.match(regexMemory)[0]) /
1024 / 1024 /
1024 1024
).toFixed(2) + "G" ).toFixed(2) +
"G (D: " +
memDefaultForPID.split(":")[2] +
")"
: "" : ""
}</td> }</td>
<td>no</td></tr>`; <td>no</td></tr>`;
}
} }
} });
}); } 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: "",
extraItem: "yes", extra_item: "yes",
}); });
html += `<tr><td>${PID}</td> html += `<tr><td>${PID}</td>
<td>${VID}</td> <td>${VID}</td>
<td>${SN}</td> <td>${SN}</td>
<td></td> <td></td>
<td></td> <td></td>
<td>yes</td></tr>`; <td>yes</td></tr>`;
} }
} else { } else {
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: "",
extraItem: "no", extra_item: "no",
}); });
html += `<tr style='background-color:${backgroundColor}'><td>${PID}</td> html += `<tr style='background-color:${backgroundColor}'><td>${PID}</td>
<td>${VID}</td> <td>${VID}</td>
<td>${SN}</td> <td>${SN}</td>
<td></td> <td></td>
<td></td> <td></td>
<td>no</td></tr>`; <td>no</td></tr>`;
}
} }
} });
}); }
} });
}); }
} }
}); );
}); });
setTimeout(() => { setTimeout(async () => {
console.log(listInformation); if (listInformation.length > 0) {
const options = { console.log(listInformation);
from: "admin@apactech.io", const options = {
to: "joseph@apactech.io", from: "admin@apactech.io",
subject: "SN AUTO REPORT", to: "joseph@apactech.io",
html: subject: "SN AUTO REPORT",
"<table border='1'>\ html:
<thead>\ "<table border='1'>\
<tr>\ <thead>\
<th>PID</th>\ <tr>\
<th>VID</th>\ <th>PID</th>\
<th>SN</th>\ <th>VID</th>\
<th>RAM</th>\ <th>SN</th>\
<th>Flash</th>\ <th>RAM</th>\
<th>Extra Item</th>\ <th>Flash</th>\
</tr>\ <th>Extra Item</th>\
</thead>\ </tr>\
<tbody>" + </thead>\
html + <tbody>" +
"</tbody>\ html +
</table>", "</tbody>\
}; </table>",
transporter.sendMail(options); };
transporter.sendMail(options);
await InfoDevice.createMany(listInformation);
}
}, 5000); }, 5000);
// const match = "show inventory".match(regexInventory); // const match = "show inventory".match(regexInventory);

View File

@ -0,0 +1,21 @@
import BaseSchema from '@ioc:Adonis/Lucid/Schema'
export default class extends BaseSchema {
protected tableName = 'info_devices'
public async up () {
this.schema.createTable(this.tableName, (table) => {
table.increments('id')
/**
* Uses timestamptz for PostgreSQL and DATETIME2 for MSSQL
*/
table.timestamp('created_at', { useTz: true })
table.timestamp('updated_at', { useTz: true })
})
}
public async down () {
this.schema.dropTable(this.tableName)
}
}