1 Commits

Author SHA1 Message Date
Sebastian 791825b318 chore(deps): update dependency phpunit/phpunit to v12.5.32
Build Test / test (pull_request) Successful in 37s
JS Unit Tests / test (pull_request) Successful in 32s
PHP Unit Tests / test (pull_request) Successful in 2m14s
PHP Integration Tests / Integration Tests (pull_request) Failing after 2m28s
2026-07-28 03:02:48 +00:00
14 changed files with 269 additions and 1029 deletions
Generated
+7 -7
View File
@@ -1442,16 +1442,16 @@
},
{
"name": "phpunit/phpunit",
"version": "12.5.31",
"version": "12.5.32",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "0608d157a284f15cc73b99a3327eff06b66a176d"
"reference": "c02591dd7840ed124a98d7770753329ad28e9f8f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/0608d157a284f15cc73b99a3327eff06b66a176d",
"reference": "0608d157a284f15cc73b99a3327eff06b66a176d",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/c02591dd7840ed124a98d7770753329ad28e9f8f",
"reference": "c02591dd7840ed124a98d7770753329ad28e9f8f",
"shasum": ""
},
"require": {
@@ -1520,7 +1520,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
"source": "https://github.com/sebastianbergmann/phpunit/tree/12.5.31"
"source": "https://github.com/sebastianbergmann/phpunit/tree/12.5.32"
},
"funding": [
{
@@ -1528,7 +1528,7 @@
"type": "other"
}
],
"time": "2026-07-06T14:54:16+00:00"
"time": "2026-07-25T06:54:13+00:00"
},
{
"name": "sebastian/cli-parser",
@@ -2556,5 +2556,5 @@
"platform-overrides": {
"php": "8.3"
},
"plugin-api-version": "2.6.0"
"plugin-api-version": "2.9.0"
}
-27
View File
@@ -1,27 +0,0 @@
<?php
declare(strict_types=1);
namespace KTXM\ProviderJmapc\Listeners;
use KTXC\User\Event\UserCreatedEvent;
use KTXC\User\Event\UserDeletingEvent;
use KTXM\ProviderJmapc\Stores\ServiceStore;
final class UserEventListener
{
public function __construct(
private readonly ServiceStore $serviceStore,
) {
}
public function onUserCreated(UserCreatedEvent $event): void
{
// TODO: implement provisioning configuration
}
public function onUserDeleting(UserDeletingEvent $event): void
{
$this->serviceStore->deleteByUser($event->tenantIdentifier(), $event->userIdentifier());
}
}
+12 -17
View File
@@ -10,15 +10,9 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc;
use KTXC\Resource\ProviderManager;
use KTXC\User\Event\UserCreatedEvent;
use KTXC\User\Event\UserDeletingEvent;
use KTXF\Event\DeliveryMode;
use KTXF\Event\EventListenerRegistrarInterface;
use KTXF\Module\Configuration\BrowserModuleContextInterface;
use KTXF\Module\Configuration\ModuleContextInterface;
use KTXF\Module\ModuleBrowserInterface;
use KTXF\Module\ModuleInstanceAbstract;
use KTXF\Resource\Provider\ProviderInterface;
use KTXM\ProviderJmapc\Listeners\UserEventListener;
use KTXM\ProviderJmapc\Providers\Mail\Provider as MailProvider;
use KTXM\ProviderJmapc\Providers\Chrono\Provider as ChronoProvider;
use KTXM\ProviderJmapc\Providers\People\Provider as PeopleProvider;
@@ -29,11 +23,10 @@ use KTXM\ProviderJmapc\Providers\Document\Provider as DocumentProvider;
*
* Provides mail, calendar, and contacts services via JMAP protocol.
*/
class Module extends ModuleInstanceAbstract
class Module extends ModuleInstanceAbstract implements ModuleBrowserInterface
{
public function __construct(
private readonly ProviderManager $providerManager,
private readonly EventListenerRegistrarInterface $events,
) {}
public function handle(): string
@@ -74,9 +67,6 @@ class Module extends ModuleInstanceAbstract
public function boot(): void
{
// Register listeners
$this->events->listen($this->handle(), UserCreatedEvent::class, UserEventListener::class, 'onUserCreated', DeliveryMode::Deferred);
$this->events->listen($this->handle(), UserDeletingEvent::class, UserEventListener::class, 'onUserDeleting', DeliveryMode::Deferred);
// Register JMAP providers - all three share the same service store
$this->providerManager->register(ProviderInterface::TYPE_MAIL, 'jmap', MailProvider::class);
//$this->providerManager->register(ProviderInterface::TYPE_CHRONO, 'jmap', ChronoProvider::class);
@@ -84,10 +74,15 @@ class Module extends ModuleInstanceAbstract
$this->providerManager->register(ProviderInterface::TYPE_DOCUMENT, 'jmap', DocumentProvider::class);
}
public function configure(ModuleContextInterface $context): void
{
if ($context instanceof BrowserModuleContextInterface) {
$context->registerModule($this, 'ProviderJmapc', 'static/module.mjs');
}
public function registerBI(): array {
return [
'handle' => $this->handle(),
'namespace' => 'ProviderJmapc',
'version' => $this->version(),
'label' => $this->label(),
'author' => $this->author(),
'description' => $this->description(),
'boot' => 'static/module.mjs',
];
}
}
+16 -8
View File
@@ -23,16 +23,24 @@ class EntityProperties extends EntityPropertiesMutableAbstract {
*/
public function fromJmap(array $parameters): static {
if (isset($parameters['size'])) {
$this->data[self::PROPERTY_SIZE] = (int) $parameters['size'];
if (isset($data['size'])) {
$this->data[self::PROPERTY_SIZE] = (int) $data['size'];
}
if (isset($data['label'])) {
$this->data[self::PROPERTY_LABEL] = (string) $data['name'];
}
if (isset($parameters['name'])) {
$this->data[self::PROPERTY_LABEL] = (string) $parameters['name'];
if (isset($data['mime'])) {
$this->data[self::PROPERTY_MIME] = (string) $data['type'];
}
if (isset($parameters['type'])) {
$this->data[self::PROPERTY_MIME] = (string) $parameters['type'];
if (isset($data['format'])) {
$this->data[self::PROPERTY_FORMAT] = null;
}
if (isset($data['encoding'])) {
$this->data[self::PROPERTY_ENCODING] = null;
}
return $this;
@@ -44,8 +52,8 @@ class EntityProperties extends EntityPropertiesMutableAbstract {
public function toJmap(): array {
$parameters = array_filter([
'name' => $this->data[self::PROPERTY_LABEL] ?? null,
'type' => $this->data[self::PROPERTY_MIME] ?? null
'name' => $this->data[self::PROPERTY_LABEL],
'type' => $this->data[self::PROPERTY_MIME] ?? 'application/octet-stream'
], static fn($value) => $value !== null);
return $parameters;
@@ -45,6 +45,7 @@ class EntityResource extends EntityMutableAbstract {
if (isset($parameters['modified'])) {
$this->data['modified'] = $parameters['modified'];
}
if (isset($parameters['accessed']))
$this->getProperties()->fromJmap($parameters);
+4 -335
View File
@@ -10,34 +10,22 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc\Providers\Document;
use Generator;
use KTXF\Blob\Signature;
use KTXF\Documents\Collection\CollectionBaseInterface;
use KTXF\Documents\Collection\CollectionMutableInterface;
use KTXF\Documents\Collection\CollectionPropertiesBaseInterface;
use KTXF\Documents\Entity\EntityBaseInterface;
use KTXF\Documents\Entity\EntityMutableInterface;
use KTXF\Documents\Entity\EntityPropertiesMutableInterface;
use KTXF\Documents\Service\ServiceBaseInterface;
use KTXF\Documents\Service\ServiceCollectionMutableInterface;
use KTXF\Documents\Service\ServiceConfigurableInterface;
use KTXF\Documents\Service\ServiceEntityMutableInterface;
use KTXF\Documents\Service\ServiceMutableInterface;
use KTXF\Documents\Service\ServiceNodeListInterface;
use KTXF\Resource\Delta\Delta;
use KTXF\Resource\Exceptions\InvalidParameterException;
use KTXF\Resource\Exceptions\UnsupportedException;
use KTXF\Resource\Filter\Filter;
use KTXF\Resource\Filter\IFilter;
use KTXF\Resource\Identifier\CollectionIdentifier;
use KTXF\Resource\Identifier\CollectionIdentifierInterface;
use KTXF\Resource\Identifier\EntityIdentifier;
use KTXF\Resource\Identifier\EntityIdentifierInterface;
use KTXF\Resource\Provider\ResourceServiceIdentityInterface;
use KTXF\Resource\Provider\ResourceServiceLocationInterface;
use KTXF\Resource\Range\IRange;
use KTXF\Resource\Range\Range;
use KTXF\Resource\Range\RangeAnchorType;
use KTXF\Resource\Range\RangeTally;
use KTXF\Resource\Range\RangeType;
use KTXF\Resource\Sort\ISort;
use KTXF\Resource\Sort\Sort;
@@ -46,7 +34,7 @@ use KTXM\ProviderJmapc\Providers\ServiceLocation;
use KTXM\ProviderJmapc\Service\Remote\RemoteFilesService;
use KTXM\ProviderJmapc\Service\Remote\RemoteService;
class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceConfigurableInterface, ServiceCollectionMutableInterface, ServiceEntityMutableInterface, ServiceNodeListInterface
class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceConfigurableInterface, ServiceCollectionMutableInterface
{
public const JSON_TYPE = ServiceBaseInterface::JSON_TYPE;
@@ -88,29 +76,6 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
self::CAPABILITY_ENTITY_DELTA => true,
self::CAPABILITY_ENTITY_EXTANT => true,
self::CAPABILITY_ENTITY_FETCH => true,
self::CAPABILITY_ENTITY_READ => true,
self::CAPABILITY_ENTITY_CREATE => true,
self::CAPABILITY_ENTITY_MODIFY => true,
self::CAPABILITY_ENTITY_DELETE => true,
self::CAPABILITY_ENTITY_MOVE => true,
self::CAPABILITY_ENTITY_COPY => true,
self::CAPABILITY_ENTITY_WRITE => true,
self::CAPABILITY_NODE_LIST => true,
self::CAPABILITY_NODE_LIST_FILTER => [
self::CAPABILITY_NODE_FILTER_LABEL => 's:100:256:256',
],
self::CAPABILITY_NODE_LIST_SORT => [
self::CAPABILITY_NODE_SORT_LABEL,
self::CAPABILITY_NODE_SORT_SIZE,
self::CAPABILITY_NODE_SORT_CREATED_ON,
self::CAPABILITY_NODE_SORT_MODIFIED_ON,
],
self::CAPABILITY_NODE_LIST_RANGE => [
self::CAPABILITY_NODE_RANGE_TALLY => [
self::CAPABILITY_NODE_RANGE_TALLY_ABSOLUTE,
self::CAPABILITY_NODE_RANGE_TALLY_RELATIVE,
],
],
];
private readonly RemoteFilesService $remoteService;
@@ -519,315 +484,19 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
yield from $this->entityFetchBulk(...$identifiers);
}
public function entityFresh(): EntityMutableInterface
{
return new EntityResource(provider: $this->provider(), service: $this->identifier());
}
/**
* Convert incoming entity properties into a native EntityResource
*/
private function entityNative(EntityPropertiesMutableInterface $properties, string|int|null $identifier = null): EntityResource
{
if ($properties instanceof EntityResource) {
return clone $properties;
}
$object = new EntityResource(provider: $this->provider(), service: $this->identifier());
$object->jsonDeserialize(array_filter([
EntityResource::PROPERTY_IDENTIFIER => $identifier,
EntityResource::PROPERTY_PROPERTIES => $properties->jsonSerialize(),
], fn($v) => $v !== null));
return $object;
}
/**
* Retrieve the remote parameters of an entity
*/
private function entityRemote(EntityIdentifierInterface $target): ?array
{
$this->initialize();
$identifier = (string)$target->entity();
$entity = $this->remoteService->entityFetch($identifier)[$identifier] ?? null;
// folders are not entities
if (!is_array($entity) || empty($entity['blobId'])) {
return null;
}
return $entity;
}
public function entityCreate(CollectionIdentifierInterface $target, EntityPropertiesMutableInterface $properties, array $options = []): EntityBaseInterface
{
$this->initialize();
$entity = $this->entityNative($properties)->toJmap();
$entity['type'] ??= 'application/octet-stream';
// a file node must reference a blob, so start with empty content until it is written
$content = '';
$blob = $this->remoteService->blobUpload($entity['type'], $content);
$entity['blobId'] = $blob['blobId'];
$entity = $this->remoteService->entityCreate((string)$target->collection(), $entity);
if ($entity === null) {
throw new \RuntimeException("Failed to create entity in collection: {$target->collection()}");
}
$object = new EntityResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($entity);
return $object;
}
public function entityModify(EntityIdentifierInterface $target, EntityPropertiesMutableInterface $properties): EntityBaseInterface
{
$this->initialize();
$identifier = (string)$target->entity();
$entity = $this->entityNative($properties, $identifier)->toJmap();
if ($this->remoteService->entityModify($identifier, $entity) === null) {
throw new \RuntimeException("Failed to modify entity: $identifier");
}
$object = new EntityResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($this->entityRemote($target) ?? $entity);
return $object;
}
public function entityDelete(EntityIdentifierInterface ...$targets): array
{
$this->initialize();
$results = [];
foreach ($targets as $target) {
$key = (string)$target;
try {
$deleted = $this->remoteService->entityDelete((string)$target->entity()) !== null;
} catch (\Throwable) {
$deleted = false;
}
$results[$key] = ['disposition' => $deleted ? 'deleted' : 'error', 'destination' => null, 'mutation' => $target];
}
return $results;
}
public function entityMove(CollectionIdentifierInterface $target, EntityIdentifierInterface ...$sources): array
{
return $this->entityRelocate($target, true, ...$sources);
}
public function entityCopy(CollectionIdentifierInterface $target, EntityIdentifierInterface ...$sources): array
{
return $this->entityRelocate($target, false, ...$sources);
}
/**
* Relocate (move or copy) entities into a target collection
*
* @return array<string, array{disposition: string, destination: ?CollectionIdentifierInterface, mutation: EntityIdentifierInterface}>
*/
private function entityRelocate(CollectionIdentifierInterface $target, bool $remove, EntityIdentifierInterface ...$sources): array
{
$this->initialize();
$results = [];
$collection = (string)$target->collection();
foreach ($sources as $source) {
$key = (string)$source;
try {
$entity = $remove
? $this->remoteService->entityMove($collection, (string)$source->entity())
: $this->remoteService->entityCopy($collection, (string)$source->entity());
} catch (\Throwable) {
$entity = null;
}
if ($entity === null) {
$results[$key] = ['disposition' => 'error', 'destination' => null, 'mutation' => $source];
continue;
}
$results[$key] = [
'disposition' => $remove ? 'moved' : 'copied',
'destination' => new CollectionIdentifier($this->provider(), $this->identifier(), $collection),
'mutation' => new EntityIdentifier($this->provider(), $this->identifier(), $collection, (string)$entity['id']),
];
}
return $results;
}
public function entityRead(EntityIdentifierInterface $target): ?string
{
$entity = $this->entityRemote($target);
if ($entity === null) {
return null;
}
return $this->remoteService->blobDownload($entity['blobId'], $entity['type'] ?? 'application/octet-stream');
return null;
}
public function entityReadStream(EntityIdentifierInterface $target)
{
$entity = $this->entityRemote($target);
if ($entity === null) {
return null;
}
return $this->remoteService->blobDownloadStream($entity['blobId'], $entity['type'] ?? 'application/octet-stream');
return null;
}
public function entityReadChunk(EntityIdentifierInterface $target, int $offset, int $length): ?string
{
$content = $this->entityRead($target);
if ($content === null) {
return null;
}
return substr($content, $offset, $length);
}
public function entityWrite(EntityIdentifierInterface $target, string $data): int
{
$entity = $this->entityRemote($target);
$identifier = (string)$target->entity();
if ($entity === null) {
throw new InvalidParameterException("Entity not found: $identifier");
}
// blobs are immutable, so content is replaced by pointing the node at a new blob
$type = $entity['type'] ?? null;
if (empty($type) || $type === 'application/octet-stream') {
$type = Signature::detect(substr($data, 0, Signature::SAMPLE_SIZE), $data)['mime'];
}
$blob = $this->remoteService->blobUpload($type, $data);
if ($this->remoteService->entityModify($identifier, ['blobId' => $blob['blobId'], 'type' => $type]) === null) {
throw new \RuntimeException("Failed to write to entity: $identifier");
}
return strlen($data);
}
public function entityWriteChunk(EntityIdentifierInterface $target, int $offset, string $data): int
{
if ($offset === 0) {
$content = $data;
} else {
// blobs can not be partially updated, so the chunk is merged into the current content
$content = $this->entityRead($target);
if ($content === null) {
throw new InvalidParameterException("Entity not found: {$target->entity()}");
}
$content = substr(str_pad($content, $offset, "\0"), 0, $offset) . $data . substr($content, $offset + strlen($data));
}
$this->entityWrite($target, $content);
return strlen($data);
}
public function entityWriteStream(EntityIdentifierInterface $target)
{
throw new UnsupportedException('Streamed writes are not supported by JMAP file storage');
}
// Node operations (unified collections + entities)
public function nodeList(string|int|null $location, ?IFilter $filter = null, ?ISort $sort = null, ?IRange $range = null): Generator
{
$this->initialize();
$result = $this->remoteService->nodeList($location !== null ? (string)$location : null);
// convert and filter, keeping folders and files apart so folders always come first
$label = null;
if ($filter !== null && isset($filter->conditions()[self::CAPABILITY_NODE_FILTER_LABEL])) {
$label = (string)$filter->conditions()[self::CAPABILITY_NODE_FILTER_LABEL]['value'];
}
$collections = [];
$entities = [];
foreach ($result['list'] as $index => $entry) {
unset($result['list'][$index]);
if (!is_array($entry) || !isset($entry['id'])) {
continue;
}
// folders carry no blob
$object = empty($entry['blobId'])
? new CollectionResource(provider: $this->provider(), service: $this->identifier())
: new EntityResource(provider: $this->provider(), service: $this->identifier());
$object->fromJmap($entry);
if ($label !== null && $label !== '' && mb_stripos($object->getProperties()->getLabel(), $label) === false) {
continue;
}
if ($object instanceof CollectionResource) {
$collections[] = $object;
} else {
$entities[] = $object;
}
}
// sort each group, defaulting to label ascending
$conditions = $sort?->conditions() ?? [];
if ($conditions === []) {
$conditions = [['attribute' => self::CAPABILITY_NODE_SORT_LABEL, 'direction' => true]];
}
$comparator = function (CollectionResource|EntityResource $a, CollectionResource|EntityResource $b) use ($conditions): int {
foreach ($conditions as $condition) {
$order = match ($condition['attribute']) {
self::CAPABILITY_NODE_SORT_LABEL => strnatcasecmp($a->getProperties()->getLabel(), $b->getProperties()->getLabel()),
self::CAPABILITY_NODE_SORT_SIZE => $this->nodeSize($a) <=> $this->nodeSize($b),
self::CAPABILITY_NODE_SORT_CREATED_ON => ($a->created()?->getTimestamp() ?? 0) <=> ($b->created()?->getTimestamp() ?? 0),
self::CAPABILITY_NODE_SORT_MODIFIED_ON => ($a->modified()?->getTimestamp() ?? 0) <=> ($b->modified()?->getTimestamp() ?? 0),
default => 0,
};
if ($order !== 0) {
return $condition['direction'] ? $order : -$order;
}
}
return strnatcasecmp($a->getProperties()->getLabel(), $b->getProperties()->getLabel());
};
usort($collections, $comparator);
usort($entities, $comparator);
$nodes = array_merge($collections, $entities);
unset($collections, $entities);
// apply range
if ($range instanceof RangeTally) {
$offset = 0;
if ($range->getAnchor() === RangeAnchorType::RELATIVE) {
// relative ranges start after the anchor node
foreach ($nodes as $index => $node) {
if ((string)$node->identifier() === (string)$range->getPosition()) {
$offset = $index + 1;
break;
}
}
} else {
$offset = max(0, (int)$range->getPosition());
}
$nodes = array_slice($nodes, $offset, $range->getTally());
}
foreach ($nodes as $index => $node) {
unset($nodes[$index]);
yield $node->identifier() => $node;
}
}
public function nodeListFilter(): IFilter
{
return new Filter($this->serviceAbilities[self::CAPABILITY_NODE_LIST_FILTER] ?? []);
}
public function nodeListSort(): ISort
{
// sort attributes are matched by key
return new Sort(array_fill_keys($this->serviceAbilities[self::CAPABILITY_NODE_LIST_SORT] ?? [], true));
}
public function nodeListRange(RangeType $type): IRange
{
if ($type !== RangeType::TALLY) {
throw new InvalidParameterException("Invalid: Node range of type '{$type->value}' is not supported");
}
return new RangeTally();
}
private function nodeSize(CollectionResource|EntityResource $node): int
{
return $node instanceof EntityResource ? $node->getProperties()->size() : 0;
return null;
}
}
-59
View File
@@ -9,7 +9,6 @@ declare(strict_types=1);
namespace KTXM\ProviderJmapc\Providers\Mail;
use KTXF\Mail\Object\Address;
use KTXF\Mail\Provider\ProviderBaseInterface;
use KTXF\Mail\Provider\ProviderServiceDiscoverInterface;
use KTXF\Mail\Provider\ProviderServiceMutateInterface;
@@ -143,66 +142,9 @@ class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface,
}
$created = $this->serviceStore->create($tenantId, $userId, $service);
$this->serviceIdentitiesSync($tenantId, $userId, (new Service())->fromStore($created));
return (string) $created['sid'];
}
/**
* Fetches sending identities from the JMAP server and overwrites
* primaryAddress/secondaryAddresses on the service with them.
*/
private function serviceIdentitiesSync(string $tenantId, string $userId, Service $service): void
{
try {
$client = RemoteService::freshClient($service);
$identities = RemoteService::mailService($client)->identityFetch();
// A JMAP server may expose multiple identities sharing the same
// address (e.g. distinct signatures/display names for one
// mailbox) — collapse those down to one entry per address,
// keeping the first label seen.
$addresses = [];
foreach ($identities as $identity) {
if ($identity->address() === null) {
continue;
}
$key = strtolower($identity->address());
if (!isset($addresses[$key])) {
$addresses[$key] = Address::fromArray(['address' => $identity->address(), 'label' => $identity->name()]);
}
}
$addresses = array_values($addresses);
if (empty($addresses)) {
return;
}
$currentAddress = strtolower($service->getPrimaryAddress()->getAddress());
$primaryIndex = 0;
foreach ($addresses as $index => $address) {
if (strtolower($address->getAddress()) === $currentAddress) {
$primaryIndex = $index;
break;
}
}
$secondary = [];
foreach ($addresses as $index => $address) {
if ($index !== $primaryIndex) {
$secondary[] = $address;
}
}
$service->setPrimaryAddress($addresses[$primaryIndex]);
$service->setSecondaryAddresses($secondary);
$this->serviceStore->modify($tenantId, $userId, $service);
} catch (\Throwable) {
// Server may not support urn:ietf:params:jmap:submission, or have
// no identities configured — fall back to what the user entered.
}
}
public function serviceModify(string $tenantId, string $userId, ResourceServiceMutateInterface $service): string
{
if (!($service instanceof Service)) {
@@ -210,7 +152,6 @@ class Provider implements ProviderBaseInterface, ProviderServiceMutateInterface,
}
$this->serviceStore->modify($tenantId, $userId, $service);
$this->serviceIdentitiesSync($tenantId, $userId, $service);
return (string) $service->identifier();
}
+46 -163
View File
@@ -102,8 +102,8 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
],
self::CAPABILITY_ENTITY_FETCH => true,
self::CAPABILITY_ENTITY_EXTANT => true,
self::CAPABILITY_ENTITY_CREATE => true,
self::CAPABILITY_ENTITY_MODIFY => true,
self::CAPABILITY_ENTITY_CREATE => false,
self::CAPABILITY_ENTITY_MODIFY => false,
self::CAPABILITY_ENTITY_PATCH => true,
self::CAPABILITY_ENTITY_DELETE => true,
self::CAPABILITY_ENTITY_MOVE => true,
@@ -206,9 +206,8 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
if (isset($data[self::PROPERTY_IDENTITY])) {
$this->setIdentity($this->freshIdentity(null, $data[self::PROPERTY_IDENTITY]));
}
if (isset($data[self::PROPERTY_PRIMARY_ADDRESS])) {
$value = $data[self::PROPERTY_PRIMARY_ADDRESS];
$this->setPrimaryAddress(is_array($value) ? Address::fromArray($value) : new Address((string)$value));
if (isset($data[self::PROPERTY_PRIMARY_ADDRESS]) && is_string($data[self::PROPERTY_PRIMARY_ADDRESS])) {
$this->setPrimaryAddress(new Address($data[self::PROPERTY_PRIMARY_ADDRESS]));
}
if (isset($data[self::PROPERTY_SECONDARY_ADDRESSES]) && is_array($data[self::PROPERTY_SECONDARY_ADDRESSES])) {
$this->setSecondaryAddresses(array_map(
@@ -468,41 +467,33 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
$this->initialize();
$deleteMode = $this->auxiliary['deleteMode'] ?? 'soft';
$deleteTarget = $this->auxiliary['deleteTarget'] ?? null;
if ($deleteMode !== 'soft' && $deleteMode !== 'hard') {
throw new \InvalidArgumentException("Invalid delete mode: $deleteMode");
}
$deleteTargetIdentifier = $deleteMode === 'soft' ? $this->resolveDeleteDestination() : null;
$deleteTargetIdentifier = null;
if ($deleteMode === 'soft') {
$targetMailbox = $this->mailService->collectionFetch((string) $target->collection());
if ($targetMailbox === null) {
throw new \RuntimeException('Collection not found for delete operation');
}
$targetIdentifier = (string) $target->collection();
$trashIdentifier = (string) $deleteTargetIdentifier->collection();
$parentIdentifier = isset($targetMailbox['parentId'])
? (string) $targetMailbox['parentId']
: null;
// JMAP mailbox IDs are opaque, so containment must be determined
// from parentId rather than by comparing ID prefixes.
if ($targetIdentifier === $trashIdentifier || $parentIdentifier === $trashIdentifier) {
$deleteMode = 'hard';
$deleteTargetIdentifier = $deleteTarget !== null && (string) $deleteTarget !== ''
? new CollectionIdentifier($this->provider(), (string) $this->identifier(), (string) $deleteTarget)
: $this->resolveCollectionByRole(CollectionRoles::Trash->value);
if ($deleteTargetIdentifier === null) {
throw new \RuntimeException('No Trash collection configured or found for deletion');
}
}
if ($deleteMode === 'soft') {
return $this->collectionMove($deleteTargetIdentifier, $target);
// we need to determine if the folder being deleted is already in the trash
if (str_starts_with((string) $target->collection(), (string) $deleteTargetIdentifier?->collection())) {
// if so, we should hard delete instead of moving to avoid duplicates in the trash
$deleteMode = 'hard';
}
if ($this->mailService->collectionDestroy((string) $target->collection(), $force) === null) {
throw new \RuntimeException("Failed to delete collection: {$target->collection()}");
}
return true;
$result = match ($deleteMode) {
'soft' => $this->collectionMove($deleteTargetIdentifier, $target),
'hard' => $this->mailService->collectionDestroy($target->collection(), $force),
};
return $result;
}
public function collectionMove(CollectionIdentifier $target, CollectionIdentifier $source): CollectionBaseInterface
@@ -629,42 +620,14 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
public function entityCreate(CollectionIdentifier $target, MessagePropertiesMutableInterface $properties, array $options = []): EntityResource
{
if ($target->provider() !== $this->provider() || (string)$target->service() !== (string)$this->identifier()) {
throw new \InvalidArgumentException('Target collection does not belong to this service: ' . (string)$target);
}
$this->initialize();
[$nativeMessage, $nativeAttachments] = $this->messagePayload($properties);
$created = $this->mailService->entityCreate((string)$target->collection(), $nativeMessage, $nativeAttachments);
if ($created === null || !isset($created['id'])) {
throw new \RuntimeException('JMAP entity creation did not return an identifier');
}
$created['mailboxIds'] ??= [(string)$target->collection() => true];
return $this->entityFresh()->fromJmap($created);
// TODO: Implement entity create
return $this->entityFresh();
}
public function entityModify(EntityIdentifier $target, MessagePropertiesMutableInterface $properties): EntityResource
public function entityModify(EntityIdentifier $identifier, MessagePropertiesMutableInterface $properties): EntityResource
{
if ($target->provider() !== $this->provider() || (string)$target->service() !== (string)$this->identifier()) {
throw new \InvalidArgumentException('Target collection does not belong to this service: ' . (string)$target);
}
$this->initialize();
[$nativeMessage, $nativeAttachments] = $this->messagePayload($properties);
$nativeMessage['id'] = (string)$target->entity();
$nativeMessage['mailboxIds'] = [(string)$target->collection() => true];
// JMAP replaces immutable Email content and returns the new authoritative ID.
$modified = $this->mailService->entityReplace($nativeMessage, $nativeAttachments);
if ($modified === null) {
throw new \RuntimeException('JMAP entity modification failed');
}
return $this->entityFresh()->fromJmap($modified);
// TODO: Implement entity modify
return $this->entityFresh();
}
public function entityPatch(MessagePropertiesMutableInterface $properties, EntityIdentifier ...$targets): array
@@ -728,6 +691,7 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
// determine delete mode and target collection (e.g. Trash) if applicable
$deleteMode = $this->auxiliary['deleteMode'] ?? 'soft';
$deleteTarget = $this->auxiliary['deleteTarget'] ?? null;
if ($deleteMode !== 'soft' && $deleteMode !== 'hard') {
throw new \InvalidArgumentException("Invalid delete mode: $deleteMode");
@@ -736,7 +700,15 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
// connect to remote store
$this->initialize();
$deleteTargetIdentifier = $deleteMode === 'soft' ? $this->resolveDeleteDestination() : null;
$deleteTargetIdentifier = null;
if ($deleteMode === 'soft') {
$deleteTargetIdentifier = $deleteTarget !== null && (string) $deleteTarget !== ''
? new CollectionIdentifier($this->provider(), (string) $this->identifier(), (string) $deleteTarget)
: $this->resolveCollectionByRole(CollectionRoles::Trash->value);
if ($deleteTargetIdentifier === null) {
throw new \RuntimeException('No Trash collection configured or found for deletion');
}
}
$deleteTargetNative = $deleteTargetIdentifier?->collection();
@@ -907,14 +879,8 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
);
}
[$nativeMessage, $nativeAttachments] = $this->messagePayload($message);
$transportId = $this->mailService->entitySubmitFresh(
$identityId,
$nativeMessage,
$preSendTarget->collection(),
$postSentTarget->collection(),
$nativeAttachments,
);
$nativeMessage = $this->normalizeMessageProperties($message)->toJmap();
$transportId = $this->mailService->entitySubmitFresh($identityId, $nativeMessage, $preSendTarget->collection(), $postSentTarget->collection());
return new EntitySubmitResult(
EntitySubmitResult::DISPOSITION_SENT,
@@ -932,38 +898,12 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
);
}
// determine the sent folder
// if no explicit sent folder is configured, we will attempt to find a folder with the "sent" role.
$postSentTarget = $this->auxiliary['sentTarget'] ?? null;
$postSentTarget = $postSentTarget !== null && (string) $postSentTarget !== ''
? new CollectionIdentifier($this->provider(), (string) $this->identifier(), (string) $postSentTarget)
: $this->resolveCollectionByRole(CollectionRoles::Sent->value);
if ($postSentTarget === null
|| $postSentTarget->provider() !== $this->provider()
|| $postSentTarget->service() !== (string)$this->identifier()) {
return new EntitySubmitResult(
EntitySubmitResult::DISPOSITION_ERROR,
errorCode: 'sent_collection_not_found',
errorMessage: 'No Sent target collection is configured or could be resolved for this service',
);
}
$patch = null;
if ($message !== null) {
[$nativeMessage, $nativeAttachments] = $this->messagePayload($message);
} else {
$nativeMessage = null;
$nativeAttachments = [];
$patch = $this->normalizeMessageProperties($message)->toJmap();
}
$transportId = $this->mailService->entitySubmitDraft(
$identityId,
(string)$source->entity(),
(string)$source->collection(),
$postSentTarget->collection(),
$nativeMessage,
$nativeAttachments,
);
$transportId = $this->mailService->entitySubmitDraft($identityId, (string)$source->entity(), $patch);
return new EntitySubmitResult(
EntitySubmitResult::DISPOSITION_SENT,
@@ -972,73 +912,16 @@ class Service implements ServiceBaseInterface, ServiceMutableInterface, ServiceC
);
}
/**
* Convert message properties and describe attachment blobs for the remote
* service. Uploading and request batching remain remote-layer concerns.
*
* @return array{0: array, 1: array<string, array{type: string, content: string}>}
*/
private function messagePayload(MessagePropertiesMutableInterface $message): array
private function normalizeMessageProperties(MessagePropertiesMutableInterface $message): MessageProperties
{
if ($message instanceof MessageProperties === false) {
$native = new MessageProperties([]);
$native->jsonDeserialize($message->jsonSerialize());
} else {
$native = $message;
if ($message instanceof MessageProperties) {
return $message;
}
$attachments = $native->getAttachments();
$uploads = [];
$native = new MessageProperties([]);
$native->jsonDeserialize($message->jsonSerialize());
foreach ($attachments as $attachment) {
if ($attachment->getBlobId() !== null) {
continue;
}
$content = $attachment->getContent();
if ($content === null) {
throw new \InvalidArgumentException(sprintf(
'Attachment "%s" has neither content nor a JMAP blob identifier',
$attachment->getName() ?? 'unnamed',
));
}
$creationId = 'attachment_' . count($uploads);
$attachment->setBlobId('#' . $creationId);
$uploads[$creationId] = [
'type' => $attachment->getType() ?? 'application/octet-stream',
'content' => $content,
];
}
if ($attachments !== []) {
$native->setAttachments(...$attachments);
}
return [$native->toJmap(), $uploads];
}
/**
* Resolve the collection soft-deleted messages and collections are moved to
*/
private function resolveDeleteDestination(): CollectionIdentifier
{
$destination = trim((string) ($this->auxiliary['deleteDestination'] ?? ''));
if ($destination === '') {
return $this->resolveCollectionByRole(CollectionRoles::Trash->value)
?? throw new \RuntimeException('No Trash collection configured or found for deletion');
}
$role = CollectionRoles::tryFrom(strtolower($destination));
if ($role !== null && $role !== CollectionRoles::None) {
$resolved = $this->resolveCollectionByRole($role->value);
if ($resolved !== null) {
return $resolved;
}
}
return new CollectionIdentifier($this->provider(), (string) $this->identifier(), $destination);
return $native;
}
private function resolveCollectionByRole(string $role): ?CollectionIdentifier
+61 -173
View File
@@ -137,54 +137,6 @@ class RemoteFilesService {
return $list;
}
/**
* list of nodes (folders and files) directly within a location in remote storage
*
* FileNode/query support is incomplete on some servers (e.g. empty fileNodeQuerySortOptions),
* so all nodes are retrieved and the children of the location are selected locally.
*
* @since 2026.10.01
*
* @return array{list: array<string,array>, state: string|null}
*/
public function nodeList(?string $location = null): array {
$location = (empty($location) || $location === self::ROOT_ID) ? null : $location;
// construct request
$r0 = new NodeGet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
// select direct children of location
$state = $response->state();
$list = [];
foreach ($response->objects() as $so) {
if (!$so instanceof NodeParametersResponse) {
continue;
}
$parameters = $so->parametersRaw();
$parent = $parameters['parentId'] ?? null;
if ($parent === self::ROOT_ID) {
$parent = null;
}
if ($parent !== $location) {
continue;
}
$parameters['signature'] = $state;
$list[$so->id()] = $parameters;
}
// return node collection
return ['list' => $list, 'state' => $state];
}
/**
* fresh instance of collection filter object
*
@@ -649,35 +601,42 @@ class RemoteFilesService {
/**
* create entity in remote storage
*
* a file node must reference a blob, a node without one is a folder
*
* @since Release 1.0.0
*/
public function entityCreate(string|null $location, array $so): ?array {
if (empty($so['blobId'])) {
throw new Exception('invalidArguments: A file node requires a blob identifier', 1);
}
public function entityCreate(string $location, array $so): ?array {
// convert entity
$to = new NodeParametersRequest();
$to->parametersRaw($so);
// define location
$location = $this->locationNormalize($location);
if ($location !== null) {
$to->in($location);
}
$to->in($location);
$id = uniqid();
// construct request
$r0 = new NodeSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->create($id, $to);
// transceive
$response = $this->performSet($r0);
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
// check for success
$result = $response->createSuccess($id);
if ($result !== null) {
return array_merge($so, ['parentId' => $location], $result);
return array_merge($so, $result);
}
// check for failure
$this->throwSetFailure($response->createFailure($id), 'entity creation');
$result = $response->createFailure($id);
if ($result !== null) {
$type = $result['type'] ?? 'unknownError';
$description = $result['description'] ?? 'An unknown error occurred during collection creation.';
throw new Exception("$type: $description", 1);
}
// return null if creation failed without failure reason
return null;
}
@@ -686,22 +645,26 @@ class RemoteFilesService {
*
* @since Release 1.0.0
*/
public function entityModify(string $identifier, array $so): ?array {
public function entityModify(array $so): ?array {
// extract entity id
$id = $so['id'];
// convert entity
$to = new NodeParametersRequest();
$to->parametersRaw($so);
// construct request
$r0 = new NodeSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->update($identifier, $to);
// transceive
$response = $this->performSet($r0);
// check for success
$result = $response->updateSuccess($identifier);
if ($result !== null) {
return array_merge($so, $result, ['id' => $identifier]);
$r0->update($id, $to);
// transmit request and receive response
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// determine if command succeeded
if (array_key_exists($id, $response->updated())) {
// update entity
$ro = $response->updated()[$id];
$so = array_merge($so, $ro);
return $so;
}
// check for failure
$this->throwSetFailure($response->updateFailure($identifier), 'entity modification');
return null;
}
@@ -709,130 +672,55 @@ class RemoteFilesService {
* delete entity from remote storage
*
* @since Release 1.0.0
*
* @return string|null new state on success
*/
public function entityDelete(string $identifier): ?string {
// construct request
public function entityDelete(string $id): ?string {
// construct set request
$r0 = new NodeSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->delete($identifier);
// transceive
$response = $this->performSet($r0);
// check for success
if ($response->deleteSuccess($identifier) !== null) {
// construct object
$r0->delete($id);
// transmit request and receive response
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// determine if command succeeded
if (array_search($id, $response->deleted()) !== false) {
return $response->stateNew();
}
// check for failure
$this->throwSetFailure($response->deleteFailure($identifier), 'entity deletion');
return null;
}
/**
* copy entity in remote storage
*
* the copy references the same blob as the source, blobs are immutable
*
* @since Release 1.0.0
*
*/
public function entityCopy(string|null $location, string $identifier): ?array {
$source = $this->entityFetch($identifier)[$identifier] ?? null;
if ($source === null) {
return null;
}
return $this->entityCreate($location, array_intersect_key($source, array_flip(['blobId', 'name', 'type', 'executable'])));
public function entityCopy(string $location, MailMessageObject $so): ?MailMessageObject {
return null;
}
/**
* move entity in remote storage
*
* @since Release 1.0.0
*
*/
public function entityMove(string|null $location, string $identifier): ?array {
$location = $this->locationNormalize($location);
public function entityMove(string $location, array $so): ?array {
// extract entity id
$id = $so['id'];
// construct request
$r0 = new NodeSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->update($identifier)->in($location);
// transceive
$response = $this->performSet($r0);
// check for success
$result = $response->updateSuccess($identifier);
if ($result !== null) {
return array_merge($result, ['id' => $identifier, 'parentId' => $location]);
$r0->update($id)->in($location);
// transmit request and receive response
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// determine if command succeeded
if (array_key_exists($id, $response->updated())) {
$so = array_merge($so, ['mailboxIds' => [$location => true]]);
return $so;
}
// check for failure
$this->throwSetFailure($response->updateFailure($identifier), 'entity move');
return null;
}
/**
* upload blob to remote storage
*
* @since 2026.10.01
*
* @return array{blobId: string, type?: string, size?: int}
*/
public function blobUpload(string $type, string &$data): array {
$response = json_decode($this->dataStore->upload($this->dataAccount, $type, $data), true);
if (!is_array($response) || empty($response['blobId'])) {
throw new Exception('serverFail: Blob upload did not return a blob identifier', 1);
}
return $response;
}
/**
* download blob from remote storage
*
* @since 2026.10.01
*/
public function blobDownload(string $identifier, string $type = 'application/octet-stream'): string {
$data = '';
$this->dataStore->download($this->dataAccount, $identifier, $data, $type);
return $data;
}
/**
* download blob from remote storage as stream
*
* @since 2026.10.01
*
* @return resource
*/
public function blobDownloadStream(string $identifier, string $type = 'application/octet-stream') {
$stream = $this->dataStore->downloadStream($this->dataAccount, $identifier, $type);
return \GuzzleHttp\Psr7\StreamWrapper::getResource($stream);
}
/**
* root location is represented by a null parent in remote storage
*/
private function locationNormalize(string|null $location): ?string {
return (empty($location) || $location === self::ROOT_ID) ? null : $location;
}
/**
* transceive a set request and return its response, throwing on command error
*/
private function performSet(NodeSet $request): mixed {
$response = $this->dataStore->perform([$request])->response(0);
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
} else {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
}
return $response;
}
/**
* throw set failure reason if present
*/
private function throwSetFailure(?array $failure, string $operation): void {
if ($failure !== null) {
$type = $failure['type'] ?? 'unknownError';
$description = $failure['description'] ?? "An unknown error occurred during $operation.";
throw new Exception("$type: $description", 1);
}
}
}
+53 -206
View File
@@ -11,7 +11,6 @@ namespace KTXM\ProviderJmapc\Service\Remote;
use Exception;
use JmapClient\Client;
use JmapClient\Requests\Blob\BlobSet;
use JmapClient\Requests\Mail\MailboxGet;
use JmapClient\Requests\Mail\MailboxParameters as MailboxParametersRequest;
use JmapClient\Requests\Mail\MailboxQuery;
@@ -728,8 +727,7 @@ class RemoteMailService {
*
* @since Release 1.0.0
*/
public function entityCreate(string $location, array $so, array $attachments = []): ?array {
$blobRequest = $this->prepareAttachmentRequest($so, $attachments);
public function entityCreate(string $location, array $so): ?array {
// convert entity
$to = new MailParametersRequest();
$to->parametersRaw($so);
@@ -739,11 +737,9 @@ class RemoteMailService {
$r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->create($id, $to);
// transceive
$requests = $blobRequest !== null ? [$blobRequest, $r0] : [$r0];
$bundle = $this->dataStore->perform($requests);
$this->assertAttachmentUploads($bundle, $blobRequest, $attachments, $so);
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response($blobRequest !== null ? 1 : 0);
$response = $bundle->response(0);
// check for command error
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
@@ -773,64 +769,27 @@ class RemoteMailService {
*
* @since Release 1.0.0
*/
public function entityReplace(array $so, array $attachments = []): ?array {
// JMAP Email content is immutable after creation. Replacing a draft must
// therefore create a new Email and remove the superseded Email together.
$id = (string)($so['id'] ?? '');
unset($so['id']);
if ($id === '') {
throw new Exception('Draft identifier is required for replacement', 1);
public function entityModify(array $so): ?array {
// extract entity id
$id = $so['id'];
// convert entity
$to = new MailParametersRequest();
$to->parametersRaw($so);
// construct request
$r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->update($id, $to);
// transceive
$bundle = $this->dataStore->perform([$r0]);
// extract response
$response = $bundle->response(0);
// determine if command succeeded
if (array_key_exists($id, $response->updated())) {
// update entity
$ro = $response->updated()[$id];
$so = array_merge($so, $ro);
return $so;
}
$location = null;
foreach (($so['mailboxIds'] ?? []) as $mailboxId => $included) {
if ($included === true) {
$location = (string)$mailboxId;
break;
}
}
if ($location === null || $location === '') {
throw new Exception('Draft mailbox is required for replacement', 1);
}
$blobRequest = $this->prepareAttachmentRequest($so, $attachments);
$replacement = new MailParametersRequest();
$replacement->parametersRaw($so);
$replacement->in($location);
$creationId = uniqid();
// Email/set supports create and destroy in one method call. When attachment
// content is present, Blob/upload is included in the same HTTP request.
$request = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$request->create($creationId, $replacement);
$request->delete($id);
$requests = $blobRequest !== null ? [$blobRequest, $request] : [$request];
$bundle = $this->dataStore->perform($requests);
$this->assertAttachmentUploads($bundle, $blobRequest, $attachments, $so);
$response = $bundle->response($blobRequest !== null ? 1 : 0);
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
}
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
$created = $response->createSuccess($creationId);
if ($created === null) {
$failure = $response->createFailure($creationId);
$type = $failure['type'] ?? 'unknownError';
$description = $failure['description'] ?? 'JMAP draft replacement failed.';
throw new Exception("$type: $description", 1);
}
if ($response->deleteSuccess($id) === null) {
$failure = $response->deleteFailure($id);
$type = $failure['type'] ?? 'unknownError';
$description = $failure['description'] ?? 'The superseded JMAP draft could not be deleted.';
throw new Exception("$type: $description", 1);
}
return array_merge($so, $created);
return null;
}
public function entityPatch(MailParametersRequest $properties, string ...$identifiers): ?array {
@@ -953,49 +912,24 @@ class RemoteMailService {
*
* @since Release 2.0.0
*/
public function entitySubmitFresh(string $identityId, array $data, string $preSendTarget, string $postSentTarget, array $attachments = []): string {
$blobRequest = $this->prepareAttachmentRequest($data, $attachments);
public function entitySubmitFresh(string $identityId, array $message, string $preSendTarget, string $postSentTarget): string {
$message = new MailParametersRequest();
$message->parametersRaw($data);
$mail = new MailParametersRequest();
$mail->parametersRaw($message);
$messageId = 'm_' . uniqid();
$submissionId = 's_' . uniqid();
$messageCreateId = 'm_' . uniqid();
$submissionCreateId = 's_' . uniqid();
$r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$m0 = $r0->create($messageId, $message);
$m0->in($preSendTarget);
$m0->draft(true);
$m0->seen(true);
$createdMessage = $r0->create($messageCreateId, $mail);
$createdMessage->in($preSendTarget);
$r1 = new MailSubmissionSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r1->completionUpdate('#' . $messageId, [
'mailboxIds/' . $postSentTarget => true,
'mailboxIds/' . $preSendTarget => null,
'keywords/$draft' => null,
]);
$s0 = $r1->create($submissionId);
$s0->identity($identityId);
$s0->message('#' . $messageId);
$submission = $r1->create($submissionCreateId);
$submission->identity($identityId);
$submission->message('#' . $messageCreateId);
$requests = $blobRequest !== null ? [$blobRequest, $r0, $r1] : [$r0, $r1];
$bundle = $this->dataStore->perform($requests);
$this->assertAttachmentUploads($bundle, $blobRequest, $attachments, $data);
$responseOffset = $blobRequest !== null ? 1 : 0;
$messageResponse = $bundle->response($responseOffset);
if ($messageResponse instanceof ResponseException) {
throw new Exception($messageResponse->type() . ': ' . $messageResponse->description(), 1);
}
if (method_exists($messageResponse, 'createFailure')) {
$failure = $messageResponse->createFailure($messageId);
if (is_array($failure)) {
$type = $failure['type'] ?? 'unknownError';
$description = $failure['description'] ?? 'Email creation failed';
throw new Exception($type . ': ' . $description, 1);
}
}
$response = $bundle->response($responseOffset + 1);
$bundle = $this->dataStore->perform([$r0, $r1]);
$response = $bundle->response(1);
if ($response instanceof ResponseException) {
if ($response->type() === 'unknownMethod') {
throw new JmapUnknownMethod($response->description(), 1);
@@ -1003,49 +937,37 @@ class RemoteMailService {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
return $this->extractSubmissionIdentifier($response, $submissionId);
return $this->extractSubmissionIdentifier($response, $submissionCreateId);
}
/**
* Submit an existing draft message. On success, the draft Email is moved
* from the drafts mailbox to the sent mailbox and its \Draft keyword is
* cleared in the same request, so the submitted draft becomes the sent
* copy rather than lingering as an unsent draft.
* Submit an existing draft message.
*
* @since Release 2.0.0
*/
public function entitySubmitDraft(string $identityId, string $draftId, string $preSendTarget, string $postSentTarget, ?array $patch = null, array $attachments = []): string {
public function entitySubmitDraft(string $identityId, string $draftId, ?array $patch = null): string {
if ($draftId === '') {
throw new Exception('Draft identifier is required for draft submission', 1);
}
$blobRequest = $patch !== null ? $this->prepareAttachmentRequest($patch, $attachments) : null;
$requests = $blobRequest !== null ? [$blobRequest] : [];
$requests = [];
if ($patch !== null && $patch !== []) {
$m0 = new MailParametersRequest();
$m0->parametersRaw($patch);
$draftMutation = new MailParametersRequest();
$draftMutation->parametersRaw($patch);
$r0 = new MailSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r0->update($draftId, $m0);
$r0->update($draftId, $draftMutation);
$requests[] = $r0;
}
$submissionId = 's_' . uniqid();
$submissionCreateId = 's_' . uniqid();
$r1 = new MailSubmissionSet($this->dataAccount, null, $this->resourceNamespace, $this->resourceEntityLabel);
$r1->completionUpdate($draftId, [
'mailboxIds/' . $postSentTarget => true,
'mailboxIds/' . $preSendTarget => null,
'keywords/$draft' => null,
]);
$s0 = $r1->create($submissionId);
$s0->identity($identityId);
$s0->message($draftId);
$submission = $r1->create($submissionCreateId);
$submission->identity($identityId);
$submission->message($draftId);
$requests[] = $r1;
$bundle = $this->dataStore->perform($requests);
if ($patch !== null) {
$this->assertAttachmentUploads($bundle, $blobRequest, $attachments, $patch);
}
$responseIndex = count($requests) - 1;
$response = $bundle->response($responseIndex);
if ($response instanceof ResponseException) {
@@ -1055,94 +977,19 @@ class RemoteMailService {
throw new Exception($response->type() . ': ' . $response->description(), 1);
}
return $this->extractSubmissionIdentifier($response, $submissionId);
return $this->extractSubmissionIdentifier($response, $submissionCreateId);
}
/**
* Upload attachment content and return its JMAP blob identifier.
*/
public function blobDeposit(string $type, string $data): string {
$response = json_decode($this->dataStore->upload($this->dataAccount, $type, $data), true);
if (!is_array($response) || !isset($response['blobId']) || !is_string($response['blobId']) || $response['blobId'] === '') {
throw new Exception('JMAP attachment upload did not return a blob identifier', 1);
}
private function collectionByRole(string $role): ?string {
$filter = $this->collectionListFilter();
$filter->condition('role', $role);
return $response['blobId'];
}
/**
* Build one Blob/upload method call for all new attachment content. Servers
* without the Blob capability fall back to the standard upload endpoint.
*
* @param array<string, array{type: string, content: string}> $attachments
*/
private function prepareAttachmentRequest(array &$data, array $attachments): ?BlobSet {
if ($attachments === []) {
$collections = $this->collectionList(null, $filter, null);
if ($collections === []) {
return null;
}
if (!$this->dataStore->sessionCapable('blob')) {
foreach ($attachments as $creationId => $attachment) {
$blobId = $this->blobDeposit($attachment['type'], $attachment['content']);
$this->replaceBlobReference($data, '#' . $creationId, $blobId);
}
return null;
}
$request = new BlobSet($this->dataAccount);
foreach ($attachments as $creationId => $attachment) {
$request->create($creationId)
->type($attachment['type'])
->dataEncoded(base64_encode($attachment['content']));
}
return $request;
}
/**
* Validate a batched Blob/upload response and replace creation references
* in the returned local representation with actual server blob IDs.
*
* @param array<string, array{type: string, content: string}> $attachments
*/
private function assertAttachmentUploads(object $bundle, ?BlobSet $request, array $attachments, array &$data): void {
if ($request === null) {
return;
}
$response = $bundle->response(0);
if ($response instanceof ResponseException) {
throw new Exception('Attachment upload failed: ' . $response->type() . ': ' . $response->description(), 1);
}
foreach (array_keys($attachments) as $creationId) {
$failure = $response->createFailure($creationId);
if ($failure !== null) {
$type = $failure['type'] ?? 'unknownError';
$description = $failure['description'] ?? 'Attachment upload failed.';
throw new Exception("$type: $description", 1);
}
$success = $response->createSuccess($creationId);
$blobId = is_array($success) ? ($success['id'] ?? null) : null;
if (!is_string($blobId) || $blobId === '') {
throw new Exception('Attachment upload did not return a blob identifier', 1);
}
$this->replaceBlobReference($data, '#' . $creationId, $blobId);
}
}
private function replaceBlobReference(array &$data, string $reference, string $blobId): void {
foreach ($data as &$value) {
if (is_array($value)) {
$this->replaceBlobReference($value, $reference, $blobId);
continue;
}
if ($value === $reference) {
$value = $blobId;
}
}
unset($value);
return (string)array_key_first($collections);
}
private function extractSubmissionIdentifier(object $response, string $createId): string {
+2 -6
View File
@@ -73,13 +73,9 @@ class RemoteService {
}
// debugging
if ($service->getDebug()) {
$logDirectory = dirname(__DIR__, 5) . '/var/logs/provider_jmap';
if (!is_dir($logDirectory) && !mkdir($logDirectory, 0775, true) && !is_dir($logDirectory)) {
throw new \RuntimeException(sprintf('Unable to create JMAP log directory: %s', $logDirectory));
}
$logFile = $logDirectory . '/' . $service->identifier() . '.json';
$logDir = dirname(__DIR__, 5) . '/var/log/jmap/' . $service->identifier() . '.json';
$client->configureTransportLogState(true);
$client->configureTransportLogLocation($logFile);
$client->configureTransportLogLocation($logDir);
}
// return
return $client;
-11
View File
@@ -176,15 +176,4 @@ class ServiceStore
return $result->getDeletedCount() > 0;
}
/**
* Delete every service owned by a user.
*/
public function deleteByUser(string $tenantId, string $userId): void
{
$this->dataStore->selectCollection(self::COLLECTION_NAME)->deleteMany([
'tid' => $tenantId,
'uid' => $userId,
]);
}
}
+2 -2
View File
@@ -274,7 +274,7 @@ async function initiateOAuth() {
variant="outlined"
prepend-inner-icon="mdi-account"
class="mb-4"
autocomplete="off"
autocomplete="username"
autocorrect="off"
autocapitalize="none"
:rules="[rules.required]"
@@ -289,7 +289,7 @@ async function initiateOAuth() {
variant="outlined"
prepend-inner-icon="mdi-lock"
class="mb-4"
autocomplete="new-password"
autocomplete="current-password"
:rules="[rules.required]"
/>
</template>
+65 -15
View File
@@ -25,7 +25,7 @@ const settingGroups = [
title: 'Addresses',
value: 'addresses' as const,
icon: 'mdi-at',
description: 'View the primary mailbox identity and sender aliases synced from the JMAP server.'
description: 'Configure the primary mailbox identity and any sender aliases exposed by this service.'
},
{
title: 'Messages',
@@ -71,7 +71,7 @@ watch(
)
watch(
[deleteMode, deleteDestination],
[deleteMode, deleteDestination, primaryAddress, secondaryAddresses],
() => {
const nextService = props.service ?? new ServiceObject()
const nextAuxiliary = {
@@ -83,9 +83,13 @@ watch(
}
if (sameAuxiliary(nextService.auxiliary ?? {}, nextAuxiliary)) {
return
if (sameAddresses(nextService)) {
return
}
}
nextService.primaryAddress = primaryAddress.value.empty ? null : primaryAddress.value
nextService.secondaryAddresses = dedupeAddresses(secondaryAddresses.value)
nextService.auxiliary = nextAuxiliary
emit('update:service', nextService)
},
@@ -107,10 +111,44 @@ function normalizeDeleteDestination(value: string): string {
return trimmedValue.length > 0 ? trimmedValue : 'Trash'
}
function dedupeAddresses(entries: ServiceAddressObject[]): ServiceAddressObject[] {
const populated = entries.filter(entry => !entry.empty)
return populated.filter((entry, index) =>
populated.findIndex(candidate => candidate.matches(entry.address)) === index)
}
function addSecondaryAddress() {
secondaryAddresses.value.push(new ServiceAddressObject())
}
function removeSecondaryAddress(index: number) {
secondaryAddresses.value.splice(index, 1)
}
function validAddress(value: string): boolean | string {
const trimmedValue = value.trim()
return trimmedValue.length === 0 || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmedValue) || 'Invalid email address'
}
function sameAuxiliary(current: Record<string, any>, next: Record<string, any>): boolean {
return (current.deleteMode === 'hard' ? 'hard' : 'soft') === next.deleteMode
&& (current.deleteDestination ?? undefined) === (next.deleteDestination ?? undefined)
}
function sameAddresses(service: ServiceObject): boolean {
const nextPrimary = primaryAddress.value.empty ? null : primaryAddress.value
const nextSecondary = dedupeAddresses(secondaryAddresses.value)
return sameAddress(service.primaryAddress, nextPrimary)
&& service.secondaryAddresses.length === nextSecondary.length
&& service.secondaryAddresses.every((entry, index) => sameAddress(entry, nextSecondary[index]))
}
function sameAddress(current: ServiceAddressObject | null, next: ServiceAddressObject | null): boolean {
if (current === null || next === null) {
return current === next
}
return current.equals(next)
}
</script>
<template>
@@ -138,57 +176,69 @@ function sameAuxiliary(current: Record<string, any>, next: Record<string, any>):
<div class="jmap-settings-card">
<h3 class="text-h6 mb-2">Addresses</h3>
<p class="text-body-2 text-medium-emphasis mb-6">
The primary mailbox identity and sender aliases are managed by the JMAP server and synced automatically.
Configure the primary mailbox identity and any additional sender aliases exposed by this service.
</p>
<div class="text-subtitle-2 mb-2">Primary Address</div>
<div class="d-flex ga-2 mb-6">
<v-text-field
:model-value="primaryAddress.label"
v-model="primaryAddress.label"
label="Display Name"
variant="outlined"
density="compact"
hide-details="auto"
readonly
/>
<v-text-field
:model-value="primaryAddress.address"
v-model="primaryAddress.address"
label="Email Address"
variant="outlined"
density="compact"
prepend-inner-icon="mdi-email-outline"
:rules="[validAddress]"
hide-details="auto"
readonly
/>
</div>
<div class="text-subtitle-2 mb-2">Secondary Addresses</div>
<p v-if="secondaryAddresses.length === 0" class="text-body-2 text-medium-emphasis">
No aliases reported by the server.
</p>
<div
v-for="(entry, index) in secondaryAddresses"
:key="index"
class="d-flex ga-2 mb-2"
>
<v-text-field
:model-value="entry.label"
v-model="entry.label"
label="Display Name"
variant="outlined"
density="compact"
hide-details="auto"
readonly
/>
<v-text-field
:model-value="entry.address"
v-model="entry.address"
label="Email Address"
variant="outlined"
density="compact"
prepend-inner-icon="mdi-email-multiple-outline"
:rules="[validAddress]"
hide-details="auto"
readonly
/>
<v-btn
icon
size="small"
variant="text"
@click="removeSecondaryAddress(index)"
>
<v-icon>mdi-delete-outline</v-icon>
<v-tooltip activator="parent" location="bottom">Remove Alias</v-tooltip>
</v-btn>
</div>
<v-btn
variant="tonal"
prepend-icon="mdi-plus"
@click="addSecondaryAddress"
>
Add Alias
</v-btn>
</div>
</v-window-item>