feat: implement test connection for all the providers

This commit is contained in:
Mauricio Siu
2024-07-12 01:29:24 -06:00
parent 342ff4b589
commit 5fadd73732
12 changed files with 6308 additions and 191 deletions

View File

@@ -5,15 +5,14 @@ import {
} from "@/server/api/trpc";
import { db } from "@/server/db";
import {
apiCreateDestination,
apiCreateDiscord,
apiCreateEmail,
apiCreateSlack,
apiCreateTelegram,
apiFindOneNotification,
apiSendTest,
apiUpdateDestination,
} from "@/server/db/schema";
import { HeadBucketCommand, S3Client } from "@aws-sdk/client-s3";
import { TRPCError } from "@trpc/server";
import { updateDestinationById } from "../services/destination";
import {
@@ -24,6 +23,7 @@ import {
findNotificationById,
removeNotificationById,
} from "../services/notification";
import nodemailer from "nodemailer";
export const notificationRouter = createTRPCRouter({
createSlack: adminProcedure
@@ -32,6 +32,7 @@ export const notificationRouter = createTRPCRouter({
try {
return await createSlackNotification(input);
} catch (error) {
console.log(error);
throw new TRPCError({
code: "BAD_REQUEST",
message: "Error to create the destination",
@@ -97,30 +98,123 @@ export const notificationRouter = createTRPCRouter({
return notification;
}),
testConnection: adminProcedure
.input(apiCreateDestination)
.input(apiSendTest)
.mutation(async ({ input }) => {
const { secretAccessKey, bucket, region, endpoint, accessKey } = input;
const s3Client = new S3Client({
region: region,
...(endpoint && {
endpoint: endpoint,
}),
credentials: {
accessKeyId: accessKey,
secretAccessKey: secretAccessKey,
},
forcePathStyle: true,
});
const headBucketCommand = new HeadBucketCommand({ Bucket: bucket });
const notificationType = input.notificationType;
console.log(input);
try {
await s3Client.send(headBucketCommand);
} catch (error) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Error to connect to bucket",
cause: error,
});
if (notificationType === "slack") {
// go to your slack dashboard
// go to integrations
// add a new integration
// select incoming webhook
// copy the webhook url
console.log("test slack");
const { webhookUrl, channel } = input;
try {
const response = await fetch(webhookUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ text: "Test notification", channel }),
});
} catch (err) {
console.log(err);
}
} else if (notificationType === "telegram") {
// start telegram
// search BotFather
// send /newbot
// name
// name-with-bot-at-the-end
// copy the token
// search @userinfobot
// send /start
// copy the Id
const { botToken, chatId } = input;
try {
const url = `https://api.telegram.org/bot${botToken}/sendMessage`;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
chat_id: chatId,
text: "Test notification",
}),
});
if (!response.ok) {
throw new Error(
`Error sending Telegram notification: ${response.statusText}`,
);
}
console.log("Telegram notification sent successfully");
} catch (error) {
console.error("Error sending Telegram notification:", error);
throw new Error("Error sending Telegram notification");
}
} else if (notificationType === "discord") {
const { webhookUrl } = input;
try {
// go to your discord server
// go to settings
// go to integrations
// add a new integration
// select webhook
// copy the webhook url
const response = await fetch(webhookUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
content: "Test notification",
}),
});
if (!response.ok) {
throw new Error(
`Error sending Discord notification: ${response.statusText}`,
);
}
console.log("Discord notification sent successfully");
} catch (error) {
console.error("Error sending Discord notification:", error);
throw new Error("Error sending Discord notification");
}
} else if (notificationType === "email") {
const { smtpServer, smtpPort, username, password, toAddresses } = input;
try {
const transporter = nodemailer.createTransport({
host: smtpServer,
port: smtpPort,
secure: smtpPort === "465",
auth: {
user: username,
pass: password,
},
});
// need to add a valid from address
const fromAddress = "no-reply@emails.dokploy.com";
const mailOptions = {
from: fromAddress,
to: toAddresses?.join(", "),
subject: "Test email",
text: "Test email",
};
await transporter.sendMail(mailOptions);
console.log("Email notification sent successfully");
} catch (error) {
console.error("Error sending Email notification:", error);
throw new Error("Error sending Email notification");
}
}
}),

View File

@@ -45,6 +45,7 @@ export const createSlackNotification = async (
appBuildError: input.appBuildError,
databaseBackup: input.databaseBackup,
dokployRestart: input.dokployRestart,
notificationType: "slack",
})
.returning()
.then((value) => value[0]);
@@ -90,6 +91,7 @@ export const createTelegramNotification = async (
appBuildError: input.appBuildError,
databaseBackup: input.databaseBackup,
dokployRestart: input.dokployRestart,
notificationType: "telegram",
})
.returning()
.then((value) => value[0]);
@@ -134,6 +136,7 @@ export const createDiscordNotification = async (
appBuildError: input.appBuildError,
databaseBackup: input.databaseBackup,
dokployRestart: input.dokployRestart,
notificationType: "discord",
})
.returning()
.then((value) => value[0]);
@@ -182,6 +185,7 @@ export const createEmailNotification = async (
appBuildError: input.appBuildError,
databaseBackup: input.databaseBackup,
dokployRestart: input.dokployRestart,
notificationType: "email",
})
.returning()
.then((value) => value[0]);
@@ -239,3 +243,22 @@ export const updateDestinationById = async (
return result[0];
};
export const sendNotification = async (
notificationData: Partial<Notification>,
) => {
// if(notificationData.notificationType === "slack"){
// const { webhookUrl, channel } = notificationData;
// try {
// const response = await fetch(webhookUrl, {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// },
// body: JSON.stringify({ text: "Test notification", channel }),
// });
// } catch (err) {
// console.log(err);
// }
// }
};