From c3ae222906ca57d3df4781e9b8023884f06a2951 Mon Sep 17 00:00:00 2001 From: Jean-Yves <7360784+docjyJ@users.noreply.github.com> Date: Mon, 7 Oct 2024 18:58:52 +0200 Subject: [PATCH] EntityImmutable --- compose.mysql.yml | 25 ++++- lib/Controller/ApiController.php | 29 ++---- lib/Cron/CheckTask.php | 4 +- lib/Db/AccountManager.php | 23 +++-- lib/Db/ConfigManager.php | 38 +++---- lib/Event/EmailChangedListener.php | 14 ++- lib/Event/PasswordChangedListener.php | 7 +- lib/Event/UserDeletedListener.php | 2 +- lib/Models/ConfigEntity.php | 68 +++++++++++-- lib/Models/ServerStatus.php | 1 - lib/ParseMixed.php | 38 +++---- lib/ResponseDefinitions.php | 2 +- lib/Services/MysqlService.php | 4 +- lib/Services/StalwartAPIService.php | 138 +++++++++++--------------- makefile | 8 +- openapi.json | 3 +- 16 files changed, 209 insertions(+), 195 deletions(-) diff --git a/compose.mysql.yml b/compose.mysql.yml index 7fd68c7..5752e98 100644 --- a/compose.mysql.yml +++ b/compose.mysql.yml @@ -1,6 +1,7 @@ services: mysql: image: mariadb:10.6 + hostname: database command: --transaction-isolation=READ-COMMITTED --log-bin=binlog --binlog-format=ROW ports: - "127.0.0.1:3306:3306" @@ -18,15 +19,31 @@ services: timeout: 5s retries: 3 + nextcloud_init: + image: nextcloud:30 + command: apache2 -v + volumes: + - nextcloud:/var/www/html:z + environment: + - MYSQL_HOST=database + - MYSQL_DATABASE=nextcloud + - MYSQL_USER=root + - MYSQL_PASSWORD=root + - NEXTCLOUD_ADMIN_USER=admin + - NEXTCLOUD_ADMIN_PASSWORD=admin + depends_on: + mysql: + condition: service_healthy + nextcloud: - image: nextcloud:apache + image: nextcloud:30 ports: - "127.0.0.1:8080:80" volumes: - .:/var/www/html/custom_apps/stalwart:z - nextcloud:/var/www/html:z environment: - - MYSQL_HOST=mysql + - MYSQL_HOST=database - MYSQL_DATABASE=nextcloud - MYSQL_USER=root - MYSQL_PASSWORD=root @@ -35,6 +52,8 @@ services: depends_on: mysql: condition: service_healthy + nextcloud_init: + condition: service_completed_successfully phpmyadmin: image: phpmyadmin @@ -49,7 +68,7 @@ services: condition: service_healthy stalwart: - image: stalwartlabs/mail-server:latest + image: stalwartlabs/mail-server:v0.10.3 hostname: stalwart ports: - "127.0.0.1:9090:8080" diff --git a/lib/Controller/ApiController.php b/lib/Controller/ApiController.php index fe48167..fb925fd 100644 --- a/lib/Controller/ApiController.php +++ b/lib/Controller/ApiController.php @@ -8,7 +8,6 @@ use OCA\Stalwart\Db\ConfigManager; use OCA\Stalwart\Db\EmailManager; use OCA\Stalwart\Models\AccountEntity; -use OCA\Stalwart\Models\ConfigEntity; use OCA\Stalwart\Models\EmailEntity; use OCA\Stalwart\ResponseDefinitions; use OCA\Stalwart\Settings\Admin; @@ -43,16 +42,6 @@ public function __construct( parent::__construct($appName, $request); } - /** @return StalwartServerConfig */ - private static function getConfigData(ConfigEntity $config): array { - return [ - 'id' => $config->cid, - 'endpoint' => $config->endpoint, - 'username' => $config->username, - 'health' => $config->health->value, - ]; - } - /** @return StalwartServerUser */ private static function getUserDataWithoutMail(AccountEntity $account): array { return [ @@ -84,7 +73,7 @@ private static function getUserData(EmailEntity $email): array { #[ApiRoute(verb: 'GET', url: '/config')] public function list(): DataResponse { try { - return new DataResponse(array_map(fn ($c) => self::getConfigData($c), $this->configManager->list())); + return new DataResponse(array_map(fn ($c) => $c->toArrayData(), $this->configManager->list())); } catch (Exception $config) { $this->logger->error($config->getMessage(), ['exception' => $config]); throw new OCSException($config->getMessage(), Http::STATUS_INTERNAL_SERVER_ERROR); @@ -103,7 +92,7 @@ public function list(): DataResponse { #[ApiRoute(verb: 'POST', url: '/config')] public function post(): DataResponse { try { - return new DataResponse(self::getConfigData($this->configManager->create())); + return new DataResponse($this->configManager->create()->toArrayData()); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); throw new OCSException($e->getMessage(), Http::STATUS_INTERNAL_SERVER_ERROR); @@ -125,7 +114,7 @@ public function post(): DataResponse { public function get(int $cid): DataResponse { try { if ($config = $this->configManager->find($cid)) { - return new DataResponse(self::getConfigData($config)); + return new DataResponse($config->toArrayData()); } else { throw new OCSNotFoundException(); } @@ -153,13 +142,9 @@ public function get(int $cid): DataResponse { public function put(int $cid, string $endpoint, string $username, string $password): DataResponse { try { if ($config = $this->configManager->find($cid)) { - $config->endpoint = $endpoint; - $config->username = $username; - if ($password !== '') { - $config->password = $password; - } - $this->configManager->update($config); - return new DataResponse(self::getConfigData($config)); + $config = $config->updateCredential($endpoint, $username, $password); + $config = $this->configManager->update($config); + return new DataResponse($config->toArrayData()); } else { throw new OCSNotFoundException(); } @@ -185,7 +170,7 @@ public function delete(int $cid): DataResponse { try { if ($config = $this->configManager->find($cid)) { $this->configManager->delete($config); - return new DataResponse(self::getConfigData($config)); + return new DataResponse($config->toArrayData()); } else { throw new OCSNotFoundException(); } diff --git a/lib/Cron/CheckTask.php b/lib/Cron/CheckTask.php index 9b81c43..c7dcbdf 100644 --- a/lib/Cron/CheckTask.php +++ b/lib/Cron/CheckTask.php @@ -2,7 +2,6 @@ namespace OCA\Stalwart\Cron; -use DateTime; use OCA\Stalwart\Db\ConfigManager; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\TimedJob; @@ -20,9 +19,8 @@ public function __construct( /** @throws Exception */ protected function run(mixed $argument): void { - $now = new DateTime(); foreach ($this->configService->list() as $config) { - if ($config->expires <= $now) { + if ($config->hasExpired()) { $this->configService->update($config); } } diff --git a/lib/Db/AccountManager.php b/lib/Db/AccountManager.php index bf2b5fe..ffb2f81 100644 --- a/lib/Db/AccountManager.php +++ b/lib/Db/AccountManager.php @@ -17,6 +17,10 @@ public function __construct( ) { } + private static function getHashFromUser(IUser $user): string { + return preg_replace('/^[^$]*/', '', $user->getPasswordHash() ?? '') ?? ''; + } + /** * @return AccountEntity[] * @throws Exception @@ -28,7 +32,7 @@ public function list(ConfigEntity $config): array { ->where($q->expr()->eq('cid', $q->createNamedParameter($config->cid, IQueryBuilder::PARAM_INT))); $result = $q->executeQuery(); $entities = []; - while ($account = ParseMixed::accuntEntity($config, $result->fetch())) { + while ($account = ParseMixed::accountEntity($config, $result->fetch())) { $entities[] = $account; } $result->closeCursor(); @@ -43,16 +47,14 @@ public function find(ConfigEntity $config, string $uid): ?AccountEntity { ->where($q->expr()->eq('cid', $q->createNamedParameter($config->cid, IQueryBuilder::PARAM_INT))) ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid))); $result = $q->executeQuery(); - $account = ParseMixed::accuntEntity($config, $result->fetch()); + $account = ParseMixed::accountEntity($config, $result->fetch()); $result->closeCursor(); return $account; } /** @throws Exception */ public function createIndividual(ConfigEntity $config, IUser $user): AccountEntity { - $password = $user->getPasswordHash() ?? null; - $password = $password !== null ? preg_replace('/^[^|]*|/', '', $password) ?? $password : ''; - $account = new AccountEntity($config, $user->getUID(), $user->getDisplayName(), $password); + $account = new AccountEntity($config, $user->getUID(), $user->getDisplayName(), self::getHashFromUser($user)); $this->db->beginTransaction(); try { $q = $this->db->getQueryBuilder(); @@ -109,12 +111,12 @@ public function listUser(string $uid): array { } /** @throws Exception */ - public function forceDelete(string $uid): void { + public function deleteUser(IUser $user): void { $this->db->beginTransaction(); try { $q = $this->db->getQueryBuilder(); $q->delete(AccountEntity::TABLE) - ->where($q->expr()->eq('uid', $q->createNamedParameter($uid))) + ->where($q->expr()->eq('uid', $q->createNamedParameter($user->getUID()))) ->executeStatement(); $this->db->commit(); } catch (Exception $e) { @@ -124,13 +126,14 @@ public function forceDelete(string $uid): void { } /** @throws Exception */ - public function forceUpdatePassword(string $uid, string $password): void { + public function updateUser(IUser $user): void { $this->db->beginTransaction(); try { $q = $this->db->getQueryBuilder(); $q->update(AccountEntity::TABLE) - ->set('password', $q->createNamedParameter($password)) - ->where($q->expr()->eq('uid', $q->createNamedParameter($uid))) + ->set('password', $q->createNamedParameter(self::getHashFromUser($user))) + ->set('display_name', $q->createNamedParameter($user->getDisplayName())) + ->where($q->expr()->eq('uid', $q->createNamedParameter($user->getUID()))) ->executeStatement(); $this->db->commit(); } catch (Exception $e) { diff --git a/lib/Db/ConfigManager.php b/lib/Db/ConfigManager.php index 6bdadf5..3f345d5 100644 --- a/lib/Db/ConfigManager.php +++ b/lib/Db/ConfigManager.php @@ -2,7 +2,7 @@ namespace OCA\Stalwart\Db; -use DateTime; +use DateTimeImmutable; use OCA\Stalwart\Models\ConfigEntity; use OCA\Stalwart\Models\ServerStatus; use OCA\Stalwart\ParseMixed; @@ -49,17 +49,8 @@ public function list(): array { } /** @throws Exception */ - public function update(ConfigEntity $config): void { - $heathResult = $this->apiService->challenge($config->endpoint, $config->username, $config->password); - $config->health = $heathResult[0]; - $config->expires = $heathResult[1]; - if ($heathResult[0] === ServerStatus::Success || $heathResult[0] === ServerStatus::NoAdmin) { - try { - $this->apiService->pushDataBase($config->cid, $config->endpoint, $config->username, $config->password); - } catch (\Exception $e) { - throw new Exception('Failed to push data to server', previous: $e); - } - } + public function update(ConfigEntity $config): ConfigEntity { + $config = $config->updateHealth($this->apiService->challenge($config)); $this->db->beginTransaction(); try { $q = $this->db->getQueryBuilder(); @@ -72,6 +63,7 @@ public function update(ConfigEntity $config): void { ->where($q->expr()->eq('cid', $q->createNamedParameter($config->cid, IQueryBuilder::PARAM_INT))) ->executeStatement(); $this->db->commit(); + return $config; } catch (Exception $e) { $this->db->rollBack(); throw $e; @@ -80,28 +72,22 @@ public function update(ConfigEntity $config): void { /** @throws Exception */ public function create(): ConfigEntity { - $config = new ConfigEntity( - 0, - '', - '', - '', - ServerStatus::Invalid, - new DateTime(), - ); + $date = new DateTimeImmutable(); + $state = ServerStatus::Invalid; $this->db->beginTransaction(); try { $q = $this->db->getQueryBuilder(); $q->insert(ConfigEntity::TABLE) ->values([ - 'endpoint' => $q->createNamedParameter($config->endpoint), - 'username' => $q->createNamedParameter($config->username), - 'password' => $q->createNamedParameter($config->password), - 'health' => $q->createNamedParameter($config->health->value), - 'expires' => $q->createNamedParameter($config->expires, IQueryBuilder::PARAM_DATE), + 'endpoint' => $q->createNamedParameter(''), + 'username' => $q->createNamedParameter(''), + 'password' => $q->createNamedParameter(''), + 'health' => $q->createNamedParameter($state->value), + 'expires' => $q->createNamedParameter($date, IQueryBuilder::PARAM_DATE), ]) ->executeStatement(); - $config->cid = $q->getLastInsertId(); + $config = new ConfigEntity($q->getLastInsertId(), '', '', '', $state, $date); $this->db->commit(); } catch (Exception $e) { $this->db->rollBack(); diff --git a/lib/Event/EmailChangedListener.php b/lib/Event/EmailChangedListener.php index 4269c15..90e1935 100644 --- a/lib/Event/EmailChangedListener.php +++ b/lib/Event/EmailChangedListener.php @@ -27,14 +27,12 @@ public function __construct( * @throws Exception */ public function handle(Event $event): void { - if ($event->getFeature() === 'email') { - /** @psalm-suppress MixedAssignment */ - $email = $event->getValue(); - if (is_string($email)) { - $uid = $event->getUser()->getUID(); - foreach ($this->accountManager->listUser($event->getUser()->getUID()) as $cid) { - $this->emailManager->setPrimary(new AccountEntity(new ConfigEntity($cid), $uid), $email); - } + $this->accountManager->updateUser($event->getUser()); + $email = $event->getUser()->getEMailAddress(); + if ($email !== null) { + $uid = $event->getUser()->getUID(); + foreach ($this->accountManager->listUser($event->getUser()->getUID()) as $cid) { + $this->emailManager->setPrimary(new AccountEntity(new ConfigEntity($cid), $uid), $email); } } } diff --git a/lib/Event/PasswordChangedListener.php b/lib/Event/PasswordChangedListener.php index 2782436..2aa998b 100644 --- a/lib/Event/PasswordChangedListener.php +++ b/lib/Event/PasswordChangedListener.php @@ -23,11 +23,6 @@ public function __construct( * @throws Exception */ public function handle(Event $event): void { - $password = $event->getUser()->getPasswordHash(); - if ($password !== null) { - $this->accountManager->forceUpdatePassword( - $event->getUser()->getUID(), - preg_replace('/^[^|]*|/', '', $password) ?? $password); - } + $this->accountManager->updateUser($event->getUser()); } } diff --git a/lib/Event/UserDeletedListener.php b/lib/Event/UserDeletedListener.php index d7a4655..d5d13a4 100644 --- a/lib/Event/UserDeletedListener.php +++ b/lib/Event/UserDeletedListener.php @@ -23,6 +23,6 @@ public function __construct( * @throws Exception */ public function handle(Event $event): void { - $this->accountManager->forceDelete($event->getUser()->getUID()); + $this->accountManager->deleteUser($event->getUser()); } } diff --git a/lib/Models/ConfigEntity.php b/lib/Models/ConfigEntity.php index b2b54e2..e03864d 100644 --- a/lib/Models/ConfigEntity.php +++ b/lib/Models/ConfigEntity.php @@ -2,20 +2,76 @@ namespace OCA\Stalwart\Models; +use DateInterval; use DateTime; +use DateTimeImmutable; use OCA\Stalwart\ResponseDefinitions; /** @psalm-import-type StalwartServerConfig from ResponseDefinitions */ class ConfigEntity { public const TABLE = 'stalwart_configs'; + private const URL_PATTERN = '/^https?:\\/\\/([a-z0-9-]+\\.)*[a-z0-9-]+(:\\d{1,5})?\\/api$/'; + public function __construct( - public int $cid, - public string $endpoint = '', - public string $username = '', - public string $password = '', - public ServerStatus $health = ServerStatus::Invalid, - public DateTime $expires = new DateTime(), + public readonly int $cid, + public readonly string $endpoint = '', + public readonly string $username = '', + public readonly string $password = '', + public readonly ServerStatus $health = ServerStatus::Invalid, + public readonly DateTimeImmutable $expires = new DateTimeImmutable(), ) { } + + /** @return StalwartServerConfig */ + public function toArrayData(): array { + return [ + 'id' => $this->cid, + 'endpoint' => $this->endpoint, + 'username' => $this->username, + 'health' => $this->health->value, + ]; + } + + public function getUrl(string $subpart = ''): ?string { + return preg_match(self::URL_PATTERN, $this->endpoint) === 1 + ? $this->endpoint . $subpart + : null; + } + + public function getBasicAuth(): ?string { + return $this->username !== '' && $this->password !== '' + ? 'Basic ' . base64_encode($this->username . ':' . $this->password) + : null; + } + + public function hasExpired(): bool { + return $this->expires < new DateTime(); + } + + public function updateCredential(string $endpoint, string $username, string $password): self { + return new self( + $this->cid, + $endpoint, + $username, + $password !== '' ? $password : $this->password, + $this->health, + $this->expires + ); + } + + public function updateHealth(ServerStatus $health): self { + $date = new DateTimeImmutable(); + $interval = $health === ServerStatus::Success + ? new DateInterval('P1D') + : new DateInterval('PT1H'); + return new self( + $this->cid, + $this->endpoint, + $this->username, + $this->password, + $health, + $date->add($interval) + ); + } } diff --git a/lib/Models/ServerStatus.php b/lib/Models/ServerStatus.php index 9252150..72bd250 100644 --- a/lib/Models/ServerStatus.php +++ b/lib/Models/ServerStatus.php @@ -4,7 +4,6 @@ enum ServerStatus: string { case Success = 'success'; - case NoAdmin = 'unprivileged'; case Unauthorized = 'unauthorized'; case BadServer = 'bad_server'; case BadNetwork = 'bad_network'; diff --git a/lib/ParseMixed.php b/lib/ParseMixed.php index 4ea6bd6..e9b354d 100644 --- a/lib/ParseMixed.php +++ b/lib/ParseMixed.php @@ -2,7 +2,7 @@ namespace OCA\Stalwart; -use DateTime; +use DateTimeImmutable; use Exception; use OCA\Stalwart\Models\AccountEntity; use OCA\Stalwart\Models\AccountType; @@ -17,9 +17,13 @@ public static function int(mixed $value): ?int { return is_int($value) ? $value : null; } - public static function dateTime(mixed $value): ?DateTime { + public static function string(mixed $value): ?string { + return is_string($value) ? $value : null; + } + + public static function dateTime(mixed $value): ?DateTimeImmutable { try { - return is_string($value) ? new DateTime($value) : null; + return is_string($value) ? new DateTimeImmutable($value) : null; } catch (Exception) { return null; } @@ -28,7 +32,6 @@ public static function dateTime(mixed $value): ?DateTime { public static function serverStatus(mixed $value): ?ServerStatus { return is_string($value) ? match ($value) { 'success' => ServerStatus::Success, - 'unprivileged' => ServerStatus::NoAdmin, 'unauthorized' => ServerStatus::Unauthorized, 'bad_server' => ServerStatus::BadServer, 'bad_network' => ServerStatus::BadNetwork, @@ -56,28 +59,19 @@ private static function emailType(mixed $value): ?EmailType { public static function configEntity(mixed $value): ?ConfigEntity { if (is_array($value) && is_int($value['cid'])) { - $entity = new ConfigEntity($value['cid']); - if (is_string($value['endpoint'])) { - $entity->endpoint = $value['endpoint']; - } - if (is_string($value['username'])) { - $entity->username = $value['username']; - } - if (is_string($value['password'])) { - $entity->password = $value['password']; - } - if ($health = self::serverStatus($value['health'])) { - $entity->health = $health; - } - if ($expires = self::dateTime($value['expires'])) { - $entity->expires = $expires; - } - return $entity; + return new ConfigEntity( + $value['cid'], + self::string($value['endpoint']) ?? '', + self::string($value['username']) ?? '', + self::string($value['password']) ?? '', + self::serverStatus($value['health']) ?? ServerStatus::Invalid, + self::dateTime($value['expires']) ?? new DateTimeImmutable(), + ); } return null; } - public static function accuntEntity(ConfigEntity $conf, mixed $value): ?AccountEntity { + public static function accountEntity(ConfigEntity $conf, mixed $value): ?AccountEntity { if (is_array($value) && $value['cid'] === $conf->cid && is_string($value['uid'])) { $entity = new AccountEntity($conf, $value['uid']); if ($type = self::accountType($value['type'])) { diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index d034b3a..0248037 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -8,7 +8,7 @@ * id: int, * endpoint: string, * username: string, - * health: 'bad_network'|'bad_server'|'invalid'|'success'|'unauthorized'|'unprivileged', + * health: 'bad_network'|'bad_server'|'invalid'|'success'|'unauthorized', * } * @psalm-type StalwartServerUser = array{ * uid: string, diff --git a/lib/Services/MysqlService.php b/lib/Services/MysqlService.php index 879205c..ee08fbb 100644 --- a/lib/Services/MysqlService.php +++ b/lib/Services/MysqlService.php @@ -16,7 +16,9 @@ class MysqlService implements ISqlService { // SELECT member_of FROM group_members WHERE name = ? private const QUERY_MEMBERS = <<getSystemValue('dbtype'); @@ -36,89 +33,72 @@ public function __construct( $this->sqlService = $sqlService; } - private static function genCred(string $username, string $password): string { - return 'Basic ' . base64_encode($username . ':' . $password); - } - - /** - * @param IResponse $response - * @return string - */ - private static function readBody(IResponse $response): string { - $body = $response->getBody(); - if (is_string($body)) { - return $body; - } - $content = stream_get_contents($body); - if ($content !== false) { - return $content; + private function settings(string $url, string $auth, string $settings): ?int { + $client = $this->clientService->newClient(); + try { + return $client->post($url . '/settings', [ + 'body' => $settings, + 'headers' => ['Authorization' => $auth] + ])->getStatusCode(); + } catch (Exception $e) { + $this->logger->warning($e->getMessage(), ['exception' => $e]); + try { + return $client->getResponseFromThrowable($e)->getStatusCode(); + } catch (Throwable) { + return null; + } } - return 'Can\'t read the response body'; } - /** - * @param bool $success - * @return DateTime - */ - private static function getExpiration(bool $success): DateTime { - $expiration = new DateTime(); - return $expiration->add($success - ? new DateInterval('P1D') - : new DateInterval('PT1H')); + private function reload(string $url, string $auth): ?int { + $client = $this->clientService->newClient(); + try { + return $client->get($url . '/reload', [ + 'headers' => ['Authorization' => $auth] + ])->getStatusCode(); + } catch (Exception $e) { + $this->logger->warning($e->getMessage(), ['exception' => $e]); + try { + return $client->getResponseFromThrowable($e)->getStatusCode(); + } catch (Throwable) { + return null; + } + } } - /** - * @param string $endpoint - * @param string $username - * @param string $password - * - * @return array{0: ServerStatus, 1: DateTime} - * @psalm-return list{ServerStatus, DateTime} - */ - public function challenge(string $endpoint, string $username, string $password): array { - if ($username === '' || $password === '' || preg_match(self::URL_PATTERN, $endpoint) !== 1) { - $this->logger->warning('A Stalwart server configuration is invalid'); - return [ServerStatus::Invalid, self::getExpiration(false)]; + public function challenge(ConfigEntity $config): ServerStatus { + $auth = $config->getBasicAuth(); + if ($auth === null) { + $this->logger->warning('Configurations ' . $config->cid . ' has no credentials'); + return ServerStatus::Invalid; } - $client = $this->clientService->newClient(); + $url = $config->getUrl(); + if ($url === null) { + $this->logger->warning('Configurations ' . $config->cid . ' has an invalid endpoint'); + return ServerStatus::Invalid; + } try { - $response = $client->post($endpoint . '/oauth', [ - 'body' => json_encode([ - 'type' => 'Code', - 'client_id' => 'nextcloud', - 'redirect_uri' => null - ], JSON_THROW_ON_ERROR), - 'headers' => ['Authorization' => self::genCred($username, $password)] - ]); - if (str_contains(self::readBody($response), '"is_admin":true')) { - return [ ServerStatus::Success, self::getExpiration(true) ]; - } else { - $this->logger->warning('The user of a Stalwart server is not an admin'); - return [ ServerStatus::NoAdmin, self::getExpiration(true) ]; - } - } catch (Throwable $e) { - try { - $response = $client->getResponseFromThrowable($e); - $this->logger->warning($e->getMessage(), ['exception' => $e]); - return [ - $response->getStatusCode() === 401 ? ServerStatus::Unauthorized : ServerStatus::BadServer, - self::getExpiration(false) - ]; - } catch (Throwable $e) { - $this->logger->warning($e->getMessage(), ['exception' => $e]); - return [ServerStatus::BadNetwork, self::getExpiration(false)]; + $settings = $this->sqlService->getStalwartConfig($config->cid); + } catch (Exception $e) { + $this->logger->warning($e->getMessage(), ['exception' => $e]); + return ServerStatus::Invalid; + } + + $code = $this->settings($url, $auth, $settings); + if ($code === 200) { + $code = $this->reload($url, $auth); + if ($code === 200) { + return ServerStatus::Success; } } - } + if ($code === 401) { + return ServerStatus::Unauthorized; + } - /** - * @throws Exception - */ - public function pushDataBase(int $config_id, string $endpoint, string $username, string $password): void { - $this->clientService->newClient()->post($endpoint . '/settings', [ - 'body' => $this->sqlService->getStalwartConfig($config_id), - 'headers' => ['Authorization' => self::genCred($username, $password)] - ]); + if ($code === null) { + return ServerStatus::BadNetwork; + } + return ServerStatus::BadServer; } } diff --git a/makefile b/makefile index 6432963..3592d5c 100644 --- a/makefile +++ b/makefile @@ -10,16 +10,16 @@ install: @composer install start-mysql: - $(COMPOSE_CLI) -f compose.mysql.yml up + docker compose -f compose.mysql.yml up stop-mysql: - $(COMPOSE_CLI) -f compose.mysql.yml down + docker compose -f compose.mysql.yml down remove-mysql: - $(COMPOSE_CLI) -f compose.mysql.yml down --volumes + docker compose -f compose.mysql.yml down --volumes fix-mysql: - $(COMPOSE_CLI) -f compose.mysql.yml exec -u 33 nextcloud php occ config:system:set --type bool --value true allow_local_remote_servers + docker compose -f compose.mysql.yml exec -u 33 nextcloud php occ config:system:set --type bool --value true allow_local_remote_servers watch: npm run watch diff --git a/openapi.json b/openapi.json index 5d9b18a..fea542b 100644 --- a/openapi.json +++ b/openapi.json @@ -70,8 +70,7 @@ "bad_server", "invalid", "success", - "unauthorized", - "unprivileged" + "unauthorized" ] } }