Merge branch 'main' into develop

This commit is contained in:
joseph le 2023-10-10 14:19:13 +07:00
commit 2d87d391bb
55 changed files with 5789 additions and 3566 deletions

1
.gitignore vendored
View File

@ -5,4 +5,5 @@ coverage
.DS_STORE
.env
app/utils/indexSN.txt
app/store
tmp

View File

@ -18,10 +18,23 @@ export default class ErpsController {
// console.log("check!")
const listLog: string[] = [];
const response = await axios.get("http://192.168.5.7:8080/");
const data = response.data;
const arrayLine = data
const responseAUTO = await axios.get(
"http://192.168.5.7:8080/AUTOlog/"
);
let data1 = response.data
.split("\n")
.filter((i) => i.search("<a href") !== -1 && i.search(".log") !== -1);
let data2 = responseAUTO.data
.split("\n")
.filter((i) => i.search("<a href") !== -1 && i.search(".log") !== -1);
const arrayLine = data1.concat(data2);
// const arrayLineAUTO = data
// .split("\n")
// .filter((i) => i.search("<a href") !== -1 && i.search(".log") !== -1);
arrayLine.map((u) => {
let temp = u
.slice(u.search("<a ") + 9, u.search("</a>"))
@ -32,7 +45,12 @@ export default class ErpsController {
parseInt(temp?.split("-")[0]) <= to
) {
listLog.push(
"http://192.168.5.7:8080/" +
(u
.slice(u.search("<a ") + 9, u.search("</a>"))
.split(">")[1]
.includes("AUTO")
? "http://192.168.5.7:8080/AUTOlog/"
: "http://192.168.5.7:8080/") +
u.slice(u.search("<a ") + 9, u.search("</a>")).split(">")[1] +
" "
);
@ -91,7 +109,7 @@ export default class ErpsController {
?.split(":")[1]
?.replace("\r", "")
.trim() !== "" &&
SN !== "N/A"
SN !== "N/A" && SN.length>4
) {
if (output.some((u) => u.SN === SN)) {
output.map((u, index) => {
@ -153,9 +171,10 @@ export default class ErpsController {
line: [i + 1],
fileName: fName,
warehouse:
fName.search("-US") !== -1 ||
fName.search(".US") !== -1 ||
fName.search("US-") !== -1
(fName.search("-US") !== -1 ||
fName.search(".US") !== -1 ||
fName.search("US-") !== -1) &&
fName.search("AUS") === -1
? "US"
: "AU",
});
@ -164,7 +183,8 @@ export default class ErpsController {
if (arrayLine[i].search("Serial Number") !== -1) {
let PCB_SN = arrayLine[i]
?.split("Serial Number")[1].split(":")[1]
?.split("Serial Number")[1]
.split(":")[1]
?.replace("\r", "")
.trim()
.replace(/[!@#$%^&*()_+{}\[\]:;<>,.?~\\/]/g, "");
@ -196,9 +216,10 @@ export default class ErpsController {
line: [i + 1],
fileName: fName,
warehouse:
fName.search("-US") !== -1 ||
fName.search(".US") !== -1 ||
fName.search("US-") !== -1
(fName.search("-US") !== -1 ||
fName.search(".US") !== -1 ||
fName.search("US-") !== -1) &&
fName.search("AUS") === -1
? "US"
: "AU",
});
@ -222,25 +243,24 @@ export default class ErpsController {
}
});
} else {
if (
PBID?.length >= 8
) {
let fName = urls[index]
?.split("/")
[urls[index]?.split("/")?.length - 1]?.trim();
output.push({
PID: "",
VID: "",
SN: PBID?.search(" ") !== -1 ? PBID?.split(" ")[0] : PBID,
line: [i + 1],
fileName: fName,
warehouse:
fName.search("-US") !== -1 ||
fName.search(".US") !== -1 ||
fName.search("US-") !== -1
? "US"
: "AU",
});
if (PBID?.length >= 8) {
let fName = urls[index]
?.split("/")
[urls[index]?.split("/")?.length - 1]?.trim();
output.push({
PID: "",
VID: "",
SN: PBID?.search(" ") !== -1 ? PBID?.split(" ")[0] : PBID,
line: [i + 1],
fileName: fName,
warehouse:
(fName.search("-US") !== -1 ||
fName.search(".US") !== -1 ||
fName.search("US-") !== -1) &&
fName.search("AUS") === -1
? "US"
: "AU",
});
}
}
}
@ -262,7 +282,9 @@ export default class ErpsController {
}
);
// console.log(report);
return report.filter((i) => i.SN !== "" && /^[A-Z0-9-]{5,}$/.test(i.SN)===true);
return report.filter(
(i) => i.SN !== "" && /^[A-Z0-9-]{5,}$/.test(i.SN) === true && i.PID !==""
);
// }, 15000);
} catch (error) {
response
@ -285,9 +307,11 @@ export default class ErpsController {
const { fileName, line, range } = request.all();
try {
const res = await axios.get("http://192.168.5.7:8080/" + fileName);
let fName =
fileName.search("AUTO") !== -1 ? "AUTOlog/" + fileName : fileName;
const res = await axios.get("http://192.168.5.7:8080/" + fName);
const arrayLine = res?.data?.split("\n");
// console.log(arrayLine)
if (range >= line) {
response.status(200).json({
content: arrayLine?.slice(0, line + range)?.join("\n"),
@ -300,14 +324,12 @@ export default class ErpsController {
} catch (error) {
console.log(error);
response
.status(500)
.send({ mess: "GET CONTENT FILE FAIL", error: error });
.status(202)
.send({ mess: "FILE NOT FOUND", error: error });
}
}
public async store({request, response}: HttpContextContract) {
}
public async store({ request, response }: HttpContextContract) {}
public async show({}: HttpContextContract) {}

View File

@ -0,0 +1,115 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Database from '@ioc:Adonis/Lucid/Database';
import KeyValue from 'App/Models/KeyValue';
import LogDetectFile from 'App/Models/LogDetectFile';
import axios from 'axios';
export default class LogsController {
public async showLog({request, response}: HttpContextContract) {
try {
// fghf
console.log(request.params().name);
let fileDetect = await LogDetectFile.findBy(
"file_name",
request.params().name
);
let logsDetect = await Database.rawQuery(
"select * from log_reports where id_file = " + fileDetect?.id_ldf
);
let modelSpecialDetected = [];
let issueSpecialDetected = [];
let listLine = logsDetect[0]
.map((obj) => obj.line)
.filter((value, index, self) => {
return self.indexOf(value) === index;
})
.sort((a, b) => a - b);
const content = await axios.get(
request.params().name.search("AUTO") !== -1
? "http://192.168.5.7:8080/AUTOlog/" + request.params().name
: "http://192.168.5.7:8080/" + request.params().name
);
let allValue = await KeyValue.all();
let listKeyValues = allValue.filter(
(i) =>
i.$original.key === "MODEL_SPECIAL" ||
i.$original.key === "CATCH_FAULTY"
);
let MODEL_SPECIAL = allValue
.filter((i) => i.$original.key === "MODEL_SPECIAL")
.map((obj) => obj.$original.value);
let listExcludeErr = allValue
.filter((i) => i.$original.key === "EXCLUDE_ERR")
.map((obj) => obj.$original.value);
let data = content.data.split("\n");
data.map((line, index) => {
data[index] = index + 1 + "|-|" + line;
listKeyValues
.map((obj) => obj.$original.value)
.map(async (value) => {
if (
line.search(value) !== -1 &&
listExcludeErr.filter((err) => line.includes(err)).length === 0
) {
data[index] =
data[index].slice(0, data[index].search(value)) +
"|-|" +
value +
"|-|" +
data[index].slice(data[index].search(value) + value.length);
// }
}
});
});
listLine.map((u) => {
if (
listExcludeErr.filter((err) => data[u - 1].includes(err)).length === 0
) {
if (MODEL_SPECIAL.filter((i) => data[u - 1].includes(i)).length > 0) {
modelSpecialDetected.push(data[u - 1]);
} else {
issueSpecialDetected.push(data[u - 1]);
}
}
});
let modelSpecial =
modelSpecialDetected.length > 0 ? modelSpecialDetected.join("\n") : "";
let issueItem =
issueSpecialDetected.length > 0 ? issueSpecialDetected.join("\n") : "";
response.status(200).send({
modelSpecial: modelSpecial,
issueItem: issueItem,
contentFile: data.join("\n"),
});
} catch (error) {
// console.error(error);
response.status(203).send("FILE NOT FOUND");
}
}
public async getAllLogDetect({request, response}: HttpContextContract) {
try {
let fileDetect = await LogDetectFile.all();
let listFiles = fileDetect.map((obj) => obj.file_name);
response.status(200).send(listFiles);
} catch (error) {
response.status(203).send("NO FILE");
}
}
public async store({}: HttpContextContract) {}
public async show({}: HttpContextContract) {}
public async edit({}: HttpContextContract) {}
public async update({}: HttpContextContract) {}
public async destroy({}: HttpContextContract) {}
}

View File

@ -0,0 +1,49 @@
import type { HttpContextContract } from "@ioc:Adonis/Core/HttpContext";
import KeyValue from "App/Models/KeyValue";
export default class ValuesController {
public async getKeyValue({ request, response }: HttpContextContract) {
let data = await KeyValue.all();
response.status(200).send(data);
}
public async create({ request, response }: HttpContextContract) {
try {
const value = await KeyValue.create({
key: request.all().key,
value: request.all().value,
model: "All",
});
response.status(200).send("ADD VALUE SUCCESS!");
} catch (error) {
response.status(500).send("ADD VALUE FAIL!");
}
}
public async store({}: HttpContextContract) {}
public async show({}: HttpContextContract) {}
public async edit({ request, response }: HttpContextContract) {
try {
const value = await KeyValue.findOrFail(request.all().id);
value.value = request.all().value;
await value.save();
response.status(200).send("EDIT VALUE SUCCESS!");
} catch (error) {
response.status(500).send("EDIT VALUE FAIL!");
}
}
public async update({}: HttpContextContract) {}
public async destroy({ request, response }: HttpContextContract) {
try {
const value = await KeyValue.findOrFail(request.all().id);
await value.delete();
response.status(200).send("DELETE VALUE SUCCESS!");
} catch (error) {
response.status(500).send("DELETE VALUE FAIL!");
}
}
}

13
app/Middleware/Logger.ts Normal file
View File

@ -0,0 +1,13 @@
import type { HttpContextContract } from "@ioc:Adonis/Core/HttpContext";
import { loggerAPI } from "App/utils/Logger";
export default class Logger {
public async handle(
{ request, response }: HttpContextContract,
next: () => Promise<void>
) {
// code for middleware goes here. ABOVE THE NEXT CALL
await next();
loggerAPI(request, response, request.url())
}
}

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()
public file_name: string
@column()
public last_check_SN: number
@column.dateTime({ autoCreate: true })
public created_at: DateTime

28
app/Models/Product.ts Normal file
View File

@ -0,0 +1,28 @@
import { DateTime } from 'luxon'
import { BaseModel, column } from '@ioc:Adonis/Lucid/Orm'
export default class Product extends BaseModel {
@column({ isPrimary: true })
public id_pro: number
@column()
public PID: string
@column()
public SN: string
@column()
public VID: string
@column()
public line: string
@column()
public file: string
@column()
public warehouse: string
@column.dateTime({ autoCreate: true })
public created_at: DateTime
}

21
app/Services/Ws.ts Normal file
View File

@ -0,0 +1,21 @@
import { Server } from 'socket.io'
import AdonisServer from '@ioc:Adonis/Core/Server'
class Ws {
public io: Server
private booted = false
public boot() {
/**
* Ignore multiple calls to the boot method
*/
if (this.booted) {
return
}
this.booted = true
this.io = new Server(AdonisServer.instance!)
}
}
export default new Ws()

View File

@ -0,0 +1 @@
<h1>fjshdkf</h1>

View File

@ -1,26 +0,0 @@
fdgdfg
fksdfk trace ak
Power Failure
ERROR: % Incomplete command
ERROR: % Incomplete command
sdfhskd ERROR PVDM3- invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shjkg
sdfhskd ERROR PVDM3- invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shjkg
invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shjkg
invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shjkg
invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shjkg
invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shjkg
sdfhskd ERROR PVDM3- invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shjkg
invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shjkg
invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shjkg
invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shjkg
invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shjkg
invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shj
invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shj
invalid |IOSXE_RP_NV-3-NV_ACCESS_FAIL|IOSXE_RP_NV-3- shj pak_debug_init sdh
abc
123 PVDM3- hui 800G2-POE-2
anfasll ak shflks as klhfalk la EHWIC- fsjklfjkl
anfasll ak shflks as klhfalk la EHWIC- fsjklfjkl
anfasll ak shflks as klhfalk la EHWIC- fsjklfjkl
123 PVDM3- hui 800G2-POE-2
123 PVDM3- hui 800G2-POE-2

View File

@ -1,15 +0,0 @@
WS-X68
WS-X68
WS-X68
WS-X68
WS-X68
SM-
SM-
SM-
WS-X68
WS-X68
WS-X68
yellow
SM-
WS-X68
fksdfk trace ak

View File

@ -1,236 +0,0 @@
set_radius_extended_configsdf
set_radius_extended_configsdfsdf
fsdsdfsf
xe xich low
set_radius_extended_configsdfsdfdfhfg
fghgf
fghgfdfjgdfkjgerr
dfhkhjh
cong hoa xa hoi chu nghia
djgkdbsk
dfhjđhd
error
con co be begkklg
dhmkfhd
err
dfkbdfnlkbndflbd
trace
err
fault
err
trace
set_radius_extended_configsdfsdfdfhfg err
set_radius_extended_configsdf
set_radius_extended_configsdfsdf
fsdsdfsf
xe xich low
set_radius_extended_configsdfsdfdfhfg
fghgf
fghgfdfjgdfkjgerr
dfhkhjh
cong hoa xa hoi chu nghia
djgkdbsk
dfhjđhd
error
con co be begkklg
dhmkfhd
err
dfkbdfnlkbndflbd
trace
err
fault
err
trace
set_radius_extended_configsdfsdfdfhfg err
set_radius_extended_configsdf
set_radius_extended_configsdfsdf
fsdsdfsf
xe xich low
set_radius_extended_configsdfsdfdfhfg
fghgf
fghgfdfjgdfkjgerr
dfhkhjh
cong hoa xa hoi chu nghia
djgkdbsk
dfhjđhd
error
con co be begkklg
dhmkfhd
err
dfkbdfnlkbndflbd
trace
err
fault
err
trace
set_radius_extended_configsdfsdfdfhfg err
set_radius_extended_configsdf
set_radius_extended_configsdfsdf
fsdsdfsf
xe xich low
set_radius_extended_configsdfsdfdfhfg
fghgf
fghgfdfjgdfkjgerr
dfhkhjh
cong hoa xa hoi chu nghia
djgkdbsk
dfhjđhd
error
con co be begkklg
dhmkfhd
err
dfkbdfnlkbndflbd
trace
err
fault
err
trace
set_radius_extended_configsdfsdfdfhfg err
set_radius_extended_configsdf
set_radius_extended_configsdfsdf
fsdsdfsf
xe xich low
set_radius_extended_configsdfsdfdfhfg
fghgf
fghgfdfjgdfkjgerr
dfhkhjh
cong hoa xa hoi chu nghia
djgkdbsk
dfhjđhd
error
con co be begkklg
dhmkfhd
err
dfkbdfnlkbndflbd
trace
err
fault
err
trace
set_radius_extended_configsdfsdfdfhfg err
set_radius_extended_configsdf
set_radius_extended_configsdfsdf
fsdsdfsf
xe xich low
set_radius_extended_configsdfsdfdfhfg
fghgf
fghgfdfjgdfkjgerr
dfhkhjh
cong hoa xa hoi chu nghia
djgkdbsk
dfhjđhd
error
con co be begkklg
dhmkfhd
err
dfkbdfnlkbndflbd
trace
err
fault
err
trace
set_radius_extended_configsdfsdfdfhfg err
set_radius_extended_configsdf
set_radius_extended_configsdfsdf
fsdsdfsf
xe xich low
set_radius_extended_configsdfsdfdfhfg
fghgf
fghgfdfjgdfkjgerr
dfhkhjh
cong hoa xa hoi chu nghia
djgkdbsk
dfhjđhd
error
con co be begkklg
dhmkfhd
err
dfkbdfnlkbndflbd
trace
err
fault
err
trace
set_radius_extended_configsdfsdfdfhfg err
set_radius_extended_configsdf
set_radius_extended_configsdfsdf
fsdsdfsf
xe xich low
set_radius_extended_configsdfsdfdfhfg
fghgf
fghgfdfjgdfkjgerr
dfhkhjh
cong hoa xa hoi chu nghia
djgkdbsk
dfhjđhd
error
con co be begkklg
dhmkfhd
err
dfkbdfnlkbndflbd
trace
err
fault
err
trace
set_radius_extended_configsdfsdfdfhfg err
set_radius_extended_configsdf
set_radius_extended_configsdfsdf
fsdsdfsf
xe xich low
set_radius_extended_configsdfsdfdfhfg
fghgf
fghgfdfjgdfkjgerr
dfhkhjh
cong hoa xa hoi chu nghia
djgkdbsk
dfhjđhd
error
con co be begkklg
dhmkfhd
err
dfkbdfnlkbndflbd
trace
err
fault
err
trace
set_radius_extended_configsdfsdfdfhfg err
set_radius_extended_configsdf
set_radius_extended_configsdfsdf
fsdsdfsf
xe xich low
set_radius_extended_configsdfsdfdfhfg
fghgf
fghgfdfjgdfkjgerr
dfhkhjh
cong hoa xa hoi chu nghia
djgkdbsk
dfhjđhd
error
con co be begkklg
dhmkfhd
err
dfkbdfnlkbndflbd
trace
err
fault
err
trace
set_radius_extended_configsdfsdfdfhfg err

File diff suppressed because it is too large Load Diff

View File

70
app/utils/Logger.ts Normal file
View File

@ -0,0 +1,70 @@
import fs from 'fs';
import moment from "moment";
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ố
if (typeof obj !== 'object' || typeof maxLength !== 'number') {
return obj;
}
// Duyệt qua các thuộc tính của đối tượng
for (const key in obj) {
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
if (typeof obj[key] === 'string' && obj[key].length > maxLength) {
// Rút ngắn chuỗi lại maxLength ký tự
obj[key] = obj[key].substring(0, maxLength);
}
}
}
if (Array.isArray(obj) && obj.length > 10) {
// Rút ngắn chuỗi lại maxLength ký tự
obj = "[Array:"+obj.length+"]\n"+obj.slice(0,15)
}
return obj;
}
export function loggerAPI(req, res, location) {
let old_data = "";
let resBody = res.getBody()
// let body = shortenStringsInObject(resBody, 300)
try {
const fileName =
"./app/store/logsAPI/" +
moment(Date.now()).format("DD_MM_YYYY").toString() +
".log";
let logInfo =
"\n\n[" +
moment(Date.now()).format("D/M/YY-HH:mm:ss") +
"] - " +
res.getStatus() +
" - " +
location +
"\n------PAYLOAD------\n" +
JSON.stringify(req.all(), null, 2) +
"\n------PARAMS-------\n" +
JSON.stringify(req.params(), null, 2) +
"\n-----RESPONSE------\n" +
JSON.stringify(resBody, null, 2) +
"\n------HEADERS------\n" +
JSON.stringify(req.headers(), null, 2) +
"\n\n======================================================================";
fs.exists(fileName, async (exists) => {
if (exists) {
old_data = await fs.readFileSync(fileName, "utf8");
fs.writeFileSync(fileName, old_data + logInfo);
} else {
fs.writeFileSync(fileName, old_data + logInfo);
}
});
} catch (error) {
res.status(500).send("CAN'T WRITE LOG");
}
}

204
app/utils/checkIndexSN.ts Normal file
View File

@ -0,0 +1,204 @@
import Env from "@ioc:Adonis/Core/Env";
// const axios = require("axios");
// import fs from "fs";
import axios from "axios";
export const checkIndexSN = async (content, beginLine, nameF) => {
try {
const arrayLine = content;
let output = [];
if (arrayLine !== undefined) {
for (let i = 0; i < arrayLine.length; i++) {
let SN = arrayLine[i]
?.split("SN:")[1]
?.trim()
.replace(/[!@#$%^&*()_+{}\[\]:;<>,.?~\\/]/g, "");
if (
arrayLine[i].search("PID:") !== -1 &&
arrayLine[i].search("SN:") !== -1 &&
arrayLine[i].search("%") === -1 &&
arrayLine[i]
?.split(",")[2]
?.split(":")[1]
?.replace("\r", "")
.trim() !== "" &&
SN !== "N/A" &&
SN.length > 4 &&
i >= beginLine
) {
if (output.some((u) => u.SN === SN)) {
output.map((u, index) => {
if (u.SN === SN) {
output[index].PID =
arrayLine[i]?.split("VID:")[0] !== undefined
? arrayLine[i]
?.split("VID:")[0]
?.slice(arrayLine[i]?.split("VID:")[0]?.search("PID"))
?.split(":")[1]
?.split(",")[0]
?.trim()
: "";
(output[index].VID =
arrayLine[i]?.split("SN:")[0] !== undefined
? arrayLine[i]
?.split("SN:")[0]
?.split("VID:")[1]
?.split(",")[0]
?.trim()
: ""),
(output[index].line = output[index].line.concat([i + 1]));
}
});
} else {
output.push({
PID:
arrayLine[i]?.split("VID:")[0] !== undefined
? arrayLine[i]
?.split("VID:")[0]
?.slice(arrayLine[i]?.split("VID:")[0]?.search("PID"))
?.split(":")[1]
?.split(",")[0]
?.trim()
: "",
VID:
arrayLine[i]?.split("SN:")[0] !== undefined
? arrayLine[i]
?.split("SN:")[0]
?.split("VID:")[1]
?.split(",")[0]
?.trim()
: "",
SN:
arrayLine[i].split("SN:")[1] !== undefined
? SN.search(" ") !== -1
? SN?.split(" ")[0]
: SN
: "",
line: [i + 1],
fileName: nameF,
warehouse:
(nameF.search("-US") !== -1 ||
nameF.search(".US") !== -1 ||
nameF.search("US-") !== -1) &&
nameF.search("AUS") === -1
? "US"
: "AU",
});
}
}
if (arrayLine[i].search("Serial Number") !== -1 && i >= beginLine) {
let PCB_SN = arrayLine[i]
?.split("Serial Number")[1]
.split(":")[1]
?.replace("\r", "")
.trim()
.replace(/[!@#$%^&*()_+{}\[\]:;<>,.?~\\/]/g, "");
if (
//Neu SN da nam trong output
output.some((u) => u.SN === PCB_SN)
) {
output.map((u, index) => {
if (u.SN === PCB_SN) {
output[index].line = output[index].line.concat([i + 1]);
}
});
} else {
// if (
// /^[A-Z0-9-]{5,}$/.test(
// PCB_SN
// )
// ) {
output.push({
PID: "",
VID: "",
SN: PCB_SN?.search(" ") !== -1 ? PCB_SN?.split(" ")[0] : PCB_SN,
line: [i + 1],
fileName: nameF,
warehouse:
(nameF.search("-US") !== -1 ||
nameF.search(".US") !== -1 ||
nameF.search("US-") !== -1) &&
nameF.search("AUS") === -1
? "US"
: "AU",
});
// }
}
}
if (
arrayLine[i].search("Processor board ID") !== -1 &&
i >= beginLine
) {
let PBID = arrayLine[i]
?.split(" ")
[arrayLine[i]?.split(" ").length - 1]?.replace("\r", "")
.trim()
.replace(/[!@#$%^&*()_+{}\[\]:;<>,.?~\\/]/g, "");
if (
//Neu SN da nam trong output
output.some((u) => u.SN === PBID)
) {
output.map((u, index) => {
if (u.SN === PBID) {
output[index].line = output[index].line.concat([i + 1]);
}
});
} else {
if (PBID?.length >= 8) {
output.push({
PID: "",
VID: "",
SN: PBID?.search(" ") !== -1 ? PBID?.split(" ")[0] : PBID,
line: [i + 1],
fileName: nameF,
warehouse:
(nameF.search("-US") !== -1 ||
nameF.search(".US") !== -1 ||
nameF.search("US-") !== -1) &&
nameF.search("AUS") === -1
? "US"
: "AU",
});
}
}
}
}
// console.log(nameF+" output\n", output);
if (output.filter((i) => i.PID !== "").length > 0) {
let token =
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2FwaS5uc3d0ZWFtLm5ldC9hcGkvbG9naW4iLCJpYXQiOjE2ODkzOTEyMDMsImV4cCI6MTcyMDkyNzIwMywibmJmIjoxNjg5MzkxMjAzLCJqdGkiOiJreFA1MW9jck5rdEYzSzY3Iiwic3ViIjozNjkwLCJwcnYiOiJjOGVlMWZjODllNzc1ZWM0YzczODY2N2U1YmUxN2E1OTBiNmQ0MGZjIn0.p-aE0oWkKmdrcKWD94oSmMd_CMbY_4MoqADIwYIhIKw";
let token_int =
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2ludC5pcHN1cHBseS5jb20uYXUvYXBpL2xvZ2luIiwiaWF0IjoxNjg5ODYyNjAxLCJleHAiOjE3MjEzOTg2MDEsIm5iZiI6MTY4OTg2MjYwMSwianRpIjoiUElZVjNBM3ZPQVlMQ081SyIsInN1YiI6MSwicHJ2IjoiYzhlZTFmYzg5ZTc3NWVjNGM3Mzg2NjdlNWJlMTdhNTkwYjZkNDBmYyJ9.UcybIKMBjTAY9i0PfIDQMtqHyN72Ul0jC03ZDGLGpMI";
let data = {
data: output.filter((i) => i.PID !== ""),
urlAPI: "/api/test-log-serial-number/save-data",
};
const response = await axios.post(
"https://api.nswteam.net/api/transferPostData",
data,
{ headers: { Authorization: "Bearer " + token } }
);
if (Env.get("RUN_ENV") === "prod") {
const response_int = await axios.post(
"https://int.ipsupply.com.au/api/transferPostData",
data,
{ headers: { Authorization: "Bearer " + token_int } }
);
console.log(nameF + " response\n", response_int.data);
}
}
}
} catch (error) {
console.log("Can't connect to log server", error);
}
};

View File

@ -0,0 +1,44 @@
const zulip = require("zulip-js");
export async function deleteMessagesZulip(streamName, topicName, numOfDay) {
const config = {
zuliprc: "./download",
zulipVersion: "v2",
};
const client = await zulip(config);
try {
const messages = await client.messages.retrieve({
anchor: "oldest",
num_before: 0,
num_after: 5000,
narrow: [
{ operator: "stream", operand: streamName },
{ operator: "topic", operand: topicName },
],
});
// console.log(messages.messages.map(u=>u.reactions))
const members = await client.users.retrieve();
// console.log(members.members)
for (const message of messages.messages) {
if (
message.reactions.filter(
(i) =>
i.emoji_name === "working_on_it" &&
members.members.filter((u) => u.user_id === i.user_id)[0]
.is_admin === true
).length === 0 &&
message.timestamp <
Math.floor((Date.now() - 60000 * 60 * 24 * numOfDay) / 1000)
) {
const res = await client.messages.deleteById({
message_id: message.id,
});
console.log(`Deleted message ID ${message.id}`);
// console.log(res)
}
}
} catch (error) {
console.error("Error:", error);
}
}

View File

@ -1,5 +1,3 @@
import LogReport from "App/Models/LogReport";
export async function getListLineByItem(listReport) {
try {
// Mảng ban đầu

View File

@ -0,0 +1,75 @@
const puppeteer = require("puppeteer");
const zulip = require("zulip-js");
(async () => {
// Launch a headless browser
const browser = await puppeteer.launch({
headless: true,
args: ["--no-sandbox"],
});
const config = {
username: "networktool-bot@zulip.ipsupply.com.au",
apiKey: "0jMAmOuhfLvBqKJikv5oAkyNM4RIEoAM",
realm: "https://zulip.ipsupply.com.au",
};
const client = await zulip(config);
const page = await browser.newPage();
// Điều hướng đến trang web chứa thẻ <a>
await page.goto("https://www.cskh.evnspc.vn/TraCuu/LichNgungGiamCungCapDien");
// Tìm thẻ <a> cần click dựa trên selector CSS hoặc XPath
const selectBoxSelector1 = "select#idCongTyDienLuc";
await page.waitForSelector(selectBoxSelector1);
await page.select(selectBoxSelector1, "PB11");
// Chờ cho trang mới mở
// await page.waitForNavigation('select#idCongTyDienLuc');
// In ra nội dung của trang mới
setTimeout(async () => {
const tableData = await page.evaluate(() => {
const tbody = document.querySelector("tbody"); // Lựa chọn thẻ <tbody> cần trích xuất
const rows = tbody.querySelectorAll("tr"); // Lựa chọn tất cả các hàng (thẻ <tr>) bên trong thẻ <tbody>
// Lặp qua từng hàng và lấy nội dung của các cột (thẻ <td>) trong hàng
const data = [];
rows.forEach((row) => {
const columns = Array.from(row.querySelectorAll("td")); // Lựa chọn tất cả các cột (thẻ <td>) trong hàng
const rowData = columns.map((column) => column.textContent.trim()); // Lấy nội dung của các cột và xóa khoảng trắng
data.push(rowData); // Thêm dữ liệu của hàng vào mảng data
});
return data.map((u) => u.join("\n\n"));
});
console.log("Table data:", tableData);
await browser.close();
let params = {
type: "stream",
to: "networkToolBot",
topic: "powerSchedule",
content:
":warning: :date: :warning:\n\n" + tableData.join("\n\n") + "\n-------",
};
client.messages.send(params);
if (
tableData.filter((i) => i.includes("KDC 91B") || i.includes("KDC91B"))
.length > 0
) {
let params = {
type: "stream",
to: "Result test - auto.nswteam.net",
topic: "Lịch cúp điện",
content:
":warning: :date: :warning:\n\n" +
tableData
.filter((i) => i.includes("KDC 91B") || i.includes("KDC91B"))[0]
.replace(/KDC 91B/g, "**KDC 91B**") +
"\n-------",
};
client.messages.send(params);
}
}, 5000);
})();

View File

@ -1,3 +1,4 @@
import Env from "@ioc:Adonis/Core/Env";
import fs from "fs";
import chokidar from "chokidar";
import moment from "moment";
@ -7,14 +8,12 @@ import KeyValue from "App/Models/KeyValue";
import Database from "@ioc:Adonis/Lucid/Database";
import { sendMessToZulip } from "./sendMessToZulip";
import { getListLineByItem } from "./getListLineByItem";
// export default class loggerAPI {
import { checkIndexSN } from "./checkIndexSN";
import { DateTime } from "luxon";
export async function runtimeCheckLogs(folderPath) {
try {
let fileList = Array();
let fileList_old = Array();
// console.log(listKeyValues.map(obj=>obj.$original.value))
// Function to update the list of files
async function updateFileList() {
//get date now
@ -35,24 +34,57 @@ export async function runtimeCheckLogs(folderPath) {
});
}
const checkSpecialVersion = (paragraph) => {
try {
const regex = /\(CAT3K_CAA-UNIVERSALK9-M\), Version 16\.9\.[2-9]/;
const regex1 =
/\(CAT3K_CAA-UNIVERSALK9-M\), Version 1[7-9]\.[0-9]\.[0-9]/;
const regex2 =
/\(CAT3K_CAA-UNIVERSALK9-M\), Version [2-9][0-9]\.[0-9]\.[0-9]/;
// Use the regular expression to find the match
const match = paragraph.match(regex);
const match1 = paragraph.match(regex1);
const match2 = paragraph.match(regex2);
if (match || match1 || match2) {
if (match) {
return match[0];
}
if (match1) {
return match1[0];
}
if (match2) {
return match2[0];
}
} else {
return "";
}
} catch (error) {
console.log(error);
}
};
// Watch the folder for new files
const folderWatcher = chokidar.watch(folderPath);
// folderWatcher.setMaxListeners(20);
folderWatcher.on("add", async (filePath) => {
//import log new file
// console.log(filePath)
//check format file name
if (
//Sua \\ --> /
filePath?.split(".")[filePath.split(".").length - 1] === "log" &&
filePath.split("/")[filePath.split("/").length - 1]?.split("-")[0] ===
//localhost
// filePath.split("\\")[filePath.split("\\").length - 1]?.split("-")[0] ===
moment(Date.now()).format("YYYYMMDD").toString()
) {
//add information file to database
console.log("New file added: ", filePath);
await LogDetectFile.firstOrCreate(
{ file_name: filePath.split("/")[filePath.split("/").length - 1] },
{ file_name: filePath.split("/")[filePath.split("/").length - 1] }
);
//localhost
// await LogDetectFile.firstOrCreate(
// { file_name: filePath.split("\\")[filePath.split("\\").length - 1] },
// { file_name: filePath.split("\\")[filePath.split("\\").length - 1] }
@ -67,216 +99,325 @@ export async function runtimeCheckLogs(folderPath) {
// Watch for changes in the files listed
async function watchFilesInList() {
// console.log("--------->", fileList);
//get date now
//check new file
await fileList
//only check new file ---> fileList - fileList_old = new file
let listFileWatch = fileList
?.filter((i) => fileList_old.includes(i) === false)
?.forEach((fileName) => {
//path file
const filePath = `${folderPath}/${fileName}`;
const scan = fs.watchFile(
filePath,
{ interval: 300000 },
async (eventType) => {
//check special item, extra RAM, error in log
let lines = [];
let content = await fs
.readFileSync(filePath)
.toString()
?.split("\n");
let allValue = await KeyValue.all();
let listKeyValues = allValue.filter(
(i) =>
i.$original.key === "MODEL_SPECIAL" ||
i.$original.key === "CATCH_FAULTY"
.map((file) => folderPath + "/" + file);
const watcher = chokidar.watch(listFileWatch, {
persistent: true,
usePolling: true,
interval: 300000,
});
watcher.setMaxListeners(200);
watcher.on("change", async (path) => {
// fs.watchFile(filePath,{ interval: 15000 },
// async (eventType) => {
//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 filePath = path;
let lines = [];
const today = DateTime.now().toFormat("yyyy-MM-dd");
let allFile = await LogDetectFile.query().whereRaw(
`DATE(created_at) = ?`,
[today]
);
// let allReport = await LogReport.all();
let allValue = await KeyValue.all();
const allReport = await LogReport.query().whereRaw(
`DATE(created_at) = ?`,
[today]
);
//get information file
let fileDetect = allFile?.filter(
(i) => i.$original.file_name === fileName
)[0];
let logsDetect = allReport?.filter(
(i) => i.$original.id_file === fileDetect?.id_ldf
);
//get the last line detected
let lastLine = Math.max(...logsDetect.map((obj) => obj.line));
//get content file in local
let contentFile = await fs
.readFileSync(filePath)
.toString()
?.split("\n");
//get index SN and send to ERP
checkIndexSN(contentFile, lastLine, fileName);
//get list item to check
let listKeyValues = allValue.filter(
(i) =>
i.$original.key === "MODEL_SPECIAL" ||
i.$original.key === "CATCH_FAULTY"
);
//get list exclude error
let listExcludeErr = allValue
.filter((i) => i.$original.key === "EXCLUDE_ERR")
.map((obj) => obj.$original.value);
//get list item special
let listExtraItem = allValue
.filter((i) => i.$original.key === "MODEL_SPECIAL")
.map((obj) => obj.$original.value);
//Process file content
if (contentFile.length > 50000) {
for (let i = 0; i < contentFile.length; i += 1000) {
const chunk = contentFile.slice(i, i + 1000);
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 (checkLog?.length === 0) {
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
)[0];
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
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(
(report) =>
report.$original.id_file === log?.id_ldf &&
report.$original.line === index + 1 &&
report.$original.detected_content === value
);
if (checkLog?.length === 0) {
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
)[0];
let checkLog = allReport?.filter(
(report) =>
report.$original.id_file === log?.id_ldf &&
report.$original.line === index + 1 &&
report.$original.detected_content === checkVersion
);
let listExcludeErr = allValue
.filter((i) => i.$original.key === "EXCLUDE_ERR")
.map((obj) => obj.$original.value);
let listExtraItem = allValue
.filter((i) => i.$original.key === "MODEL_SPECIAL")
.map((obj) => obj.$original.value);
console.log(listExtraItem)
content.map((line, index) => {
listKeyValues
.map((obj) => obj.$original.value)
.map(async (value) => {
if (
line.search(value) !== -1 &&
listExcludeErr.filter((err) => line.includes(err))
.length === 0
) {
// let keyWord = "";
// line.split(" ").map((word) => {
// if (word.toLocaleLowerCase().includes(value)) {
// keyWord = keyWord + word;
// }
// });
// if (value.length === keyWord.length) {
const log = await LogDetectFile.findBy(
"file_name",
fileName
);
let checkLog = await Database.rawQuery(
"select * from log_reports where id_file = " +
log?.id_ldf +
" and line = " +
(index + 1) +
" and detected_content='" +
value +
"'"
);
if (checkLog[0].length === 0) {
await LogReport.create({
detected_content: value,
line: index + 1,
id_file: log?.id_ldf,
});
lines.push(index + 1);
}
}
});
});
// }, 5000);
//true: import log to log_report table, send report to Zulip
setTimeout(async () => {
if (lines.length === 0) {
console.log(`${fileName} has changed (${eventType})---Good`);
} else {
console.log(
`${fileName} has changed (${eventType})---SOS---${lines.length}`
);
let fileDetect = await LogDetectFile.findBy(
"file_name",
fileName
);
let logsDetect = await Database.rawQuery(
"select * from log_reports where id_file = " +
fileDetect?.id_ldf
);
let listReport = await getListLineByItem(logsDetect[0]);
let content =
"| |Last updated at | Item/error | Count | Report \n|---|:---:|:---|:---|:-----------:\n";
let spoiler = "";
// let file = await fs
// .readFileSync(filePath)
// .toString()
// ?.split("\n");
// if (logsDetect[0].length > 10) {
// spoiler =
// spoiler +
// "```spoiler ..." +
// (logsDetect[0].length - 5) +
// " more items\n" +
// content;
// logsDetect[0]
// .reverse()
// .slice(0, 5)
// ?.map((log, index) => {
// content =
// content +
// "|" +
// (logsDetect[0].length - index) +
// "|**" +
// moment(log.created_at).format("HH:mm - DD/MM") +
// "**|" +
// log.line +
// "|" +
// log.detected_content +
// "|" +
// file[log.line - 1] +
// "|[View](https://logs.danielvu.com/api/log/showLog/" +
// fileName +
// ")\n";
// });
// logsDetect[0]
// .slice(5, logsDetect[0].length)
// ?.map((log, index) => {
// spoiler =
// spoiler +
// "|" +
// (logsDetect[0].length - index - 5) +
// "|**" +
// moment(log.created_at).format("HH:mm - DD/MM") +
// "**|" +
// log.line +
// "|" +
// log.detected_content +
// "|" +
// file[log.line - 1] +
// "|[View](https://logs.danielvu.com/api/log/showLog/" +
// fileName +
// ")\n";
// });
// spoiler = spoiler + "\n```\n\n";
// } else {
listReport.map((log, index) => {
let item = listExtraItem.includes(log.detected_content)
? ":medal: **" + log.detected_content+"**"
: ":small_orange_diamond: "+log.detected_content;
content =
content +
"|" +
(index + 1) +
"|**" +
moment(log.created_at).format("HH:mm - DD/MM") +
"**|" +
item +
"|" +
log.line.length +
// "|" +
// file[log.line - 1] +
"|[View](https://logs.danielvu.com/api/log/showLog/" +
fileName +
")\n";
});
// }
// setTimeout(() => {
sendMessToZulip(
"stream",
"Result test - auto.nswteam.net",
"Log Alert",
":warning: :warning: **" +
fileName +
"**\n\n" +
content +
"\n\n" +
spoiler
);
sendMessToZulip(
"stream",
"AUS_VN_Test",
"Test Log Alerts",
":warning: :warning: **" +
fileName +
"**\n\n" +
content +
"\n\n" +
spoiler
);
// }, 3000);
}
}, 3000);
//false: next
if (checkLog?.length === 0) {
await LogReport.create({
detected_content: checkVersion,
line: index + 1,
id_file: log?.id_ldf,
});
lines.push(index + 1);
}
}
);
//setMaxListeners
scan.setMaxListeners(0);
// }
});
});
}
//true: import log to log_report table, send report to Zulip
setTimeout(async () => {
if (lines.length === 0) {
console.log(
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]
);
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 +
"**:no_entry: :no_entry:"
: "------------\n\n:warning: :warning: **" + fileName + "**";
sendMessToZulip(
"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) => {
console.error(`Watcher error: ${error}`);
});
// await fileList.slice(0,40)
// ?.filter((i) => fileList_old.includes(i) === false)
// ?.forEach((fileName) => {
// //path file
// const filePath = `${folderPath}/${fileName}`;
// });
}
} catch (error) {
console.log(error);

25
app/utils/screenShot.ts Normal file
View File

@ -0,0 +1,25 @@
import puppeteer from 'puppeteer';
export const screenShot = async (filename, time) => {
const browser = await puppeteer.launch({
headless: true,
args: ["--no-sandbox"],
});
try {
// Open a new page
const page = await browser.newPage();
await page.goto("https://logs.danielvu.com/screenShot/" + filename);
const bodyHandle = await page.$("body");
const { height } = await bodyHandle.boundingBox();
await bodyHandle.dispose();
await page.setViewport({ width: 1920, height: 800 });
setTimeout(async () => {
await page.screenshot({ path: "/home/screenshot/"+time+".png" });
browser.close();
}, 5000);
} catch (error) {
console.log(error);
}
};

BIN
app/utils/screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 304 KiB

View File

@ -0,0 +1,358 @@
import Env from "@ioc:Adonis/Core/Env";
import fs from "fs";
import moment from "moment/moment";
import nodeMailer from "nodemailer";
import LogDetectFile from "App/Models/LogDetectFile";
import InfoDevice from "App/Models/InfoDevice";
import KeyValue from "App/Models/KeyValue";
export const sendDeviceInfora = async () => {
try {
//Regex check show inventory
const regexInventory = /sh.*? inv.*/;
//Regex check show version
const regexVersion = /sh.*? ver.*/;
const regexMemory = /(\d+)K/g;
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 = [];
let dataFile = await LogDetectFile.all();
let html = "";
//List file today
const listFile = fs
.readdirSync(Env.get("FOLDER_LOGS"))
.filter((f) => f.includes(date) && f.split(".")[f.split(".").length - 1]);
//Configure mail
const transporter = nodeMailer.createTransport({
pool: true,
host: "mail.ipsupply.com.au",
port: 465,
secure: true,
auth: {
user: "admin@apactech.io",
pass: "BGK!dyt6upd2eax1bhz",
},
});
//Read file in listFile
await listFile.map(async (file) => {
fs.readFile(
Env.get("FOLDER_LOGS") + "/" + file,
"utf8",
async (err, data) => {
if (err) {
console.log(`Error reading file: ${err}`);
} else {
//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 {
await LogDetectFile.firstOrCreate(
{ file_name: file },
{ file_name: file }
);
dataFile = await LogDetectFile.all();
DBFileCheck = dataFile.filter(
(i) => i.$attributes.file_name === file
)[0];
}
//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(
(line) => line.match(regexVersion) !== null
).length > 0
) {
const lineShowver = deviceContent.indexOf(
deviceContent.filter(
(line) => line.match(regexVersion) !== null
)[0]
);
const showVersion = deviceContent.slice(
lineShowver,
deviceContent.indexOf(
deviceContent.filter(
(line) => line.search("Configuration register") !== -1
)[0]
) + 1
);
showInventoryContent.map((u, index) => {
const PID = u
?.split("VID:")[0]
?.split("PID:")[1]
?.replace(/,/g, "")
.trim();
const VID = u
?.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>
<td>${VID}</td>
<td>${SN}</td>
<td></td>
<td></td>
<td>yes</td></tr>`;
}
} else {
if (PID !== "" && SN !== "") {
const memDefaultForPID =
memDefault.filter((i) =>
PID.includes(i.split(":")[0])
)[0] !== undefined
? memDefault.filter((i) =>
PID.includes(i.split(":")[0])
)[0]
: PID + ":N/A:N/A";
let RAM =
showVersion
.filter(
(line) =>
line.includes("bytes of memory") ||
line.includes("bytes of physical memory")
)
.join("<br>")
.match(regexMemory) !== null
? (
parseInt(
showVersion
.filter(
(line) =>
line.includes("bytes of memory") ||
line.includes("bytes of physical memory")
)
.join("<br>")
.match(regexMemory)[0]
) /
1024 /
1024
).toFixed(2) +
"G (D: " +
memDefaultForPID.split(":")[1] +
")"
: "";
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>${SN}</td>
<td>${RAM}</td>
<td>${
flash.match(regexMemory) !== null
? (
parseInt(flash.match(regexMemory)[0]) /
1024 /
1024
).toFixed(2) +
"G (D: " +
memDefaultForPID.split(":")[2] +
")"
: ""
}</td>
<td>no</td></tr>`;
}
}
});
} else {
//show version not exists --> RAM = N/A, Flash = N/A
showInventoryContent.map((u, index) => {
const PID = u
?.split("VID:")[0]
?.split("PID:")[1]
?.replace(/,/g, "")
.trim();
const VID = u
?.split("VID:")[1]
?.split("SN:")[0]
?.replace(/,/g, "")
.trim();
const SN = u?.split("SN:")[1]?.replace(/,/g, "").trim();
if (index > 0) {
if (PID !== "" && SN !== "") {
listInformation.push({
PID: PID,
VID: VID,
SN: SN,
RAM: "",
flash: "",
extra_item: "yes",
});
html += `<tr><td>${PID}</td>
<td>${VID}</td>
<td>${SN}</td>
<td></td>
<td></td>
<td>yes</td></tr>`;
}
} else {
if (PID !== "" && SN !== "") {
listInformation.push({
PID: PID,
VID: VID,
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 () => {
if (listInformation.length > 0) {
console.log(listInformation);
const options = {
from: "admin@apactech.io",
to: "joseph@apactech.io, ips@ipsupply.com.au",
subject: "(AUTO-REPORT) SERIAL NUMBER",
html:
"<table border='1'>\
<thead>\
<tr>\
<th>PID</th>\
<th>VID</th>\
<th>SN</th>\
<th>RAM</th>\
<th>Flash</th>\
<th>Extra Item</th>\
</tr>\
</thead>\
<tbody>" +
html +
"</tbody>\
</table>",
};
transporter.sendMail(options);
await InfoDevice.createMany(listInformation);
}
}, 5000);
} catch (error) {
console.log(error);
}
};

View File

@ -8,14 +8,24 @@ export const sendMessToZulip = async (type, to, topic, content) => {
realm: "https://zulip.ipsupply.com.au",
};
const client = await zulip(config);
let params = {
type: type,
to: to,
topic: topic,
content: content
};
if(type === "private"){
let params = {
type: type,
to: to,
content: content
};
await client.messages.send(params);
}else{
let params = {
type: type,
to: to,
topic: topic,
content: content
};
await client.messages.send(params);
}
await client.messages.send(params);
} catch (error) {
console.log(error);
}

View File

@ -0,0 +1,119 @@
const moment = require("moment/moment");
const zulip = require("zulip-js");
const { exec } = require("child_process");
const sendNotification = async () => {
try {
const config = {
username: "networktool-bot@zulip.ipsupply.com.au",
apiKey: "0jMAmOuhfLvBqKJikv5oAkyNM4RIEoAM",
realm: "https://zulip.ipsupply.com.au",
};
const client = await zulip(config);
let auto1 = "";
let auto2 = "";
let log = "";
exec("nc -zv 172.16.7.13 8002", (error, stdout, stderr) => {
if (error) {
// console.error(`Error executing command: ${error.message}`);
return;
}
if (stdout !== "") {
auto1 += stdout;
} else {
auto1 += stderr;
}
});
exec("nc -zv 172.16.7.13 5000", (error, stdout, stderr) => {
if (error) {
// console.error(`Error executing command: ${error.message}`);
return;
}
if (stdout !== "") {
auto2 += stdout;
} else {
auto2 += stderr;
}
});
exec("nc -zv 172.16.6.23 7777", (error, stdout, stderr) => {
if (error) {
exec("/root/.nvm/versions/node/v16.14.0/bin/pm2 restart all", (error, stdout, stderr) => {
if (error) {
console.log("RESTART: ", stdout);
let params = {
type: "stream",
to: "networkToolBot",
topic: "Log service",
content: "Can't restart server. Please check!\n```\n"+error+"\n```",
};
client.messages.send(params);
}
// console.log("RESTART: ", stdout);
let params = {
type: "stream",
to: "networkToolBot",
topic: "Log service",
content: "Restarting ...",
};
client.messages.send(params);
});
return;
}
if (stdout !== "") {
log += stdout;
} else {
log += stderr;
}
});
setTimeout(async () => {
console.log({ auto1: auto1, auto2: auto2, log: log });
if (process.argv[2] === "daily") {
let autoStatus =
auto1?.includes("succeeded") && auto2?.includes("succeeded")
? ":check:"
: ":red_circle:";
let logStatus = log?.includes("succeeded") ? ":check:" : ":red_circle:";
let time = moment(Date.now()).format("HH:mm - DD/MM");
let content =
"| |Server| System time| Status \n|---|:---:|:---|:---:\n|1|auto.danielvu.com|**" +
time +
"**|" +
autoStatus +
"|\n|2|logs.danielvu.com|**" +
time +
"**|" +
logStatus +
"|";
let params = {
type: "stream",
to: "System Logs",
topic: "stream events",
content: content,
};
// let params = {
// type: "stream",
// to: "Result test - auto.nswteam.net",
// topic: "AU-dev",
// content: content,
// };
await client.messages.send(params);
}
}, 5000);
} catch (error) {
console.log(error);
}
};
sendNotification();

View File

@ -0,0 +1,44 @@
import { FormData } from "zulip-js/lib/helper";
import axios from "axios";
import fs from "fs";
export const uploadFileToZulip = async (filename) => {
// try {
const ZULIP_API_URL = "https://zulip.ipsupply.com.au/api/v1";
const ZULIP_API_KEY = "0jMAmOuhfLvBqKJikv5oAkyNM4RIEoAM";
const BOT_EMAIL = "networktool-bot@zulip.ipsupply.com.au";
// const ZULIP_API_URL = "https://zulip.ipsupply.com.au/api/v1";
// const ZULIP_API_KEY = "7XGrpwzFtQyUVDQzdwL3hjdVSbLx55yt";
// const BOT_EMAIL = "joseph.le@apactech.io";
try {
const fileStream = fs.createReadStream("/home/screenshot/"+filename+".png");
const formData = new FormData();
formData.append("file", fileStream);
const response = await axios.post(
`${ZULIP_API_URL}/user_uploads`,
formData,
{
headers: {
"Content-Type": "application/octet-stream",
Authorization: `Basic ${Buffer.from(
`${BOT_EMAIL}:${ZULIP_API_KEY}`
).toString("base64")}`,
},
}
);
if (response.status === 200) {
const uploadedFile = response.data.uri;
return uploadedFile;
} else {
console.error("Failed to upload file:", response.statusText);
return null;
}
} catch (error) {
console.log("Error uploading file:", error.message);
}
};

4
app/utils/zuliprc Normal file
View File

@ -0,0 +1,4 @@
[api]
email=networktool-bot@zulip.ipsupply.com.au
key=0jMAmOuhfLvBqKJikv5oAkyNM4RIEoAM
site=https://zulip.ipsupply.com.au

View File

@ -5,8 +5,8 @@
* file.
*/
import Env from '@ioc:Adonis/Core/Env'
import type { DatabaseConfig } from '@ioc:Adonis/Lucid/Database'
import Env from "@ioc:Adonis/Core/Env";
import type { DatabaseConfig } from "@ioc:Adonis/Lucid/Database";
const databaseConfig: DatabaseConfig = {
/*
@ -19,7 +19,7 @@ const databaseConfig: DatabaseConfig = {
| file.
|
*/
connection: Env.get('DB_CONNECTION'),
connection: Env.get("DB_CONNECTION"),
connections: {
/*
@ -34,24 +34,28 @@ const databaseConfig: DatabaseConfig = {
|
*/
mysql: {
client: 'mysql2',
client: "mysql2",
connection: {
host: Env.get('MYSQL_HOST'),
port: Env.get('MYSQL_PORT'),
user: Env.get('MYSQL_USER'),
password: Env.get('MYSQL_PASSWORD', ''),
database: Env.get('MYSQL_DB_NAME'),
host: Env.get("MYSQL_HOST"),
port: Env.get("MYSQL_PORT"),
user: Env.get("MYSQL_USER"),
password: Env.get("MYSQL_PASSWORD", ""),
database: Env.get("MYSQL_DB_NAME"),
},
pool: {min:1, max:120},
acquireConnectionTimeout: 60000,
pool: {
min: 1,
max: 2000,
acquireTimeoutMillis: 60 * 1000
},
migrations: {
naturalSort: true,
},
healthCheck: false,
debug: false,
},
},
};
}
}
export default databaseConfig
export default databaseConfig;

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)
}
}

4
download Normal file
View File

@ -0,0 +1,4 @@
[api]
email=joseph.le@apactech.io
key=7XGrpwzFtQyUVDQzdwL3hjdVSbLx55yt
site=https://zulip.ipsupply.com.au

View File

@ -12,8 +12,10 @@
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.5.0",
"dotenv": "^16.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.15.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
@ -3237,6 +3239,14 @@
}
}
},
"node_modules/@remix-run/router": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.8.0.tgz",
"integrity": "sha512-mrfKqIHnSZRyIzBcanNJmVQELTnX+qagEDlcKO90RgRBVOZGSGvZKeDihTRfWcqoDn5N/NkUcwWTccnpN18Tfg==",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/@rollup/plugin-babel": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-5.3.1.tgz",
@ -6999,11 +7009,14 @@
}
},
"node_modules/dotenv": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-10.0.0.tgz",
"integrity": "sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q==",
"version": "16.3.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz",
"integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==",
"engines": {
"node": ">=10"
"node": ">=12"
},
"funding": {
"url": "https://github.com/motdotla/dotenv?sponsor=1"
}
},
"node_modules/dotenv-expand": {
@ -14672,6 +14685,36 @@
"node": ">=0.10.0"
}
},
"node_modules/react-router": {
"version": "6.15.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.15.0.tgz",
"integrity": "sha512-NIytlzvzLwJkCQj2HLefmeakxxWHWAP+02EGqWEZy+DgfHHKQMUoBBjUQLOtFInBMhWtb3hiUy6MfFgwLjXhqg==",
"dependencies": {
"@remix-run/router": "1.8.0"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"react": ">=16.8"
}
},
"node_modules/react-router-dom": {
"version": "6.15.0",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.15.0.tgz",
"integrity": "sha512-aR42t0fs7brintwBGAv2+mGlCtgtFQeOzK0BM1/OiqEzRejOZtpMZepvgkscpMUnKb8YO84G7s3LsHnnDNonbQ==",
"dependencies": {
"@remix-run/router": "1.8.0",
"react-router": "6.15.0"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"react": ">=16.8",
"react-dom": ">=16.8"
}
},
"node_modules/react-scripts": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/react-scripts/-/react-scripts-5.0.1.tgz",
@ -14744,6 +14787,14 @@
}
}
},
"node_modules/react-scripts/node_modules/dotenv": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-10.0.0.tgz",
"integrity": "sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q==",
"engines": {
"node": ">=10"
}
},
"node_modules/read-cache": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",
@ -19842,6 +19893,11 @@
"source-map": "^0.7.3"
}
},
"@remix-run/router": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.8.0.tgz",
"integrity": "sha512-mrfKqIHnSZRyIzBcanNJmVQELTnX+qagEDlcKO90RgRBVOZGSGvZKeDihTRfWcqoDn5N/NkUcwWTccnpN18Tfg=="
},
"@rollup/plugin-babel": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-5.3.1.tgz",
@ -22635,9 +22691,9 @@
}
},
"dotenv": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-10.0.0.tgz",
"integrity": "sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q=="
"version": "16.3.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz",
"integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ=="
},
"dotenv-expand": {
"version": "5.1.0",
@ -28006,6 +28062,23 @@
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz",
"integrity": "sha512-F27qZr8uUqwhWZboondsPx8tnC3Ct3SxZA3V5WyEvujRyyNv0VYPhoBg1gZ8/MV5tubQp76Trw8lTv9hzRBa+A=="
},
"react-router": {
"version": "6.15.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.15.0.tgz",
"integrity": "sha512-NIytlzvzLwJkCQj2HLefmeakxxWHWAP+02EGqWEZy+DgfHHKQMUoBBjUQLOtFInBMhWtb3hiUy6MfFgwLjXhqg==",
"requires": {
"@remix-run/router": "1.8.0"
}
},
"react-router-dom": {
"version": "6.15.0",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.15.0.tgz",
"integrity": "sha512-aR42t0fs7brintwBGAv2+mGlCtgtFQeOzK0BM1/OiqEzRejOZtpMZepvgkscpMUnKb8YO84G7s3LsHnnDNonbQ==",
"requires": {
"@remix-run/router": "1.8.0",
"react-router": "6.15.0"
}
},
"react-scripts": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/react-scripts/-/react-scripts-5.0.1.tgz",
@ -28059,6 +28132,13 @@
"webpack-dev-server": "^4.6.0",
"webpack-manifest-plugin": "^4.0.2",
"workbox-webpack-plugin": "^6.4.1"
},
"dependencies": {
"dotenv": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-10.0.0.tgz",
"integrity": "sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q=="
}
}
},
"read-cache": {

View File

@ -7,8 +7,10 @@
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.5.0",
"dotenv": "^16.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.15.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -24,7 +24,7 @@
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
<title>Log View</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>

View File

@ -2,13 +2,22 @@ import axios from "axios";
import React, { useEffect, useState } from "react";
import { getKeyValues } from "./api/apiLog";
import ManageValues from "./pages/ManageValues";
import { Routes, Route, Switch, useParams } from "react-router-dom";
import ShowLog from "./components/ShowLog/ShowLog";
import ListLog from "./components/ListLog/ListLog";
import ScreenShot from "./components/ScreenShot/ScreenShot";
function App() {
return (
<div className="App">
<ManageValues/>
<Routes>
{/* Define routes */}
<Route path="/" element={<ManageValues />}>
{/* Render the UserProfile component */}
</Route>
<Route path="/logs/:name" element={<ShowLog />}></Route>
<Route path="/logs" element={<ListLog />}></Route>
<Route path="/screenShot/:name" element={<ScreenShot />}></Route>
</Routes>
</div>
);
}

View File

@ -1,5 +1,8 @@
// const API = "https://logs.danielvu.com/api";
const API = "http://localhost:3333/api";
const API = process.env.REACT_APP_API_SERVER_ADDRESS;
// const API = "http://localhost:3333/api";
export const getKeyValues = API + "/getKeyValue";
export const deleteValue = API + "/deleteValue";
export const addKeyValue = API + "/addValue";
export const addKeyValue = API + "/addValue";
export const editValue = API + "/editValue";
export const getLog = API + "/log/showLog";
export const getListLog = API + "/getAllLogDetect";

View File

@ -0,0 +1,46 @@
.mainList{
height: 100vh;
scroll-behavior: smooth;
border: solid gray 5px;
width:100%;
word-wrap:break-word;
white-space:pre;
overflow: auto;
font-family: monospace;
text-rendering: auto;
color: fieldtext;
letter-spacing: normal;
word-spacing: normal;
line-height: normal;
text-transform: none;
text-indent: 0px;
text-shadow: none;
display: inline-block;
text-align: start;
appearance: auto;
-webkit-rtl-ordering: logical;
resize: vertical;
cursor: text;
background-color: field;
column-count: initial !important;
writing-mode: horizontal-tb !important;
box-sizing: border-box;
margin: 0em;
/* border-width: 1px; */
/* border-style: solid; */
/* border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); */
/* border-image: initial; */
padding: 5px;
/* position: relative; */
}
.inputSearch{
position: sticky;
top:0;
right: 0;
text-align: right;
}
.inputSearch input{
width: 30%;
}

View File

@ -0,0 +1,63 @@
import axios from "axios";
import React, { useEffect, useState } from "react";
import { Link, Navigate, useParams } from "react-router-dom";
import { getListLog } from "../../api/apiLog";
import "./ListLog.css";
const ListLog = () => {
const [listFile, setListFile] = useState([]);
const [status, setStatus] = useState(200);
const [nameSearch, setNameSearch] = useState("");
const getListFile = async () => {
try {
const res = await axios.get(getListLog);
setListFile(res.data);
setStatus(res.status);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
getListFile();
}, []);
if (status === 200) {
return (
<div className="mainList">
<div className="inputSearch">
<Link to={"/"}>
<button
style={{
color: "white",
backgroundColor: "blue",
cursor: "pointer",
float:"left"
}}
>
Home
</button></Link>
<label>Search: </label>
<input value={nameSearch} placeholder={"Enter a file name"} onChange={(e)=>{
setNameSearch(e.target.value)
}}></input>
</div>
{listFile?.filter((f)=>f.toLocaleLowerCase().search(nameSearch.toLocaleLowerCase())!==-1).map((file) => (
<div>
<Link to={"/logs/" + file}>{file}</Link>
<br></br>
</div>
))}
</div>
);
} else {
return (
<div>
<h1>
<i>No files</i>
</h1>
</div>
);
}
};
export default ListLog;

View File

@ -0,0 +1,34 @@
#bodyScreen {
height: 100%;
padding: 5px;
word-wrap: break-word;
border: solid gray 5px;
white-space: pre;
overflow: auto;
font-family: monospace;
text-rendering: auto;
color: fieldtext;
letter-spacing: normal;
word-spacing: normal;
line-height: normal;
text-transform: none;
text-indent: 0px;
text-shadow: none;
display: inline-block;
text-align: start;
appearance: auto;
-webkit-rtl-ordering: logical;
resize: vertical;
cursor: text;
background-color: field;
column-count: initial !important;
writing-mode: horizontal-tb !important;
/* box-sizing: border-box; */
margin: 0em;
/* border-width: 1px; */
/* border-style: solid;/ */
/* border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); */
/* border-image: initial; */
padding: 5px;
font-size: 1.2rem;
}

View File

@ -0,0 +1,99 @@
import axios from "axios";
import React, { useEffect, useState } from "react";
import { Link, Navigate, useParams } from "react-router-dom";
import { getLog } from "../../api/apiLog";
import "./ScreenShot.css";
const ScreenShot = () => {
let { name } = useParams();
const [log, setLog] = useState({});
const [status, setStatus] = useState(200);
const getContentLog = async () => {
try {
const res = await axios.get(getLog + "/" + name);
setLog(res.data);
setStatus(res.status);
} catch (error) {
console.log(error);
}
};
function scrollToBottom() {
const targetDiv = document.getElementById('bodyScreen');
targetDiv.scrollTop = targetDiv.scrollHeight;
}
// Call the function to scroll to the end of the page
useEffect(() => {
getContentLog();
// setTimeout(() => {
// scrollToBottom();
// }, 2000);
}, []);
// console.log(window.location.hash);
if (status === 200) {
return (
<div className="main">
<div id="bodyScreen">
<h3
style={{
display:
log?.modelSpecial === "" && log?.issueItem === ""
? "block"
: "none",
}}
>
No errors were found in the file
</h3>
<h3 style={{ display: log?.modelSpecial !== "" ? "block" : "none" }}>
Extra items:
</h3>
{log?.modelSpecial?.split("\n")?.map((line) => (
<span>
<span className="lineNumberLog">{line.split("|-|")[0]}</span>
<span>{line.split("|-|")[1]}</span>
<span className="itemDetected">
<a
href={"#" + line.split("|-|")[0]}
style={{ textDecoration: "none", color: "black" }}
>
{line.split("|-|")[2]}
</a>
</span>
<span>{line.split("|-|")[3]}</span>
<br></br>
</span>
))}
<h3 style={{ display: log?.issueItem !== "" ? "block" : "none" }}>
Issue found:
</h3>
{log?.issueItem?.split("\n")?.reverse().map((line) => (
<span>
<span className="lineNumberLog">{line.split("|-|")[0]}</span>
<span>{line.split("|-|")[1]}</span>
<span className="itemDetected">
<a
href={"#" + line.split("|-|")[0]}
style={{ textDecoration: "none", color: "black" }}
>
{line.split("|-|")[2]}
</a>
</span>
<span>{line.split("|-|")[3]}</span>
<br></br>
</span>
))}
</div>
</div>
);
} else {
return (
<div>
<h1>
<i>The file was not found.</i>
</h1>
</div>
);
}
};
export default ScreenShot;

View File

@ -0,0 +1,106 @@
.main {
display: flex;
height: 100vh;
flex-flow: column;
background-color: gray;
/* position: relative; */
}
.detectedDiv {
height: 40%;
padding: 5px;
word-wrap: break-word;
border: solid gray 5px;
white-space: pre;
overflow: auto;
font-family: monospace;
text-rendering: auto;
color: fieldtext;
letter-spacing: normal;
word-spacing: normal;
line-height: normal;
text-transform: none;
text-indent: 0px;
text-shadow: none;
display: inline-block;
text-align: start;
appearance: auto;
-webkit-rtl-ordering: logical;
resize: vertical;
cursor: text;
background-color: field;
column-count: initial !important;
writing-mode: horizontal-tb !important;
/* box-sizing: border-box; */
margin: 0em;
/* border-width: 1px; */
/* border-style: solid;/ */
/* border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); */
/* border-image: initial; */
padding: 5px;
}
.logContent {
scroll-behavior: smooth;
border: solid gray 5px;
width: 100%;
height: 60%;
word-wrap: break-word;
white-space: pre;
overflow: auto;
font-family: monospace;
text-rendering: auto;
color: fieldtext;
letter-spacing: normal;
word-spacing: normal;
line-height: normal;
text-transform: none;
text-indent: 0px;
text-shadow: none;
display: inline-block;
text-align: start;
appearance: auto;
-webkit-rtl-ordering: logical;
resize: vertical;
cursor: text;
background-color: field;
column-count: initial !important;
writing-mode: horizontal-tb !important;
box-sizing: border-box;
margin: 0em;
/* border-width: 1px; */
/* border-style: solid; */
/* border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); */
/* border-image: initial; */
padding: 5px;
}
.itemDetected {
background-color: rgb(240, 155, 155);
cursor: pointer;
}
.itemDetected:hover {
background-color: rgba(240, 155, 155, 0.583);
}
.lineNumberLog {
background-color: yellow;
}
.buttonOption {
/* position: "sticky"; */
/* top: 0; */
/* background-color: "white"; */
text-align: "center";
background-color: rgba(255, 0, 0, 0);
display: "flex";
padding: 0 10px 0 0;
color: white;
font-weight: 700;
border-left: 5px solid gray;
border-right: 5px solid gray;
}
.buttonOption span{
float: right;
}

View File

@ -0,0 +1,142 @@
import axios from "axios";
import React, { useEffect, useState } from "react";
import { Link, Navigate, useParams } from "react-router-dom";
import { getLog } from "../../api/apiLog";
import "./ShowLog.css";
const ShowLog = () => {
let { name } = useParams();
const [log, setLog] = useState({});
const [status, setStatus] = useState(200);
const getContentLog = async () => {
try {
const res = await axios.get(getLog + "/" + name);
setLog(res.data);
setStatus(res.status);
} catch (error) {
console.log(error);
}
};
const scrollToElement = () => {
const hash = window.location.hash;
if (hash) {
const targetElement = document.getElementById(hash.slice(1));
if (targetElement) {
targetElement.scrollIntoView({ behavior: "smooth" });
}
}
};
useEffect(() => {
getContentLog();
setTimeout(() => {
scrollToElement();
}, 3000);
}, []);
if (status === 200) {
return (
<div className="main">
<div className="buttonOption">
<Link to={"/"}>
<button
style={{
color: "white",
backgroundColor: "blue",
cursor: "pointer",
}}
>
Home
</button>
</Link>
<Link to={"/logs"}>
{" "}
<button
style={{
color: "white",
backgroundColor: "blue",
cursor: "pointer",
}}
>
List of detected files
</button>
</Link>
<span>{name}</span>
</div>
<div className="detectedDiv">
<h3
style={{
display:
log?.modelSpecial === "" && log?.issueItem === ""
? "block"
: "none",
}}
>
No errors were found in the file
</h3>
<h3 style={{ display: log?.modelSpecial !== "" ? "block" : "none" }}>
Extra items:
</h3>
{log?.modelSpecial?.split("\n")?.reverse().map((line) => (
<span>
<span className="lineNumberLog">{line.split("|-|")[0]}</span>
<span>{line.split("|-|")[1]}</span>
<span className="itemDetected">
<a
href={"#" + line.split("|-|")[0]}
style={{ textDecoration: "none", color: "black" }}
>
{line.split("|-|")[2]}
</a>
</span>
<span>{line.split("|-|")[3]}</span>
<br></br>
</span>
))}
<h3 style={{ display: log?.issueItem !== "" ? "block" : "none" }}>
Issue found:
</h3>
{log?.issueItem?.split("\n")?.reverse().map((line) => (
<span>
<span className="lineNumberLog">{line.split("|-|")[0]}</span>
<span>{line.split("|-|")[1]}</span>
<span className="itemDetected">
<a
href={"#" + line.split("|-|")[0]}
style={{ textDecoration: "none", color: "black" }}
>
{line.split("|-|")[2]}
</a>
</span>
<span>{line.split("|-|")[3]}</span>
<br></br>
</span>
))}
</div>
<div className="logContent">
{log?.contentFile?.split("\n")?.map((line) => (
<span>
<span className="lineNumberLog">{line.split("|-|")[0]}</span>
<span>{line.split("|-|")[1]}</span>
<span className="itemDetected">
<span id={line.split("|-|")[0]}>{line.split("|-|")[2]}</span>
</span>
<span>{line.split("|-|")[3]}</span>
<br></br>
</span>
))}
</div>
</div>
);
} else {
return (
<div>
<h1>
<i>The file was not found.</i>
</h1>
</div>
);
}
};
export default ShowLog;

View File

@ -3,12 +3,17 @@ import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter, Route, Routes } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
<BrowserRouter>
<Routes>
<Route path="*" element={<App />} />
</Routes>
</BrowserRouter>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function

View File

@ -1,10 +1,13 @@
import axios from "axios";
import React, { useEffect, useState } from "react";
import { addKeyValue, deleteValue, getKeyValues } from "../api/apiLog";
import { addKeyValue, deleteValue, editValue, getKeyValues } from "../api/apiLog";
import { Link } from "react-router-dom";
const ManageValues = () => {
const [keyValue, setKeyValue] = useState([]);
const [key, setKey] = useState([]);
const [addValue, setAddValue] = useState({key: "CATCH_FAULTY", value:""});
const [addValue, setAddValue] = useState({ key: "CATCH_FAULTY", value: "" });
const [inputSelect, setInpuSelect] = useState(0)
const [inputValue, setInputValue] = useState("")
const getValues = async () => {
try {
const res = await axios.post(getKeyValues);
@ -14,21 +17,22 @@ const ManageValues = () => {
console.log(error);
}
};
useEffect(() => {
getValues();
}, []);
console.log(inputValue)
return (
<div
style={{
display: "flex",
alignItems:"center",
flexFlow: "column"
alignItems: "center",
flexFlow: "column",
}}
>
<div style={{ height: "80vh", overflow: "auto" }}>
<table>
<thead style={{width:"100%"}}>
<thead style={{ width: "100%" }}>
<tr>
<th
style={{ position: "sticky", top: 0, backgroundColor: "white" }}
@ -36,7 +40,12 @@ const ManageValues = () => {
Key
</th>
<th
style={{ position: "sticky", top: 0, backgroundColor: "white", width:"400px" }}
style={{
position: "sticky",
top: 0,
backgroundColor: "white",
width: "400px",
}}
>
Value
</th>
@ -49,31 +58,99 @@ const ManageValues = () => {
</thead>
<tbody>
{keyValue?.map((value) => (
<tr style={{backgroundColor:value.key==="MODEL_SPECIAL"?"rgb(219 219 255 / 47%)":value.key==="CATCH_FAULTY"?"rgb(166 255 165 / 43%)":"rgb(253 189 152 / 41%)"}}>
<tr
style={{
backgroundColor:
value.key === "MODEL_SPECIAL"
? "rgb(219 219 255 / 47%)"
: value.key === "CATCH_FAULTY"
? "rgb(166 255 165 / 43%)"
: value.key === "MEMORY_DEFAULT"
? "rgb(253 244 52 / 41%)"
: "rgb(253 189 152 / 41%)",
}}
>
<td>{value.key}</td>
<td>
<input value={value.value} disabled style={{width:"100%"}}></input>
<input
value={inputSelect===value.id_key?inputValue:value.value}
disabled={inputSelect===value.id_key?false:true}
style={{ width: "100%" }}
onChange={(e)=>{
setInputValue(e.target.value)
}}
></input>
</td>
<td>
<button style={{cursor:"pointer", backgroundColor:"red", color:"white"}} onClick={async()=>{
const res = await axios.post(deleteValue, {id: value.id_key})
if(res.status !== 200){
alert(res.data)
}else{
<button
style={{
cursor: "pointer",
backgroundColor: "red",
color: "white",
}}
onClick={async () => {
const res = await axios.post(deleteValue, {
id: value.id_key,
});
if (res.status !== 200) {
alert(res.data);
} else {
getValues();
}
}}>Delete</button>
{/* <button style={{cursor:"pointer", backgroundColor:"green", color:"white"}}>Save</button> */}
}
}}
>
Delete
</button>
<button
style={{
cursor: "pointer",
backgroundColor: "yellow",
color: "black",
display:inputSelect===value.id_key?"none":"inline"
}}
onClick={async () => {
setInpuSelect(value.id_key)
setInputValue(value.value)
}}
>
Edit
</button>
<button
style={{
cursor: "pointer",
backgroundColor: "green",
color: "white",
display:inputSelect===value.id_key?"inline":"none"
}}
onClick={async () => {
setInpuSelect(0)
const res = await axios.post(editValue, {
id: value.id_key,
value: inputValue
});
if (res.status !== 200) {
alert(res.data);
} else {
getValues();
}
}}
>
Done
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
<div style={{ width: "50%", display:"flex", margin:10 }}>
<select style={{ width: "35%" }} onChange={(e)=>{
setAddValue({...addValue, key:e.target.value})
}}>
<div style={{ width: "50%", display: "flex", margin: 10 }}>
<select
style={{ width: "35%" }}
onChange={(e) => {
setAddValue({ ...addValue, key: e.target.value });
}}
>
{key
.filter((value, index, self) => {
return self.indexOf(value) === index;
@ -82,22 +159,51 @@ const ManageValues = () => {
<option value={u}>{u}</option>
))}
</select>
<input placeholder="value" style={{margin:"0 5px", width:"50%"}} onChange={(e)=>{
setAddValue({...addValue, value: e.target.value})
}}></input>
<button style={{cursor:"pointer", backgroundColor:"green", color:"white"}} onClick={async()=>{
if(addValue.key !=="" && addValue.value!==""){
const res = await axios.post(addKeyValue,{key: addValue.key, value: addValue.value})
if(res.status !== 200){
alert(res.data)
}else{
getValues();
}
}else{
alert("Value is empty!")
<input
placeholder="value"
style={{ margin: "0 5px", width: "50%" }}
onChange={(e) => {
setAddValue({ ...addValue, value: e.target.value });
}}
></input>
<button
style={{
cursor: "pointer",
backgroundColor: "green",
color: "white",
}}
onClick={async () => {
if (addValue.key !== "" && addValue.value !== "") {
const res = await axios.post(addKeyValue, {
key: addValue.key,
value: addValue.value,
});
if (res.status !== 200) {
alert(res.data);
} else {
getValues();
}
} else {
alert("Value is empty!");
}
}}>Add</button>
}}
>
Add
</button>
</div>
<div>
<Link to={"/logs"}>
{" "}
<button
style={{
color: "white",
backgroundColor: "blue",
cursor: "pointer",
}}
>
List of detected files
</button>
</Link>
</div>
</div>
);

3975
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -30,13 +30,20 @@
"axios": "^1.4.0",
"child_process": "^1.0.2",
"chokidar": "^3.5.3",
"dotenv": "^16.3.1",
"fs": "^0.0.1-security",
"helpers": "^0.0.6",
"jsonwebtoken": "^9.0.1",
"luxon": "^3.4.0",
"moment": "^2.29.4",
"mysql2": "^3.6.0",
"nodemailer": "^6.9.5",
"path": "^0.12.7",
"proxy-addr": "^2.0.7",
"puppeteer": "^21.2.1",
"reflect-metadata": "^0.1.13",
"socket.io": "^4.7.2",
"socket.io-client": "^4.7.2",
"source-map-support": "^0.5.21",
"zulip-js": "^2.0.9"
}

View File

@ -1,23 +1,28 @@
import type { ApplicationContract } from '@ioc:Adonis/Core/Application'
import type { ApplicationContract } from "@ioc:Adonis/Core/Application";
import io from "socket.io-client";
export default class AppProvider {
constructor (protected app: ApplicationContract) {
}
constructor(protected app: ApplicationContract) {}
public register () {
public register() {
// Register your own bindings
}
public async boot () {
public async boot() {
// IoC container is ready
}
public async ready () {
public async ready() {
// setInterval(() => {
// let socket = io("http://118.71.46.74:7777");
// socket?.emit("monitor", { name: "logs server", status: "I'm file" });
// }, 20000);
// if (this.app.environment === 'web') {
// await import('../start/socket')
// }
// App is ready
}
public async shutdown () {
public async shutdown() {
// Cleanup, since app is going down
}
}

334
screenshot.js Normal file
View File

@ -0,0 +1,334 @@
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]
// console.log(a.slice(0,4))
// const checkSpecialVersion = (paragraph) => {
// try {
// const regex = /\(CAT3K_CAA-UNIVERSALK9-M\), Version 16\.9\.[2-9]/;
// const regex1 = /\(CAT3K_CAA-UNIVERSALK9-M\), Version 1[7-9]\.[0-9]\.[2-9]/;
// const regex2 =
// /\(CAT3K_CAA-UNIVERSALK9-M\), Version [2-9][0-9]\.[0-9]\.[2-9]/;
// // Use the regular expression to find the match
// const match = paragraph.match(regex);
// const match1 = paragraph.match(regex1);
// const match2 = paragraph.match(regex2);
// if (match || match1 || match2) {
// if (match) {
// console.log(match[0]);
// }
// if (match1) {
// console.log(match1[0]);
// }
// if (match2) {
// console.log(match2[0]);
// }
// } else {
// return "";
// }
// } catch (error) {
// console.log(error);
// }
// };
// checkSpecialVersion(
// "Cisco IOS Software [Fuji], Catalyst L3 Switch Software (CAT3K_CAA-UNIVERSALK9-M), Version 16.9.1, RELEASE SOFTWARE (fc2)"
// );
// const puppeteer = require("puppeteer");
// const zulip = require("zulip-js");
// (async () => {
// const browser = await puppeteer.launch();
// const page = await browser.newPage();
// // Điều hướng đến trang web chứa thẻ <a>
// await page.goto("https://www.cskh.evnspc.vn/TraCuu/LichNgungGiamCungCapDien");
// // Tìm thẻ <a> cần click dựa trên selector CSS hoặc XPath
// const selectBoxSelector1 = "select#idCongTyDienLuc";
// await page.waitForSelector(selectBoxSelector1);
// await page.select(selectBoxSelector1, "PB11");
// // Chờ cho trang mới mở
// // await page.waitForNavigation('select#idCongTyDienLuc');
// // In ra nội dung của trang mới
// setTimeout(async () => {
// const tableData = await page.evaluate(() => {
// const tbody = document.querySelector("table"); // Lựa chọn thẻ <tbody> cần trích xuất
// const rows = tbody.querySelectorAll("tr"); // Lựa chọn tất cả các hàng (thẻ <tr>) bên trong thẻ <tbody>
// // const headerRow = document.querySelectorAll("thead"); // Lựa chọn tất cả các hàng (thẻ <tr>) bên trong thẻ <tbody>
// // Lấy tên các cột từ hàng đầu (thẻ <th>)
// // const headerColumns = headerRow.querySelectorAll("tr");
// // const columnNames = headerColumns.map((headerColumn) =>
// // headerColumn.textContent.trim()
// // );
// const data1 = [];
// // headerColumns.forEach((clo) => {
// // const columns = Array.from(clo.querySelectorAll("th")); // Lựa chọn tất cả các cột (thẻ <td>) trong hàng
// // const rowData = columns.map((column) => column.textContent.trim()); // Lấy nội dung của các cột và xóa khoảng trắng
// // data1.push(rowData); // Thêm dữ liệu của hàng vào mảng data
// // });
// // Lặp qua từng hàng và lấy nội dung của các cột (thẻ <td>) trong hàng
// const data = [];
// rows.forEach((row) => {
// const columns = Array.from(row.querySelectorAll("td")); // Lựa chọn tất cả các cột (thẻ <td>) trong hàng
// const headers = Array.from(row.querySelectorAll("th"));
// const rowHeader = headers.map((header) => header.textContent.trim());
// const rowData = columns.map((column) => column.textContent.trim()); // Lấy nội dung của các cột và xóa khoảng trắng
// data.push(rowData); // Thêm dữ liệu của hàng vào mảng data
// data1.push(rowHeader)
// });
// return { data: data, columnNames: data1 };
// });
// const content = []
// tableData.data?.map((u,index)=>{
// for(let i=0; i<u.length;i++){
// tableData.data[index] = tableData.columnNames[index]+": "+u[]
// }
// })
// console.log("Table data:", );
// await browser.close();
// }, 5000);
// })();
// console.log("data: ",
// data.paragraphText
// .split(" ")
// .filter((i) => i.includes("KDC 91B") || i.includes("KDC91B")))
// if (
// data.paragraphText
// .split(" ")
// .filter((i) => i.includes("KDC 91B") || i.includes("KDC91B")).length > 0
// ) {
// let params = {
// type: "stream",
// to: "Result test - auto.nswteam.net",
// topic: "Lịch cúp điện",
// content:
// ":warning: :date: :warning:\n" +
// data.paragraphText
// .split(" ")
// .filter((i) => i.includes("KDC 91B") || i.includes("KDC91B"))[0]?.replace(/ /g,"\n\n")?.replace(/KDC 91B/g,"**KDC 91B**") +
// "\n-------",
// };
// client.messages.send(params);
// }
// const zulip = require("zulip-js");
// const config = {
// zuliprc: "./download",
// zulipVersion: "v2",
// };
// async function deleteMessages() {
// const client = await zulip(config);
// // Thay thế "stream-name", "topic-name", và các mốc thời gian cụ thể
// const streamName = "Result test - auto.nswteam.net";
// const topicName = "test";
// try {
// const messages = await client.messages.retrieve({
// anchor: "oldest",
// num_before: 0,
// num_after: 5000, // Điều chỉnh theo nhu cầu của bạn
// narrow: [
// { operator: "stream", operand: streamName },
// { operator: "topic", operand: topicName },
// // {
// // operator: ,
// // operand: `169457100,1694571399`,
// // },
// ],
// });
// // console.log(messages.messages.map(u=>u.reactions))
// const members = await client.users.retrieve();
// // console.log(members.members)
// console.log(messages.messages.length)
// // await client.messages.deleteById([159454, 159455]);
// for (const message of messages.messages) {
// console.log(message.id)
// if (
// message.reactions.filter(
// (i) =>
// i.emoji_name === "working_on_it" &&
// members.members.filter((u) => u.user_id === i.user_id)[0]
// .is_admin === true
// ).length === 0 &&
// message.timestamp < Math.floor((Date.now() - 60000*60*24*10) / 1000)
// ) {
// const res = await client.messages.deleteById({
// message_id: message.id,
// });
// console.log(`Deleted message ID ${message.id}`);
// console.log(res)
// }
// }
// } catch (error) {
// console.error("Error:", error);
// }
// }
// deleteMessages();
// const zulip = require("zulip-js");
// const fs = require("fs");
// const config = {
// zuliprc: "./download",
// zulipVersion: "v2", // Use the appropriate API version
// };
// const imageFilePath = "./screenshot.png";
// const imageBase64 = fs.readFileSync(imageFilePath, { encoding: "base64" });
// async function send() {
// const client = await zulip(config);
// try {
// const message = {
// type: "stream",
// to: "Result test - auto.nswteam.net", // Replace with the target stream name or recipient email
// topic: "AU-dev", // Replace with the message topic
// content: "Check out this image:",
// filename: "asakfga",
// file: imageBase64
// };
// client.messages.sendFile(message).then((response) => {
// console.log("Message sent successfully:", response);
// });
// } catch (error) {
// console.error("Error:", error);
// }
// }
// send();
// Usage example
// const filePath = __dirname+'\\screenshot.png';
// uploadFileToZulip(filePath);
// const zulip = require('zulip-js');
// // Configure your Zulip API details
// const config = {
// username: 'joseph.le@apactech.io',
// apiKey: '7XGrpwzFtQyUVDQzdwL3hjdVSbLx55yt',
// realm: 'https://zulip.ipsupply.com.au',
// };
// async function uploadFileToZulip(filePath) {
// try {
// const client = await zulip(config);
// // Read the file as binary data
// const fs = require('fs');
// const fileData = fs.readFileSync(filePath);
// // Create a FormData object
// const formData = new FormData();
// formData.append('file', fileData);
// // Upload the file
// const response = await client.callEndpoint('POST', 'user_uploads', formData, {headers:{
// 'Content-Type': 'multipart/form-data',
// // other headers if needed
// }});
// // if (response.result === 'success') {
// // const uploadedFileURL = response.uri;
// // console.log('File uploaded successfully. URL:', uploadedFileURL);
// // } else {
// // console.error('Failed to upload file:', response.msg);
// // }
// } catch (error) {
// console.error('Error uploading file:', error);
// }
// }
// const filePath = 'screenshot.png'; // Replace with your file path
// uploadFileToZulip(filePath);
// const puppeteer = require("puppeteer");
// (async () => {
// const browser = await puppeteer.launch();
// // Store the endpoint to be able to reconnect to the browser.
// const browserWSEndpoint = browser.wsEndpoint("https://pptr.dev/api/puppeteer.browser");
// // Disconnect puppeteer from the browser.
// browser.disconnect();
// // Use the endpoint to reestablish a connection
// const browser2 = await puppeteer.connect({browserWSEndpoint});
// // Close the browser.
// await browser2.close();
// })();
// const zulip = require("zulip-js");
// (async () => {
// const config = {
// username: "networktool-bot@zulip.ipsupply.com.au",
// apiKey: "0jMAmOuhfLvBqKJikv5oAkyNM4RIEoAM",
// realm: "https://zulip.ipsupply.com.au",
// };
// const client = await zulip(config);
// const user_id = 45;
// let params = {
// to: "joseph.le@apactech.io",
// type: "private",
// content: "With mirth and laughter let old wrinkles come.",
// };
// console.log(await client.messages.send(params))
// })()
// (async()=>{
// let listLog = []
// let from = 20230926
// let to = 20230926
// const response = await axios.get("http://192.168.5.7:8080/");
// const responseAUTO = await axios.get(
// "http://192.168.5.7:8080/AUTOlog/"
// );
// let data1 = response.data.split("\n")
// .filter((i) => i.search("<a href") !== -1 && i.search(".log") !== -1);
// let data2 = responseAUTO.data.split("\n")
// .filter((i) => i.search("<a href") !== -1 && i.search(".log") !== -1);
// const arrayLine = data1.concat(data2)
// // const arrayLineAUTO = data
// // .split("\n")
// // .filter((i) => i.search("<a href") !== -1 && i.search(".log") !== -1);
// arrayLine.map((u) => {
// let temp = u
// .slice(u.search("<a ") + 9, u.search("</a>"))
// .split(">")[1];
// if (
// parseInt(temp?.split("-")[0]) >= from &&
// parseInt(temp?.split("-")[0]) <= to
// ) {
// listLog.push(
// (u.slice(u.search("<a ") + 9, u.search("</a>")).split(">")[1].includes("AUTO")?"http://192.168.5.7:8080/AUTOlog/":"http://192.168.5.7:8080/") +
// u.slice(u.search("<a ") + 9, u.search("</a>")).split(">")[1] +
// " "
// );
// }
// });
// console.log(listLog)
// })()

BIN
screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

View File

@ -10,7 +10,6 @@
*/
import Server from '@ioc:Adonis/Core/Server'
/*
|--------------------------------------------------------------------------
| Global middleware
@ -21,7 +20,7 @@ import Server from '@ioc:Adonis/Core/Server'
|
*/
Server.middleware.register([
() => import('@ioc:Adonis/Core/BodyParser'),
() => import('@ioc:Adonis/Core/BodyParser')
])
/*
@ -42,4 +41,5 @@ Server.middleware.register([
*/
Server.middleware.registerNamed({
checkToken: () => import('App/Middleware/CheckToken'),
writeLog: () => import('App/Middleware/Logger')
})

View File

@ -1,203 +0,0 @@
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 LogDetectFile from "App/Models/LogDetectFile";
import { runtimeCheckLogs } from "App/utils/runtimeCheckLogs";
import Env from "@ioc:Adonis/Core/Env";
import KeyValue from "App/Models/KeyValue";
import ErpsController from "App/Controllers/Http/ErpsController";
import LogReport from "App/Models/LogReport";
import Database from "@ioc:Adonis/Lucid/Database";
import { exec } from "child_process";
runtimeCheckLogs(Env.get("FOLDER_LOGS"));
// Route.get("/api/list", async () => {
// const a = await LogDetectFile.all();
// return a;
// });
//ERP get index serial number
Route.post(
"/api/getIndexSerialNumber",
"ErpsController.getIndexSerialNumber"
).middleware("checkToken");
Route.post("/api/getParagraph", "ErpsController.getParagraph").middleware(
"checkToken"
);
//Users
Route.post("/api/account/createUser", "UsersController.create");
Route.post("/api/account/checkLogin", "UsersController.checkLogin");
//Log
Route.get("/api/log/showLog/:name?", async ({ request, response }) => {
try {
let fileDetect = await LogDetectFile.findBy(
"file_name",
request.params().name
);
let logsDetect = await Database.rawQuery(
"select * from log_reports where id_file = " + fileDetect?.id_ldf
);
let detectedLines = [];
let listLine = logsDetect[0]
.map((obj) => obj.line)
.filter((value, index, self) => {
return self.indexOf(value) === index;
})
.sort((a, b) => a - b);
const content = await axios.get(
"http://192.168.5.7:8080/" + request.params().name
);
let allValue = await KeyValue.all();
let listKeyValues = allValue.filter(
(i) =>
i.$original.key === "MODEL_SPECIAL" ||
i.$original.key === "CATCH_FAULTY"
);
let data = content.data.split("\n");
data.map((line, index) => {
data[index] =
"<span style='background-color:pink;'>" +
(index + 1) +
"</span>" +
line;
listKeyValues
.map((obj) => obj.$original.value)
.map(async (value) => {
if (line.search(value) !== -1) {
data[index] =
data[index].slice(0, data[index].search(value)) +
"<span style='background-color:yellow;'>" +
value +
"</span>" +
data[index].slice(data[index].search(value) + value.length);
// }
}
});
});
listLine.map((u) => {
detectedLines.push(data[u - 1]);
});
// console.log(data)
response.send(
"<html>\
<body>\
<div style='width:100%;height:100%;word-wrap:break-word;white-space:pre;overflow: auto;font-family: monospace;text-rendering: auto;\
color: fieldtext;\
letter-spacing: normal;\
word-spacing: normal;\
line-height: normal;\
text-transform: none;\
text-indent: 0px;\
text-shadow: none;\
display: inline-block;\
text-align: start;\
appearance: auto;\
-webkit-rtl-ordering: logical;\
resize: auto;\
cursor: text;\
background-color: field;\
column-count: initial !important;\
writing-mode: horizontal-tb !important;\
box-sizing: border-box;\
margin: 0em;\
border-width: 1px;\
border-style: solid;\
border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133));\
border-image: initial;\
padding: 2px;'>" +
"<b>Detected lines in file:</b>\n" +
detectedLines.join("\n") +
"\n\n" +
data.join("\n") +
"</div>\
</body>\
</html>"
);
} catch (error) {
response.send("<h1>-------------- File not found --------------</h1>");
}
});
//Key-Value
Route.post("/api/getKeyValue", async ({ request, response }) => {
let data = await KeyValue.all();
response.status(200).send(data);
});
Route.post("/api/deleteValue", async ({ request, response }) => {
try {
const value = await KeyValue.findOrFail(request.all().id);
await value.delete();
response.status(200).send("DELETE VALUE SUCCESS!");
} catch (error) {
response.status(500).send("DELETE VALUE FAIL!");
}
});
Route.post("/api/addValue", async ({ request, response }) => {
try {
const value = await KeyValue.create({
key: request.all().key,
value: request.all().value,
model: "All",
});
response.status(200).send("ADD VALUE SUCCESS!");
} catch (error) {
response.status(500).send("ADD VALUE FAIL!");
}
});
Route.post("/api/gitea-webhook", ({ request, response }) => {
// Kiểm tra xem đó có phải sự kiện bạn muốn xử lý không
// if (request.headers['x-gitlab-event'] === 'push') {
// // Lấy dữ liệu sự kiện từ req.body
// const eventData = req.body;
// // Xử lý dữ liệu sự kiện ở đây
// console.log('Received push event from GitLab:');
// console.log(JSON.stringify(eventData, null, 2));
// }
console.log(request.headers());
console.log(request.all());
console.log("first3215423")
console.log("New event ---> ", request.header('x-gitea-event'));
// exec(
// "/home/joseph/adonis-gitlab-webhook/gitea.sh",
// (error, stdout, stderr) => {
// if (error) {
// console.error(`Error executing command: ${error}`);
// return;
// }
// console.log(`Command output:\n${stdout}`);
// }
// );
});

13
start/socket.ts Normal file
View File

@ -0,0 +1,13 @@
import Ws from 'App/Services/Ws'
Ws.boot()
/**
* Listen for incoming socket connections
*/
Ws.io.on('connection', (socket) => {
socket.emit('news', { hello: 'world' })
socket.on('my other event', (data) => {
console.log(data)
})
})

3
uploads/abc.txt Normal file
View File

@ -0,0 +1,3 @@
sdfsdf
dfgdfg
dfgdf

4
zuliprc Normal file
View File

@ -0,0 +1,4 @@
[api]
email=networktool-bot@zulip.ipsupply.com.au
key=0jMAmOuhfLvBqKJikv5oAkyNM4RIEoAM
site=https://zulip.ipsupply.com.au