90 lines
2.6 KiB
TypeScript
90 lines
2.6 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
import { authOptions } from '@/lib/auth';
|
|
import { EmailService } from '@/lib/services/email-service';
|
|
import { prisma } from '@/lib/prisma';
|
|
import { MailCredentials } from '@prisma/client';
|
|
|
|
// Keep track of last prefetch time for each user
|
|
const lastPrefetchMap = new Map<string, number>();
|
|
const PREFETCH_COOLDOWN_MS = 30000; // 30 seconds cooldown between prefetches
|
|
|
|
// Cache TTL for folders in Redis (5 minutes)
|
|
const FOLDERS_CACHE_TTL = 3600; // 1 hour
|
|
|
|
// Redis key for folders cache
|
|
const FOLDERS_CACHE_KEY = (userId: string, accountId: string) => `email:folders:${userId}:${accountId}`;
|
|
|
|
/**
|
|
* This endpoint is called when the app initializes to check if the user has email credentials
|
|
* and to start prefetching email data in the background if they do
|
|
*/
|
|
export async function GET() {
|
|
try {
|
|
// Authentication check
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
// Get user with their accounts
|
|
const user = await prisma.user.findUnique({
|
|
where: { id: session.user.id },
|
|
include: {
|
|
mailCredentials: {
|
|
select: {
|
|
id: true,
|
|
email: true,
|
|
password: true,
|
|
host: true,
|
|
port: true,
|
|
userId: true,
|
|
createdAt: true,
|
|
updatedAt: true
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
if (!user) {
|
|
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
|
}
|
|
|
|
const accounts = Array.isArray(user.mailCredentials) ? user.mailCredentials : [];
|
|
if (accounts.length === 0) {
|
|
return NextResponse.json({
|
|
authenticated: true,
|
|
accounts: [],
|
|
message: 'No email accounts found'
|
|
});
|
|
}
|
|
|
|
// Get folders for each account using EmailService
|
|
const emailService = EmailService.getInstance();
|
|
const accountsWithFolders = await Promise.all(
|
|
accounts.map(async (account: MailCredentials) => {
|
|
const folders = await emailService.getFolders(user.id, {
|
|
...account,
|
|
imapHost: account.host,
|
|
imapPort: account.port,
|
|
imapSecure: true
|
|
});
|
|
return {
|
|
...account,
|
|
folders
|
|
};
|
|
})
|
|
);
|
|
|
|
return NextResponse.json({
|
|
authenticated: true,
|
|
accounts: accountsWithFolders
|
|
});
|
|
} catch (error) {
|
|
console.error('Error in session route:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Internal server error' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|