243 lines
8.3 KiB
TypeScript
243 lines
8.3 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
|
import { getUserEmailCredentials, getMailboxes } from '@/lib/services/email-service';
|
|
import { prefetchUserEmailData } from '@/lib/services/prefetch-service';
|
|
import { getCachedEmailCredentials, getRedisStatus, warmupRedisCache, getCachedImapSession, cacheImapSession } from '@/lib/redis';
|
|
import { prisma } from '@/lib/prisma';
|
|
import { ImapFlow } from 'imapflow';
|
|
|
|
// 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 to store account folders to avoid repeated calls to the IMAP server
|
|
const accountFoldersCache = new Map<string, { folders: string[], timestamp: number }>();
|
|
const FOLDERS_CACHE_TTL = 5 * 60 * 1000; // 5 minute cache
|
|
|
|
/**
|
|
* Get folders for a specific account
|
|
*/
|
|
async function getAccountFolders(accountId: string, account: any): Promise<string[]> {
|
|
// Check cache first
|
|
const cacheKey = `folders:${accountId}`;
|
|
const cachedData = accountFoldersCache.get(cacheKey);
|
|
const now = Date.now();
|
|
|
|
if (cachedData && (now - cachedData.timestamp < FOLDERS_CACHE_TTL)) {
|
|
return cachedData.folders;
|
|
}
|
|
|
|
try {
|
|
// Connect to IMAP server for this account
|
|
const client = new ImapFlow({
|
|
host: account.host,
|
|
port: account.port,
|
|
secure: true,
|
|
auth: {
|
|
user: account.email,
|
|
pass: account.password,
|
|
},
|
|
logger: false,
|
|
tls: {
|
|
rejectUnauthorized: false
|
|
}
|
|
});
|
|
|
|
await client.connect();
|
|
|
|
// Get folders for this account
|
|
const folders = await getMailboxes(client);
|
|
|
|
// Close connection
|
|
await client.logout();
|
|
|
|
// Cache the result
|
|
accountFoldersCache.set(cacheKey, {
|
|
folders,
|
|
timestamp: now
|
|
});
|
|
|
|
return folders;
|
|
} catch (error) {
|
|
console.error(`Error fetching folders for account ${account.email}:`, error);
|
|
// Return fallback folders on error
|
|
return ['INBOX', 'Sent', 'Drafts', 'Trash'];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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 {
|
|
// Warm up Redis connection
|
|
await warmupRedisCache();
|
|
|
|
// Get Redis status to include in response
|
|
const redisStatus = await getRedisStatus();
|
|
|
|
// Get server session to verify authentication
|
|
const session = await getServerSession(authOptions);
|
|
|
|
// Check if user is authenticated
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({
|
|
authenticated: false,
|
|
redisStatus,
|
|
message: "Not authenticated"
|
|
});
|
|
}
|
|
|
|
const userId = session.user.id;
|
|
|
|
// Check when we last prefetched for this user
|
|
const lastPrefetchTime = lastPrefetchMap.get(userId) || 0;
|
|
const now = Date.now();
|
|
const shouldPrefetch = now - lastPrefetchTime > PREFETCH_COOLDOWN_MS;
|
|
|
|
// Check if we have a cached session
|
|
const cachedSession = await getCachedImapSession(userId);
|
|
console.log(`[DEBUG] Cached session for user ${userId}:`,
|
|
cachedSession ? {
|
|
hasMailboxes: Array.isArray(cachedSession.mailboxes),
|
|
mailboxCount: cachedSession.mailboxes?.length || 0
|
|
} : 'null');
|
|
|
|
// First, check Redis cache for credentials - this is for backward compatibility
|
|
let credentials = await getCachedEmailCredentials(userId);
|
|
console.log(`[DEBUG] Cached credentials for user ${userId}:`,
|
|
credentials ? { email: credentials.email, hasPassword: !!credentials.password } : 'null');
|
|
let credentialsSource = 'cache';
|
|
|
|
// Now fetch all email accounts for this user
|
|
// Query the database directly using Prisma
|
|
try {
|
|
const allAccounts = await prisma.mailCredentials.findMany({
|
|
where: { userId },
|
|
select: {
|
|
id: true,
|
|
email: true,
|
|
password: true,
|
|
host: true,
|
|
port: true
|
|
}
|
|
});
|
|
console.log(`[DEBUG] Found ${allAccounts.length} accounts in database for user ${userId}:`);
|
|
allAccounts.forEach((account, idx) => {
|
|
console.log(`[DEBUG] Account ${idx + 1}: ID=${account.id}, Email=${account.email}`);
|
|
});
|
|
|
|
// Get additional fields that might be in the database but not in the type
|
|
const accountsWithMetadata = await Promise.all(allAccounts.map(async (account) => {
|
|
// Get the raw account data to access fields not in the type
|
|
const rawAccount = await prisma.$queryRaw`
|
|
SELECT display_name, color
|
|
FROM "MailCredentials"
|
|
WHERE id = ${account.id}
|
|
`;
|
|
|
|
// Cast the raw result to an array and get the first item
|
|
const metadata = Array.isArray(rawAccount) ? rawAccount[0] : rawAccount;
|
|
|
|
// Get folders for this specific account
|
|
const accountFolders = await getAccountFolders(account.id, {
|
|
...account,
|
|
...metadata
|
|
});
|
|
|
|
return {
|
|
...account,
|
|
display_name: metadata?.display_name || account.email,
|
|
color: metadata?.color || "#0082c9",
|
|
folders: accountFolders
|
|
};
|
|
}));
|
|
|
|
console.log(`Found ${allAccounts.length} email accounts for user ${userId}`);
|
|
|
|
// If not in cache and no accounts found, check database for single account (backward compatibility)
|
|
if (!credentials && allAccounts.length === 0) {
|
|
credentials = await getUserEmailCredentials(userId);
|
|
credentialsSource = 'database';
|
|
}
|
|
|
|
// If no credentials found
|
|
if (!credentials && allAccounts.length === 0) {
|
|
return NextResponse.json({
|
|
authenticated: true,
|
|
hasEmailCredentials: false,
|
|
redisStatus,
|
|
message: "No email credentials found"
|
|
});
|
|
}
|
|
|
|
let prefetchStarted = false;
|
|
|
|
// Only prefetch if the cooldown period has elapsed
|
|
if (shouldPrefetch) {
|
|
// Update the last prefetch time
|
|
lastPrefetchMap.set(userId, now);
|
|
|
|
// Start prefetching email data in the background
|
|
// We don't await this to avoid blocking the response
|
|
prefetchUserEmailData(userId).catch(err => {
|
|
console.error('Background prefetch error:', err);
|
|
});
|
|
|
|
prefetchStarted = true;
|
|
} else {
|
|
console.log(`Skipping prefetch for ${userId}, last prefetch was ${Math.round((now - lastPrefetchTime)/1000)}s ago`);
|
|
}
|
|
|
|
// Store last visit time in session data
|
|
if (cachedSession) {
|
|
await cacheImapSession(userId, {
|
|
...cachedSession,
|
|
lastActive: cachedSession.lastActive || Date.now(), // Ensure lastActive is set
|
|
lastVisit: now
|
|
});
|
|
} else {
|
|
await cacheImapSession(userId, {
|
|
lastActive: Date.now(),
|
|
lastVisit: now
|
|
});
|
|
}
|
|
|
|
// Return all accounts information with their specific folders
|
|
return NextResponse.json({
|
|
authenticated: true,
|
|
hasEmailCredentials: true,
|
|
email: credentials?.email || (allAccounts.length > 0 ? allAccounts[0].email : ''),
|
|
redisStatus,
|
|
prefetchStarted,
|
|
credentialsSource,
|
|
lastVisit: cachedSession?.lastVisit,
|
|
mailboxes: cachedSession?.mailboxes || [], // For backward compatibility
|
|
allAccounts: accountsWithMetadata.map(account => ({
|
|
id: account.id,
|
|
email: account.email,
|
|
display_name: account.display_name || account.email,
|
|
color: account.color || "#0082c9",
|
|
folders: account.folders || [] // Use account-specific folders
|
|
}))
|
|
});
|
|
} catch (dbError) {
|
|
console.error(`[ERROR] Database query failed:`, dbError);
|
|
return NextResponse.json({
|
|
authenticated: true,
|
|
hasEmailCredentials: false,
|
|
error: "Database query failed",
|
|
details: dbError instanceof Error ? dbError.message : "Unknown database error",
|
|
redisStatus
|
|
}, { status: 500 });
|
|
}
|
|
} catch (error) {
|
|
console.error("Error checking session:", error);
|
|
return NextResponse.json({
|
|
authenticated: false,
|
|
error: "Internal Server Error"
|
|
}, { status: 500 });
|
|
}
|
|
}
|