125 lines
3.7 KiB
TypeScript
125 lines
3.7 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
||
import { prisma } from "@/lib/prisma";
|
||
|
||
/**
|
||
* app/api/webhooks/mail/route.ts
|
||
*
|
||
* Webhook endpoint for incoming mail notifications.
|
||
* Uses Prisma to look up user mappings in the database.
|
||
*/
|
||
|
||
export async function POST(req: NextRequest) {
|
||
let aliciMail = "Bilinmiyor";
|
||
let sender = "Bilinmiyor";
|
||
let subject = "(Konu Yok)";
|
||
|
||
try {
|
||
const data = await req.json();
|
||
console.log("[Mail Webhook] Gelen Payload:", JSON.stringify(data));
|
||
|
||
// Extract basic info from the incoming payload (Mailcow handles these fields)
|
||
aliciMail = (data.to || data.rcpt || "").toLowerCase().trim();
|
||
sender = data.from || "Bilinmiyor";
|
||
subject = data.subject || "(Konu Yok)";
|
||
|
||
console.log(`[Mail Webhook] İşleniyor: ${sender} -> ${aliciMail}`);
|
||
|
||
// 1. Find mapping in database
|
||
const mapping = await prisma.mailboxMapping.findUnique({
|
||
where: { email: aliciMail },
|
||
include: { user: true },
|
||
});
|
||
|
||
if (mapping?.user) {
|
||
const { user } = mapping;
|
||
const targetChatId = user.telegramId;
|
||
|
||
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`;
|
||
|
||
let status = "SENT";
|
||
let errorDetail = null;
|
||
|
||
try {
|
||
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) {
|
||
status = "FAILED";
|
||
errorDetail = `Telegram API Error: ${res.status} ${await res.text()}`;
|
||
}
|
||
} catch (err: any) {
|
||
status = "FAILED";
|
||
errorDetail = `Network Error: ${err.message}`;
|
||
}
|
||
|
||
// Log successful/failed delivery
|
||
await prisma.notificationLog.create({
|
||
data: {
|
||
mailbox: aliciMail,
|
||
sender,
|
||
subject,
|
||
status,
|
||
error: errorDetail,
|
||
userId: user.id,
|
||
},
|
||
});
|
||
} else {
|
||
// Log that user was found but notification skipped
|
||
await prisma.notificationLog.create({
|
||
data: {
|
||
mailbox: aliciMail,
|
||
sender,
|
||
subject,
|
||
status: "FAILED",
|
||
error: !process.env.TELEGRAM_BOT_TOKEN ? "Bot token missing" : "User has no Telegram ID",
|
||
userId: user.id,
|
||
},
|
||
});
|
||
}
|
||
} else {
|
||
console.log(`[Webhook] Sahibi bilinmeyen veya eşleşmeyen mail: ${aliciMail}`);
|
||
|
||
// Log unmapped mail
|
||
await prisma.notificationLog.create({
|
||
data: {
|
||
mailbox: aliciMail,
|
||
sender,
|
||
subject,
|
||
status: "FAILED",
|
||
error: "No user mapping found for this email",
|
||
},
|
||
});
|
||
}
|
||
|
||
return NextResponse.json({ status: "ok" });
|
||
} catch (error: any) {
|
||
console.error(`[Mail Webhook] Hata: ${error.message}`);
|
||
|
||
// Attempt to log the fatal error if we have enough info
|
||
try {
|
||
await prisma.notificationLog.create({
|
||
data: {
|
||
mailbox: aliciMail,
|
||
sender,
|
||
subject,
|
||
status: "FAILED",
|
||
error: `Fatal Error: ${error.message}`,
|
||
},
|
||
});
|
||
} catch (dbErr) {
|
||
console.error("[Mail Webhook] Could not even log the error to DB");
|
||
}
|
||
|
||
return NextResponse.json({ error: "İşlem başarısız" }, { status: 500 });
|
||
}
|
||
}
|