* SPDX-License-Identifier: AGPL-3.0-or-later */ namespace KTXM\MailManager\Controllers; use InvalidArgumentException; use KTXC\Http\Response\JsonResponse; use KTXC\Http\Response\Response; use KTXC\Http\Response\StreamedNdJsonResponse; use KTXC\SessionIdentity; use KTXC\SessionTenant; use KTXF\Controller\ControllerAbstract; use KTXF\Json\JsonSerializable; use KTXF\Resource\Identifier\CollectionIdentifier; use KTXF\Resource\Identifier\EntityIdentifier; use KTXF\Resource\Identifier\ResourceIdentifier; use KTXF\Resource\Identifier\ResourceIdentifiers; use KTXF\Resource\Provider\ResourceServiceLocationInterface; use KTXF\Resource\Selector\SourceSelector; use KTXF\Routing\Attributes\AuthenticatedRoute; use KTXM\MailManager\Manager; use Psr\Log\LoggerInterface; use Throwable; /** * Default Controller - Unified Mail API * * Handles all mail operations in JMAP-style API pattern. * Supports both single operations and batches with result references. */ class DefaultController extends ControllerAbstract { private const ERR_MISSING_PROVIDER = 'Missing parameter: provider'; private const ERR_MISSING_IDENTIFIER = 'Missing parameter: identifier'; private const ERR_MISSING_SERVICE = 'Missing parameter: service'; private const ERR_MISSING_COLLECTION = 'Missing parameter: collection'; private const ERR_MISSING_DATA = 'Missing parameter: data'; private const ERR_MISSING_SOURCES = 'Missing parameter: sources'; private const ERR_MISSING_TARGET = 'Missing parameter: target'; private const ERR_MISSING_IDENTIFIERS = 'Missing parameter: identifiers'; private const ERR_INVALID_OPERATION = 'Invalid operation: '; private const ERR_INVALID_PROVIDER = 'Invalid parameter: provider must be a string'; private const ERR_INVALID_SERVICE = 'Invalid parameter: service must be a string'; private const ERR_INVALID_IDENTIFIER = 'Invalid parameter: identifier must be a string'; private const ERR_INVALID_COLLECTION = 'Invalid parameter: collection must be a string or integer'; private const ERR_INVALID_SOURCES = 'Invalid parameter: sources must be an array'; private const ERR_INVALID_TARGET = 'Invalid parameter: target must be an array'; private const ERR_INVALID_IDENTIFIERS = 'Invalid parameter: identifiers must be an array'; private const ERR_INVALID_DATA = 'Invalid parameter: data must be an array'; private const STREAM_FLUSH_INTERVAL = 1; public function __construct( private readonly SessionTenant $tenantIdentity, private readonly SessionIdentity $userIdentity, private Manager $mailManager, private readonly LoggerInterface $logger ) {} /** * Main API endpoint for mail operations * * Single operation: * { * "version": 1, * "transaction": "tx-1", * "operation": "entity.create", * "data": {...} * } * * @return Response */ #[AuthenticatedRoute('/v1', name: 'mail.manager.v1', methods: ['POST'])] public function index( int $version, string $transaction, string|null $operation = null, array|null $data = null, string|null $user = null ): Response { // authorize request $tenantId = $this->tenantIdentity->identifier(); $userId = $this->userIdentity->identifier(); try { if ($operation !== null) { $result = $this->processOperation($tenantId, $userId, $operation, $data ?? [], $version, $transaction); if ($result instanceof Response) { return $result; } return new JsonResponse([ 'version' => $version, 'transaction' => $transaction, 'operation' => $operation, 'status' => 'success', 'data' => $result ], JsonResponse::HTTP_OK); } throw new InvalidArgumentException('Operation must be provided'); } catch (Throwable $t) { $this->logger->error('Error processing request', ['exception' => $t]); return new JsonResponse([ 'version' => $version, 'transaction' => $transaction, 'operation' => $operation, 'status' => 'error', 'data' => [ 'code' => $t->getCode(), 'message' => $t->getMessage() ] ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); } } /** * Process a single operation */ private function processOperation(string $tenantId, string $userId, string $operation, array $data, int $version = 1, string $transaction = ''): mixed { return match ($operation) { // Provider operations 'provider.list' => $this->providerList($tenantId, $userId, $data), 'provider.fetch' => $this->providerFetch($tenantId, $userId, $data), 'provider.extant' => $this->providerExtant($tenantId, $userId, $data), // Service operations 'service.list' => $this->serviceList($tenantId, $userId, $data), 'service.fetch' => $this->serviceFetch($tenantId, $userId, $data), 'service.extant' => $this->serviceExtant($tenantId, $userId, $data), 'service.create' => $this->serviceCreate($tenantId, $userId, $data), 'service.update' => $this->serviceUpdate($tenantId, $userId, $data), 'service.delete' => $this->serviceDelete($tenantId, $userId, $data), 'service.discover' => $this->serviceDiscover($tenantId, $userId, $data, $version, $transaction), 'service.test' => $this->serviceTest($tenantId, $userId, $data), // Collection operations 'collection.list' => $this->collectionList($tenantId, $userId, $data), 'collection.fetch' => $this->collectionFetch($tenantId, $userId, $data), 'collection.extant' => $this->collectionExtant($tenantId, $userId, $data), 'collection.create' => $this->collectionCreate($tenantId, $userId, $data), 'collection.update' => $this->collectionUpdate($tenantId, $userId, $data), 'collection.delete' => $this->collectionDelete($tenantId, $userId, $data), 'collection.delta' => throw new InvalidArgumentException('Operation not implemented: ' . $operation), 'collection.move' => throw new InvalidArgumentException('Operation not implemented: ' . $operation), // Entity operations 'entity.list' => $this->entityList($tenantId, $userId, $data), 'entity.fetch' => $this->entityFetch($tenantId, $userId, $data), 'entity.extant' => $this->entityExtant($tenantId, $userId, $data), 'entity.create' => throw new InvalidArgumentException('Operation not implemented: ' . $operation), 'entity.update' => throw new InvalidArgumentException('Operation not implemented: ' . $operation), 'entity.delete' => throw new InvalidArgumentException('Operation not implemented: ' . $operation), 'entity.stream' => $this->entityStream($tenantId, $userId, $data, $version, $transaction), 'entity.delta' => $this->entityDelta($tenantId, $userId, $data), 'entity.move' => $this->entityMove($tenantId, $userId, $data), 'entity.copy' => throw new InvalidArgumentException('Operation not implemented: ' . $operation), 'entity.transmit' => $this->entityTransmit($tenantId, $userId, $data), default => throw new InvalidArgumentException(self::ERR_INVALID_OPERATION . $operation) }; } // ==================== Provider Operations ==================== private function providerList(string $tenantId, string $userId, array $data): mixed { $sources = null; if (isset($data['sources']) && is_array($data['sources'])) { $sources = new SourceSelector(); $sources->jsonDeserialize($data['sources']); } return $this->mailManager->providerList($tenantId, $userId, $sources); } private function providerFetch(string $tenantId, string $userId, array $data): mixed { if (!isset($data['identifier'])) { throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER); } if (!is_string($data['identifier'])) { throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER); } return $this->mailManager->providerFetch($tenantId, $userId, $data['identifier']); } private function providerExtant(string $tenantId, string $userId, array $data): mixed { if (!isset($data['sources'])) { throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); } if (!is_array($data['sources'])) { throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); } $sources = new SourceSelector(); $sources->jsonDeserialize($data['sources']); return $this->mailManager->providerExtant($tenantId, $userId, $sources); } // ==================== Service Operations ===================== private function serviceList(string $tenantId, string $userId, array $data): mixed { $sources = null; if (isset($data['sources']) && is_array($data['sources'])) { $sources = new SourceSelector(); $sources->jsonDeserialize($data['sources']); } return $this->mailManager->serviceList($tenantId, $userId, $sources); } private function serviceFetch(string $tenantId, string $userId, array $data): mixed { if (!isset($data['provider'])) { throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); } if (!is_string($data['provider'])) { throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); } if (!isset($data['identifier'])) { throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER); } if (!is_string($data['identifier'])) { throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER); } return $this->mailManager->serviceFetch($tenantId, $userId, $data['provider'], $data['identifier']); } private function serviceExtant(string $tenantId, string $userId, array $data): mixed { if (!isset($data['sources'])) { throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); } if (!is_array($data['sources'])) { throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); } $sources = new SourceSelector(); $sources->jsonDeserialize($data['sources']); return $this->mailManager->serviceExtant($tenantId, $userId, $sources); } private function serviceCreate(string $tenantId, string $userId, array $data): mixed { if (!isset($data['provider'])) { throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); } if (!is_string($data['provider'])) { throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); } if (!isset($data['data'])) { throw new InvalidArgumentException(self::ERR_MISSING_DATA); } if (!is_array($data['data'])) { throw new InvalidArgumentException(self::ERR_INVALID_DATA); } return $this->mailManager->serviceCreate( $tenantId, $userId, $data['provider'], $data['data'] ); } private function serviceUpdate(string $tenantId, string $userId, array $data): mixed { if (!isset($data['provider'])) { throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); } if (!is_string($data['provider'])) { throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); } if (!isset($data['identifier'])) { throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER); } if (!is_string($data['identifier'])) { throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER); } if (!isset($data['data'])) { throw new InvalidArgumentException(self::ERR_MISSING_DATA); } if (!is_array($data['data'])) { throw new InvalidArgumentException(self::ERR_INVALID_DATA); } return $this->mailManager->serviceUpdate( $tenantId, $userId, $data['provider'], $data['identifier'], $data['data'] ); } private function serviceDelete(string $tenantId, string $userId, array $data): mixed { if (!isset($data['provider'])) { throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); } if (!is_string($data['provider'])) { throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); } if (!isset($data['identifier'])) { throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER); } if (!is_string($data['identifier'])) { throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER); } return $this->mailManager->serviceDelete( $tenantId, $userId, $data['provider'], $data['identifier'] ); } private function serviceTest(string $tenantId, string $userId, array $data): mixed { if (!isset($data['provider'])) { throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); } if (!is_string($data['provider'])) { throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); } if (!isset($data['identifier']) && !isset($data['location']) && !isset($data['identity'])) { throw new InvalidArgumentException('Either a service identifier or location and identity must be provided for service test'); } return $this->mailManager->serviceTest( $tenantId, $userId, $data['provider'], $data['identifier'] ?? null, $data['location'] ?? null, $data['identity'] ?? null, ); } private function serviceDiscover(string $tenantId, string $userId, array $data, int $version, string $transaction): StreamedNdJsonResponse { if (!isset($data['identity']) || empty($data['identity']) || !is_string($data['identity'])) { throw new InvalidArgumentException(self::ERR_INVALID_DATA); } $provider = $data['provider'] ?? null; $identity = $data['identity']; $location = $data['location'] ?? null; $secret = $data['secret'] ?? null; $discoverGenerator = $this->mailManager->serviceDiscover($tenantId, $userId, $provider, $identity, $location, $secret); $logger = $this->logger; $response = (function () use ($discoverGenerator, $version, $transaction, $logger): \Generator { yield ['type' => 'control', 'status' => 'start', 'version' => $version, 'transaction' => $transaction]; $total = 0; try { foreach ($discoverGenerator as $providerId => $serviceLocation) { if (!$serviceLocation instanceof ResourceServiceLocationInterface) { continue; } yield [ 'type' => 'data', 'data' => [ 'provider' => $providerId, 'location' => $serviceLocation->jsonSerialize() ] ]; $total++; } } catch (\Throwable $t) { $logger->error('Error streaming service discovery', ['exception' => $t]); yield ['type' => 'error', 'message' => $t->getMessage()]; return; } yield ['type' => 'control', 'status' => 'end', 'total' => $total]; })(); return new StreamedNdJsonResponse($response, 1, 200, ['Content-Type' => 'application/json']); } // ==================== Collection Operations ==================== private function collectionList(string $tenantId, string $userId, array $data): mixed { $sources = null; if (isset($data['sources']) && is_array($data['sources'])) { $sources = new SourceSelector(); $sources->jsonDeserialize($data['sources']); } $filter = $data['filter'] ?? null; $sort = $data['sort'] ?? null; return $this->mailManager->collectionList($tenantId, $userId, $sources, $filter, $sort); } private function collectionExtant(string $tenantId, string $userId, array $data): mixed { if (!isset($data['sources'])) { throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); } if (!is_array($data['sources'])) { throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); } $sources = new SourceSelector(); $sources->jsonDeserialize($data['sources']); return $this->mailManager->collectionExtant($tenantId, $userId, $sources); } private function collectionFetch(string $tenantId, string $userId, array $data): mixed { if (!isset($data['provider'])) { throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); } if (!is_string($data['provider'])) { throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); } if (!isset($data['service'])) { throw new InvalidArgumentException(self::ERR_MISSING_SERVICE); } if (!is_string($data['service'])) { throw new InvalidArgumentException(self::ERR_INVALID_SERVICE); } if (!isset($data['identifier'])) { throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER); } if (!is_string($data['identifier']) && !is_int($data['identifier'])) { throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION); } return $this->mailManager->collectionFetch( $tenantId, $userId, $data['provider'], $data['service'], $data['identifier'] ); } private function collectionCreate(string $tenantId, string $userId, array $data): mixed { if (!isset($data['provider'])) { throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); } if (!is_string($data['provider'])) { throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); } if (!isset($data['service'])) { throw new InvalidArgumentException(self::ERR_MISSING_SERVICE); } if (!is_string($data['service'])) { throw new InvalidArgumentException(self::ERR_INVALID_SERVICE); } if (isset($data['collection']) && !is_string($data['collection']) && !is_int($data['collection'])) { throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION); } if (!isset($data['properties'])) { throw new InvalidArgumentException(self::ERR_MISSING_DATA); } if (!is_array($data['properties'])) { throw new InvalidArgumentException(self::ERR_INVALID_DATA); } return $this->mailManager->collectionCreate( $tenantId, $userId, $data['provider'], $data['service'], $data['collection'] ?? null, $data['properties'] ); } private function collectionUpdate(string $tenantId, string $userId, array $data): mixed { if (!isset($data['provider'])) { throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); } if (!is_string($data['provider'])) { throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); } if (!isset($data['service'])) { throw new InvalidArgumentException(self::ERR_MISSING_SERVICE); } if (!is_string($data['service'])) { throw new InvalidArgumentException(self::ERR_INVALID_SERVICE); } if (!isset($data['identifier'])) { throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER); } if (!is_string($data['identifier']) && !is_int($data['identifier'])) { throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION); } if (!isset($data['properties'])) { throw new InvalidArgumentException(self::ERR_MISSING_DATA); } if (!is_array($data['properties'])) { throw new InvalidArgumentException(self::ERR_INVALID_DATA); } return $this->mailManager->collectionUpdate( $tenantId, $userId, $data['provider'], $data['service'], $data['identifier'], $data['properties'] ); } private function collectionDelete(string $tenantId, string $userId, array $data): mixed { if (!isset($data['provider'])) { throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); } if (!is_string($data['provider'])) { throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); } if (!isset($data['service'])) { throw new InvalidArgumentException(self::ERR_MISSING_SERVICE); } if (!is_string($data['service'])) { throw new InvalidArgumentException(self::ERR_INVALID_SERVICE); } if (!isset($data['identifier'])) { throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIER); } if (!is_string($data['identifier']) && !is_int($data['identifier'])) { throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIER); } return $this->mailManager->collectionDelete( $tenantId, $userId, $data['provider'], $data['service'], $data['identifier'], $data['options'] ?? [] ); } // ==================== Entity Operations ==================== private function entityList(string $tenantId, string $userId, array $data): mixed { if (!isset($data['sources'])) { throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); } if (!is_array($data['sources'])) { throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); } $sources = new SourceSelector(); $sources->jsonDeserialize($data['sources']); $filter = $data['filter'] ?? null; $sort = $data['sort'] ?? null; $range = $data['range'] ?? null; return $this->mailManager->entityList($tenantId, $userId, $sources, $filter, $sort, $range); } private function entityFetch(string $tenantId, string $userId, array $data): mixed { if (!isset($data['provider'])) { throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); } if (!is_string($data['provider'])) { throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); } if (!isset($data['service'])) { throw new InvalidArgumentException(self::ERR_MISSING_SERVICE); } if (!is_string($data['service'])) { throw new InvalidArgumentException(self::ERR_INVALID_SERVICE); } if (!isset($data['collection'])) { throw new InvalidArgumentException(self::ERR_MISSING_COLLECTION); } if (!is_string($data['collection']) && !is_int($data['collection'])) { throw new InvalidArgumentException(self::ERR_INVALID_COLLECTION); } if (!isset($data['identifiers'])) { throw new InvalidArgumentException(self::ERR_MISSING_IDENTIFIERS); } if (!is_array($data['identifiers'])) { throw new InvalidArgumentException(self::ERR_INVALID_IDENTIFIERS); } return $this->mailManager->entityFetch( $tenantId, $userId, $data['provider'], $data['service'], $data['collection'], $data['identifiers'] ); } private function entityExtant(string $tenantId, string $userId, array $data): mixed { if (!isset($data['sources'])) { throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); } if (!is_array($data['sources'])) { throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); } $sources = new SourceSelector(); $sources->jsonDeserialize($data['sources']); return $this->mailManager->entityExtant($tenantId, $userId, $sources); } private function entityDelta(string $tenantId, string $userId, array $data): mixed { if (!isset($data['sources'])) { throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); } if (!is_array($data['sources'])) { throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); } $sources = new SourceSelector(); $sources->jsonDeserialize($data['sources']); return $this->mailManager->entityDelta($tenantId, $userId, $sources); } private function entityMove(string $tenantId, string $userId, array $data): mixed { if (!isset($data['target'])) { throw new InvalidArgumentException(self::ERR_MISSING_TARGET); } if (!is_string($data['target'])) { throw new InvalidArgumentException(self::ERR_INVALID_TARGET); } if (!isset($data['sources'])) { throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); } if (!is_array($data['sources'])) { throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); } $target = ResourceIdentifier::fromString($data['target']); if (!$target instanceof CollectionIdentifier) { throw new InvalidArgumentException('Invalid parameter: target must be provider:service:collection'); } $sources = ResourceIdentifiers::fromArray($data['sources']); foreach ($sources as $source) { if (!$source instanceof EntityIdentifier) { throw new InvalidArgumentException('Invalid parameter: sources must contain provider:service:collection:entity identifiers'); } } return $this->mailManager->entityMove($tenantId, $userId, $target, $sources); } private function entityTransmit(string $tenantId, string $userId, array $data): mixed { if (!isset($data['provider'])) { throw new InvalidArgumentException(self::ERR_MISSING_PROVIDER); } if (!is_string($data['provider'])) { throw new InvalidArgumentException(self::ERR_INVALID_PROVIDER); } if (!isset($data['service'])) { throw new InvalidArgumentException(self::ERR_MISSING_SERVICE); } if (!is_string($data['service'])) { throw new InvalidArgumentException(self::ERR_INVALID_SERVICE); } $jobId = $this->mailManager->entityTransmit( $tenantId, $userId, $data['provider'], $data['service'], $data['data'] ); return ['jobId' => $jobId]; } private function entityStream(string $tenantId, string $userId, array $data, int $version, string $transaction): StreamedNdJsonResponse { if (!isset($data['sources'])) { throw new InvalidArgumentException(self::ERR_MISSING_SOURCES); } if (!is_array($data['sources'])) { throw new InvalidArgumentException(self::ERR_INVALID_SOURCES); } $sources = new SourceSelector(); $sources->jsonDeserialize($data['sources']); $filter = $data['filter'] ?? null; $sort = $data['sort'] ?? null; $range = $data['range'] ?? null; $entityGenerator = $this->mailManager->entityStream($tenantId, $userId, $sources, $filter, $sort, $range); $logger = $this->logger; $responseGenerator = (function () use ($entityGenerator, $version, $transaction, $logger): \Generator { yield ['type' => 'control', 'status' => 'start', 'version' => $version, 'transaction' => $transaction]; $total = 0; try { foreach ($entityGenerator as $entity) { if (!$entity instanceof JsonSerializable) { continue; } yield [ 'type' => 'data', 'data' => $entity->jsonSerialize() ]; $total++; } } catch (\Throwable $t) { $logger->error('Error streaming entities', ['exception' => $t]); yield ['type' => 'error', 'message' => $t->getMessage()]; return; } yield ['type' => 'control', 'status' => 'end', 'total' => $total]; })(); return new StreamedNdJsonResponse($responseGenerator, 1, 200, ['Content-Type' => 'application/json']); } }