Full implemantation

This commit is contained in:
2022-11-28 22:56:21 -03:00
parent 30ef4c6a35
commit c53eb4c7a6
55 changed files with 1505 additions and 1011 deletions

View File

@ -3,37 +3,65 @@ namespace ProVM\Common\Service;
use Ddeboer\Imap\Message\AttachmentInterface;
use Ddeboer\Imap\MessageInterface;
use ProVM\Emails\Model\Attachment;
use ProVM\Common\Exception\Message\NoAttachments;
use ProVM\Emails\Model\Message;
use ProVM\Emails\Repository\Attachment;
use Psr\Log\LoggerInterface;
use Safe\Exceptions\FilesystemException;
class Attachments
class Attachments extends Base
{
public function __construct(Decrypt $decrypt, \ProVM\Emails\Repository\Attachment $repository, string $attachments_folder)
public function __construct(Messages $messages, Attachment $repository, Remote\Attachments $remoteService,
Decrypt $decrypt, string $attachments_folder, LoggerInterface $logger)
{
$this->setDecrypt($decrypt);
$this->setAttachmentsFolder($attachments_folder);
$this->setMessages($messages)
->setRepository($repository)
->setRemoteService($remoteService)
->setDecrypt($decrypt)
->setFolder($attachments_folder)
->setLogger($logger);
}
protected string $attachments_folder;
protected Messages $messages;
protected Attachment $repository;
protected Remote\Attachments $remoteService;
protected Decrypt $decrypt;
protected \ProVM\Emails\Repository\Attachment $repository;
protected string $folder;
public function getAttachmentsFolder(): string
public function getMessages(): Messages
{
return $this->attachments_folder;
return $this->messages;
}
public function getRepository(): Attachment
{
return $this->repository;
}
public function getRemoteService(): Remote\Attachments
{
return $this->remoteService;
}
public function getDecrypt(): Decrypt
{
return $this->decrypt;
}
public function getRepository(): \ProVM\Emails\Repository\Attachment
public function getFolder(): string
{
return $this->repository;
return $this->folder;
}
public function setAttachmentsFolder(string $folder): Attachments
public function setMessages(Messages $messages): Attachments
{
$this->attachments_folder = $folder;
$this->messages = $messages;
return $this;
}
public function setRepository(Attachment $repository): Attachments
{
$this->repository = $repository;
return $this;
}
public function setRemoteService(Remote\Attachments $service): Attachments
{
$this->remoteService = $service;
return $this;
}
public function setDecrypt(Decrypt $decrypt): Attachments
@ -41,119 +69,164 @@ class Attachments
$this->decrypt = $decrypt;
return $this;
}
public function setRepository(\ProVM\Emails\Repository\Attachment $repository): Attachments
public function setFolder(string $folder): Attachments
{
$this->repository = $repository;
$this->folder = $folder;
return $this;
}
public function validateAttachment(AttachmentInterface $remote_attachment): bool
public function getLocalAttachment(Message $message, string $relative_filename): \ProVM\Emails\Model\Attachment
{
return str_contains($remote_attachment->getFilename(), '.pdf');
return $this->getRepository()->fetchByMessageAndFilename($message->getId(), $relative_filename);
}
public function getRemoteAttachment(Message $message, string $relative_filename): AttachmentInterface
{
$remote_message = $this->getMessages()->getRemoteMessage($message->getUID());
return $this->getRemoteService()->get($remote_message, $relative_filename);
}
public function buildAttachment(Message $message, AttachmentInterface $remote_attachment): Attachment
public function getAll(): array
{
return $this->getRepository()->fetchAll();
}
public function create(int $message_id): array
{
$message = $this->getMessages()->getRepository()->fetchById($message_id);
$remote_message = $this->getMessages()->getRemoteMessage($message->getUID());
if (!$remote_message->hasAttachments()) {
throw new NoAttachments($remote_message);
}
$attachments = [];
foreach ($remote_message->getAttachments() as $attachment) {
if (!$this->getMessages()->validateAttachment($attachment)) {
continue;
}
if ($this->save($message, $attachment, false)) {
$attachments []= $attachment->getFilename();
}
}
return $attachments;
}
public function grab(int $message_id): array
{
$message = $this->getMessages()->getRepository()->fetchById($message_id);
$remote_message = $this->getMessages()->getRemoteMessage($message->getUID());
if (!$remote_message->hasAttachments()) {
throw new NoAttachments($remote_message);
}
$attachments = [];
foreach ($remote_message->getAttachments() as $attachment) {
if (!$this->getMessages()->validateAttachment($attachment)) {
continue;
}
if ($this->save($message, $attachment)) {
$attachments []= $attachment->getFilename();
}
}
return $attachments;
}
public function save(Message $message, AttachmentInterface $remote_attachment, bool $upload = true): bool
{
$data = [
'message_id' => $message->getId(),
'filename' => $this->buildFilename($message, $remote_attachment)
'filename' => $remote_attachment->getFilename()
];
return $this->getRepository()->create($data);
}
try {
$attachment = $this->getRepository()->create($data);
$this->getRepository()->save($attachment);
if ($upload and $this->upload($attachment, $remote_attachment)) {
$attachment->itIsDownloaded();
$message->doesHaveDownloadedAttachments();
$this->getMessages()->getRepository()->save($message);
public function exists(Attachment $attachment): bool
{
$filename = $this->buildFilename($attachment);
return file_exists($filename);
}
if ($this->isFileEncrypted($attachment->getMessage(), $attachment->getFilename())) {
$attachment->itIsEncrypted();
public function buildFilename(Message $message, AttachmentInterface $attachment): string
{
$filename = implode(' - ', [
$message->getSubject(),
$message->getDateTime()->format('Y-m-d'),
$attachment->getFilename()
]);
return implode(DIRECTORY_SEPARATOR, [
$this->getAttachmentsFolder(),
$filename
]);
}
public function checkEncrypted(): array
{
$output = [];
foreach ($this->fetchAttachments() as $attachment) {
$output[$attachment->getFilename()] = $this->getDecrypt()->isEncrypted($attachment->getRealPath());
}
return $output;
}
public function fetchAttachments(): array
{
$files = new \FilesystemIterator($this->getAttachmentsFolder());
$attachments = [];
foreach ($files as $file) {
if ($file->isDir()) {
continue;
if ($this->isFileDecrypted($attachment->getMessage(), $attachment->getFilename())) {
$attachment->itIsDecrypted();
} else {
if ($this->decrypt($attachment->getMessage(), $attachment->getFilename())) {
$attachment->itIsDecrypted();
}
}
}
}
$attachments []= $file;
}
return $attachments;
}
public function fetchDecryptedAttachments(): array
{
$folder = implode(DIRECTORY_SEPARATOR, [$this->getAttachmentsFolder(), 'decrypted']);
$files = new \FilesystemIterator($folder);
$attachments = [];
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
$attachments []= $file;
}
return $attachments;
}
public function fetchFullAttachments(): array
{
$attachments = $this->fetchAttachments();
$output = [];
foreach ($attachments as $attachment) {
$att = [
'original_attachment' => $attachment,
'encrypted' => $this->getDecrypt()->isEncrypted($attachment->getRealPath())
];
if ($att['encrypted']) {
$att['decrypted_attachment'] = $this->getDecryptedAttachment($attachment);
}
$output []= $att;
}
return $output;
}
public function getAttachment(string $filename): \SplFileInfo
{
if (!str_contains($filename, $this->getAttachmentsFolder())) {
$filename = implode(DIRECTORY_SEPARATOR, [$this->getAttachmentsFolder(), $filename]);
}
return new \SplFileInfo($filename);
}
public function getDecryptedAttachment(\SplFileInfo $info): \SplFileInfo|bool
{
$new_file = implode(DIRECTORY_SEPARATOR, [$info->getPath(), 'decrypted', $info->getFilename()]);
if (!file_exists($new_file)) {
$this->getRepository()->save($attachment);
return true;
} catch (PDOException $e) {
$this->getLogger()->error($e);
return false;
}
return new \SplFileInfo($new_file);
}
public function removeEncryption(string $filename): \SplFileInfo
public function upload(\ProVM\Emails\Model\Attachment $attachment, AttachmentInterface $remote_attachment): bool
{
$attachment = $this->getAttachment($filename);
$new_file = implode(DIRECTORY_SEPARATOR, [$attachment->getPath(), 'decrypted', $attachment->getFilename()]);
if ($this->getDecrypt()->runCommand($attachment->getRealPath(), $new_file)) {
return new \SplFileInfo($new_file);
$destination = implode(DIRECTORY_SEPARATOR, [
$this->getFolder(),
$attachment->getFullFilename()
]);
try {
\Safe\file_put_contents($destination, $remote_attachment->getDecodedContent());
return true;
} catch (FilesystemException $e) {
$this->getLogger()->error($e);
return false;
}
return $attachment;
}
public function isFileEncrypted(Message $message, string $relative_filename): bool
{
$attachment = $this->getLocalAttachment($message, $relative_filename);
$filename = implode(DIRECTORY_SEPARATOR, [
$this->getFolder(),
$attachment->getFullFilename()
]);
try {
return $this->getDecrypt()->isEncrypted($filename);
} catch (\InvalidArgumentException $e) {
return false;
}
}
public function isFileDecrypted(Message $message, string $relative_filename): bool
{
$attachment = $this->getLocalAttachment($message, $relative_filename);
$filename = implode(DIRECTORY_SEPARATOR, [
$this->getFolder(),
'decrypted',
$attachment->getFullFilename()
]);
try {
return !$this->getDecrypt()->isEncrypted($filename);
} catch (\InvalidArgumentException $e) {
return false;
}
}
public function decrypt(Message $message, string $relative_filename): bool
{
$attachment = $this->getLocalAttachment($message, $relative_filename);
$source = implode(DIRECTORY_SEPARATOR, [
$this->getFolder(),
$attachment->getFullFilename()
]);
$destination = implode(DIRECTORY_SEPARATOR, [
$this->getFolder(),
'decrypted',
$attachment->getFullFilename()
]);
return $this->getDecrypt()->runCommand($source, $destination);
}
public function isDownloaded(Message $message, MessageInterface $remote_message): bool
{
if (!$message->hasValidAttachments()) {
return false;
}
foreach ($remote_message->getAttachments() as $attachment) {
if (!str_contains($attachment->getFilename(), '.pdf')) {
continue;
}
$attachment = $this->getLocalAttachment($message, $attachment->getFilename());
if (!$attachment->isDownloaded()) {
return false;
}
}
return true;
}
}

View File

@ -1,158 +0,0 @@
<?php
namespace ProVM\Common\Service;
use Iterator;
use Generator;
use ProVM\Common\Exception\EmptyMailbox;
use Ddeboer\Imap\MailboxInterface;
use Ddeboer\Imap\MessageInterface;
use ProVM\Emails\Repository\Message;
class Emails extends Base
{
public function __construct(Mailboxes $mailboxService, Message $messageRepository, string $attachments_folder)
{
$this->setMailboxes($mailboxService);
$this->setMessageRepository($messageRepository);
$this->setAttachmentsFolder($attachments_folder);
}
protected Message $messageRepository;
protected Mailboxes $mailboxService;
protected string $attachments_folder;
public function getMailboxes(): Mailboxes
{
return $this->mailboxService;
}
public function getMessageRepository(): Message
{
return $this->messageRepository;
}
public function getAttachmentsFolder(): string
{
return $this->attachments_folder;
}
public function setMailboxes(Mailboxes $mailboxService): Emails
{
$this->mailboxService = $mailboxService;
return $this;
}
public function setMessageRepository(Message $messageRepository): Emails
{
$this->messageRepository = $messageRepository;
return $this;
}
public function setAttachmentsFolder(string $folder): Emails
{
$this->attachments_folder = $folder;
return $this;
}
//----------------------------------------------------------------
// Messages
public function getMessages(MailboxInterface $mailbox, int $start = 0, ?int $amount = null): array
{
$output = [];
$cnt = 0;
$messages = $this->getMessageRepository()->fetchByMailboxAndPosition($mailbox->getName(), $start, $amount ?? 1);
if ($messages) {
foreach ($messages as $message) {
$output []= $message;
$cnt ++;
}
}
if ($amount === null or $cnt < $amount) {
$messages = $this->getMailboxes()->getMessages($mailbox, $cnt + $start, $amount ?? $mailbox->count());
foreach ($messages as $m) {
$message = $this->saveMessage($mailbox, $m, $cnt + $start);
$cnt ++;
if ($message === null) {
continue;
}
$output []= $message;
}
}
return $output;
}
public function saveMessage(MailboxInterface $mailbox, MessageInterface $message, int $position): ?\ProVM\Emails\Model\Message
{
$data = [
'mailbox_id' => $mailbox->getId(),
'position' => $position,
'uid' => $message->getNumber(),
'subject' => $message->getSubject(),
'from' => $message->getFrom()->getFullAddress(),
'date_time' => $message->getDate()->format('Y-m-d H:i:s'),
];
return $this->getMessageRepository()->create($data);
}
public function getValidMessages(MailboxInterface $mailbox, int $start = 0, ?int $amount = null): array
{
$messages = $this->getMessages($mailbox, $start, $amount);
$output = array_filter($messages, function(\ProVM\Emails\Model\Message $message) {
return ($message->hasAttachments() and $message->hasValidAttachments());
});
if ($amount === null or count($output) >= $amount) {
return $output;
}
$cnt = $start + $amount;
while (count($output) < $amount) {
\Safe\ini_set('max_execution_time', ((int) \Safe\ini_get('max_execution_time')) + $amount * 5);
$messages = $this->getMailboxes()->getMessages($mailbox, $start + $amount, $amount);
foreach ($messages as $m) {
$message = $this->saveMessage($mailbox, $m, $cnt + $start);
$cnt ++;
if ($message === null) {
continue;
}
if ($message->hasAttachments() and $message->hasValidAttachments() and count($output) < $amount) {
$output []= $message;
}
}
}
return $output;
}
// Attachments
public function saveAttachments(MessageInterface $message, ?string $extension = null): array
{
if (!$message->hasAttachments()) {
return [];
}
$attachments = [];
foreach ($message->getAttachments() as $attachment) {
$this->getLogger()->debug($attachment->getFilename());
if ($extension !== null) {
$extension = trim($extension, '.');
if (!str_contains($attachment->getFilename(), ".{$extension}")) {
continue;
}
}
$filename = implode(DIRECTORY_SEPARATOR, [
$this->getAttachmentsFolder(),
"{$message->getSubject()} - {$message->getDate()->format('Y-m-d')} - {$attachment->getFilename()}"
]);
$this->getLogger()->debug($filename);
\Safe\file_put_contents($filename, $attachment->getDecodedContent());
$attachments []= $filename;
}
return $attachments;
}
public function getAttachments(?string $mailbox = null, int $start = 0, ?int $amount = null, ?string $extension = null): array
{
if ($mailbox === null) {
$mailbox = '/';
}
$mb = $this->getMailboxes()->get($mailbox);
$messages = $this->getMessages($mb, $start, $amount);
$attachments = [];
foreach ($messages as $message) {
$attachments = array_merge($attachments, $this->saveAttachments($message, $extension));
}
return $attachments;
}
}

View File

@ -1,73 +0,0 @@
<?php
namespace ProVM\Common\Service;
use Psr\Log\LoggerInterface;
use PDO;
class Install
{
public function __construct(LoggerInterface $logger, PDO $pdo)
{
$this->setLogger($logger);
$this->setConnection($pdo);
}
protected LoggerInterface $logger;
protected PDO $connection;
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function getConnection(): PDO
{
return $this->connection;
}
public function setLogger(LoggerInterface $logger): Install
{
$this->logger = $logger;
return $this;
}
public function setConnection(PDO $pdo): Install
{
$this->connection = $pdo;
return $this;
}
public function run(): void
{
$tables = [
'messages' => [
'`mailbox_id` int UNSIGNED NOT NULL',
'`position` int UNSIGNED NOT NULL',
'`uid` int UNSIGNED NOT NULL PRIMARY KEY',
'`subject` varchar(255) NOT NULL',
'`from` varchar(100) NOT NULL',
'`date_time` datetime NOT NULL',
'`has_attachments` int(1) DEFAULT 0',
'`valid_attachments` int(1) DEFAULT 0',
'`downloaded_attachments` int(1) DEFAULT 0'
],
'attachments' => [
'`message_uid` int UNSIGNED NOT NULL',
'`filename` varchar(255) NOT NULL PRIMARY KEY',
'`encrypted` int(1) DEFAULT 0',
'`decrypted` int(1) DEFAULT 0',
'CONSTRAINT `message_uid_fk` FOREIGN KEY (`message_uid`) REFERENCES `messages` (`uid`)'
],
'mailboxes' => [
'`'
]
];
foreach ($tables as $table => $definitions) {
$this->getConnection()->query($this->buildCreateTable($table, $definitions));
}
}
protected function buildCreateTable(string $table_name, array $columns): string
{
$query = ["CREATE TABLE IF NOT EXISTS `{$table_name}` ("];
$query []= implode(',' . PHP_EOL, $columns);
$query []= ')';
return implode(PHP_EOL, $query);
}
}

View File

@ -0,0 +1,71 @@
<?php
namespace ProVM\Common\Service;
use PDOException;
use ProVM\Common\Exception\Database\BlankResult;
use Safe\DateTimeImmutable;
use ProVM\Emails\Repository\Job;
class Jobs extends Base
{
public function __construct(Job $repository)
{
$this->setRepository($repository);
}
protected Job $repository;
public function getRepository(): Job
{
return $this->repository;
}
public function setRepository(Job $repository): Jobs
{
$this->repository = $repository;
return $this;
}
public function schedule(int $message_id): bool
{
$data = [
'message_id' => $message_id,
'date_time' => (new DateTimeImmutable())->format('Y-m-d H:i:s')
];
try {
$job = $this->getRepository()->create($data);
$this->getRepository()->save($job);
return true;
} catch (PDOException $e) {
return false;
}
}
public function getPending(): array
{
return $this->getRepository()->fetchAllPending();
}
public function isPending(int $message_id): bool
{
try {
$this->getRepository()->fetchPendingByMessage($message_id);
return true;
} catch (BlankResult $e) {
return false;
}
}
public function find(int $message_id): \ProVM\Emails\Model\Job
{
return $this->getRepository()->fetchPendingByMessage($message_id);
}
public function execute(int $job_id): bool
{
try {
$job = $this->getRepository()->fetchById($job_id);
$job->wasExecuted();
$this->getRepository()->save($job);
return true;
} catch (PDOException $e) {
return false;
}
}
}

View File

@ -1,151 +1,143 @@
<?php
namespace ProVM\Common\Service;
use Ddeboer\Imap\Message\AttachmentInterface;
use Iterator;
use Generator;
use Ddeboer\Imap\ConnectionInterface;
use Ddeboer\Imap\MailboxInterface;
use Ddeboer\Imap\MessageInterface;
use ProVM\Common\Exception\EmptyMailbox;
use ProVM\Common\Exception\Mailbox\Invalid;
use PDOException;
use Psr\Log\LoggerInterface;
use ProVM\Common\Exception\Database\BlankResult;
use ProVM\Emails\Repository\Mailbox;
use ProVM\Common\Service\Remote;
use ProVM\Emails\Repository\State;
class Mailboxes extends Base
{
public function __construct(ConnectionInterface $connection, Attachments $attachments, string $username)
public function __construct(Mailbox $repository, Remote\Mailboxes $remoteService, State\Mailbox $states, LoggerInterface $logger)
{
$this->setConnection($connection)
->setAttachments($attachments)
->setUsername($username);
$this->setRepository($repository)
->setRemoteService($remoteService)
->setStatesRepository($states)
->setLogger($logger);
}
protected ConnectionInterface $connection;
protected Attachments $attachments;
protected string $username;
protected Mailbox $repository;
protected Remote\Mailboxes $remoteService;
protected State\Mailbox $statesRepository;
public function getConnection(): ConnectionInterface
public function getRepository(): Mailbox
{
return $this->connection;
return $this->repository;
}
public function getAttachments(): Attachments
public function getRemoteService(): Remote\Mailboxes
{
return $this->attachments;
return $this->remoteService;
}
public function getUsername(): string
public function getStatesRepository(): State\Mailbox
{
return $this->username;
return $this->statesRepository;
}
public function setConnection(ConnectionInterface $connection): Mailboxes
public function setRepository(Mailbox $repository): Mailboxes
{
$this->connection = $connection;
$this->repository = $repository;
return $this;
}
public function setAttachments(Attachments $attachments): Mailboxes
public function setRemoteService(Remote\Mailboxes $service): Mailboxes
{
$this->attachments = $attachments;
$this->remoteService = $service;
return $this;
}
public function setUsername(string $username): Mailboxes
public function setStatesRepository(State\Mailbox $repository): Mailboxes
{
$this->username = $username;
$this->statesRepository = $repository;
return $this;
}
protected array $mailboxes;
public function getLocalMailbox(string $mailbox_name): \ProVM\Emails\Model\Mailbox
{
return $this->getRepository()->fetchByName($mailbox_name);
}
public function getRemoteMailbox(string $mailbox_name): MailboxInterface
{
return $this->getRemoteService()->get($mailbox_name);
}
public function getAll(): array
{
if (!isset($this->mailboxes)) {
$this->mailboxes = $this->getConnection()->getMailboxes();
}
return $this->mailboxes;
return $this->getRemoteService()->getAll();
}
public function get(string $mailbox): MailboxInterface
public function getRegistered(): array
{
if (!$this->getConnection()->hasMailbox($mailbox)) {
throw new Invalid();
}
return $this->getConnection()->getMailbox($mailbox);
return $this->getRepository()->fetchAll();
}
public function get(int $mailbox_id): \ProVM\Emails\Model\Mailbox
{
return $this->getRepository()->fetchById($mailbox_id);
}
// Messages
protected function advanceIterator(Iterator $iterator, int $up_to): Iterator
public function isRegistered(string $mailbox_name): bool
{
for ($i = 0; $i < $up_to; $i ++) {
$iterator->next();
try {
$mailbox = $this->getRepository()->fetchByName($mailbox_name);
return true;
} catch (BlankResult $e) {
return false;
}
return $iterator;
}
public function getMessages(MailboxInterface $mailbox, int $start = 0, ?int $amount = null): Generator
public function register(string $mailbox_name): bool
{
if ($mailbox->count() === 0) {
$this->getLogger()->notice('No mails found.');
throw new EmptyMailbox();
}
$it = $mailbox->getIterator();
if ($amount === null) {
$amount = $mailbox->count() - $start;
}
$it = $this->advanceIterator($it, $start);
for ($i = $start; $i < min($start + $amount, $mailbox->count()); $i ++) {
yield $it->key() => $it->current();
$it->next();
$remote_mailbox = $this->getRemoteMailbox($mailbox_name);
$name = $remote_mailbox->getName();
$validity = $remote_mailbox->getStatus()->uidvalidity;
try {
$mailbox = $this->getRepository()->create(compact('name', 'validity'));
$this->getRepository()->save($mailbox);
return true;
} catch (PDOException $e) {
return false;
}
}
public function countValid(MailboxInterface $mailbox): int
public function updateState(\ProVM\Emails\Model\Mailbox $mailbox, array $messages, \DateTimeInterface $dateTime): bool
{
$cnt = 0;
foreach ($mailbox->getIterator() as $message) {
if ($this->hasAttachments($message) and $this->validAttachments($message)) {
$cnt ++;
}
$data = [
'mailbox_id' => $mailbox->getId(),
'date_time' => $dateTime->format('Y-m-d H:i:s'),
'count' => count($messages),
'uids' => serialize($messages)
];
try {
$state = $this->getStatesRepository()->create($data);
$this->getStatesRepository()->save($state);
return true;
} catch (PDOException $e) {
return false;
}
return $cnt;
}
/**
* @param MailboxInterface $mailbox
* @param int $uid
* @return MessageInterface
*/
public function getMessage(MailboxInterface $mailbox, int $uid): MessageInterface
public function unregister(string $mailbox_name): bool
{
return $mailbox->getMessage($uid);
try {
$mailbox = $this->getRepository()->fetchByName($mailbox_name);
} catch (BlankResult $e) {
// It's already unregistered
return true;
}
try {
$this->getRepository()->delete($mailbox);
return true;
} catch (PDOException $e) {
return false;
}
}
public function validate(string $mailbox_name): bool
{
$mailbox = $this->getLocalMailbox($mailbox_name);
protected function validateAddress(array $to): bool
{
foreach ($to as $address) {
if (strtolower($address->getAddress()) === strtolower($this->getUsername())) {
return true;
}
}
return false;
}
public function hasAttachments(MessageInterface $message): bool
{
return ($message->hasAttachments() and $this->validateAddress($message->getTo()));
}
protected function validateAttachment(AttachmentInterface $attachment): bool
{
return str_contains($attachment->getFilename(), '.pdf');
}
public function validAttachments(MessageInterface $message): bool
{
foreach ($message->getAttachments() as $attachment) {
if ($this->validateAttachment($attachment)) {
return true;
}
}
return false;
}
public function downloadAttachments(MessageInterface $message)
{
foreach ($message->getAttachments() as $attachment) {
if ($this->validateAttachment($attachment)) {
$attachment->getContent();
}
if (!$this->getRemoteService()->validate($mailbox_name, $mailbox->getValidity())) {
$remote_mailbox = $this->getRemoteMailbox($mailbox_name);
$mailbox->setValidity($remote_mailbox->getStatus()->uidvalidity);
$this->getRepository()->save($mailbox);
return false;
}
return true;
}
}

View File

@ -1,37 +1,177 @@
<?php
namespace ProVM\Common\Service;
use ProVM\Common\Factory\Model;
use Ddeboer\Imap\Exception\MessageDoesNotExistException;
use Ddeboer\Imap\MailboxInterface;
use PDOException;
use ProVM\Common\Exception\Mailbox\Stateless;
use Psr\Log\LoggerInterface;
use Ddeboer\Imap\MessageInterface;
use Ddeboer\Imap\Message\AttachmentInterface;
use ProVM\Emails\Model\Mailbox;
use ProVM\Emails\Repository\Message;
use Safe\DateTimeImmutable;
class Messages
class Messages extends Base
{
public function __construct(Model $factory, LoggerInterface $logger)
public function __construct(Mailboxes $mailboxes, Message $repository, Remote\Messages $remoteService, LoggerInterface $logger)
{
$this->setFactory($factory)
$this->setMailboxes($mailboxes)
->setRepository($repository)
->setRemoteService($remoteService)
->setLogger($logger);
}
protected Model $factory;
protected LoggerInterface $logger;
protected Mailboxes $mailboxes;
protected Message $repository;
protected Remote\Messages $remoteService;
public function getFactory(): Model
public function getMailboxes(): Mailboxes
{
return $this->factory;
return $this->mailboxes;
}
public function getLogger(): LoggerInterface
public function getRepository(): Message
{
return $this->logger;
return $this->repository;
}
public function getRemoteService(): Remote\Messages
{
return $this->remoteService;
}
public function setFactory(Model $factory): Messages
public function setMailboxes(Mailboxes $mailboxes): Messages
{
$this->factory = $factory;
$this->mailboxes = $mailboxes;
return $this;
}
public function setLogger(LoggerInterface $logger): Messages
public function setRepository(Message $repository): Messages
{
$this->logger = $logger;
$this->repository = $repository;
return $this;
}
public function setRemoteService(Remote\Messages $service): Messages
{
$this->remoteService = $service;
return $this;
}
public function getLocalMessage(string $message_uid): \ProVM\Emails\Model\Message
{
return $this->getRepository()->fetchByUID($message_uid);
}
public function getRemoteMessage(string $message_uid): MessageInterface
{
$message = $this->getLocalMessage($message_uid);
$remote_mailbox = $this->getMailboxes()->getRemoteMailbox($message->getMailbox()->getName());
return $this->getRemoteService()->get($remote_mailbox, $message->getSubject(), $message->getFrom(), $message->getDateTime());
}
public function getAll(string $mailbox_name): array
{
$mailbox = $this->getMailboxes()->getLocalMailbox($mailbox_name);
return $this->getRepository()->fetchByMailbox($mailbox->getId());
}
public function getValid(string $mailbox_name): array
{
$mailbox = $this->getMailboxes()->getLocalMailbox($mailbox_name);
return $this->getRepository()->fetchValidByMailbox($mailbox->getId());
}
public function grab(string $mailbox_name): array
{
$mailbox = $this->getMailboxes()->getLocalMailbox($mailbox_name);
if (!$this->getMailboxes()->validate($mailbox_name)) {
$this->restoreUIDs($mailbox_name);
}
try {
$start = $mailbox->lastPosition() + 1;
} catch (Stateless $e) {
$start = 0;
}
$remote_mailbox = $this->getMailboxes()->getRemoteMailbox($mailbox_name);
$total = $remote_mailbox->count();
$total_amount = $total - $start;
$amount = min(100, $total_amount);
$messages = [];
for ($i = 0; $i < $total_amount; $i += $amount) {
if ($amount + $i > $total_amount) {
$amount = $total_amount - $i;
}
$remote_messages = $this->getRemoteService()->getAll($remote_mailbox, $start + $i, $amount);
foreach ($remote_messages as $p => $m) {
if ($this->save($mailbox, $m, $p)) {
$messages []= $m->getId();
}
}
}
$this->getMailboxes()->updateState($mailbox, $messages, new DateTimeImmutable());
return $messages;
}
public function restoreUIDs(string $mailbox_name): void
{
$mailbox = $this->getMailboxes()->getLocalMailbox($mailbox_name);
$remote_mailbox = $this->getMailboxes()->getRemoteMailbox($mailbox_name);
$total_amount = $mailbox->lastPosition();
$amount = min(100, $total_amount);
for ($i = 0; $i < $total_amount; $i += $amount) {
if ($amount + $i > $total_amount) {
$amount = $total_amount - $i;
}
$remote_messages = $this->getRemoteService()->getAll($remote_mailbox, $i, $amount);
foreach ($remote_messages as $m) {
$this->update($mailbox, $m, $i);
}
}
}
public function save(Mailbox $mailbox, MessageInterface $remote_message, int $position): bool
{
$data = [
'mailbox_id' => $mailbox->getId(),
'position' => $position,
'uid' => $remote_message->getId(),
'subject' => $remote_message->getSubject() ?? '',
'from' => $remote_message->getFrom()->getAddress(),
'date_time' => $remote_message->getDate()->format('Y-m-d H:i:s')
];
try {
$message = $this->getRepository()->create($data);
if ($message->getId() === 0) {
if ($remote_message->hasAttachments()) {
$message->doesHaveAttachments();
}
if ($this->validAttachments($remote_message)) {
$message->doesHaveValidAttachments();
}
}
$this->getRepository()->save($message);
return true;
} catch (PDOException $e) {
$this->getLogger()->error($e);
return false;
}
}
public function update(Mailbox $mailbox, MessageInterface $remote_message, int $position): bool
{
try {
$message = $this->getRepository()->fetchByMailboxSubjectFromAndDate($mailbox->getId(), $remote_message->getSubject(), $remote_message->getFrom()->getAddress(), $remote_message->getDate());
$message->setUID($remote_message->getId());
$message->setPosition($position);
$this->getRepository()->save($message);
return true;
} catch (PDOException $e) {
return false;
}
}
public function validateAttachment(AttachmentInterface $attachment): bool
{
return str_contains($attachment->getFilename(), '.pdf');
}
public function validAttachments(MessageInterface $remote_message): bool
{
foreach ($remote_message->getAttachments() as $attachment) {
if ($this->validateAttachment($attachment)) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace ProVM\Common\Service\Remote;
use Psr\Log\LoggerInterface;
use Ddeboer\Imap\ConnectionInterface;
use Ddeboer\Imap\MessageInterface;
use Ddeboer\Imap\Message\AttachmentInterface;
use ProVM\Common\Exception\Attachment\NotFound;
class Attachments extends Base
{
public function __construct(ConnectionInterface $connection, LoggerInterface $logger)
{
$this->setConnection($connection)
->setLogger($logger);
}
public function getAttachments(MessageInterface $message): array
{
return $message->getAttachments();
}
public function get(MessageInterface $message, string $filename): AttachmentInterface
{
foreach ($message->getAttachments() as $attachment) {
if ($attachment->getFilename() === $filename) {
return $attachment;
}
}
throw new NotFound($message, $filename);
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace ProVM\Common\Service\Remote;
use Ddeboer\Imap\ConnectionInterface;
use ProVM\Common\Service\Base as BaseService;
abstract class Base extends BaseService
{
protected ConnectionInterface $connection;
public function getConnection(): ConnectionInterface
{
return $this->connection;
}
public function setConnection(ConnectionInterface $connection): Base
{
$this->connection = $connection;
return $this;
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace ProVM\Common\Service\Remote;
use Psr\Log\LoggerInterface;
use Ddeboer\Imap\ConnectionInterface;
use Ddeboer\Imap\MailboxInterface;
use ProVM\Common\Exception\Mailbox\Invalid;
/**
* Grab mailboxes from Email Provider
*/
class Mailboxes extends Base
{
public function __construct(ConnectionInterface $connection, LoggerInterface $logger)
{
$this->setConnection($connection)
->setLogger($logger);
}
protected array $mailboxes;
public function getAll(): array
{
if (!isset($this->mailboxes)) {
$this->mailboxes = $this->getConnection()->getMailboxes();
}
return $this->mailboxes;
}
/**
* @throws Invalid
*/
public function get(string $mailbox_name): MailboxInterface
{
if (!$this->getConnection()->hasMailbox($mailbox_name)) {
throw new Invalid($mailbox_name);
}
return $this->getConnection()->getMailbox($mailbox_name);
}
public function validate(string $mailbox_name, int $uidvalidity): bool
{
$mailbox = $this->get($mailbox_name);
return ($mailbox->getStatus()->uidvalidity === $uidvalidity);
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace ProVM\Common\Service\Remote;
use DateTimeInterface;
use Ddeboer\Imap\Exception\MessageDoesNotExistException;
use Psr\Log\LoggerInterface;
use Ddeboer\Imap\ConnectionInterface;
use Ddeboer\Imap\MailboxInterface;
use Ddeboer\Imap\MessageInterface;
use Ddeboer\Imap\SearchExpression;
use Ddeboer\Imap\Search\Date\On;
use Ddeboer\Imap\Search\Email\From;
use Ddeboer\Imap\Search\Text\Subject;
use ProVM\Common\Exception\EmptyMailbox;
class Messages extends Base
{
public function __construct(ConnectionInterface $connection, LoggerInterface $logger)
{
$this->setConnection($connection)
->setLogger($logger);
}
public function getAll(MailboxInterface $mailbox, int $start = 0, ?int $amount = null): array
{
if ($mailbox->count() === 0) {
throw new EmptyMailbox($mailbox);
}
if ($amount === null) {
$amount = $mailbox->count() - $start;
}
$it = $mailbox->getIterator();
for ($i = 0; $i < $start; $i ++) {
$it->next();
}
$messages = [];
for ($i = $start; $i < $start + $amount; $i ++) {
if (!$it->valid()) {
break;
}
$messages[$i] = $it->current();
$it->next();
}
return $messages;
}
public function get(MailboxInterface $mailbox, string $subject, string $from, DateTimeInterface $dateTime): MessageInterface
{
if ($mailbox->count() === 0) {
$this->getLogger()->notice("Mailbox {$mailbox->getName()} is empty");
throw new EmptyMailbox($mailbox);
}
$query = new SearchExpression();
$query->addCondition(new Subject($subject));
$query->addCondition(new From($from));
$query->addCondition(new On($dateTime));
$result = $mailbox->getMessages($query);
if (count($result) === 0) {
throw new MessageDoesNotExistException("{$mailbox->getName()}: {$subject} - {$from} [{$dateTime->format('Y-m-d H:i:s')}]");
}
return $result->current();
}
}