80 lines
2.2 KiB
TypeScript
80 lines
2.2 KiB
TypeScript
import { prisma } from '@/lib/prisma';
|
|
import { syncInfomaniakCalendar } from './caldav-sync';
|
|
import { logger } from '@/lib/logger';
|
|
|
|
/**
|
|
* Run periodic sync for all enabled calendar syncs
|
|
* This should be called by a cron job or scheduled task
|
|
*/
|
|
export async function runCalendarSyncJob(): Promise<void> {
|
|
try {
|
|
logger.info('Starting calendar sync job');
|
|
|
|
// Get all enabled sync configurations that need syncing
|
|
const syncConfigs = await prisma.calendarSync.findMany({
|
|
where: {
|
|
syncEnabled: true,
|
|
},
|
|
include: {
|
|
calendar: true,
|
|
mailCredential: true,
|
|
},
|
|
});
|
|
|
|
logger.info('Found sync configurations', {
|
|
count: syncConfigs.length,
|
|
});
|
|
|
|
const results = {
|
|
total: syncConfigs.length,
|
|
successful: 0,
|
|
failed: 0,
|
|
skipped: 0,
|
|
};
|
|
|
|
for (const syncConfig of syncConfigs) {
|
|
try {
|
|
// Check if sync is needed
|
|
if (syncConfig.lastSyncAt) {
|
|
const minutesSinceLastSync =
|
|
(Date.now() - syncConfig.lastSyncAt.getTime()) / (1000 * 60);
|
|
if (minutesSinceLastSync < syncConfig.syncFrequency) {
|
|
logger.debug('Sync skipped - too soon', {
|
|
calendarSyncId: syncConfig.id,
|
|
minutesSinceLastSync,
|
|
syncFrequency: syncConfig.syncFrequency,
|
|
});
|
|
results.skipped++;
|
|
continue;
|
|
}
|
|
}
|
|
|
|
// Sync based on provider
|
|
if (syncConfig.provider === 'infomaniak') {
|
|
await syncInfomaniakCalendar(syncConfig.id, false);
|
|
results.successful++;
|
|
} else {
|
|
logger.warn('Unknown sync provider', {
|
|
calendarSyncId: syncConfig.id,
|
|
provider: syncConfig.provider,
|
|
});
|
|
results.skipped++;
|
|
}
|
|
} catch (error) {
|
|
logger.error('Error syncing calendar', {
|
|
calendarSyncId: syncConfig.id,
|
|
error: error instanceof Error ? error.message : String(error),
|
|
});
|
|
results.failed++;
|
|
}
|
|
}
|
|
|
|
logger.info('Calendar sync job completed', results);
|
|
} catch (error) {
|
|
logger.error('Error running calendar sync job', {
|
|
error: error instanceof Error ? error.message : String(error),
|
|
});
|
|
throw error;
|
|
}
|
|
}
|