feat: update webhook to support global webhook (#407)

This commit is contained in:
Dream Hunter
2024-08-15 00:23:31 +08:00
committed by GitHub
parent c969c4b082
commit 621476cb79
17 changed files with 416 additions and 216 deletions

View File

@@ -1,26 +1,9 @@
import { Context } from "hono";
import { HonoCustomType } from "../types";
import { CONSTANTS } from "../constants";
import { AdminWebhookSettings, WebhookMail } from "../models";
import { AdminWebhookSettings, WebhookSettings } from "../models";
import { getBooleanValue } from "../utils";
import { commonParseMail } from "../common";
class WebhookSettings {
url: string = ''
method: string = 'POST'
headers: string = JSON.stringify({
"Content-Type": "application/json"
}, null, 2)
body: string = JSON.stringify({
"from": "${from}",
"to": "${to}",
"subject": "${subject}",
"raw": "${raw}",
"parsedText": "${parsedText}",
"parsedHtml": "${parsedHtml}",
}, null, 2)
}
import { commonParseMail, sendWebhook } from "../common";
async function getWebhookSettings(c: Context<HonoCustomType>): Promise<Response> {
@@ -55,63 +38,6 @@ async function saveWebhookSettings(c: Context<HonoCustomType>): Promise<Response
return c.json({ success: true })
}
async function sendWebhook(settings: WebhookSettings, formatMap: WebhookMail): Promise<{ success: boolean, message?: string }> {
// send webhook
let body = settings.body;
for (const key of Object.keys(formatMap)) {
/* eslint-disable no-useless-escape */
body = body.replace(
new RegExp(`\\$\\{${key}\\}`, "g"),
JSON.stringify(
formatMap[key as keyof WebhookMail]
).replace(/^"(.*)"$/, '\$1')
);
/* eslint-enable no-useless-escape */
}
const response = await fetch(settings.url, {
method: settings.method,
headers: JSON.parse(settings.headers),
body: body
});
if (!response.ok) {
console.log("send webhook error", response.status, response.statusText);
return { success: false, message: `send webhook error: ${response.status} ${response.statusText}` };
}
return { success: true }
}
export async function trigerWebhook(
c: Context<HonoCustomType>,
address: string,
raw_mail: string
): Promise<void> {
if (!c.env.KV || !getBooleanValue(c.env.ENABLE_WEBHOOK)) {
return
}
const adminSettings = await c.env.KV.get<AdminWebhookSettings>(CONSTANTS.WEBHOOK_KV_SETTINGS_KEY, "json");
if (!adminSettings?.allowList.includes(address)) {
return;
}
const settings = await c.env.KV.get<WebhookSettings>(
`${CONSTANTS.WEBHOOK_KV_USER_SETTINGS_KEY}:${address}`, "json"
);
if (!settings) {
return;
}
const parsedEmail = await commonParseMail(raw_mail);
const res = await sendWebhook(settings, {
from: parsedEmail?.sender || "",
to: address,
subject: parsedEmail?.subject || "",
raw: raw_mail,
parsedText: parsedEmail?.text || "",
parsedHtml: parsedEmail?.html || ""
});
if (!res.success) {
console.log(res.message);
}
}
async function testWebhookSettings(c: Context<HonoCustomType>): Promise<Response> {
const settings = await c.req.json<WebhookSettings>();
const { address } = c.get("jwtPayload");