Hi, From Dokploy 👋
", - ); - return true; - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: `${error instanceof Error ? error.message : "Unknown error"}`, - cause: error, - }); - } - }), - createResend: adminProcedure - .input(apiCreateResend) - .mutation(async ({ input, ctx }) => { - try { - return await createResendNotification( - input, - ctx.session.activeOrganizationId, - ); - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error creating the notification", - cause: error, - }); - } - }), - updateResend: adminProcedure - .input(apiUpdateResend) - .mutation(async ({ input, ctx }) => { - try { - const notification = await findNotificationById(input.notificationId); - if (notification.organizationId !== ctx.session.activeOrganizationId) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "You are not authorized to update this notification", - }); - } - return await updateResendNotification({ - ...input, - organizationId: ctx.session.activeOrganizationId, - }); - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error updating the notification", - cause: error, - }); - } - }), - testResendConnection: adminProcedure - .input(apiTestResendConnection) - .mutation(async ({ input }) => { - try { - await sendResendNotification( - input, - "Test Email", - "Hi, From Dokploy 👋
", - ); - return true; - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: `${error instanceof Error ? error.message : "Unknown error"}`, - cause: error, - }); - } - }), - remove: adminProcedure - .input(apiFindOneNotification) - .mutation(async ({ input, ctx }) => { - try { - const notification = await findNotificationById(input.notificationId); - if (notification.organizationId !== ctx.session.activeOrganizationId) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "You are not authorized to delete this notification", - }); - } - return await removeNotificationById(input.notificationId); - } catch (error) { - const message = - error instanceof Error - ? error.message - : "Error deleting this notification"; - throw new TRPCError({ - code: "BAD_REQUEST", - message, - }); - } - }), - one: protectedProcedure - .input(apiFindOneNotification) - .query(async ({ input, ctx }) => { - const notification = await findNotificationById(input.notificationId); - if (notification.organizationId !== ctx.session.activeOrganizationId) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "You are not authorized to access this notification", - }); - } - return notification; - }), - all: adminProcedure.query(async ({ ctx }) => { - return await db.query.notifications.findMany({ - with: { - slack: true, - telegram: true, - discord: true, - email: true, - resend: true, - gotify: true, - ntfy: true, - custom: true, - lark: true, - pushover: true, - }, - orderBy: desc(notifications.createdAt), - where: eq(notifications.organizationId, ctx.session.activeOrganizationId), - }); - }), - receiveNotification: publicProcedure - .input( - z.object({ - ServerType: z.enum(["Dokploy", "Remote"]).default("Dokploy"), - Type: z.enum(["Memory", "CPU"]), - Value: z.number(), - Threshold: z.number(), - Message: z.string(), - Timestamp: z.string(), - Token: z.string(), - }), - ) - .mutation(async ({ input }) => { - try { - let organizationId = ""; - let ServerName = ""; - if (input.ServerType === "Dokploy") { - const settings = await getWebServerSettings(); - if ( - !settings?.metricsConfig?.server?.token || - settings.metricsConfig.server.token !== input.Token - ) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Token not found", - }); - } - - // For Dokploy server type, we don't have a specific organizationId - // This might need to be adjusted based on your business logic - organizationId = ""; - ServerName = "Dokploy"; - } else { - const result = await db - .select() - .from(server) - .where( - sql`${server.metricsConfig}::jsonb -> 'server' ->> 'token' = ${input.Token}`, - ); - - if (!result?.[0]?.organizationId) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Token not found", - }); - } - - organizationId = result?.[0]?.organizationId; - ServerName = "Remote"; - } - - await sendServerThresholdNotifications(organizationId, { - ...input, - ServerName, - }); - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error sending the notification", - cause: error, - }); - } - }), - createGotify: adminProcedure - .input(apiCreateGotify) - .mutation(async ({ input, ctx }) => { - try { - return await createGotifyNotification( - input, - ctx.session.activeOrganizationId, - ); - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error creating the notification", - cause: error, - }); - } - }), - updateGotify: adminProcedure - .input(apiUpdateGotify) - .mutation(async ({ input, ctx }) => { - try { - const notification = await findNotificationById(input.notificationId); - if ( - IS_CLOUD && - notification.organizationId !== ctx.session.activeOrganizationId - ) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "You are not authorized to update this notification", - }); - } - return await updateGotifyNotification({ - ...input, - organizationId: ctx.session.activeOrganizationId, - }); - } catch (error) { - throw error; - } - }), - testGotifyConnection: adminProcedure - .input(apiTestGotifyConnection) - .mutation(async ({ input }) => { - try { - await sendGotifyNotification( - input, - "Test Notification", - "Hi, From Dokploy 👋", - ); - return true; - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error testing the notification", - cause: error, - }); - } - }), - createNtfy: adminProcedure - .input(apiCreateNtfy) - .mutation(async ({ input, ctx }) => { - try { - return await createNtfyNotification( - input, - ctx.session.activeOrganizationId, - ); - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error creating the notification", - cause: error, - }); - } - }), - updateNtfy: adminProcedure - .input(apiUpdateNtfy) - .mutation(async ({ input, ctx }) => { - try { - const notification = await findNotificationById(input.notificationId); - if ( - IS_CLOUD && - notification.organizationId !== ctx.session.activeOrganizationId - ) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "You are not authorized to update this notification", - }); - } - return await updateNtfyNotification({ - ...input, - organizationId: ctx.session.activeOrganizationId, - }); - } catch (error) { - throw error; - } - }), - testNtfyConnection: adminProcedure - .input(apiTestNtfyConnection) - .mutation(async ({ input }) => { - try { - await sendNtfyNotification( - input, - "Test Notification", - "", - "view, visit Dokploy on Github, https://github.com/dokploy/dokploy, clear=true;", - "Hi, From Dokploy 👋", - ); - return true; - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error testing the notification", - cause: error, - }); - } - }), - createCustom: adminProcedure - .input(apiCreateCustom) - .mutation(async ({ input, ctx }) => { - try { - return await createCustomNotification( - input, - ctx.session.activeOrganizationId, - ); - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error creating the notification", - cause: error, - }); - } - }), - updateCustom: adminProcedure - .input(apiUpdateCustom) - .mutation(async ({ input, ctx }) => { - try { - const notification = await findNotificationById(input.notificationId); - if (notification.organizationId !== ctx.session.activeOrganizationId) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "You are not authorized to update this notification", - }); - } - return await updateCustomNotification({ - ...input, - organizationId: ctx.session.activeOrganizationId, - }); - } catch (error) { - throw error; - } - }), - testCustomConnection: adminProcedure - .input(apiTestCustomConnection) - .mutation(async ({ input }) => { - try { - await sendCustomNotification(input, { - title: "Test Notification", - message: "Hi, From Dokploy 👋", - timestamp: new Date().toISOString(), - }); - return true; - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: `${error instanceof Error ? error.message : "Unknown error"}`, - cause: error, - }); - } - }), - createLark: adminProcedure - .input(apiCreateLark) - .mutation(async ({ input, ctx }) => { - try { - return await createLarkNotification( - input, - ctx.session.activeOrganizationId, - ); - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error creating the notification", - cause: error, - }); - } - }), - updateLark: adminProcedure - .input(apiUpdateLark) - .mutation(async ({ input, ctx }) => { - try { - const notification = await findNotificationById(input.notificationId); - if ( - IS_CLOUD && - notification.organizationId !== ctx.session.activeOrganizationId - ) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "You are not authorized to update this notification", - }); - } - return await updateLarkNotification({ - ...input, - organizationId: ctx.session.activeOrganizationId, - }); - } catch (error) { - throw error; - } - }), - testLarkConnection: adminProcedure - .input(apiTestLarkConnection) - .mutation(async ({ input }) => { - try { - await sendLarkNotification(input, { - msg_type: "text", - content: { - text: "Hi, From Dokploy 👋", - }, - }); - return true; - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error testing the notification", - cause: error, - }); - } - }), - createPushover: adminProcedure - .input(apiCreatePushover) - .mutation(async ({ input, ctx }) => { - try { - return await createPushoverNotification( - input, - ctx.session.activeOrganizationId, - ); - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error creating the notification", - cause: error, - }); - } - }), - updatePushover: adminProcedure - .input(apiUpdatePushover) - .mutation(async ({ input, ctx }) => { - try { - const notification = await findNotificationById(input.notificationId); - if ( - IS_CLOUD && - notification.organizationId !== ctx.session.activeOrganizationId - ) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "You are not authorized to update this notification", - }); - } - return await updatePushoverNotification({ - ...input, - organizationId: ctx.session.activeOrganizationId, - }); - } catch (error) { - throw error; - } - }), - testPushoverConnection: adminProcedure - .input(apiTestPushoverConnection) - .mutation(async ({ input }) => { - try { - await sendPushoverNotification( - input, - "Test Notification", - "Hi, From Dokploy 👋", - ); - return true; - } catch (error) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error testing the notification", - cause: error, - }); - } - }), - getEmailProviders: adminProcedure.query(async ({ ctx }) => { - return await db.query.notifications.findMany({ - where: eq(notifications.organizationId, ctx.session.activeOrganizationId), - with: { - email: true, - resend: true, - }, - }); - }), -}); +} from "@/server/db/schema"; + +export const notificationRouter = createTRPCRouter({ + createSlack: adminProcedure + .input(apiCreateSlack) + .mutation(async ({ input, ctx }) => { + try { + return await createSlackNotification( + input, + ctx.session.activeOrganizationId, + ); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error creating the notification", + cause: error, + }); + } + }), + updateSlack: adminProcedure + .input(apiUpdateSlack) + .mutation(async ({ input, ctx }) => { + try { + const notification = await findNotificationById(input.notificationId); + if (notification.organizationId !== ctx.session.activeOrganizationId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } + return await updateSlackNotification({ + ...input, + organizationId: ctx.session.activeOrganizationId, + }); + } catch (error) { + throw error; + } + }), + testSlackConnection: adminProcedure + .input(apiTestSlackConnection) + .mutation(async ({ input }) => { + try { + await sendSlackNotification(input, { + channel: input.channel, + text: "Hi, From Dokploy 👋", + }); + return true; + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: `${error instanceof Error ? error.message : "Unknown error"}`, + cause: error, + }); + } + }), + createTelegram: adminProcedure + .input(apiCreateTelegram) + .mutation(async ({ input, ctx }) => { + try { + return await createTelegramNotification( + input, + ctx.session.activeOrganizationId, + ); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error creating the notification", + cause: error, + }); + } + }), + + updateTelegram: adminProcedure + .input(apiUpdateTelegram) + .mutation(async ({ input, ctx }) => { + try { + const notification = await findNotificationById(input.notificationId); + if (notification.organizationId !== ctx.session.activeOrganizationId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } + return await updateTelegramNotification({ + ...input, + organizationId: ctx.session.activeOrganizationId, + }); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error updating the notification", + cause: error, + }); + } + }), + testTelegramConnection: adminProcedure + .input(apiTestTelegramConnection) + .mutation(async ({ input }) => { + try { + await sendTelegramNotification(input, "Hi, From Dokploy 👋"); + return true; + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error testing the notification", + cause: error, + }); + } + }), + createDiscord: adminProcedure + .input(apiCreateDiscord) + .mutation(async ({ input, ctx }) => { + try { + return await createDiscordNotification( + input, + ctx.session.activeOrganizationId, + ); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error creating the notification", + cause: error, + }); + } + }), + + updateDiscord: adminProcedure + .input(apiUpdateDiscord) + .mutation(async ({ input, ctx }) => { + try { + const notification = await findNotificationById(input.notificationId); + if (notification.organizationId !== ctx.session.activeOrganizationId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } + return await updateDiscordNotification({ + ...input, + organizationId: ctx.session.activeOrganizationId, + }); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error updating the notification", + cause: error, + }); + } + }), + + testDiscordConnection: adminProcedure + .input(apiTestDiscordConnection) + .mutation(async ({ input }) => { + try { + const decorate = (decoration: string, text: string) => + `${input.decoration ? decoration : ""} ${text}`.trim(); + + await sendDiscordNotification(input, { + title: decorate(">", "`🤚` - Test Notification"), + description: decorate(">", "Hi, From Dokploy 👋"), + color: 0xf3f7f4, + }); + + return true; + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: `${error instanceof Error ? error.message : "Unknown error"}`, + cause: error, + }); + } + }), + createEmail: adminProcedure + .input(apiCreateEmail) + .mutation(async ({ input, ctx }) => { + try { + return await createEmailNotification( + input, + ctx.session.activeOrganizationId, + ); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error creating the notification", + cause: error, + }); + } + }), + updateEmail: adminProcedure + .input(apiUpdateEmail) + .mutation(async ({ input, ctx }) => { + try { + const notification = await findNotificationById(input.notificationId); + if (notification.organizationId !== ctx.session.activeOrganizationId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } + return await updateEmailNotification({ + ...input, + organizationId: ctx.session.activeOrganizationId, + }); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error updating the notification", + cause: error, + }); + } + }), + testEmailConnection: adminProcedure + .input(apiTestEmailConnection) + .mutation(async ({ input }) => { + try { + await sendEmailNotification( + input, + "Test Email", + "Hi, From Dokploy 👋
", + ); + return true; + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: `${error instanceof Error ? error.message : "Unknown error"}`, + cause: error, + }); + } + }), + createResend: adminProcedure + .input(apiCreateResend) + .mutation(async ({ input, ctx }) => { + try { + return await createResendNotification( + input, + ctx.session.activeOrganizationId, + ); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error creating the notification", + cause: error, + }); + } + }), + updateResend: adminProcedure + .input(apiUpdateResend) + .mutation(async ({ input, ctx }) => { + try { + const notification = await findNotificationById(input.notificationId); + if (notification.organizationId !== ctx.session.activeOrganizationId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } + return await updateResendNotification({ + ...input, + organizationId: ctx.session.activeOrganizationId, + }); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error updating the notification", + cause: error, + }); + } + }), + testResendConnection: adminProcedure + .input(apiTestResendConnection) + .mutation(async ({ input }) => { + try { + await sendResendNotification( + input, + "Test Email", + "Hi, From Dokploy 👋
", + ); + return true; + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: `${error instanceof Error ? error.message : "Unknown error"}`, + cause: error, + }); + } + }), + remove: adminProcedure + .input(apiFindOneNotification) + .mutation(async ({ input, ctx }) => { + try { + const notification = await findNotificationById(input.notificationId); + if (notification.organizationId !== ctx.session.activeOrganizationId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to delete this notification", + }); + } + return await removeNotificationById(input.notificationId); + } catch (error) { + const message = + error instanceof Error + ? error.message + : "Error deleting this notification"; + throw new TRPCError({ + code: "BAD_REQUEST", + message, + }); + } + }), + one: protectedProcedure + .input(apiFindOneNotification) + .query(async ({ input, ctx }) => { + const notification = await findNotificationById(input.notificationId); + if (notification.organizationId !== ctx.session.activeOrganizationId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to access this notification", + }); + } + return notification; + }), + all: adminProcedure.query(async ({ ctx }) => { + return await db.query.notifications.findMany({ + with: { + slack: true, + telegram: true, + discord: true, + email: true, + resend: true, + gotify: true, + ntfy: true, + custom: true, + lark: true, + pushover: true, + }, + orderBy: desc(notifications.createdAt), + where: eq(notifications.organizationId, ctx.session.activeOrganizationId), + }); + }), + receiveNotification: publicProcedure + .input( + z.object({ + ServerType: z.enum(["Dokploy", "Remote"]).default("Dokploy"), + Type: z.enum(["Memory", "CPU"]), + Value: z.number(), + Threshold: z.number(), + Message: z.string(), + Timestamp: z.string(), + Token: z.string(), + }), + ) + .mutation(async ({ input }) => { + try { + let organizationId = ""; + let ServerName = ""; + if (input.ServerType === "Dokploy") { + const settings = await getWebServerSettings(); + if ( + !settings?.metricsConfig?.server?.token || + settings.metricsConfig.server.token !== input.Token + ) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Token not found", + }); + } + + // For Dokploy server type, we don't have a specific organizationId + // This might need to be adjusted based on your business logic + organizationId = ""; + ServerName = "Dokploy"; + } else { + const result = await db + .select() + .from(server) + .where( + sql`${server.metricsConfig}::jsonb -> 'server' ->> 'token' = ${input.Token}`, + ); + + if (!result?.[0]?.organizationId) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Token not found", + }); + } + + organizationId = result?.[0]?.organizationId; + ServerName = "Remote"; + } + + await sendServerThresholdNotifications(organizationId, { + ...input, + ServerName, + }); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error sending the notification", + cause: error, + }); + } + }), + createGotify: adminProcedure + .input(apiCreateGotify) + .mutation(async ({ input, ctx }) => { + try { + return await createGotifyNotification( + input, + ctx.session.activeOrganizationId, + ); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error creating the notification", + cause: error, + }); + } + }), + updateGotify: adminProcedure + .input(apiUpdateGotify) + .mutation(async ({ input, ctx }) => { + try { + const notification = await findNotificationById(input.notificationId); + if ( + IS_CLOUD && + notification.organizationId !== ctx.session.activeOrganizationId + ) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } + return await updateGotifyNotification({ + ...input, + organizationId: ctx.session.activeOrganizationId, + }); + } catch (error) { + throw error; + } + }), + testGotifyConnection: adminProcedure + .input(apiTestGotifyConnection) + .mutation(async ({ input }) => { + try { + await sendGotifyNotification( + input, + "Test Notification", + "Hi, From Dokploy 👋", + ); + return true; + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error testing the notification", + cause: error, + }); + } + }), + createNtfy: adminProcedure + .input(apiCreateNtfy) + .mutation(async ({ input, ctx }) => { + try { + return await createNtfyNotification( + input, + ctx.session.activeOrganizationId, + ); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error creating the notification", + cause: error, + }); + } + }), + updateNtfy: adminProcedure + .input(apiUpdateNtfy) + .mutation(async ({ input, ctx }) => { + try { + const notification = await findNotificationById(input.notificationId); + if ( + IS_CLOUD && + notification.organizationId !== ctx.session.activeOrganizationId + ) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } + return await updateNtfyNotification({ + ...input, + organizationId: ctx.session.activeOrganizationId, + }); + } catch (error) { + throw error; + } + }), + testNtfyConnection: adminProcedure + .input(apiTestNtfyConnection) + .mutation(async ({ input }) => { + try { + await sendNtfyNotification( + input, + "Test Notification", + "", + "view, visit Dokploy on Github, https://github.com/dokploy/dokploy, clear=true;", + "Hi, From Dokploy 👋", + ); + return true; + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error testing the notification", + cause: error, + }); + } + }), + createCustom: adminProcedure + .input(apiCreateCustom) + .mutation(async ({ input, ctx }) => { + try { + return await createCustomNotification( + input, + ctx.session.activeOrganizationId, + ); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error creating the notification", + cause: error, + }); + } + }), + updateCustom: adminProcedure + .input(apiUpdateCustom) + .mutation(async ({ input, ctx }) => { + try { + const notification = await findNotificationById(input.notificationId); + if (notification.organizationId !== ctx.session.activeOrganizationId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } + return await updateCustomNotification({ + ...input, + organizationId: ctx.session.activeOrganizationId, + }); + } catch (error) { + throw error; + } + }), + testCustomConnection: adminProcedure + .input(apiTestCustomConnection) + .mutation(async ({ input }) => { + try { + await sendCustomNotification(input, { + title: "Test Notification", + message: "Hi, From Dokploy 👋", + timestamp: new Date().toISOString(), + }); + return true; + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: `${error instanceof Error ? error.message : "Unknown error"}`, + cause: error, + }); + } + }), + createLark: adminProcedure + .input(apiCreateLark) + .mutation(async ({ input, ctx }) => { + try { + return await createLarkNotification( + input, + ctx.session.activeOrganizationId, + ); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error creating the notification", + cause: error, + }); + } + }), + updateLark: adminProcedure + .input(apiUpdateLark) + .mutation(async ({ input, ctx }) => { + try { + const notification = await findNotificationById(input.notificationId); + if ( + IS_CLOUD && + notification.organizationId !== ctx.session.activeOrganizationId + ) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } + return await updateLarkNotification({ + ...input, + organizationId: ctx.session.activeOrganizationId, + }); + } catch (error) { + throw error; + } + }), + testLarkConnection: adminProcedure + .input(apiTestLarkConnection) + .mutation(async ({ input }) => { + try { + await sendLarkNotification(input, { + msg_type: "text", + content: { + text: "Hi, From Dokploy 👋", + }, + }); + return true; + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error testing the notification", + cause: error, + }); + } + }), + createPushover: adminProcedure + .input(apiCreatePushover) + .mutation(async ({ input, ctx }) => { + try { + return await createPushoverNotification( + input, + ctx.session.activeOrganizationId, + ); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error creating the notification", + cause: error, + }); + } + }), + updatePushover: adminProcedure + .input(apiUpdatePushover) + .mutation(async ({ input, ctx }) => { + try { + const notification = await findNotificationById(input.notificationId); + if ( + IS_CLOUD && + notification.organizationId !== ctx.session.activeOrganizationId + ) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } + return await updatePushoverNotification({ + ...input, + organizationId: ctx.session.activeOrganizationId, + }); + } catch (error) { + throw error; + } + }), + testPushoverConnection: adminProcedure + .input(apiTestPushoverConnection) + .mutation(async ({ input }) => { + try { + await sendPushoverNotification( + input, + "Test Notification", + "Hi, From Dokploy 👋", + ); + return true; + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Error testing the notification", + cause: error, + }); + } + }), + getEmailProviders: adminProcedure.query(async ({ ctx }) => { + return await db.query.notifications.findMany({ + where: eq(notifications.organizationId, ctx.session.activeOrganizationId), + with: { + email: true, + resend: true, + }, + }); + }), +}); diff --git a/packages/server/src/services/notification.ts b/packages/server/src/services/notification.ts index f11619aac..ee329c457 100644 --- a/packages/server/src/services/notification.ts +++ b/packages/server/src/services/notification.ts @@ -1,8 +1,8 @@ -import { db } from "@dokploy/server/db"; -import { - type apiCreateCustom, - type apiCreateDiscord, - type apiCreateEmail, +import { db } from "@dokploy/server/db"; +import { + type apiCreateCustom, + type apiCreateDiscord, + type apiCreateEmail, type apiCreateGotify, type apiCreateLark, type apiCreateNtfy, @@ -32,986 +32,986 @@ import { slack, telegram, } from "@dokploy/server/db/schema"; -import { TRPCError } from "@trpc/server"; -import { eq } from "drizzle-orm"; - -export type Notification = typeof notifications.$inferSelect; - -export const createSlackNotification = async ( - input: typeof apiCreateSlack._type, - organizationId: string, -) => { - await db.transaction(async (tx) => { - const newSlack = await tx - .insert(slack) - .values({ - channel: input.channel, - webhookUrl: input.webhookUrl, - }) - .returning() - .then((value) => value[0]); - - if (!newSlack) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting slack", - }); - } - - const newDestination = await tx - .insert(notifications) - .values({ - slackId: newSlack.slackId, - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - notificationType: "slack", - organizationId: organizationId, - serverThreshold: input.serverThreshold, - }) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting notification", - }); - } - - return newDestination; - }); -}; - -export const updateSlackNotification = async ( - input: typeof apiUpdateSlack._type, -) => { - await db.transaction(async (tx) => { - const newDestination = await tx - .update(notifications) - .set({ - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - organizationId: input.organizationId, - serverThreshold: input.serverThreshold, - }) - .where(eq(notifications.notificationId, input.notificationId)) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error Updating notification", - }); - } - - await tx - .update(slack) - .set({ - channel: input.channel, - webhookUrl: input.webhookUrl, - }) - .where(eq(slack.slackId, input.slackId)) - .returning() - .then((value) => value[0]); - - return newDestination; - }); -}; - -export const createTelegramNotification = async ( - input: typeof apiCreateTelegram._type, - organizationId: string, -) => { - await db.transaction(async (tx) => { - const newTelegram = await tx - .insert(telegram) - .values({ - botToken: input.botToken, - chatId: input.chatId, - messageThreadId: input.messageThreadId, - }) - .returning() - .then((value) => value[0]); - - if (!newTelegram) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting telegram", - }); - } - - const newDestination = await tx - .insert(notifications) - .values({ - telegramId: newTelegram.telegramId, - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - notificationType: "telegram", - organizationId: organizationId, - serverThreshold: input.serverThreshold, - }) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting notification", - }); - } - - return newDestination; - }); -}; - -export const updateTelegramNotification = async ( - input: typeof apiUpdateTelegram._type, -) => { - await db.transaction(async (tx) => { - const newDestination = await tx - .update(notifications) - .set({ - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - organizationId: input.organizationId, - serverThreshold: input.serverThreshold, - }) - .where(eq(notifications.notificationId, input.notificationId)) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error Updating notification", - }); - } - - await tx - .update(telegram) - .set({ - botToken: input.botToken, - chatId: input.chatId, - messageThreadId: input.messageThreadId, - }) - .where(eq(telegram.telegramId, input.telegramId)) - .returning() - .then((value) => value[0]); - - return newDestination; - }); -}; - -export const createDiscordNotification = async ( - input: typeof apiCreateDiscord._type, - organizationId: string, -) => { - await db.transaction(async (tx) => { - const newDiscord = await tx - .insert(discord) - .values({ - webhookUrl: input.webhookUrl, - decoration: input.decoration, - }) - .returning() - .then((value) => value[0]); - - if (!newDiscord) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting discord", - }); - } - - const newDestination = await tx - .insert(notifications) - .values({ - discordId: newDiscord.discordId, - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - notificationType: "discord", - organizationId: organizationId, - serverThreshold: input.serverThreshold, - }) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting notification", - }); - } - - return newDestination; - }); -}; - -export const updateDiscordNotification = async ( - input: typeof apiUpdateDiscord._type, -) => { - await db.transaction(async (tx) => { - const newDestination = await tx - .update(notifications) - .set({ - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - organizationId: input.organizationId, - serverThreshold: input.serverThreshold, - }) - .where(eq(notifications.notificationId, input.notificationId)) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error Updating notification", - }); - } - - await tx - .update(discord) - .set({ - webhookUrl: input.webhookUrl, - decoration: input.decoration, - }) - .where(eq(discord.discordId, input.discordId)) - .returning() - .then((value) => value[0]); - - return newDestination; - }); -}; - -export const createEmailNotification = async ( - input: typeof apiCreateEmail._type, - organizationId: string, -) => { - await db.transaction(async (tx) => { - const newEmail = await tx - .insert(email) - .values({ - smtpServer: input.smtpServer, - smtpPort: input.smtpPort, - username: input.username, - password: input.password, - fromAddress: input.fromAddress, - toAddresses: input.toAddresses, - }) - .returning() - .then((value) => value[0]); - - if (!newEmail) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting email", - }); - } - - const newDestination = await tx - .insert(notifications) - .values({ - emailId: newEmail.emailId, - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - notificationType: "email", - organizationId: organizationId, - serverThreshold: input.serverThreshold, - }) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting notification", - }); - } - - return newDestination; - }); -}; - -export const updateEmailNotification = async ( - input: typeof apiUpdateEmail._type, -) => { - await db.transaction(async (tx) => { - const newDestination = await tx - .update(notifications) - .set({ - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - organizationId: input.organizationId, - serverThreshold: input.serverThreshold, - }) - .where(eq(notifications.notificationId, input.notificationId)) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error Updating notification", - }); - } - - await tx - .update(email) - .set({ - smtpServer: input.smtpServer, - smtpPort: input.smtpPort, - username: input.username, - password: input.password, - fromAddress: input.fromAddress, - toAddresses: input.toAddresses, - }) - .where(eq(email.emailId, input.emailId)) - .returning() - .then((value) => value[0]); - - return newDestination; - }); -}; - -export const createResendNotification = async ( - input: typeof apiCreateResend._type, - organizationId: string, -) => { - await db.transaction(async (tx) => { - const newResend = await tx - .insert(resend) - .values({ - apiKey: input.apiKey, - fromAddress: input.fromAddress, - toAddresses: input.toAddresses, - }) - .returning() - .then((value) => value[0]); - - if (!newResend) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting resend", - }); - } - - const newDestination = await tx - .insert(notifications) - .values({ - resendId: newResend.resendId, - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - notificationType: "resend", - organizationId: organizationId, - serverThreshold: input.serverThreshold, - }) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting notification", - }); - } - - return newDestination; - }); -}; - -export const updateResendNotification = async ( - input: typeof apiUpdateResend._type, -) => { - await db.transaction(async (tx) => { - const newDestination = await tx - .update(notifications) - .set({ - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - organizationId: input.organizationId, - serverThreshold: input.serverThreshold, - }) - .where(eq(notifications.notificationId, input.notificationId)) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error Updating notification", - }); - } - - await tx - .update(resend) - .set({ - apiKey: input.apiKey, - fromAddress: input.fromAddress, - toAddresses: input.toAddresses, - }) - .where(eq(resend.resendId, input.resendId)) - .returning() - .then((value) => value[0]); - - return newDestination; - }); -}; - -export const createGotifyNotification = async ( - input: typeof apiCreateGotify._type, - organizationId: string, -) => { - await db.transaction(async (tx) => { - const newGotify = await tx - .insert(gotify) - .values({ - serverUrl: input.serverUrl, - appToken: input.appToken, - priority: input.priority, - decoration: input.decoration, - }) - .returning() - .then((value) => value[0]); - - if (!newGotify) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting gotify", - }); - } - - const newDestination = await tx - .insert(notifications) - .values({ - gotifyId: newGotify.gotifyId, - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - notificationType: "gotify", - organizationId: organizationId, - }) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting notification", - }); - } - - return newDestination; - }); -}; - -export const updateGotifyNotification = async ( - input: typeof apiUpdateGotify._type, -) => { - await db.transaction(async (tx) => { - const newDestination = await tx - .update(notifications) - .set({ - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - organizationId: input.organizationId, - }) - .where(eq(notifications.notificationId, input.notificationId)) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error Updating notification", - }); - } - - await tx - .update(gotify) - .set({ - serverUrl: input.serverUrl, - appToken: input.appToken, - priority: input.priority, - decoration: input.decoration, - }) - .where(eq(gotify.gotifyId, input.gotifyId)); - - return newDestination; - }); -}; - -export const createNtfyNotification = async ( - input: typeof apiCreateNtfy._type, - organizationId: string, -) => { - await db.transaction(async (tx) => { - const newNtfy = await tx - .insert(ntfy) - .values({ - serverUrl: input.serverUrl, - topic: input.topic, - accessToken: input.accessToken ?? null, - priority: input.priority, - }) - .returning() - .then((value) => value[0]); - - if (!newNtfy) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting ntfy", - }); - } - - const newDestination = await tx - .insert(notifications) - .values({ - ntfyId: newNtfy.ntfyId, - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - notificationType: "ntfy", - organizationId: organizationId, - }) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting notification", - }); - } - - return newDestination; - }); -}; - -export const updateNtfyNotification = async ( - input: typeof apiUpdateNtfy._type, -) => { - await db.transaction(async (tx) => { - const newDestination = await tx - .update(notifications) - .set({ - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - organizationId: input.organizationId, - }) - .where(eq(notifications.notificationId, input.notificationId)) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error Updating notification", - }); - } - - await tx - .update(ntfy) - .set({ - serverUrl: input.serverUrl, - topic: input.topic, - accessToken: input.accessToken ?? null, - priority: input.priority, - }) - .where(eq(ntfy.ntfyId, input.ntfyId)); - - return newDestination; - }); -}; - -export const createCustomNotification = async ( - input: typeof apiCreateCustom._type, - organizationId: string, -) => { - await db.transaction(async (tx) => { - const newCustom = await tx - .insert(custom) - .values({ - endpoint: input.endpoint, - headers: input.headers, - }) - .returning() - .then((value) => value[0]); - - if (!newCustom) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting custom", - }); - } - - const newDestination = await tx - .insert(notifications) - .values({ - customId: newCustom.customId, - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - notificationType: "custom", - organizationId: organizationId, - serverThreshold: input.serverThreshold, - }) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting notification", - }); - } - - return newDestination; - }); -}; - -export const updateCustomNotification = async ( - input: typeof apiUpdateCustom._type, -) => { - await db.transaction(async (tx) => { - const newDestination = await tx - .update(notifications) - .set({ - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - organizationId: input.organizationId, - serverThreshold: input.serverThreshold, - }) - .where(eq(notifications.notificationId, input.notificationId)) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error Updating notification", - }); - } - - await tx - .update(custom) - .set({ - endpoint: input.endpoint, - headers: input.headers, - }) - .where(eq(custom.customId, input.customId)); - - return newDestination; - }); -}; - -export const findNotificationById = async (notificationId: string) => { - const notification = await db.query.notifications.findFirst({ - where: eq(notifications.notificationId, notificationId), - with: { - slack: true, - telegram: true, - discord: true, - email: true, - resend: true, - gotify: true, - ntfy: true, - custom: true, - lark: true, - pushover: true, - }, - }); - if (!notification) { - throw new TRPCError({ - code: "NOT_FOUND", - message: "Notification not found", - }); - } - return notification; -}; - -export const removeNotificationById = async (notificationId: string) => { - const result = await db - .delete(notifications) - .where(eq(notifications.notificationId, notificationId)) - .returning(); - - return result[0]; -}; - -export const createLarkNotification = async ( - input: typeof apiCreateLark._type, - organizationId: string, -) => { - await db.transaction(async (tx) => { - const newLark = await tx - .insert(lark) - .values({ - webhookUrl: input.webhookUrl, - }) - .returning() - .then((value) => value[0]); - - if (!newLark) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting lark", - }); - } - - const newDestination = await tx - .insert(notifications) - .values({ - larkId: newLark.larkId, - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - notificationType: "lark", - organizationId: organizationId, - serverThreshold: input.serverThreshold, - }) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error input: Inserting notification", - }); - } - - return newDestination; - }); -}; - -export const updateLarkNotification = async ( - input: typeof apiUpdateLark._type, -) => { - await db.transaction(async (tx) => { - const newDestination = await tx - .update(notifications) - .set({ - name: input.name, - appDeploy: input.appDeploy, - appBuildError: input.appBuildError, - databaseBackup: input.databaseBackup, - volumeBackup: input.volumeBackup, - dokployRestart: input.dokployRestart, - dockerCleanup: input.dockerCleanup, - organizationId: input.organizationId, - serverThreshold: input.serverThreshold, - }) - .where(eq(notifications.notificationId, input.notificationId)) - .returning() - .then((value) => value[0]); - - if (!newDestination) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Error Updating notification", - }); - } - - await tx - .update(lark) - .set({ - webhookUrl: input.webhookUrl, - }) - .where(eq(lark.larkId, input.larkId)) - .returning() - .then((value) => value[0]); - - return newDestination; - }); -}; - -export const updateNotificationById = async ( - notificationId: string, - notificationData: Partial${errorMessage}`
- : "";
- const sizeInfo = backupSize ? `\nBackup Size: ${backupSize}` : "";
-
- const messageText = `${statusEmoji} Volume Backup ${typeStatus}\n\nProject: ${projectName}\nApplication: ${applicationName}\nVolume Name: ${volumeName}\nService Type: ${serviceType}${sizeInfo}\nDate: ${format(date, "PP")}\nTime: ${format(date, "pp")}${isError ? errorMsg : ""}`;
-
- await sendTelegramNotification(telegram, messageText);
- }
-
- if (slack) {
- const { channel } = slack;
- await sendSlackNotification(slack, {
- channel: channel,
- attachments: [
- {
- color: type === "success" ? "#00FF00" : "#FF0000",
- pretext:
- type === "success"
- ? ":white_check_mark: *Volume Backup Successful*"
- : ":x: *Volume Backup Failed*",
- fields: [
- ...(type === "error" && errorMessage
- ? [
- {
- title: "Error Message",
- value: errorMessage,
- short: false,
- },
- ]
- : []),
- {
- title: "Project",
- value: projectName,
- short: true,
- },
- {
- title: "Application",
- value: applicationName,
- short: true,
- },
- {
- title: "Volume Name",
- value: volumeName,
- short: true,
- },
- {
- title: "Service Type",
- value: serviceType,
- short: true,
- },
- ...(backupSize
- ? [
- {
- title: "Backup Size",
- value: backupSize,
- short: true,
- },
- ]
- : []),
- {
- title: "Time",
- value: date.toLocaleString(),
- short: true,
- },
- {
- title: "Type",
- value: type,
- short: true,
- },
- {
- title: "Status",
- value: type === "success" ? "Successful" : "Failed",
- short: true,
- },
- ],
- },
- ],
- });
- }
-
- if (pushover) {
- await sendPushoverNotification(
- pushover,
- `Volume Backup ${type === "success" ? "Successful" : "Failed"}`,
- `Project: ${projectName}\nApplication: ${applicationName}\nVolume: ${volumeName}\nService Type: ${serviceType}${backupSize ? `\nBackup Size: ${backupSize}` : ""}\nDate: ${date.toLocaleString()}${type === "error" && errorMessage ? `\nError: ${errorMessage}` : ""}`,
- );
- }
- }
-};
+
+export const sendVolumeBackupNotifications = async ({
+ projectName,
+ applicationName,
+ volumeName,
+ serviceType,
+ type,
+ errorMessage,
+ organizationId,
+ backupSize,
+}: {
+ projectName: string;
+ applicationName: string;
+ volumeName: string;
+ serviceType:
+ | "application"
+ | "postgres"
+ | "mysql"
+ | "mongodb"
+ | "mariadb"
+ | "redis"
+ | "compose";
+ type: "error" | "success";
+ organizationId: string;
+ errorMessage?: string;
+ backupSize?: string;
+}) => {
+ const date = new Date();
+ const unixDate = ~~(Number(date) / 1000);
+ const notificationList = await db.query.notifications.findMany({
+ where: and(
+ eq(notifications.volumeBackup, true),
+ eq(notifications.organizationId, organizationId),
+ ),
+ with: {
+ email: true,
+ discord: true,
+ telegram: true,
+ slack: true,
+ resend: true,
+ gotify: true,
+ ntfy: true,
+ pushover: true,
+ },
+ });
+
+ for (const notification of notificationList) {
+ const { email, resend, discord, telegram, slack, gotify, ntfy, pushover } =
+ notification;
+
+ if (email || resend) {
+ const subject = `Volume Backup ${type === "success" ? "Successful" : "Failed"} - ${applicationName}`;
+ const htmlContent = await renderAsync(
+ VolumeBackupEmail({
+ projectName,
+ applicationName,
+ volumeName,
+ serviceType,
+ type,
+ errorMessage,
+ backupSize,
+ date: date.toISOString(),
+ }),
+ );
+ if (email) {
+ await sendEmailNotification(email, subject, htmlContent);
+ }
+ if (resend) {
+ await sendResendNotification(resend, subject, htmlContent);
+ }
+ }
+
+ if (discord) {
+ const decorate = (decoration: string, text: string) =>
+ `${discord.decoration ? decoration : ""} ${text}`.trim();
+
+ await sendDiscordNotification(discord, {
+ title:
+ type === "success"
+ ? decorate(">", "`✅` Volume Backup Successful")
+ : decorate(">", "`❌` Volume Backup Failed"),
+ color: type === "success" ? 0x57f287 : 0xed4245,
+ fields: [
+ {
+ name: decorate("`🛠️`", "Project"),
+ value: projectName,
+ inline: true,
+ },
+ {
+ name: decorate("`⚙️`", "Application"),
+ value: applicationName,
+ inline: true,
+ },
+ {
+ name: decorate("`💾`", "Volume Name"),
+ value: volumeName,
+ inline: true,
+ },
+ {
+ name: decorate("`🔧`", "Service Type"),
+ value: serviceType,
+ inline: true,
+ },
+ ...(backupSize
+ ? [
+ {
+ name: decorate("`📊`", "Backup Size"),
+ value: backupSize,
+ inline: true,
+ },
+ ]
+ : []),
+ {
+ name: decorate("`📅`", "Date"),
+ value: `${errorMessage}`
+ : "";
+ const sizeInfo = backupSize ? `\nBackup Size: ${backupSize}` : "";
+
+ const messageText = `${statusEmoji} Volume Backup ${typeStatus}\n\nProject: ${projectName}\nApplication: ${applicationName}\nVolume Name: ${volumeName}\nService Type: ${serviceType}${sizeInfo}\nDate: ${format(date, "PP")}\nTime: ${format(date, "pp")}${isError ? errorMsg : ""}`;
+
+ await sendTelegramNotification(telegram, messageText);
+ }
+
+ if (slack) {
+ const { channel } = slack;
+ await sendSlackNotification(slack, {
+ channel: channel,
+ attachments: [
+ {
+ color: type === "success" ? "#00FF00" : "#FF0000",
+ pretext:
+ type === "success"
+ ? ":white_check_mark: *Volume Backup Successful*"
+ : ":x: *Volume Backup Failed*",
+ fields: [
+ ...(type === "error" && errorMessage
+ ? [
+ {
+ title: "Error Message",
+ value: errorMessage,
+ short: false,
+ },
+ ]
+ : []),
+ {
+ title: "Project",
+ value: projectName,
+ short: true,
+ },
+ {
+ title: "Application",
+ value: applicationName,
+ short: true,
+ },
+ {
+ title: "Volume Name",
+ value: volumeName,
+ short: true,
+ },
+ {
+ title: "Service Type",
+ value: serviceType,
+ short: true,
+ },
+ ...(backupSize
+ ? [
+ {
+ title: "Backup Size",
+ value: backupSize,
+ short: true,
+ },
+ ]
+ : []),
+ {
+ title: "Time",
+ value: date.toLocaleString(),
+ short: true,
+ },
+ {
+ title: "Type",
+ value: type,
+ short: true,
+ },
+ {
+ title: "Status",
+ value: type === "success" ? "Successful" : "Failed",
+ short: true,
+ },
+ ],
+ },
+ ],
+ });
+ }
+
+ if (pushover) {
+ await sendPushoverNotification(
+ pushover,
+ `Volume Backup ${type === "success" ? "Successful" : "Failed"}`,
+ `Project: ${projectName}\nApplication: ${applicationName}\nVolume: ${volumeName}\nService Type: ${serviceType}${backupSize ? `\nBackup Size: ${backupSize}` : ""}\nDate: ${date.toLocaleString()}${type === "error" && errorMessage ? `\nError: ${errorMessage}` : ""}`,
+ );
+ }
+ }
+};