A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
import { BackupCompletionStats, BackupTaskStats, ReplicationFailureInfo } from '../types/backups';
import { PlanFull } from '../types/plans';
import { INotificationChannelResolver, PushNotificationPayload } from '../types/notifications';
import { BackupStartedNotification } from './templates/email/backup/BackupStartedNotification';
import { BackupSuccessNotification } from './templates/email/backup/BackupSuccessNotification';
import { BackupFailedNotification } from './templates/email/backup/BackupFailedNotification';
import { ReplicationFailedNotification } from './templates/email/backup/ReplicationFailedNotification';
import { planLogger } from '../utils/logger';
import { NotificationChannelResolver } from '../notifications/channels/NotificationChannelResolver';
import { SlackChannel } from '../notifications/channels/SlackChannel';
import { DiscordChannel } from '../notifications/channels/DiscordChannel';
import { configService } from '../services/ConfigService';
interface BackupDataType {
id?: string;
startTime?: Date;
endTime?: Date;
error?: string;
stats?: BackupTaskStats | BackupCompletionStats;
replicationFailures?: ReplicationFailureInfo[];
}
type NotificationType = 'start' | 'end' | 'success' | 'failure' | 'replication_failure';
export class BackupNotification {
protected BackupStartedNotificationClass = BackupStartedNotification;
protected BackupSuccessNotificationClass = BackupSuccessNotification;
protected BackupFailedNotificationClass = BackupFailedNotification;
protected ReplicationFailedNotificationClass = ReplicationFailedNotification;
protected notificationChannelResolver: INotificationChannelResolver = NotificationChannelResolver;
shouldSend(notificationCase: string, notificationType: string) {
return (
notificationCase === 'both' ||
notificationCase === notificationType ||
(notificationCase === 'end' && ['success', 'failure'].includes(notificationType))
);
}
async send(plan: PlanFull, notificationType: NotificationType, backupData?: BackupDataType) {
const notification = plan.settings.notification;
if (notification?.email?.enabled) {
await this.sendEmail(plan, notificationType, backupData);
}
if (notification?.slack?.enabled) {
await this.sendSlack(plan, notificationType, backupData);
}
if (notification?.discord?.enabled) {
await this.sendDiscord(plan, notificationType, backupData);
}
if (notification?.push?.enabled) {
await this.sendPushNotification(plan, notificationType, backupData);
}
}
async sendEmail(
plan: PlanFull,
notificationType: NotificationType,
backupData?: BackupDataType,
notificationCase?: string
) {
try {
const notification = plan.settings.notification;
const shouldSend = this.shouldSend(notification?.email?.case || 'end', notificationType);
if (!shouldSend) return;
const emailType = notification?.email?.type || 'smtp';
if (!notification?.email?.emails) throw new Error('Email Notification Emails Missing.');
const emailChannel = await this.notificationChannelResolver.getChannel(emailType);
const notificationClass = await this.getNotificationClass(
plan,
notificationType,
backupData,
'html'
);
const notificationResult = await emailChannel.send(notificationClass, {
emails: notification.email.emails,
});
if (!notificationResult?.success)
throw new Error(notificationResult?.result || 'Unknown Error');
// Log Success Notification Result
planLogger('notification', plan.id, backupData?.id).info(
`Backup ${notificationType} Notification Email Sent Successfully.`
);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown Error.';
planLogger('notification', plan.id, backupData?.id).error(
`Error Sending Backup ${notificationType} Email Notification. Reason: ${errorMessage}`
);
}
}
async sendSlack(
plan: PlanFull,
notificationType: NotificationType,
backupData?: BackupDataType,
notificationCase?: string
) {
try {
const notification = plan.settings.notification;
const theCase = notificationCase ? notificationCase : notification?.slack?.case || 'end';
const shouldSend = notificationCase ? true : this.shouldSend(theCase, notificationType);
if (!shouldSend) return;
const webhookUrl = notification?.slack?.url;
if (!webhookUrl) throw new Error('Slack Webhook URL Missing.');
const slackChannel = new SlackChannel(webhookUrl);
const notificationClass = await this.getNotificationClass(
plan,
notificationType,
backupData,
'slack'
);
const notificationResult = await slackChannel.send(notificationClass);
if (!notificationResult?.success)
throw new Error(notificationResult?.result || 'Unknown Error');
planLogger('notification', plan.id, backupData?.id).info(
`Backup ${notificationType} Slack Notification Sent Successfully.`
);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown Error.';
planLogger('notification', plan.id, backupData?.id).error(
`Error Sending Backup ${notificationType} Slack Notification. Reason: ${errorMessage}`
);
}
}
async sendDiscord(
plan: PlanFull,
notificationType: NotificationType,
backupData?: BackupDataType,
notificationCase?: string
) {
try {
const notification = plan.settings.notification;
const theCase = notificationCase ? notificationCase : notification?.discord?.case || 'end';
const shouldSend = notificationCase ? true : this.shouldSend(theCase, notificationType);
if (!shouldSend) return;
const webhookUrl = notification?.discord?.url;
if (!webhookUrl) throw new Error('Discord Webhook URL Missing.');
const discordChannel = new DiscordChannel(webhookUrl);
const notificationClass = await this.getNotificationClass(
plan,
notificationType,
backupData,
'discord'
);
const notificationResult = await discordChannel.send(notificationClass);
if (!notificationResult?.success)
throw new Error(notificationResult?.result || 'Unknown Error');
planLogger('notification', plan.id, backupData?.id).info(
`Backup ${notificationType} Discord Notification Sent Successfully.`
);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown Error.';
planLogger('notification', plan.id, backupData?.id).error(
`Error Sending Backup ${notificationType} Discord Notification. Reason: ${errorMessage}`
);
}
}
async sendPushNotification(
plan: PlanFull,
notificationType: NotificationType,
backupData?: BackupDataType,
notificationCase?: string
) {
try {
const { notification } = plan.settings;
const theCase = notificationCase ? notificationCase : notification?.push?.case || 'end';
const shouldSend = notificationCase ? true : this.shouldSend(theCase, notificationType);
if (!shouldSend) return;
if (!notification?.push?.url) throw new Error('Push Notification URL missing.');
const ntfyChannel = await this.notificationChannelResolver.getChannel('ntfy');
const notificationClass = await this.getNotificationClass(
plan,
notificationType,
backupData,
'push'
);
const body = notificationClass.getContent();
const pushContent: PushNotificationPayload = JSON.parse(body);
const pushTags = notification?.push?.tags || '';
const result = await ntfyChannel.send(notificationClass, {
url: notification.push.url,
title: pushContent.title,
body: pushContent.body,
priority: pushContent.priority,
tags: `${pushContent.emoji ? `${pushContent.emoji}, ` : ''}${pushTags}`,
icon: 'https://pluton.b-cdn.net/logo.png',
markdown: 'yes',
actions:
pushContent.buttonText && pushContent.buttonUrl
? `view, ${pushContent.buttonText}, ${pushContent.buttonUrl}`
: undefined,
});
if (!result.success) throw new Error(result.result);
// Log Success Notification Result
planLogger('notification', plan.id, backupData?.id).info(
`Backup ${notificationType} Notification Sent Successfully.`
);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : 'Failed to Send Push Notification.';
console.log('[Push] errorMessage :', errorMessage);
planLogger('notification', plan.id, backupData?.id).error(
`Error Sending Backup ${notificationType} Webhook Notification. Reason: ${errorMessage}`
);
}
}
async getNotificationClass(
plan: PlanFull,
notificationType: NotificationType,
backupData?: BackupDataType,
output: 'html' | 'json' | 'push' | 'slack' | 'discord' = 'html'
) {
let notificationClass;
const deviceName = plan.device?.name || '';
const storageName = plan.storage?.name || '';
const storageType = plan.storage?.type || '';
switch (notificationType) {
case 'replication_failure':
notificationClass = new this.ReplicationFailedNotificationClass({
appTitle: configService.config.APP_TITLE || 'Pluton',
plan,
deviceName,
storageName,
storageType,
error: backupData?.error || 'Replication failed',
startTime: backupData?.startTime || new Date(),
endTime: backupData?.endTime || new Date(),
failedMirrors: (backupData as any)?.failedMirrors,
output,
});
break;
case 'start':
notificationClass = new this.BackupStartedNotificationClass({
appTitle: configService.config.APP_TITLE || 'Pluton',
plan,
deviceName,
storageName,
storageType,
startTime: backupData?.startTime || new Date(),
stats: backupData?.stats as BackupTaskStats,
output,
});
break;
case 'success':
notificationClass = new this.BackupSuccessNotificationClass({
appTitle: configService.config.APP_TITLE || 'Pluton',
plan,
deviceName,
storageName,
storageType,
startTime: backupData?.startTime || new Date(),
endTime: backupData?.endTime || new Date(),
stats: backupData?.stats as BackupCompletionStats,
replicationFailures: backupData?.replicationFailures,
output,
});
break;
case 'failure':
notificationClass = new this.BackupFailedNotificationClass({
appTitle: configService.config.APP_TITLE || 'Pluton',
plan,
deviceName,
storageName,
storageType,
error: backupData?.error || '',
startTime: backupData?.startTime || new Date(),
endTime: backupData?.endTime || new Date(),
stats: backupData?.stats as BackupTaskStats,
output,
});
break;
case 'end':
if (backupData?.error) {
notificationClass = new this.BackupFailedNotificationClass({
appTitle: configService.config.APP_TITLE || 'Pluton',
plan,
deviceName,
storageName,
storageType,
error: backupData?.error || '',
startTime: backupData?.startTime || new Date(),
endTime: backupData?.endTime || new Date(),
stats: backupData?.stats as BackupTaskStats,
output,
});
} else {
notificationClass = new this.BackupSuccessNotificationClass({
appTitle: configService.config.APP_TITLE || 'Pluton',
plan,
deviceName,
storageName,
storageType,
startTime: backupData?.startTime || new Date(),
endTime: backupData?.endTime || new Date(),
stats: backupData?.stats as BackupCompletionStats,
output,
});
}
break;
// Add other notification types here
}
return notificationClass;
}
}