63 lines
2.3 KiB
TypeScript
63 lines
2.3 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
||
import { getUsers } from "@/lib/users";
|
||
|
||
/**
|
||
* app/api/webhooks/mail/route.ts
|
||
*
|
||
* Webhook endpoint for incoming mail notifications (e.g. from Rspamd or Mailcow).
|
||
* Sends notifications to Telegram based on the recipient email.
|
||
*/
|
||
|
||
export async function POST(req: NextRequest) {
|
||
try {
|
||
const data = await req.json();
|
||
|
||
// Extract basic info from the incoming payload
|
||
const aliciMail = (data.to || data.rcpt || "").toLowerCase().trim();
|
||
const sender = data.from || "Bilinmiyor";
|
||
const subject = data.subject || "(Konu Yok)";
|
||
|
||
console.log(`[Mail Webhook] Yeni mail geldi: ${sender} -> ${aliciMail}`);
|
||
|
||
// 1. Find which USER_X owns this mail address via MAIL_email=USER_X mapping
|
||
const envKey = `MAIL_${aliciMail}`;
|
||
const ownerUserKey = process.env[envKey]; // e.g., "USER_0"
|
||
|
||
if (ownerUserKey) {
|
||
// 2. Get that USER's Telegram ID (e.g., USER_0_TELEGRAM_ID)
|
||
const tgIdKey = `${ownerUserKey}_TELEGRAM_ID`;
|
||
const targetChatId = process.env[tgIdKey];
|
||
|
||
if (targetChatId && process.env.TELEGRAM_BOT_TOKEN) {
|
||
const message = `🔔 *Yeni Mail Geldi!*\n\n📧 *Alıcı:* ${aliciMail}\n👤 *Gönderen:* ${sender}\n📝 *Konu:* ${subject}`;
|
||
|
||
const telegramUrl = `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/sendMessage`;
|
||
|
||
const res = await fetch(telegramUrl, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
chat_id: targetChatId,
|
||
text: message,
|
||
parse_mode: "Markdown",
|
||
}),
|
||
});
|
||
|
||
if (!res.ok) {
|
||
const errorText = await res.text();
|
||
console.error(`[Mail Webhook] Telegram API hatası: ${res.status} ${errorText}`);
|
||
} else {
|
||
console.log(`[Webhook] Bildirim ${ownerUserKey} kullanıcısına (ID: ${targetChatId}) gönderildi.`);
|
||
}
|
||
}
|
||
} else {
|
||
console.log(`[Webhook] Sahibi bilinmeyen veya eşleşmeyen mail: ${aliciMail}`);
|
||
}
|
||
|
||
return NextResponse.json({ status: "ok" });
|
||
} catch (error: any) {
|
||
console.error(`[Mail Webhook] Hata: ${error.message}`);
|
||
return NextResponse.json({ error: "İşlem başarısız" }, { status: 500 });
|
||
}
|
||
}
|