This commit is contained in:
2022-11-29 11:12:35 -03:00
137 changed files with 5506 additions and 0 deletions

13
.env.sample Normal file
View File

@ -0,0 +1,13 @@
CLI_PATH=./cli
API_PATH=./api
UI_PATH=./ui
COMPOSE_PROJECT_NAME=emails
COMPOSE_PATH_SEPARATOR=:
COMPOSE_FILE=./docker-compose.yml:${CLI_PATH}/docker-compose.yml:${API_PATH}/docker-compose.yml:${UI_PATH}/docker-compose.yml
COMPOSE_PROFILES=api,ui
ATT_PATH=./attachments
LOGS_PATH=./logs
WEB_PORT=8000
API_PORT=8080

3
.gitignore vendored
View File

@ -1,8 +1,11 @@
# Env
**/*.env
**/attachments/
**/logs/
# Composer
**/vendor/
**/*.lock
# Views
**/cache/

1
.key.env.sample Normal file
View File

@ -0,0 +1 @@
API_KEY=

6
.mail.env.sample Normal file
View File

@ -0,0 +1,6 @@
EMAIL_HOST=imap.gmail.com
EMAIL_PORT=993
EMAIL_USERNAME=@gmail.com
EMAIL_PASSWORD=
EMAIL_FOLDER=
ATTACHMENTS_FOLDER=/attachments

28
NOTES.md Normal file
View File

@ -0,0 +1,28 @@
## UI
* [x] List `mailboxes` all in the `Email Provider`, identifying those *registered* locally.
* [x] Select which to *register* or unregister for watching.
* [x] List *registered* `mailboxes`.
* [x] List `messages` for selected `mailbox`.
* [x] Schedule `attachments` downloads.
* [ ] Download `attachments` (*encrypted* & *decrypted*).
## CLI
* [x] Get `mailboxes` from **[API]** then run `grab messages` job in **[API]** for each one.
* [x] Get `pending attachments` jobs from **[API]** and run.
## API
* [x] Grab all `mailboxes` from `Email Provider`, identifying those that are registered.
* [x] Register `mailboxes` into **[database]** and grab latest `messages`.
* [x] Grab new `messages` from `Email Provider` for selected `mailboxes` and store them in the `database`.
* [x] Grab `messages` from **[database]** for selected `mailboxes`.
* [x] Grab `attachments` from `Email Provider` for selected `messages`.
* [x] Register `messages` for `attachment` job.
* [x] Decrypt `attachments`.
## Workflow
* **[User]** Choose `mailboxes` to register or unregister
-> **[API]** Register selected `mailboxes` and get `messages` for recently registered.
* **[Cron]** Get registered `mailboxes` -> **[API]** Get `messages`
* **[User]** Check messages found -> **[API]** Schedule `attachments`
* **[Cron]** Get `attachment download` jobs -> **[API]** grab `attachments`

8
README.md Normal file
View File

@ -0,0 +1,8 @@
# Emails
ProVM
## Description
Grab attachments from emails by inbox.
* Choose what mailboxes to watch.
* Select messages that you want to grab attachments from.
* Download (or view in browser) (decrypted) attachments from messages.

13
api/Dockerfile Normal file
View File

@ -0,0 +1,13 @@
FROM php:8-fpm
RUN apt-get update \
&& apt-get install -y libc-client-dev libkrb5-dev git libzip-dev unzip qpdf \
&& rm -r /var/lib/apt/lists/* \
&& docker-php-ext-configure imap --with-kerberos --with-imap-ssl \
&& docker-php-ext-install imap zip pdo pdo_mysql
COPY ./errors.ini /usr/local/etc/php/conf.d/docker-php-errors.ini
COPY --from=composer /usr/bin/composer /usr/bin/composer
WORKDIR /app/api

View File

@ -0,0 +1,64 @@
<?php
namespace ProVM\Common\Controller;
use ProVM\Common\Exception\Request\MissingArgument;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use ProVM\Common\Implement\Controller\Json;
use ProVM\Common\Service\Attachments as Service;
use ProVM\Emails\Model\Attachment;
use Psr\Log\LoggerInterface;
class Attachments
{
use Json;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
$attachments = array_map(function(Attachment $attachment) {
return $attachment->toArray();
},$service->getAll());
$output = [
'total' => count($attachments),
'attachments' => $attachments
];
return $this->withJson($response, $output);
}
public function grab(ServerRequestInterface $request, ResponseInterface $response, Service $service, \ProVM\Common\Service\Jobs $jobsService): ResponseInterface
{
$body = $request->getBody();
$json = \Safe\json_decode($body->getContents());
if (!isset($json->messages)) {
throw new MissingArgument('messages', 'array', 'message UIDs');
}
$output = [
'messages' => $json->messages,
'total' => count($json->messages),
'saved' => [
'attachments' => [],
'total' => 0
]
];
foreach ($json->messages as $message_id) {
if (!$jobsService->isPending($message_id)) {
continue;
}
if ($service->grab($message_id)) {
$job = $jobsService->find($message_id);
$jobsService->execute($job->getId());
$output['saved']['attachments'] []= $job->toArray();
$output['saved']['total'] ++;
}
}
return $this->withJson($response, $output);
}
public function get(ServerRequestInterface $request, ResponseInterface $response, Service $service, LoggerInterface $logger, int $attachment_id): ResponseInterface
{
$attachment = $service->getRepository()->fetchById($attachment_id);
$response->withHeader('Content-Type', 'application/pdf');
$response->withHeader('Content-Disposition', "'attachment;filename='{$attachment->getFullFilename()}'");
$response->getBody()->write($service->getFile($attachment_id));
return $response;
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace ProVM\Common\Controller;
use ProVM\Common\Implement\Controller\Json;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class Base
{
use Json;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
return $this->withJson($response, [
'version' => '1.0.0'
]);
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace ProVM\Common\Controller;
use ProVM\Emails\Model\Job;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use ProVM\Common\Exception\Request\MissingArgument;
use ProVM\Common\Implement\Controller\Json;
use ProVM\Common\Service\Jobs as Service;
class Jobs
{
use Json;
public function schedule(ServerRequestInterface $request, ResponseInterface $response, Service $jobsService): ResponseInterface
{
$body = $request->getBody();
$json = \Safe\json_decode($body->getContents());
if (!isset($json->messages)) {
throw new MissingArgument('messages', 'array', 'messages ids');
}
$output = [
'messages' => $json->messages,
'total' => count($json->messages),
'scheduled' => 0
];
foreach ($json->messages as $message_id) {
if ($jobsService->schedule($message_id)) {
$output['scheduled'] ++;
}
}
return $this->withJson($response, $output);
}
public function pending(ServerRequestInterface $request, ResponseInterface $response, Service $jobsService): ResponseInterface
{
$pending = array_map(function(Job $job) {
return $job->toArray();
}, $jobsService->getPending());
$output = [
'total' => count($pending),
'pending' => $pending
];
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,100 @@
<?php
namespace ProVM\Common\Controller;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Ddeboer\Imap\MailboxInterface;
use ProVM\Common\Exception\Request\MissingArgument;
use ProVM\Common\Implement\Controller\Json;
use ProVM\Common\Service\Mailboxes as Service;
use ProVM\Emails\Model\Mailbox;
class Mailboxes
{
use Json;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
$mailboxes = array_values(array_map(function(MailboxInterface $mailbox) use ($service) {
$arr = ['name' => $mailbox->getName(), 'registered' => false];
if ($service->isRegistered($mailbox->getName())) {
$mb = $service->getLocalMailbox($mailbox->getName());
$arr['id'] = $mb->getId();
$arr['registered'] = true;
}
return $arr;
}, $service->getAll()));
$output = [
'total' => count($mailboxes),
'mailboxes' => $mailboxes
];
return $this->withJson($response, $output);
}
public function registered(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
$mailboxes = array_map(function(Mailbox $mailbox) {
return $mailbox->toArray();
}, $service->getRegistered());
$output = [
'total' => count($mailboxes),
'mailboxes' => $mailboxes
];
return $this->withJson($response, $output);
}
public function get(ServerRequestInterface $request, ResponseInterface $response, Service $service, int $mailbox_id): ResponseInterface
{
$mailbox = $service->getRepository()->fetchById($mailbox_id);
return $this->withJson($response, ['mailbox' => $mailbox->toArray()]);
}
public function register(ServerRequestInterface $request, ResponseInterface $response, Service $service, \ProVM\Common\Service\Messages $messagesService): ResponseInterface
{
$body = $request->getBody();
$json = \Safe\json_decode($body->getContents());
if (!isset($json->mailboxes)) {
throw new MissingArgument('mailboxes', 'array', 'mailboxes names');
}
$output = [
'mailboxes' => $json->mailboxes,
'total' => count($json->mailboxes),
'registered' => [
'total' => 0,
'mailboxes' => []
]
];
foreach ($json->mailboxes as $mailbox_name) {
$arr = [
'id' => '',
'name' => $mailbox_name,
'registered' => false
];
if ($service->register($mailbox_name)) {
$mailbox = $service->getLocalMailbox($mailbox_name);
$arr['id'] = $mailbox->getId();
$arr['registered'] = true;
$output['registered']['total'] ++;
$output['registered']['mailboxes'] []= $arr;
$messagesService->grab($mailbox_name);
}
}
return $this->withJson($response, $output, 201);
}
public function unregister(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
$body = $request->getBody();
$json = \Safe\json_decode($body->getContents());
if (!isset($json->mailboxes)) {
throw new MissingArgument('mailboxes', 'array', 'mailboxes names');
}
$output = [
'mailboxes' => $json->mailboxes,
'total' => count($json->mailboxes),
'unregistered' => 0
];
foreach ($json->mailboxes as $mailbox_name) {
if ($service->unregister($mailbox_name)) {
$output['unregistered'] ++;
}
}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,73 @@
<?php
namespace ProVM\Common\Controller;
use Ddeboer\Imap\Exception\MessageDoesNotExistException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use ProVM\Common\Exception\Request\MissingArgument;
use ProVM\Common\Implement\Controller\Json;
use ProVM\Common\Service\Messages as Service;
use ProVM\Emails\Model\Message;
class Messages
{
use Json;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Service $service, int $mailbox_id): ResponseInterface
{
$mailbox = $service->getMailboxes()->get($mailbox_id);
$messages = array_map(function(Message $message) {
return $message->toArray();
}, $service->getAll($mailbox->getName()));
$output = [
'mailbox' => $mailbox->toArray(),
'total' => count($messages),
'messages' => $messages
];
return $this->withJson($response, $output);
}
public function valid(ServerRequestInterface $request, ResponseInterface $response, Service $service, \ProVM\Common\Service\Attachments $attachments, int $mailbox_id): ResponseInterface
{
$mailbox = $service->getMailboxes()->get($mailbox_id);
$messages = array_values(array_filter(array_map(function(Message $message) use ($service, $attachments) {
return $message->toArray();
}, $service->getValid($mailbox->getName())), function($message) {
return $message !== null;
}));
$output = [
'mailbox' => $mailbox->toArray(),
'total' => count($messages),
'messages' => $messages
];
return $this->withJson($response, $output);
}
public function get(ServerRequestInterface $request, ResponseInterface $response, Service $service, int $message_id): ResponseInterface
{
$message = $service->getRepository()->fetchById($message_id);
return $this->withJson($response, ['message' => $message->toArray()]);
}
public function grab(ServerRequestInterface $request, ResponseInterface $response, Service $service, \ProVM\Common\Service\Attachments $attachmentsService): ResponseInterface
{
$body = $request->getBody();
$json = \Safe\json_decode($body->getContents());
if (!isset($json->mailboxes)) {
throw new MissingArgument('mailboxes', 'array', 'mailboxes names');
}
$output = [
'mailboxes' => $json->mailboxes,
'messages' => [],
'message_count' => 0
];
foreach ($json->mailboxes as $mailbox_name) {
$messages = $service->grab($mailbox_name);
foreach ($messages as $message) {
if ($message->hasValidAttachments()) {
$attachmentsService->create($message);
}
}
$output['messages'] = array_merge($output['messages'], $messages);
$output['message_count'] += count($messages);
}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,6 @@
<?php
namespace ProVM\Common\Define;
interface Model
{
}

View File

@ -0,0 +1,15 @@
<?php
namespace ProVM\Common\Exception\Attachment;
use Ddeboer\Imap\MessageInterface;
use Exception;
class NotFound extends Exception
{
public function __construct(MessageInterface $message, string $filename, ?Throwable $previous = null)
{
$message = "Attachment {$filename} not found in {$message->getId()}";
$code = 120;
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace ProVM\Common\Exception\Database;
use Exception;
class BlankResult extends Exception
{
public function __construct(?Throwable $previous = null)
{
$message = "No results found";
$code = 300;
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace ProVM\Common\Exception;
use Ddeboer\Imap\MailboxInterface;
use Exception;
class EmptyMailbox extends Exception
{
public function __construct(MailboxInterface $mailbox, ?Throwable $previous = null)
{
$message = "No mails found in {$mailbox->getName()}";
$code = 101;
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace ProVM\Common\Exception\Mailbox;
use Exception;
class Invalid extends Exception
{
public function __construct(string $mailbox_name, ?Throwable $previous = null)
{
$message = "Mailbox {$mailbox_name} not found";
$code = 100;
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace ProVM\Common\Exception\Mailbox;
use Exception;
use ProVM\Emails\Model\Mailbox;
class Stateless extends Exception
{
public function __construct(Mailbox $mailbox, ?Throwable $previous = null)
{
$message = "Mailbox {$mailbox->getName()} has not loaded any emails.";
$code = 102;
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace ProVM\Common\Exception\Message;
use Ddeboer\Imap\MessageInterface;
use Exception;
class NoAttachments extends Exception
{
public function __construct(MessageInterface $message, ?Throwable $previous = null)
{
$message = "{$message->getSubject()} has no attachments";
$code = 110;
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace ProVM\Common\Exception\Request;
use Exception;
class MissingArgument extends Exception
{
public function __construct(string $argument_name, string $argument_type, string $argument_description, ?Throwable $previous = null)
{
$message = "Missing argument {$argument_name} [{$argument_type}] | {$argument_description}";
$code = 10;
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace ProVM\Common\Factory;
use ProVM\Common\Implement\Repository;
use Psr\Container\ContainerInterface;
class Model
{
public function __construct(ContainerInterface $container)
{
$this->setContainer($container);
}
protected ContainerInterface $container;
protected array $repositories;
public function getContainer(): ContainerInterface
{
return $this->container;
}
public function getRepositories(): array
{
return $this->repositories;
}
public function getRepository(string $name): string
{
return $this->getRepositories()[$name];
}
public function setContainer(ContainerInterface $container): Model
{
$this->container = $container;
return $this;
}
public function addRepository(string $name, string $repository_class_name): Model
{
$this->repositories[$name] = $repository_class_name;
return $this;
}
public function setRepositories(array $repositories): Model
{
foreach ($repositories as $name => $class) {
$this->addRepository($name, $class);
}
return $this;
}
public function find(string $model_class_name): Repository
{
$name = str_replace("ProVM\\Emails\\Model\\", '', $model_class_name);
try {
$repository_class = $this->getRepository($name);
} catch (\Exception $e) {
$repository_class = str_replace('Model', 'Repository', $model_class_name);
}
return $this->getContainer()->get($repository_class);
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace ProVM\Common\Implement\Controller;
use Psr\Http\Message\ResponseInterface;
trait Json
{
public function withJson(ResponseInterface $response, mixed $data, int $status = 200): ResponseInterface
{
$response->getBody()->write(\Safe\json_encode($data));
return $response
->withStatus($status)
->withHeader('Content-Type', 'application/json');
}
}

View File

@ -0,0 +1,187 @@
<?php
namespace ProVM\Common\Implement;
use PDO;
use PDOException;
use ProVM\Common\Exception\Database\BlankResult;
use Psr\Log\LoggerInterface;
use ProVM\Common\Define\Model as ModelInterface;
abstract class Repository
{
public function __construct(PDO $connection, LoggerInterface $logger)
{
$this->setConnection($connection)
->setLogger($logger);
}
protected PDO $connection;
protected string $table;
protected LoggerInterface $logger;
public function getConnection(): PDO
{
return $this->connection;
}
public function getTable(): string
{
return $this->table;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function setConnection(PDO $pdo): Repository
{
$this->connection = $pdo;
return $this;
}
public function setTable(string $table): Repository
{
$this->table = $table;
return $this;
}
public function setLogger(LoggerInterface $logger): Repository
{
$this->logger = $logger;
return $this;
}
abstract protected function fieldsForUpdate(): array;
abstract protected function valuesForUpdate(ModelInterface $model): array;
protected function idProperty(): string
{
return 'getId';
}
protected function idField(): string
{
return 'id';
}
public function update(ModelInterface $model, ModelInterface $old): void
{
$query = "UPDATE `{$this->getTable()}` SET ";
$model_values = $this->valuesForUpdate($model);
$old_values = $this->valuesForUpdate($old);
$columns = [];
$values = [];
foreach ($this->fieldsForUpdate() as $i => $column) {
if (isset($model_values[$i]) and $old_values[$i] !== $model_values[$i]) {
$columns []= "`{$column}` = ?";
$values []= $model_values[$i];
}
}
if (count($columns) === 0) {
return;
}
$query .= implode(', ', $columns) . " WHERE {$this->idField()} = ?";
$values []= $old->{$this->idProperty()}();
$st = $this->getConnection()->prepare($query);
$st->execute($values);
}
abstract protected function fieldsForInsert(): array;
abstract protected function valuesForInsert(ModelInterface $model): array;
protected function insert(ModelInterface $model): void
{
$fields = $this->fieldsForInsert();
$fields_string = implode(', ', array_map(function($field) {
return "`{$field}`";
}, $fields));
$fields_questions = implode(', ', array_fill(0, count($fields), '?'));
$query = "INSERT INTO `{$this->getTable()}` ({$fields_string}) VALUES ({$fields_questions})";
$values = $this->valuesForInsert($model);
$st = $this->getConnection()->prepare($query);
$st->execute($values);
}
abstract protected function defaultFind(ModelInterface $model): ModelInterface;
public function save(ModelInterface &$model): void
{
try {
$old = $this->defaultFind($model);
$this->update($model, $old);
} catch (BlankResult $e) {
$this->insert($model);
$model->setId($this->getConnection()->lastInsertId());
} catch(PDOException $e) {
$this->getLogger()->error($e);
throw $e;
}
}
abstract public function load(array $row): ModelInterface;
abstract protected function fieldsForCreate(): array;
abstract protected function valuesForCreate(array $data): array;
abstract protected function defaultSearch(array $data): ModelInterface;
public function create(array $data): ModelInterface
{
try {
return $this->defaultSearch($data);
} catch (PDOException | BlankResult $e) {
$data[$this->idField()] = 0;
return $this->load($data);
}
}
protected function getId(ModelInterface $model): int
{
return $model->getId();
}
public function resetIndex(): void
{
$query = "ALTER TABLE `{$this->getTable()}` AUTO_INCREMENT = 1";
$this->getConnection()->query($query);
}
public function optimize(): void
{
$query = "OPTIMIZE TABLE `{$this->getTable()}`";
$this->getConnection()->query($query);
}
public function delete(ModelInterface $model): void
{
$query = "DELETE FROM `{$this->getTable()}` WHERE `{$this->idField()}` = ?";
$st = $this->getConnection()->prepare($query);
$st->execute([$this->getId($model)]);
$this->resetIndex();
$this->optimize();
}
protected function fetchOne(string $query, ?array $values = null): ModelInterface
{
if ($values !== null) {
$st = $this->getConnection()->prepare($query);
$st->execute($values);
} else {
$st = $this->getConnection()->query($query);
}
$row = $st->fetch(PDO::FETCH_ASSOC);
if (!$row) {
throw new BlankResult();
}
return $this->load($row);
}
protected function fetchMany(string $query, ?array $values = null): array
{
if ($values !== null) {
$st = $this->getConnection()->prepare($query);
$st->execute($values);
} else {
$st = $this->getConnection()->query($query);
}
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
if (!$rows) {
throw new BlankResult();
}
return array_map([$this, 'load'], $rows);
}
public function fetchAll(): array
{
$query = "SELECT * FROM `{$this->getTable()}`";
return $this->fetchMany($query);
}
public function fetchById(int $id): ModelInterface
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `{$this->idField()}` = ?";
return $this->fetchOne($query, [$id]);
}
}

View File

@ -0,0 +1,72 @@
<?php
namespace ProVM\Common\Middleware;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
class Auth
{
public function __construct(ResponseFactoryInterface $factory, LoggerInterface $logger, string $api_key)
{
$this->setResponseFactory($factory);
$this->setLogger($logger);
$this->setAPIKey($api_key);
}
protected ResponseFactoryInterface $factory;
protected LoggerInterface $logger;
protected string $api_key;
public function getResponseFactory(): ResponseFactoryInterface
{
return $this->factory;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function getAPIKey(): string
{
return $this->api_key;
}
public function setResponseFactory(ResponseFactoryInterface $factory): Auth
{
$this->factory = $factory;
return $this;
}
public function setLogger(LoggerInterface $logger): Auth
{
$this->logger = $logger;
return $this;
}
public function setAPIKey(string $key): Auth
{
$this->api_key = $key;
return $this;
}
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ($request->getMethod() === 'OPTIONS') {
return $handler->handle($request);
}
$auths = $request->getHeader('Authorization');
foreach ($auths as $auth) {
if (str_contains($auth, 'Bearer')) {
$key = str_replace('Bearer ', '', $auth);
if (sha1($this->getAPIKey()) === $key) {
return $handler->handle($request);
}
}
}
$this->getLogger()->debug(sha1($this->getAPIKey()));
$response = $this->getResponseFactory()->createResponse(401);
$response->getBody()->write(\Safe\json_encode(['error' => 401, 'message' => 'Incorrect token']));
return $response
->withHeader('Content-Type', 'application/json');
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace ProVM\Common\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
class CORS
{
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
$request
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Credentials', 'true')
->withHeader('Access-Control-Allow-Headers', 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range')
->withHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,PUT,DELETE,PATCH');
return $response;
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace ProVM\Common\Middleware;
use ProVM\Common\Exception\Database\BlankResult;
use ProVM\Common\Exception\Mailbox\Stateless;
use ProVM\Common\Exception\Request\MissingArgument;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
use Safe\Exceptions\JsonException;
class CustomExceptions
{
public function __construct(ResponseFactoryInterface $factory, LoggerInterface $logger)
{
$this->setResponseFactory($factory)
->setLogger($logger);
}
protected ResponseFactoryInterface $factory;
protected LoggerInterface $logger;
public function getResponseFactory(): ResponseFactoryInterface
{
return $this->factory;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function setResponseFactory(ResponseFactoryInterface $factory): CustomExceptions
{
$this->factory = $factory;
return $this;
}
public function setLogger(LoggerInterface $logger): CustomExceptions
{
$this->logger = $logger;
return $this;
}
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
try {
return $handler->handle($request);
} catch (BlankResult $e) {
$this->getLogger()->error($e);
return $this->getResponseFactory()->createResponse(204);
} catch (JsonException $e) {
$this->getLogger()->error($e);
return $this->getResponseFactory()->createResponse(415, 'Only JSON Media Type is supported for this request');
} catch (MissingArgument $e) {
$this->getLogger()->error($e);
return $this->getResponseFactory()->createResponse(400, $e->getMessage());
}
}
}

View File

@ -0,0 +1,250 @@
<?php
namespace ProVM\Common\Service;
use Ddeboer\Imap\Message\AttachmentInterface;
use Ddeboer\Imap\MessageInterface;
use Nyholm\Psr7\Stream;
use ProVM\Common\Exception\Message\NoAttachments;
use ProVM\Emails\Model\Message;
use ProVM\Emails\Repository\Attachment;
use Psr\Http\Message\StreamInterface;
use Psr\Log\LoggerInterface;
use Safe\Exceptions\FilesystemException;
class Attachments extends Base
{
public function __construct(Messages $messages, Attachment $repository, Remote\Attachments $remoteService,
Decrypt $decrypt, string $attachments_folder, LoggerInterface $logger)
{
$this->setMessages($messages)
->setRepository($repository)
->setRemoteService($remoteService)
->setDecrypt($decrypt)
->setFolder($attachments_folder)
->setLogger($logger);
}
protected Messages $messages;
protected Attachment $repository;
protected Remote\Attachments $remoteService;
protected Decrypt $decrypt;
protected string $folder;
public function getMessages(): Messages
{
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 getFolder(): string
{
return $this->folder;
}
public function setMessages(Messages $messages): Attachments
{
$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
{
$this->decrypt = $decrypt;
return $this;
}
public function setFolder(string $folder): Attachments
{
$this->folder = $folder;
return $this;
}
public function getLocalAttachment(Message $message, string $relative_filename): \ProVM\Emails\Model\Attachment
{
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 getFile(int $attachment_id): string
{
$attachment = $this->getRepository()->fetchById($attachment_id);
$filename = implode(DIRECTORY_SEPARATOR, [
$this->getFolder(),
$attachment->getFullFilename()
]);
if ($attachment->isDecrypted()) {
$filename = implode(DIRECTORY_SEPARATOR, [
$this->getFolder(),
'decrypted',
$attachment->getFullFilename()
]);
}
return \Safe\file_get_contents($filename);
}
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' => $remote_attachment->getFilename()
];
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);
if ($this->isFileEncrypted($attachment->getMessage(), $attachment->getFilename())) {
$attachment->itIsEncrypted();
if ($this->isFileDecrypted($attachment->getMessage(), $attachment->getFilename())) {
$attachment->itIsDecrypted();
} else {
if ($this->decrypt($attachment->getMessage(), $attachment->getFilename())) {
$attachment->itIsDecrypted();
}
}
}
}
$this->getRepository()->save($attachment);
return true;
} catch (PDOException $e) {
$this->getLogger()->error($e);
return false;
}
}
public function upload(\ProVM\Emails\Model\Attachment $attachment, AttachmentInterface $remote_attachment): bool
{
$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;
}
}
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

@ -0,0 +1,27 @@
<?php
namespace ProVM\Common\Service;
use Psr\Log\LoggerInterface;
abstract class Base
{
protected LoggerInterface $logger;
/**
* @return LoggerInterface
*/
public function getLogger(): LoggerInterface
{
return $this->logger;
}
/**
* @param LoggerInterface $logger
* @return $this
*/
public function setLogger(LoggerInterface $logger): Base
{
$this->logger = $logger;
return $this;
}
}

View File

@ -0,0 +1,91 @@
<?php
namespace ProVM\Common\Service;
use Psr\Log\LoggerInterface;
use function Safe\exec;
class Decrypt
{
public function __construct(LoggerInterface $logger, string $base_command, array $passwords)
{
$this->setLogger($logger);
$this->setBaseCommand($base_command);
$this->setPasswords($passwords);
}
protected array $passwords;
protected string $base_command;
protected LoggerInterface $logger;
public function getPasswords(): array
{
return $this->passwords;
}
public function getBaseCommand(): string
{
return $this->base_command;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function addPassword(string $password): Decrypt
{
$this->passwords []= $password;
return $this;
}
public function setPasswords(array $passwords): Decrypt
{
foreach ($passwords as $password) {
$this->addPassword($password);
}
return $this;
}
public function setBaseCommand(string $command): Decrypt
{
$this->base_command = $command;
return $this;
}
public function setLogger(LoggerInterface $logger): Decrypt
{
$this->logger = $logger;
return $this;
}
public function isEncrypted(string $filename): bool
{
if (!file_exists($filename)) {
throw new \InvalidArgumentException("File not found {$filename}");
}
$escaped_filename = escapeshellarg($filename);
$cmd = "{$this->getBaseCommand()} --is-encrypted {$escaped_filename}";
exec($cmd, $output, $retcode);
return $retcode == 0;
}
public function buildCommand(string $in_file, string $out_file, string $password): string
{
return $this->getBaseCommand() . ' -password=' . escapeshellarg($password) . ' -decrypt ' . escapeshellarg($in_file) . ' ' . escapeshellarg($out_file);
}
public function runCommand(string $in_file, string $out_file): bool
{
if (file_exists($out_file)) {
return true;
}
foreach ($this->getPasswords() as $password) {
$cmd = $this->buildCommand($in_file, $out_file, $password);
exec($cmd, $output, $retcode);
$success = $retcode == 0;
if ($success) {
return true;
}
if (file_exists($out_file)) {
unlink($out_file);
}
unset($output);
}
return false;
}
}

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

@ -0,0 +1,143 @@
<?php
namespace ProVM\Common\Service;
use Ddeboer\Imap\MailboxInterface;
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(Mailbox $repository, Remote\Mailboxes $remoteService, State\Mailbox $states, LoggerInterface $logger)
{
$this->setRepository($repository)
->setRemoteService($remoteService)
->setStatesRepository($states)
->setLogger($logger);
}
protected Mailbox $repository;
protected Remote\Mailboxes $remoteService;
protected State\Mailbox $statesRepository;
public function getRepository(): Mailbox
{
return $this->repository;
}
public function getRemoteService(): Remote\Mailboxes
{
return $this->remoteService;
}
public function getStatesRepository(): State\Mailbox
{
return $this->statesRepository;
}
public function setRepository(Mailbox $repository): Mailboxes
{
$this->repository = $repository;
return $this;
}
public function setRemoteService(Remote\Mailboxes $service): Mailboxes
{
$this->remoteService = $service;
return $this;
}
public function setStatesRepository(State\Mailbox $repository): Mailboxes
{
$this->statesRepository = $repository;
return $this;
}
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
{
return $this->getRemoteService()->getAll();
}
public function getRegistered(): array
{
return $this->getRepository()->fetchAll();
}
public function get(int $mailbox_id): \ProVM\Emails\Model\Mailbox
{
return $this->getRepository()->fetchById($mailbox_id);
}
public function isRegistered(string $mailbox_name): bool
{
try {
$mailbox = $this->getRepository()->fetchByName($mailbox_name);
return true;
} catch (BlankResult $e) {
return false;
}
}
public function register(string $mailbox_name): bool
{
$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 updateState(\ProVM\Emails\Model\Mailbox $mailbox, array $messages, \DateTimeInterface $dateTime): bool
{
$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;
}
}
public function unregister(string $mailbox_name): bool
{
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);
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

@ -0,0 +1,177 @@
<?php
namespace ProVM\Common\Service;
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 extends Base
{
public function __construct(Mailboxes $mailboxes, Message $repository, Remote\Messages $remoteService, LoggerInterface $logger)
{
$this->setMailboxes($mailboxes)
->setRepository($repository)
->setRemoteService($remoteService)
->setLogger($logger);
}
protected Mailboxes $mailboxes;
protected Message $repository;
protected Remote\Messages $remoteService;
public function getMailboxes(): Mailboxes
{
return $this->mailboxes;
}
public function getRepository(): Message
{
return $this->repository;
}
public function getRemoteService(): Remote\Messages
{
return $this->remoteService;
}
public function setMailboxes(Mailboxes $mailboxes): Messages
{
$this->mailboxes = $mailboxes;
return $this;
}
public function setRepository(Message $repository): Messages
{
$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();
}
}

32
api/composer.json Normal file
View File

@ -0,0 +1,32 @@
{
"name": "provm/emails_api",
"type": "project",
"require": {
"ddeboer/imap": "^1.14",
"monolog/monolog": "^3.2",
"nyholm/psr7": "^1.5",
"nyholm/psr7-server": "^1.0",
"php-di/slim-bridge": "^3.2",
"thecodingmachine/safe": "^2.4",
"zeuxisoo/slim-whoops": "^0.7.3"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"kint-php/kint": "^4.2"
},
"authors": [
{
"name": "Aldarien",
"email": "aldarien85@gmail.com"
}
],
"autoload": {
"psr-4": {
"ProVM\\Common\\": "common/",
"ProVM\\Emails\\": "src/"
}
},
"config": {
"sort-packages": true
}
}

49
api/docker-compose.yml Normal file
View File

@ -0,0 +1,49 @@
version: '3'
services:
proxy:
profiles:
- api
volumes:
- ${API_PATH:-.}:/app/api
- ${API_PATH:-.}/nginx.conf:/etc/nginx/conf.d/api.conf
ports:
- "${API_PORT:-8080}:8080"
api:
profiles:
- api
container_name: emails-api
build:
context: ${API_PATH:-.}
restart: unless-stopped
env_file:
- ${API_PATH:-.}/.env
- ${API_PATH:-.}/.db.env
- .mail.env
- .key.env
volumes:
- ${API_PATH:-.}/:/app/api
- ${LOGS_PATH}/api:/logs
- ${ATT_PATH}:/attachments
db:
profiles:
- api
container_name: emails-db
image: mariadb
restart: unless-stopped
env_file:
- ${API_PATH:-.}/.db.env
volumes:
- emails_data:/var/lib/mysql
adminer:
profiles:
- testing
container_name: emails-adminer
image: adminer
restart: unless-stopped
env_file:
- ${API_PATH:-.}/.adminer.env
ports:
- "8081:8080"
volumes:
emails_data: {}

3
api/errors.ini Normal file
View File

@ -0,0 +1,3 @@
error_reporting=E_ALL
log_errors=true
error_log=/logs/errors.log

36
api/nginx.conf Normal file
View File

@ -0,0 +1,36 @@
server {
listen 0.0.0.0:8080;
root /app/api/public;
index index.php index.html index.htm;
access_log /var/logs/nginx/access.log;
error_log /var/logs/nginx/error.log;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'application/json';
add_header 'Content-Length' 0;
return 204;
}
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass api:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}

13
api/public/index.php Normal file
View File

@ -0,0 +1,13 @@
<?php
$app = require_once implode(DIRECTORY_SEPARATOR, [
dirname(__FILE__, 2),
'setup',
'app.php'
]);
Monolog\ErrorHandler::register($app->getContainer()->get(Psr\Log\LoggerInterface::class));
try {
$app->run();
} catch (Error | Exception $e) {
$app->getContainer()->get(Psr\Log\LoggerInterface::class)->error($e);
throw $e;
}

View File

@ -0,0 +1,18 @@
<?php
use ProVM\Common\Controller\Mailboxes;
use ProVM\Common\Controller\Messages;
$app->group('/mailboxes', function($app) {
$app->post('/register[/]', [Mailboxes::class, 'register']);
$app->delete('/unregister[/]', [Mailboxes::class, 'unregister']);
$app->get('/registered[/]', [Mailboxes::class, 'registered']);
$app->get('[/]', Mailboxes::class);
});
$app->group('/mailbox/{mailbox_id}', function($app) {
$app->group('/messages', function($app) {
$app->get('/valid[/]', [Messages::class, 'valid']);
$app->get('[/]', Messages::class);
});
$app->get('[/]', [Mailboxes::class, 'get']);
});

View File

@ -0,0 +1,11 @@
<?php
use ProVM\Common\Controller\Attachments;
$app->group('/attachments', function($app) {
$app->put('/grab', [Attachments::class, 'grab']);
$app->post('/decrypt', [Attachments::class, 'decrypt']);
$app->get('[/]', Attachments::class);
});
$app->group('/attachment/{attachment_id}', function($app) {
$app->get('[/]', [Attachments::class, 'get']);
});

View File

@ -0,0 +1,12 @@
<?php
use ProVM\Common\Controller\Messages;
use ProVM\Common\Controller\Jobs;
$app->group('/messages', function($app) {
$app->put('/grab', [Messages::class, 'grab']);
$app->put('/schedule', [Jobs::class, 'schedule']);
$app->get('/pending', [Jobs::class, 'pending']);
});
$app->group('/message/{message_id}', function($app) {
$app->get('[/]', [Messages::class, 'get']);
});

View File

@ -0,0 +1,4 @@
<?php
use ProVM\Common\Controller\Base;
$app->get('[/]', Base::class);

43
api/setup/app.php Normal file
View File

@ -0,0 +1,43 @@
<?php
require_once 'composer.php';
$builder = new \DI\ContainerBuilder();
$folders = [
'settings',
'setups'
];
foreach ($folders as $f) {
$folder = implode(DIRECTORY_SEPARATOR, [
__DIR__,
$f
]);
if (!file_exists($folder)) {
continue;
}
$files = new FilesystemIterator($folder);
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
$builder->addDefinitions($file->getRealPath());
}
}
$app = \DI\Bridge\Slim\Bridge::create($builder->build());
$folder = implode(DIRECTORY_SEPARATOR, [
__DIR__,
'middleware'
]);
if (file_exists($folder)) {
$files = new FilesystemIterator($folder);
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
require_once $file->getRealPath();
}
}
return $app;

6
api/setup/composer.php Normal file
View File

@ -0,0 +1,6 @@
<?php
require_once implode(DIRECTORY_SEPARATOR, [
dirname(__FILE__, 2),
'vendor',
'autoload.php'
]);

View File

@ -0,0 +1,11 @@
<?php
$app->addRoutingMiddleware();
$folder = $app->getContainer()->get('routes_folder');
$files = new FilesystemIterator($folder);
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
include_once $file->getRealPath();
}

View File

@ -0,0 +1,2 @@
<?php
$app->add($app->getContainer()->get(ProVM\Common\Middleware\CORS::class));

View File

@ -0,0 +1,2 @@
<?php
$app->add($app->getContainer()->get(ProVM\Common\Middleware\CustomExceptions::class));

View File

@ -0,0 +1,2 @@
<?php
$app->add($app->getContainer()->get(ProVM\Common\Middleware\Auth::class));

View File

@ -0,0 +1,2 @@
<?php
$app->add($app->getContainer()->get(Zeuxisoo\Whoops\Slim\WhoopsMiddleware::class));

View File

@ -0,0 +1,31 @@
<?php
return [
'emails' => function() {
$data = [
'host' => $_ENV['EMAIL_HOST'],
'username' => $_ENV['EMAIL_USERNAME'],
'password' => $_ENV['EMAIL_PASSWORD'],
'folder' => $_ENV['EMAIL_FOLDER'],
];
if (isset($_ENV['EMAIL_PORT'])) {
$data['port'] = $_ENV['EMAIL_PORT'];
}
return json_decode(json_encode($data));
},
'passwords' => function() {
return explode($_ENV['PASSWORDS_SEPARATOR'] ?? ',', $_ENV['PASSWORDS'] ?? '');
},
'api_key' => $_ENV['API_KEY'],
'database' => function() {
$arr = [
'host' => 'db',
'name' => $_ENV['MYSQL_DATABASE'],
'username' => $_ENV['MYSQL_USER'],
'password' => $_ENV['MYSQL_PASSWORD']
];
if (isset($_ENV['MYSQL_PORT'])) {
$arr['port'] = $_ENV['MYSQL_PORT'];
}
return (object) $arr;
}
];

View File

@ -0,0 +1,21 @@
<?php
use Psr\Container\ContainerInterface;
return [
'base_folder' => function() {
return dirname(__FILE__, 3);
},
'resources_folder' => function(ContainerInterface $container) {
return implode(DIRECTORY_SEPARATOR, [
$container->get('base_folder'),
'resources'
]);
},
'routes_folder' => function(ContainerInterface $container) {
return implode(DIRECTORY_SEPARATOR, [
$container->get('resources_folder'),
'routes'
]);
},
'attachments_folder' => $_ENV['ATTACHMENTS_FOLDER'],
];

View File

@ -0,0 +1,4 @@
<?php
return [
'base_command' => 'qpdf'
];

View File

@ -0,0 +1,4 @@
<?php
return [
'log_file' => '/logs/php.log'
];

View File

@ -0,0 +1,27 @@
<?php
use Psr\Container\ContainerInterface;
return [
Ddeboer\Imap\ServerInterface::class => function(ContainerInterface $container) {
$emails = $container->get('emails');
if (isset($emails->port)) {
return new \Ddeboer\Imap\Server($emails->host, $emails->port);
}
return new \Ddeboer\Imap\Server($emails->host);
},
\Ddeboer\Imap\ConnectionInterface::class => function(ContainerInterface $container) {
$emails = $container->get('emails');
$server = $container->get(\Ddeboer\Imap\ServerInterface::class);
return $server->authenticate($emails->username, $emails->password);
},
PDO::class => function(ContainerInterface $container) {
$database = $container->get('database');
$dsn = ["mysql:host={$database->host}"];
if (isset($database->port)) {
$dsn []= "port={$database->port}";
}
$dsn []= "dbname={$database->name}";
$dsn = implode(';', $dsn);
return new PDO($dsn, $database->username, $database->password);
},
];

View File

@ -0,0 +1,22 @@
<?php
use Psr\Container\ContainerInterface;
return [
ProVM\Common\Service\Decrypt::class => function(ContainerInterface $container) {
return new ProVM\Common\Service\Decrypt(
$container->get(Psr\Log\LoggerInterface::class),
$container->get('base_command'),
$container->get('passwords')
);
},
ProVM\Common\Service\Attachments::class => function(ContainerInterface $container) {
return new ProVM\Common\Service\Attachments(
$container->get(ProVM\Common\Service\Messages::class),
$container->get(ProVM\Emails\Repository\Attachment::class),
$container->get(ProVM\Common\Service\Remote\Attachments::class),
$container->get(ProVM\Common\Service\Decrypt::class),
$container->get('attachments_folder'),
$container->get(Psr\Log\LoggerInterface::class)
);
}
];

View File

@ -0,0 +1,17 @@
<?php
use Psr\Container\ContainerInterface;
return [
\ProVM\Common\Factory\Model::class => function(ContainerInterface $container) {
$factory = new \ProVM\Common\Factory\Model($container);
$repositories = [
'Mailbox' => \ProVM\Emails\Repository\Mailbox::class,
'Message' => \ProVM\Emails\Repository\Message::class,
'Attachment' => \ProVM\Emails\Repository\Attachment::class,
"State\\Mailbox" => \ProVM\Emails\Repository\State\Mailbox::class,
"State\\Message" => \ProVM\Emails\Repository\State\Message::class,
"State\\Attachment" => \ProVM\Emails\Repository\State\Attachment::class
];
return $factory->setRepositories($repositories);
}
];

View File

@ -0,0 +1,11 @@
<?php
use Psr\Container\ContainerInterface;
return [
ProVM\Common\Middleware\CustomExceptions::class => function(ContainerInterface $container) {
return new ProVM\Common\Middleware\CustomExceptions(
$container->get(Nyholm\Psr7\Factory\Psr17Factory::class),
$container->get(Psr\Log\LoggerInterface::class)
);
}
];

View File

@ -0,0 +1,12 @@
<?php
use Psr\Container\ContainerInterface;
return [
\ProVM\Common\Middleware\Auth::class => function(ContainerInterface $container) {
return new \ProVM\Common\Middleware\Auth(
$container->get(\Nyholm\Psr7\Factory\Psr17Factory::class),
$container->get(\Psr\Log\LoggerInterface::class),
$container->get('api_key')
);
}
];

View File

@ -0,0 +1,22 @@
<?php
use Psr\Container\ContainerInterface;
return [
Monolog\Handler\DeduplicationHandler::class => function(ContainerInterface $container) {
return new Monolog\Handler\DeduplicationHandler($container->get(Monolog\Handler\RotatingFileHandler::class));
},
Monolog\Handler\RotatingFileHandler::class => function(ContainerInterface $container) {
$handler = new Monolog\Handler\RotatingFileHandler($container->get('log_file'));
$handler->setFormatter($container->get(Monolog\Formatter\SyslogFormatter::class));
return $handler;
},
Psr\Log\LoggerInterface::class => function(ContainerInterface $container) {
$logger = new Monolog\Logger('file_logger');
$logger->pushHandler($container->get(Monolog\Handler\DeduplicationHandler::class));
//$logger->pushHandler($container->get(Monolog\Handler\RotatingFileHandler::class));
$logger->pushProcessor($container->get(Monolog\Processor\PsrLogMessageProcessor::class));
$logger->pushProcessor($container->get(Monolog\Processor\IntrospectionProcessor::class));
$logger->pushProcessor($container->get(Monolog\Processor\MemoryUsageProcessor::class));
return $logger;
}
];

View File

@ -0,0 +1,15 @@
<?php
use Psr\Container\ContainerInterface;
return [
\Whoops\Handler\JsonResponseHandler::class => function(ContainerInterface $container) {
return (new \Whoops\Handler\JsonResponseHandler())
->setJsonApi(true)
->addTraceToOutput(true);
},
\Zeuxisoo\Whoops\Slim\WhoopsMiddleware::class => function(ContainerInterface $container) {
return new \Zeuxisoo\Whoops\Slim\WhoopsMiddleware([], [
$container->get(\Whoops\Handler\JsonResponseHandler::class)
]);
}
];

View File

@ -0,0 +1,172 @@
<?php
namespace ProVM\Emails\Model;
use ProVM\Common\Define\Model;
use ProVM\Common\Exception\Database\BlankResult;
class Attachment implements Model
{
protected int $id;
protected Message $message;
protected string $filename;
public function getId(): int
{
return $this->id;
}
public function getMessage(): Message
{
return $this->message;
}
public function getFilename(): string
{
return $this->filename;
}
public function setId(int $id): Attachment
{
$this->id = $id;
return $this;
}
public function setMessage(Message $message): Attachment
{
$this->message = $message;
return $this;
}
public function setFilename(string $filename): Attachment
{
$this->filename = $filename;
return $this;
}
protected \ProVM\Emails\Repository\State\Attachment $stateRepository;
public function getStateRepository(): \ProVM\Emails\Repository\State\Attachment
{
return $this->stateRepository;
}
public function setStateRepository(\ProVM\Emails\Repository\State\Attachment $repository): Attachment
{
$this->stateRepository = $repository;
return $this;
}
protected array $states;
public function getStates(): array
{
if (!isset($this->states)) {
try {
$this->setStates($this->getStateRepository()->fetchByAttachment($this->getId()));
} catch (BlankResult $e) {
return [];
}
}
return $this->states;
}
public function getState(string $name): State\Attachment
{
try {
return $this->getStates()[$name];
} catch (\Exception $e) {
$this->newState($name);
return $this->getStates()[$name];
}
}
public function addState(State\Attachment $state): Attachment
{
$this->states[$state->getName()] = $state;
return $this;
}
public function setStates(array $states): Attachment
{
foreach ($states as $state) {
$this->addState($state);
}
return $this;
}
protected function newState(string $name): Attachment
{
$this->addState((new State\Attachment())
->setAttachment($this)
->setName($name)
);
return $this;
}
public function getFullFilename(): string
{
return implode(' - ', [
$this->getMessage()->getSubject(),
$this->getMessage()->getDateTime()->format('Y-m-d His'),
$this->getFilename()
]);
}
public function isDownloaded(): bool
{
return $this->getState('downloaded')?->getValue() ?? false;
}
public function isEncrypted(): bool
{
return $this->getState('encrypted')?->getValue() ?? false;
}
public function isDecrypted(): bool
{
try {
return $this->getState('decrypted')?->getValue() ?? false;
} catch (\Exception $e) {
$this->newState('decrypted');
return $this->getState('decrypted')?->getValue() ?? false;
}
}
public function itIsDownloaded(): Attachment
{
try {
$this->getState('downloaded')->setValue(true);
} catch (\Exception $e) {
$this->newState('downloaded');
$this->getState('downloaded')->setValue(true);
}
return $this;
}
public function itIsEncrypted(): Attachment
{
try {
$this->getState('encrypted')->setValue(true);
} catch (\Exception $e) {
$this->newState('encrypted');
$this->getState('encrypted')->setValue(true);
}
return $this;
}
public function itIsDecrypted(): Attachment
{
try {
$this->getState('decrypted')->setValue(true);
} catch (\Exception $e) {
$this->newState('decrypted');
$this->getState('decrypted')->setValue(true);
}
return $this;
}
public function toArray(): array
{
return [
'id' => $this->getId(),
'message' => [
'id' => $this->getMessage()->getId(),
'mailbox' => $this->getMessage()->getMailbox()->toArray(),
'position' => $this->getMessage()->getPosition(),
'uid' => $this->getMessage()->getUID(),
'subject' => $this->getMessage()->getSubject(),
'from' => $this->getMessage()->getFrom(),
'date_time' => $this->getMessage()->getDateTime()->format('Y-m-d H:i:s')
],
'filename' => $this->getFilename(),
'fullname' => $this->getFullFilename(),
'downloaded' => $this->isDownloaded(),
'encrypted' => $this->isEncrypted(),
'decrypted' => $this->isDecrypted()
];
}
}

61
api/src/Model/Job.php Normal file
View File

@ -0,0 +1,61 @@
<?php
namespace ProVM\Emails\Model;
use DateTimeInterface;
use ProVM\Common\Define\Model;
class Job implements Model
{
protected int $id;
protected Message $message;
protected DateTimeInterface $dateTime;
protected bool $executed;
public function getId(): int
{
return $this->id;
}
public function getMessage(): Message
{
return $this->message;
}
public function getDateTime(): DateTimeInterface
{
return $this->dateTime;
}
public function isExecuted(): bool
{
return $this->executed ?? false;
}
public function setId(int $id): Job
{
$this->id = $id;
return $this;
}
public function setMessage(Message $message): Job
{
$this->message = $message;
return $this;
}
public function setDateTime(DateTimeInterface $dateTime): Job
{
$this->dateTime = $dateTime;
return $this;
}
public function wasExecuted(): Job
{
$this->executed = true;
return $this;
}
public function toArray(): array
{
return [
'id' => $this->getId(),
'message' => $this->getMessage()->toArray(),
'date_time' => $this->getDateTime()->format('Y-m-d H:i:s'),
'executed' => $this->isExecuted()
];
}
}

122
api/src/Model/Mailbox.php Normal file
View File

@ -0,0 +1,122 @@
<?php
namespace ProVM\Emails\Model;
use DateTimeInterface;
use ProVM\Common\Define\Model;
use ProVM\Common\Exception\Database\BlankResult;
use ProVM\Common\Exception\EmptyMailbox;
use ProVM\Common\Exception\Mailbox\Stateless;
use Safe\DateTimeImmutable;
class Mailbox implements Model
{
protected int $id;
protected string $name;
protected int $validity;
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getValidity(): int
{
return $this->validity;
}
public function setId(int $id): Mailbox
{
$this->id = $id;
return $this;
}
public function setName(string $name): Mailbox
{
$this->name = $name;
return $this;
}
public function setValidity(int $uidvalidity): Mailbox
{
$this->validity = $uidvalidity;
return $this;
}
protected \ProVM\Emails\Repository\State\Mailbox $stateRepository;
public function getStateRepository(): \ProVM\Emails\Repository\State\Mailbox
{
return $this->stateRepository;
}
public function setStateRepository(\ProVM\Emails\Repository\State\Mailbox $repository): Mailbox
{
$this->stateRepository = $repository;
return $this;
}
protected array $states;
public function getStates(): array
{
if (!isset($this->states)) {
try {
$this->setStates($this->getStateRepository()->fetchByMailbox($this->getId()));
} catch (BlankResult $e) {
return [];
}
}
return $this->states;
}
public function addState(\ProVM\Emails\Model\State\Mailbox $state): Mailbox
{
$this->states []= $state;
return $this;
}
public function setStates(array $states): Mailbox
{
foreach ($states as $state) {
$this->addState($state);
}
return $this;
}
public function lastState(): State\Mailbox
{
if (count($this->getStates()) === 0) {
throw new Stateless($this);
}
return $this->getStates()[array_key_last($this->getStates())];
}
public function lastChecked(): ?DateTimeInterface
{
if (count($this->getStates()) == 0) {
return null;
}
return $this->lastState()->getDateTime();
}
public function lastCount(): int
{
if (count($this->getStates()) == 0) {
return 0;
}
return $this->lastState()->getCount();
}
public function lastPosition(): int
{
$state = $this->lastState()->getUIDs();
return array_key_last($state);
}
public function toArray(): array
{
return [
'id' => $this->getId(),
'name' => $this->getName(),
//'validity' => $this->getValidity(),
'last_checked' => [
'date' => $this->lastChecked() ?? 'never',
'count' => $this->lastCount() ?? 0
]
];
}
}

215
api/src/Model/Message.php Normal file
View File

@ -0,0 +1,215 @@
<?php
namespace ProVM\Emails\Model;
use DateTimeInterface;
use ProVM\Common\Define\Model;
use ProVM\Common\Exception\Database\BlankResult;
class Message implements Model
{
protected int $id;
protected Mailbox $mailbox;
protected int $position;
protected string $uid;
protected string $subject;
protected string $from;
protected DateTimeInterface $dateTime;
public function getId(): int
{
return $this->id;
}
public function getMailbox(): Mailbox
{
return $this->mailbox;
}
public function getPosition(): int
{
return $this->position;
}
public function getUID(): string
{
return $this->uid;
}
public function getSubject(): string
{
return $this->subject;
}
public function getFrom(): string
{
return $this->from;
}
public function getDateTime(): DateTimeInterface
{
return $this->dateTime;
}
public function setId(int $id): Message
{
$this->id = $id;
return $this;
}
public function setMailbox(Mailbox $mailbox): Message
{
$this->mailbox = $mailbox;
return $this;
}
public function setPosition(int $position): Message
{
$this->position = $position;
return $this;
}
public function setUID(string $uid): Message
{
$this->uid = $uid;
return $this;
}
public function setSubject(string $subject): Message
{
$this->subject = $subject;
return $this;
}
public function setFrom(string $from): Message
{
$this->from = $from;
return $this;
}
public function setDateTime(DateTimeInterface $dateTime): Message
{
$this->dateTime = $dateTime;
return $this;
}
protected \ProVM\Common\Factory\Model $factory;
public function getFactory(): \ProVM\Common\Factory\Model
{
return $this->factory;
}
public function setFactory(\ProVM\Common\Factory\Model $factory): Message
{
$this->factory = $factory;
return $this;
}
protected array $states;
public function getStates(): array
{
if (!isset($this->states)) {
try {
$this->setStates($this->getFactory()->find(\ProVM\Emails\Model\State\Message::class)->fetchByMessage($this->getId()));
} catch (BlankResult $e) {
return [];
}
}
return $this->states;
}
public function getState(string $name): \ProVM\Emails\Model\State\Message
{
return $this->getStates()[$name];
}
public function addState(\ProVM\Emails\Model\State\Message $state): Message
{
$this->states[$state->getName()] = $state;
return $this;
}
public function setStates(array $states): Message
{
foreach ($states as $state) {
$this->addState($state);
}
return $this;
}
protected function newState(string $name): Message
{
$this->addState((new \ProVM\Emails\Model\State\Message())
->setName($name)
->setMessage($this)
);
return $this;
}
public function hasAttachments(): bool
{
return $this->getState('has_attachments')->getValue() ?? false;
}
public function hasValidAttachments(): bool
{
return $this->getState('valid_attachments')->getValue() ?? false;
}
public function hasDownloadedAttachments(): bool
{
return $this->getState('downloaded_attachments')->getValue() ?? false;
}
public function doesHaveAttachments(): Message
{
if (!isset($this->getState()['has_attachments'])) {
$this->newState('has_attachments');
}
$this->getState('has_attachments')->setValue(true);
return $this;
}
public function doesHaveValidAttachments(): Message
{
if (!isset($this->getStates()['valid_attachments'])) {
$this->newState('valid_attachments');
}
$this->getState('valid_attachments')->setValue(true);
return $this;
}
public function doesHaveDownloadedAttachments(): Message
{
if (!isset($this->getStates()['downloaded_attachments'])) {
$this->newState('downloaded_attachments');
}
$this->getState('downloaded_attachments')->setValue(true);
return $this;
}
protected array $attachments;
public function getAttachments(): array
{
if (!isset($this->attachments)) {
try {
$this->setAttachments($this->getFactory()->find(Attachment::class)->fetchByMessage($this->getId()));
} catch (BlankResult $e) {
return [];
}
}
return $this->attachments ?? [];
}
public function addAttachment(Attachment $attachment): Message
{
$this->attachments []= $attachment;
return $this;
}
public function setAttachments(array $attachments): Message
{
foreach ($attachments as $attachment) {
$this->addAttachment($attachment);
}
return $this;
}
public function toArray(): array
{
return [
'id' => $this->getId(),
'uid' => $this->getUID(),
'subject' => $this->getSubject(),
'from' => $this->getFrom(),
'date_time' => $this->getDateTime()->format('Y-m-d H:i:s'),
'states' => [
'has_attachments' => $this->hasAttachments(),
'valid_attachments' => $this->hasValidAttachments(),
'downloaded_attachments' => $this->hasDownloadedAttachments()
],
'attachments' => $this->hasValidAttachments() ? array_map(function(Attachment $attachment) {
return $attachment->toArray();
}, $this->getAttachments()) : []
];
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace ProVM\Emails\Model\State;
use ProVM\Common\Define\Model;
class Attachment implements Model
{
protected int $id;
protected \ProVM\Emails\Model\Attachment $attachment;
protected string $name;
protected bool $value;
public function getId(): int
{
return $this->id;
}
public function getAttachment(): \ProVM\Emails\Model\Attachment
{
return $this->attachment;
}
public function getName(): string
{
return $this->name;
}
public function getValue(): bool
{
return $this->value ?? false;
}
public function setId(int $id): Attachment
{
$this->id = $id;
return $this;
}
public function setAttachment(\ProVM\Emails\Model\Attachment $attachment): Attachment
{
$this->attachment = $attachment;
return $this;
}
public function setName(string $name): Attachment
{
$this->name = $name;
return $this;
}
public function setValue(bool $value): Attachment
{
$this->value = $value;
return $this;
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace ProVM\Emails\Model\State;
use DateTimeInterface;
use ProVM\Common\Define\Model;
class Mailbox implements Model
{
protected int $id;
protected \ProVM\Emails\Model\Mailbox $mailbox;
protected DateTimeInterface $dateTime;
protected int $count;
protected array $uids;
public function getId(): int
{
return $this->id;
}
public function getMailbox(): \ProVM\Emails\Model\Mailbox
{
return $this->mailbox;
}
public function getDateTime(): DateTimeInterface
{
return $this->dateTime;
}
public function getCount(): int
{
return $this->count;
}
public function getUIDs(): array
{
return $this->uids;
}
public function setId(int $id): Mailbox
{
$this->id = $id;
return $this;
}
public function setMailbox(\ProVM\Emails\Model\Mailbox $mailbox): Mailbox
{
$this->mailbox = $mailbox;
return $this;
}
public function setDateTime(DateTimeInterface $dateTime): Mailbox
{
$this->dateTime = $dateTime;
return $this;
}
public function setCount(int $count): Mailbox
{
$this->count = $count;
return $this;
}
public function addUID(string $uid): Mailbox
{
$this->uids []= $uid;
return $this;
}
public function setUIDs(array $uids): Mailbox
{
foreach ($uids as $uid) {
$this->addUID($uid);
}
return $this;
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace ProVM\Emails\Model\State;
use ProVM\Common\Define\Model;
class Message implements Model
{
protected int $id;
protected \ProVM\Emails\Model\Message $message;
protected string $name;
protected bool $value;
public function getId(): int
{
return $this->id;
}
public function getMessage(): \ProVM\Emails\Model\Message
{
return $this->message;
}
public function getName(): string
{
return $this->name;
}
public function getValue(): bool
{
return $this->value;
}
public function setId(int $id): Message
{
$this->id = $id;
return $this;
}
public function setMessage(\ProVM\Emails\Model\Message $message): Message
{
$this->message = $message;
return $this;
}
public function setName(string $name): Message
{
$this->name = $name;
return $this;
}
public function setValue(bool $value): Message
{
$this->value = $value;
return $this;
}
}

View File

@ -0,0 +1,118 @@
<?php
namespace ProVM\Emails\Repository;
use PDO;
use ProVM\Common\Exception\Database\BlankResult;
use Psr\Log\LoggerInterface;
use ProVM\Common\Define\Model as ModelInterface;
use ProVM\Common\Factory\Model;
use ProVM\Common\Implement\Repository;
class Attachment extends Repository
{
public function __construct(PDO $connection, LoggerInterface $logger, Model $factory)
{
parent::__construct($connection, $logger);
$this->setFactory($factory)
->setTable('attachments');
}
protected Model $factory;
public function getFactory(): Model
{
return $this->factory;
}
public function setFactory(Model $factory): Attachment
{
$this->factory = $factory;
return $this;
}
protected function fieldsForInsert(): array
{
return [
'message_id',
'filename'
];
}
protected function fieldsForUpdate(): array
{
return $this->fieldsForInsert();
}
protected function fieldsForCreate(): array
{
return $this->fieldsForInsert();
}
protected function valuesForUpdate(ModelInterface $model): array
{
return $this->valuesForInsert($model);
}
protected function valuesForInsert(ModelInterface $model): array
{
return [
$model->getMessage()->getId(),
$model->getFilename()
];
}
protected function defaultFind(ModelInterface $model): ModelInterface
{
return $this->fetchByMessageAndFilename($model->getMessage()->getId(), $model->getFilename());
}
protected function valuesForCreate(array $data): array
{
return [
$data['message_id'],
$data['filename']
];
}
protected function defaultSearch(array $data): ModelInterface
{
return $this->fetchByMessageAndFilename($data['message_id'], $data['filename']);
}
public function load(array $row): \ProVM\Emails\Model\Attachment
{
return (new \ProVM\Emails\Model\Attachment())
->setId($row['id'])
->setMessage($this->getFactory()->find(\ProVM\Emails\Model\Message::class)->fetchById($row['message_id']))
->setFilename($row['filename'])
->setStateRepository($this->getFactory()->find(\ProVM\Emails\Model\State\Attachment::class));
}
public function save(ModelInterface &$model): void
{
parent::save($model);
$states_names = [
'downloaded',
'encrypted',
'decrypted'
];
foreach ($states_names as $name) {
try {
$state = $model->getState($name);
$this->getFactory()->find(\ProVM\Emails\Model\State\Attachment::class)->save($state);
} catch (BlankResult $e) {
$this->getLogger()->error($e);
$data = [
'attachment_id' => $model->getId(),
'name' => $name,
'value' => false
];
$state = $this->getFactory()->find(\ProVM\Emails\Model\State\Attachment::class)->create($data);
$this->getFactory()->find(\ProVM\Emails\Model\State\Attachment::class)->save($state);
}
}
}
public function fetchByMessageAndFilename(int $message_id, string $filename): \ProVM\Emails\Model\Attachment
{
$query = "SELECT * FROM {$this->getTable()} WHERE message_id = ? AND filename = ?";
return $this->fetchOne($query, [$message_id, $filename]);
}
public function fetchByMessage(int $message_id): array
{
$query = "SELECT * FROM {$this->getTable()} WHERE message_id = ?";
return $this->fetchMany($query, [$message_id]);
}
}

108
api/src/Repository/Job.php Normal file
View File

@ -0,0 +1,108 @@
<?php
namespace ProVM\Emails\Repository;
use PDO;
use ProVM\Common\Factory\Model;
use Psr\Log\LoggerInterface;
use Safe\DateTimeImmutable;
use ProVM\Common\Define\Model as ModelInterface;
use ProVM\Common\Implement\Repository;
use ProVM\Emails\Model\Job as BaseModel;
class Job extends Repository
{
public function __construct(PDO $connection, LoggerInterface $logger, Model $factory)
{
parent::__construct($connection, $logger);
$this->setFactory($factory)
->setTable('attachments_jobs');
}
protected \ProVM\Common\Factory\Model $factory;
public function getFactory(): \ProVM\Common\Factory\Model
{
return $this->factory;
}
public function setFactory(\ProVM\Common\Factory\Model $factory): Job
{
$this->factory = $factory;
return $this;
}
protected function fieldsForUpdate(): array
{
return $this->fieldsForInsert();
}
protected function valuesForUpdate(ModelInterface $model): array
{
return $this->valuesForInsert($model);
}
protected function fieldsForInsert(): array
{
return [
'message_id',
'date_time',
'executed'
];
}
protected function valuesForInsert(ModelInterface $model): array
{
return [
$model->getMessage()->getId(),
$model->getDateTime()->format('Y-m-d H:i:s'),
$model->isExecuted() ? 1 : 0
];
}
protected function defaultFind(ModelInterface $model): ModelInterface
{
return $this->fetchByMessageAndDate($model->getMessage()->getId(), $model->getDateTime()->format('Y-m-d H:i:s'));
}
protected function fieldsForCreate(): array
{
return [
'message_id',
'date_time',
'executed'
];
}
protected function valuesForCreate(array $data): array
{
return [
$data['message_id'],
$data['date_time'],
$data['executed'] ?? 0
];
}
protected function defaultSearch(array $data): ModelInterface
{
return $this->fetchByMessageAndDate($data['message_id'], $data['date_time']);
}
public function load(array $row): ModelInterface
{
$model = (new BaseModel())
->setId($row['id'])
->setMessage($this->getFactory()->find(\ProVM\Emails\Model\Message::class)->fetchById($row['message_id']))
->setDateTime(new DateTimeImmutable($row['date_time']));
if ($row['executed'] ?? 0 === 1) {
$model->wasExecuted();
}
return $model;
}
public function fetchAllPending(): array
{
$query = "SELECT * FROM {$this->getTable()} WHERE `executed` = 0";
return $this->fetchMany($query);
}
public function fetchByMessageAndDate(int $message_id, string $date_time): \ProVM\Emails\Model\Job
{
$query = "SELECT * FROM {$this->getTable()} WHERE `message_id` = ? AND `date_time` = ?";
return $this->fetchOne($query, [$message_id, $date_time]);
}
public function fetchPendingByMessage(int $message_id): \ProVM\Emails\Model\Job
{
$query = "SELECT * FROM {$this->getTable()} WHERE `message_id` = ? AND `executed` = 0";
return $this->fetchOne($query, [$message_id]);
}
}

View File

@ -0,0 +1,89 @@
<?php
namespace ProVM\Emails\Repository;
use PDO;
use ProVM\Common\Define\Model;
use Psr\Log\LoggerInterface;
use ProVM\Common\Implement\Repository;
class Mailbox extends Repository
{
public function __construct(PDO $connection, LoggerInterface $logger, State\Mailbox $states)
{
parent::__construct($connection, $logger);
$this->setStates($states)
->setTable('mailboxes');
}
protected State\Mailbox $stateRepository;
public function getStates(): State\Mailbox
{
return $this->stateRepository;
}
public function setStates(State\Mailbox $states): Mailbox
{
$this->stateRepository = $states;
return $this;
}
protected function fieldsForUpdate(): array
{
return $this->fieldsForInsert();
}
protected function fieldsForInsert(): array
{
return [
'name',
'validity'
];
}
protected function fieldsForCreate(): array
{
return $this->fieldsForInsert();
}
protected function valuesForInsert(Model $model): array
{
return [
$model->getName(),
$model->getValidity()
];
}
protected function defaultFind(Model $model): Model
{
return $this->fetchByName($model->getName());
}
protected function valuesForUpdate(Model $model): array
{
return array_merge($this->valuesForInsert($model), [
$model->getId()
]);
}
protected function valuesForCreate(array $data): array
{
return [
$data['name'],
$data['validity']
];
}
protected function defaultSearch(array $data): Model
{
return $this->fetchByName($data['name']);
}
public function load(array $row): \ProVM\Emails\Model\Mailbox
{
return (new \ProVM\Emails\Model\Mailbox())
->setId($row['id'])
->setName($row['name'])
->setValidity($row['validity'])
->setStateRepository($this->getStates());
}
public function fetchByName(string $name): \ProVM\Emails\Model\Mailbox
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `name` = ?";
return $this->fetchOne($query, [$name]);
}
}

View File

@ -0,0 +1,163 @@
<?php
namespace ProVM\Emails\Repository;
use DateTimeInterface;
use PDO;
use PDOException;
use Exception;
use ProVM\Common\Define\Model;
use Psr\Log\LoggerInterface;
use ProVM\Common\Implement\Repository;
use Safe\DateTimeImmutable;
use Safe\Exceptions\ErrorfuncException;
class Message extends Repository
{
public function __construct(PDO $connection, LoggerInterface $logger, \ProVM\Common\Factory\Model $factory)
{
parent::__construct($connection, $logger);
$this->setTable('messages')
->setFactory($factory);
}
protected \ProVM\Common\Factory\Model $factory;
public function getFactory(): \ProVM\Common\Factory\Model
{
return $this->factory;
}
public function setFactory(\ProVM\Common\Factory\Model $factory): Message
{
$this->factory = $factory;
return $this;
}
protected function fieldsForUpdate(): array
{
return $this->fieldsForInsert();
}
protected function fieldsForInsert(): array
{
return [
'uid',
'mailbox_id',
'position',
'subject',
'from',
'date_time'
];
}
protected function fieldsForCreate(): array
{
return $this->fieldsForUpdate();
}
protected function valuesForUpdate(Model $model): array
{
return array_merge($this->valuesForInsert($model), [
$model->getId()
]);
}
protected function valuesForInsert(Model $model): array
{
return [
$model->getUID(),
$model->getMailbox()->getId(),
$model->getPosition(),
$model->getSubject(),
$model->getFrom(),
$model->getDateTime()->format('Y-m-d H:i:s')
];
}
protected function defaultFind(Model $model): Model
{
return $this->fetchByUID($model->getUID());
}
protected function valuesForCreate(array $data): array
{
return [
$data['mailbox_id'],
$data['position'],
$data['uid'],
$data['subject'],
$data['from'],
$data['date_time']
];
}
protected function defaultSearch(array $data): Model
{
return $this->fetchByUID($data['uid']);
}
/**
* @param array $row
* @return \ProVM\Emails\Model\Message
*/
public function load(array $row): \ProVM\Emails\Model\Message
{
return (new \ProVM\Emails\Model\Message())
->setId($row['id'])
->setUID($row['uid'])
->setMailbox($this->getFactory()->find(\ProVM\Emails\Model\Mailbox::class)->fetchById($row['mailbox_id']))
->setPosition($row['position'])
->setSubject($row['subject'])
->setFrom($row['from'])
->setDateTime(new DateTimeImmutable($row['date_time']))
->setFactory($this->getFactory());
}
public function save(Model &$model): void
{
parent::save($model);
$valid_states = [
'has_attachments',
'valid_attachments',
'downloaded_attachments'
];
foreach ($valid_states as $state_name) {
try {
$model->getState($state_name);
} catch (\Exception $e) {
$data = [
'message_id' => $model->getId(),
'name' => $state_name
];
$state = $this->getFactory()->find(\ProVM\Emails\Model\State\Message::class)->create($data);
$model->addState($state);
}
}
foreach ($model->getStates() as $state) {
$state->setMessage($model);
$this->getFactory()->find(\ProVM\Emails\Model\State\Message::class)->save($state);
}
}
public function fetchByUID(string $uid): \ProVM\Emails\Model\Message
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `uid` = ?";
return $this->fetchOne($query, [$uid]);
}
public function fetchByMailbox(int $mailbox_id): array
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `mailbox_id` = ?";
return $this->fetchMany($query, [$mailbox_id]);
}
public function fetchByMailboxAndPosition(int $mailbox_id, int $start, int $amount): array
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `mailbox_id` = ? AND `position` BETWEEN ? AND ? LIMIT {$amount}";
return $this->fetchMany($query, [$mailbox_id, $start, $start + $amount]);
}
public function fetchValidByMailbox(int $mailbox_id): array
{
$query = "SELECT a.*
FROM `{$this->getTable()}` a
JOIN `messages_states` b ON b.`message_id` = a.`id`
WHERE a.`mailbox_id` = ? AND b.`name` = 'valid_attachments' AND b.`value` = 1";
return $this->fetchMany($query, [$mailbox_id]);
}
public function fetchByMailboxSubjectFromAndDate(int $mailbox_id, string $subject, string $from, DateTimeInterface $dateTime): \ProVM\Emails\Model\Message
{
$query = "SELECT * FROM `{$this->getTable()}`
WHERE `mailbox_id` = ? `subject` = ? AND `from` = ? AND `date_time` = ?";
return $this->fetchOne($query, [$mailbox_id, $subject, $from, $dateTime->format('Y-m-d H:i:s')]);
}
}

View File

@ -0,0 +1,93 @@
<?php
namespace ProVM\Emails\Repository\State;
use PDO;
use ProVM\Common\Define\Model;
use ProVM\Common\Implement\Repository;
use Psr\Log\LoggerInterface;
class Attachment extends Repository
{
public function __construct(PDO $connection, LoggerInterface $logger, \ProVM\Common\Factory\Model $factory)
{
parent::__construct($connection, $logger);
$this->setTable('attachments_states')
->setFactory($factory);
}
protected \ProVM\Common\Factory\Model $factory;
public function getFactory(): \ProVM\Common\Factory\Model
{
return $this->factory;
}
public function setFactory(\ProVM\Common\Factory\Model $factory): Attachment
{
$this->factory = $factory;
return $this;
}
protected function fieldsForInsert(): array
{
return [
'attachment_id',
'name',
'value'
];
}
protected function valuesForInsert(Model $model): array
{
return [
$model->getAttachment()->getId(),
$model->getName(),
$model->getValue() ? 1 : 0
];
}
protected function fieldsForUpdate(): array
{
return $this->fieldsForInsert();
}
protected function defaultFind(Model $model): Model
{
return $this->fetchByAttachmentAndName($model->getAttachment()->getId(), $model->getName());
}
protected function valuesForUpdate(Model $model): array
{
return $this->valuesForInsert($model);
}
protected function fieldsForCreate(): array
{
return $this->fieldsForInsert();
}
protected function valuesForCreate(array $data): array
{
return [
$data['attachment_id'],
$data['name'],
$data['value'] ? 1 : 0
];
}
protected function defaultSearch(array $data): Model
{
return $this->fetchByAttachmentAndName($data['attachment_id'], $data['name']);
}
public function load(array $row): \ProVM\Emails\Model\State\Attachment
{
return (new \ProVM\Emails\Model\State\Attachment())
->setId($row['id'])
->setAttachment($this->getFactory()->find(\ProVM\Emails\Model\Attachment::class)->fetchById($row['attachment_id']))
->setName($row['name'])
->setValue($row['value'] !== 0);
}
public function fetchByAttachment(int $attachment_id): array
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `attachment_id` = ?";
return $this->fetchMany($query, [$attachment_id]);
}
public function fetchByAttachmentAndName(int $attachment_id, string $name): \ProVM\Emails\Model\State\Attachment
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `attachment_id` = ? AND `name` = ?";
return $this->fetchOne($query, [$attachment_id, $name]);
}
}

View File

@ -0,0 +1,102 @@
<?php
namespace ProVM\Emails\Repository\State;
use PDO;
use Psr\Log\LoggerInterface;
use Safe\DateTimeImmutable;
use ProVM\Common\Define\Model;
use ProVM\Common\Implement\Repository;
class Mailbox extends Repository
{
public function __construct(PDO $connection, LoggerInterface $logger, \ProVM\Common\Factory\Model $factory)
{
parent::__construct($connection, $logger);
$this->setTable('mailboxes_states')
->setFactory($factory);
}
protected \ProVM\Common\Factory\Model $factory;
public function getFactory(): \ProVM\Common\Factory\Model
{
return $this->factory;
}
public function setFactory(\ProVM\Common\Factory\Model $factory): Mailbox
{
$this->factory = $factory;
return $this;
}
protected function fieldsForUpdate(): array
{
return $this->fieldsForInsert();
}
protected function valuesForUpdate(Model $model): array
{
return array_merge($this->valuesForInsert($model), [$model->getId()]);
}
protected function fieldsForInsert(): array
{
return [
'mailbox_id',
'date_time',
'count',
'uids'
];
}
protected function valuesForInsert(Model $model): array
{
return [
$model->getMailbox()->getId(),
$model->getDateTime()->format('Y-m-d H:i:s'),
$model->getCount(),
serialize($model->getUIDs())
];
}
protected function defaultFind(Model $model): Model
{
return $this->fetchByMailboxAndDate($model->getMailbox()->getId(), $model->getDateTime()->format('Y-m-d H:i:s'));
}
protected function fieldsForCreate(): array
{
return $this->fieldsForInsert();
}
protected function valuesForCreate(array $data): array
{
return [
$data['mailbox_id'],
$data['date_time'],
$data['count'],
$data['uids']
];
}
protected function defaultSearch(array $data): Model
{
return $this->fetchByMailboxAndDate($data['mailbox_id'], $data['date_time']);
}
public function load(array $row): \ProVM\Emails\Model\State\Mailbox
{
return (new \ProVM\Emails\Model\State\Mailbox())
->setId($row['id'])
->setMailbox($this->getFactory()->find(\ProVM\Emails\Model\Mailbox::class)->fetchById($row['mailbox_id']))
->setDateTime(new DateTimeImmutable($row['date_time']))
->setCount($row['count'])
->setUIDs(unserialize($row['uids']));
}
public function fetchByMailbox(int $mailbox_id): array
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `mailbox_id` = ?";
return $this->fetchMany($query, [$mailbox_id]);
}
public function fetchByMailboxAndDate(int $mailbox_id, \DateTimeInterface | string $date_time): \ProVM\Emails\Model\State\Mailbox
{
if (!is_string($date_time)) {
$date_time = $date_time->format('Y-m-d H:i:s');
}
$query = "SELECT * FROM `{$this->getTable()}` WHERE `mailbox_id` = ? AND `date_time` = ?";
return $this->fetchOne($query, [$mailbox_id, $date_time]);
}
}

View File

@ -0,0 +1,93 @@
<?php
namespace ProVM\Emails\Repository\State;
use PDO;
use ProVM\Common\Define\Model;
use Psr\Log\LoggerInterface;
use ProVM\Common\Implement\Repository;
class Message extends Repository
{
public function __construct(PDO $connection, LoggerInterface $logger, \ProVM\Common\Factory\Model $factory)
{
parent::__construct($connection, $logger);
$this->setTable('messages_states')
->setFactory($factory);
}
protected \ProVM\Common\Factory\Model $factory;
public function getFactory(): \ProVM\Common\Factory\Model
{
return $this->factory;
}
public function setFactory(\ProVM\Common\Factory\Model $factory): Message
{
$this->factory = $factory;
return $this;
}
protected function fieldsForUpdate(): array
{
return $this->fieldsForInsert();
}
protected function valuesForUpdate(Model $model): array
{
return array_merge($this->valuesForInsert($model), [$model->getId()]);
}
public function fieldsForInsert(): array
{
return [
'message_id',
'name',
'value'
];
}
protected function valuesForInsert(Model $model): array
{
return [
$model->getMessage()->getId(),
$model->getName(),
$model->getValue() ? 1 : 0
];
}
protected function defaultFind(Model $model): Model
{
return $this->fetchByMessageAndName($model->getMessage()->getId(), $model->getName());
}
protected function fieldsForCreate(): array
{
return $this->fieldsForInsert();
}
protected function valuesForCreate(array $data): array
{
return [
$data['message_id'],
$data['name'],
$data['value'] ? 1 : 0
];
}
protected function defaultSearch(array $data): Model
{
return $this->fetchByMessageAndName($data['message_id'], $data['name']);
}
public function load(array $row): \ProVM\Emails\Model\State\Message
{
return (new \ProVM\Emails\Model\State\Message())
->setId($row['id'])
->setName($row['name'])
->setMessage($this->getFactory()->find(\ProVM\Emails\Model\Message::class)->fetchById($row['message_id']))
->setValue(($row['value'] ?? 0) !== 0);
}
public function fetchByMessage(int $message_id): array
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `message_id` = ?";
return $this->fetchMany($query, [$message_id]);
}
public function fetchByMessageAndName(int $message_id, string $name): \ProVM\Emails\Model\State\Message
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `message_id` = ? AND `name` = ?";
return $this->fetchOne($query, [$message_id, $name]);
}
}

14
cli/Dockerfile Normal file
View File

@ -0,0 +1,14 @@
FROM php:8-cli
ENV PATH ${PATH}:/app/bin
RUN apt-get update \
&& apt-get install -y cron git libzip-dev unzip \
&& rm -r /var/lib/apt/lists/* \
&& docker-php-ext-install zip
COPY ./crontab /var/spool/cron/crontabs/root
WORKDIR /app
CMD [ "cron", "-f", "-L", "15" ]

3
cli/bin/emails Normal file
View File

@ -0,0 +1,3 @@
#!/bin/bash
php /app/public/index.php "$@"

View File

@ -0,0 +1,67 @@
<?php
namespace ProVM\Common\Command;
use ProVM\Common\Service\Communicator;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'attachments:decrypt',
description: 'Decrypt attachments pending',
hidden: false
)]
class DecryptPdf extends Command
{
public function __construct(Communicator $communicator, string $name = null)
{
$this->setCommunicator($communicator);
parent::__construct($name);
}
protected Communicator $communicator;
public function getCommunicator(): Communicator
{
return $this->communicator;
}
public function setCommunicator(Communicator $communicator): DecryptPdf
{
$this->communicator = $communicator;
return $this;
}
protected function getAttachments(): array
{
$response = $this->getCommunicator()->get('/attachments/pending');
return \Safe\json_decode($response->getBody()->getContents())->attachments;
}
protected function decrypt(string $attachment): bool
{
$response = $this->getCommunicator()->put('/attachments/decrypt', ['attachments' => [$attachment]]);
return \Safe\json_decode($response->getBody()->getContents())->status;
}
public function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$io->title('Decrypt Attachments');
$io->section('Grabbing Attachments');
$attachments = $this->getAttachments();
$io->text('Found ' . count($attachments) . ' attachments.');
$io->section('Decrypting Attachments');
foreach ($attachments as $attachment) {
$status = $this->decrypt($attachment);
if ($status) {
$io->success("{$attachment} decrypted correctly.");
} else {
$io->error("Problem decrypting {$attachment}.");
}
}
$io->success('Done.');
return Command::SUCCESS;
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace ProVM\Common\Command;
use ProVM\Common\Service\Communicator;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'attachments:grab',
description: 'Grab attachments from pending messages',
aliases: ['attachments:get'],
hidden: false
)]
class GrabAttachments extends Command
{
public function __construct(Communicator $communicator, string $name = null)
{
$this->setCommunicator($communicator);
parent::__construct($name);
}
protected Communicator $service;
public function getCommunicator(): Communicator
{
return $this->service;
}
public function setCommunicator(Communicator $service): GrabAttachments
{
$this->service = $service;
return $this;
}
protected function getMessages(): array
{
$response = $this->getCommunicator()->get('/messages/pending');
return \Safe\json_decode($response->getBody()->getContents())->messages;
}
protected function grabAttachments(int $message_uid): int
{
$response = $this->getCommunicator()->put('/attachments/grab', ['messages' => [$message_uid]]);
return \Safe\json_decode($response->getBody()->getContents())->attachment_count;
}
public function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->title('Grab Attachments');
$io->section('Grabbing Messages');
$messages = $this->getMessages();
$io->text('Found ' . count($messages) . ' messages.');
$io->section('Grabbing Attachments');
foreach ($messages as $job) {
$message = $job->message;
$attachments = $this->grabAttachments($message->uid);
$io->text("Found {$attachments} attachments for message UID:{$message->uid}.");
}
$io->success('Done.');
return Command::SUCCESS;
}
}

View File

@ -0,0 +1,66 @@
<?php
namespace ProVM\Common\Command;
use ProVM\Common\Service\Communicator;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'messages:grab',
description: 'Run grab messages job for registered mailboxes',
aliases: ['messages'],
hidden: false
)]
class Messages extends Command
{
public function __construct(Communicator $communicator, string $name = null)
{
$this->setCommunicator($communicator);
parent::__construct($name);
}
protected Communicator $communicator;
public function getCommunicator(): Communicator
{
return $this->communicator;
}
public function setCommunicator(Communicator $communicator): Messages
{
$this->communicator = $communicator;
return $this;
}
protected function getMailboxes(): array
{
$response = $this->getCommunicator()->get('/mailboxes/registered');
return \Safe\json_decode($response->getBody()->getContents())->mailboxes;
}
protected function grabMessages(string $mailbox): int
{
$response = $this->getCommunicator()->put('/messages/grab', ['mailboxes' => [$mailbox]]);
$body = \Safe\json_decode($response->getBody()->getContents());
return $body->message_count;
}
public function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$io->title('Messages');
$io->section('Grabbing Registered Mailboxes');
$mailboxes = $this->getMailboxes();
$io->text('Found ' . count($mailboxes) . ' registered mailboxes.');
$io->section('Grabbing Messages');
foreach ($mailboxes as $mailbox) {
$message_count = $this->grabMessages($mailbox->name);
$io->text("Found {$message_count} messages in {$mailbox->name}.");
}
$io->success('Done.');
return Command::SUCCESS;
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace ProVM\Common\Service;
use HttpResponseException;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\ResponseInterface;
use function Safe\json_encode;
class Communicator
{
public function __construct(ClientInterface $client)
{
$this->setClient($client);
}
protected ClientInterface $client;
public function getClient(): ClientInterface
{
return $this->client;
}
public function setClient(ClientInterface $client): Communicator
{
$this->client = $client;
return $this;
}
protected function handleResponse(ResponseInterface $response): ResponseInterface
{
if ($response->getStatusCode() < 200 or $response->getStatusCode() >= 300) {
throw new HttpResponseException($response->getStatusCode(), $response->getReasonPhrase());
}
return $response;
}
protected function request(string $method, string $uri, ?array $body = null): ResponseInterface
{
$options = [];
if ($body !== null) {
$options['headers'] = [
'Content-Type' => 'application/json'
];
$options['body'] = json_encode($body);
}
return $this->handleResponse($this->getClient()->request($method, $uri, $options));
}
public function get(string $uri): ResponseInterface
{
return $this->request('get', $uri);
}
public function post(string $uri, array $data): ResponseInterface
{
return $this->request('post', $uri, $data);
}
public function put(string $uri, array $data): ResponseInterface
{
return $this->request('put', $uri, $data);
}
public function delete(string $uri, array $data): ResponseInterface
{
return $this->request('delete', $uri, $data);
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace ProVM\Common\Wrapper;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Application as Base;
class Application extends Base
{
public function __construct(ContainerInterface $container, string $name = 'UNKNOWN', string $version = 'UNKNOWN')
{
$this->setContainer($container);
parent::__construct($name, $version);
}
protected ContainerInterface $container;
public function getContainer(): ContainerInterface
{
return $this->container;
}
public function setContainer(ContainerInterface $container): Application
{
$this->container = $container;
return $this;
}
}

30
cli/composer.json Normal file
View File

@ -0,0 +1,30 @@
{
"name": "provm/emails",
"type": "project",
"require": {
"guzzlehttp/guzzle": "^7.5",
"monolog/monolog": "^3.2",
"php-di/php-di": "^6.4",
"symfony/console": "^6.1",
"thecodingmachine/safe": "^2.4"
},
"require-dev": {
"kint-php/kint": "^4.2",
"mockery/mockery": "^1.5",
"phpunit/phpunit": "^9.5"
},
"autoload": {
"psr-4": {
"ProVM\\Common\\": "common/"
}
},
"authors": [
{
"name": "Aldarien",
"email": "aldarien85@gmail.com"
}
],
"config": {
"sort-packages": true
}
}

3
cli/crontab Normal file
View File

@ -0,0 +1,3 @@
# minutes hour day_of_month month day_of_week command
0 2 * * 2-6 /app/bin/emails messages:grab >> /logs/messages.log
0 3 * * 2-6 /app/bin/emails attachments:grab >> /logs/attachments.log

15
cli/docker-compose.yml Normal file
View File

@ -0,0 +1,15 @@
version: '3'
services:
cli:
profiles:
- cli
container_name: emails-cli
build:
context: ${CLI_PATH:-.}
restart: unless-stopped
env_file:
- ${CLI_PATH:-.}/.env
- .key.env
volumes:
- ${CLI_PATH:-.}/:/app
- ./logs/cli:/logs

12
cli/public/index.php Normal file
View File

@ -0,0 +1,12 @@
<?php
$app = require_once implode(DIRECTORY_SEPARATOR, [
dirname(__FILE__, 2),
'setup',
'app.php'
]);
try {
$app->run();
} catch (Error | Exception $e) {
$app->getContainer()->get(\Psr\Log\LoggerInterface::class)->error($e);
throw $e;
}

View File

@ -0,0 +1,2 @@
<?php
$app->add($app->getContainer()->get(\ProVM\Common\Command\Messages::class));

View File

@ -0,0 +1,3 @@
<?php
$app->add($app->getContainer()->get(\ProVM\Common\Command\GrabAttachments::class));
$app->add($app->getContainer()->get(\ProVM\Common\Command\DecryptPdf::class));

43
cli/setup/app.php Normal file
View File

@ -0,0 +1,43 @@
<?php
require_once 'composer.php';
$builder = new \DI\ContainerBuilder();
$folders = [
'settings',
'setups'
];
foreach ($folders as $f) {
$folder = implode(DIRECTORY_SEPARATOR, [
__DIR__,
$f
]);
if (!file_exists($folder)) {
continue;
}
$files = new FilesystemIterator($folder);
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
$builder->addDefinitions($file->getRealPath());
}
}
$app = new \ProVM\Common\Wrapper\Application($builder->build());
$folder = implode(DIRECTORY_SEPARATOR, [
__DIR__,
'middleware'
]);
if (file_exists($folder)) {
$files = new FilesystemIterator($folder);
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
include_once $file->getRealPath();
}
}
return $app;

6
cli/setup/composer.php Normal file
View File

@ -0,0 +1,6 @@
<?php
require_once implode(DIRECTORY_SEPARATOR, [
dirname(__FILE__, 2),
'vendor',
'autoload.php'
]);

View File

@ -0,0 +1,9 @@
<?php
$folder = $app->getContainer()->get('commands_folder');
$files = new FilesystemIterator($folder);
foreach ($files as $file) {
if ($file->isDir()) {
continue;
}
include_once $file->getRealPath();
}

View File

@ -0,0 +1,5 @@
<?php
return [
'api_uri' => $_ENV['API_URI'],
'api_key' => sha1($_ENV['API_KEY'])
];

View File

@ -0,0 +1,18 @@
<?php
use Psr\Container\ContainerInterface;
return [
'base_folder' => dirname(__FILE__, 3),
'resources_folder' => function(ContainerInterface $container) {
return implode(DIRECTORY_SEPARATOR, [
$container->get('base_folder'),
'resources'
]);
},
'commands_folder' => function(ContainerInterface $container) {
return implode(DIRECTORY_SEPARATOR, [
$container->get('resources_folder'),
'commands'
]);
}
];

View File

@ -0,0 +1,4 @@
<?php
return [
'log_file' => '/logs/php.log'
];

View File

@ -0,0 +1,13 @@
<?php
use Psr\Container\ContainerInterface;
return [
\Psr\Http\Client\ClientInterface::class => function(ContainerInterface $container) {
return new \GuzzleHttp\Client([
'base_uri' => $container->get('api_uri'),
'headers' => [
'Authorization' => "Bearer {$container->get('api_key')}"
]
]);
}
];

View File

@ -0,0 +1,15 @@
<?php
use Psr\Container\ContainerInterface;
return [
\Monolog\Handler\RotatingFileHandler::class => function(ContainerInterface $container) {
$handler = new \Monolog\Handler\RotatingFileHandler($container->get('log_file'));
$handler->setFormatter($container->get(\Monolog\Formatter\LineFormatter::class));
return $handler;
},
\Psr\Log\LoggerInterface::class => function(ContainerInterface $container) {
$logger = new \Monolog\Logger('file_logger');
$logger->pushHandler($container->get(\Monolog\Handler\RotatingFileHandler::class));
return $logger;
}
];

45
default.conf Normal file
View File

@ -0,0 +1,45 @@
# server {
# listen 80;
# listen [::]:80;
# server_name localhost;
#
# #access_log /var/log/nginx/host.access.log main;
#
# location / {
# root /usr/share/nginx/html;
# index index.html index.htm;
# }
#
# #error_page 404 /404.html;
#
# # redirect server error pages to the static page /50x.html
# #
# error_page 500 502 503 504 /50x.html;
# location = /50x.html {
# root /usr/share/nginx/html;
# }
#
# # proxy the PHP scripts to Apache listening on 127.0.0.1:80
# #
# #location ~ \.php$ {
# # proxy_pass http://127.0.0.1;
# #}
#
# # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
# #
# #location ~ \.php$ {
# # root html;
# # fastcgi_pass 127.0.0.1:9000;
# # fastcgi_index index.php;
# # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# # include fastcgi_params;
# #}
#
# # deny access to .htaccess files, if Apache's document root
# # concurs with nginx's one
# #
# #location ~ /\.ht {
# # deny all;
# #}
# }

12
docker-compose.yml Normal file
View File

@ -0,0 +1,12 @@
version: '3'
services:
proxy:
container_name: emails-proxy
image: nginx
restart: unless-stopped
volumes:
- ./default.conf:/etc/nginx/conf.d/default.conf
- ${LOGS_PATH}/proxy:/var/logs/nginx
ports:
- "${WEB_PORT:-80}:80"

Some files were not shown because too many files have changed in this diff Show More