A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
feat: adds the ability to get push notifications on backup events via ntfy
towfiqi27d81d2cc915
diff --git a/backend/__tests__/controllers/SettingsController.test.ts b/backend/__tests__/controllers/SettingsController.test.tsindex b134922..28251bc 100644--- a/backend/__tests__/controllers/SettingsController.test.ts+++ b/backend/__tests__/controllers/SettingsController.test.ts@@ -264,7 +264,7 @@ describe('SettingsController', () => {expect(mockStatus).toHaveBeenCalledWith(200);expect(mockJson).toHaveBeenCalledWith({success: true,- result: 'Email Sent Successfully',+ result: 'Notification Sent Successfully. Integration Validated.',});});diff --git a/backend/__tests__/notifications/NtfyChannel.test.ts b/backend/__tests__/notifications/NtfyChannel.test.tsnew file mode 100644index 0000000..eb37f89--- /dev/null+++ b/backend/__tests__/notifications/NtfyChannel.test.ts@@ -0,0 +1,220 @@+import { NtfyChannel } from '../../src/notifications/channels/NtfyChannel';+import { BaseNotification } from '../../src/notifications/BaseNotification';+import { NTFYSettings } from '../../src/types/settings';++// Mock global fetch+const mockFetch = jest.fn();+global.fetch = mockFetch;++// Mock notification for testing+class MockNotification extends BaseNotification {+ constructor(content: string = 'Test push notification', subject: string = 'Test Subject') {+ super();+ this.subject = subject;+ this.content = content;+ }++ protected buildContent(): string {+ return '';+ }+}++describe('NtfyChannel', () => {+ let ntfyChannel: NtfyChannel;+ const defaultSettings: NTFYSettings = {+ authType: 'token',+ authToken: 'tk_test123',+ connected: false,+ };++ beforeEach(() => {+ jest.clearAllMocks();+ ntfyChannel = new NtfyChannel(defaultSettings);+ });++ describe('constructor', () => {+ it('should create instance with ntfy settings', () => {+ expect(ntfyChannel).toBeInstanceOf(NtfyChannel);+ expect(ntfyChannel['ntfySettings']).toEqual(defaultSettings);+ });+ });++ describe('send', () => {+ it('should send notification successfully', async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ text: jest.fn().mockResolvedValue('ok'),+ });++ const notification = new MockNotification('Hello from Pluton');+ const result = await ntfyChannel.send(notification, {+ url: 'https://ntfy.sh/testtopic',+ });++ expect(result).toEqual({+ success: true,+ result: 'Ntfy notification sent successfully',+ });+ expect(mockFetch).toHaveBeenCalledWith('https://ntfy.sh/testtopic', {+ method: 'POST',+ headers: {+ Title: 'Test Subject',+ Authorization: 'Bearer tk_test123',+ },+ body: 'Hello from Pluton',+ });+ });++ it('should include Authorization header when authToken is set', async () => {+ mockFetch.mockResolvedValue({ ok: true });++ const notification = new MockNotification();+ await ntfyChannel.send(notification, { url: 'https://ntfy.sh/topic' });++ const callArgs = mockFetch.mock.calls[0];+ expect(callArgs[1].headers.Authorization).toBe('Bearer tk_test123');+ });++ it('should not include Authorization header when authToken is empty', async () => {+ const noAuthSettings: NTFYSettings = {+ authType: 'token',+ authToken: '',+ connected: false,+ };+ ntfyChannel = new NtfyChannel(noAuthSettings);+ mockFetch.mockResolvedValue({ ok: true });++ const notification = new MockNotification();+ await ntfyChannel.send(notification, { url: 'https://ntfy.sh/topic' });++ const callArgs = mockFetch.mock.calls[0];+ expect(callArgs[1].headers.Authorization).toBeUndefined();+ });++ it('should return failure when topic URL is missing', async () => {+ const notification = new MockNotification();++ const result = await ntfyChannel.send(notification, {});++ expect(result).toEqual({+ success: false,+ result: 'Ntfy topic URL is required',+ });+ expect(mockFetch).not.toHaveBeenCalled();+ });++ it('should return failure when options is undefined', async () => {+ const notification = new MockNotification();++ const result = await ntfyChannel.send(notification);++ expect(result).toEqual({+ success: false,+ result: 'Ntfy topic URL is required',+ });+ expect(mockFetch).not.toHaveBeenCalled();+ });++ it('should return failure when ntfy returns non-ok response', async () => {+ mockFetch.mockResolvedValue({+ ok: false,+ status: 401,+ text: jest.fn().mockResolvedValue('unauthorized'),+ });++ const notification = new MockNotification();+ const result = await ntfyChannel.send(notification, {+ url: 'https://ntfy.sh/topic',+ });++ expect(result).toEqual({+ success: false,+ result: 'Ntfy returned 401: unauthorized',+ });+ });++ it('should return failure when ntfy returns 403', async () => {+ mockFetch.mockResolvedValue({+ ok: false,+ status: 403,+ text: jest.fn().mockResolvedValue('forbidden'),+ });++ const notification = new MockNotification();+ const result = await ntfyChannel.send(notification, {+ url: 'https://ntfy.sh/topic',+ });++ expect(result).toEqual({+ success: false,+ result: 'Ntfy returned 403: forbidden',+ });+ });++ it('should return failure when ntfy returns 404', async () => {+ mockFetch.mockResolvedValue({+ ok: false,+ status: 404,+ text: jest.fn().mockResolvedValue('not found'),+ });++ const notification = new MockNotification();+ const result = await ntfyChannel.send(notification, {+ url: 'https://ntfy.sh/topic',+ });++ expect(result).toEqual({+ success: false,+ result: 'Ntfy returned 404: not found',+ });+ });++ it('should handle network errors gracefully', async () => {+ mockFetch.mockRejectedValue(new Error('Network error'));++ const notification = new MockNotification();+ const result = await ntfyChannel.send(notification, {+ url: 'https://ntfy.sh/topic',+ });++ expect(result).toEqual({+ success: false,+ result: 'Network error',+ });+ });++ it('should handle unknown errors gracefully', async () => {+ mockFetch.mockRejectedValue('Unknown');++ const notification = new MockNotification();+ const result = await ntfyChannel.send(notification, {+ url: 'https://ntfy.sh/topic',+ });++ expect(result).toEqual({+ success: false,+ result: 'Failed to send Ntfy notification',+ });+ });++ it('should set the Title header from the notification subject', async () => {+ mockFetch.mockResolvedValue({ ok: true });++ const notification = new MockNotification('Body', 'My Custom Title');+ await ntfyChannel.send(notification, { url: 'https://ntfy.sh/topic' });++ const callArgs = mockFetch.mock.calls[0];+ expect(callArgs[1].headers.Title).toBe('My Custom Title');+ });++ it('should send the notification content as the body', async () => {+ mockFetch.mockResolvedValue({ ok: true });++ const notification = new MockNotification('Pluton backup completed.');+ await ntfyChannel.send(notification, { url: 'https://ntfy.sh/topic' });++ const callArgs = mockFetch.mock.calls[0];+ expect(callArgs[1].body).toBe('Pluton backup completed.');+ });+ });+});diff --git a/backend/__tests__/notifications/TestNtfyNotification.test.ts b/backend/__tests__/notifications/TestNtfyNotification.test.tsnew file mode 100644index 0000000..cff83ad--- /dev/null+++ b/backend/__tests__/notifications/TestNtfyNotification.test.ts@@ -0,0 +1,79 @@+import { TestNtfyNotification } from '../../src/notifications/templates/push/test-ntfy/TestNtfyNotification';++// Mock dependencies+jest.mock('../../src/services/ConfigService', () => ({+ configService: {+ config: {+ APP_TITLE: 'Test App',+ APP_URL: 'http://test.com',+ },+ },+}));++describe('TestNtfyNotification', () => {+ describe('constructor', () => {+ it('should create notification with ntfy integration type', () => {+ const notification = new TestNtfyNotification({+ integrationType: 'ntfy',+ appTitle: 'Test App',+ });++ expect(notification.getSubject()).toBe('Ntfy Integration Successful');+ });++ it('should set integration name from INTEGRATIONS_AVAILABLE', () => {+ const notification = new TestNtfyNotification({+ integrationType: 'ntfy',+ appTitle: 'Test App',+ });++ expect(notification['integrationName']).toBe('Ntfy');+ });+ });++ describe('buildContent', () => {+ it('should use configured APP_TITLE in content', () => {+ const notification = new TestNtfyNotification({+ integrationType: 'ntfy',+ appTitle: 'Custom App',+ });++ const content = notification.getContent();++ expect(content).toContain('Test App'); // from configService mock+ expect(content).toContain('Ntfy');+ });++ it('should return plain text content (not HTML)', () => {+ const notification = new TestNtfyNotification({+ integrationType: 'ntfy',+ appTitle: 'Test App',+ });++ const content = notification.getContent();++ // Should be plain text, not wrapped in HTML+ expect(content).not.toContain('<div');+ expect(content).not.toContain('<h2');+ expect(content).toContain('can successfully send push notifications using Ntfy');+ });++ it('should fallback to Pluton when APP_TITLE is not configured', () => {+ // Temporarily override the mock+ const configModule = require('../../src/services/ConfigService');+ const originalTitle = configModule.configService.config.APP_TITLE;+ configModule.configService.config.APP_TITLE = '';++ const notification = new TestNtfyNotification({+ integrationType: 'ntfy',+ appTitle: 'Pluton',+ });++ const content = notification.getContent();+ expect(content).toContain('Pluton');++ // Restore+ configModule.configService.config.APP_TITLE = originalTitle;+ });+ });+});diff --git a/backend/__tests__/services/SettingsService.test.ts b/backend/__tests__/services/SettingsService.test.tsindex c419e4b..1f97947 100644--- a/backend/__tests__/services/SettingsService.test.ts+++ b/backend/__tests__/services/SettingsService.test.ts@@ -1,12 +1,12 @@-import { createReadStream, constants, ReadStream } from 'fs';-import path from 'path';+import { createReadStream, constants } from 'fs';import { readFile, access } from 'fs/promises';import { SettingsService } from '../../src/services/SettingsService';import { SettingsStore } from '../../src/stores/SettingsStore';import { AppSettings } from '../../src/types/settings';-import { AppError, NotFoundError } from '../../src/utils/AppError';+import { AppError } from '../../src/utils/AppError';import { NotificationChannelResolver } from '../../src/notifications/channels/NotificationChannelResolver';import { SMTPChannel } from '../../src/notifications/channels/SMTPChannel';+import { NtfyChannel } from '../../src/notifications/channels/NtfyChannel';import { Settings } from '../../src/db/schema/settings';// Mock all dependencies@@ -22,7 +22,9 @@ jest.mock('../../src/db/index', () => ({jest.mock('../../src/stores/SettingsStore');jest.mock('../../src/notifications/channels/NotificationChannelResolver');jest.mock('../../src/notifications/templates/email/test-email/TestEmailNotification');+jest.mock('../../src/notifications/templates/push/test-ntfy/TestNtfyNotification');jest.mock('../../src/notifications/channels/SMTPChannel');+jest.mock('../../src/notifications/channels/NtfyChannel');jest.mock('fs/promises');jest.mock('fs');@@ -138,7 +140,10 @@ describe('SettingsService', () => {describe('validateIntegration', () => {const settingsId = 1;const testPayload = { email: '[email protected]' };- const mockAppSettings = {+ const mockIntegrationSettings = {+ smtp: { server: 'smtp.example.com', connected: false },+ } as AppSettings['integration'];+ const mockReturnedAppSettings = {title: 'Pluton',integration: { smtp: { server: 'smtp.example.com', connected: false } },} as AppSettings;@@ -146,15 +151,15 @@ describe('SettingsService', () => {it('should validate, send email, and update connection status to true', async () => {// First update returns the settings, second one confirms connection status updatemockSettingsStore.update- .mockResolvedValueOnce({ id: 1, settings: mockAppSettings } as any)- .mockResolvedValueOnce({ id: 1, settings: mockAppSettings } as any);+ .mockResolvedValueOnce({ id: 1, settings: mockReturnedAppSettings } as any)+ .mockResolvedValueOnce({ id: 1, settings: mockReturnedAppSettings } as any);mockSmtpChannel.send.mockResolvedValue({ success: true, result: 'Email sent' });const result = await settingsService.validateIntegration(settingsId,'smtp',testPayload,- mockAppSettings+ mockIntegrationSettings);expect(MockedNotificationChannelResolver.encryptSecrets).toHaveBeenCalled();@@ -173,19 +178,19 @@ describe('SettingsService', () => {});it('should throw an AppError if sending the email fails', async () => {- mockSettingsStore.update.mockResolvedValue({ id: 1, settings: mockAppSettings } as any);+ mockSettingsStore.update.mockResolvedValue({+ id: 1,+ settings: mockReturnedAppSettings,+ } as any);mockSmtpChannel.send.mockResolvedValue({ success: false, result: 'Auth failed' });- const promise = settingsService.validateIntegration(- settingsId,- 'smtp',- testPayload,- mockAppSettings- );+ const promise = settingsService.validateIntegration(settingsId, 'smtp', testPayload, {+ ...mockIntegrationSettings,+ });await expect(promise).rejects.toThrow(AppError);await expect(promise).rejects.toThrow(- 'Failed to send test email using smtp. Reason: Auth failed'+ 'Failed to send test notification using smtp. Reason: Auth failed');// Ensure the second update to set `connected: true` was NOT called@@ -196,12 +201,101 @@ describe('SettingsService', () => {mockSettingsStore.update.mockResolvedValue(null); // Simulate DB update failureawait expect(- settingsService.validateIntegration(settingsId, 'smtp', testPayload, mockAppSettings)+ settingsService.validateIntegration(settingsId, 'smtp', testPayload, {+ ...mockIntegrationSettings,+ })).rejects.toThrow('Failed to update settings');// Ensure no email was attemptedexpect(mockSmtpChannel.send).not.toHaveBeenCalled();});++ // Ntfy integration validation tests+ describe('ntfy', () => {+ const ntfyTestPayload = { url: 'https://ntfy.sh/testtopic' };+ const mockNtfyIntegrationSettings = {+ ntfy: { authType: 'token', authToken: 'tk_test', connected: false },+ } as AppSettings['integration'];+ const mockNtfyReturnedAppSettings = {+ title: 'Pluton',+ integration: { ntfy: { authType: 'token', authToken: 'tk_test', connected: false } },+ } as AppSettings;+ let mockNtfyChannel: jest.Mocked<NtfyChannel>;++ beforeEach(() => {+ mockNtfyChannel = new NtfyChannel({} as any) as jest.Mocked<NtfyChannel>;+ (MockedNotificationChannelResolver.getChannel as jest.Mock).mockResolvedValue(+ mockNtfyChannel+ );+ });++ it('should validate ntfy, send push notification, and update connection status', async () => {+ mockSettingsStore.update+ .mockResolvedValueOnce({ id: 1, settings: mockNtfyReturnedAppSettings } as any)+ .mockResolvedValueOnce({ id: 1, settings: mockNtfyReturnedAppSettings } as any);+ mockNtfyChannel.send.mockResolvedValue({+ success: true,+ result: 'Ntfy notification sent',+ });++ const result = await settingsService.validateIntegration(+ settingsId,+ 'ntfy',+ ntfyTestPayload,+ { ...mockNtfyIntegrationSettings }+ );++ expect(MockedNotificationChannelResolver.encryptSecrets).toHaveBeenCalled();+ expect(mockSettingsStore.update).toHaveBeenCalledTimes(2);+ expect(mockNtfyChannel.send).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ url: 'https://ntfy.sh/testtopic' })+ );+ expect(mockSettingsStore.update).toHaveBeenLastCalledWith(+ settingsId,+ expect.objectContaining({+ integration: expect.objectContaining({+ ntfy: expect.objectContaining({ connected: true }),+ }),+ })+ );+ expect(result).toBe(true);+ });++ it('should throw an AppError if sending the ntfy notification fails', async () => {+ mockSettingsStore.update.mockResolvedValue({+ id: 1,+ settings: mockNtfyReturnedAppSettings,+ } as any);+ mockNtfyChannel.send.mockResolvedValue({+ success: false,+ result: 'Ntfy returned 401: unauthorized',+ });++ const promise = settingsService.validateIntegration(settingsId, 'ntfy', ntfyTestPayload, {+ ...mockNtfyIntegrationSettings,+ });++ await expect(promise).rejects.toThrow(AppError);+ await expect(promise).rejects.toThrow(+ 'Failed to send test notification using ntfy. Reason: Ntfy returned 401: unauthorized'+ );++ expect(mockSettingsStore.update).toHaveBeenCalledTimes(1);+ });++ it('should throw an AppError if the initial ntfy settings update fails', async () => {+ mockSettingsStore.update.mockResolvedValue(null);++ await expect(+ settingsService.validateIntegration(settingsId, 'ntfy', ntfyTestPayload, {+ ...mockNtfyIntegrationSettings,+ })+ ).rejects.toThrow('Failed to update settings');++ expect(mockNtfyChannel.send).not.toHaveBeenCalled();+ });+ });});// ----------------------------------------diff --git a/backend/src/controllers/SettingsController.ts b/backend/src/controllers/SettingsController.tsindex 7b67f62..3e49f70 100644--- a/backend/src/controllers/SettingsController.ts+++ b/backend/src/controllers/SettingsController.ts@@ -82,7 +82,7 @@ export class SettingsController {});return;}- const appSettings = req.body.settings as AppSettings;+ const appSettings = req.body.settings as AppSettings['integration'];const integrationType = req.body.type as IntegrationTypes;try {@@ -92,7 +92,9 @@ export class SettingsController {req.body.test,appSettings);- res.status(200).json({ success: true, result: 'Email Sent Successfully' });+ res+ .status(200)+ .json({ success: true, result: 'Notification Sent Successfully. Integration Validated.' });return;} catch (error: unknown) {res.status(500).json({@@ -100,7 +102,7 @@ export class SettingsController {error:error instanceof Error? error.message- : `Failed to send test email using ${integrationType}.`,+ : `Failed to send test notification using ${integrationType}.`,});return;}diff --git a/backend/src/notifications/BackupNotification.ts b/backend/src/notifications/BackupNotification.tsindex 52a1dde..176ad27 100644--- a/backend/src/notifications/BackupNotification.ts+++ b/backend/src/notifications/BackupNotification.ts@@ -1,6 +1,6 @@import { BackupCompletionStats, BackupTaskStats, ReplicationFailureInfo } from '../types/backups';import { PlanFull } from '../types/plans';-import { INotificationChannelResolver } from '../types/notifications';+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';@@ -49,6 +49,9 @@ export class BackupNotification {if (notification?.discord?.enabled) {await this.sendDiscord(plan, notificationType, backupData);}+ if (notification?.push?.enabled) {+ await this.sendPushNotification(plan, notificationType, backupData);+ }}async sendEmail(@@ -167,6 +170,61 @@ export class BackupNotification {}}+ 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) throw new Error('Does not match Plan Notification Case.');+ 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,diff --git a/backend/src/notifications/channels/NotificationChannelResolver.ts b/backend/src/notifications/channels/NotificationChannelResolver.tsindex 8e81a1c..63a4fab 100644--- a/backend/src/notifications/channels/NotificationChannelResolver.ts+++ b/backend/src/notifications/channels/NotificationChannelResolver.ts@@ -1,6 +1,7 @@import Cryptr from 'cryptr';-import { AppSettings, IntegrationTypes, SmtpSettings } from '../../types/settings';+import { AppSettings, IntegrationTypes, NTFYSettings, SmtpSettings } from '../../types/settings';import { SMTPChannel } from './SMTPChannel';+import { NtfyChannel } from './NtfyChannel';import { getNestedValue, setNestedValue } from '../../utils/helpers';import { db } from '../../db/index';import { SettingsStore } from '../../stores/SettingsStore';@@ -8,7 +9,7 @@ import { configService } from '../../services/ConfigService';import { NotificationChannel } from '../NotificationChannel';export class NotificationChannelResolver {- static secretFields: string[] = ['smtp.password'];+ static secretFields: string[] = ['smtp.password', 'ntfy.authToken'];static async getChannel(channelType: IntegrationTypes = 'smtp'): Promise<NotificationChannel> {const settingsStore = new SettingsStore(db);@@ -21,6 +22,8 @@ export class NotificationChannelResolver {switch (channelType) {case 'smtp':return new SMTPChannel(channelConfig as SmtpSettings);+ case 'ntfy':+ return new NtfyChannel(channelConfig as NTFYSettings);default:return new SMTPChannel(channelConfig as SmtpSettings);}diff --git a/backend/src/notifications/channels/NtfyChannel.ts b/backend/src/notifications/channels/NtfyChannel.tsnew file mode 100644index 0000000..68d452f--- /dev/null+++ b/backend/src/notifications/channels/NtfyChannel.ts@@ -0,0 +1,63 @@+import { BaseNotification } from '../BaseNotification';+import { NotificationChannel } from '../NotificationChannel';+import { NTFYSettings } from '../../types/settings';++export class NtfyChannel implements NotificationChannel {+ protected ntfySettings: NTFYSettings;++ constructor(ntfySettings: NTFYSettings) {+ this.ntfySettings = ntfySettings;+ }++ async send(+ notification: BaseNotification,+ options?: Record<string, any>+ ): Promise<{ success: boolean; result: string }> {+ try {+ const topicUrl = options?.url;+ if (!topicUrl) {+ return { success: false, result: 'Ntfy topic URL is required' };+ }++ const headers: Record<string, string> = {+ Title: options?.title || notification.getSubject(),+ };++ if (this.ntfySettings.authToken) {+ headers['Authorization'] = `Bearer ${this.ntfySettings.authToken}`;+ }++ if (options?.priority) headers['Priority'] = String(options.priority);+ if (options?.tags) headers['Tags'] = options.tags;+ if (options?.icon) headers['Icon'] = options.icon;+ if (options?.markdown) headers['Markdown'] = options.markdown;+ if (options?.actions) headers['Actions'] = options.actions;++ const body = options?.body ?? notification.getContent();++ const response = await fetch(topicUrl, {+ method: 'POST',+ headers,+ body,+ });++ if (!response.ok) {+ const errorText = await response.text();+ return {+ success: false,+ result: `Ntfy returned ${response.status}: ${errorText}`,+ };+ }++ return {+ success: true,+ result: 'Ntfy notification sent successfully',+ };+ } catch (error: any) {+ return {+ success: false,+ result: error?.message || 'Failed to send Ntfy notification',+ };+ }+ }+}diff --git a/backend/src/notifications/templates/email/backup/BackupFailedNotification.ts b/backend/src/notifications/templates/email/backup/BackupFailedNotification.tsindex c4487dc..fe005f6 100644--- a/backend/src/notifications/templates/email/backup/BackupFailedNotification.ts+++ b/backend/src/notifications/templates/email/backup/BackupFailedNotification.ts@@ -32,6 +32,9 @@ export class BackupFailedNotification extends BaseNotification {if (this.contentType === 'json') {return this.buildJSONContent(data);}+ if (this.contentType === 'push') {+ return this.buildSlackContent(data);+ }if (this.contentType === 'slack') {return this.buildSlackContent(data);}@@ -199,4 +202,18 @@ export class BackupFailedNotification extends BaseNotification {return JSON.stringify({ embeds: [embed] });}++ buildPushContent(data: BackupFailedNotificationPayload) {+ const { appTitle, deviceName, storageName, storageType, plan } = data;+ const sourceCount = plan.sourceConfig.includes.length;+ const payload = {+ title: `${appTitle}: Backup Failed for Plan "${plan.title}"`,+ body: `Failed to backup ${sourceCount} sources from ${deviceName} to ${storageName}(${storageType}).`,+ priority: 4,+ emoji: 'warning',+ buttonUrl: `${configService.config.APP_URL}/plan/${data.plan.id}`,+ buttonText: 'View Plan',+ };+ return JSON.stringify(payload);+ }}diff --git a/backend/src/notifications/templates/email/backup/BackupStartedNotification.ts b/backend/src/notifications/templates/email/backup/BackupStartedNotification.tsindex 09ba35c..3a7b9b6 100644--- a/backend/src/notifications/templates/email/backup/BackupStartedNotification.ts+++ b/backend/src/notifications/templates/email/backup/BackupStartedNotification.ts@@ -30,6 +30,9 @@ export class BackupStartedNotification extends BaseNotification {if (this.contentType === 'json') {return this.buildJSONContent(data);}+ if (this.contentType === 'push') {+ return this.buildPushContent(data);+ }if (this.contentType === 'slack') {return this.buildSlackContent(data);}@@ -169,4 +172,18 @@ export class BackupStartedNotification extends BaseNotification {return JSON.stringify({ embeds: [embed] });}++ buildPushContent(data: BackupStartedPayload) {+ const { appTitle, deviceName, storageName, storageType, plan } = data;+ const sourceCount = plan.sourceConfig.includes.length;+ const payload = {+ title: `${appTitle}: Backup Started for Plan "${plan.title}"`,+ body: `Backing up ${sourceCount} sources from ${deviceName} to ${storageName}(${storageType}).`,+ priority: 3,+ emoji: 'arrows_counterclockwise',+ buttonUrl: `${configService.config.APP_URL}/plan/${data.plan.id}`,+ buttonText: 'View Plan',+ };+ return JSON.stringify(payload);+ }}diff --git a/backend/src/notifications/templates/email/backup/BackupSuccessNotification.ts b/backend/src/notifications/templates/email/backup/BackupSuccessNotification.tsindex a8e87cf..f610e21 100644--- a/backend/src/notifications/templates/email/backup/BackupSuccessNotification.ts+++ b/backend/src/notifications/templates/email/backup/BackupSuccessNotification.ts@@ -36,6 +36,9 @@ export class BackupSuccessNotification extends BaseNotification {if (this.contentType === 'json') {return this.buildJSONContent(data);}+ if (this.contentType === 'push') {+ return this.buildPushContent(data);+ }if (this.contentType === 'slack') {return this.buildSlackContent(data);}@@ -139,6 +142,7 @@ export class BackupSuccessNotification extends BaseNotification {} = data;const storageTypeName = storageType ? providers[storageType]?.name || storageType : '';const appUrl = configService.config.APP_URL || '';+ const hasReplicationFailures = replicationFailures && replicationFailures.length > 0;const fields: { type: string; text: string }[] = [{ type: 'mrkdwn', text: `*Plan:* ${plan.title}` },@@ -168,7 +172,11 @@ export class BackupSuccessNotification extends BaseNotification {const blocks: Record<string, any>[] = [{type: 'header',- text: { type: 'plain_text', text: `✅ Backup Complete: ${plan.title}`, emoji: true },+ text: {+ type: 'plain_text',+ text: `${hasReplicationFailures ? '⚠️' : '✅'} Backup Complete: ${plan.title}`,+ emoji: true,+ },},{type: 'section',@@ -176,7 +184,7 @@ export class BackupSuccessNotification extends BaseNotification {},];- if (replicationFailures && replicationFailures.length > 0) {+ if (hasReplicationFailures) {blocks.push({type: 'section',text: {@@ -221,6 +229,7 @@ export class BackupSuccessNotification extends BaseNotification {} = data;const storageTypeName = storageType ? providers[storageType]?.name || storageType : '';const appUrl = configService.config.APP_URL || '';+ const hasReplicationFailures = replicationFailures && replicationFailures.length > 0;const fields: { name: string; value: string; inline: boolean }[] = [{ name: 'Plan', value: plan.title, inline: true },@@ -259,8 +268,8 @@ export class BackupSuccessNotification extends BaseNotification {}const embed: Record<string, any> = {- title: `✅ Backup Complete: ${plan.title}`,- color: 0x22c55e, // green+ title: `${hasReplicationFailures ? '⚠️' : '✅'} Backup Complete: ${plan.title}`,+ color: hasReplicationFailures ? 0xf59e0b : 0x22c55e,fields,timestamp: new Date(startTime).toISOString(),footer: { text: appTitle },@@ -272,4 +281,37 @@ export class BackupSuccessNotification extends BaseNotification {return JSON.stringify({ embeds: [embed] });}++ buildPushContent(data: BackupSuccessNotificationPayload) {+ const { appTitle, deviceName, storageName, storageType, plan, stats, replicationFailures } =+ data;+ const hasReplicationFailures = replicationFailures && replicationFailures.length > 0;+ const sourceCount = plan.sourceConfig.includes.length;+ const backupChanges = () => {+ const newCount = (stats?.files_new || 0) + (stats?.dirs_new || 0);+ const modifiedCount = (stats?.files_changed || 0) + (stats?.dirs_changed || 0);+ const removedCount = 0;+ const parts = [];+ if (newCount > 0) parts.push(`${newCount} New`);+ if (modifiedCount > 0) parts.push(`${modifiedCount} Modified`);+ if (removedCount > 0) parts.push(`${removedCount} Removed`);+ return parts.length > 0 ? parts.join(' / ') : 'No Changes';+ };+ // const+ const payload = {+ title: `${appTitle}: Backup Successful for Plan "${plan.title}"`,+ body: `Successfully Backed up ${sourceCount} sources from ${deviceName} to ${storageName}(${storageType}).++ Changes: ${backupChanges()}+ Total Size: ${formatBytes(stats?.total_bytes_processed || 0)}+ Total Files: ${formatNumberToK(stats?.total_files_processed || 0)}+ Total Duration: ${formatDuration(stats?.total_duration || 0)}+ ${hasReplicationFailures ? `⚠️ Replication Failures: ${replicationFailures.map(f => f.storageName || f.storageId).join(', ')}` : ''}`,+ priority: 3,+ emoji: hasReplicationFailures ? 'warning' : 'white_check_mark',+ buttonUrl: `${configService.config.APP_URL}/plan/${data.plan.id}`,+ buttonText: 'View Plan',+ };+ return JSON.stringify(payload);+ }}diff --git a/backend/src/notifications/templates/email/backup/ReplicationFailedNotification.ts b/backend/src/notifications/templates/email/backup/ReplicationFailedNotification.tsindex 696d8e2..aaaa392 100644--- a/backend/src/notifications/templates/email/backup/ReplicationFailedNotification.ts+++ b/backend/src/notifications/templates/email/backup/ReplicationFailedNotification.ts@@ -219,4 +219,21 @@ export class ReplicationFailedNotification extends BaseNotification {return JSON.stringify({ embeds: [embed] });}++ buildPushContent(data: ReplicationFailedNotificationPayload) {+ const { appTitle, deviceName, storageName, storageType, plan, failedMirrors = [] } = data;+ const sourceCount = plan.sourceConfig.includes.length;++ const payload = {+ title: `${appTitle}: Replication Failed for Plan "${plan.title}"`,+ body: `Failed to replicate ${sourceCount} sources from ${deviceName} to ${failedMirrors.length} storages.+ ${failedMirrors.map(mirror => `${mirror.storageName} : (${mirror.error || 'Unknown Error'})`).join(', ')}+ `,+ priority: 3,+ emoji: 'white_check_mark',+ buttonUrl: `${configService.config.APP_URL}/plan/${data.plan.id}`,+ buttonText: 'View Plan',+ };+ return JSON.stringify(payload);+ }}diff --git a/backend/src/notifications/templates/push/test-ntfy/TestNtfyNotification.ts b/backend/src/notifications/templates/push/test-ntfy/TestNtfyNotification.tsnew file mode 100644index 0000000..6e13150--- /dev/null+++ b/backend/src/notifications/templates/push/test-ntfy/TestNtfyNotification.ts@@ -0,0 +1,17 @@+import { configService } from '../../../../services/ConfigService';+import { INTEGRATIONS_AVAILABLE, IntegrationTypes } from '../../../../types/settings';+import { BaseNotification } from '../../../BaseNotification';++export class TestNtfyNotification extends BaseNotification {+ integrationName = '';+ constructor(data: { integrationType: IntegrationTypes; appTitle: string }) {+ super();+ const integrationType = data.integrationType;+ this.integrationName = INTEGRATIONS_AVAILABLE[integrationType].name;+ this.subject = `${this.integrationName} Integration Successful`;+ this.content = this.buildContent(data);+ }+ protected buildContent(data: { integrationType: IntegrationTypes; appTitle: string }): string {+ return `${configService.config.APP_TITLE || 'Pluton'} can successfully send push notifications using ${this.integrationName}.`;+ }+}diff --git a/backend/src/services/SettingsService.ts b/backend/src/services/SettingsService.tsindex 6f0acf4..6708b9a 100644--- a/backend/src/services/SettingsService.ts+++ b/backend/src/services/SettingsService.ts@@ -4,6 +4,7 @@ import { createReadStream, constants, ReadStream } from 'fs';import { readFile, access } from 'fs/promises';import { Settings, settingsUpdateSchema } from '../db/schema/settings';import { TestEmailNotification } from '../notifications/templates/email/test-email/TestEmailNotification';+import { TestNtfyNotification } from '../notifications/templates/push/test-ntfy/TestNtfyNotification';import { SettingsStore } from '../stores/SettingsStore';import { AppSettings, IntegrationTypes } from '../types/settings';import { INotificationChannelResolver } from '../types/notifications';@@ -64,30 +65,49 @@ export class SettingsService {async validateIntegration(id: number,type: IntegrationTypes,- test: { email: string },- settings: AppSettings+ test: { email?: string; url?: string },+ settings: AppSettings['integration']): Promise<boolean> {- const appSettings = settings;-+ const integrationSettings = settings;const integrationType = type;- appSettings.integration = this.notificationChannelResolver.encryptSecrets(- appSettings.integration as AppSettings['integration']- );++ if (!integrationSettings[integrationType]) {+ throw new AppError(400, `Integration settings for ${type} are missing.`);+ }++ const encryptedIntegration =+ this.notificationChannelResolver.encryptSecrets(integrationSettings);try {// First Update the Integration Settings with the provided config- const updatedSettings = await this.settingsStore.update(id, appSettings);+ const updatedSettings = await this.settingsStore.update(id, {+ integration: {+ ...integrationSettings,+ [integrationType]: encryptedIntegration[integrationType],+ },+ } as AppSettings);if (!updatedSettings) {throw new AppError(500, 'Failed to update settings');}const theAppSettings = updatedSettings.settings as AppSettings;const appTitle = theAppSettings?.title || 'Pluton';-- // Send the test email- const notificationClass = new TestEmailNotification({ integrationType, appTitle });- const senderChannel = await this.notificationChannelResolver.getChannel(integrationType);- const sendRes = await senderChannel.send(notificationClass, {- emails: test.email,- });+ let sendRes = { success: false, result: '' };++ // Send the test notification+ if (type === 'ntfy') {+ const notificationClass = new TestNtfyNotification({ integrationType, appTitle });+ const senderChannel = await this.notificationChannelResolver.getChannel(integrationType);+ sendRes = await senderChannel.send(notificationClass, {+ url: test.url,+ icon: 'https://pluton.b-cdn.net/logo.png',+ });+ } else {+ const notificationClass = new TestEmailNotification({ integrationType, appTitle });+ const senderChannel = await this.notificationChannelResolver.getChannel(integrationType);+ console.log('senderChannel :', senderChannel);+ sendRes = await senderChannel.send(notificationClass, {+ emails: test.email,+ });+ }// Set the integration status to connectedif (sendRes.success) {@@ -100,7 +120,7 @@ export class SettingsService {} else {throw new AppError(500,- `Failed to send test email using ${integrationType}. Reason: ${sendRes.result}`+ `Failed to send test notification using ${integrationType}. Reason: ${sendRes.result}`);}} catch (error: unknown) {@@ -108,7 +128,7 @@ export class SettingsService {500,error instanceof Error? error.message- : `Failed to send test email using ${integrationType}.`+ : `Failed to send test notification using ${integrationType}.`);}}diff --git a/backend/src/types/notifications.ts b/backend/src/types/notifications.tsindex 9b60368..76eafec 100644--- a/backend/src/types/notifications.ts+++ b/backend/src/types/notifications.ts@@ -29,3 +29,12 @@ export interface BackupNotificationData {compression: boolean;taskStats?: BackupTaskStats;}++export interface PushNotificationPayload {+ title: string;+ body: string;+ priority: number;+ emoji?: string;+ buttonUrl?: string;+ buttonText?: string;+}diff --git a/frontend/src/@types/settings.ts b/frontend/src/@types/settings.tsindex ea04774..731485d 100644--- a/frontend/src/@types/settings.ts+++ b/frontend/src/@types/settings.ts@@ -18,3 +18,46 @@ export interface LogItem {deviceId?: string;msg: string;}++export interface NtfySettingsType {+ authType: string;+ authToken: string;+ connected: boolean;+}++export interface IntegrationSettings {+ smtp?: SmtpSettingsType;+ ntfy?: NtfySettingsType;+}++export type IntegrationTypes = 'smtp' | 'sendgrid' | 'mailgun' | 'brevo' | 'resend' | 'awsSes' | 'ntfy';+export const INTEGRATIONS_AVAILABLE: Record<IntegrationTypes, { name: string; required: string[] }> = {+ smtp: {+ name: 'SMTP',+ required: ['server', 'port', 'username', 'password', 'senderEmail'],+ },+ sendgrid: {+ name: 'SendGrid',+ required: ['apiKey', 'senderEmail'],+ },+ mailgun: {+ name: 'Mailgun',+ required: ['apiKey', 'domain', 'senderEmail'],+ },+ brevo: {+ name: 'Brevo',+ required: ['apiKey', 'senderEmail'],+ },+ resend: {+ name: 'Resend',+ required: ['apiKey', 'senderEmail'],+ },+ awsSes: {+ name: 'AWS SES',+ required: ['accessKeyId', 'secretAccessKey', 'region', 'senderEmail'],+ },+ ntfy: {+ name: 'Ntfy',+ required: ['authType', 'authToken'],+ },+} as const;diff --git a/frontend/src/components/Plan/PlanSettings/PlanNotificationSettings.tsx b/frontend/src/components/Plan/PlanSettings/PlanNotificationSettings.tsxindex abadc18..df92d2d 100644--- a/frontend/src/components/Plan/PlanSettings/PlanNotificationSettings.tsx+++ b/frontend/src/components/Plan/PlanSettings/PlanNotificationSettings.tsx@@ -28,6 +28,7 @@ const PlanNotificationSettings = ({}: PlanNotificationSettingsProps) => {const hasConnectedIntegrations = types.length > 0;const defaultEmail = !hasConnectedIntegrations && admin_email ? admin_email : '';+ const hasNtfyConnected = types.includes('ntfy');const updateNotificationEmails = (emails: string) => {onUpdate({ ...notificationSettings, email: { ...notificationSettings.email, emails } });@@ -203,6 +204,70 @@ const PlanNotificationSettings = ({</div>)}</div>++ {/* Ntfy Push Notification */}+ <div className={classes.notificationSettingsSection}>+ <div className={`${classes.field} ${classes.notificationToggle}`}>+ <Icon type="ntfy" size={14} />+ <Toggle+ label="Enable Ntfy Push Notifications"+ fieldValue={notificationSettings?.push?.enabled || false}+ onUpdate={(val: boolean) => onUpdate({ ...notificationSettings, push: { ...notificationSettings.push, enabled: val } })}+ hint={`Send me Push Notifications on Backup failure or success.`}+ inline={true}+ />+ </div>+ {notificationSettings.push?.enabled &&+ (hasNtfyConnected ? (+ <div className={classes.notificationSettings}>+ {!isSync && (+ <div className={classes.field}>+ <Select+ label="Send Notification On"+ fieldValue={notificationSettings?.push?.case || 'failure'}+ options={caseOptions}+ onUpdate={(val: string) =>+ onUpdate({+ ...notificationSettings,+ push: { ...notificationSettings.push, case: val as PlanNotification['push']['case'] },+ })+ }+ inline={true}+ />+ </div>+ )}+ <div className={classes.field}>+ <Input+ label="Ntfy Push URL"+ fieldValue={notificationSettings?.push?.url || ''}+ onUpdate={(val) => onUpdate({ ...notificationSettings, push: { ...notificationSettings.push, url: val } })}+ placeholder="https://ntfy.sh/mytopic"+ inline={true}+ required={true}+ full={true}+ error={!notificationSettings?.push?.url ? 'Required' : undefined}+ />+ </div>+ <div className={classes.field}>+ <Input+ label="Tags"+ fieldValue={notificationSettings?.push?.tags || ''}+ onUpdate={(val) => onUpdate({ ...notificationSettings, push: { ...notificationSettings.push, tags: val } })}+ placeholder="warning, daily-backup"+ inline={true}+ full={true}+ />+ </div>+ </div>+ ) : (+ <div className={classes.notificationSettings}>+ <div className={classes.fieldNotice}>+ ⚠️ Ntfy Auth Token is not configured. Set it up in <NavLink to={`/settings?t=integration`}>Settings</NavLink> to enable Ntfy+ Push Notifications.+ </div>+ </div>+ ))}+ </div></>);};diff --git a/frontend/src/components/Settings/IntegrationSettings/IntegrationSettings.module.scss b/frontend/src/components/Settings/IntegrationSettings/IntegrationSettings.module.scssindex b06052e..bfe04b0 100644--- a/frontend/src/components/Settings/IntegrationSettings/IntegrationSettings.module.scss+++ b/frontend/src/components/Settings/IntegrationSettings/IntegrationSettings.module.scss@@ -36,3 +36,19 @@}}}++@media only screen and (max-width: 768px) {+ .integrations {+ .field {+ width: 100%;+ }+ }+ .integrationSelect {+ width: 100%;+ margin-bottom: 30px;++ :global([class*='_dropdown_']) {+ width: 100%;+ }+ }+}diff --git a/frontend/src/components/Settings/IntegrationSettings/IntegrationSettings.tsx b/frontend/src/components/Settings/IntegrationSettings/IntegrationSettings.tsxindex 0db70da..bcc7995 100644--- a/frontend/src/components/Settings/IntegrationSettings/IntegrationSettings.tsx+++ b/frontend/src/components/Settings/IntegrationSettings/IntegrationSettings.tsx@@ -1,9 +1,10 @@import { useState } from 'react';import classes from './IntegrationSettings.module.scss';-import Input from '../../common/form/Input/Input';-import ActionModal from '../../common/ActionModal/ActionModal';-import { useValidateIntegration } from '../../../services/settings';import SMTPSettings from './SMTPSettings';+import NtfySettings from './NtfySettings';+import Icon from '../../common/Icon/Icon';+import Select from '../../common/form/Select/Select';+import { isMobile } from '../../../utils';interface IntegrationSettingsProps {settingsID: number;@@ -12,12 +13,9 @@ interface IntegrationSettingsProps {}const IntegrationSettings = ({ settingsID, settings, onUpdate }: IntegrationSettingsProps) => {- const [testEmail, setTestEmail] = useState('');- const [showEmailTestModal, setShowEmailTestModal] = useState<'' | 'smtp'>('');+ const [tab, setTab] = useState<'smtp' | 'ntfy'>('smtp');const integrationSettings = settings?.integration || {};- const { smtp } = integrationSettings || {};-- const validationMutation = useValidateIntegration();+ const { smtp, ntfy } = integrationSettings || {};const onIntegrationUpdate = (key: string, intSettings: Record<string, any>) => {console.log('onIntegrationUpdate :', key, intSettings);@@ -26,42 +24,47 @@ const IntegrationSettings = ({ settingsID, settings, onUpdate }: IntegrationSettreturn (<div className={classes.integrations}>- <div>- <SMTPSettings- settings={smtp}- onUpdate={(iSettings) => onIntegrationUpdate('smtp', iSettings)}- showTestModal={(type) => setShowEmailTestModal(type)}- />- </div>- {showEmailTestModal && (- <ActionModal- title={`Test SMTP Integration`}- message={- <>- <Input- label="Send Test Email to this email"- full={true}- fieldValue={testEmail}- onUpdate={(val) => setTestEmail(val)}- type="email"- placeholder="[email protected]"- />- </>- }- errorMessage={validationMutation.error?.message}- successMessage={validationMutation.isSuccess ? 'Test email sent. Integration validated successfully.' : ''}- closeModal={() => setShowEmailTestModal('')}- width="400px"- secondaryAction={{ title: 'Close', action: () => setShowEmailTestModal('') }}- primaryAction={{- title: `Send Test Email`,- type: 'default',- icon: 'email',- isPending: validationMutation.isPending,- action: () => validationMutation.mutate({ settingsID, type: 'smtp', settings: settings, test: { email: testEmail } }),- }}+ {isMobile() ? (+ <Select+ customClasses={classes.integrationSelect}+ options={[+ { label: 'SMTP', value: 'smtp', icon: 'email' },+ { label: 'Ntfy', value: 'ntfy', icon: 'ntfy' },+ ]}+ fieldValue={tab}+ full={true}+ onUpdate={(val) => setTab(val as 'smtp' | 'ntfy')}/>+ ) : (+ <>+ <ul className={classes.tabs}>+ <li className={`${tab === 'smtp' ? classes.tabActive : ''}`} onClick={() => setTab('smtp')}>+ <Icon type="email" size={14} /> SMTP+ {smtp?.connected && <Icon type="check-circle-filled" size={12} />}+ </li>+ <li className={`${tab === 'ntfy' ? classes.tabActive : ''}`} onClick={() => setTab('ntfy')}>+ <Icon type="ntfy" size={14} /> Ntfy+ {ntfy?.connected && <Icon type="check-circle-filled" size={12} />}+ </li>+ </ul>+ </>)}+ <div>+ {tab === 'smtp' && (+ <SMTPSettings+ settingsID={settingsID}+ settings={integrationSettings}+ onUpdate={(iSettings) => onIntegrationUpdate('smtp', iSettings)}+ />+ )}+ {tab === 'ntfy' && (+ <NtfySettings+ settingsID={settingsID}+ settings={integrationSettings}+ onUpdate={(iSettings) => onIntegrationUpdate('ntfy', iSettings)}+ />+ )}+ </div></div>);};diff --git a/frontend/src/components/Settings/IntegrationSettings/NtfySettings.tsx b/frontend/src/components/Settings/IntegrationSettings/NtfySettings.tsxnew file mode 100644index 0000000..9c9a83c--- /dev/null+++ b/frontend/src/components/Settings/IntegrationSettings/NtfySettings.tsx@@ -0,0 +1,106 @@+import { useState } from 'react';+import classes from './IntegrationSettings.module.scss';+import { IntegrationSettings, NtfySettingsType } from '../../../@types';+import Icon from '../../common/Icon/Icon';+import Select from '../../common/form/Select/Select';+import Input from '../../common/form/Input/Input';+import ActionModal from '../../common/ActionModal/ActionModal';+import { useValidateIntegration } from '../../../services';+import PasswordField from '../../common/form/PasswordField/PasswordField';++interface NtfySettingsProps {+ settingsID: number;+ settings: IntegrationSettings;+ onUpdate: (settings: NtfySettingsType) => void;+}++const NtfySettings = ({ settingsID, settings, onUpdate }: NtfySettingsProps) => {+ const [ntfySettings, setNtfySettings] = useState<NtfySettingsType>(settings?.ntfy || { authType: 'token', authToken: '', connected: false });+ const [errorFields, setErrorFields] = useState<{ authToken: string }>({ authToken: '' });+ const [showTestModal, setShowTestModal] = useState(false);+ const [testUrl, setTestUrl] = useState('');+ const validationMutation = useValidateIntegration();++ const authType = ntfySettings.authType || 'token';++ const updateNtfySettings = (updated: NtfySettingsType) => {+ setNtfySettings(updated);+ onUpdate(updated);+ };++ const validateSettings = (e: React.FormEvent) => {+ e.preventDefault();++ const newErrors = { authToken: '' };++ if (!ntfySettings?.authToken) {+ newErrors.authToken = 'Required';+ }+ setErrorFields(newErrors);+ const hasErrors = Object.values(newErrors).some((error) => error !== '');+ if (!hasErrors) {+ setShowTestModal(true);+ }+ };++ return (+ <div>+ <div className={classes.field}>+ <Select+ label="Auth Type*"+ fieldValue={authType}+ options={[{ label: 'Token', value: 'token' }]}+ onUpdate={(val) => updateNtfySettings({ ...ntfySettings, authType: val })}+ inline={true}+ />+ </div>+ <div className={classes.field}>+ <PasswordField+ label="Auth Token*"+ fieldValue={ntfySettings.authToken}+ onUpdate={(val) => updateNtfySettings({ ...ntfySettings, authToken: val })}+ error={errorFields?.authToken}+ />+ </div>+ <div className={classes.field}>+ <button className={classes.validateBtn} onClick={validateSettings} type="button">+ <Icon type="check" size={10} /> {ntfySettings.connected ? 'Re-validate Ntfy' : 'Validate Ntfy'}+ </button>+ </div>+ {showTestModal && (+ <ActionModal+ title={`Test Ntfy Integration`}+ message={+ <>+ <Input+ label="Send Test Notification to this topic"+ full={true}+ inline={false}+ fieldValue={testUrl}+ onUpdate={(val) => setTestUrl(val)}+ type="text"+ placeholder="test/topic url. Eg: https://ntfy.sh/testtopic"+ />+ </>+ }+ errorMessage={validationMutation.error?.message}+ successMessage={validationMutation.isSuccess ? 'Test notification sent. Integration validated successfully.' : ''}+ closeModal={() => setShowTestModal(false)}+ width="400px"+ secondaryAction={{ title: 'Close', action: () => setShowTestModal(false) }}+ primaryAction={{+ title: `Send Test Notification`,+ type: 'default',+ icon: 'send',+ isPending: validationMutation.isPending,+ action: () =>+ testUrl &&+ validationMutation.mutate({ settingsID, type: 'ntfy', settings: { ...settings, ntfy: ntfySettings }, test: { url: testUrl } }),+ }}+ />+ )}+ </div>+ );+};++export default NtfySettings;diff --git a/frontend/src/components/Settings/IntegrationSettings/SMTPSettings.tsx b/frontend/src/components/Settings/IntegrationSettings/SMTPSettings.tsxindex 7e15416..9ac43e3 100644--- a/frontend/src/components/Settings/IntegrationSettings/SMTPSettings.tsx+++ b/frontend/src/components/Settings/IntegrationSettings/SMTPSettings.tsx@@ -3,42 +3,47 @@ import Input from '../../common/form/Input/Input';import Icon from '../../common/Icon/Icon';import { isValidEmail } from '../../../utils/helpers';import { SmtpSettingsType } from '../../../@types/settings';+import { IntegrationSettings } from '../../../@types';import classes from './IntegrationSettings.module.scss';+import ValidateEmailIntegration from './ValidateEmailIntegration';interface SMTPSettingsProps {- settings: SmtpSettingsType;+ settingsID: number;+ settings: IntegrationSettings;onUpdate: (settings: SmtpSettingsType) => void;- showTestModal: (type: 'smtp') => void;}-const SMTPSettings = ({ settings, onUpdate, showTestModal }: SMTPSettingsProps) => {+const SMTPSettings = ({ settingsID, settings, onUpdate }: SMTPSettingsProps) => {+ const [showTestModal, setShowTestModal] = useState(false);const [errorFields, setErrorFields] = useState<{ server: string; port: string; senderEmail: string }>({server: '',port: '',senderEmail: '',});+ const smtpSettings = settings?.smtp || { server: '', port: 587, senderEmail: '', username: '', password: '', connected: false };+const validateSettings = (e: React.FormEvent) => {e.preventDefault();const newErrors = { server: '', port: '', senderEmail: '' };- if (!settings?.server) {+ if (!smtpSettings?.server) {newErrors.server = 'Server is required';}- if (!settings?.port) {+ if (!smtpSettings?.port) {newErrors.port = 'Port is required';}- if (!settings?.senderEmail) {+ if (!smtpSettings?.senderEmail) {newErrors.senderEmail = 'Sender Email is required';- } else if (!isValidEmail(settings.senderEmail)) {+ } else if (!isValidEmail(smtpSettings.senderEmail)) {newErrors.senderEmail = 'Invalid email';}setErrorFields(newErrors);const hasErrors = Object.values(newErrors).some((error) => error !== '');if (!hasErrors) {- showTestModal('smtp');+ setShowTestModal(true);}};@@ -47,16 +52,16 @@ const SMTPSettings = ({ settings, onUpdate, showTestModal }: SMTPSettingsProps)<div className={classes.field}><Inputlabel="SMTP Server*"- fieldValue={(settings?.server || '') as string}- onUpdate={(val) => onUpdate({ ...settings, server: val })}+ fieldValue={(smtpSettings?.server || '') as string}+ onUpdate={(val) => onUpdate({ ...smtpSettings, server: val })}error={errorFields?.server}/></div><div className={classes.field}><Inputlabel="SMTP PORT*"- fieldValue={(settings?.port || '') as string}- onUpdate={(val) => onUpdate({ ...settings, port: parseInt(val, 10) })}+ fieldValue={(smtpSettings?.port || '') as string}+ onUpdate={(val) => onUpdate({ ...smtpSettings, port: parseInt(val, 10) })}error={errorFields?.port}/></div>@@ -64,32 +69,36 @@ const SMTPSettings = ({ settings, onUpdate, showTestModal }: SMTPSettingsProps)<Inputlabel="Sender Email*"type="email"- fieldValue={(settings?.senderEmail || '') as string}- onUpdate={(val) => onUpdate({ ...settings, senderEmail: val })}+ fieldValue={(smtpSettings?.senderEmail || '') as string}+ onUpdate={(val) => onUpdate({ ...smtpSettings, senderEmail: val })}error={errorFields?.senderEmail}/></div><div className={classes.field}><Inputlabel="SMTP Username"- fieldValue={(settings?.username || '') as string}- onUpdate={(val) => onUpdate({ ...settings, username: val })}+ fieldValue={(smtpSettings?.username || '') as string}+ onUpdate={(val) => onUpdate({ ...smtpSettings, username: val })}/></div><div className={classes.field}><Inputlabel="SMTP Password"- fieldValue={(settings?.password || '') as string}+ fieldValue={(smtpSettings?.password || '') as string}type="password"- onUpdate={(val) => onUpdate({ ...settings, password: val })}+ onUpdate={(val) => onUpdate({ ...smtpSettings, password: val })}/></div><div className={classes.field}><button className={classes.validateBtn} onClick={validateSettings} type="button">- <Icon type="check" size={10} /> {settings?.connected ? 'Re-validate SMTP' : 'Validate SMTP'}+ <Icon type="check" size={10} /> {smtpSettings?.connected ? 'Re-validate SMTP' : 'Validate SMTP'}</button></div>++ {showTestModal && (+ <ValidateEmailIntegration settingsID={settingsID} settings={settings} integrationType="smtp" onClose={() => setShowTestModal(false)} />+ )}</div>);};diff --git a/frontend/src/components/Settings/IntegrationSettings/ValidateEmailIntegration.tsx b/frontend/src/components/Settings/IntegrationSettings/ValidateEmailIntegration.tsxnew file mode 100644index 0000000..b13949f--- /dev/null+++ b/frontend/src/components/Settings/IntegrationSettings/ValidateEmailIntegration.tsx@@ -0,0 +1,58 @@+import { useState } from 'react';+import Input from '../../common/form/Input/Input';+import ActionModal from '../../common/ActionModal/ActionModal';+import { useValidateIntegration } from '../../../services';+import { INTEGRATIONS_AVAILABLE, IntegrationSettings, IntegrationTypes } from '../../../@types';++interface ValidateEmailIntegrationProps {+ settingsID: number;+ settings: IntegrationSettings;+ integrationType: IntegrationTypes;+ onClose: () => void;+}++const ValidateEmailIntegration = ({ settingsID, settings, integrationType, onClose }: ValidateEmailIntegrationProps) => {+ const [testEmail, setTestEmail] = useState('');+ const validationMutation = useValidateIntegration();+ const integrationName = INTEGRATIONS_AVAILABLE[integrationType as IntegrationTypes].name;++ return (+ <ActionModal+ title={`Test ${integrationName} Integration`}+ message={+ <>+ <Input+ label="Send Test Email to this email"+ full={true}+ inline={false}+ fieldValue={testEmail}+ onUpdate={(val) => setTestEmail(val)}+ type="email"+ placeholder="[email protected]"+ />+ </>+ }+ errorMessage={validationMutation.error?.message}+ successMessage={validationMutation.isSuccess ? `Test email sent. ${integrationName} validated successfully.` : ''}+ closeModal={onClose}+ width="400px"+ secondaryAction={{ title: 'Close', action: onClose }}+ primaryAction={{+ title: 'Send Test Email',+ type: 'default',+ icon: 'email',+ isPending: validationMutation.isPending,+ action: () =>+ testEmail &&+ validationMutation.mutate({+ settingsID,+ type: integrationType,+ settings: { ...settings },+ test: { email: testEmail },+ }),+ }}+ />+ );+};++export default ValidateEmailIntegration;diff --git a/frontend/src/components/index.ts b/frontend/src/components/index.tsindex 49b2a45..fbd6889 100644--- a/frontend/src/components/index.ts+++ b/frontend/src/components/index.ts@@ -113,6 +113,8 @@ export { default as AppLogs } from './Settings/AppLogs/AppLogs';export { default as GeneralSettings } from './Settings/GeneralSettings/GeneralSettings';export { default as IntegrationSettings } from './Settings/IntegrationSettings/IntegrationSettings';export { default as SMTPSettings } from './Settings/IntegrationSettings/SMTPSettings';+export { default as NtfySettings } from './Settings/IntegrationSettings/NtfySettings';+export { default as ValidateEmailIntegration } from './Settings/IntegrationSettings/ValidateEmailIntegration';export { default as TwoFactorSetup } from './Settings/TwoFactorSetup/TwoFactorSetup';// Skeleton componentsdiff --git a/frontend/src/services/settings.ts b/frontend/src/services/settings.tsindex d6cf1e4..1e17136 100644--- a/frontend/src/services/settings.ts+++ b/frontend/src/services/settings.ts@@ -2,6 +2,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { experimental_createQueryPersister } from '@tanstack/react-query-persist-client';import { API_URL } from '../utils/constants';import { useNavigate } from 'react-router';+import { IntegrationSettings } from '../@types';// ============== Settings API ==============@@ -136,10 +137,9 @@ export function useGetDownloadAppLogs() {export async function validateIntegration(updatePayload: {settingsID: number;type: string;- settings: Record<string, string | boolean | number>;+ settings: IntegrationSettings;test: Record<string, string | boolean | number>;}) {- console.log('updatePayload :', updatePayload);const header = new Headers({ 'Content-Type': 'application/json', Accept: 'application/json' });const res = await fetch(`${API_URL}/settings/integration/validate`, {method: 'POST',