-
Notifications
You must be signed in to change notification settings - Fork 3
/
FetchMailboxesHandler.php
103 lines (85 loc) · 3.15 KB
/
FetchMailboxesHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
// This file is part of Bileto.
// Copyright 2022-2024 Probesys
// SPDX-License-Identifier: AGPL-3.0-or-later
namespace App\MessageHandler;
use App\Entity\Mailbox;
use App\Entity\MailboxEmail;
use App\Message\FetchMailboxes;
use App\Repository\MailboxRepository;
use App\Repository\MailboxEmailRepository;
use App\Security\Encryptor;
use Psr\Log\LoggerInterface;
use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Webklex\PHPIMAP;
#[AsMessageHandler]
class FetchMailboxesHandler
{
public function __construct(
private MailboxRepository $mailboxRepository,
private MailboxEmailRepository $mailboxEmailRepository,
private Encryptor $encryptor,
private LockFactory $lockFactory,
private LoggerInterface $logger,
) {
}
public function __invoke(FetchMailboxes $message): void
{
$mailboxes = $this->mailboxRepository->findAll();
foreach ($mailboxes as $mailbox) {
$lock = $this->lockFactory->createLock("fetch-mailbox.{$mailbox->getId()}", ttl: 10 * 60);
if (!$lock->acquire()) {
continue;
}
try {
$this->fetchMailbox($mailbox);
} catch (\Exception $e) {
$error = $e->getMessage();
$mailbox->setLastError($error);
$this->mailboxRepository->save($mailbox, true);
$this->logger->error("Mailbox #{$mailbox->getId()} error: {$error}");
} finally {
$lock->release();
}
}
}
protected function fetchMailbox(Mailbox $mailbox): void
{
$clientManager = new PHPIMAP\ClientManager();
$client = $clientManager->make([
'host' => $mailbox->getHost(),
'protocol' => $mailbox->getProtocol(),
'port' => $mailbox->getPort(),
'encryption' => $mailbox->getEncryption(),
'validate_cert' => true,
'username' => $mailbox->getUsername(),
'password' => $this->encryptor->decrypt($mailbox->getPassword()),
]);
$client->connect();
$postAction = $mailbox->getPostAction();
$folder = $client->getFolderByPath($mailbox->getFolder());
$messages = $folder->messages()->unseen()->get();
$error = '';
foreach ($messages as $email) {
$mailboxEmail = new MailboxEmail($mailbox, $email);
$this->mailboxEmailRepository->save($mailboxEmail, true);
if ($postAction === 'delete') {
try {
$email->delete();
} catch (\Exception $e) {
$error = $e->getMessage();
$this->logger->warning(
"Mailbox #{$mailbox->getId()} error (will try to mark as seen): {$error}"
);
$email->setFlag('Seen');
}
} elseif ($postAction === 'mark as read') {
$email->setFlag('Seen');
}
}
$client->disconnect();
$mailbox->setLastError($error);
$this->mailboxRepository->save($mailbox, true);
}
}