upgrade logic

This commit is contained in:
joseph le 2025-04-03 09:27:56 +07:00
parent 7303a9c7c8
commit d8b569b5e8
5 changed files with 159 additions and 156 deletions

209
index.js
View File

@ -3,138 +3,111 @@ const express = require("express");
const app = express(); const app = express();
const { exec } = require("child_process"); const { exec } = require("child_process");
const nodeMailer = require("nodemailer"); const nodeMailer = require("nodemailer");
// Read configuration file
const contentFile = fs.readFileSync("./service_run/giteaService.conf", "utf8"); const contentFile = fs.readFileSync("./service_run/giteaService.conf", "utf8");
let checkStatus = "ready" let checkStatus = "ready";
// const checkFile = fs.readFileSync("./service_run/checkFile", "utf8");
// Get port from configuration file
const PORT = contentFile const PORT = contentFile
.split("\n") .split("\n")
.filter((i) => i.includes("PORT_SERVICE"))[0] .find(line => line.includes("PORT_SERVICE"))
?.split("=")[1]
.trim() || 5000;
// Get email configuration from config file
const getConfigValue = (key) => contentFile
.split("\n")
.find(line => line.includes(key))
?.split("=")[1] ?.split("=")[1]
.trim(); .trim();
// Configure email transporter
const createTransporter = () => nodeMailer.createTransport({
pool: true,
host: "mail.apactech.io",
port: 465,
secure: true,
auth: {
user: "admin@apactech.io",
pass: "BGK!dyt6upd2eax1bhz",
},
});
app.use(express.json()); app.use(express.json());
app.post("/git/gitea-webhook", async (req, res) => { app.post("/git/gitea-webhook", async (req, res) => {
let title = ""; let title = "";
const checkSendMail = getConfigValue("SEND_EMAIL");
const checkSendMail = contentFile const emailAddress = getConfigValue("EMAIL_ADDRESS");
.split("\n")
.filter((i) => i.includes("SEND_EMAIL"))[0]
?.split("=")[1]
.trim();
const emailAddress = contentFile
.split("\n")
.filter((i) => i.includes("EMAIL_ADDRESS"))[0]
?.split("=")[1]
.trim();
const FE_Path = contentFile
.split("\n")
.filter((i) => i.includes("FE_PROJECT_PATH"))[0]
?.split("=")[1]
.trim();
const giteaEvent = req.headers["x-gitea-event"]; const giteaEvent = req.headers["x-gitea-event"];
const body = req.body; // Return response immediately
//console.log(body) res.status(200).send({ mess: "The event has been received!", data: req.body });
res console.log("STATUS:", checkStatus);
.status(200)
.send({ mess: "The event has been received!", data: req.body }); // Check if there is a running process
console.log("CHECK FILE", checkStatus);
if (checkStatus === "busy") { if (checkStatus === "busy") {
const transporter = nodeMailer.createTransport({ if (checkSendMail === "True") {
pool: true, const transporter = createTransporter();
host: "mail.ipsupply.com.au", const options = {
port: 465, from: "admin@apactech.io",
secure: true, to: emailAddress,
auth: { subject: "Git notifications (Fail)",
user: "admin@apactech.io", html: "<h3>There is an active build process. Please check and push again in a few minutes.</h3>",
pass: "BGK!dyt6upd2eax1bhz", };
}, return transporter.sendMail(options);
}); }
return;
const options = {
from: "admin@apactech.io",
to: emailAddress,
subject: "Git notifications (Fail)",
html:
"<h3>There is an active build process in the " +
FE_Path +
" directory. Please check and push again in a few minutes.</h3>",
};
return transporter.sendMail(options);
} else {
console.log("New event: " + giteaEvent);
// fs.writeFileSync("./service_run/checkFile", "true");
checkStatus="busy"
exec("./service_run/giteaHook.sh", (error, stdout, stderr) => {
let content = stdout !== "" ? stdout : stderr;
if (error) {
console.log("Pull failed. Please check");
console.log(`Error executing command: ${error}`);
title += "New Git envent: " + giteaEvent;
} else {
console.log(stdout);
if (
stderr.includes("Error") ||
stderr.includes("failed") ||
stdout.includes("Error") ||
stdout.includes("failed")
) {
title += "New Git envent: " + giteaEvent;
} else {
title += "New Git envent: " + giteaEvent + "(success)";
}
setTimeout(() => {
checkStatus="ready"
// fs.writeFileSync("./service_run/checkFile", "false");
}, 10000);
}
if (checkSendMail === "True") {
const transporter = nodeMailer.createTransport({
pool: true,
host: "mail.ipsupply.com.au",
port: 465,
secure: true,
auth: {
user: "admin@apactech.io",
pass: "BGK!dyt6upd2eax1bhz",
},
});
const options = {
from: "admin@apactech.io",
to: emailAddress,
subject: title,
html:
"<h1>*** " +
giteaEvent +
" event ***</h1><h4>Committer: " +
req.body.commits[0]?.committer.name +
"</h4><h4>Message: " +
req.body.commits[0]?.message +
"</h4><h4>Branch: " +
req.body.ref +
"</h4><a href='" +
req.body.commits[0]?.url +
"'>Link: " +
req.body.commits[0]?.url +
"</a><h4>Process output:</h4><textarea style='wordWrap:break-word; display: block; width:100%; height:70vh;border:solid 2px orange'>" +
content +
"</textarea>",
};
return transporter.sendMail(options);
}
});
} }
// Process new event
console.log("New event: " + giteaEvent);
checkStatus = "busy";
exec("./service_run/giteaHook.sh", (error, stdout, stderr) => {
let content = stdout || stderr;
if (error) {
console.log("Pull failed. Please check");
console.log(`Error executing command: ${error}`);
title = `New Git event: ${giteaEvent}`;
} else {
console.log(stdout);
const hasError = [stderr, stdout].some(output =>
output && (output.includes("Error") || output.includes("failed"))
);
title = `New Git event: ${giteaEvent}${hasError ? "" : " (success)"}`;
// Reset status after 10 seconds
setTimeout(() => {
checkStatus = "ready";
}, 10000);
}
// Send notification email if configured
if (checkSendMail === "True") {
const transporter = createTransporter();
const options = {
from: "admin@apactech.io",
to: emailAddress,
subject: title,
html: `
<h1>*** ${giteaEvent} event ***</h1>
<h4>Committer: ${req.body.commits[0]?.committer.name || "N/A"}</h4>
<h4>Message: ${req.body.commits[0]?.message || "N/A"}</h4>
<h4>Branch: ${req.body.ref || "N/A"}</h4>
${req.body.commits[0]?.url ? `<a href='${req.body.commits[0].url}'>Link: ${req.body.commits[0].url}</a>` : ""}
<h4>Process output:</h4>
<textarea style='wordWrap:break-word; display: block; width:100%; height:70vh;border:solid 2px orange'>${content.replace(/error|fail|warning/gi, match => `<span style="background-color:yellow;color:red;font-weight:bold">${match}</span>`)}</textarea>
`,
};
return transporter.sendMail(options);
}
});
}); });
app.listen(PORT, () => { app.listen(PORT, () => {
console.log("Service is running on port ", PORT); console.log("Service is running on port", PORT);
}); });

View File

@ -49,14 +49,14 @@ else
echo "" && echo "" &&
echo "$result" && echo "$result" &&
output=$(echo "$result" | grep "|" | awk -F "|" '{gsub(/ /, "", $1); print $1}') && output=$(echo "$result" | grep "|" | awk -F "|" '{gsub(/ /, "", $1); print $1}') &&
while IFS= read -r line; do # while IFS= read -r line; do
if [[ $line != "" && $(find "$project" | grep "$line" | grep -q "$FE_PROJECT_PATH"; echo $?) -eq 0 ]]; then # if [[ $line != "" && $(find "$project" | grep "$line" | grep -q "$FE_PROJECT_PATH"; echo $?) -eq 0 ]]; then
echo "$line ton tai" && # echo "$line ton tai" &&
check="true" # check="true"
else # else
echo "$line ko ton tai" # echo "$line ko ton tai"
fi # fi
done <<< "$output" # done <<< "$output"
# process_ids=$(ps aux | grep "$FE_PROJECT_PATH" | grep "build" | grep -v grep | awk '{print $2}') && # process_ids=$(ps aux | grep "$FE_PROJECT_PATH" | grep "build" | grep -v grep | awk '{print $2}') &&
# #
@ -82,25 +82,25 @@ else
# #
# fi # fi
if [[ $check == "true" ]]; then # if [[ $check == "true" ]]; then
echo "|--------------------------------------------------------|" # echo "|--------------------------------------------------------|"
echo "|***** THERE ARE CHANGES INSIDE FOLDER $FE_PROJECT_PATH *****|" # echo "|***** THERE ARE CHANGES INSIDE FOLDER $FE_PROJECT_PATH *****|"
echo "|--------------------------------------------------------|" # echo "|--------------------------------------------------------|"
echo "|---------------|" # echo "|---------------|"
echo "|*** INSTALL ***|" # echo "|*** INSTALL ***|"
echo "|---------------|" # echo "|---------------|"
cd $FE_PROJECT_PATH && # cd $FE_PROJECT_PATH &&
npm install -f # npm install -f
echo "|-------------|" # echo "|-------------|"
echo "|*** BUILD ***|" # echo "|*** BUILD ***|"
echo "|-------------|" # echo "|-------------|"
npm run build && # npm run build &&
cp -rf $FE_PROJECT_PATH/build/* $FE_ROOT_FOLDER_PATH # cp -rf $FE_PROJECT_PATH/build/* $FE_ROOT_FOLDER_PATH
fi # fi
echo "|----------------------|" echo "|----------------------|"
echo "|*** UPDATE LIBRARY ***|" echo "|*** UPDATE LIBRARY ***|"

View File

@ -22,14 +22,6 @@ SEND_EMAIL=True
# Example: /home/My_project/ # Example: /home/My_project/
PROJECT_PATH=</project/directory/path> PROJECT_PATH=</project/directory/path>
# URL of front-end directory(*)
# Example: /home/My_project/FE_directory
FE_PROJECT_PATH=</FE/directory/path>
# URL of front-end public directory (*)
# Example: /var/www/html
FE_ROOT_FOLDER_PATH=</FE/public/directory/path>
# #
# It is possible to add many other directory besides the front-end directory # It is possible to add many other directory besides the front-end directory
# #
@ -39,6 +31,10 @@ FE_ROOT_FOLDER_PATH=</FE/public/directory/path>
# #
# Example: # Example:
# URL of FE directory(*)
#FE_PROCESS_PATH=/home/My_project/FE_directory
#FE_PROCESS_PATH_COMMAND=npm install -f && npm run build && cp -rf /home/My_project/FE_directory/build/* /var/www/html
# URL of back-end directory(*) # URL of back-end directory(*)
#BE_PROCESS_PATH=/home/My_project/BE_directory #BE_PROCESS_PATH=/home/My_project/BE_directory
#BE_PROCESS_PATH_COMMAND=npm install && echo "\n" && echo "BACK_END" #BE_PROCESS_PATH_COMMAND=npm install && echo "\n" && echo "BACK_END"

View File

@ -18,11 +18,12 @@ SET_ORIGIN=$(git remote set-url origin $REPOSITORY_AUTH) &&
# Ki?m tra xem Node.js đ? cài đ?t chưa # Ki?m tra xem Node.js đ? cài đ?t chưa
if ! command -v node &> /dev/null; then if ! command -v node &> /dev/null; then
echo -e "\e[31mNode.js is not installed.\e[0m" # echo -e "\e[31mNode.js is not installed.\e[0m"
echo -e "\e[32mInstall Node.js...\e[0m" # echo -e "\e[32mInstall Node.js...\e[0m"
curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - && # curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - &&
sudo apt-get install nodejs -y && # sudo apt-get install nodejs -y &&
node -v echo -e "\e[41mNodejs is not install\e[0m"
exit 1
else else
echo -e "\e[32mNodejs is installed!\e[0m" && echo -e "\e[32mNodejs is installed!\e[0m" &&
node -v node -v
@ -30,8 +31,8 @@ fi
# Ki?m tra xem npm đ? cài đ?t chưa # Ki?m tra xem npm đ? cài đ?t chưa
if ! command -v npm &> /dev/null; then if ! command -v npm &> /dev/null; then
echo -e "\e[31mnpm is not installed. Install npm...\e[0m" echo -e "\e[41mNPM is not install\e[0m"
sudo apt-get install npm -y exit 1
else else
echo -e "\e[32mnpm is installed!\e[0m" && echo -e "\e[32mnpm is installed!\e[0m" &&
npm -v npm -v

33
test.js Normal file
View File

@ -0,0 +1,33 @@
const nodeMailer = require("nodemailer");
// Configure email transporter
const transporter = nodeMailer.createTransport({
pool: true,
host: "mail.apactech.io",
port: 465,
secure: true,
auth: {
user: "admin@apactech.io",
pass: "BGK!dyt6upd2eax1bhz",
},
});
// const transporter = createTransporter();
const options = {
from: "admin@apactech.io",
to: "joseph@apactech.io",
subject: "Test",
html: `
<h1>*** event ***</h1>
<h4>Committer: N/A</h4>
<h4>Message: N/A</h4>
<h4>Branch: N/A</h4>
<h4>Process output:</h4>
<textarea style='wordWrap:break-word; display: block; width:100%; height:70vh;border:solid 2px orange'>N/A</textarea>
`,
};
transporter.sendMail(options);
console.log("first")