mail_calendar_sync/lib/BackgroundJob/ProcessImipResponsesJob.php
2026-02-09 23:02:34 -05:00

95 lines
3.1 KiB
PHP

<?php
declare(strict_types=1);
namespace OCA\MailCalendarSync\BackgroundJob;
use OCA\MailCalendarSync\Db\ConfigMapper;
use OCA\MailCalendarSync\Db\LogMapper;
use OCA\MailCalendarSync\Db\ProcessedMessageMapper;
use OCA\MailCalendarSync\Service\SyncService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
use Psr\Log\LoggerInterface;
/**
* Background job that scans for new iMIP calendar responses
* in connected mail accounts and applies them to calendars.
*
* The job itself runs every 5 minutes (the minimum), but
* per-user sync intervals are respected via last-sync tracking.
*/
class ProcessImipResponsesJob extends TimedJob {
public function __construct(
ITimeFactory $time,
private SyncService $syncService,
private ConfigMapper $configMapper,
private LogMapper $logMapper,
private ProcessedMessageMapper $processedMapper,
private LoggerInterface $logger,
) {
parent::__construct($time);
// Job checks every 5 minutes; per-user interval handled in run()
$this->setInterval(300);
$this->setTimeSensitivity(self::TIME_SENSITIVE);
}
protected function run(mixed $argument): void {
$this->logger->info('Starting mail-calendar sync background job');
try {
$configs = $this->configMapper->findAllEnabled();
$totalProcessed = 0;
$totalUpdated = 0;
$totalErrors = 0;
foreach ($configs as $config) {
$userId = $config->getUserId();
// Check if enough time has passed since last sync for this user
$syncInterval = $config->getSyncInterval();
$lastSync = $config->getUpdatedAt();
if ($lastSync !== null && $syncInterval > 300) {
$lastSyncTime = strtotime($lastSync);
if ($lastSyncTime !== false && (time() - $lastSyncTime) < $syncInterval) {
continue; // Not time yet for this user
}
}
try {
$stats = $this->syncService->syncForUser($userId);
$totalProcessed += $stats['processed'];
$totalUpdated += $stats['updated'];
$totalErrors += $stats['errors'];
} catch (\Throwable $e) {
$totalErrors++;
$this->logger->error('Sync failed for user', [
'userId' => $userId,
'exception' => $e,
]);
}
}
$this->logger->info('Mail-calendar sync completed', [
'users' => count($configs),
'processed' => $totalProcessed,
'updated' => $totalUpdated,
'errors' => $totalErrors,
]);
// Periodic cleanup of old records
$this->logMapper->cleanupOld(30);
$this->processedMapper->cleanupOld(90);
} catch (\Throwable $e) {
$this->logger->error('Mail-calendar sync background job failed', [
'exception' => $e,
]);
}
}
}