add config for webhook
This commit is contained in:
1 parent
c008d2e046
commit
5018a2dfde
1 file changed
+94
-79
@@ -1,11 +1,12 @@
|
|||||||
const SERVICE_NAME = "NotificationService";
|
const SERVICE_NAME = "NotificationService";
|
||||||
const TELEGRAM_API_BASE_URL = "https://api.telegram.org/bot";
|
const TELEGRAM_API_BASE_URL = "https://api.telegram.org/bot";
|
||||||
const PLATFORM_TYPES = ["telegram", "slack", "discord"];
|
const PLATFORM_TYPES = ["telegram", "slack", "discord", "webhook"];
|
||||||
|
|
||||||
const MESSAGE_FORMATTERS = {
|
const MESSAGE_FORMATTERS = {
|
||||||
telegram: (messageText, chatId) => ({ chat_id: chatId, text: messageText }),
|
telegram: (messageText, chatId) => ({ chat_id: chatId, text: messageText }),
|
||||||
slack: (messageText) => ({ text: messageText }),
|
slack: (messageText) => ({ text: messageText }),
|
||||||
discord: (messageText) => ({ content: messageText }),
|
discord: (messageText) => ({ content: messageText }),
|
||||||
|
webhook: (messageText) => ({ text: messageText }),
|
||||||
};
|
};
|
||||||
|
|
||||||
class NotificationService {
|
class NotificationService {
|
||||||
@@ -42,49 +43,57 @@ class NotificationService {
|
|||||||
formatNotificationMessage(monitor, status, platform, chatId, code, timestamp) {
|
formatNotificationMessage(monitor, status, platform, chatId, code, timestamp) {
|
||||||
// Format timestamp using the local system timezone
|
// Format timestamp using the local system timezone
|
||||||
const formatTime = (timestamp) => {
|
const formatTime = (timestamp) => {
|
||||||
const date = new Date(timestamp);
|
const date = new Date(timestamp);
|
||||||
|
|
||||||
// Get timezone abbreviation and format the date
|
// Get timezone abbreviation and format the date
|
||||||
const timeZoneAbbr = date.toLocaleTimeString('en-US', { timeZoneName: 'short' })
|
const timeZoneAbbr = date
|
||||||
.split(' ').pop();
|
.toLocaleTimeString("en-US", { timeZoneName: "short" })
|
||||||
|
.split(" ")
|
||||||
|
.pop();
|
||||||
|
|
||||||
// Format the date with readable format
|
// Format the date with readable format
|
||||||
return date.toLocaleString('en-US', {
|
return (
|
||||||
year: 'numeric',
|
date
|
||||||
month: '2-digit',
|
.toLocaleString("en-US", {
|
||||||
day: '2-digit',
|
year: "numeric",
|
||||||
hour: '2-digit',
|
month: "2-digit",
|
||||||
minute: '2-digit',
|
day: "2-digit",
|
||||||
second: '2-digit',
|
hour: "2-digit",
|
||||||
hour12: false
|
minute: "2-digit",
|
||||||
}).replace(/(\d+)\/(\d+)\/(\d+),\s/, '$3-$1-$2 ') + ' ' + timeZoneAbbr;
|
second: "2-digit",
|
||||||
|
hour12: false,
|
||||||
|
})
|
||||||
|
.replace(/(\d+)\/(\d+)\/(\d+),\s/, "$3-$1-$2 ") +
|
||||||
|
" " +
|
||||||
|
timeZoneAbbr
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get formatted time
|
// Get formatted time
|
||||||
const formattedTime = timestamp
|
const formattedTime = timestamp
|
||||||
? formatTime(timestamp)
|
? formatTime(timestamp)
|
||||||
: formatTime(new Date().getTime());
|
: formatTime(new Date().getTime());
|
||||||
|
|
||||||
// Create different messages based on status with extra spacing
|
// Create different messages based on status with extra spacing
|
||||||
let messageText;
|
let messageText;
|
||||||
if (status === true) {
|
if (status === true) {
|
||||||
messageText = this.stringService.monitorUpAlert
|
messageText = this.stringService.monitorUpAlert
|
||||||
.replace("{monitorName}", monitor.name)
|
.replace("{monitorName}", monitor.name)
|
||||||
.replace("{time}", formattedTime)
|
.replace("{time}", formattedTime)
|
||||||
.replace("{code}", code || 'Unknown');
|
.replace("{code}", code || "Unknown");
|
||||||
} else {
|
} else {
|
||||||
messageText = this.stringService.monitorDownAlert
|
messageText = this.stringService.monitorDownAlert
|
||||||
.replace("{monitorName}", monitor.name)
|
.replace("{monitorName}", monitor.name)
|
||||||
.replace("{time}", formattedTime)
|
.replace("{time}", formattedTime)
|
||||||
.replace("{code}", code || 'Unknown');
|
.replace("{code}", code || "Unknown");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!PLATFORM_TYPES.includes(platform)) {
|
if (!PLATFORM_TYPES.includes(platform)) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
return MESSAGE_FORMATTERS[platform](messageText, chatId);
|
return MESSAGE_FORMATTERS[platform](messageText, chatId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends a webhook notification to a specified platform.
|
* Sends a webhook notification to a specified platform.
|
||||||
@@ -108,53 +117,53 @@ class NotificationService {
|
|||||||
|
|
||||||
// Early return if platform is not supported
|
// Early return if platform is not supported
|
||||||
if (!PLATFORM_TYPES.includes(platform)) {
|
if (!PLATFORM_TYPES.includes(platform)) {
|
||||||
this.logger.warn({
|
this.logger.warn({
|
||||||
message: this.stringService.getWebhookUnsupportedPlatform(platform),
|
message: this.stringService.getWebhookUnsupportedPlatform(platform),
|
||||||
service: this.SERVICE_NAME,
|
service: this.SERVICE_NAME,
|
||||||
method: "sendWebhookNotification",
|
method: "sendWebhookNotification",
|
||||||
details: { platform }
|
details: { platform },
|
||||||
});
|
});
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Early return for telegram if required fields are missing
|
// Early return for telegram if required fields are missing
|
||||||
if (platform === "telegram" && (!botToken || !chatId)) {
|
if (platform === "telegram" && (!botToken || !chatId)) {
|
||||||
this.logger.warn({
|
this.logger.warn({
|
||||||
message: "Missing required fields for Telegram notification",
|
message: "Missing required fields for Telegram notification",
|
||||||
service: this.SERVICE_NAME,
|
service: this.SERVICE_NAME,
|
||||||
method: "sendWebhookNotification",
|
method: "sendWebhookNotification",
|
||||||
details: { platform }
|
details: { platform },
|
||||||
});
|
});
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
let url = webhookUrl;
|
let url = webhookUrl;
|
||||||
if (platform === "telegram") {
|
if (platform === "telegram") {
|
||||||
url = `${TELEGRAM_API_BASE_URL}${botToken}/sendMessage`;
|
url = `${TELEGRAM_API_BASE_URL}${botToken}/sendMessage`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = this.formatNotificationMessage(
|
const message = this.formatNotificationMessage(
|
||||||
monitor,
|
monitor,
|
||||||
status,
|
status,
|
||||||
platform,
|
platform,
|
||||||
chatId,
|
chatId,
|
||||||
code, // Pass the code field directly
|
code, // Pass the code field directly
|
||||||
networkResponse.timestamp
|
networkResponse.timestamp
|
||||||
);
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await this.networkService.requestWebhook(platform, url, message);
|
const response = await this.networkService.requestWebhook(platform, url, message);
|
||||||
return response.status;
|
return response.status;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
message: this.stringService.getWebhookSendError(platform),
|
message: this.stringService.getWebhookSendError(platform),
|
||||||
service: this.SERVICE_NAME,
|
service: this.SERVICE_NAME,
|
||||||
method: "sendWebhookNotification",
|
method: "sendWebhookNotification",
|
||||||
stack: error.stack,
|
stack: error.stack,
|
||||||
});
|
});
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends an email notification for hardware infrastructure alerts
|
* Sends an email notification for hardware infrastructure alerts
|
||||||
@@ -197,33 +206,33 @@ class NotificationService {
|
|||||||
|
|
||||||
async handleStatusNotifications(networkResponse) {
|
async handleStatusNotifications(networkResponse) {
|
||||||
try {
|
try {
|
||||||
// If status hasn't changed, we're done
|
// If status hasn't changed, we're done
|
||||||
if (networkResponse.statusChanged === false) return false;
|
if (networkResponse.statusChanged === false) return false;
|
||||||
// if prevStatus is undefined, monitor is resuming, we're done
|
// if prevStatus is undefined, monitor is resuming, we're done
|
||||||
if (networkResponse.prevStatus === undefined) return false;
|
if (networkResponse.prevStatus === undefined) return false;
|
||||||
|
|
||||||
const notifications = await this.db.getNotificationsByMonitorId(
|
const notifications = await this.db.getNotificationsByMonitorId(
|
||||||
networkResponse.monitorId
|
networkResponse.monitorId
|
||||||
);
|
);
|
||||||
|
|
||||||
for (const notification of notifications) {
|
for (const notification of notifications) {
|
||||||
if (notification.type === "email") {
|
if (notification.type === "email") {
|
||||||
await this.sendEmail(networkResponse, notification.address);
|
await this.sendEmail(networkResponse, notification.address);
|
||||||
} else if (notification.type === "webhook") {
|
} else if (notification.type === "webhook") {
|
||||||
await this.sendWebhookNotification(networkResponse, notification);
|
await this.sendWebhookNotification(networkResponse, notification);
|
||||||
|
}
|
||||||
|
// Handle other types of notifications here
|
||||||
}
|
}
|
||||||
// Handle other types of notifications here
|
return true;
|
||||||
}
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
message: error.message,
|
message: error.message,
|
||||||
service: this.SERVICE_NAME,
|
service: this.SERVICE_NAME,
|
||||||
method: "handleNotifications",
|
method: "handleNotifications",
|
||||||
stack: error.stack,
|
stack: error.stack,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Handles status change notifications for a monitor
|
* Handles status change notifications for a monitor
|
||||||
*
|
*
|
||||||
@@ -257,7 +266,13 @@ class NotificationService {
|
|||||||
const alerts = {
|
const alerts = {
|
||||||
cpu: cpuThreshold !== -1 && cpuUsage > cpuThreshold ? true : false,
|
cpu: cpuThreshold !== -1 && cpuUsage > cpuThreshold ? true : false,
|
||||||
memory: memoryThreshold !== -1 && memoryUsage > memoryThreshold ? true : false,
|
memory: memoryThreshold !== -1 && memoryUsage > memoryThreshold ? true : false,
|
||||||
disk: disk?.some(d => diskThreshold !== -1 && typeof d?.usage_percent === "number" && d?.usage_percent > diskThreshold) ?? false,
|
disk:
|
||||||
|
disk?.some(
|
||||||
|
(d) =>
|
||||||
|
diskThreshold !== -1 &&
|
||||||
|
typeof d?.usage_percent === "number" &&
|
||||||
|
d?.usage_percent > diskThreshold
|
||||||
|
) ?? false,
|
||||||
};
|
};
|
||||||
|
|
||||||
const notifications = await this.db.getNotificationsByMonitorId(
|
const notifications = await this.db.getNotificationsByMonitorId(
|
||||||
|
|||||||
Reference in new issue
Block a user