84 lines
2.2 KiB
TypeScript
84 lines
2.2 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { getServerSession } from "next-auth/next";
|
|
import { authOptions } from "@/app/api/auth/options";
|
|
import { prisma } from "@/lib/prisma";
|
|
import { discoverInfomaniakCalendars } from "@/lib/services/caldav-sync";
|
|
import { logger } from "@/lib/logger";
|
|
|
|
/**
|
|
* Discover CalDAV calendars for an Infomaniak email account
|
|
* POST /api/calendars/sync/discover
|
|
*/
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
|
|
}
|
|
|
|
const { mailCredentialId } = await req.json();
|
|
|
|
if (!mailCredentialId) {
|
|
return NextResponse.json(
|
|
{ error: "mailCredentialId est requis" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Get mail credentials
|
|
const mailCreds = await prisma.mailCredentials.findFirst({
|
|
where: {
|
|
id: mailCredentialId,
|
|
userId: session.user.id,
|
|
},
|
|
});
|
|
|
|
if (!mailCreds) {
|
|
return NextResponse.json(
|
|
{ error: "Credentials non trouvés" },
|
|
{ status: 404 }
|
|
);
|
|
}
|
|
|
|
// Check if it's an Infomaniak account
|
|
if (!mailCreds.host.includes('infomaniak')) {
|
|
return NextResponse.json(
|
|
{ error: "Ce compte n'est pas un compte Infomaniak" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
if (!mailCreds.password) {
|
|
return NextResponse.json(
|
|
{ error: "Mot de passe requis pour la synchronisation CalDAV" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Discover calendars
|
|
const calendars = await discoverInfomaniakCalendars(
|
|
mailCreds.email,
|
|
mailCreds.password
|
|
);
|
|
|
|
logger.info('Calendars discovered', {
|
|
userId: session.user.id,
|
|
email: mailCreds.email,
|
|
calendarsCount: calendars.length,
|
|
});
|
|
|
|
return NextResponse.json({ calendars });
|
|
} catch (error) {
|
|
logger.error('Error discovering calendars', {
|
|
error: error instanceof Error ? error.message : String(error),
|
|
});
|
|
return NextResponse.json(
|
|
{
|
|
error: "Erreur lors de la découverte des calendriers",
|
|
details: error instanceof Error ? error.message : String(error),
|
|
},
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|